1009b1c42SEd Schouten //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten
9b915e9e0SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
10b915e9e0SDimitry Andric #include "MetadataLoader.h"
11b915e9e0SDimitry Andric #include "ValueList.h"
12b915e9e0SDimitry Andric #include "llvm/ADT/APFloat.h"
13b915e9e0SDimitry Andric #include "llvm/ADT/APInt.h"
14b915e9e0SDimitry Andric #include "llvm/ADT/ArrayRef.h"
15b915e9e0SDimitry Andric #include "llvm/ADT/DenseMap.h"
165a5ac124SDimitry Andric #include "llvm/ADT/STLExtras.h"
17009b1c42SEd Schouten #include "llvm/ADT/SmallString.h"
18009b1c42SEd Schouten #include "llvm/ADT/SmallVector.h"
19b915e9e0SDimitry Andric #include "llvm/ADT/StringRef.h"
20b915e9e0SDimitry Andric #include "llvm/ADT/Twine.h"
21b60736ecSDimitry Andric #include "llvm/Bitcode/BitcodeCommon.h"
22f8af5cf6SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
23b60736ecSDimitry Andric #include "llvm/Bitstream/BitstreamReader.h"
24eb11fae6SDimitry Andric #include "llvm/Config/llvm-config.h"
25b915e9e0SDimitry Andric #include "llvm/IR/Argument.h"
267fa27ce4SDimitry Andric #include "llvm/IR/AttributeMask.h"
27b915e9e0SDimitry Andric #include "llvm/IR/Attributes.h"
285ca98fd9SDimitry Andric #include "llvm/IR/AutoUpgrade.h"
29b915e9e0SDimitry Andric #include "llvm/IR/BasicBlock.h"
307ab83427SDimitry Andric #include "llvm/IR/CallingConv.h"
31b915e9e0SDimitry Andric #include "llvm/IR/Comdat.h"
32b915e9e0SDimitry Andric #include "llvm/IR/Constant.h"
33ac9a064cSDimitry Andric #include "llvm/IR/ConstantRangeList.h"
344a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
35044eb2f6SDimitry Andric #include "llvm/IR/DataLayout.h"
365a5ac124SDimitry Andric #include "llvm/IR/DebugInfo.h"
375a5ac124SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
38b915e9e0SDimitry Andric #include "llvm/IR/DebugLoc.h"
394a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
40b915e9e0SDimitry Andric #include "llvm/IR/Function.h"
417ab83427SDimitry Andric #include "llvm/IR/GVMaterializer.h"
42145449b1SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
43b915e9e0SDimitry Andric #include "llvm/IR/GlobalAlias.h"
44b915e9e0SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
45b915e9e0SDimitry Andric #include "llvm/IR/GlobalObject.h"
46b915e9e0SDimitry Andric #include "llvm/IR/GlobalValue.h"
47b915e9e0SDimitry Andric #include "llvm/IR/GlobalVariable.h"
484a16efa3SDimitry Andric #include "llvm/IR/InlineAsm.h"
49b915e9e0SDimitry Andric #include "llvm/IR/InstIterator.h"
50b915e9e0SDimitry Andric #include "llvm/IR/InstrTypes.h"
51b915e9e0SDimitry Andric #include "llvm/IR/Instruction.h"
52b915e9e0SDimitry Andric #include "llvm/IR/Instructions.h"
53b915e9e0SDimitry Andric #include "llvm/IR/Intrinsics.h"
54145449b1SDimitry Andric #include "llvm/IR/IntrinsicsAArch64.h"
55145449b1SDimitry Andric #include "llvm/IR/IntrinsicsARM.h"
56f8af5cf6SDimitry Andric #include "llvm/IR/LLVMContext.h"
57044eb2f6SDimitry Andric #include "llvm/IR/Metadata.h"
584a16efa3SDimitry Andric #include "llvm/IR/Module.h"
5901095a5dSDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
604a16efa3SDimitry Andric #include "llvm/IR/Operator.h"
61ac9a064cSDimitry Andric #include "llvm/IR/ProfDataUtils.h"
62b915e9e0SDimitry Andric #include "llvm/IR/Type.h"
63044eb2f6SDimitry Andric #include "llvm/IR/Value.h"
64b915e9e0SDimitry Andric #include "llvm/IR/Verifier.h"
65b915e9e0SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
66b915e9e0SDimitry Andric #include "llvm/Support/Casting.h"
6701095a5dSDimitry Andric #include "llvm/Support/CommandLine.h"
68b915e9e0SDimitry Andric #include "llvm/Support/Compiler.h"
6901095a5dSDimitry Andric #include "llvm/Support/Debug.h"
70b915e9e0SDimitry Andric #include "llvm/Support/Error.h"
71b915e9e0SDimitry Andric #include "llvm/Support/ErrorHandling.h"
72044eb2f6SDimitry Andric #include "llvm/Support/ErrorOr.h"
73044eb2f6SDimitry Andric #include "llvm/Support/MathExtras.h"
74009b1c42SEd Schouten #include "llvm/Support/MemoryBuffer.h"
75e3b55780SDimitry Andric #include "llvm/Support/ModRef.h"
76f8af5cf6SDimitry Andric #include "llvm/Support/raw_ostream.h"
777fa27ce4SDimitry Andric #include "llvm/TargetParser/Triple.h"
78b915e9e0SDimitry Andric #include <algorithm>
79b915e9e0SDimitry Andric #include <cassert>
80b915e9e0SDimitry Andric #include <cstddef>
81b915e9e0SDimitry Andric #include <cstdint>
825a5ac124SDimitry Andric #include <deque>
83b915e9e0SDimitry Andric #include <map>
84b915e9e0SDimitry Andric #include <memory>
85e3b55780SDimitry Andric #include <optional>
86044eb2f6SDimitry Andric #include <set>
87b915e9e0SDimitry Andric #include <string>
88b915e9e0SDimitry Andric #include <system_error>
89b915e9e0SDimitry Andric #include <tuple>
9001095a5dSDimitry Andric #include <utility>
91b915e9e0SDimitry Andric #include <vector>
9201095a5dSDimitry Andric
93009b1c42SEd Schouten using namespace llvm;
94009b1c42SEd Schouten
9501095a5dSDimitry Andric static cl::opt<bool> PrintSummaryGUIDs(
9601095a5dSDimitry Andric "print-summary-global-ids", cl::init(false), cl::Hidden,
9701095a5dSDimitry Andric cl::desc(
9801095a5dSDimitry Andric "Print the global id for each value when reading the module summary"));
9901095a5dSDimitry Andric
100145449b1SDimitry Andric static cl::opt<bool> ExpandConstantExprs(
101145449b1SDimitry Andric "expand-constant-exprs", cl::Hidden,
102145449b1SDimitry Andric cl::desc(
103145449b1SDimitry Andric "Expand constant expressions to instructions for testing purposes"));
104145449b1SDimitry Andric
105ac9a064cSDimitry Andric /// Load bitcode directly into RemoveDIs format (use debug records instead
106ac9a064cSDimitry Andric /// of debug intrinsics). UNSET is treated as FALSE, so the default action
107ac9a064cSDimitry Andric /// is to do nothing. Individual tools can override this to incrementally add
108ac9a064cSDimitry Andric /// support for the RemoveDIs format.
109ac9a064cSDimitry Andric cl::opt<cl::boolOrDefault> LoadBitcodeIntoNewDbgInfoFormat(
110ac9a064cSDimitry Andric "load-bitcode-into-experimental-debuginfo-iterators", cl::Hidden,
111ac9a064cSDimitry Andric cl::desc("Load bitcode directly into the new debug info format (regardless "
112ac9a064cSDimitry Andric "of input format)"));
113ac9a064cSDimitry Andric extern cl::opt<bool> UseNewDbgInfoFormat;
114ac9a064cSDimitry Andric extern cl::opt<cl::boolOrDefault> PreserveInputDbgFormat;
115ac9a064cSDimitry Andric extern bool WriteNewDbgInfoFormatToBitcode;
116ac9a064cSDimitry Andric extern cl::opt<bool> WriteNewDbgInfoFormat;
117ac9a064cSDimitry Andric
1185a5ac124SDimitry Andric namespace {
119b915e9e0SDimitry Andric
12058b69754SDimitry Andric enum {
12158b69754SDimitry Andric SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
12258b69754SDimitry Andric };
12358b69754SDimitry Andric
124044eb2f6SDimitry Andric } // end anonymous namespace
125044eb2f6SDimitry Andric
error(const Twine & Message)126044eb2f6SDimitry Andric static Error error(const Twine &Message) {
127b915e9e0SDimitry Andric return make_error<StringError>(
128b915e9e0SDimitry Andric Message, make_error_code(BitcodeError::CorruptedBitcode));
1295a5ac124SDimitry Andric }
1305a5ac124SDimitry Andric
hasInvalidBitcodeHeader(BitstreamCursor & Stream)131e6d15924SDimitry Andric static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
132e6d15924SDimitry Andric if (!Stream.canSkipToPos(4))
133e6d15924SDimitry Andric return createStringError(std::errc::illegal_byte_sequence,
134e6d15924SDimitry Andric "file too small to contain bitcode header");
135e6d15924SDimitry Andric for (unsigned C : {'B', 'C'})
136e6d15924SDimitry Andric if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
137e6d15924SDimitry Andric if (Res.get() != C)
138e6d15924SDimitry Andric return createStringError(std::errc::illegal_byte_sequence,
139e6d15924SDimitry Andric "file doesn't start with bitcode header");
140e6d15924SDimitry Andric } else
141e6d15924SDimitry Andric return Res.takeError();
142e6d15924SDimitry Andric for (unsigned C : {0x0, 0xC, 0xE, 0xD})
143e6d15924SDimitry Andric if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
144e6d15924SDimitry Andric if (Res.get() != C)
145e6d15924SDimitry Andric return createStringError(std::errc::illegal_byte_sequence,
146e6d15924SDimitry Andric "file doesn't start with bitcode header");
147e6d15924SDimitry Andric } else
148e6d15924SDimitry Andric return Res.takeError();
149e6d15924SDimitry Andric return Error::success();
1505a5ac124SDimitry Andric }
1515a5ac124SDimitry Andric
initStream(MemoryBufferRef Buffer)152044eb2f6SDimitry Andric static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
153b915e9e0SDimitry Andric const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
154b915e9e0SDimitry Andric const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
155b915e9e0SDimitry Andric
156b915e9e0SDimitry Andric if (Buffer.getBufferSize() & 3)
157b915e9e0SDimitry Andric return error("Invalid bitcode signature");
158b915e9e0SDimitry Andric
159b915e9e0SDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents.
160b915e9e0SDimitry Andric // The magic number is 0x0B17C0DE stored in little endian.
161b915e9e0SDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd))
162b915e9e0SDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
163b915e9e0SDimitry Andric return error("Invalid bitcode wrapper header");
164b915e9e0SDimitry Andric
165b915e9e0SDimitry Andric BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
166e6d15924SDimitry Andric if (Error Err = hasInvalidBitcodeHeader(Stream))
167e6d15924SDimitry Andric return std::move(Err);
168b915e9e0SDimitry Andric
169b915e9e0SDimitry Andric return std::move(Stream);
1705a5ac124SDimitry Andric }
1715a5ac124SDimitry Andric
172b915e9e0SDimitry Andric /// Convert a string from a record into an std::string, return true on failure.
173b915e9e0SDimitry Andric template <typename StrTy>
convertToString(ArrayRef<uint64_t> Record,unsigned Idx,StrTy & Result)174b915e9e0SDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
175b915e9e0SDimitry Andric StrTy &Result) {
176b915e9e0SDimitry Andric if (Idx > Record.size())
177b915e9e0SDimitry Andric return true;
178b915e9e0SDimitry Andric
179cfca06d7SDimitry Andric Result.append(Record.begin() + Idx, Record.end());
180b915e9e0SDimitry Andric return false;
1815a5ac124SDimitry Andric }
1825a5ac124SDimitry Andric
183b915e9e0SDimitry Andric // Strip all the TBAA attachment for the module.
stripTBAA(Module * M)184044eb2f6SDimitry Andric static void stripTBAA(Module *M) {
185b915e9e0SDimitry Andric for (auto &F : *M) {
186b915e9e0SDimitry Andric if (F.isMaterializable())
187b915e9e0SDimitry Andric continue;
188b915e9e0SDimitry Andric for (auto &I : instructions(F))
189b915e9e0SDimitry Andric I.setMetadata(LLVMContext::MD_tbaa, nullptr);
190b915e9e0SDimitry Andric }
191b915e9e0SDimitry Andric }
1925a5ac124SDimitry Andric
193b915e9e0SDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
194b915e9e0SDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any.
readIdentificationBlock(BitstreamCursor & Stream)195044eb2f6SDimitry Andric static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
196e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
197e6d15924SDimitry Andric return std::move(Err);
1985a5ac124SDimitry Andric
199b915e9e0SDimitry Andric // Read all the records.
200b915e9e0SDimitry Andric SmallVector<uint64_t, 64> Record;
201b915e9e0SDimitry Andric
202b915e9e0SDimitry Andric std::string ProducerIdentification;
203b915e9e0SDimitry Andric
204b915e9e0SDimitry Andric while (true) {
205e6d15924SDimitry Andric BitstreamEntry Entry;
206c0981da4SDimitry Andric if (Error E = Stream.advance().moveInto(Entry))
207c0981da4SDimitry Andric return std::move(E);
208b915e9e0SDimitry Andric
209b915e9e0SDimitry Andric switch (Entry.Kind) {
210b915e9e0SDimitry Andric default:
211b915e9e0SDimitry Andric case BitstreamEntry::Error:
212b915e9e0SDimitry Andric return error("Malformed block");
213b915e9e0SDimitry Andric case BitstreamEntry::EndBlock:
214b915e9e0SDimitry Andric return ProducerIdentification;
215b915e9e0SDimitry Andric case BitstreamEntry::Record:
216b915e9e0SDimitry Andric // The interesting case.
217b915e9e0SDimitry Andric break;
218b915e9e0SDimitry Andric }
219b915e9e0SDimitry Andric
220b915e9e0SDimitry Andric // Read a record.
221b915e9e0SDimitry Andric Record.clear();
222e6d15924SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
223e6d15924SDimitry Andric if (!MaybeBitCode)
224e6d15924SDimitry Andric return MaybeBitCode.takeError();
225e6d15924SDimitry Andric switch (MaybeBitCode.get()) {
226b915e9e0SDimitry Andric default: // Default behavior: reject
227b915e9e0SDimitry Andric return error("Invalid value");
228b915e9e0SDimitry Andric case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
229b915e9e0SDimitry Andric convertToString(Record, 0, ProducerIdentification);
230b915e9e0SDimitry Andric break;
231b915e9e0SDimitry Andric case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
232b915e9e0SDimitry Andric unsigned epoch = (unsigned)Record[0];
233b915e9e0SDimitry Andric if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
234b915e9e0SDimitry Andric return error(
235b915e9e0SDimitry Andric Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
236b915e9e0SDimitry Andric "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
237b915e9e0SDimitry Andric }
238b915e9e0SDimitry Andric }
239b915e9e0SDimitry Andric }
240b915e9e0SDimitry Andric }
241b915e9e0SDimitry Andric }
242b915e9e0SDimitry Andric
readIdentificationCode(BitstreamCursor & Stream)243044eb2f6SDimitry Andric static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
244b915e9e0SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily
245b915e9e0SDimitry Andric // need to understand them all.
246b915e9e0SDimitry Andric while (true) {
247b915e9e0SDimitry Andric if (Stream.AtEndOfStream())
248b915e9e0SDimitry Andric return "";
249b915e9e0SDimitry Andric
250e6d15924SDimitry Andric BitstreamEntry Entry;
251c0981da4SDimitry Andric if (Error E = Stream.advance().moveInto(Entry))
252c0981da4SDimitry Andric return std::move(E);
253e6d15924SDimitry Andric
254b915e9e0SDimitry Andric switch (Entry.Kind) {
255b915e9e0SDimitry Andric case BitstreamEntry::EndBlock:
256b915e9e0SDimitry Andric case BitstreamEntry::Error:
257b915e9e0SDimitry Andric return error("Malformed block");
258b915e9e0SDimitry Andric
259b915e9e0SDimitry Andric case BitstreamEntry::SubBlock:
260b915e9e0SDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
261b915e9e0SDimitry Andric return readIdentificationBlock(Stream);
262b915e9e0SDimitry Andric
263b915e9e0SDimitry Andric // Ignore other sub-blocks.
264e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
265e6d15924SDimitry Andric return std::move(Err);
266b915e9e0SDimitry Andric continue;
267b915e9e0SDimitry Andric case BitstreamEntry::Record:
268c0981da4SDimitry Andric if (Error E = Stream.skipRecord(Entry.ID).takeError())
269c0981da4SDimitry Andric return std::move(E);
270b915e9e0SDimitry Andric continue;
271b915e9e0SDimitry Andric }
272b915e9e0SDimitry Andric }
273b915e9e0SDimitry Andric }
274b915e9e0SDimitry Andric
hasObjCCategoryInModule(BitstreamCursor & Stream)275044eb2f6SDimitry Andric static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
276e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
277e6d15924SDimitry Andric return std::move(Err);
278b915e9e0SDimitry Andric
279b915e9e0SDimitry Andric SmallVector<uint64_t, 64> Record;
280b915e9e0SDimitry Andric // Read all the records for this module.
281b915e9e0SDimitry Andric
282b915e9e0SDimitry Andric while (true) {
283e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
284e6d15924SDimitry Andric if (!MaybeEntry)
285e6d15924SDimitry Andric return MaybeEntry.takeError();
286e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
287b915e9e0SDimitry Andric
288b915e9e0SDimitry Andric switch (Entry.Kind) {
289b915e9e0SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
290b915e9e0SDimitry Andric case BitstreamEntry::Error:
291b915e9e0SDimitry Andric return error("Malformed block");
292b915e9e0SDimitry Andric case BitstreamEntry::EndBlock:
293b915e9e0SDimitry Andric return false;
294b915e9e0SDimitry Andric case BitstreamEntry::Record:
295b915e9e0SDimitry Andric // The interesting case.
296b915e9e0SDimitry Andric break;
297b915e9e0SDimitry Andric }
298b915e9e0SDimitry Andric
299b915e9e0SDimitry Andric // Read a record.
300e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
301e6d15924SDimitry Andric if (!MaybeRecord)
302e6d15924SDimitry Andric return MaybeRecord.takeError();
303e6d15924SDimitry Andric switch (MaybeRecord.get()) {
304b915e9e0SDimitry Andric default:
305b915e9e0SDimitry Andric break; // Default behavior, ignore unknown content.
306b915e9e0SDimitry Andric case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
307b915e9e0SDimitry Andric std::string S;
308b915e9e0SDimitry Andric if (convertToString(Record, 0, S))
309145449b1SDimitry Andric return error("Invalid section name record");
310b915e9e0SDimitry Andric // Check for the i386 and other (x86_64, ARM) conventions
311b915e9e0SDimitry Andric if (S.find("__DATA,__objc_catlist") != std::string::npos ||
312ac9a064cSDimitry Andric S.find("__OBJC,__category") != std::string::npos ||
313ac9a064cSDimitry Andric S.find("__TEXT,__swift") != std::string::npos)
314b915e9e0SDimitry Andric return true;
315b915e9e0SDimitry Andric break;
316b915e9e0SDimitry Andric }
317b915e9e0SDimitry Andric }
318b915e9e0SDimitry Andric Record.clear();
319b915e9e0SDimitry Andric }
320b915e9e0SDimitry Andric llvm_unreachable("Exit infinite loop");
321b915e9e0SDimitry Andric }
322b915e9e0SDimitry Andric
hasObjCCategory(BitstreamCursor & Stream)323044eb2f6SDimitry Andric static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
324b915e9e0SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily
325b915e9e0SDimitry Andric // need to understand them all.
326b915e9e0SDimitry Andric while (true) {
327e6d15924SDimitry Andric BitstreamEntry Entry;
328c0981da4SDimitry Andric if (Error E = Stream.advance().moveInto(Entry))
329c0981da4SDimitry Andric return std::move(E);
330b915e9e0SDimitry Andric
331b915e9e0SDimitry Andric switch (Entry.Kind) {
332b915e9e0SDimitry Andric case BitstreamEntry::Error:
333b915e9e0SDimitry Andric return error("Malformed block");
334b915e9e0SDimitry Andric case BitstreamEntry::EndBlock:
335b915e9e0SDimitry Andric return false;
336b915e9e0SDimitry Andric
337b915e9e0SDimitry Andric case BitstreamEntry::SubBlock:
338b915e9e0SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID)
339b915e9e0SDimitry Andric return hasObjCCategoryInModule(Stream);
340b915e9e0SDimitry Andric
341b915e9e0SDimitry Andric // Ignore other sub-blocks.
342e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
343e6d15924SDimitry Andric return std::move(Err);
344b915e9e0SDimitry Andric continue;
345b915e9e0SDimitry Andric
346b915e9e0SDimitry Andric case BitstreamEntry::Record:
347c0981da4SDimitry Andric if (Error E = Stream.skipRecord(Entry.ID).takeError())
348c0981da4SDimitry Andric return std::move(E);
349b915e9e0SDimitry Andric continue;
350b915e9e0SDimitry Andric }
351b915e9e0SDimitry Andric }
352b915e9e0SDimitry Andric }
353b915e9e0SDimitry Andric
readModuleTriple(BitstreamCursor & Stream)354044eb2f6SDimitry Andric static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
355e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
356e6d15924SDimitry Andric return std::move(Err);
357b915e9e0SDimitry Andric
358b915e9e0SDimitry Andric SmallVector<uint64_t, 64> Record;
359b915e9e0SDimitry Andric
360b915e9e0SDimitry Andric std::string Triple;
361b915e9e0SDimitry Andric
362b915e9e0SDimitry Andric // Read all the records for this module.
363b915e9e0SDimitry Andric while (true) {
364e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
365e6d15924SDimitry Andric if (!MaybeEntry)
366e6d15924SDimitry Andric return MaybeEntry.takeError();
367e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
368b915e9e0SDimitry Andric
369b915e9e0SDimitry Andric switch (Entry.Kind) {
370b915e9e0SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
371b915e9e0SDimitry Andric case BitstreamEntry::Error:
372b915e9e0SDimitry Andric return error("Malformed block");
373b915e9e0SDimitry Andric case BitstreamEntry::EndBlock:
374b915e9e0SDimitry Andric return Triple;
375b915e9e0SDimitry Andric case BitstreamEntry::Record:
376b915e9e0SDimitry Andric // The interesting case.
377b915e9e0SDimitry Andric break;
378b915e9e0SDimitry Andric }
379b915e9e0SDimitry Andric
380b915e9e0SDimitry Andric // Read a record.
381e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
382e6d15924SDimitry Andric if (!MaybeRecord)
383e6d15924SDimitry Andric return MaybeRecord.takeError();
384e6d15924SDimitry Andric switch (MaybeRecord.get()) {
385b915e9e0SDimitry Andric default: break; // Default behavior, ignore unknown content.
386b915e9e0SDimitry Andric case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
387b915e9e0SDimitry Andric std::string S;
388b915e9e0SDimitry Andric if (convertToString(Record, 0, S))
389145449b1SDimitry Andric return error("Invalid triple record");
390b915e9e0SDimitry Andric Triple = S;
391b915e9e0SDimitry Andric break;
392b915e9e0SDimitry Andric }
393b915e9e0SDimitry Andric }
394b915e9e0SDimitry Andric Record.clear();
395b915e9e0SDimitry Andric }
396b915e9e0SDimitry Andric llvm_unreachable("Exit infinite loop");
397b915e9e0SDimitry Andric }
398b915e9e0SDimitry Andric
readTriple(BitstreamCursor & Stream)399044eb2f6SDimitry Andric static Expected<std::string> readTriple(BitstreamCursor &Stream) {
400b915e9e0SDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily
401b915e9e0SDimitry Andric // need to understand them all.
402b915e9e0SDimitry Andric while (true) {
403e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advance();
404e6d15924SDimitry Andric if (!MaybeEntry)
405e6d15924SDimitry Andric return MaybeEntry.takeError();
406e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
407b915e9e0SDimitry Andric
408b915e9e0SDimitry Andric switch (Entry.Kind) {
409b915e9e0SDimitry Andric case BitstreamEntry::Error:
410b915e9e0SDimitry Andric return error("Malformed block");
411b915e9e0SDimitry Andric case BitstreamEntry::EndBlock:
412b915e9e0SDimitry Andric return "";
413b915e9e0SDimitry Andric
414b915e9e0SDimitry Andric case BitstreamEntry::SubBlock:
415b915e9e0SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID)
416b915e9e0SDimitry Andric return readModuleTriple(Stream);
417b915e9e0SDimitry Andric
418b915e9e0SDimitry Andric // Ignore other sub-blocks.
419e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
420e6d15924SDimitry Andric return std::move(Err);
421b915e9e0SDimitry Andric continue;
422b915e9e0SDimitry Andric
423b915e9e0SDimitry Andric case BitstreamEntry::Record:
424e6d15924SDimitry Andric if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
425b915e9e0SDimitry Andric continue;
426e6d15924SDimitry Andric else
427e6d15924SDimitry Andric return Skipped.takeError();
428b915e9e0SDimitry Andric }
429b915e9e0SDimitry Andric }
430b915e9e0SDimitry Andric }
431b915e9e0SDimitry Andric
432044eb2f6SDimitry Andric namespace {
433044eb2f6SDimitry Andric
434b915e9e0SDimitry Andric class BitcodeReaderBase {
435b915e9e0SDimitry Andric protected:
BitcodeReaderBase(BitstreamCursor Stream,StringRef Strtab)436d99dafe2SDimitry Andric BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
437d99dafe2SDimitry Andric : Stream(std::move(Stream)), Strtab(Strtab) {
438b915e9e0SDimitry Andric this->Stream.setBlockInfo(&BlockInfo);
439b915e9e0SDimitry Andric }
440b915e9e0SDimitry Andric
441b915e9e0SDimitry Andric BitstreamBlockInfo BlockInfo;
442b915e9e0SDimitry Andric BitstreamCursor Stream;
443d99dafe2SDimitry Andric StringRef Strtab;
444d99dafe2SDimitry Andric
445d99dafe2SDimitry Andric /// In version 2 of the bitcode we store names of global values and comdats in
446d99dafe2SDimitry Andric /// a string table rather than in the VST.
447d99dafe2SDimitry Andric bool UseStrtab = false;
448b915e9e0SDimitry Andric
44971d5a254SDimitry Andric Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
45071d5a254SDimitry Andric
451d99dafe2SDimitry Andric /// If this module uses a string table, pop the reference to the string table
452d99dafe2SDimitry Andric /// and return the referenced string and the rest of the record. Otherwise
453d99dafe2SDimitry Andric /// just return the record itself.
454d99dafe2SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>>
455d99dafe2SDimitry Andric readNameFromStrtab(ArrayRef<uint64_t> Record);
456d99dafe2SDimitry Andric
457145449b1SDimitry Andric Error readBlockInfo();
458b915e9e0SDimitry Andric
459b915e9e0SDimitry Andric // Contains an arbitrary and optional string identifying the bitcode producer
460b915e9e0SDimitry Andric std::string ProducerIdentification;
461b915e9e0SDimitry Andric
462b915e9e0SDimitry Andric Error error(const Twine &Message);
4635a5ac124SDimitry Andric };
4645a5ac124SDimitry Andric
465044eb2f6SDimitry Andric } // end anonymous namespace
466044eb2f6SDimitry Andric
error(const Twine & Message)467b915e9e0SDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) {
468b915e9e0SDimitry Andric std::string FullMsg = Message.str();
469b915e9e0SDimitry Andric if (!ProducerIdentification.empty())
470b915e9e0SDimitry Andric FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
471b915e9e0SDimitry Andric LLVM_VERSION_STRING "')";
472b915e9e0SDimitry Andric return ::error(FullMsg);
4735a5ac124SDimitry Andric }
4745a5ac124SDimitry Andric
47571d5a254SDimitry Andric Expected<unsigned>
parseVersionRecord(ArrayRef<uint64_t> Record)47671d5a254SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
477044eb2f6SDimitry Andric if (Record.empty())
478145449b1SDimitry Andric return error("Invalid version record");
47971d5a254SDimitry Andric unsigned ModuleVersion = Record[0];
480d99dafe2SDimitry Andric if (ModuleVersion > 2)
48171d5a254SDimitry Andric return error("Invalid value");
482d99dafe2SDimitry Andric UseStrtab = ModuleVersion >= 2;
48371d5a254SDimitry Andric return ModuleVersion;
48471d5a254SDimitry Andric }
48571d5a254SDimitry Andric
486d99dafe2SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>>
readNameFromStrtab(ArrayRef<uint64_t> Record)487d99dafe2SDimitry Andric BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
488d99dafe2SDimitry Andric if (!UseStrtab)
489d99dafe2SDimitry Andric return {"", Record};
490d99dafe2SDimitry Andric // Invalid reference. Let the caller complain about the record being empty.
491d99dafe2SDimitry Andric if (Record[0] + Record[1] > Strtab.size())
492d99dafe2SDimitry Andric return {"", {}};
493d99dafe2SDimitry Andric return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
494d99dafe2SDimitry Andric }
495d99dafe2SDimitry Andric
496044eb2f6SDimitry Andric namespace {
497044eb2f6SDimitry Andric
498145449b1SDimitry Andric /// This represents a constant expression or constant aggregate using a custom
499145449b1SDimitry Andric /// structure internal to the bitcode reader. Later, this structure will be
500145449b1SDimitry Andric /// expanded by materializeValue() either into a constant expression/aggregate,
501145449b1SDimitry Andric /// or into an instruction sequence at the point of use. This allows us to
502145449b1SDimitry Andric /// upgrade bitcode using constant expressions even if this kind of constant
503145449b1SDimitry Andric /// expression is no longer supported.
504145449b1SDimitry Andric class BitcodeConstant final : public Value,
505145449b1SDimitry Andric TrailingObjects<BitcodeConstant, unsigned> {
506145449b1SDimitry Andric friend TrailingObjects;
507145449b1SDimitry Andric
508145449b1SDimitry Andric // Value subclass ID: Pick largest possible value to avoid any clashes.
509145449b1SDimitry Andric static constexpr uint8_t SubclassID = 255;
510145449b1SDimitry Andric
511145449b1SDimitry Andric public:
512145449b1SDimitry Andric // Opcodes used for non-expressions. This includes constant aggregates
513145449b1SDimitry Andric // (struct, array, vector) that might need expansion, as well as non-leaf
514145449b1SDimitry Andric // constants that don't need expansion (no_cfi, dso_local, blockaddress),
515145449b1SDimitry Andric // but still go through BitcodeConstant to avoid different uselist orders
516145449b1SDimitry Andric // between the two cases.
517145449b1SDimitry Andric static constexpr uint8_t ConstantStructOpcode = 255;
518145449b1SDimitry Andric static constexpr uint8_t ConstantArrayOpcode = 254;
519145449b1SDimitry Andric static constexpr uint8_t ConstantVectorOpcode = 253;
520145449b1SDimitry Andric static constexpr uint8_t NoCFIOpcode = 252;
521145449b1SDimitry Andric static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
522145449b1SDimitry Andric static constexpr uint8_t BlockAddressOpcode = 250;
523ac9a064cSDimitry Andric static constexpr uint8_t ConstantPtrAuthOpcode = 249;
524ac9a064cSDimitry Andric static constexpr uint8_t FirstSpecialOpcode = ConstantPtrAuthOpcode;
525145449b1SDimitry Andric
526145449b1SDimitry Andric // Separate struct to make passing different number of parameters to
527145449b1SDimitry Andric // BitcodeConstant::create() more convenient.
528145449b1SDimitry Andric struct ExtraInfo {
529145449b1SDimitry Andric uint8_t Opcode;
530145449b1SDimitry Andric uint8_t Flags;
531ac9a064cSDimitry Andric unsigned BlockAddressBB = 0;
532ac9a064cSDimitry Andric Type *SrcElemTy = nullptr;
533ac9a064cSDimitry Andric std::optional<ConstantRange> InRange;
534145449b1SDimitry Andric
ExtraInfo__anona50cac5d0411::BitcodeConstant::ExtraInfo535ac9a064cSDimitry Andric ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, Type *SrcElemTy = nullptr,
536ac9a064cSDimitry Andric std::optional<ConstantRange> InRange = std::nullopt)
537ac9a064cSDimitry Andric : Opcode(Opcode), Flags(Flags), SrcElemTy(SrcElemTy),
538ac9a064cSDimitry Andric InRange(std::move(InRange)) {}
539ac9a064cSDimitry Andric
ExtraInfo__anona50cac5d0411::BitcodeConstant::ExtraInfo540ac9a064cSDimitry Andric ExtraInfo(uint8_t Opcode, uint8_t Flags, unsigned BlockAddressBB)
541ac9a064cSDimitry Andric : Opcode(Opcode), Flags(Flags), BlockAddressBB(BlockAddressBB) {}
542145449b1SDimitry Andric };
543145449b1SDimitry Andric
544145449b1SDimitry Andric uint8_t Opcode;
545145449b1SDimitry Andric uint8_t Flags;
546145449b1SDimitry Andric unsigned NumOperands;
547ac9a064cSDimitry Andric unsigned BlockAddressBB;
548145449b1SDimitry Andric Type *SrcElemTy; // GEP source element type.
549ac9a064cSDimitry Andric std::optional<ConstantRange> InRange; // GEP inrange attribute.
550145449b1SDimitry Andric
551145449b1SDimitry Andric private:
BitcodeConstant(Type * Ty,const ExtraInfo & Info,ArrayRef<unsigned> OpIDs)552145449b1SDimitry Andric BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
553145449b1SDimitry Andric : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags),
554ac9a064cSDimitry Andric NumOperands(OpIDs.size()), BlockAddressBB(Info.BlockAddressBB),
555ac9a064cSDimitry Andric SrcElemTy(Info.SrcElemTy), InRange(Info.InRange) {
556145449b1SDimitry Andric std::uninitialized_copy(OpIDs.begin(), OpIDs.end(),
557145449b1SDimitry Andric getTrailingObjects<unsigned>());
558145449b1SDimitry Andric }
559145449b1SDimitry Andric
560145449b1SDimitry Andric BitcodeConstant &operator=(const BitcodeConstant &) = delete;
561145449b1SDimitry Andric
562145449b1SDimitry Andric public:
create(BumpPtrAllocator & A,Type * Ty,const ExtraInfo & Info,ArrayRef<unsigned> OpIDs)563145449b1SDimitry Andric static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty,
564145449b1SDimitry Andric const ExtraInfo &Info,
565145449b1SDimitry Andric ArrayRef<unsigned> OpIDs) {
566145449b1SDimitry Andric void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()),
567145449b1SDimitry Andric alignof(BitcodeConstant));
568145449b1SDimitry Andric return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
569145449b1SDimitry Andric }
570145449b1SDimitry Andric
classof(const Value * V)571145449b1SDimitry Andric static bool classof(const Value *V) { return V->getValueID() == SubclassID; }
572145449b1SDimitry Andric
getOperandIDs() const573145449b1SDimitry Andric ArrayRef<unsigned> getOperandIDs() const {
574e3b55780SDimitry Andric return ArrayRef(getTrailingObjects<unsigned>(), NumOperands);
575145449b1SDimitry Andric }
576145449b1SDimitry Andric
getInRange() const577ac9a064cSDimitry Andric std::optional<ConstantRange> getInRange() const {
578145449b1SDimitry Andric assert(Opcode == Instruction::GetElementPtr);
579ac9a064cSDimitry Andric return InRange;
580145449b1SDimitry Andric }
581145449b1SDimitry Andric
getOpcodeName() const582145449b1SDimitry Andric const char *getOpcodeName() const {
583145449b1SDimitry Andric return Instruction::getOpcodeName(Opcode);
584145449b1SDimitry Andric }
585145449b1SDimitry Andric };
586145449b1SDimitry Andric
587b915e9e0SDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
5885a5ac124SDimitry Andric LLVMContext &Context;
5893a0822f0SDimitry Andric Module *TheModule = nullptr;
590dd58ef01SDimitry Andric // Next offset to start scanning for lazy parsing of function bodies.
5913a0822f0SDimitry Andric uint64_t NextUnreadBit = 0;
592dd58ef01SDimitry Andric // Last function offset found in the VST.
593dd58ef01SDimitry Andric uint64_t LastFunctionBlockBit = 0;
5943a0822f0SDimitry Andric bool SeenValueSymbolTable = false;
595dd58ef01SDimitry Andric uint64_t VSTOffset = 0;
5965a5ac124SDimitry Andric
59771d5a254SDimitry Andric std::vector<std::string> SectionTable;
59871d5a254SDimitry Andric std::vector<std::string> GCTable;
59971d5a254SDimitry Andric
6005a5ac124SDimitry Andric std::vector<Type *> TypeList;
601145449b1SDimitry Andric /// Track type IDs of contained types. Order is the same as the contained
602145449b1SDimitry Andric /// types of a Type*. This is used during upgrades of typed pointer IR in
603145449b1SDimitry Andric /// opaque pointer mode.
604145449b1SDimitry Andric DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
605145449b1SDimitry Andric /// In some cases, we need to create a type ID for a type that was not
606145449b1SDimitry Andric /// explicitly encoded in the bitcode, or we don't know about at the current
607145449b1SDimitry Andric /// point. For example, a global may explicitly encode the value type ID, but
608145449b1SDimitry Andric /// not have a type ID for the pointer to value type, for which we create a
609145449b1SDimitry Andric /// virtual type ID instead. This map stores the new type ID that was created
610145449b1SDimitry Andric /// for the given pair of Type and contained type ID.
611145449b1SDimitry Andric DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs;
612145449b1SDimitry Andric DenseMap<Function *, unsigned> FunctionTypeIDs;
613145449b1SDimitry Andric /// Allocator for BitcodeConstants. This should come before ValueList,
614145449b1SDimitry Andric /// because the ValueList might hold ValueHandles to these constants, so
615145449b1SDimitry Andric /// ValueList must be destroyed before Alloc.
616145449b1SDimitry Andric BumpPtrAllocator Alloc;
6175a5ac124SDimitry Andric BitcodeReaderValueList ValueList;
618e3b55780SDimitry Andric std::optional<MetadataLoader> MDLoader;
6195a5ac124SDimitry Andric std::vector<Comdat *> ComdatList;
62077fc4c14SDimitry Andric DenseSet<GlobalObject *> ImplicitComdatObjects;
6215a5ac124SDimitry Andric SmallVector<Instruction *, 64> InstructionList;
6225a5ac124SDimitry Andric
6235a5ac124SDimitry Andric std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
624c0981da4SDimitry Andric std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
625c0981da4SDimitry Andric
626c0981da4SDimitry Andric struct FunctionOperandInfo {
627c0981da4SDimitry Andric Function *F;
628c0981da4SDimitry Andric unsigned PersonalityFn;
629c0981da4SDimitry Andric unsigned Prefix;
630c0981da4SDimitry Andric unsigned Prologue;
631c0981da4SDimitry Andric };
632c0981da4SDimitry Andric std::vector<FunctionOperandInfo> FunctionOperands;
6335a5ac124SDimitry Andric
6343a0822f0SDimitry Andric /// The set of attributes by index. Index zero in the file is for null, and
6353a0822f0SDimitry Andric /// is thus not represented here. As such all indices are off by one.
63671d5a254SDimitry Andric std::vector<AttributeList> MAttributes;
6375a5ac124SDimitry Andric
638dd58ef01SDimitry Andric /// The set of attribute groups.
63971d5a254SDimitry Andric std::map<unsigned, AttributeList> MAttributeGroups;
6405a5ac124SDimitry Andric
6413a0822f0SDimitry Andric /// While parsing a function body, this is a list of the basic blocks for the
6423a0822f0SDimitry Andric /// function.
6435a5ac124SDimitry Andric std::vector<BasicBlock*> FunctionBBs;
6445a5ac124SDimitry Andric
6455a5ac124SDimitry Andric // When reading the module header, this list is populated with functions that
6465a5ac124SDimitry Andric // have bodies later in the file.
6475a5ac124SDimitry Andric std::vector<Function*> FunctionsWithBodies;
6485a5ac124SDimitry Andric
6495a5ac124SDimitry Andric // When intrinsic functions are encountered which require upgrading they are
6505a5ac124SDimitry Andric // stored here with their replacement function.
651044eb2f6SDimitry Andric using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
65201095a5dSDimitry Andric UpdatedIntrinsicMap UpgradedIntrinsics;
6535a5ac124SDimitry Andric
6545a5ac124SDimitry Andric // Several operations happen after the module header has been read, but
6555a5ac124SDimitry Andric // before function bodies are processed. This keeps track of whether
6565a5ac124SDimitry Andric // we've done this yet.
6573a0822f0SDimitry Andric bool SeenFirstFunctionBody = false;
6585a5ac124SDimitry Andric
6593a0822f0SDimitry Andric /// When function bodies are initially scanned, this map contains info about
6603a0822f0SDimitry Andric /// where to find deferred function body in the stream.
6615a5ac124SDimitry Andric DenseMap<Function*, uint64_t> DeferredFunctionInfo;
6625a5ac124SDimitry Andric
6635a5ac124SDimitry Andric /// When Metadata block is initially scanned when parsing the module, we may
6645a5ac124SDimitry Andric /// choose to defer parsing of the metadata. This vector contains info about
6655a5ac124SDimitry Andric /// which Metadata blocks are deferred.
6665a5ac124SDimitry Andric std::vector<uint64_t> DeferredMetadataInfo;
6675a5ac124SDimitry Andric
6685a5ac124SDimitry Andric /// These are basic blocks forward-referenced by block addresses. They are
6695a5ac124SDimitry Andric /// inserted lazily into functions when they're loaded. The basic block ID is
6705a5ac124SDimitry Andric /// its index into the vector.
6715a5ac124SDimitry Andric DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
6725a5ac124SDimitry Andric std::deque<Function *> BasicBlockFwdRefQueue;
6735a5ac124SDimitry Andric
674145449b1SDimitry Andric /// These are Functions that contain BlockAddresses which refer a different
675145449b1SDimitry Andric /// Function. When parsing the different Function, queue Functions that refer
676145449b1SDimitry Andric /// to the different Function. Those Functions must be materialized in order
677145449b1SDimitry Andric /// to resolve their BlockAddress constants before the different Function
678145449b1SDimitry Andric /// gets moved into another Module.
679145449b1SDimitry Andric std::vector<Function *> BackwardRefFunctions;
680145449b1SDimitry Andric
6813a0822f0SDimitry Andric /// Indicates that we are using a new encoding for instruction operands where
6823a0822f0SDimitry Andric /// most operands in the current FUNCTION_BLOCK are encoded relative to the
6833a0822f0SDimitry Andric /// instruction number, for a more compact encoding. Some instruction
6843a0822f0SDimitry Andric /// operands are not relative to the instruction ID: basic block numbers, and
6853a0822f0SDimitry Andric /// types. Once the old style function blocks have been phased out, we would
6865a5ac124SDimitry Andric /// not need this flag.
6873a0822f0SDimitry Andric bool UseRelativeIDs = false;
6885a5ac124SDimitry Andric
6895a5ac124SDimitry Andric /// True if all functions will be materialized, negating the need to process
6905a5ac124SDimitry Andric /// (e.g.) blockaddress forward references.
6913a0822f0SDimitry Andric bool WillMaterializeAllForwardRefs = false;
6925a5ac124SDimitry Andric
693ac9a064cSDimitry Andric /// Tracks whether we have seen debug intrinsics or records in this bitcode;
694ac9a064cSDimitry Andric /// seeing both in a single module is currently a fatal error.
695ac9a064cSDimitry Andric bool SeenDebugIntrinsic = false;
696ac9a064cSDimitry Andric bool SeenDebugRecord = false;
697ac9a064cSDimitry Andric
6985a5ac124SDimitry Andric bool StripDebugInfo = false;
699b915e9e0SDimitry Andric TBAAVerifier TBAAVerifyHelper;
700dd58ef01SDimitry Andric
701dd58ef01SDimitry Andric std::vector<std::string> BundleTags;
702ca089b24SDimitry Andric SmallVector<SyncScope::ID, 8> SSIDs;
703dd58ef01SDimitry Andric
704e3b55780SDimitry Andric std::optional<ValueTypeCallbackTy> ValueTypeCallback;
705e3b55780SDimitry Andric
7065a5ac124SDimitry Andric public:
707d99dafe2SDimitry Andric BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
708d99dafe2SDimitry Andric StringRef ProducerIdentification, LLVMContext &Context);
7095a5ac124SDimitry Andric
710b915e9e0SDimitry Andric Error materializeForwardReferencedFunctions();
7115a5ac124SDimitry Andric
712b915e9e0SDimitry Andric Error materialize(GlobalValue *GV) override;
713b915e9e0SDimitry Andric Error materializeModule() override;
7145a5ac124SDimitry Andric std::vector<StructType *> getIdentifiedStructTypes() const override;
7155a5ac124SDimitry Andric
716eb11fae6SDimitry Andric /// Main interface to parsing a bitcode buffer.
7173a0822f0SDimitry Andric /// \returns true if an error occurred.
718e3b55780SDimitry Andric Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
719e3b55780SDimitry Andric bool IsImporting, ParserCallbacks Callbacks = {});
72001095a5dSDimitry Andric
7215a5ac124SDimitry Andric static uint64_t decodeSignRotatedValue(uint64_t V);
7225a5ac124SDimitry Andric
7235a5ac124SDimitry Andric /// Materialize any deferred Metadata block.
724b915e9e0SDimitry Andric Error materializeMetadata() override;
7255a5ac124SDimitry Andric
7265a5ac124SDimitry Andric void setStripDebugInfo() override;
7275a5ac124SDimitry Andric
7285a5ac124SDimitry Andric private:
7295a5ac124SDimitry Andric std::vector<StructType *> IdentifiedStructTypes;
7305a5ac124SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
7315a5ac124SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context);
7325a5ac124SDimitry Andric
733145449b1SDimitry Andric static constexpr unsigned InvalidTypeID = ~0u;
734b915e9e0SDimitry Andric
735145449b1SDimitry Andric Type *getTypeByID(unsigned ID);
736145449b1SDimitry Andric Type *getPtrElementTypeByID(unsigned ID);
737145449b1SDimitry Andric unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0);
738145449b1SDimitry Andric unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
739145449b1SDimitry Andric
740e3b55780SDimitry Andric void callValueTypeCallback(Value *F, unsigned TypeID);
741145449b1SDimitry Andric Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB);
742145449b1SDimitry Andric Expected<Constant *> getValueForInitializer(unsigned ID);
743145449b1SDimitry Andric
getFnValueByID(unsigned ID,Type * Ty,unsigned TyID,BasicBlock * ConstExprInsertBB)744145449b1SDimitry Andric Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID,
745145449b1SDimitry Andric BasicBlock *ConstExprInsertBB) {
7465a5ac124SDimitry Andric if (Ty && Ty->isMetadataTy())
7475a5ac124SDimitry Andric return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
748145449b1SDimitry Andric return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB);
7495a5ac124SDimitry Andric }
750b915e9e0SDimitry Andric
getFnMetadataByID(unsigned ID)7515a5ac124SDimitry Andric Metadata *getFnMetadataByID(unsigned ID) {
75202a33680SDimitry Andric return MDLoader->getMetadataFwdRefOrLoad(ID);
7535a5ac124SDimitry Andric }
754b915e9e0SDimitry Andric
getBasicBlock(unsigned ID) const7555a5ac124SDimitry Andric BasicBlock *getBasicBlock(unsigned ID) const {
7565a5ac124SDimitry Andric if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
7575a5ac124SDimitry Andric return FunctionBBs[ID];
7585a5ac124SDimitry Andric }
759b915e9e0SDimitry Andric
getAttributes(unsigned i) const76071d5a254SDimitry Andric AttributeList getAttributes(unsigned i) const {
7615a5ac124SDimitry Andric if (i-1 < MAttributes.size())
7625a5ac124SDimitry Andric return MAttributes[i-1];
76371d5a254SDimitry Andric return AttributeList();
7645a5ac124SDimitry Andric }
7655a5ac124SDimitry Andric
7663a0822f0SDimitry Andric /// Read a value/type pair out of the specified record from slot 'Slot'.
7673a0822f0SDimitry Andric /// Increment Slot past the number of slots used in the record. Return true on
7683a0822f0SDimitry Andric /// failure.
getValueTypePair(const SmallVectorImpl<uint64_t> & Record,unsigned & Slot,unsigned InstNum,Value * & ResVal,unsigned & TypeID,BasicBlock * ConstExprInsertBB)769b60736ecSDimitry Andric bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
770145449b1SDimitry Andric unsigned InstNum, Value *&ResVal, unsigned &TypeID,
771145449b1SDimitry Andric BasicBlock *ConstExprInsertBB) {
7725a5ac124SDimitry Andric if (Slot == Record.size()) return true;
7735a5ac124SDimitry Andric unsigned ValNo = (unsigned)Record[Slot++];
7745a5ac124SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum.
7755a5ac124SDimitry Andric if (UseRelativeIDs)
7765a5ac124SDimitry Andric ValNo = InstNum - ValNo;
7775a5ac124SDimitry Andric if (ValNo < InstNum) {
7785a5ac124SDimitry Andric // If this is not a forward reference, just return the value we already
7795a5ac124SDimitry Andric // have.
780145449b1SDimitry Andric TypeID = ValueList.getTypeID(ValNo);
781145449b1SDimitry Andric ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB);
782145449b1SDimitry Andric assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) &&
783145449b1SDimitry Andric "Incorrect type ID stored for value");
7845a5ac124SDimitry Andric return ResVal == nullptr;
7855a5ac124SDimitry Andric }
7865a5ac124SDimitry Andric if (Slot == Record.size())
7875a5ac124SDimitry Andric return true;
7885a5ac124SDimitry Andric
789145449b1SDimitry Andric TypeID = (unsigned)Record[Slot++];
790145449b1SDimitry Andric ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID,
791145449b1SDimitry Andric ConstExprInsertBB);
7925a5ac124SDimitry Andric return ResVal == nullptr;
7935a5ac124SDimitry Andric }
7945a5ac124SDimitry Andric
7953a0822f0SDimitry Andric /// Read a value out of the specified record from slot 'Slot'. Increment Slot
7963a0822f0SDimitry Andric /// past the number of slots used by the value in the record. Return true if
7973a0822f0SDimitry Andric /// there is an error.
popValue(const SmallVectorImpl<uint64_t> & Record,unsigned & Slot,unsigned InstNum,Type * Ty,unsigned TyID,Value * & ResVal,BasicBlock * ConstExprInsertBB)798b60736ecSDimitry Andric bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
799145449b1SDimitry Andric unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
800145449b1SDimitry Andric BasicBlock *ConstExprInsertBB) {
801145449b1SDimitry Andric if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
8025a5ac124SDimitry Andric return true;
8035a5ac124SDimitry Andric // All values currently take a single record slot.
8045a5ac124SDimitry Andric ++Slot;
8055a5ac124SDimitry Andric return false;
8065a5ac124SDimitry Andric }
8075a5ac124SDimitry Andric
8083a0822f0SDimitry Andric /// Like popValue, but does not increment the Slot number.
getValue(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty,unsigned TyID,Value * & ResVal,BasicBlock * ConstExprInsertBB)809b60736ecSDimitry Andric bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
810145449b1SDimitry Andric unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
811145449b1SDimitry Andric BasicBlock *ConstExprInsertBB) {
812145449b1SDimitry Andric ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
8135a5ac124SDimitry Andric return ResVal == nullptr;
8145a5ac124SDimitry Andric }
8155a5ac124SDimitry Andric
8163a0822f0SDimitry Andric /// Version of getValue that returns ResVal directly, or 0 if there is an
8173a0822f0SDimitry Andric /// error.
getValue(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty,unsigned TyID,BasicBlock * ConstExprInsertBB)818b60736ecSDimitry Andric Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
819145449b1SDimitry Andric unsigned InstNum, Type *Ty, unsigned TyID,
820145449b1SDimitry Andric BasicBlock *ConstExprInsertBB) {
8215a5ac124SDimitry Andric if (Slot == Record.size()) return nullptr;
8225a5ac124SDimitry Andric unsigned ValNo = (unsigned)Record[Slot];
8235a5ac124SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum.
8245a5ac124SDimitry Andric if (UseRelativeIDs)
8255a5ac124SDimitry Andric ValNo = InstNum - ValNo;
826145449b1SDimitry Andric return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
8275a5ac124SDimitry Andric }
8285a5ac124SDimitry Andric
8293a0822f0SDimitry Andric /// Like getValue, but decodes signed VBRs.
getValueSigned(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty,unsigned TyID,BasicBlock * ConstExprInsertBB)830b60736ecSDimitry Andric Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
831145449b1SDimitry Andric unsigned InstNum, Type *Ty, unsigned TyID,
832145449b1SDimitry Andric BasicBlock *ConstExprInsertBB) {
8335a5ac124SDimitry Andric if (Slot == Record.size()) return nullptr;
8345a5ac124SDimitry Andric unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
8355a5ac124SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum.
8365a5ac124SDimitry Andric if (UseRelativeIDs)
8375a5ac124SDimitry Andric ValNo = InstNum - ValNo;
838145449b1SDimitry Andric return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
8395a5ac124SDimitry Andric }
8405a5ac124SDimitry Andric
readConstantRange(ArrayRef<uint64_t> Record,unsigned & OpNum,unsigned BitWidth)841ac9a064cSDimitry Andric Expected<ConstantRange> readConstantRange(ArrayRef<uint64_t> Record,
842ac9a064cSDimitry Andric unsigned &OpNum,
843ac9a064cSDimitry Andric unsigned BitWidth) {
844ac9a064cSDimitry Andric if (Record.size() - OpNum < 2)
845ac9a064cSDimitry Andric return error("Too few records for range");
846ac9a064cSDimitry Andric if (BitWidth > 64) {
847ac9a064cSDimitry Andric unsigned LowerActiveWords = Record[OpNum];
848ac9a064cSDimitry Andric unsigned UpperActiveWords = Record[OpNum++] >> 32;
849ac9a064cSDimitry Andric if (Record.size() - OpNum < LowerActiveWords + UpperActiveWords)
850ac9a064cSDimitry Andric return error("Too few records for range");
851ac9a064cSDimitry Andric APInt Lower =
852ac9a064cSDimitry Andric readWideAPInt(ArrayRef(&Record[OpNum], LowerActiveWords), BitWidth);
853ac9a064cSDimitry Andric OpNum += LowerActiveWords;
854ac9a064cSDimitry Andric APInt Upper =
855ac9a064cSDimitry Andric readWideAPInt(ArrayRef(&Record[OpNum], UpperActiveWords), BitWidth);
856ac9a064cSDimitry Andric OpNum += UpperActiveWords;
857ac9a064cSDimitry Andric return ConstantRange(Lower, Upper);
858ac9a064cSDimitry Andric } else {
859ac9a064cSDimitry Andric int64_t Start = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
860ac9a064cSDimitry Andric int64_t End = BitcodeReader::decodeSignRotatedValue(Record[OpNum++]);
861ac9a064cSDimitry Andric return ConstantRange(APInt(BitWidth, Start), APInt(BitWidth, End));
862ac9a064cSDimitry Andric }
863ac9a064cSDimitry Andric }
864ac9a064cSDimitry Andric
865ac9a064cSDimitry Andric Expected<ConstantRange>
readBitWidthAndConstantRange(ArrayRef<uint64_t> Record,unsigned & OpNum)866ac9a064cSDimitry Andric readBitWidthAndConstantRange(ArrayRef<uint64_t> Record, unsigned &OpNum) {
867ac9a064cSDimitry Andric if (Record.size() - OpNum < 1)
868ac9a064cSDimitry Andric return error("Too few records for range");
869ac9a064cSDimitry Andric unsigned BitWidth = Record[OpNum++];
870ac9a064cSDimitry Andric return readConstantRange(Record, OpNum, BitWidth);
871ac9a064cSDimitry Andric }
872ac9a064cSDimitry Andric
873344a3780SDimitry Andric /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
874344a3780SDimitry Andric /// corresponding argument's pointee type. Also upgrades intrinsics that now
875344a3780SDimitry Andric /// require an elementtype attribute.
876145449b1SDimitry Andric Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
877e6d15924SDimitry Andric
8785a5ac124SDimitry Andric /// Converts alignment exponent (i.e. power of two (or zero)) to the
8795a5ac124SDimitry Andric /// corresponding alignment to use. If alignment is too large, returns
8805a5ac124SDimitry Andric /// a corresponding error code.
8811d5ae102SDimitry Andric Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
882b915e9e0SDimitry Andric Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
883e3b55780SDimitry Andric Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
884e3b55780SDimitry Andric ParserCallbacks Callbacks = {});
88571d5a254SDimitry Andric
88671d5a254SDimitry Andric Error parseComdatRecord(ArrayRef<uint64_t> Record);
88771d5a254SDimitry Andric Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
88871d5a254SDimitry Andric Error parseFunctionRecord(ArrayRef<uint64_t> Record);
88971d5a254SDimitry Andric Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
89071d5a254SDimitry Andric ArrayRef<uint64_t> Record);
89171d5a254SDimitry Andric
892b915e9e0SDimitry Andric Error parseAttributeBlock();
893b915e9e0SDimitry Andric Error parseAttributeGroupBlock();
894b915e9e0SDimitry Andric Error parseTypeTable();
895b915e9e0SDimitry Andric Error parseTypeTableBody();
896b915e9e0SDimitry Andric Error parseOperandBundleTags();
897ca089b24SDimitry Andric Error parseSyncScopeNames();
8985a5ac124SDimitry Andric
899b915e9e0SDimitry Andric Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
900dd58ef01SDimitry Andric unsigned NameIndex, Triple &TT);
901d99dafe2SDimitry Andric void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
902d99dafe2SDimitry Andric ArrayRef<uint64_t> Record);
903b915e9e0SDimitry Andric Error parseValueSymbolTable(uint64_t Offset = 0);
904d99dafe2SDimitry Andric Error parseGlobalValueSymbolTable();
905b915e9e0SDimitry Andric Error parseConstants();
906b915e9e0SDimitry Andric Error rememberAndSkipFunctionBodies();
907b915e9e0SDimitry Andric Error rememberAndSkipFunctionBody();
9085a5ac124SDimitry Andric /// Save the positions of the Metadata blocks and skip parsing the blocks.
909b915e9e0SDimitry Andric Error rememberAndSkipMetadata();
910b915e9e0SDimitry Andric Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
911b915e9e0SDimitry Andric Error parseFunctionBody(Function *F);
912b915e9e0SDimitry Andric Error globalCleanup();
913b915e9e0SDimitry Andric Error resolveGlobalAndIndirectSymbolInits();
914b915e9e0SDimitry Andric Error parseUseLists();
915b915e9e0SDimitry Andric Error findFunctionInStream(
9165a5ac124SDimitry Andric Function *F,
9175a5ac124SDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
918ca089b24SDimitry Andric
919ca089b24SDimitry Andric SyncScope::ID getDecodedSyncScopeID(unsigned Val);
9205a5ac124SDimitry Andric };
921dd58ef01SDimitry Andric
922dd58ef01SDimitry Andric /// Class to manage reading and parsing function summary index bitcode
923dd58ef01SDimitry Andric /// files/sections.
924b915e9e0SDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
925b915e9e0SDimitry Andric /// The module index built during parsing.
926b915e9e0SDimitry Andric ModuleSummaryIndex &TheIndex;
927dd58ef01SDimitry Andric
92801095a5dSDimitry Andric /// Indicates whether we have encountered a global value summary section
929b915e9e0SDimitry Andric /// yet during parsing.
93001095a5dSDimitry Andric bool SeenGlobalValSummary = false;
931dd58ef01SDimitry Andric
93201095a5dSDimitry Andric /// Indicates whether we have already parsed the VST, used for error checking.
93301095a5dSDimitry Andric bool SeenValueSymbolTable = false;
93401095a5dSDimitry Andric
93501095a5dSDimitry Andric /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
93601095a5dSDimitry Andric /// Used to enable on-demand parsing of the VST.
93701095a5dSDimitry Andric uint64_t VSTOffset = 0;
93801095a5dSDimitry Andric
939c46e6a59SDimitry Andric // Map to save ValueId to ValueInfo association that was recorded in the
94001095a5dSDimitry Andric // ValueSymbolTable. It is used after the VST is parsed to convert
94101095a5dSDimitry Andric // call graph edges read from the function summary from referencing
942c46e6a59SDimitry Andric // callees by their ValueId to using the ValueInfo instead, which is how
94301095a5dSDimitry Andric // they are recorded in the summary index being built.
944c46e6a59SDimitry Andric // We save a GUID which refers to the same global as the ValueInfo, but
945c46e6a59SDimitry Andric // ignoring the linkage, i.e. for values other than local linkage they are
946e3b55780SDimitry Andric // identical (this is the second tuple member).
947e3b55780SDimitry Andric // The third tuple member is the real GUID of the ValueInfo.
948e3b55780SDimitry Andric DenseMap<unsigned,
949e3b55780SDimitry Andric std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>>
950c46e6a59SDimitry Andric ValueIdToValueInfoMap;
951dd58ef01SDimitry Andric
952dd58ef01SDimitry Andric /// Map populated during module path string table parsing, from the
953dd58ef01SDimitry Andric /// module ID to a string reference owned by the index's module
95401095a5dSDimitry Andric /// path string table, used to correlate with combined index
955dd58ef01SDimitry Andric /// summary records.
956dd58ef01SDimitry Andric DenseMap<uint64_t, StringRef> ModuleIdMap;
957dd58ef01SDimitry Andric
95801095a5dSDimitry Andric /// Original source file name recorded in a bitcode record.
95901095a5dSDimitry Andric std::string SourceFileName;
96001095a5dSDimitry Andric
961a303c417SDimitry Andric /// The string identifier given to this module by the client, normally the
962a303c417SDimitry Andric /// path to the bitcode file.
963a303c417SDimitry Andric StringRef ModulePath;
964a303c417SDimitry Andric
965e3b55780SDimitry Andric /// Callback to ask whether a symbol is the prevailing copy when invoked
966e3b55780SDimitry Andric /// during combined index building.
967e3b55780SDimitry Andric std::function<bool(GlobalValue::GUID)> IsPrevailing;
968e3b55780SDimitry Andric
969e3b55780SDimitry Andric /// Saves the stack ids from the STACK_IDS record to consult when adding stack
970e3b55780SDimitry Andric /// ids from the lists in the callsite and alloc entries to the index.
971e3b55780SDimitry Andric std::vector<uint64_t> StackIds;
972e3b55780SDimitry Andric
973dd58ef01SDimitry Andric public:
974e3b55780SDimitry Andric ModuleSummaryIndexBitcodeReader(
975e3b55780SDimitry Andric BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
976b1c73532SDimitry Andric StringRef ModulePath,
977e3b55780SDimitry Andric std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr);
978dd58ef01SDimitry Andric
979a303c417SDimitry Andric Error parseModule();
980dd58ef01SDimitry Andric
981dd58ef01SDimitry Andric private:
982d99dafe2SDimitry Andric void setValueGUID(uint64_t ValueID, StringRef ValueName,
983d99dafe2SDimitry Andric GlobalValue::LinkageTypes Linkage,
984d99dafe2SDimitry Andric StringRef SourceFileName);
985b915e9e0SDimitry Andric Error parseValueSymbolTable(
98601095a5dSDimitry Andric uint64_t Offset,
98701095a5dSDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
988b915e9e0SDimitry Andric std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
989b915e9e0SDimitry Andric std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
990b915e9e0SDimitry Andric bool IsOldProfileFormat,
991eb11fae6SDimitry Andric bool HasProfile,
992eb11fae6SDimitry Andric bool HasRelBF);
9937c7aba6eSDimitry Andric Error parseEntireSummary(unsigned ID);
994b915e9e0SDimitry Andric Error parseModuleStringTable();
995e6d15924SDimitry Andric void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
996e6d15924SDimitry Andric void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
997e6d15924SDimitry Andric TypeIdCompatibleVtableInfo &TypeId);
998b60736ecSDimitry Andric std::vector<FunctionSummary::ParamAccess>
999b60736ecSDimitry Andric parseParamAccesses(ArrayRef<uint64_t> Record);
1000b915e9e0SDimitry Andric
1001e3b55780SDimitry Andric template <bool AllowNullValueInfo = false>
1002e3b55780SDimitry Andric std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
1003c46e6a59SDimitry Andric getValueInfoFromValueId(unsigned ValueId);
1004a303c417SDimitry Andric
1005eb11fae6SDimitry Andric void addThisModule();
1006eb11fae6SDimitry Andric ModuleSummaryIndex::ModuleInfo *getThisModule();
1007dd58ef01SDimitry Andric };
1008b915e9e0SDimitry Andric
100901095a5dSDimitry Andric } // end anonymous namespace
10105a5ac124SDimitry Andric
errorToErrorCodeAndEmitErrors(LLVMContext & Ctx,Error Err)1011b915e9e0SDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
1012b915e9e0SDimitry Andric Error Err) {
1013b915e9e0SDimitry Andric if (Err) {
1014b915e9e0SDimitry Andric std::error_code EC;
1015b915e9e0SDimitry Andric handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
1016b915e9e0SDimitry Andric EC = EIB.convertToErrorCode();
1017b915e9e0SDimitry Andric Ctx.emitError(EIB.message());
1018b915e9e0SDimitry Andric });
101967c32a98SDimitry Andric return EC;
102063faed5bSDimitry Andric }
102167c32a98SDimitry Andric return std::error_code();
1022b915e9e0SDimitry Andric }
1023b915e9e0SDimitry Andric
BitcodeReader(BitstreamCursor Stream,StringRef Strtab,StringRef ProducerIdentification,LLVMContext & Context)1024d99dafe2SDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
1025b915e9e0SDimitry Andric StringRef ProducerIdentification,
1026b915e9e0SDimitry Andric LLVMContext &Context)
1027d99dafe2SDimitry Andric : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
1028145449b1SDimitry Andric ValueList(this->Stream.SizeInBytes(),
1029145449b1SDimitry Andric [this](unsigned ValID, BasicBlock *InsertBB) {
1030145449b1SDimitry Andric return materializeValue(ValID, InsertBB);
1031145449b1SDimitry Andric }) {
1032cfca06d7SDimitry Andric this->ProducerIdentification = std::string(ProducerIdentification);
1033b915e9e0SDimitry Andric }
1034b915e9e0SDimitry Andric
materializeForwardReferencedFunctions()1035b915e9e0SDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() {
1036b915e9e0SDimitry Andric if (WillMaterializeAllForwardRefs)
1037b915e9e0SDimitry Andric return Error::success();
103867c32a98SDimitry Andric
103967c32a98SDimitry Andric // Prevent recursion.
104067c32a98SDimitry Andric WillMaterializeAllForwardRefs = true;
104167c32a98SDimitry Andric
104267c32a98SDimitry Andric while (!BasicBlockFwdRefQueue.empty()) {
104367c32a98SDimitry Andric Function *F = BasicBlockFwdRefQueue.front();
104467c32a98SDimitry Andric BasicBlockFwdRefQueue.pop_front();
104567c32a98SDimitry Andric assert(F && "Expected valid function");
104667c32a98SDimitry Andric if (!BasicBlockFwdRefs.count(F))
104767c32a98SDimitry Andric // Already materialized.
104867c32a98SDimitry Andric continue;
104967c32a98SDimitry Andric
105067c32a98SDimitry Andric // Check for a function that isn't materializable to prevent an infinite
105167c32a98SDimitry Andric // loop. When parsing a blockaddress stored in a global variable, there
105267c32a98SDimitry Andric // isn't a trivial way to check if a function will have a body without a
105367c32a98SDimitry Andric // linear search through FunctionsWithBodies, so just check it here.
105467c32a98SDimitry Andric if (!F->isMaterializable())
10553a0822f0SDimitry Andric return error("Never resolved function from blockaddress");
105667c32a98SDimitry Andric
105767c32a98SDimitry Andric // Try to materialize F.
1058b915e9e0SDimitry Andric if (Error Err = materialize(F))
1059b915e9e0SDimitry Andric return Err;
106067c32a98SDimitry Andric }
106167c32a98SDimitry Andric assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
106267c32a98SDimitry Andric
1063145449b1SDimitry Andric for (Function *F : BackwardRefFunctions)
1064145449b1SDimitry Andric if (Error Err = materialize(F))
1065145449b1SDimitry Andric return Err;
1066145449b1SDimitry Andric BackwardRefFunctions.clear();
1067145449b1SDimitry Andric
106867c32a98SDimitry Andric // Reset state.
106967c32a98SDimitry Andric WillMaterializeAllForwardRefs = false;
1070b915e9e0SDimitry Andric return Error::success();
1071009b1c42SEd Schouten }
1072009b1c42SEd Schouten
1073009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1074009b1c42SEd Schouten // Helper functions to implement forward reference resolution, etc.
1075009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1076009b1c42SEd Schouten
hasImplicitComdat(size_t Val)10775a5ac124SDimitry Andric static bool hasImplicitComdat(size_t Val) {
10785a5ac124SDimitry Andric switch (Val) {
10795a5ac124SDimitry Andric default:
10805a5ac124SDimitry Andric return false;
10815a5ac124SDimitry Andric case 1: // Old WeakAnyLinkage
10825a5ac124SDimitry Andric case 4: // Old LinkOnceAnyLinkage
10835a5ac124SDimitry Andric case 10: // Old WeakODRLinkage
10845a5ac124SDimitry Andric case 11: // Old LinkOnceODRLinkage
10855a5ac124SDimitry Andric return true;
10865a5ac124SDimitry Andric }
10875a5ac124SDimitry Andric }
10885a5ac124SDimitry Andric
getDecodedLinkage(unsigned Val)108967c32a98SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
1090009b1c42SEd Schouten switch (Val) {
1091009b1c42SEd Schouten default: // Map unknown/new linkages to external
109267c32a98SDimitry Andric case 0:
109367c32a98SDimitry Andric return GlobalValue::ExternalLinkage;
109467c32a98SDimitry Andric case 2:
109567c32a98SDimitry Andric return GlobalValue::AppendingLinkage;
109667c32a98SDimitry Andric case 3:
109767c32a98SDimitry Andric return GlobalValue::InternalLinkage;
109867c32a98SDimitry Andric case 5:
109967c32a98SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
110067c32a98SDimitry Andric case 6:
110167c32a98SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
110267c32a98SDimitry Andric case 7:
110367c32a98SDimitry Andric return GlobalValue::ExternalWeakLinkage;
110467c32a98SDimitry Andric case 8:
110567c32a98SDimitry Andric return GlobalValue::CommonLinkage;
110667c32a98SDimitry Andric case 9:
110767c32a98SDimitry Andric return GlobalValue::PrivateLinkage;
110867c32a98SDimitry Andric case 12:
110967c32a98SDimitry Andric return GlobalValue::AvailableExternallyLinkage;
11105ca98fd9SDimitry Andric case 13:
11115ca98fd9SDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
11125ca98fd9SDimitry Andric case 14:
11135ca98fd9SDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
111467c32a98SDimitry Andric case 15:
111567c32a98SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
11165a5ac124SDimitry Andric case 1: // Old value with implicit comdat.
11175a5ac124SDimitry Andric case 16:
11185a5ac124SDimitry Andric return GlobalValue::WeakAnyLinkage;
11195a5ac124SDimitry Andric case 10: // Old value with implicit comdat.
11205a5ac124SDimitry Andric case 17:
11215a5ac124SDimitry Andric return GlobalValue::WeakODRLinkage;
11225a5ac124SDimitry Andric case 4: // Old value with implicit comdat.
11235a5ac124SDimitry Andric case 18:
11245a5ac124SDimitry Andric return GlobalValue::LinkOnceAnyLinkage;
11255a5ac124SDimitry Andric case 11: // Old value with implicit comdat.
11265a5ac124SDimitry Andric case 19:
11275a5ac124SDimitry Andric return GlobalValue::LinkOnceODRLinkage;
1128009b1c42SEd Schouten }
1129009b1c42SEd Schouten }
1130009b1c42SEd Schouten
getDecodedFFlags(uint64_t RawFlags)1131044eb2f6SDimitry Andric static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
1132044eb2f6SDimitry Andric FunctionSummary::FFlags Flags;
1133044eb2f6SDimitry Andric Flags.ReadNone = RawFlags & 0x1;
1134044eb2f6SDimitry Andric Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1135044eb2f6SDimitry Andric Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1136044eb2f6SDimitry Andric Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1137d8e91e46SDimitry Andric Flags.NoInline = (RawFlags >> 4) & 0x1;
1138706b4fc4SDimitry Andric Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1139c0981da4SDimitry Andric Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1140c0981da4SDimitry Andric Flags.MayThrow = (RawFlags >> 7) & 0x1;
1141c0981da4SDimitry Andric Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
114277fc4c14SDimitry Andric Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1143044eb2f6SDimitry Andric return Flags;
1144044eb2f6SDimitry Andric }
1145044eb2f6SDimitry Andric
1146344a3780SDimitry Andric // Decode the flags for GlobalValue in the summary. The bits for each attribute:
1147344a3780SDimitry Andric //
1148344a3780SDimitry Andric // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
1149344a3780SDimitry Andric // visibility: [8, 10).
getDecodedGVSummaryFlags(uint64_t RawFlags,uint64_t Version)115001095a5dSDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
115101095a5dSDimitry Andric uint64_t Version) {
115201095a5dSDimitry Andric // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
115301095a5dSDimitry Andric // like getDecodedLinkage() above. Any future change to the linkage enum and
115401095a5dSDimitry Andric // to getDecodedLinkage() will need to be taken into account here as above.
115501095a5dSDimitry Andric auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
1156344a3780SDimitry Andric auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
1157ac9a064cSDimitry Andric auto IK = GlobalValueSummary::ImportKind((RawFlags >> 10) & 1); // 1 bit
115801095a5dSDimitry Andric RawFlags = RawFlags >> 4;
11597e7b6700SDimitry Andric bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1160d288ef4cSDimitry Andric // The Live flag wasn't introduced until version 3. For dead stripping
11617e7b6700SDimitry Andric // to work correctly on earlier versions, we must conservatively treat all
11627e7b6700SDimitry Andric // values as live.
1163d288ef4cSDimitry Andric bool Live = (RawFlags & 0x2) || Version < 3;
1164044eb2f6SDimitry Andric bool Local = (RawFlags & 0x4);
1165e6d15924SDimitry Andric bool AutoHide = (RawFlags & 0x8);
1166044eb2f6SDimitry Andric
1167344a3780SDimitry Andric return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
1168ac9a064cSDimitry Andric Live, Local, AutoHide, IK);
116901095a5dSDimitry Andric }
117001095a5dSDimitry Andric
1171d8e91e46SDimitry Andric // Decode the flags for GlobalVariable in the summary
getDecodedGVarFlags(uint64_t RawFlags)1172d8e91e46SDimitry Andric static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
1173cfca06d7SDimitry Andric return GlobalVarSummary::GVarFlags(
1174cfca06d7SDimitry Andric (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
1175cfca06d7SDimitry Andric (RawFlags & 0x4) ? true : false,
1176cfca06d7SDimitry Andric (GlobalObject::VCallVisibility)(RawFlags >> 3));
1177d8e91e46SDimitry Andric }
1178d8e91e46SDimitry Andric
1179b1c73532SDimitry Andric static std::pair<CalleeInfo::HotnessType, bool>
getDecodedHotnessCallEdgeInfo(uint64_t RawFlags)1180b1c73532SDimitry Andric getDecodedHotnessCallEdgeInfo(uint64_t RawFlags) {
1181b1c73532SDimitry Andric CalleeInfo::HotnessType Hotness =
1182b1c73532SDimitry Andric static_cast<CalleeInfo::HotnessType>(RawFlags & 0x7); // 3 bits
1183b1c73532SDimitry Andric bool HasTailCall = (RawFlags & 0x8); // 1 bit
1184b1c73532SDimitry Andric return {Hotness, HasTailCall};
1185b1c73532SDimitry Andric }
1186b1c73532SDimitry Andric
getDecodedRelBFCallEdgeInfo(uint64_t RawFlags,uint64_t & RelBF,bool & HasTailCall)1187b1c73532SDimitry Andric static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF,
1188b1c73532SDimitry Andric bool &HasTailCall) {
1189b1c73532SDimitry Andric static constexpr uint64_t RelBlockFreqMask =
1190b1c73532SDimitry Andric (1 << CalleeInfo::RelBlockFreqBits) - 1;
1191b1c73532SDimitry Andric RelBF = RawFlags & RelBlockFreqMask; // RelBlockFreqBits bits
1192b1c73532SDimitry Andric HasTailCall = (RawFlags & (1 << CalleeInfo::RelBlockFreqBits)); // 1 bit
1193b1c73532SDimitry Andric }
1194b1c73532SDimitry Andric
getDecodedVisibility(unsigned Val)11953a0822f0SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
1196009b1c42SEd Schouten switch (Val) {
1197009b1c42SEd Schouten default: // Map unknown visibilities to default.
1198009b1c42SEd Schouten case 0: return GlobalValue::DefaultVisibility;
1199009b1c42SEd Schouten case 1: return GlobalValue::HiddenVisibility;
1200009b1c42SEd Schouten case 2: return GlobalValue::ProtectedVisibility;
1201009b1c42SEd Schouten }
1202009b1c42SEd Schouten }
1203009b1c42SEd Schouten
12045ca98fd9SDimitry Andric static GlobalValue::DLLStorageClassTypes
getDecodedDLLStorageClass(unsigned Val)12053a0822f0SDimitry Andric getDecodedDLLStorageClass(unsigned Val) {
12065ca98fd9SDimitry Andric switch (Val) {
12075ca98fd9SDimitry Andric default: // Map unknown values to default.
12085ca98fd9SDimitry Andric case 0: return GlobalValue::DefaultStorageClass;
12095ca98fd9SDimitry Andric case 1: return GlobalValue::DLLImportStorageClass;
12105ca98fd9SDimitry Andric case 2: return GlobalValue::DLLExportStorageClass;
12115ca98fd9SDimitry Andric }
12125ca98fd9SDimitry Andric }
12135ca98fd9SDimitry Andric
getDecodedDSOLocal(unsigned Val)1214044eb2f6SDimitry Andric static bool getDecodedDSOLocal(unsigned Val) {
1215044eb2f6SDimitry Andric switch(Val) {
1216044eb2f6SDimitry Andric default: // Map unknown values to preemptable.
1217044eb2f6SDimitry Andric case 0: return false;
1218044eb2f6SDimitry Andric case 1: return true;
1219044eb2f6SDimitry Andric }
1220044eb2f6SDimitry Andric }
1221044eb2f6SDimitry Andric
getDecodedCodeModel(unsigned Val)1222b1c73532SDimitry Andric static std::optional<CodeModel::Model> getDecodedCodeModel(unsigned Val) {
1223b1c73532SDimitry Andric switch (Val) {
1224b1c73532SDimitry Andric case 1:
1225b1c73532SDimitry Andric return CodeModel::Tiny;
1226b1c73532SDimitry Andric case 2:
1227b1c73532SDimitry Andric return CodeModel::Small;
1228b1c73532SDimitry Andric case 3:
1229b1c73532SDimitry Andric return CodeModel::Kernel;
1230b1c73532SDimitry Andric case 4:
1231b1c73532SDimitry Andric return CodeModel::Medium;
1232b1c73532SDimitry Andric case 5:
1233b1c73532SDimitry Andric return CodeModel::Large;
1234b1c73532SDimitry Andric }
1235b1c73532SDimitry Andric
1236b1c73532SDimitry Andric return {};
1237b1c73532SDimitry Andric }
1238b1c73532SDimitry Andric
getDecodedThreadLocalMode(unsigned Val)12393a0822f0SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
124058b69754SDimitry Andric switch (Val) {
124158b69754SDimitry Andric case 0: return GlobalVariable::NotThreadLocal;
124258b69754SDimitry Andric default: // Map unknown non-zero value to general dynamic.
124358b69754SDimitry Andric case 1: return GlobalVariable::GeneralDynamicTLSModel;
124458b69754SDimitry Andric case 2: return GlobalVariable::LocalDynamicTLSModel;
124558b69754SDimitry Andric case 3: return GlobalVariable::InitialExecTLSModel;
124658b69754SDimitry Andric case 4: return GlobalVariable::LocalExecTLSModel;
124758b69754SDimitry Andric }
124858b69754SDimitry Andric }
124958b69754SDimitry Andric
getDecodedUnnamedAddrType(unsigned Val)125001095a5dSDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
125101095a5dSDimitry Andric switch (Val) {
125201095a5dSDimitry Andric default: // Map unknown to UnnamedAddr::None.
125301095a5dSDimitry Andric case 0: return GlobalVariable::UnnamedAddr::None;
125401095a5dSDimitry Andric case 1: return GlobalVariable::UnnamedAddr::Global;
125501095a5dSDimitry Andric case 2: return GlobalVariable::UnnamedAddr::Local;
125601095a5dSDimitry Andric }
125701095a5dSDimitry Andric }
125801095a5dSDimitry Andric
getDecodedCastOpcode(unsigned Val)12593a0822f0SDimitry Andric static int getDecodedCastOpcode(unsigned Val) {
1260009b1c42SEd Schouten switch (Val) {
1261009b1c42SEd Schouten default: return -1;
1262009b1c42SEd Schouten case bitc::CAST_TRUNC : return Instruction::Trunc;
1263009b1c42SEd Schouten case bitc::CAST_ZEXT : return Instruction::ZExt;
1264009b1c42SEd Schouten case bitc::CAST_SEXT : return Instruction::SExt;
1265009b1c42SEd Schouten case bitc::CAST_FPTOUI : return Instruction::FPToUI;
1266009b1c42SEd Schouten case bitc::CAST_FPTOSI : return Instruction::FPToSI;
1267009b1c42SEd Schouten case bitc::CAST_UITOFP : return Instruction::UIToFP;
1268009b1c42SEd Schouten case bitc::CAST_SITOFP : return Instruction::SIToFP;
1269009b1c42SEd Schouten case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
1270009b1c42SEd Schouten case bitc::CAST_FPEXT : return Instruction::FPExt;
1271009b1c42SEd Schouten case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
1272009b1c42SEd Schouten case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
1273009b1c42SEd Schouten case bitc::CAST_BITCAST : return Instruction::BitCast;
1274f8af5cf6SDimitry Andric case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
1275009b1c42SEd Schouten }
1276009b1c42SEd Schouten }
12775a5ac124SDimitry Andric
getDecodedUnaryOpcode(unsigned Val,Type * Ty)1278d8e91e46SDimitry Andric static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
1279d8e91e46SDimitry Andric bool IsFP = Ty->isFPOrFPVectorTy();
1280d8e91e46SDimitry Andric // UnOps are only valid for int/fp or vector of int/fp types
1281d8e91e46SDimitry Andric if (!IsFP && !Ty->isIntOrIntVectorTy())
1282d8e91e46SDimitry Andric return -1;
1283d8e91e46SDimitry Andric
1284d8e91e46SDimitry Andric switch (Val) {
1285d8e91e46SDimitry Andric default:
1286d8e91e46SDimitry Andric return -1;
12871d5ae102SDimitry Andric case bitc::UNOP_FNEG:
1288d8e91e46SDimitry Andric return IsFP ? Instruction::FNeg : -1;
1289d8e91e46SDimitry Andric }
1290d8e91e46SDimitry Andric }
1291d8e91e46SDimitry Andric
getDecodedBinaryOpcode(unsigned Val,Type * Ty)12923a0822f0SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
12935a5ac124SDimitry Andric bool IsFP = Ty->isFPOrFPVectorTy();
12945a5ac124SDimitry Andric // BinOps are only valid for int/fp or vector of int/fp types
12955a5ac124SDimitry Andric if (!IsFP && !Ty->isIntOrIntVectorTy())
12965a5ac124SDimitry Andric return -1;
12975a5ac124SDimitry Andric
1298009b1c42SEd Schouten switch (Val) {
12995a5ac124SDimitry Andric default:
13005a5ac124SDimitry Andric return -1;
1301f4fe016fSEd Schouten case bitc::BINOP_ADD:
13025a5ac124SDimitry Andric return IsFP ? Instruction::FAdd : Instruction::Add;
1303f4fe016fSEd Schouten case bitc::BINOP_SUB:
13045a5ac124SDimitry Andric return IsFP ? Instruction::FSub : Instruction::Sub;
1305f4fe016fSEd Schouten case bitc::BINOP_MUL:
13065a5ac124SDimitry Andric return IsFP ? Instruction::FMul : Instruction::Mul;
13075a5ac124SDimitry Andric case bitc::BINOP_UDIV:
13085a5ac124SDimitry Andric return IsFP ? -1 : Instruction::UDiv;
1309009b1c42SEd Schouten case bitc::BINOP_SDIV:
13105a5ac124SDimitry Andric return IsFP ? Instruction::FDiv : Instruction::SDiv;
13115a5ac124SDimitry Andric case bitc::BINOP_UREM:
13125a5ac124SDimitry Andric return IsFP ? -1 : Instruction::URem;
1313009b1c42SEd Schouten case bitc::BINOP_SREM:
13145a5ac124SDimitry Andric return IsFP ? Instruction::FRem : Instruction::SRem;
13155a5ac124SDimitry Andric case bitc::BINOP_SHL:
13165a5ac124SDimitry Andric return IsFP ? -1 : Instruction::Shl;
13175a5ac124SDimitry Andric case bitc::BINOP_LSHR:
13185a5ac124SDimitry Andric return IsFP ? -1 : Instruction::LShr;
13195a5ac124SDimitry Andric case bitc::BINOP_ASHR:
13205a5ac124SDimitry Andric return IsFP ? -1 : Instruction::AShr;
13215a5ac124SDimitry Andric case bitc::BINOP_AND:
13225a5ac124SDimitry Andric return IsFP ? -1 : Instruction::And;
13235a5ac124SDimitry Andric case bitc::BINOP_OR:
13245a5ac124SDimitry Andric return IsFP ? -1 : Instruction::Or;
13255a5ac124SDimitry Andric case bitc::BINOP_XOR:
13265a5ac124SDimitry Andric return IsFP ? -1 : Instruction::Xor;
1327009b1c42SEd Schouten }
1328009b1c42SEd Schouten }
1329009b1c42SEd Schouten
getDecodedRMWOperation(unsigned Val)13303a0822f0SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
133130815c53SDimitry Andric switch (Val) {
133230815c53SDimitry Andric default: return AtomicRMWInst::BAD_BINOP;
133330815c53SDimitry Andric case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
133430815c53SDimitry Andric case bitc::RMW_ADD: return AtomicRMWInst::Add;
133530815c53SDimitry Andric case bitc::RMW_SUB: return AtomicRMWInst::Sub;
133630815c53SDimitry Andric case bitc::RMW_AND: return AtomicRMWInst::And;
133730815c53SDimitry Andric case bitc::RMW_NAND: return AtomicRMWInst::Nand;
133830815c53SDimitry Andric case bitc::RMW_OR: return AtomicRMWInst::Or;
133930815c53SDimitry Andric case bitc::RMW_XOR: return AtomicRMWInst::Xor;
134030815c53SDimitry Andric case bitc::RMW_MAX: return AtomicRMWInst::Max;
134130815c53SDimitry Andric case bitc::RMW_MIN: return AtomicRMWInst::Min;
134230815c53SDimitry Andric case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
134330815c53SDimitry Andric case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1344e6d15924SDimitry Andric case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
1345e6d15924SDimitry Andric case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
13461f917f69SDimitry Andric case bitc::RMW_FMAX: return AtomicRMWInst::FMax;
13471f917f69SDimitry Andric case bitc::RMW_FMIN: return AtomicRMWInst::FMin;
1348e3b55780SDimitry Andric case bitc::RMW_UINC_WRAP:
1349e3b55780SDimitry Andric return AtomicRMWInst::UIncWrap;
1350e3b55780SDimitry Andric case bitc::RMW_UDEC_WRAP:
1351e3b55780SDimitry Andric return AtomicRMWInst::UDecWrap;
135230815c53SDimitry Andric }
135330815c53SDimitry Andric }
135430815c53SDimitry Andric
getDecodedOrdering(unsigned Val)13553a0822f0SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) {
135630815c53SDimitry Andric switch (Val) {
135701095a5dSDimitry Andric case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
135801095a5dSDimitry Andric case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
135901095a5dSDimitry Andric case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
136001095a5dSDimitry Andric case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
136101095a5dSDimitry Andric case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
136201095a5dSDimitry Andric case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
136330815c53SDimitry Andric default: // Map unknown orderings to sequentially-consistent.
136401095a5dSDimitry Andric case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
136530815c53SDimitry Andric }
136630815c53SDimitry Andric }
136730815c53SDimitry Andric
getDecodedComdatSelectionKind(unsigned Val)13685ca98fd9SDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
13695ca98fd9SDimitry Andric switch (Val) {
13705ca98fd9SDimitry Andric default: // Map unknown selection kinds to any.
13715ca98fd9SDimitry Andric case bitc::COMDAT_SELECTION_KIND_ANY:
13725ca98fd9SDimitry Andric return Comdat::Any;
13735ca98fd9SDimitry Andric case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
13745ca98fd9SDimitry Andric return Comdat::ExactMatch;
13755ca98fd9SDimitry Andric case bitc::COMDAT_SELECTION_KIND_LARGEST:
13765ca98fd9SDimitry Andric return Comdat::Largest;
13775ca98fd9SDimitry Andric case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1378344a3780SDimitry Andric return Comdat::NoDeduplicate;
13795ca98fd9SDimitry Andric case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
13805ca98fd9SDimitry Andric return Comdat::SameSize;
13815ca98fd9SDimitry Andric }
13825ca98fd9SDimitry Andric }
13835ca98fd9SDimitry Andric
getDecodedFastMathFlags(unsigned Val)1384ee8648bdSDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1385ee8648bdSDimitry Andric FastMathFlags FMF;
1386eb11fae6SDimitry Andric if (0 != (Val & bitc::UnsafeAlgebra))
1387eb11fae6SDimitry Andric FMF.setFast();
1388eb11fae6SDimitry Andric if (0 != (Val & bitc::AllowReassoc))
1389044eb2f6SDimitry Andric FMF.setAllowReassoc();
1390eb11fae6SDimitry Andric if (0 != (Val & bitc::NoNaNs))
1391ee8648bdSDimitry Andric FMF.setNoNaNs();
1392eb11fae6SDimitry Andric if (0 != (Val & bitc::NoInfs))
1393ee8648bdSDimitry Andric FMF.setNoInfs();
1394eb11fae6SDimitry Andric if (0 != (Val & bitc::NoSignedZeros))
1395ee8648bdSDimitry Andric FMF.setNoSignedZeros();
1396eb11fae6SDimitry Andric if (0 != (Val & bitc::AllowReciprocal))
1397ee8648bdSDimitry Andric FMF.setAllowReciprocal();
1398eb11fae6SDimitry Andric if (0 != (Val & bitc::AllowContract))
139971d5a254SDimitry Andric FMF.setAllowContract(true);
1400eb11fae6SDimitry Andric if (0 != (Val & bitc::ApproxFunc))
1401044eb2f6SDimitry Andric FMF.setApproxFunc();
1402ee8648bdSDimitry Andric return FMF;
1403ee8648bdSDimitry Andric }
1404ee8648bdSDimitry Andric
upgradeDLLImportExportLinkage(GlobalValue * GV,unsigned Val)1405b915e9e0SDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1406e3b55780SDimitry Andric // A GlobalValue with local linkage cannot have a DLL storage class.
1407e3b55780SDimitry Andric if (GV->hasLocalLinkage())
1408e3b55780SDimitry Andric return;
14095ca98fd9SDimitry Andric switch (Val) {
14105ca98fd9SDimitry Andric case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
14115ca98fd9SDimitry Andric case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
14125ca98fd9SDimitry Andric }
14135ca98fd9SDimitry Andric }
14145ca98fd9SDimitry Andric
getTypeByID(unsigned ID)1415344a3780SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) {
1416411bd29eSDimitry Andric // The type table size is always specified correctly.
1417411bd29eSDimitry Andric if (ID >= TypeList.size())
14185ca98fd9SDimitry Andric return nullptr;
1419009b1c42SEd Schouten
1420411bd29eSDimitry Andric if (Type *Ty = TypeList[ID])
1421411bd29eSDimitry Andric return Ty;
1422411bd29eSDimitry Andric
1423411bd29eSDimitry Andric // If we have a forward reference, the only possible case is when it is to a
1424411bd29eSDimitry Andric // named struct. Just create a placeholder for now.
142567c32a98SDimitry Andric return TypeList[ID] = createIdentifiedStructType(Context);
142667c32a98SDimitry Andric }
142767c32a98SDimitry Andric
getContainedTypeID(unsigned ID,unsigned Idx)1428145449b1SDimitry Andric unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) {
1429145449b1SDimitry Andric auto It = ContainedTypeIDs.find(ID);
1430145449b1SDimitry Andric if (It == ContainedTypeIDs.end())
1431145449b1SDimitry Andric return InvalidTypeID;
1432145449b1SDimitry Andric
1433145449b1SDimitry Andric if (Idx >= It->second.size())
1434145449b1SDimitry Andric return InvalidTypeID;
1435145449b1SDimitry Andric
1436145449b1SDimitry Andric return It->second[Idx];
1437145449b1SDimitry Andric }
1438145449b1SDimitry Andric
getPtrElementTypeByID(unsigned ID)1439145449b1SDimitry Andric Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) {
1440145449b1SDimitry Andric if (ID >= TypeList.size())
1441145449b1SDimitry Andric return nullptr;
1442145449b1SDimitry Andric
1443145449b1SDimitry Andric Type *Ty = TypeList[ID];
1444145449b1SDimitry Andric if (!Ty->isPointerTy())
1445145449b1SDimitry Andric return nullptr;
1446145449b1SDimitry Andric
14477fa27ce4SDimitry Andric return getTypeByID(getContainedTypeID(ID, 0));
1448145449b1SDimitry Andric }
1449145449b1SDimitry Andric
getVirtualTypeID(Type * Ty,ArrayRef<unsigned> ChildTypeIDs)1450145449b1SDimitry Andric unsigned BitcodeReader::getVirtualTypeID(Type *Ty,
1451145449b1SDimitry Andric ArrayRef<unsigned> ChildTypeIDs) {
1452145449b1SDimitry Andric unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0];
1453145449b1SDimitry Andric auto CacheKey = std::make_pair(Ty, ChildTypeID);
1454145449b1SDimitry Andric auto It = VirtualTypeIDs.find(CacheKey);
1455145449b1SDimitry Andric if (It != VirtualTypeIDs.end()) {
1456145449b1SDimitry Andric // The cmpxchg return value is the only place we need more than one
1457145449b1SDimitry Andric // contained type ID, however the second one will always be the same (i1),
1458145449b1SDimitry Andric // so we don't need to include it in the cache key. This asserts that the
1459145449b1SDimitry Andric // contained types are indeed as expected and there are no collisions.
1460145449b1SDimitry Andric assert((ChildTypeIDs.empty() ||
1461145449b1SDimitry Andric ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1462145449b1SDimitry Andric "Incorrect cached contained type IDs");
1463145449b1SDimitry Andric return It->second;
1464145449b1SDimitry Andric }
1465145449b1SDimitry Andric
1466145449b1SDimitry Andric unsigned TypeID = TypeList.size();
1467145449b1SDimitry Andric TypeList.push_back(Ty);
1468145449b1SDimitry Andric if (!ChildTypeIDs.empty())
1469145449b1SDimitry Andric append_range(ContainedTypeIDs[TypeID], ChildTypeIDs);
1470145449b1SDimitry Andric VirtualTypeIDs.insert({CacheKey, TypeID});
1471145449b1SDimitry Andric return TypeID;
1472145449b1SDimitry Andric }
1473145449b1SDimitry Andric
toGEPNoWrapFlags(uint64_t Flags)1474ac9a064cSDimitry Andric static GEPNoWrapFlags toGEPNoWrapFlags(uint64_t Flags) {
1475ac9a064cSDimitry Andric GEPNoWrapFlags NW;
1476ac9a064cSDimitry Andric if (Flags & (1 << bitc::GEP_INBOUNDS))
1477ac9a064cSDimitry Andric NW |= GEPNoWrapFlags::inBounds();
1478ac9a064cSDimitry Andric if (Flags & (1 << bitc::GEP_NUSW))
1479ac9a064cSDimitry Andric NW |= GEPNoWrapFlags::noUnsignedSignedWrap();
1480ac9a064cSDimitry Andric if (Flags & (1 << bitc::GEP_NUW))
1481ac9a064cSDimitry Andric NW |= GEPNoWrapFlags::noUnsignedWrap();
1482ac9a064cSDimitry Andric return NW;
1483ac9a064cSDimitry Andric }
1484ac9a064cSDimitry Andric
isConstExprSupported(const BitcodeConstant * BC)14857fa27ce4SDimitry Andric static bool isConstExprSupported(const BitcodeConstant *BC) {
14867fa27ce4SDimitry Andric uint8_t Opcode = BC->Opcode;
14877fa27ce4SDimitry Andric
1488145449b1SDimitry Andric // These are not real constant expressions, always consider them supported.
1489145449b1SDimitry Andric if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1490145449b1SDimitry Andric return true;
1491145449b1SDimitry Andric
1492e3b55780SDimitry Andric // If -expand-constant-exprs is set, we want to consider all expressions
1493e3b55780SDimitry Andric // as unsupported.
1494e3b55780SDimitry Andric if (ExpandConstantExprs)
1495e3b55780SDimitry Andric return false;
1496e3b55780SDimitry Andric
14971f917f69SDimitry Andric if (Instruction::isBinaryOp(Opcode))
14981f917f69SDimitry Andric return ConstantExpr::isSupportedBinOp(Opcode);
14991f917f69SDimitry Andric
1500b1c73532SDimitry Andric if (Instruction::isCast(Opcode))
1501b1c73532SDimitry Andric return ConstantExpr::isSupportedCastOp(Opcode);
1502b1c73532SDimitry Andric
15037fa27ce4SDimitry Andric if (Opcode == Instruction::GetElementPtr)
15047fa27ce4SDimitry Andric return ConstantExpr::isSupportedGetElementPtr(BC->SrcElemTy);
15057fa27ce4SDimitry Andric
15067fa27ce4SDimitry Andric switch (Opcode) {
15077fa27ce4SDimitry Andric case Instruction::FNeg:
15087fa27ce4SDimitry Andric case Instruction::Select:
1509ac9a064cSDimitry Andric case Instruction::ICmp:
1510ac9a064cSDimitry Andric case Instruction::FCmp:
15117fa27ce4SDimitry Andric return false;
15127fa27ce4SDimitry Andric default:
15137fa27ce4SDimitry Andric return true;
15147fa27ce4SDimitry Andric }
1515145449b1SDimitry Andric }
1516145449b1SDimitry Andric
materializeValue(unsigned StartValID,BasicBlock * InsertBB)1517145449b1SDimitry Andric Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID,
1518145449b1SDimitry Andric BasicBlock *InsertBB) {
1519145449b1SDimitry Andric // Quickly handle the case where there is no BitcodeConstant to resolve.
1520145449b1SDimitry Andric if (StartValID < ValueList.size() && ValueList[StartValID] &&
1521145449b1SDimitry Andric !isa<BitcodeConstant>(ValueList[StartValID]))
1522145449b1SDimitry Andric return ValueList[StartValID];
1523145449b1SDimitry Andric
1524145449b1SDimitry Andric SmallDenseMap<unsigned, Value *> MaterializedValues;
1525145449b1SDimitry Andric SmallVector<unsigned> Worklist;
1526145449b1SDimitry Andric Worklist.push_back(StartValID);
1527145449b1SDimitry Andric while (!Worklist.empty()) {
1528145449b1SDimitry Andric unsigned ValID = Worklist.back();
1529145449b1SDimitry Andric if (MaterializedValues.count(ValID)) {
1530145449b1SDimitry Andric // Duplicate expression that was already handled.
1531145449b1SDimitry Andric Worklist.pop_back();
1532145449b1SDimitry Andric continue;
1533145449b1SDimitry Andric }
1534145449b1SDimitry Andric
1535145449b1SDimitry Andric if (ValID >= ValueList.size() || !ValueList[ValID])
1536145449b1SDimitry Andric return error("Invalid value ID");
1537145449b1SDimitry Andric
1538145449b1SDimitry Andric Value *V = ValueList[ValID];
1539145449b1SDimitry Andric auto *BC = dyn_cast<BitcodeConstant>(V);
1540145449b1SDimitry Andric if (!BC) {
1541145449b1SDimitry Andric MaterializedValues.insert({ValID, V});
1542145449b1SDimitry Andric Worklist.pop_back();
1543145449b1SDimitry Andric continue;
1544145449b1SDimitry Andric }
1545145449b1SDimitry Andric
1546145449b1SDimitry Andric // Iterate in reverse, so values will get popped from the worklist in
1547145449b1SDimitry Andric // expected order.
1548145449b1SDimitry Andric SmallVector<Value *> Ops;
1549145449b1SDimitry Andric for (unsigned OpID : reverse(BC->getOperandIDs())) {
1550145449b1SDimitry Andric auto It = MaterializedValues.find(OpID);
1551145449b1SDimitry Andric if (It != MaterializedValues.end())
1552145449b1SDimitry Andric Ops.push_back(It->second);
1553145449b1SDimitry Andric else
1554145449b1SDimitry Andric Worklist.push_back(OpID);
1555145449b1SDimitry Andric }
1556145449b1SDimitry Andric
1557145449b1SDimitry Andric // Some expressions have not been resolved yet, handle them first and then
1558145449b1SDimitry Andric // revisit this one.
1559145449b1SDimitry Andric if (Ops.size() != BC->getOperandIDs().size())
1560145449b1SDimitry Andric continue;
1561145449b1SDimitry Andric std::reverse(Ops.begin(), Ops.end());
1562145449b1SDimitry Andric
1563145449b1SDimitry Andric SmallVector<Constant *> ConstOps;
1564145449b1SDimitry Andric for (Value *Op : Ops)
1565145449b1SDimitry Andric if (auto *C = dyn_cast<Constant>(Op))
1566145449b1SDimitry Andric ConstOps.push_back(C);
1567145449b1SDimitry Andric
1568145449b1SDimitry Andric // Materialize as constant expression if possible.
15697fa27ce4SDimitry Andric if (isConstExprSupported(BC) && ConstOps.size() == Ops.size()) {
1570145449b1SDimitry Andric Constant *C;
1571145449b1SDimitry Andric if (Instruction::isCast(BC->Opcode)) {
1572145449b1SDimitry Andric C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType());
1573145449b1SDimitry Andric if (!C)
1574145449b1SDimitry Andric C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType());
1575145449b1SDimitry Andric } else if (Instruction::isBinaryOp(BC->Opcode)) {
1576145449b1SDimitry Andric C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags);
1577145449b1SDimitry Andric } else {
1578145449b1SDimitry Andric switch (BC->Opcode) {
1579ac9a064cSDimitry Andric case BitcodeConstant::ConstantPtrAuthOpcode: {
1580ac9a064cSDimitry Andric auto *Key = dyn_cast<ConstantInt>(ConstOps[1]);
1581ac9a064cSDimitry Andric if (!Key)
1582ac9a064cSDimitry Andric return error("ptrauth key operand must be ConstantInt");
1583ac9a064cSDimitry Andric
1584ac9a064cSDimitry Andric auto *Disc = dyn_cast<ConstantInt>(ConstOps[2]);
1585ac9a064cSDimitry Andric if (!Disc)
1586ac9a064cSDimitry Andric return error("ptrauth disc operand must be ConstantInt");
1587ac9a064cSDimitry Andric
1588ac9a064cSDimitry Andric C = ConstantPtrAuth::get(ConstOps[0], Key, Disc, ConstOps[3]);
1589ac9a064cSDimitry Andric break;
1590ac9a064cSDimitry Andric }
1591145449b1SDimitry Andric case BitcodeConstant::NoCFIOpcode: {
1592145449b1SDimitry Andric auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1593145449b1SDimitry Andric if (!GV)
1594145449b1SDimitry Andric return error("no_cfi operand must be GlobalValue");
1595145449b1SDimitry Andric C = NoCFIValue::get(GV);
1596145449b1SDimitry Andric break;
1597145449b1SDimitry Andric }
1598145449b1SDimitry Andric case BitcodeConstant::DSOLocalEquivalentOpcode: {
1599145449b1SDimitry Andric auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1600145449b1SDimitry Andric if (!GV)
1601145449b1SDimitry Andric return error("dso_local operand must be GlobalValue");
1602145449b1SDimitry Andric C = DSOLocalEquivalent::get(GV);
1603145449b1SDimitry Andric break;
1604145449b1SDimitry Andric }
1605145449b1SDimitry Andric case BitcodeConstant::BlockAddressOpcode: {
1606145449b1SDimitry Andric Function *Fn = dyn_cast<Function>(ConstOps[0]);
1607145449b1SDimitry Andric if (!Fn)
1608145449b1SDimitry Andric return error("blockaddress operand must be a function");
1609145449b1SDimitry Andric
1610145449b1SDimitry Andric // If the function is already parsed we can insert the block address
1611145449b1SDimitry Andric // right away.
1612145449b1SDimitry Andric BasicBlock *BB;
1613ac9a064cSDimitry Andric unsigned BBID = BC->BlockAddressBB;
1614145449b1SDimitry Andric if (!BBID)
1615145449b1SDimitry Andric // Invalid reference to entry block.
1616145449b1SDimitry Andric return error("Invalid ID");
1617145449b1SDimitry Andric if (!Fn->empty()) {
1618145449b1SDimitry Andric Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1619145449b1SDimitry Andric for (size_t I = 0, E = BBID; I != E; ++I) {
1620145449b1SDimitry Andric if (BBI == BBE)
1621145449b1SDimitry Andric return error("Invalid ID");
1622145449b1SDimitry Andric ++BBI;
1623145449b1SDimitry Andric }
1624145449b1SDimitry Andric BB = &*BBI;
1625145449b1SDimitry Andric } else {
1626145449b1SDimitry Andric // Otherwise insert a placeholder and remember it so it can be
1627145449b1SDimitry Andric // inserted when the function is parsed.
1628145449b1SDimitry Andric auto &FwdBBs = BasicBlockFwdRefs[Fn];
1629145449b1SDimitry Andric if (FwdBBs.empty())
1630145449b1SDimitry Andric BasicBlockFwdRefQueue.push_back(Fn);
1631145449b1SDimitry Andric if (FwdBBs.size() < BBID + 1)
1632145449b1SDimitry Andric FwdBBs.resize(BBID + 1);
1633145449b1SDimitry Andric if (!FwdBBs[BBID])
1634145449b1SDimitry Andric FwdBBs[BBID] = BasicBlock::Create(Context);
1635145449b1SDimitry Andric BB = FwdBBs[BBID];
1636145449b1SDimitry Andric }
1637145449b1SDimitry Andric C = BlockAddress::get(Fn, BB);
1638145449b1SDimitry Andric break;
1639145449b1SDimitry Andric }
1640145449b1SDimitry Andric case BitcodeConstant::ConstantStructOpcode:
1641145449b1SDimitry Andric C = ConstantStruct::get(cast<StructType>(BC->getType()), ConstOps);
1642145449b1SDimitry Andric break;
1643145449b1SDimitry Andric case BitcodeConstant::ConstantArrayOpcode:
1644145449b1SDimitry Andric C = ConstantArray::get(cast<ArrayType>(BC->getType()), ConstOps);
1645145449b1SDimitry Andric break;
1646145449b1SDimitry Andric case BitcodeConstant::ConstantVectorOpcode:
1647145449b1SDimitry Andric C = ConstantVector::get(ConstOps);
1648145449b1SDimitry Andric break;
1649145449b1SDimitry Andric case Instruction::GetElementPtr:
1650ac9a064cSDimitry Andric C = ConstantExpr::getGetElementPtr(
1651ac9a064cSDimitry Andric BC->SrcElemTy, ConstOps[0], ArrayRef(ConstOps).drop_front(),
1652ac9a064cSDimitry Andric toGEPNoWrapFlags(BC->Flags), BC->getInRange());
1653145449b1SDimitry Andric break;
1654145449b1SDimitry Andric case Instruction::ExtractElement:
1655145449b1SDimitry Andric C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]);
1656145449b1SDimitry Andric break;
1657145449b1SDimitry Andric case Instruction::InsertElement:
1658145449b1SDimitry Andric C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1],
1659145449b1SDimitry Andric ConstOps[2]);
1660145449b1SDimitry Andric break;
1661145449b1SDimitry Andric case Instruction::ShuffleVector: {
1662145449b1SDimitry Andric SmallVector<int, 16> Mask;
1663145449b1SDimitry Andric ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask);
1664145449b1SDimitry Andric C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask);
1665145449b1SDimitry Andric break;
1666145449b1SDimitry Andric }
1667145449b1SDimitry Andric default:
1668145449b1SDimitry Andric llvm_unreachable("Unhandled bitcode constant");
1669145449b1SDimitry Andric }
1670145449b1SDimitry Andric }
1671145449b1SDimitry Andric
1672145449b1SDimitry Andric // Cache resolved constant.
1673145449b1SDimitry Andric ValueList.replaceValueWithoutRAUW(ValID, C);
1674145449b1SDimitry Andric MaterializedValues.insert({ValID, C});
1675145449b1SDimitry Andric Worklist.pop_back();
1676145449b1SDimitry Andric continue;
1677145449b1SDimitry Andric }
1678145449b1SDimitry Andric
1679145449b1SDimitry Andric if (!InsertBB)
1680145449b1SDimitry Andric return error(Twine("Value referenced by initializer is an unsupported "
1681145449b1SDimitry Andric "constant expression of type ") +
1682145449b1SDimitry Andric BC->getOpcodeName());
1683145449b1SDimitry Andric
1684145449b1SDimitry Andric // Materialize as instructions if necessary.
1685145449b1SDimitry Andric Instruction *I;
1686145449b1SDimitry Andric if (Instruction::isCast(BC->Opcode)) {
1687145449b1SDimitry Andric I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0],
1688145449b1SDimitry Andric BC->getType(), "constexpr", InsertBB);
1689145449b1SDimitry Andric } else if (Instruction::isUnaryOp(BC->Opcode)) {
1690145449b1SDimitry Andric I = UnaryOperator::Create((Instruction::UnaryOps)BC->Opcode, Ops[0],
1691145449b1SDimitry Andric "constexpr", InsertBB);
1692145449b1SDimitry Andric } else if (Instruction::isBinaryOp(BC->Opcode)) {
1693145449b1SDimitry Andric I = BinaryOperator::Create((Instruction::BinaryOps)BC->Opcode, Ops[0],
1694145449b1SDimitry Andric Ops[1], "constexpr", InsertBB);
1695145449b1SDimitry Andric if (isa<OverflowingBinaryOperator>(I)) {
1696145449b1SDimitry Andric if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap)
1697145449b1SDimitry Andric I->setHasNoSignedWrap();
1698145449b1SDimitry Andric if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap)
1699145449b1SDimitry Andric I->setHasNoUnsignedWrap();
1700145449b1SDimitry Andric }
1701145449b1SDimitry Andric if (isa<PossiblyExactOperator>(I) &&
1702145449b1SDimitry Andric (BC->Flags & PossiblyExactOperator::IsExact))
1703145449b1SDimitry Andric I->setIsExact();
1704145449b1SDimitry Andric } else {
1705145449b1SDimitry Andric switch (BC->Opcode) {
1706145449b1SDimitry Andric case BitcodeConstant::ConstantVectorOpcode: {
1707145449b1SDimitry Andric Type *IdxTy = Type::getInt32Ty(BC->getContext());
1708145449b1SDimitry Andric Value *V = PoisonValue::get(BC->getType());
1709145449b1SDimitry Andric for (auto Pair : enumerate(Ops)) {
1710145449b1SDimitry Andric Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1711145449b1SDimitry Andric V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins",
1712145449b1SDimitry Andric InsertBB);
1713145449b1SDimitry Andric }
1714145449b1SDimitry Andric I = cast<Instruction>(V);
1715145449b1SDimitry Andric break;
1716145449b1SDimitry Andric }
1717e3b55780SDimitry Andric case BitcodeConstant::ConstantStructOpcode:
1718e3b55780SDimitry Andric case BitcodeConstant::ConstantArrayOpcode: {
1719e3b55780SDimitry Andric Value *V = PoisonValue::get(BC->getType());
1720e3b55780SDimitry Andric for (auto Pair : enumerate(Ops))
1721e3b55780SDimitry Andric V = InsertValueInst::Create(V, Pair.value(), Pair.index(),
1722e3b55780SDimitry Andric "constexpr.ins", InsertBB);
1723e3b55780SDimitry Andric I = cast<Instruction>(V);
1724e3b55780SDimitry Andric break;
1725e3b55780SDimitry Andric }
1726145449b1SDimitry Andric case Instruction::ICmp:
1727145449b1SDimitry Andric case Instruction::FCmp:
1728145449b1SDimitry Andric I = CmpInst::Create((Instruction::OtherOps)BC->Opcode,
1729145449b1SDimitry Andric (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1],
1730145449b1SDimitry Andric "constexpr", InsertBB);
1731145449b1SDimitry Andric break;
1732145449b1SDimitry Andric case Instruction::GetElementPtr:
1733145449b1SDimitry Andric I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0],
1734e3b55780SDimitry Andric ArrayRef(Ops).drop_front(), "constexpr",
1735e3b55780SDimitry Andric InsertBB);
1736ac9a064cSDimitry Andric cast<GetElementPtrInst>(I)->setNoWrapFlags(toGEPNoWrapFlags(BC->Flags));
1737145449b1SDimitry Andric break;
1738145449b1SDimitry Andric case Instruction::Select:
1739145449b1SDimitry Andric I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB);
1740145449b1SDimitry Andric break;
1741145449b1SDimitry Andric case Instruction::ExtractElement:
1742145449b1SDimitry Andric I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB);
1743145449b1SDimitry Andric break;
1744145449b1SDimitry Andric case Instruction::InsertElement:
1745145449b1SDimitry Andric I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr",
1746145449b1SDimitry Andric InsertBB);
1747145449b1SDimitry Andric break;
1748145449b1SDimitry Andric case Instruction::ShuffleVector:
1749145449b1SDimitry Andric I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr",
1750145449b1SDimitry Andric InsertBB);
1751145449b1SDimitry Andric break;
1752145449b1SDimitry Andric default:
1753145449b1SDimitry Andric llvm_unreachable("Unhandled bitcode constant");
1754145449b1SDimitry Andric }
1755145449b1SDimitry Andric }
1756145449b1SDimitry Andric
1757145449b1SDimitry Andric MaterializedValues.insert({ValID, I});
1758145449b1SDimitry Andric Worklist.pop_back();
1759145449b1SDimitry Andric }
1760145449b1SDimitry Andric
1761145449b1SDimitry Andric return MaterializedValues[StartValID];
1762145449b1SDimitry Andric }
1763145449b1SDimitry Andric
getValueForInitializer(unsigned ID)1764145449b1SDimitry Andric Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) {
1765145449b1SDimitry Andric Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr);
1766145449b1SDimitry Andric if (!MaybeV)
1767145449b1SDimitry Andric return MaybeV.takeError();
1768145449b1SDimitry Andric
1769145449b1SDimitry Andric // Result must be Constant if InsertBB is nullptr.
1770145449b1SDimitry Andric return cast<Constant>(MaybeV.get());
1771145449b1SDimitry Andric }
1772145449b1SDimitry Andric
createIdentifiedStructType(LLVMContext & Context,StringRef Name)177367c32a98SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
177467c32a98SDimitry Andric StringRef Name) {
177567c32a98SDimitry Andric auto *Ret = StructType::create(Context, Name);
177667c32a98SDimitry Andric IdentifiedStructTypes.push_back(Ret);
177767c32a98SDimitry Andric return Ret;
177867c32a98SDimitry Andric }
177967c32a98SDimitry Andric
createIdentifiedStructType(LLVMContext & Context)178067c32a98SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
178167c32a98SDimitry Andric auto *Ret = StructType::create(Context);
178267c32a98SDimitry Andric IdentifiedStructTypes.push_back(Ret);
178367c32a98SDimitry Andric return Ret;
1784009b1c42SEd Schouten }
1785009b1c42SEd Schouten
1786009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1787009b1c42SEd Schouten // Functions for parsing blocks from the bitcode file
1788009b1c42SEd Schouten //===----------------------------------------------------------------------===//
1789009b1c42SEd Schouten
getRawAttributeMask(Attribute::AttrKind Val)1790b915e9e0SDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1791b915e9e0SDimitry Andric switch (Val) {
1792b915e9e0SDimitry Andric case Attribute::EndAttrKinds:
1793cfca06d7SDimitry Andric case Attribute::EmptyKey:
1794cfca06d7SDimitry Andric case Attribute::TombstoneKey:
1795b915e9e0SDimitry Andric llvm_unreachable("Synthetic enumerators which should never get here");
1796b915e9e0SDimitry Andric
1797b915e9e0SDimitry Andric case Attribute::None: return 0;
1798b915e9e0SDimitry Andric case Attribute::ZExt: return 1 << 0;
1799b915e9e0SDimitry Andric case Attribute::SExt: return 1 << 1;
1800b915e9e0SDimitry Andric case Attribute::NoReturn: return 1 << 2;
1801b915e9e0SDimitry Andric case Attribute::InReg: return 1 << 3;
1802b915e9e0SDimitry Andric case Attribute::StructRet: return 1 << 4;
1803b915e9e0SDimitry Andric case Attribute::NoUnwind: return 1 << 5;
1804b915e9e0SDimitry Andric case Attribute::NoAlias: return 1 << 6;
1805b915e9e0SDimitry Andric case Attribute::ByVal: return 1 << 7;
1806b915e9e0SDimitry Andric case Attribute::Nest: return 1 << 8;
1807b915e9e0SDimitry Andric case Attribute::ReadNone: return 1 << 9;
1808b915e9e0SDimitry Andric case Attribute::ReadOnly: return 1 << 10;
1809b915e9e0SDimitry Andric case Attribute::NoInline: return 1 << 11;
1810b915e9e0SDimitry Andric case Attribute::AlwaysInline: return 1 << 12;
1811b915e9e0SDimitry Andric case Attribute::OptimizeForSize: return 1 << 13;
1812b915e9e0SDimitry Andric case Attribute::StackProtect: return 1 << 14;
1813b915e9e0SDimitry Andric case Attribute::StackProtectReq: return 1 << 15;
1814b915e9e0SDimitry Andric case Attribute::Alignment: return 31 << 16;
1815b915e9e0SDimitry Andric case Attribute::NoCapture: return 1 << 21;
1816b915e9e0SDimitry Andric case Attribute::NoRedZone: return 1 << 22;
1817b915e9e0SDimitry Andric case Attribute::NoImplicitFloat: return 1 << 23;
1818b915e9e0SDimitry Andric case Attribute::Naked: return 1 << 24;
1819b915e9e0SDimitry Andric case Attribute::InlineHint: return 1 << 25;
1820b915e9e0SDimitry Andric case Attribute::StackAlignment: return 7 << 26;
1821b915e9e0SDimitry Andric case Attribute::ReturnsTwice: return 1 << 29;
1822b915e9e0SDimitry Andric case Attribute::UWTable: return 1 << 30;
1823b915e9e0SDimitry Andric case Attribute::NonLazyBind: return 1U << 31;
1824b915e9e0SDimitry Andric case Attribute::SanitizeAddress: return 1ULL << 32;
1825b915e9e0SDimitry Andric case Attribute::MinSize: return 1ULL << 33;
1826b915e9e0SDimitry Andric case Attribute::NoDuplicate: return 1ULL << 34;
1827b915e9e0SDimitry Andric case Attribute::StackProtectStrong: return 1ULL << 35;
1828b915e9e0SDimitry Andric case Attribute::SanitizeThread: return 1ULL << 36;
1829b915e9e0SDimitry Andric case Attribute::SanitizeMemory: return 1ULL << 37;
1830b915e9e0SDimitry Andric case Attribute::NoBuiltin: return 1ULL << 38;
1831b915e9e0SDimitry Andric case Attribute::Returned: return 1ULL << 39;
1832b915e9e0SDimitry Andric case Attribute::Cold: return 1ULL << 40;
1833b915e9e0SDimitry Andric case Attribute::Builtin: return 1ULL << 41;
1834b915e9e0SDimitry Andric case Attribute::OptimizeNone: return 1ULL << 42;
1835b915e9e0SDimitry Andric case Attribute::InAlloca: return 1ULL << 43;
1836b915e9e0SDimitry Andric case Attribute::NonNull: return 1ULL << 44;
1837b915e9e0SDimitry Andric case Attribute::JumpTable: return 1ULL << 45;
1838b915e9e0SDimitry Andric case Attribute::Convergent: return 1ULL << 46;
1839b915e9e0SDimitry Andric case Attribute::SafeStack: return 1ULL << 47;
1840b915e9e0SDimitry Andric case Attribute::NoRecurse: return 1ULL << 48;
1841e3b55780SDimitry Andric // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately.
1842e3b55780SDimitry Andric // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately.
1843b915e9e0SDimitry Andric case Attribute::SwiftSelf: return 1ULL << 51;
1844b915e9e0SDimitry Andric case Attribute::SwiftError: return 1ULL << 52;
1845b915e9e0SDimitry Andric case Attribute::WriteOnly: return 1ULL << 53;
1846a303c417SDimitry Andric case Attribute::Speculatable: return 1ULL << 54;
1847044eb2f6SDimitry Andric case Attribute::StrictFP: return 1ULL << 55;
1848044eb2f6SDimitry Andric case Attribute::SanitizeHWAddress: return 1ULL << 56;
1849eb11fae6SDimitry Andric case Attribute::NoCfCheck: return 1ULL << 57;
1850eb11fae6SDimitry Andric case Attribute::OptForFuzzing: return 1ULL << 58;
1851eb11fae6SDimitry Andric case Attribute::ShadowCallStack: return 1ULL << 59;
1852d8e91e46SDimitry Andric case Attribute::SpeculativeLoadHardening:
1853d8e91e46SDimitry Andric return 1ULL << 60;
1854e6d15924SDimitry Andric case Attribute::ImmArg:
1855e6d15924SDimitry Andric return 1ULL << 61;
1856e6d15924SDimitry Andric case Attribute::WillReturn:
1857e6d15924SDimitry Andric return 1ULL << 62;
1858e6d15924SDimitry Andric case Attribute::NoFree:
1859e6d15924SDimitry Andric return 1ULL << 63;
1860cfca06d7SDimitry Andric default:
1861cfca06d7SDimitry Andric // Other attributes are not supported in the raw format,
1862cfca06d7SDimitry Andric // as we ran out of space.
1863cfca06d7SDimitry Andric return 0;
1864b915e9e0SDimitry Andric }
1865b915e9e0SDimitry Andric llvm_unreachable("Unsupported attribute type");
1866b915e9e0SDimitry Andric }
1867b915e9e0SDimitry Andric
addRawAttributeValue(AttrBuilder & B,uint64_t Val)1868b915e9e0SDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1869b915e9e0SDimitry Andric if (!Val) return;
1870b915e9e0SDimitry Andric
1871b915e9e0SDimitry Andric for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1872b915e9e0SDimitry Andric I = Attribute::AttrKind(I + 1)) {
1873b915e9e0SDimitry Andric if (uint64_t A = (Val & getRawAttributeMask(I))) {
1874b915e9e0SDimitry Andric if (I == Attribute::Alignment)
1875b915e9e0SDimitry Andric B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1876b915e9e0SDimitry Andric else if (I == Attribute::StackAlignment)
1877b915e9e0SDimitry Andric B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1878344a3780SDimitry Andric else if (Attribute::isTypeAttrKind(I))
1879344a3780SDimitry Andric B.addTypeAttr(I, nullptr); // Type will be auto-upgraded.
1880b915e9e0SDimitry Andric else
1881b915e9e0SDimitry Andric B.addAttribute(I);
1882b915e9e0SDimitry Andric }
1883b915e9e0SDimitry Andric }
1884b915e9e0SDimitry Andric }
18854a16efa3SDimitry Andric
1886eb11fae6SDimitry Andric /// This fills an AttrBuilder object with the LLVM attributes that have
18874a16efa3SDimitry Andric /// been decoded from the given integer. This function must stay in sync with
18884a16efa3SDimitry Andric /// 'encodeLLVMAttributesForBitcode'.
decodeLLVMAttributesForBitcode(AttrBuilder & B,uint64_t EncodedAttrs,uint64_t AttrIdx)18894a16efa3SDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1890e3b55780SDimitry Andric uint64_t EncodedAttrs,
1891e3b55780SDimitry Andric uint64_t AttrIdx) {
18924a16efa3SDimitry Andric // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
18934a16efa3SDimitry Andric // the bits above 31 down by 11 bits.
18944a16efa3SDimitry Andric unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
18954a16efa3SDimitry Andric assert((!Alignment || isPowerOf2_32(Alignment)) &&
18964a16efa3SDimitry Andric "Alignment must be a power of two.");
18974a16efa3SDimitry Andric
18984a16efa3SDimitry Andric if (Alignment)
18994a16efa3SDimitry Andric B.addAlignmentAttr(Alignment);
1900e3b55780SDimitry Andric
1901e3b55780SDimitry Andric uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1902e3b55780SDimitry Andric (EncodedAttrs & 0xffff);
1903e3b55780SDimitry Andric
1904e3b55780SDimitry Andric if (AttrIdx == AttributeList::FunctionIndex) {
1905e3b55780SDimitry Andric // Upgrade old memory attributes.
1906e3b55780SDimitry Andric MemoryEffects ME = MemoryEffects::unknown();
1907e3b55780SDimitry Andric if (Attrs & (1ULL << 9)) {
1908e3b55780SDimitry Andric // ReadNone
1909e3b55780SDimitry Andric Attrs &= ~(1ULL << 9);
1910e3b55780SDimitry Andric ME &= MemoryEffects::none();
1911e3b55780SDimitry Andric }
1912e3b55780SDimitry Andric if (Attrs & (1ULL << 10)) {
1913e3b55780SDimitry Andric // ReadOnly
1914e3b55780SDimitry Andric Attrs &= ~(1ULL << 10);
1915e3b55780SDimitry Andric ME &= MemoryEffects::readOnly();
1916e3b55780SDimitry Andric }
1917e3b55780SDimitry Andric if (Attrs & (1ULL << 49)) {
1918e3b55780SDimitry Andric // InaccessibleMemOnly
1919e3b55780SDimitry Andric Attrs &= ~(1ULL << 49);
1920e3b55780SDimitry Andric ME &= MemoryEffects::inaccessibleMemOnly();
1921e3b55780SDimitry Andric }
1922e3b55780SDimitry Andric if (Attrs & (1ULL << 50)) {
1923e3b55780SDimitry Andric // InaccessibleMemOrArgMemOnly
1924e3b55780SDimitry Andric Attrs &= ~(1ULL << 50);
1925e3b55780SDimitry Andric ME &= MemoryEffects::inaccessibleOrArgMemOnly();
1926e3b55780SDimitry Andric }
1927e3b55780SDimitry Andric if (Attrs & (1ULL << 53)) {
1928e3b55780SDimitry Andric // WriteOnly
1929e3b55780SDimitry Andric Attrs &= ~(1ULL << 53);
1930e3b55780SDimitry Andric ME &= MemoryEffects::writeOnly();
1931e3b55780SDimitry Andric }
1932e3b55780SDimitry Andric if (ME != MemoryEffects::unknown())
1933e3b55780SDimitry Andric B.addMemoryAttr(ME);
1934e3b55780SDimitry Andric }
1935e3b55780SDimitry Andric
1936e3b55780SDimitry Andric addRawAttributeValue(B, Attrs);
19374a16efa3SDimitry Andric }
19384a16efa3SDimitry Andric
parseAttributeBlock()1939b915e9e0SDimitry Andric Error BitcodeReader::parseAttributeBlock() {
1940e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1941e6d15924SDimitry Andric return Err;
1942009b1c42SEd Schouten
1943009b1c42SEd Schouten if (!MAttributes.empty())
19443a0822f0SDimitry Andric return error("Invalid multiple blocks");
1945009b1c42SEd Schouten
1946009b1c42SEd Schouten SmallVector<uint64_t, 64> Record;
1947009b1c42SEd Schouten
194871d5a254SDimitry Andric SmallVector<AttributeList, 8> Attrs;
1949009b1c42SEd Schouten
1950009b1c42SEd Schouten // Read all the records.
1951b915e9e0SDimitry Andric while (true) {
1952e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1953e6d15924SDimitry Andric if (!MaybeEntry)
1954e6d15924SDimitry Andric return MaybeEntry.takeError();
1955e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
19564a16efa3SDimitry Andric
19574a16efa3SDimitry Andric switch (Entry.Kind) {
19584a16efa3SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
19594a16efa3SDimitry Andric case BitstreamEntry::Error:
19603a0822f0SDimitry Andric return error("Malformed block");
19614a16efa3SDimitry Andric case BitstreamEntry::EndBlock:
1962b915e9e0SDimitry Andric return Error::success();
19634a16efa3SDimitry Andric case BitstreamEntry::Record:
19644a16efa3SDimitry Andric // The interesting case.
19654a16efa3SDimitry Andric break;
1966009b1c42SEd Schouten }
1967009b1c42SEd Schouten
1968009b1c42SEd Schouten // Read a record.
1969009b1c42SEd Schouten Record.clear();
1970e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1971e6d15924SDimitry Andric if (!MaybeRecord)
1972e6d15924SDimitry Andric return MaybeRecord.takeError();
1973e6d15924SDimitry Andric switch (MaybeRecord.get()) {
1974009b1c42SEd Schouten default: // Default behavior: ignore.
1975009b1c42SEd Schouten break;
1976044eb2f6SDimitry Andric case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1977cfca06d7SDimitry Andric // Deprecated, but still needed to read old bitcode files.
1978009b1c42SEd Schouten if (Record.size() & 1)
1979145449b1SDimitry Andric return error("Invalid parameter attribute record");
1980009b1c42SEd Schouten
1981009b1c42SEd Schouten for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
19826f8fc217SDimitry Andric AttrBuilder B(Context);
1983e3b55780SDimitry Andric decodeLLVMAttributesForBitcode(B, Record[i+1], Record[i]);
198471d5a254SDimitry Andric Attrs.push_back(AttributeList::get(Context, Record[i], B));
1985009b1c42SEd Schouten }
1986009b1c42SEd Schouten
198771d5a254SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs));
1988009b1c42SEd Schouten Attrs.clear();
1989009b1c42SEd Schouten break;
1990044eb2f6SDimitry Andric case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1991ac9a064cSDimitry Andric for (uint64_t Val : Record)
1992ac9a064cSDimitry Andric Attrs.push_back(MAttributeGroups[Val]);
19934a16efa3SDimitry Andric
199471d5a254SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs));
19954a16efa3SDimitry Andric Attrs.clear();
19964a16efa3SDimitry Andric break;
19974a16efa3SDimitry Andric }
19984a16efa3SDimitry Andric }
19994a16efa3SDimitry Andric }
20004a16efa3SDimitry Andric
2001f8af5cf6SDimitry Andric // Returns Attribute::None on unrecognized codes.
getAttrFromCode(uint64_t Code)20023a0822f0SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
2003f8af5cf6SDimitry Andric switch (Code) {
2004f8af5cf6SDimitry Andric default:
2005f8af5cf6SDimitry Andric return Attribute::None;
2006f8af5cf6SDimitry Andric case bitc::ATTR_KIND_ALIGNMENT:
2007f8af5cf6SDimitry Andric return Attribute::Alignment;
2008f8af5cf6SDimitry Andric case bitc::ATTR_KIND_ALWAYS_INLINE:
2009f8af5cf6SDimitry Andric return Attribute::AlwaysInline;
2010f8af5cf6SDimitry Andric case bitc::ATTR_KIND_BUILTIN:
2011f8af5cf6SDimitry Andric return Attribute::Builtin;
2012f8af5cf6SDimitry Andric case bitc::ATTR_KIND_BY_VAL:
2013f8af5cf6SDimitry Andric return Attribute::ByVal;
20145ca98fd9SDimitry Andric case bitc::ATTR_KIND_IN_ALLOCA:
20155ca98fd9SDimitry Andric return Attribute::InAlloca;
2016f8af5cf6SDimitry Andric case bitc::ATTR_KIND_COLD:
2017f8af5cf6SDimitry Andric return Attribute::Cold;
20185a5ac124SDimitry Andric case bitc::ATTR_KIND_CONVERGENT:
20195a5ac124SDimitry Andric return Attribute::Convergent;
2020c0981da4SDimitry Andric case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION:
2021c0981da4SDimitry Andric return Attribute::DisableSanitizerInstrumentation;
2022344a3780SDimitry Andric case bitc::ATTR_KIND_ELEMENTTYPE:
2023344a3780SDimitry Andric return Attribute::ElementType;
20241f917f69SDimitry Andric case bitc::ATTR_KIND_FNRETTHUNK_EXTERN:
20251f917f69SDimitry Andric return Attribute::FnRetThunkExtern;
2026f8af5cf6SDimitry Andric case bitc::ATTR_KIND_INLINE_HINT:
2027f8af5cf6SDimitry Andric return Attribute::InlineHint;
2028f8af5cf6SDimitry Andric case bitc::ATTR_KIND_IN_REG:
2029f8af5cf6SDimitry Andric return Attribute::InReg;
20305ca98fd9SDimitry Andric case bitc::ATTR_KIND_JUMP_TABLE:
20315ca98fd9SDimitry Andric return Attribute::JumpTable;
2032e3b55780SDimitry Andric case bitc::ATTR_KIND_MEMORY:
2033e3b55780SDimitry Andric return Attribute::Memory;
20347fa27ce4SDimitry Andric case bitc::ATTR_KIND_NOFPCLASS:
20357fa27ce4SDimitry Andric return Attribute::NoFPClass;
2036f8af5cf6SDimitry Andric case bitc::ATTR_KIND_MIN_SIZE:
2037f8af5cf6SDimitry Andric return Attribute::MinSize;
2038f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NAKED:
2039f8af5cf6SDimitry Andric return Attribute::Naked;
2040f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NEST:
2041f8af5cf6SDimitry Andric return Attribute::Nest;
2042f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NO_ALIAS:
2043f8af5cf6SDimitry Andric return Attribute::NoAlias;
2044f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NO_BUILTIN:
2045f8af5cf6SDimitry Andric return Attribute::NoBuiltin;
2046b60736ecSDimitry Andric case bitc::ATTR_KIND_NO_CALLBACK:
2047b60736ecSDimitry Andric return Attribute::NoCallback;
2048f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NO_CAPTURE:
2049f8af5cf6SDimitry Andric return Attribute::NoCapture;
2050f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NO_DUPLICATE:
2051f8af5cf6SDimitry Andric return Attribute::NoDuplicate;
2052e6d15924SDimitry Andric case bitc::ATTR_KIND_NOFREE:
2053e6d15924SDimitry Andric return Attribute::NoFree;
2054f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
2055f8af5cf6SDimitry Andric return Attribute::NoImplicitFloat;
2056f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NO_INLINE:
2057f8af5cf6SDimitry Andric return Attribute::NoInline;
2058dd58ef01SDimitry Andric case bitc::ATTR_KIND_NO_RECURSE:
2059dd58ef01SDimitry Andric return Attribute::NoRecurse;
2060cfca06d7SDimitry Andric case bitc::ATTR_KIND_NO_MERGE:
2061cfca06d7SDimitry Andric return Attribute::NoMerge;
2062f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NON_LAZY_BIND:
2063f8af5cf6SDimitry Andric return Attribute::NonLazyBind;
20645ca98fd9SDimitry Andric case bitc::ATTR_KIND_NON_NULL:
20655ca98fd9SDimitry Andric return Attribute::NonNull;
20665ca98fd9SDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE:
20675ca98fd9SDimitry Andric return Attribute::Dereferenceable;
20685a5ac124SDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
20695a5ac124SDimitry Andric return Attribute::DereferenceableOrNull;
2070145449b1SDimitry Andric case bitc::ATTR_KIND_ALLOC_ALIGN:
2071145449b1SDimitry Andric return Attribute::AllocAlign;
2072145449b1SDimitry Andric case bitc::ATTR_KIND_ALLOC_KIND:
2073145449b1SDimitry Andric return Attribute::AllocKind;
207401095a5dSDimitry Andric case bitc::ATTR_KIND_ALLOC_SIZE:
207501095a5dSDimitry Andric return Attribute::AllocSize;
2076145449b1SDimitry Andric case bitc::ATTR_KIND_ALLOCATED_POINTER:
2077145449b1SDimitry Andric return Attribute::AllocatedPointer;
2078f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NO_RED_ZONE:
2079f8af5cf6SDimitry Andric return Attribute::NoRedZone;
2080f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NO_RETURN:
2081f8af5cf6SDimitry Andric return Attribute::NoReturn;
2082e6d15924SDimitry Andric case bitc::ATTR_KIND_NOSYNC:
2083e6d15924SDimitry Andric return Attribute::NoSync;
2084eb11fae6SDimitry Andric case bitc::ATTR_KIND_NOCF_CHECK:
2085eb11fae6SDimitry Andric return Attribute::NoCfCheck;
2086344a3780SDimitry Andric case bitc::ATTR_KIND_NO_PROFILE:
2087344a3780SDimitry Andric return Attribute::NoProfile;
2088e3b55780SDimitry Andric case bitc::ATTR_KIND_SKIP_PROFILE:
2089e3b55780SDimitry Andric return Attribute::SkipProfile;
2090f8af5cf6SDimitry Andric case bitc::ATTR_KIND_NO_UNWIND:
2091f8af5cf6SDimitry Andric return Attribute::NoUnwind;
2092145449b1SDimitry Andric case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS:
2093145449b1SDimitry Andric return Attribute::NoSanitizeBounds;
2094344a3780SDimitry Andric case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
2095344a3780SDimitry Andric return Attribute::NoSanitizeCoverage;
2096cfca06d7SDimitry Andric case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
2097cfca06d7SDimitry Andric return Attribute::NullPointerIsValid;
2098b1c73532SDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING:
2099b1c73532SDimitry Andric return Attribute::OptimizeForDebugging;
2100eb11fae6SDimitry Andric case bitc::ATTR_KIND_OPT_FOR_FUZZING:
2101eb11fae6SDimitry Andric return Attribute::OptForFuzzing;
2102f8af5cf6SDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
2103f8af5cf6SDimitry Andric return Attribute::OptimizeForSize;
2104f8af5cf6SDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_NONE:
2105f8af5cf6SDimitry Andric return Attribute::OptimizeNone;
2106f8af5cf6SDimitry Andric case bitc::ATTR_KIND_READ_NONE:
2107f8af5cf6SDimitry Andric return Attribute::ReadNone;
2108f8af5cf6SDimitry Andric case bitc::ATTR_KIND_READ_ONLY:
2109f8af5cf6SDimitry Andric return Attribute::ReadOnly;
2110f8af5cf6SDimitry Andric case bitc::ATTR_KIND_RETURNED:
2111f8af5cf6SDimitry Andric return Attribute::Returned;
2112f8af5cf6SDimitry Andric case bitc::ATTR_KIND_RETURNS_TWICE:
2113f8af5cf6SDimitry Andric return Attribute::ReturnsTwice;
2114f8af5cf6SDimitry Andric case bitc::ATTR_KIND_S_EXT:
2115f8af5cf6SDimitry Andric return Attribute::SExt;
2116a303c417SDimitry Andric case bitc::ATTR_KIND_SPECULATABLE:
2117a303c417SDimitry Andric return Attribute::Speculatable;
2118f8af5cf6SDimitry Andric case bitc::ATTR_KIND_STACK_ALIGNMENT:
2119f8af5cf6SDimitry Andric return Attribute::StackAlignment;
2120f8af5cf6SDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT:
2121f8af5cf6SDimitry Andric return Attribute::StackProtect;
2122f8af5cf6SDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_REQ:
2123f8af5cf6SDimitry Andric return Attribute::StackProtectReq;
2124f8af5cf6SDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
2125f8af5cf6SDimitry Andric return Attribute::StackProtectStrong;
21263a0822f0SDimitry Andric case bitc::ATTR_KIND_SAFESTACK:
21273a0822f0SDimitry Andric return Attribute::SafeStack;
2128eb11fae6SDimitry Andric case bitc::ATTR_KIND_SHADOWCALLSTACK:
2129eb11fae6SDimitry Andric return Attribute::ShadowCallStack;
2130044eb2f6SDimitry Andric case bitc::ATTR_KIND_STRICT_FP:
2131044eb2f6SDimitry Andric return Attribute::StrictFP;
2132f8af5cf6SDimitry Andric case bitc::ATTR_KIND_STRUCT_RET:
2133f8af5cf6SDimitry Andric return Attribute::StructRet;
2134f8af5cf6SDimitry Andric case bitc::ATTR_KIND_SANITIZE_ADDRESS:
2135f8af5cf6SDimitry Andric return Attribute::SanitizeAddress;
2136044eb2f6SDimitry Andric case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
2137044eb2f6SDimitry Andric return Attribute::SanitizeHWAddress;
2138f8af5cf6SDimitry Andric case bitc::ATTR_KIND_SANITIZE_THREAD:
2139f8af5cf6SDimitry Andric return Attribute::SanitizeThread;
2140f8af5cf6SDimitry Andric case bitc::ATTR_KIND_SANITIZE_MEMORY:
2141f8af5cf6SDimitry Andric return Attribute::SanitizeMemory;
2142ac9a064cSDimitry Andric case bitc::ATTR_KIND_SANITIZE_NUMERICAL_STABILITY:
2143ac9a064cSDimitry Andric return Attribute::SanitizeNumericalStability;
2144d8e91e46SDimitry Andric case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
2145d8e91e46SDimitry Andric return Attribute::SpeculativeLoadHardening;
214601095a5dSDimitry Andric case bitc::ATTR_KIND_SWIFT_ERROR:
214701095a5dSDimitry Andric return Attribute::SwiftError;
214801095a5dSDimitry Andric case bitc::ATTR_KIND_SWIFT_SELF:
214901095a5dSDimitry Andric return Attribute::SwiftSelf;
2150344a3780SDimitry Andric case bitc::ATTR_KIND_SWIFT_ASYNC:
2151344a3780SDimitry Andric return Attribute::SwiftAsync;
2152f8af5cf6SDimitry Andric case bitc::ATTR_KIND_UW_TABLE:
2153f8af5cf6SDimitry Andric return Attribute::UWTable;
2154344a3780SDimitry Andric case bitc::ATTR_KIND_VSCALE_RANGE:
2155344a3780SDimitry Andric return Attribute::VScaleRange;
2156e6d15924SDimitry Andric case bitc::ATTR_KIND_WILLRETURN:
2157e6d15924SDimitry Andric return Attribute::WillReturn;
215801095a5dSDimitry Andric case bitc::ATTR_KIND_WRITEONLY:
215901095a5dSDimitry Andric return Attribute::WriteOnly;
2160f8af5cf6SDimitry Andric case bitc::ATTR_KIND_Z_EXT:
2161f8af5cf6SDimitry Andric return Attribute::ZExt;
2162e6d15924SDimitry Andric case bitc::ATTR_KIND_IMMARG:
2163e6d15924SDimitry Andric return Attribute::ImmArg;
2164e6d15924SDimitry Andric case bitc::ATTR_KIND_SANITIZE_MEMTAG:
2165e6d15924SDimitry Andric return Attribute::SanitizeMemTag;
2166cfca06d7SDimitry Andric case bitc::ATTR_KIND_PREALLOCATED:
2167cfca06d7SDimitry Andric return Attribute::Preallocated;
2168cfca06d7SDimitry Andric case bitc::ATTR_KIND_NOUNDEF:
2169cfca06d7SDimitry Andric return Attribute::NoUndef;
2170b60736ecSDimitry Andric case bitc::ATTR_KIND_BYREF:
2171b60736ecSDimitry Andric return Attribute::ByRef;
2172b60736ecSDimitry Andric case bitc::ATTR_KIND_MUSTPROGRESS:
2173b60736ecSDimitry Andric return Attribute::MustProgress;
2174b60736ecSDimitry Andric case bitc::ATTR_KIND_HOT:
2175b60736ecSDimitry Andric return Attribute::Hot;
2176145449b1SDimitry Andric case bitc::ATTR_KIND_PRESPLIT_COROUTINE:
2177145449b1SDimitry Andric return Attribute::PresplitCoroutine;
2178b1c73532SDimitry Andric case bitc::ATTR_KIND_WRITABLE:
2179b1c73532SDimitry Andric return Attribute::Writable;
2180b1c73532SDimitry Andric case bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE:
2181b1c73532SDimitry Andric return Attribute::CoroDestroyOnlyWhenComplete;
2182312c0ed1SDimitry Andric case bitc::ATTR_KIND_DEAD_ON_UNWIND:
2183312c0ed1SDimitry Andric return Attribute::DeadOnUnwind;
2184ac9a064cSDimitry Andric case bitc::ATTR_KIND_RANGE:
2185ac9a064cSDimitry Andric return Attribute::Range;
2186ac9a064cSDimitry Andric case bitc::ATTR_KIND_INITIALIZES:
2187ac9a064cSDimitry Andric return Attribute::Initializes;
2188f8af5cf6SDimitry Andric }
2189f8af5cf6SDimitry Andric }
2190f8af5cf6SDimitry Andric
parseAlignmentValue(uint64_t Exponent,MaybeAlign & Alignment)2191b915e9e0SDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
21921d5ae102SDimitry Andric MaybeAlign &Alignment) {
21935a5ac124SDimitry Andric // Note: Alignment in bitcode files is incremented by 1, so that zero
21945a5ac124SDimitry Andric // can be used for default alignment.
21955a5ac124SDimitry Andric if (Exponent > Value::MaxAlignmentExponent + 1)
21963a0822f0SDimitry Andric return error("Invalid alignment value");
21971d5ae102SDimitry Andric Alignment = decodeMaybeAlign(Exponent);
2198b915e9e0SDimitry Andric return Error::success();
21995a5ac124SDimitry Andric }
22005a5ac124SDimitry Andric
parseAttrKind(uint64_t Code,Attribute::AttrKind * Kind)2201b915e9e0SDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
22023a0822f0SDimitry Andric *Kind = getAttrFromCode(Code);
2203f8af5cf6SDimitry Andric if (*Kind == Attribute::None)
2204b915e9e0SDimitry Andric return error("Unknown attribute kind (" + Twine(Code) + ")");
2205b915e9e0SDimitry Andric return Error::success();
2206f8af5cf6SDimitry Andric }
2207f8af5cf6SDimitry Andric
upgradeOldMemoryAttribute(MemoryEffects & ME,uint64_t EncodedKind)2208e3b55780SDimitry Andric static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) {
2209e3b55780SDimitry Andric switch (EncodedKind) {
2210e3b55780SDimitry Andric case bitc::ATTR_KIND_READ_NONE:
2211e3b55780SDimitry Andric ME &= MemoryEffects::none();
2212e3b55780SDimitry Andric return true;
2213e3b55780SDimitry Andric case bitc::ATTR_KIND_READ_ONLY:
2214e3b55780SDimitry Andric ME &= MemoryEffects::readOnly();
2215e3b55780SDimitry Andric return true;
2216e3b55780SDimitry Andric case bitc::ATTR_KIND_WRITEONLY:
2217e3b55780SDimitry Andric ME &= MemoryEffects::writeOnly();
2218e3b55780SDimitry Andric return true;
2219e3b55780SDimitry Andric case bitc::ATTR_KIND_ARGMEMONLY:
2220e3b55780SDimitry Andric ME &= MemoryEffects::argMemOnly();
2221e3b55780SDimitry Andric return true;
2222e3b55780SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
2223e3b55780SDimitry Andric ME &= MemoryEffects::inaccessibleMemOnly();
2224e3b55780SDimitry Andric return true;
2225e3b55780SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
2226e3b55780SDimitry Andric ME &= MemoryEffects::inaccessibleOrArgMemOnly();
2227e3b55780SDimitry Andric return true;
2228e3b55780SDimitry Andric default:
2229e3b55780SDimitry Andric return false;
2230e3b55780SDimitry Andric }
2231e3b55780SDimitry Andric }
2232e3b55780SDimitry Andric
parseAttributeGroupBlock()2233b915e9e0SDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() {
2234e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
2235e6d15924SDimitry Andric return Err;
22364a16efa3SDimitry Andric
22374a16efa3SDimitry Andric if (!MAttributeGroups.empty())
22383a0822f0SDimitry Andric return error("Invalid multiple blocks");
22394a16efa3SDimitry Andric
22404a16efa3SDimitry Andric SmallVector<uint64_t, 64> Record;
22414a16efa3SDimitry Andric
22424a16efa3SDimitry Andric // Read all the records.
2243b915e9e0SDimitry Andric while (true) {
2244e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2245e6d15924SDimitry Andric if (!MaybeEntry)
2246e6d15924SDimitry Andric return MaybeEntry.takeError();
2247e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
22484a16efa3SDimitry Andric
22494a16efa3SDimitry Andric switch (Entry.Kind) {
22504a16efa3SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
22514a16efa3SDimitry Andric case BitstreamEntry::Error:
22523a0822f0SDimitry Andric return error("Malformed block");
22534a16efa3SDimitry Andric case BitstreamEntry::EndBlock:
2254b915e9e0SDimitry Andric return Error::success();
22554a16efa3SDimitry Andric case BitstreamEntry::Record:
22564a16efa3SDimitry Andric // The interesting case.
22574a16efa3SDimitry Andric break;
22584a16efa3SDimitry Andric }
22594a16efa3SDimitry Andric
22604a16efa3SDimitry Andric // Read a record.
22614a16efa3SDimitry Andric Record.clear();
2262e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2263e6d15924SDimitry Andric if (!MaybeRecord)
2264e6d15924SDimitry Andric return MaybeRecord.takeError();
2265e6d15924SDimitry Andric switch (MaybeRecord.get()) {
22664a16efa3SDimitry Andric default: // Default behavior: ignore.
22674a16efa3SDimitry Andric break;
22684a16efa3SDimitry Andric case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
22694a16efa3SDimitry Andric if (Record.size() < 3)
2270145449b1SDimitry Andric return error("Invalid grp record");
22714a16efa3SDimitry Andric
22724a16efa3SDimitry Andric uint64_t GrpID = Record[0];
22734a16efa3SDimitry Andric uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
22744a16efa3SDimitry Andric
22756f8fc217SDimitry Andric AttrBuilder B(Context);
2276e3b55780SDimitry Andric MemoryEffects ME = MemoryEffects::unknown();
22774a16efa3SDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) {
22784a16efa3SDimitry Andric if (Record[i] == 0) { // Enum attribute
2279f8af5cf6SDimitry Andric Attribute::AttrKind Kind;
2280e3b55780SDimitry Andric uint64_t EncodedKind = Record[++i];
2281e3b55780SDimitry Andric if (Idx == AttributeList::FunctionIndex &&
2282e3b55780SDimitry Andric upgradeOldMemoryAttribute(ME, EncodedKind))
2283e3b55780SDimitry Andric continue;
2284e3b55780SDimitry Andric
2285e3b55780SDimitry Andric if (Error Err = parseAttrKind(EncodedKind, &Kind))
2286b915e9e0SDimitry Andric return Err;
2287f8af5cf6SDimitry Andric
2288e6d15924SDimitry Andric // Upgrade old-style byval attribute to one with a type, even if it's
2289e6d15924SDimitry Andric // nullptr. We will have to insert the real type when we associate
2290e6d15924SDimitry Andric // this AttributeList with a function.
2291e6d15924SDimitry Andric if (Kind == Attribute::ByVal)
2292e6d15924SDimitry Andric B.addByValAttr(nullptr);
2293b60736ecSDimitry Andric else if (Kind == Attribute::StructRet)
2294b60736ecSDimitry Andric B.addStructRetAttr(nullptr);
2295344a3780SDimitry Andric else if (Kind == Attribute::InAlloca)
2296344a3780SDimitry Andric B.addInAllocaAttr(nullptr);
2297145449b1SDimitry Andric else if (Kind == Attribute::UWTable)
2298145449b1SDimitry Andric B.addUWTableAttr(UWTableKind::Default);
2299344a3780SDimitry Andric else if (Attribute::isEnumAttrKind(Kind))
2300f8af5cf6SDimitry Andric B.addAttribute(Kind);
2301344a3780SDimitry Andric else
2302344a3780SDimitry Andric return error("Not an enum attribute");
23035ca98fd9SDimitry Andric } else if (Record[i] == 1) { // Integer attribute
2304f8af5cf6SDimitry Andric Attribute::AttrKind Kind;
2305b915e9e0SDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind))
2306b915e9e0SDimitry Andric return Err;
2307344a3780SDimitry Andric if (!Attribute::isIntAttrKind(Kind))
2308344a3780SDimitry Andric return error("Not an int attribute");
2309f8af5cf6SDimitry Andric if (Kind == Attribute::Alignment)
23104a16efa3SDimitry Andric B.addAlignmentAttr(Record[++i]);
23115ca98fd9SDimitry Andric else if (Kind == Attribute::StackAlignment)
23124a16efa3SDimitry Andric B.addStackAlignmentAttr(Record[++i]);
23135ca98fd9SDimitry Andric else if (Kind == Attribute::Dereferenceable)
23145ca98fd9SDimitry Andric B.addDereferenceableAttr(Record[++i]);
23155a5ac124SDimitry Andric else if (Kind == Attribute::DereferenceableOrNull)
23165a5ac124SDimitry Andric B.addDereferenceableOrNullAttr(Record[++i]);
231701095a5dSDimitry Andric else if (Kind == Attribute::AllocSize)
231801095a5dSDimitry Andric B.addAllocSizeAttrFromRawRepr(Record[++i]);
2319344a3780SDimitry Andric else if (Kind == Attribute::VScaleRange)
2320344a3780SDimitry Andric B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2321145449b1SDimitry Andric else if (Kind == Attribute::UWTable)
2322145449b1SDimitry Andric B.addUWTableAttr(UWTableKind(Record[++i]));
2323145449b1SDimitry Andric else if (Kind == Attribute::AllocKind)
2324145449b1SDimitry Andric B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i]));
2325e3b55780SDimitry Andric else if (Kind == Attribute::Memory)
2326e3b55780SDimitry Andric B.addMemoryAttr(MemoryEffects::createFromIntValue(Record[++i]));
23277fa27ce4SDimitry Andric else if (Kind == Attribute::NoFPClass)
23287fa27ce4SDimitry Andric B.addNoFPClassAttr(
23297fa27ce4SDimitry Andric static_cast<FPClassTest>(Record[++i] & fcAllFlags));
2330e6d15924SDimitry Andric } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
23314a16efa3SDimitry Andric bool HasValue = (Record[i++] == 4);
23324a16efa3SDimitry Andric SmallString<64> KindStr;
23334a16efa3SDimitry Andric SmallString<64> ValStr;
23344a16efa3SDimitry Andric
23354a16efa3SDimitry Andric while (Record[i] != 0 && i != e)
23364a16efa3SDimitry Andric KindStr += Record[i++];
23374a16efa3SDimitry Andric assert(Record[i] == 0 && "Kind string not null terminated");
23384a16efa3SDimitry Andric
23394a16efa3SDimitry Andric if (HasValue) {
23404a16efa3SDimitry Andric // Has a value associated with it.
23414a16efa3SDimitry Andric ++i; // Skip the '0' that terminates the "kind" string.
23424a16efa3SDimitry Andric while (Record[i] != 0 && i != e)
23434a16efa3SDimitry Andric ValStr += Record[i++];
23444a16efa3SDimitry Andric assert(Record[i] == 0 && "Value string not null terminated");
23454a16efa3SDimitry Andric }
23464a16efa3SDimitry Andric
23474a16efa3SDimitry Andric B.addAttribute(KindStr.str(), ValStr.str());
2348145449b1SDimitry Andric } else if (Record[i] == 5 || Record[i] == 6) {
2349e6d15924SDimitry Andric bool HasType = Record[i] == 6;
2350e6d15924SDimitry Andric Attribute::AttrKind Kind;
2351e6d15924SDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind))
2352e6d15924SDimitry Andric return Err;
2353344a3780SDimitry Andric if (!Attribute::isTypeAttrKind(Kind))
2354344a3780SDimitry Andric return error("Not a type attribute");
2355344a3780SDimitry Andric
2356344a3780SDimitry Andric B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
2357ac9a064cSDimitry Andric } else if (Record[i] == 7) {
2358ac9a064cSDimitry Andric Attribute::AttrKind Kind;
2359ac9a064cSDimitry Andric
2360ac9a064cSDimitry Andric i++;
2361ac9a064cSDimitry Andric if (Error Err = parseAttrKind(Record[i++], &Kind))
2362ac9a064cSDimitry Andric return Err;
2363ac9a064cSDimitry Andric if (!Attribute::isConstantRangeAttrKind(Kind))
2364ac9a064cSDimitry Andric return error("Not a ConstantRange attribute");
2365ac9a064cSDimitry Andric
2366ac9a064cSDimitry Andric Expected<ConstantRange> MaybeCR =
2367ac9a064cSDimitry Andric readBitWidthAndConstantRange(Record, i);
2368ac9a064cSDimitry Andric if (!MaybeCR)
2369ac9a064cSDimitry Andric return MaybeCR.takeError();
2370ac9a064cSDimitry Andric i--;
2371ac9a064cSDimitry Andric
2372ac9a064cSDimitry Andric B.addConstantRangeAttr(Kind, MaybeCR.get());
2373ac9a064cSDimitry Andric } else if (Record[i] == 8) {
2374ac9a064cSDimitry Andric Attribute::AttrKind Kind;
2375ac9a064cSDimitry Andric
2376ac9a064cSDimitry Andric i++;
2377ac9a064cSDimitry Andric if (Error Err = parseAttrKind(Record[i++], &Kind))
2378ac9a064cSDimitry Andric return Err;
2379ac9a064cSDimitry Andric if (!Attribute::isConstantRangeListAttrKind(Kind))
2380ac9a064cSDimitry Andric return error("Not a constant range list attribute");
2381ac9a064cSDimitry Andric
2382ac9a064cSDimitry Andric SmallVector<ConstantRange, 2> Val;
2383ac9a064cSDimitry Andric if (i + 2 > e)
2384ac9a064cSDimitry Andric return error("Too few records for constant range list");
2385ac9a064cSDimitry Andric unsigned RangeSize = Record[i++];
2386ac9a064cSDimitry Andric unsigned BitWidth = Record[i++];
2387ac9a064cSDimitry Andric for (unsigned Idx = 0; Idx < RangeSize; ++Idx) {
2388ac9a064cSDimitry Andric Expected<ConstantRange> MaybeCR =
2389ac9a064cSDimitry Andric readConstantRange(Record, i, BitWidth);
2390ac9a064cSDimitry Andric if (!MaybeCR)
2391ac9a064cSDimitry Andric return MaybeCR.takeError();
2392ac9a064cSDimitry Andric Val.push_back(MaybeCR.get());
2393ac9a064cSDimitry Andric }
2394ac9a064cSDimitry Andric i--;
2395ac9a064cSDimitry Andric
2396ac9a064cSDimitry Andric if (!ConstantRangeList::isOrderedRanges(Val))
2397ac9a064cSDimitry Andric return error("Invalid (unordered or overlapping) range list");
2398ac9a064cSDimitry Andric B.addConstantRangeListAttr(Kind, Val);
2399145449b1SDimitry Andric } else {
2400145449b1SDimitry Andric return error("Invalid attribute group entry");
24014a16efa3SDimitry Andric }
24024a16efa3SDimitry Andric }
24034a16efa3SDimitry Andric
2404e3b55780SDimitry Andric if (ME != MemoryEffects::unknown())
2405e3b55780SDimitry Andric B.addMemoryAttr(ME);
2406e3b55780SDimitry Andric
2407cfca06d7SDimitry Andric UpgradeAttributes(B);
240871d5a254SDimitry Andric MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
24094a16efa3SDimitry Andric break;
24104a16efa3SDimitry Andric }
2411009b1c42SEd Schouten }
2412009b1c42SEd Schouten }
2413009b1c42SEd Schouten }
2414009b1c42SEd Schouten
parseTypeTable()2415b915e9e0SDimitry Andric Error BitcodeReader::parseTypeTable() {
2416e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
2417e6d15924SDimitry Andric return Err;
2418009b1c42SEd Schouten
24193a0822f0SDimitry Andric return parseTypeTableBody();
2420411bd29eSDimitry Andric }
2421411bd29eSDimitry Andric
parseTypeTableBody()2422b915e9e0SDimitry Andric Error BitcodeReader::parseTypeTableBody() {
2423009b1c42SEd Schouten if (!TypeList.empty())
24243a0822f0SDimitry Andric return error("Invalid multiple blocks");
2425009b1c42SEd Schouten
2426009b1c42SEd Schouten SmallVector<uint64_t, 64> Record;
2427009b1c42SEd Schouten unsigned NumRecords = 0;
2428009b1c42SEd Schouten
2429411bd29eSDimitry Andric SmallString<64> TypeName;
2430411bd29eSDimitry Andric
2431009b1c42SEd Schouten // Read all the records for this type table.
2432b915e9e0SDimitry Andric while (true) {
2433e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2434e6d15924SDimitry Andric if (!MaybeEntry)
2435e6d15924SDimitry Andric return MaybeEntry.takeError();
2436e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
24374a16efa3SDimitry Andric
24384a16efa3SDimitry Andric switch (Entry.Kind) {
24394a16efa3SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
24404a16efa3SDimitry Andric case BitstreamEntry::Error:
24413a0822f0SDimitry Andric return error("Malformed block");
24424a16efa3SDimitry Andric case BitstreamEntry::EndBlock:
2443009b1c42SEd Schouten if (NumRecords != TypeList.size())
24443a0822f0SDimitry Andric return error("Malformed block");
2445b915e9e0SDimitry Andric return Error::success();
24464a16efa3SDimitry Andric case BitstreamEntry::Record:
24474a16efa3SDimitry Andric // The interesting case.
24484a16efa3SDimitry Andric break;
2449009b1c42SEd Schouten }
2450009b1c42SEd Schouten
2451009b1c42SEd Schouten // Read a record.
2452009b1c42SEd Schouten Record.clear();
24535ca98fd9SDimitry Andric Type *ResultTy = nullptr;
2454145449b1SDimitry Andric SmallVector<unsigned> ContainedIDs;
2455e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2456e6d15924SDimitry Andric if (!MaybeRecord)
2457e6d15924SDimitry Andric return MaybeRecord.takeError();
2458e6d15924SDimitry Andric switch (MaybeRecord.get()) {
2459f8af5cf6SDimitry Andric default:
24603a0822f0SDimitry Andric return error("Invalid value");
2461009b1c42SEd Schouten case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
2462009b1c42SEd Schouten // TYPE_CODE_NUMENTRY contains a count of the number of types in the
2463009b1c42SEd Schouten // type list. This allows us to reserve space.
2464b60736ecSDimitry Andric if (Record.empty())
2465145449b1SDimitry Andric return error("Invalid numentry record");
2466411bd29eSDimitry Andric TypeList.resize(Record[0]);
2467009b1c42SEd Schouten continue;
2468009b1c42SEd Schouten case bitc::TYPE_CODE_VOID: // VOID
246959850d08SRoman Divacky ResultTy = Type::getVoidTy(Context);
2470009b1c42SEd Schouten break;
247163faed5bSDimitry Andric case bitc::TYPE_CODE_HALF: // HALF
247263faed5bSDimitry Andric ResultTy = Type::getHalfTy(Context);
247363faed5bSDimitry Andric break;
2474cfca06d7SDimitry Andric case bitc::TYPE_CODE_BFLOAT: // BFLOAT
2475cfca06d7SDimitry Andric ResultTy = Type::getBFloatTy(Context);
2476cfca06d7SDimitry Andric break;
2477009b1c42SEd Schouten case bitc::TYPE_CODE_FLOAT: // FLOAT
247859850d08SRoman Divacky ResultTy = Type::getFloatTy(Context);
2479009b1c42SEd Schouten break;
2480009b1c42SEd Schouten case bitc::TYPE_CODE_DOUBLE: // DOUBLE
248159850d08SRoman Divacky ResultTy = Type::getDoubleTy(Context);
2482009b1c42SEd Schouten break;
2483009b1c42SEd Schouten case bitc::TYPE_CODE_X86_FP80: // X86_FP80
248459850d08SRoman Divacky ResultTy = Type::getX86_FP80Ty(Context);
2485009b1c42SEd Schouten break;
2486009b1c42SEd Schouten case bitc::TYPE_CODE_FP128: // FP128
248759850d08SRoman Divacky ResultTy = Type::getFP128Ty(Context);
2488009b1c42SEd Schouten break;
2489009b1c42SEd Schouten case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
249059850d08SRoman Divacky ResultTy = Type::getPPC_FP128Ty(Context);
2491009b1c42SEd Schouten break;
2492009b1c42SEd Schouten case bitc::TYPE_CODE_LABEL: // LABEL
249359850d08SRoman Divacky ResultTy = Type::getLabelTy(Context);
2494009b1c42SEd Schouten break;
2495009b1c42SEd Schouten case bitc::TYPE_CODE_METADATA: // METADATA
249659850d08SRoman Divacky ResultTy = Type::getMetadataTy(Context);
2497009b1c42SEd Schouten break;
2498cf099d11SDimitry Andric case bitc::TYPE_CODE_X86_MMX: // X86_MMX
2499cf099d11SDimitry Andric ResultTy = Type::getX86_MMXTy(Context);
2500cf099d11SDimitry Andric break;
2501b60736ecSDimitry Andric case bitc::TYPE_CODE_X86_AMX: // X86_AMX
2502b60736ecSDimitry Andric ResultTy = Type::getX86_AMXTy(Context);
2503b60736ecSDimitry Andric break;
2504dd58ef01SDimitry Andric case bitc::TYPE_CODE_TOKEN: // TOKEN
2505dd58ef01SDimitry Andric ResultTy = Type::getTokenTy(Context);
2506dd58ef01SDimitry Andric break;
25075a5ac124SDimitry Andric case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
2508b60736ecSDimitry Andric if (Record.empty())
2509145449b1SDimitry Andric return error("Invalid integer record");
2510009b1c42SEd Schouten
25115a5ac124SDimitry Andric uint64_t NumBits = Record[0];
25125a5ac124SDimitry Andric if (NumBits < IntegerType::MIN_INT_BITS ||
25135a5ac124SDimitry Andric NumBits > IntegerType::MAX_INT_BITS)
25143a0822f0SDimitry Andric return error("Bitwidth for integer type out of range");
25155a5ac124SDimitry Andric ResultTy = IntegerType::get(Context, NumBits);
2516009b1c42SEd Schouten break;
25175a5ac124SDimitry Andric }
2518009b1c42SEd Schouten case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
2519009b1c42SEd Schouten // [pointee type, address space]
2520b60736ecSDimitry Andric if (Record.empty())
2521145449b1SDimitry Andric return error("Invalid pointer record");
2522009b1c42SEd Schouten unsigned AddressSpace = 0;
2523009b1c42SEd Schouten if (Record.size() == 2)
2524009b1c42SEd Schouten AddressSpace = Record[1];
2525411bd29eSDimitry Andric ResultTy = getTypeByID(Record[0]);
25265a5ac124SDimitry Andric if (!ResultTy ||
25275a5ac124SDimitry Andric !PointerType::isValidElementType(ResultTy))
25283a0822f0SDimitry Andric return error("Invalid type");
2529145449b1SDimitry Andric ContainedIDs.push_back(Record[0]);
2530411bd29eSDimitry Andric ResultTy = PointerType::get(ResultTy, AddressSpace);
2531009b1c42SEd Schouten break;
2532009b1c42SEd Schouten }
2533344a3780SDimitry Andric case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
2534344a3780SDimitry Andric if (Record.size() != 1)
2535145449b1SDimitry Andric return error("Invalid opaque pointer record");
2536344a3780SDimitry Andric unsigned AddressSpace = Record[0];
2537344a3780SDimitry Andric ResultTy = PointerType::get(Context, AddressSpace);
2538344a3780SDimitry Andric break;
2539344a3780SDimitry Andric }
254063faed5bSDimitry Andric case bitc::TYPE_CODE_FUNCTION_OLD: {
2541cfca06d7SDimitry Andric // Deprecated, but still needed to read old bitcode files.
2542009b1c42SEd Schouten // FUNCTION: [vararg, attrid, retty, paramty x N]
2543009b1c42SEd Schouten if (Record.size() < 3)
2544145449b1SDimitry Andric return error("Invalid function record");
254563faed5bSDimitry Andric SmallVector<Type*, 8> ArgTys;
2546411bd29eSDimitry Andric for (unsigned i = 3, e = Record.size(); i != e; ++i) {
2547411bd29eSDimitry Andric if (Type *T = getTypeByID(Record[i]))
2548411bd29eSDimitry Andric ArgTys.push_back(T);
2549411bd29eSDimitry Andric else
2550009b1c42SEd Schouten break;
2551009b1c42SEd Schouten }
2552411bd29eSDimitry Andric
2553411bd29eSDimitry Andric ResultTy = getTypeByID(Record[2]);
25545ca98fd9SDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-3)
25553a0822f0SDimitry Andric return error("Invalid type");
2556411bd29eSDimitry Andric
2557145449b1SDimitry Andric ContainedIDs.append(Record.begin() + 2, Record.end());
2558411bd29eSDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2559411bd29eSDimitry Andric break;
2560411bd29eSDimitry Andric }
256163faed5bSDimitry Andric case bitc::TYPE_CODE_FUNCTION: {
256263faed5bSDimitry Andric // FUNCTION: [vararg, retty, paramty x N]
256363faed5bSDimitry Andric if (Record.size() < 2)
2564145449b1SDimitry Andric return error("Invalid function record");
256563faed5bSDimitry Andric SmallVector<Type*, 8> ArgTys;
256663faed5bSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) {
25675a5ac124SDimitry Andric if (Type *T = getTypeByID(Record[i])) {
25685a5ac124SDimitry Andric if (!FunctionType::isValidArgumentType(T))
25693a0822f0SDimitry Andric return error("Invalid function argument type");
257063faed5bSDimitry Andric ArgTys.push_back(T);
25715a5ac124SDimitry Andric }
257263faed5bSDimitry Andric else
257363faed5bSDimitry Andric break;
257463faed5bSDimitry Andric }
257563faed5bSDimitry Andric
257663faed5bSDimitry Andric ResultTy = getTypeByID(Record[1]);
25775ca98fd9SDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-2)
25783a0822f0SDimitry Andric return error("Invalid type");
257963faed5bSDimitry Andric
2580145449b1SDimitry Andric ContainedIDs.append(Record.begin() + 1, Record.end());
258163faed5bSDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
258263faed5bSDimitry Andric break;
258363faed5bSDimitry Andric }
2584411bd29eSDimitry Andric case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
2585b60736ecSDimitry Andric if (Record.empty())
2586145449b1SDimitry Andric return error("Invalid anon struct record");
258763faed5bSDimitry Andric SmallVector<Type*, 8> EltTys;
2588411bd29eSDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2589411bd29eSDimitry Andric if (Type *T = getTypeByID(Record[i]))
2590411bd29eSDimitry Andric EltTys.push_back(T);
2591411bd29eSDimitry Andric else
2592411bd29eSDimitry Andric break;
2593411bd29eSDimitry Andric }
2594411bd29eSDimitry Andric if (EltTys.size() != Record.size()-1)
25953a0822f0SDimitry Andric return error("Invalid type");
2596145449b1SDimitry Andric ContainedIDs.append(Record.begin() + 1, Record.end());
259759850d08SRoman Divacky ResultTy = StructType::get(Context, EltTys, Record[0]);
2598009b1c42SEd Schouten break;
2599009b1c42SEd Schouten }
2600411bd29eSDimitry Andric case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
26013a0822f0SDimitry Andric if (convertToString(Record, 0, TypeName))
2602145449b1SDimitry Andric return error("Invalid struct name record");
2603411bd29eSDimitry Andric continue;
2604411bd29eSDimitry Andric
2605411bd29eSDimitry Andric case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
2606b60736ecSDimitry Andric if (Record.empty())
2607145449b1SDimitry Andric return error("Invalid named struct record");
2608411bd29eSDimitry Andric
2609411bd29eSDimitry Andric if (NumRecords >= TypeList.size())
26103a0822f0SDimitry Andric return error("Invalid TYPE table");
2611411bd29eSDimitry Andric
2612411bd29eSDimitry Andric // Check to see if this was forward referenced, if so fill in the temp.
2613411bd29eSDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2614411bd29eSDimitry Andric if (Res) {
2615411bd29eSDimitry Andric Res->setName(TypeName);
26165ca98fd9SDimitry Andric TypeList[NumRecords] = nullptr;
2617411bd29eSDimitry Andric } else // Otherwise, create a new struct.
261867c32a98SDimitry Andric Res = createIdentifiedStructType(Context, TypeName);
2619411bd29eSDimitry Andric TypeName.clear();
2620411bd29eSDimitry Andric
2621411bd29eSDimitry Andric SmallVector<Type*, 8> EltTys;
2622411bd29eSDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2623411bd29eSDimitry Andric if (Type *T = getTypeByID(Record[i]))
2624411bd29eSDimitry Andric EltTys.push_back(T);
2625411bd29eSDimitry Andric else
2626411bd29eSDimitry Andric break;
2627411bd29eSDimitry Andric }
2628411bd29eSDimitry Andric if (EltTys.size() != Record.size()-1)
2629145449b1SDimitry Andric return error("Invalid named struct record");
2630411bd29eSDimitry Andric Res->setBody(EltTys, Record[0]);
2631145449b1SDimitry Andric ContainedIDs.append(Record.begin() + 1, Record.end());
2632411bd29eSDimitry Andric ResultTy = Res;
2633411bd29eSDimitry Andric break;
2634411bd29eSDimitry Andric }
2635411bd29eSDimitry Andric case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
2636411bd29eSDimitry Andric if (Record.size() != 1)
2637145449b1SDimitry Andric return error("Invalid opaque type record");
2638411bd29eSDimitry Andric
2639411bd29eSDimitry Andric if (NumRecords >= TypeList.size())
26403a0822f0SDimitry Andric return error("Invalid TYPE table");
2641411bd29eSDimitry Andric
2642411bd29eSDimitry Andric // Check to see if this was forward referenced, if so fill in the temp.
2643411bd29eSDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2644411bd29eSDimitry Andric if (Res) {
2645411bd29eSDimitry Andric Res->setName(TypeName);
26465ca98fd9SDimitry Andric TypeList[NumRecords] = nullptr;
2647411bd29eSDimitry Andric } else // Otherwise, create a new struct with no body.
264867c32a98SDimitry Andric Res = createIdentifiedStructType(Context, TypeName);
2649411bd29eSDimitry Andric TypeName.clear();
2650411bd29eSDimitry Andric ResultTy = Res;
2651411bd29eSDimitry Andric break;
2652411bd29eSDimitry Andric }
2653e3b55780SDimitry Andric case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...]
2654e3b55780SDimitry Andric if (Record.size() < 1)
2655e3b55780SDimitry Andric return error("Invalid target extension type record");
2656e3b55780SDimitry Andric
2657e3b55780SDimitry Andric if (NumRecords >= TypeList.size())
2658e3b55780SDimitry Andric return error("Invalid TYPE table");
2659e3b55780SDimitry Andric
2660e3b55780SDimitry Andric if (Record[0] >= Record.size())
2661e3b55780SDimitry Andric return error("Too many type parameters");
2662e3b55780SDimitry Andric
2663e3b55780SDimitry Andric unsigned NumTys = Record[0];
2664e3b55780SDimitry Andric SmallVector<Type *, 4> TypeParams;
2665e3b55780SDimitry Andric SmallVector<unsigned, 8> IntParams;
2666e3b55780SDimitry Andric for (unsigned i = 0; i < NumTys; i++) {
2667e3b55780SDimitry Andric if (Type *T = getTypeByID(Record[i + 1]))
2668e3b55780SDimitry Andric TypeParams.push_back(T);
2669e3b55780SDimitry Andric else
2670e3b55780SDimitry Andric return error("Invalid type");
2671e3b55780SDimitry Andric }
2672e3b55780SDimitry Andric
2673e3b55780SDimitry Andric for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) {
2674e3b55780SDimitry Andric if (Record[i] > UINT_MAX)
2675e3b55780SDimitry Andric return error("Integer parameter too large");
2676e3b55780SDimitry Andric IntParams.push_back(Record[i]);
2677e3b55780SDimitry Andric }
2678e3b55780SDimitry Andric ResultTy = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
2679e3b55780SDimitry Andric TypeName.clear();
2680e3b55780SDimitry Andric break;
2681e3b55780SDimitry Andric }
2682009b1c42SEd Schouten case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
2683009b1c42SEd Schouten if (Record.size() < 2)
2684145449b1SDimitry Andric return error("Invalid array type record");
26855a5ac124SDimitry Andric ResultTy = getTypeByID(Record[1]);
26865a5ac124SDimitry Andric if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
26873a0822f0SDimitry Andric return error("Invalid type");
2688145449b1SDimitry Andric ContainedIDs.push_back(Record[1]);
26895a5ac124SDimitry Andric ResultTy = ArrayType::get(ResultTy, Record[0]);
2690009b1c42SEd Schouten break;
2691e6d15924SDimitry Andric case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or
2692e6d15924SDimitry Andric // [numelts, eltty, scalable]
2693009b1c42SEd Schouten if (Record.size() < 2)
2694145449b1SDimitry Andric return error("Invalid vector type record");
269585d8b2bbSDimitry Andric if (Record[0] == 0)
26963a0822f0SDimitry Andric return error("Invalid vector length");
26975a5ac124SDimitry Andric ResultTy = getTypeByID(Record[1]);
2698c0981da4SDimitry Andric if (!ResultTy || !VectorType::isValidElementType(ResultTy))
26993a0822f0SDimitry Andric return error("Invalid type");
2700e6d15924SDimitry Andric bool Scalable = Record.size() > 2 ? Record[2] : false;
2701145449b1SDimitry Andric ContainedIDs.push_back(Record[1]);
2702e6d15924SDimitry Andric ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2703009b1c42SEd Schouten break;
2704009b1c42SEd Schouten }
2705009b1c42SEd Schouten
2706411bd29eSDimitry Andric if (NumRecords >= TypeList.size())
27073a0822f0SDimitry Andric return error("Invalid TYPE table");
27085a5ac124SDimitry Andric if (TypeList[NumRecords])
27093a0822f0SDimitry Andric return error(
27105a5ac124SDimitry Andric "Invalid TYPE table: Only named structs can be forward referenced");
2711411bd29eSDimitry Andric assert(ResultTy && "Didn't read a type?");
2712145449b1SDimitry Andric TypeList[NumRecords] = ResultTy;
2713145449b1SDimitry Andric if (!ContainedIDs.empty())
2714145449b1SDimitry Andric ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2715145449b1SDimitry Andric ++NumRecords;
2716009b1c42SEd Schouten }
2717009b1c42SEd Schouten }
2718411bd29eSDimitry Andric
parseOperandBundleTags()2719b915e9e0SDimitry Andric Error BitcodeReader::parseOperandBundleTags() {
2720e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
2721e6d15924SDimitry Andric return Err;
2722dd58ef01SDimitry Andric
2723dd58ef01SDimitry Andric if (!BundleTags.empty())
2724dd58ef01SDimitry Andric return error("Invalid multiple blocks");
2725dd58ef01SDimitry Andric
2726dd58ef01SDimitry Andric SmallVector<uint64_t, 64> Record;
2727dd58ef01SDimitry Andric
2728b915e9e0SDimitry Andric while (true) {
2729e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2730e6d15924SDimitry Andric if (!MaybeEntry)
2731e6d15924SDimitry Andric return MaybeEntry.takeError();
2732e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
2733dd58ef01SDimitry Andric
2734dd58ef01SDimitry Andric switch (Entry.Kind) {
2735dd58ef01SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
2736dd58ef01SDimitry Andric case BitstreamEntry::Error:
2737dd58ef01SDimitry Andric return error("Malformed block");
2738dd58ef01SDimitry Andric case BitstreamEntry::EndBlock:
2739b915e9e0SDimitry Andric return Error::success();
2740dd58ef01SDimitry Andric case BitstreamEntry::Record:
2741dd58ef01SDimitry Andric // The interesting case.
2742dd58ef01SDimitry Andric break;
2743dd58ef01SDimitry Andric }
2744dd58ef01SDimitry Andric
2745dd58ef01SDimitry Andric // Tags are implicitly mapped to integers by their order.
2746dd58ef01SDimitry Andric
2747e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2748e6d15924SDimitry Andric if (!MaybeRecord)
2749e6d15924SDimitry Andric return MaybeRecord.takeError();
2750e6d15924SDimitry Andric if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
2751145449b1SDimitry Andric return error("Invalid operand bundle record");
2752dd58ef01SDimitry Andric
2753dd58ef01SDimitry Andric // OPERAND_BUNDLE_TAG: [strchr x N]
2754dd58ef01SDimitry Andric BundleTags.emplace_back();
2755dd58ef01SDimitry Andric if (convertToString(Record, 0, BundleTags.back()))
2756145449b1SDimitry Andric return error("Invalid operand bundle record");
2757dd58ef01SDimitry Andric Record.clear();
2758dd58ef01SDimitry Andric }
2759dd58ef01SDimitry Andric }
2760dd58ef01SDimitry Andric
parseSyncScopeNames()2761ca089b24SDimitry Andric Error BitcodeReader::parseSyncScopeNames() {
2762e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2763e6d15924SDimitry Andric return Err;
2764ca089b24SDimitry Andric
2765ca089b24SDimitry Andric if (!SSIDs.empty())
2766ca089b24SDimitry Andric return error("Invalid multiple synchronization scope names blocks");
2767ca089b24SDimitry Andric
2768ca089b24SDimitry Andric SmallVector<uint64_t, 64> Record;
2769ca089b24SDimitry Andric while (true) {
2770e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2771e6d15924SDimitry Andric if (!MaybeEntry)
2772e6d15924SDimitry Andric return MaybeEntry.takeError();
2773e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
2774e6d15924SDimitry Andric
2775ca089b24SDimitry Andric switch (Entry.Kind) {
2776ca089b24SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
2777ca089b24SDimitry Andric case BitstreamEntry::Error:
2778ca089b24SDimitry Andric return error("Malformed block");
2779ca089b24SDimitry Andric case BitstreamEntry::EndBlock:
2780ca089b24SDimitry Andric if (SSIDs.empty())
2781ca089b24SDimitry Andric return error("Invalid empty synchronization scope names block");
2782ca089b24SDimitry Andric return Error::success();
2783ca089b24SDimitry Andric case BitstreamEntry::Record:
2784ca089b24SDimitry Andric // The interesting case.
2785ca089b24SDimitry Andric break;
2786ca089b24SDimitry Andric }
2787ca089b24SDimitry Andric
2788ca089b24SDimitry Andric // Synchronization scope names are implicitly mapped to synchronization
2789ca089b24SDimitry Andric // scope IDs by their order.
2790ca089b24SDimitry Andric
2791e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2792e6d15924SDimitry Andric if (!MaybeRecord)
2793e6d15924SDimitry Andric return MaybeRecord.takeError();
2794e6d15924SDimitry Andric if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2795145449b1SDimitry Andric return error("Invalid sync scope record");
2796ca089b24SDimitry Andric
2797ca089b24SDimitry Andric SmallString<16> SSN;
2798ca089b24SDimitry Andric if (convertToString(Record, 0, SSN))
2799145449b1SDimitry Andric return error("Invalid sync scope record");
2800ca089b24SDimitry Andric
2801ca089b24SDimitry Andric SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2802ca089b24SDimitry Andric Record.clear();
2803ca089b24SDimitry Andric }
2804ca089b24SDimitry Andric }
2805ca089b24SDimitry Andric
2806dd58ef01SDimitry Andric /// Associate a value with its name from the given index in the provided record.
recordValue(SmallVectorImpl<uint64_t> & Record,unsigned NameIndex,Triple & TT)2807b915e9e0SDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2808dd58ef01SDimitry Andric unsigned NameIndex, Triple &TT) {
2809dd58ef01SDimitry Andric SmallString<128> ValueName;
2810dd58ef01SDimitry Andric if (convertToString(Record, NameIndex, ValueName))
2811dd58ef01SDimitry Andric return error("Invalid record");
2812dd58ef01SDimitry Andric unsigned ValueID = Record[0];
2813dd58ef01SDimitry Andric if (ValueID >= ValueList.size() || !ValueList[ValueID])
2814dd58ef01SDimitry Andric return error("Invalid record");
2815dd58ef01SDimitry Andric Value *V = ValueList[ValueID];
2816dd58ef01SDimitry Andric
2817dd58ef01SDimitry Andric StringRef NameStr(ValueName.data(), ValueName.size());
2818b1c73532SDimitry Andric if (NameStr.contains(0))
2819dd58ef01SDimitry Andric return error("Invalid value name");
2820dd58ef01SDimitry Andric V->setName(NameStr);
2821dd58ef01SDimitry Andric auto *GO = dyn_cast<GlobalObject>(V);
282277fc4c14SDimitry Andric if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
2823dd58ef01SDimitry Andric GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2824dd58ef01SDimitry Andric return V;
2825dd58ef01SDimitry Andric }
2826dd58ef01SDimitry Andric
282701095a5dSDimitry Andric /// Helper to note and return the current location, and jump to the given
282801095a5dSDimitry Andric /// offset.
jumpToValueSymbolTable(uint64_t Offset,BitstreamCursor & Stream)2829e6d15924SDimitry Andric static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
283001095a5dSDimitry Andric BitstreamCursor &Stream) {
2831dd58ef01SDimitry Andric // Save the current parsing location so we can jump back at the end
2832dd58ef01SDimitry Andric // of the VST read.
283301095a5dSDimitry Andric uint64_t CurrentBit = Stream.GetCurrentBitNo();
2834e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2835e6d15924SDimitry Andric return std::move(JumpFailed);
2836e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2837e6d15924SDimitry Andric if (!MaybeEntry)
2838e6d15924SDimitry Andric return MaybeEntry.takeError();
2839145449b1SDimitry Andric if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
2840145449b1SDimitry Andric MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
2841145449b1SDimitry Andric return error("Expected value symbol table subblock");
284201095a5dSDimitry Andric return CurrentBit;
2843dd58ef01SDimitry Andric }
2844dd58ef01SDimitry Andric
setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,Function * F,ArrayRef<uint64_t> Record)2845d99dafe2SDimitry Andric void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2846d99dafe2SDimitry Andric Function *F,
2847d99dafe2SDimitry Andric ArrayRef<uint64_t> Record) {
2848d99dafe2SDimitry Andric // Note that we subtract 1 here because the offset is relative to one word
2849d99dafe2SDimitry Andric // before the start of the identification or module block, which was
2850d99dafe2SDimitry Andric // historically always the start of the regular bitcode header.
2851d99dafe2SDimitry Andric uint64_t FuncWordOffset = Record[1] - 1;
2852d99dafe2SDimitry Andric uint64_t FuncBitOffset = FuncWordOffset * 32;
2853d99dafe2SDimitry Andric DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2854d99dafe2SDimitry Andric // Set the LastFunctionBlockBit to point to the last function block.
2855d99dafe2SDimitry Andric // Later when parsing is resumed after function materialization,
2856d99dafe2SDimitry Andric // we can simply skip that last function block.
2857d99dafe2SDimitry Andric if (FuncBitOffset > LastFunctionBlockBit)
2858d99dafe2SDimitry Andric LastFunctionBlockBit = FuncBitOffset;
2859d99dafe2SDimitry Andric }
2860d99dafe2SDimitry Andric
2861d99dafe2SDimitry Andric /// Read a new-style GlobalValue symbol table.
parseGlobalValueSymbolTable()2862d99dafe2SDimitry Andric Error BitcodeReader::parseGlobalValueSymbolTable() {
2863d99dafe2SDimitry Andric unsigned FuncBitcodeOffsetDelta =
2864d99dafe2SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2865d99dafe2SDimitry Andric
2866e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2867e6d15924SDimitry Andric return Err;
2868d99dafe2SDimitry Andric
2869d99dafe2SDimitry Andric SmallVector<uint64_t, 64> Record;
2870d99dafe2SDimitry Andric while (true) {
2871e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2872e6d15924SDimitry Andric if (!MaybeEntry)
2873e6d15924SDimitry Andric return MaybeEntry.takeError();
2874e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
2875d99dafe2SDimitry Andric
2876d99dafe2SDimitry Andric switch (Entry.Kind) {
2877d99dafe2SDimitry Andric case BitstreamEntry::SubBlock:
2878d99dafe2SDimitry Andric case BitstreamEntry::Error:
2879d99dafe2SDimitry Andric return error("Malformed block");
2880d99dafe2SDimitry Andric case BitstreamEntry::EndBlock:
2881d99dafe2SDimitry Andric return Error::success();
2882d99dafe2SDimitry Andric case BitstreamEntry::Record:
2883d99dafe2SDimitry Andric break;
2884d99dafe2SDimitry Andric }
2885d99dafe2SDimitry Andric
2886d99dafe2SDimitry Andric Record.clear();
2887e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2888e6d15924SDimitry Andric if (!MaybeRecord)
2889e6d15924SDimitry Andric return MaybeRecord.takeError();
2890e6d15924SDimitry Andric switch (MaybeRecord.get()) {
2891145449b1SDimitry Andric case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
2892145449b1SDimitry Andric unsigned ValueID = Record[0];
2893145449b1SDimitry Andric if (ValueID >= ValueList.size() || !ValueList[ValueID])
2894145449b1SDimitry Andric return error("Invalid value reference in symbol table");
2895d99dafe2SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2896145449b1SDimitry Andric cast<Function>(ValueList[ValueID]), Record);
2897d99dafe2SDimitry Andric break;
2898d99dafe2SDimitry Andric }
2899d99dafe2SDimitry Andric }
2900d99dafe2SDimitry Andric }
2901145449b1SDimitry Andric }
2902d99dafe2SDimitry Andric
290301095a5dSDimitry Andric /// Parse the value symbol table at either the current parsing location or
290401095a5dSDimitry Andric /// at the given bit offset if provided.
parseValueSymbolTable(uint64_t Offset)2905b915e9e0SDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
290601095a5dSDimitry Andric uint64_t CurrentBit;
290701095a5dSDimitry Andric // Pass in the Offset to distinguish between calling for the module-level
290801095a5dSDimitry Andric // VST (where we want to jump to the VST offset) and the function-level
290901095a5dSDimitry Andric // VST (where we don't).
2910d99dafe2SDimitry Andric if (Offset > 0) {
2911e6d15924SDimitry Andric Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2912e6d15924SDimitry Andric if (!MaybeCurrentBit)
2913e6d15924SDimitry Andric return MaybeCurrentBit.takeError();
2914e6d15924SDimitry Andric CurrentBit = MaybeCurrentBit.get();
2915d99dafe2SDimitry Andric // If this module uses a string table, read this as a module-level VST.
2916d99dafe2SDimitry Andric if (UseStrtab) {
2917d99dafe2SDimitry Andric if (Error Err = parseGlobalValueSymbolTable())
2918d99dafe2SDimitry Andric return Err;
2919e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2920e6d15924SDimitry Andric return JumpFailed;
2921d99dafe2SDimitry Andric return Error::success();
2922d99dafe2SDimitry Andric }
2923d99dafe2SDimitry Andric // Otherwise, the VST will be in a similar format to a function-level VST,
2924d99dafe2SDimitry Andric // and will contain symbol names.
2925d99dafe2SDimitry Andric }
292601095a5dSDimitry Andric
2927dd58ef01SDimitry Andric // Compute the delta between the bitcode indices in the VST (the word offset
2928dd58ef01SDimitry Andric // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2929dd58ef01SDimitry Andric // expected by the lazy reader. The reader's EnterSubBlock expects to have
2930dd58ef01SDimitry Andric // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2931dd58ef01SDimitry Andric // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2932dd58ef01SDimitry Andric // just before entering the VST subblock because: 1) the EnterSubBlock
2933dd58ef01SDimitry Andric // changes the AbbrevID width; 2) the VST block is nested within the same
2934dd58ef01SDimitry Andric // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2935dd58ef01SDimitry Andric // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2936dd58ef01SDimitry Andric // jump to the FUNCTION_BLOCK using this offset later, we don't want
2937dd58ef01SDimitry Andric // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2938dd58ef01SDimitry Andric unsigned FuncBitcodeOffsetDelta =
2939dd58ef01SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2940dd58ef01SDimitry Andric
2941e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2942e6d15924SDimitry Andric return Err;
2943009b1c42SEd Schouten
2944009b1c42SEd Schouten SmallVector<uint64_t, 64> Record;
2945009b1c42SEd Schouten
29465a5ac124SDimitry Andric Triple TT(TheModule->getTargetTriple());
29475a5ac124SDimitry Andric
2948009b1c42SEd Schouten // Read all the records for this value table.
2949009b1c42SEd Schouten SmallString<128> ValueName;
2950b915e9e0SDimitry Andric
2951b915e9e0SDimitry Andric while (true) {
2952e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2953e6d15924SDimitry Andric if (!MaybeEntry)
2954e6d15924SDimitry Andric return MaybeEntry.takeError();
2955e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
2956009b1c42SEd Schouten
29574a16efa3SDimitry Andric switch (Entry.Kind) {
29584a16efa3SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
29594a16efa3SDimitry Andric case BitstreamEntry::Error:
29603a0822f0SDimitry Andric return error("Malformed block");
29614a16efa3SDimitry Andric case BitstreamEntry::EndBlock:
2962dd58ef01SDimitry Andric if (Offset > 0)
2963e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2964e6d15924SDimitry Andric return JumpFailed;
2965b915e9e0SDimitry Andric return Error::success();
29664a16efa3SDimitry Andric case BitstreamEntry::Record:
29674a16efa3SDimitry Andric // The interesting case.
29684a16efa3SDimitry Andric break;
2969009b1c42SEd Schouten }
2970009b1c42SEd Schouten
2971009b1c42SEd Schouten // Read a record.
2972009b1c42SEd Schouten Record.clear();
2973e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2974e6d15924SDimitry Andric if (!MaybeRecord)
2975e6d15924SDimitry Andric return MaybeRecord.takeError();
2976e6d15924SDimitry Andric switch (MaybeRecord.get()) {
2977009b1c42SEd Schouten default: // Default behavior: unknown type.
2978009b1c42SEd Schouten break;
297901095a5dSDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
2980b915e9e0SDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2981b915e9e0SDimitry Andric if (Error Err = ValOrErr.takeError())
2982b915e9e0SDimitry Andric return Err;
2983dd58ef01SDimitry Andric ValOrErr.get();
2984dd58ef01SDimitry Andric break;
2985dd58ef01SDimitry Andric }
2986dd58ef01SDimitry Andric case bitc::VST_CODE_FNENTRY: {
298701095a5dSDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2988b915e9e0SDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2989b915e9e0SDimitry Andric if (Error Err = ValOrErr.takeError())
2990b915e9e0SDimitry Andric return Err;
2991dd58ef01SDimitry Andric Value *V = ValOrErr.get();
2992009b1c42SEd Schouten
299371d5a254SDimitry Andric // Ignore function offsets emitted for aliases of functions in older
299471d5a254SDimitry Andric // versions of LLVM.
2995d99dafe2SDimitry Andric if (auto *F = dyn_cast<Function>(V))
2996d99dafe2SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2997009b1c42SEd Schouten break;
2998009b1c42SEd Schouten }
2999009b1c42SEd Schouten case bitc::VST_CODE_BBENTRY: {
30003a0822f0SDimitry Andric if (convertToString(Record, 1, ValueName))
3001145449b1SDimitry Andric return error("Invalid bbentry record");
3002009b1c42SEd Schouten BasicBlock *BB = getBasicBlock(Record[0]);
30035ca98fd9SDimitry Andric if (!BB)
3004145449b1SDimitry Andric return error("Invalid bbentry record");
3005009b1c42SEd Schouten
3006ac9a064cSDimitry Andric BB->setName(ValueName.str());
3007009b1c42SEd Schouten ValueName.clear();
3008009b1c42SEd Schouten break;
3009009b1c42SEd Schouten }
3010009b1c42SEd Schouten }
3011009b1c42SEd Schouten }
3012009b1c42SEd Schouten }
3013009b1c42SEd Schouten
30143a0822f0SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR
30153a0822f0SDimitry Andric /// encoding.
decodeSignRotatedValue(uint64_t V)3016522600a2SDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
3017009b1c42SEd Schouten if ((V & 1) == 0)
3018009b1c42SEd Schouten return V >> 1;
3019009b1c42SEd Schouten if (V != 1)
3020009b1c42SEd Schouten return -(V >> 1);
3021009b1c42SEd Schouten // There is no such thing as -0 with integers. "-0" really means MININT.
3022009b1c42SEd Schouten return 1ULL << 63;
3023009b1c42SEd Schouten }
3024009b1c42SEd Schouten
30253a0822f0SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can.
resolveGlobalAndIndirectSymbolInits()3026b915e9e0SDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
3027009b1c42SEd Schouten std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
3028c0981da4SDimitry Andric std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
3029c0981da4SDimitry Andric std::vector<FunctionOperandInfo> FunctionOperandWorklist;
3030009b1c42SEd Schouten
3031009b1c42SEd Schouten GlobalInitWorklist.swap(GlobalInits);
303201095a5dSDimitry Andric IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
3033c0981da4SDimitry Andric FunctionOperandWorklist.swap(FunctionOperands);
3034009b1c42SEd Schouten
3035009b1c42SEd Schouten while (!GlobalInitWorklist.empty()) {
3036009b1c42SEd Schouten unsigned ValID = GlobalInitWorklist.back().second;
3037009b1c42SEd Schouten if (ValID >= ValueList.size()) {
3038009b1c42SEd Schouten // Not ready to resolve this yet, it requires something later in the file.
3039009b1c42SEd Schouten GlobalInits.push_back(GlobalInitWorklist.back());
3040009b1c42SEd Schouten } else {
3041145449b1SDimitry Andric Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3042145449b1SDimitry Andric if (!MaybeC)
3043145449b1SDimitry Andric return MaybeC.takeError();
3044145449b1SDimitry Andric GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
3045009b1c42SEd Schouten }
3046009b1c42SEd Schouten GlobalInitWorklist.pop_back();
3047009b1c42SEd Schouten }
3048009b1c42SEd Schouten
304901095a5dSDimitry Andric while (!IndirectSymbolInitWorklist.empty()) {
305001095a5dSDimitry Andric unsigned ValID = IndirectSymbolInitWorklist.back().second;
3051009b1c42SEd Schouten if (ValID >= ValueList.size()) {
305201095a5dSDimitry Andric IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
3053009b1c42SEd Schouten } else {
3054145449b1SDimitry Andric Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3055145449b1SDimitry Andric if (!MaybeC)
3056145449b1SDimitry Andric return MaybeC.takeError();
3057145449b1SDimitry Andric Constant *C = MaybeC.get();
3058c0981da4SDimitry Andric GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
3059c0981da4SDimitry Andric if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
3060c0981da4SDimitry Andric if (C->getType() != GV->getType())
30613a0822f0SDimitry Andric return error("Alias and aliasee types don't match");
3062c0981da4SDimitry Andric GA->setAliasee(C);
3063c0981da4SDimitry Andric } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
3064b1c73532SDimitry Andric GI->setResolver(C);
3065c0981da4SDimitry Andric } else {
3066c0981da4SDimitry Andric return error("Expected an alias or an ifunc");
3067c0981da4SDimitry Andric }
3068009b1c42SEd Schouten }
306901095a5dSDimitry Andric IndirectSymbolInitWorklist.pop_back();
3070009b1c42SEd Schouten }
3071f8af5cf6SDimitry Andric
3072c0981da4SDimitry Andric while (!FunctionOperandWorklist.empty()) {
3073c0981da4SDimitry Andric FunctionOperandInfo &Info = FunctionOperandWorklist.back();
3074c0981da4SDimitry Andric if (Info.PersonalityFn) {
3075c0981da4SDimitry Andric unsigned ValID = Info.PersonalityFn - 1;
3076c0981da4SDimitry Andric if (ValID < ValueList.size()) {
3077145449b1SDimitry Andric Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3078145449b1SDimitry Andric if (!MaybeC)
3079145449b1SDimitry Andric return MaybeC.takeError();
3080145449b1SDimitry Andric Info.F->setPersonalityFn(MaybeC.get());
3081c0981da4SDimitry Andric Info.PersonalityFn = 0;
3082f8af5cf6SDimitry Andric }
3083f8af5cf6SDimitry Andric }
3084c0981da4SDimitry Andric if (Info.Prefix) {
3085c0981da4SDimitry Andric unsigned ValID = Info.Prefix - 1;
3086c0981da4SDimitry Andric if (ValID < ValueList.size()) {
3087145449b1SDimitry Andric Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3088145449b1SDimitry Andric if (!MaybeC)
3089145449b1SDimitry Andric return MaybeC.takeError();
3090145449b1SDimitry Andric Info.F->setPrefixData(MaybeC.get());
3091c0981da4SDimitry Andric Info.Prefix = 0;
309267c32a98SDimitry Andric }
309367c32a98SDimitry Andric }
3094c0981da4SDimitry Andric if (Info.Prologue) {
3095c0981da4SDimitry Andric unsigned ValID = Info.Prologue - 1;
3096c0981da4SDimitry Andric if (ValID < ValueList.size()) {
3097145449b1SDimitry Andric Expected<Constant *> MaybeC = getValueForInitializer(ValID);
3098145449b1SDimitry Andric if (!MaybeC)
3099145449b1SDimitry Andric return MaybeC.takeError();
3100145449b1SDimitry Andric Info.F->setPrologueData(MaybeC.get());
3101c0981da4SDimitry Andric Info.Prologue = 0;
31023a0822f0SDimitry Andric }
3103c0981da4SDimitry Andric }
3104c0981da4SDimitry Andric if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
3105c0981da4SDimitry Andric FunctionOperands.push_back(Info);
3106c0981da4SDimitry Andric FunctionOperandWorklist.pop_back();
31073a0822f0SDimitry Andric }
31083a0822f0SDimitry Andric
3109b915e9e0SDimitry Andric return Error::success();
3110009b1c42SEd Schouten }
3111009b1c42SEd Schouten
readWideAPInt(ArrayRef<uint64_t> Vals,unsigned TypeBits)3112cfca06d7SDimitry Andric APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
311358b69754SDimitry Andric SmallVector<uint64_t, 8> Words(Vals.size());
3114b915e9e0SDimitry Andric transform(Vals, Words.begin(),
3115522600a2SDimitry Andric BitcodeReader::decodeSignRotatedValue);
311658b69754SDimitry Andric
311758b69754SDimitry Andric return APInt(TypeBits, Words);
311858b69754SDimitry Andric }
311958b69754SDimitry Andric
parseConstants()3120b915e9e0SDimitry Andric Error BitcodeReader::parseConstants() {
3121e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
3122e6d15924SDimitry Andric return Err;
3123009b1c42SEd Schouten
3124009b1c42SEd Schouten SmallVector<uint64_t, 64> Record;
3125009b1c42SEd Schouten
3126009b1c42SEd Schouten // Read all the records for this value table.
312730815c53SDimitry Andric Type *CurTy = Type::getInt32Ty(Context);
3128145449b1SDimitry Andric unsigned Int32TyID = getVirtualTypeID(CurTy);
3129145449b1SDimitry Andric unsigned CurTyID = Int32TyID;
3130145449b1SDimitry Andric Type *CurElemTy = nullptr;
3131009b1c42SEd Schouten unsigned NextCstNo = ValueList.size();
3132b915e9e0SDimitry Andric
3133b915e9e0SDimitry Andric while (true) {
3134e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3135e6d15924SDimitry Andric if (!MaybeEntry)
3136e6d15924SDimitry Andric return MaybeEntry.takeError();
3137e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
31384a16efa3SDimitry Andric
31394a16efa3SDimitry Andric switch (Entry.Kind) {
31404a16efa3SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
31414a16efa3SDimitry Andric case BitstreamEntry::Error:
31423a0822f0SDimitry Andric return error("Malformed block");
31434a16efa3SDimitry Andric case BitstreamEntry::EndBlock:
31444a16efa3SDimitry Andric if (NextCstNo != ValueList.size())
314501095a5dSDimitry Andric return error("Invalid constant reference");
3146b915e9e0SDimitry Andric return Error::success();
31474a16efa3SDimitry Andric case BitstreamEntry::Record:
31484a16efa3SDimitry Andric // The interesting case.
3149009b1c42SEd Schouten break;
3150009b1c42SEd Schouten }
3151009b1c42SEd Schouten
3152009b1c42SEd Schouten // Read a record.
3153009b1c42SEd Schouten Record.clear();
315401095a5dSDimitry Andric Type *VoidType = Type::getVoidTy(Context);
31555ca98fd9SDimitry Andric Value *V = nullptr;
3156e6d15924SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3157e6d15924SDimitry Andric if (!MaybeBitCode)
3158e6d15924SDimitry Andric return MaybeBitCode.takeError();
3159e6d15924SDimitry Andric switch (unsigned BitCode = MaybeBitCode.get()) {
3160009b1c42SEd Schouten default: // Default behavior: unknown constant
3161009b1c42SEd Schouten case bitc::CST_CODE_UNDEF: // UNDEF
3162009b1c42SEd Schouten V = UndefValue::get(CurTy);
3163009b1c42SEd Schouten break;
3164b60736ecSDimitry Andric case bitc::CST_CODE_POISON: // POISON
3165b60736ecSDimitry Andric V = PoisonValue::get(CurTy);
3166b60736ecSDimitry Andric break;
3167009b1c42SEd Schouten case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
3168009b1c42SEd Schouten if (Record.empty())
3169145449b1SDimitry Andric return error("Invalid settype record");
31705ca98fd9SDimitry Andric if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3171145449b1SDimitry Andric return error("Invalid settype record");
317201095a5dSDimitry Andric if (TypeList[Record[0]] == VoidType)
317301095a5dSDimitry Andric return error("Invalid constant type");
3174145449b1SDimitry Andric CurTyID = Record[0];
3175145449b1SDimitry Andric CurTy = TypeList[CurTyID];
3176145449b1SDimitry Andric CurElemTy = getPtrElementTypeByID(CurTyID);
3177009b1c42SEd Schouten continue; // Skip the ValueList manipulation.
3178009b1c42SEd Schouten case bitc::CST_CODE_NULL: // NULL
31791d5ae102SDimitry Andric if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
31801d5ae102SDimitry Andric return error("Invalid type for a constant null value");
3181e3b55780SDimitry Andric if (auto *TETy = dyn_cast<TargetExtType>(CurTy))
3182e3b55780SDimitry Andric if (!TETy->hasProperty(TargetExtType::HasZeroInit))
3183e3b55780SDimitry Andric return error("Invalid type for a constant null value");
3184009b1c42SEd Schouten V = Constant::getNullValue(CurTy);
3185009b1c42SEd Schouten break;
3186009b1c42SEd Schouten case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
3187ac9a064cSDimitry Andric if (!CurTy->isIntOrIntVectorTy() || Record.empty())
3188145449b1SDimitry Andric return error("Invalid integer const record");
3189522600a2SDimitry Andric V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
3190009b1c42SEd Schouten break;
3191009b1c42SEd Schouten case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
3192ac9a064cSDimitry Andric if (!CurTy->isIntOrIntVectorTy() || Record.empty())
3193145449b1SDimitry Andric return error("Invalid wide integer const record");
3194009b1c42SEd Schouten
3195ac9a064cSDimitry Andric auto *ScalarTy = cast<IntegerType>(CurTy->getScalarType());
3196ac9a064cSDimitry Andric APInt VInt = readWideAPInt(Record, ScalarTy->getBitWidth());
3197ac9a064cSDimitry Andric V = ConstantInt::get(CurTy, VInt);
3198009b1c42SEd Schouten break;
3199009b1c42SEd Schouten }
3200009b1c42SEd Schouten case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
3201009b1c42SEd Schouten if (Record.empty())
3202145449b1SDimitry Andric return error("Invalid float const record");
3203ac9a064cSDimitry Andric
3204ac9a064cSDimitry Andric auto *ScalarTy = CurTy->getScalarType();
3205ac9a064cSDimitry Andric if (ScalarTy->isHalfTy())
3206ac9a064cSDimitry Andric V = ConstantFP::get(CurTy, APFloat(APFloat::IEEEhalf(),
32074a16efa3SDimitry Andric APInt(16, (uint16_t)Record[0])));
3208ac9a064cSDimitry Andric else if (ScalarTy->isBFloatTy())
3209ac9a064cSDimitry Andric V = ConstantFP::get(
3210ac9a064cSDimitry Andric CurTy, APFloat(APFloat::BFloat(), APInt(16, (uint32_t)Record[0])));
3211ac9a064cSDimitry Andric else if (ScalarTy->isFloatTy())
3212ac9a064cSDimitry Andric V = ConstantFP::get(CurTy, APFloat(APFloat::IEEEsingle(),
32134a16efa3SDimitry Andric APInt(32, (uint32_t)Record[0])));
3214ac9a064cSDimitry Andric else if (ScalarTy->isDoubleTy())
3215ac9a064cSDimitry Andric V = ConstantFP::get(
3216ac9a064cSDimitry Andric CurTy, APFloat(APFloat::IEEEdouble(), APInt(64, Record[0])));
3217ac9a064cSDimitry Andric else if (ScalarTy->isX86_FP80Ty()) {
3218009b1c42SEd Schouten // Bits are not stored the same way as a normal i80 APInt, compensate.
3219009b1c42SEd Schouten uint64_t Rearrange[2];
3220009b1c42SEd Schouten Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
3221009b1c42SEd Schouten Rearrange[1] = Record[0] >> 48;
3222ac9a064cSDimitry Andric V = ConstantFP::get(
3223ac9a064cSDimitry Andric CurTy, APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange)));
3224ac9a064cSDimitry Andric } else if (ScalarTy->isFP128Ty())
3225ac9a064cSDimitry Andric V = ConstantFP::get(CurTy,
3226ac9a064cSDimitry Andric APFloat(APFloat::IEEEquad(), APInt(128, Record)));
3227ac9a064cSDimitry Andric else if (ScalarTy->isPPC_FP128Ty())
3228ac9a064cSDimitry Andric V = ConstantFP::get(
3229ac9a064cSDimitry Andric CurTy, APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record)));
3230009b1c42SEd Schouten else
3231ac9a064cSDimitry Andric V = PoisonValue::get(CurTy);
3232009b1c42SEd Schouten break;
3233009b1c42SEd Schouten }
3234009b1c42SEd Schouten
3235009b1c42SEd Schouten case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
3236009b1c42SEd Schouten if (Record.empty())
3237145449b1SDimitry Andric return error("Invalid aggregate record");
3238009b1c42SEd Schouten
3239009b1c42SEd Schouten unsigned Size = Record.size();
3240145449b1SDimitry Andric SmallVector<unsigned, 16> Elts;
3241145449b1SDimitry Andric for (unsigned i = 0; i != Size; ++i)
3242145449b1SDimitry Andric Elts.push_back(Record[i]);
3243009b1c42SEd Schouten
3244145449b1SDimitry Andric if (isa<StructType>(CurTy)) {
3245145449b1SDimitry Andric V = BitcodeConstant::create(
3246145449b1SDimitry Andric Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3247145449b1SDimitry Andric } else if (isa<ArrayType>(CurTy)) {
3248145449b1SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy,
3249145449b1SDimitry Andric BitcodeConstant::ConstantArrayOpcode, Elts);
3250145449b1SDimitry Andric } else if (isa<VectorType>(CurTy)) {
3251145449b1SDimitry Andric V = BitcodeConstant::create(
3252145449b1SDimitry Andric Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3253009b1c42SEd Schouten } else {
3254ac9a064cSDimitry Andric V = PoisonValue::get(CurTy);
3255009b1c42SEd Schouten }
3256009b1c42SEd Schouten break;
3257009b1c42SEd Schouten }
325863faed5bSDimitry Andric case bitc::CST_CODE_STRING: // STRING: [values]
3259009b1c42SEd Schouten case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
3260009b1c42SEd Schouten if (Record.empty())
3261145449b1SDimitry Andric return error("Invalid string record");
3262009b1c42SEd Schouten
326358b69754SDimitry Andric SmallString<16> Elts(Record.begin(), Record.end());
326463faed5bSDimitry Andric V = ConstantDataArray::getString(Context, Elts,
326563faed5bSDimitry Andric BitCode == bitc::CST_CODE_CSTRING);
3266009b1c42SEd Schouten break;
3267009b1c42SEd Schouten }
326863faed5bSDimitry Andric case bitc::CST_CODE_DATA: {// DATA: [n x value]
326963faed5bSDimitry Andric if (Record.empty())
3270145449b1SDimitry Andric return error("Invalid data record");
327163faed5bSDimitry Andric
3272cfca06d7SDimitry Andric Type *EltTy;
3273cfca06d7SDimitry Andric if (auto *Array = dyn_cast<ArrayType>(CurTy))
3274cfca06d7SDimitry Andric EltTy = Array->getElementType();
3275cfca06d7SDimitry Andric else
3276cfca06d7SDimitry Andric EltTy = cast<VectorType>(CurTy)->getElementType();
327763faed5bSDimitry Andric if (EltTy->isIntegerTy(8)) {
327863faed5bSDimitry Andric SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
327963faed5bSDimitry Andric if (isa<VectorType>(CurTy))
328063faed5bSDimitry Andric V = ConstantDataVector::get(Context, Elts);
328163faed5bSDimitry Andric else
328263faed5bSDimitry Andric V = ConstantDataArray::get(Context, Elts);
328363faed5bSDimitry Andric } else if (EltTy->isIntegerTy(16)) {
328463faed5bSDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
328563faed5bSDimitry Andric if (isa<VectorType>(CurTy))
328663faed5bSDimitry Andric V = ConstantDataVector::get(Context, Elts);
328763faed5bSDimitry Andric else
328863faed5bSDimitry Andric V = ConstantDataArray::get(Context, Elts);
328963faed5bSDimitry Andric } else if (EltTy->isIntegerTy(32)) {
329063faed5bSDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
329163faed5bSDimitry Andric if (isa<VectorType>(CurTy))
329263faed5bSDimitry Andric V = ConstantDataVector::get(Context, Elts);
329363faed5bSDimitry Andric else
329463faed5bSDimitry Andric V = ConstantDataArray::get(Context, Elts);
329563faed5bSDimitry Andric } else if (EltTy->isIntegerTy(64)) {
329663faed5bSDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
329763faed5bSDimitry Andric if (isa<VectorType>(CurTy))
329863faed5bSDimitry Andric V = ConstantDataVector::get(Context, Elts);
329963faed5bSDimitry Andric else
330063faed5bSDimitry Andric V = ConstantDataArray::get(Context, Elts);
3301050e163aSDimitry Andric } else if (EltTy->isHalfTy()) {
3302050e163aSDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3303050e163aSDimitry Andric if (isa<VectorType>(CurTy))
3304cfca06d7SDimitry Andric V = ConstantDataVector::getFP(EltTy, Elts);
3305050e163aSDimitry Andric else
3306cfca06d7SDimitry Andric V = ConstantDataArray::getFP(EltTy, Elts);
3307cfca06d7SDimitry Andric } else if (EltTy->isBFloatTy()) {
3308cfca06d7SDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3309cfca06d7SDimitry Andric if (isa<VectorType>(CurTy))
3310cfca06d7SDimitry Andric V = ConstantDataVector::getFP(EltTy, Elts);
3311cfca06d7SDimitry Andric else
3312cfca06d7SDimitry Andric V = ConstantDataArray::getFP(EltTy, Elts);
331363faed5bSDimitry Andric } else if (EltTy->isFloatTy()) {
3314050e163aSDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
331563faed5bSDimitry Andric if (isa<VectorType>(CurTy))
3316cfca06d7SDimitry Andric V = ConstantDataVector::getFP(EltTy, Elts);
331763faed5bSDimitry Andric else
3318cfca06d7SDimitry Andric V = ConstantDataArray::getFP(EltTy, Elts);
331963faed5bSDimitry Andric } else if (EltTy->isDoubleTy()) {
3320050e163aSDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
332163faed5bSDimitry Andric if (isa<VectorType>(CurTy))
3322cfca06d7SDimitry Andric V = ConstantDataVector::getFP(EltTy, Elts);
332363faed5bSDimitry Andric else
3324cfca06d7SDimitry Andric V = ConstantDataArray::getFP(EltTy, Elts);
332563faed5bSDimitry Andric } else {
33263a0822f0SDimitry Andric return error("Invalid type for value");
332763faed5bSDimitry Andric }
332863faed5bSDimitry Andric break;
332963faed5bSDimitry Andric }
3330d8e91e46SDimitry Andric case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
3331d8e91e46SDimitry Andric if (Record.size() < 2)
3332145449b1SDimitry Andric return error("Invalid unary op constexpr record");
3333d8e91e46SDimitry Andric int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
3334d8e91e46SDimitry Andric if (Opc < 0) {
3335ac9a064cSDimitry Andric V = PoisonValue::get(CurTy); // Unknown unop.
3336d8e91e46SDimitry Andric } else {
3337145449b1SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]);
3338d8e91e46SDimitry Andric }
3339d8e91e46SDimitry Andric break;
3340d8e91e46SDimitry Andric }
3341009b1c42SEd Schouten case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
3342f8af5cf6SDimitry Andric if (Record.size() < 3)
3343145449b1SDimitry Andric return error("Invalid binary op constexpr record");
33443a0822f0SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
3345009b1c42SEd Schouten if (Opc < 0) {
3346ac9a064cSDimitry Andric V = PoisonValue::get(CurTy); // Unknown binop.
3347009b1c42SEd Schouten } else {
3348145449b1SDimitry Andric uint8_t Flags = 0;
334959850d08SRoman Divacky if (Record.size() >= 4) {
335059850d08SRoman Divacky if (Opc == Instruction::Add ||
335159850d08SRoman Divacky Opc == Instruction::Sub ||
3352cf099d11SDimitry Andric Opc == Instruction::Mul ||
3353cf099d11SDimitry Andric Opc == Instruction::Shl) {
335459850d08SRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
335559850d08SRoman Divacky Flags |= OverflowingBinaryOperator::NoSignedWrap;
335659850d08SRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
335759850d08SRoman Divacky Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3358cf099d11SDimitry Andric } else if (Opc == Instruction::SDiv ||
3359cf099d11SDimitry Andric Opc == Instruction::UDiv ||
3360cf099d11SDimitry Andric Opc == Instruction::LShr ||
3361cf099d11SDimitry Andric Opc == Instruction::AShr) {
3362cf099d11SDimitry Andric if (Record[3] & (1 << bitc::PEO_EXACT))
3363b1c73532SDimitry Andric Flags |= PossiblyExactOperator::IsExact;
336459850d08SRoman Divacky }
336559850d08SRoman Divacky }
3366145449b1SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags},
3367145449b1SDimitry Andric {(unsigned)Record[1], (unsigned)Record[2]});
3368009b1c42SEd Schouten }
3369009b1c42SEd Schouten break;
3370009b1c42SEd Schouten }
3371009b1c42SEd Schouten case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
3372f8af5cf6SDimitry Andric if (Record.size() < 3)
3373145449b1SDimitry Andric return error("Invalid cast constexpr record");
33743a0822f0SDimitry Andric int Opc = getDecodedCastOpcode(Record[0]);
3375009b1c42SEd Schouten if (Opc < 0) {
3376ac9a064cSDimitry Andric V = PoisonValue::get(CurTy); // Unknown cast.
3377009b1c42SEd Schouten } else {
3378145449b1SDimitry Andric unsigned OpTyID = Record[1];
3379145449b1SDimitry Andric Type *OpTy = getTypeByID(OpTyID);
3380f8af5cf6SDimitry Andric if (!OpTy)
3381145449b1SDimitry Andric return error("Invalid cast constexpr record");
3382145449b1SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]);
3383009b1c42SEd Schouten }
3384009b1c42SEd Schouten break;
3385009b1c42SEd Schouten }
3386b915e9e0SDimitry Andric case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
3387ac9a064cSDimitry Andric case bitc::CST_CODE_CE_GEP_OLD: // [ty, n x operands]
3388ac9a064cSDimitry Andric case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD: // [ty, flags, n x
3389ac9a064cSDimitry Andric // operands]
3390ac9a064cSDimitry Andric case bitc::CST_CODE_CE_GEP: // [ty, flags, n x operands]
3391ac9a064cSDimitry Andric case bitc::CST_CODE_CE_GEP_WITH_INRANGE: { // [ty, flags, start, end, n x
3392b915e9e0SDimitry Andric // operands]
3393145449b1SDimitry Andric if (Record.size() < 2)
3394145449b1SDimitry Andric return error("Constant GEP record must have at least two elements");
33955a5ac124SDimitry Andric unsigned OpNum = 0;
33965a5ac124SDimitry Andric Type *PointeeType = nullptr;
3397ac9a064cSDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD ||
3398ac9a064cSDimitry Andric BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE ||
3399ac9a064cSDimitry Andric BitCode == bitc::CST_CODE_CE_GEP || Record.size() % 2)
34005a5ac124SDimitry Andric PointeeType = getTypeByID(Record[OpNum++]);
3401b915e9e0SDimitry Andric
3402ac9a064cSDimitry Andric uint64_t Flags = 0;
3403ac9a064cSDimitry Andric std::optional<ConstantRange> InRange;
3404ac9a064cSDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX_OLD) {
3405b915e9e0SDimitry Andric uint64_t Op = Record[OpNum++];
3406ac9a064cSDimitry Andric Flags = Op & 1; // inbounds
3407ac9a064cSDimitry Andric unsigned InRangeIndex = Op >> 1;
3408ac9a064cSDimitry Andric // "Upgrade" inrange by dropping it. The feature is too niche to
3409ac9a064cSDimitry Andric // bother.
3410ac9a064cSDimitry Andric (void)InRangeIndex;
3411ac9a064cSDimitry Andric } else if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE) {
3412ac9a064cSDimitry Andric Flags = Record[OpNum++];
3413ac9a064cSDimitry Andric Expected<ConstantRange> MaybeInRange =
3414ac9a064cSDimitry Andric readBitWidthAndConstantRange(Record, OpNum);
3415ac9a064cSDimitry Andric if (!MaybeInRange)
3416ac9a064cSDimitry Andric return MaybeInRange.takeError();
3417ac9a064cSDimitry Andric InRange = MaybeInRange.get();
3418ac9a064cSDimitry Andric } else if (BitCode == bitc::CST_CODE_CE_GEP) {
3419ac9a064cSDimitry Andric Flags = Record[OpNum++];
3420b915e9e0SDimitry Andric } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
3421ac9a064cSDimitry Andric Flags = (1 << bitc::GEP_INBOUNDS);
3422b915e9e0SDimitry Andric
3423145449b1SDimitry Andric SmallVector<unsigned, 16> Elts;
3424145449b1SDimitry Andric unsigned BaseTypeID = Record[OpNum];
34255a5ac124SDimitry Andric while (OpNum != Record.size()) {
3426145449b1SDimitry Andric unsigned ElTyID = Record[OpNum++];
3427145449b1SDimitry Andric Type *ElTy = getTypeByID(ElTyID);
3428f8af5cf6SDimitry Andric if (!ElTy)
3429145449b1SDimitry Andric return error("Invalid getelementptr constexpr record");
3430145449b1SDimitry Andric Elts.push_back(Record[OpNum++]);
3431009b1c42SEd Schouten }
34325a5ac124SDimitry Andric
343301095a5dSDimitry Andric if (Elts.size() < 1)
343401095a5dSDimitry Andric return error("Invalid gep with no operands");
343501095a5dSDimitry Andric
3436145449b1SDimitry Andric Type *BaseType = getTypeByID(BaseTypeID);
3437145449b1SDimitry Andric if (isa<VectorType>(BaseType)) {
3438145449b1SDimitry Andric BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3439145449b1SDimitry Andric BaseType = getTypeByID(BaseTypeID);
3440145449b1SDimitry Andric }
3441145449b1SDimitry Andric
3442145449b1SDimitry Andric PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType);
3443145449b1SDimitry Andric if (!OrigPtrTy)
3444145449b1SDimitry Andric return error("GEP base operand must be pointer or vector of pointer");
3445145449b1SDimitry Andric
3446145449b1SDimitry Andric if (!PointeeType) {
3447145449b1SDimitry Andric PointeeType = getPtrElementTypeByID(BaseTypeID);
3448e6d15924SDimitry Andric if (!PointeeType)
3449145449b1SDimitry Andric return error("Missing element type for old-style constant GEP");
34507fa27ce4SDimitry Andric }
3451e6d15924SDimitry Andric
3452ac9a064cSDimitry Andric V = BitcodeConstant::create(
3453ac9a064cSDimitry Andric Alloc, CurTy,
3454ac9a064cSDimitry Andric {Instruction::GetElementPtr, uint8_t(Flags), PointeeType, InRange},
3455145449b1SDimitry Andric Elts);
3456009b1c42SEd Schouten break;
3457009b1c42SEd Schouten }
3458f8af5cf6SDimitry Andric case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
3459f8af5cf6SDimitry Andric if (Record.size() < 3)
3460145449b1SDimitry Andric return error("Invalid select constexpr record");
3461f8af5cf6SDimitry Andric
3462145449b1SDimitry Andric V = BitcodeConstant::create(
3463145449b1SDimitry Andric Alloc, CurTy, Instruction::Select,
3464145449b1SDimitry Andric {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3465145449b1SDimitry Andric break;
3466f8af5cf6SDimitry Andric }
34675ca98fd9SDimitry Andric case bitc::CST_CODE_CE_EXTRACTELT
34685ca98fd9SDimitry Andric : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3469f8af5cf6SDimitry Andric if (Record.size() < 3)
3470145449b1SDimitry Andric return error("Invalid extractelement constexpr record");
3471145449b1SDimitry Andric unsigned OpTyID = Record[0];
347230815c53SDimitry Andric VectorType *OpTy =
3473145449b1SDimitry Andric dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
34745ca98fd9SDimitry Andric if (!OpTy)
3475145449b1SDimitry Andric return error("Invalid extractelement constexpr record");
3476145449b1SDimitry Andric unsigned IdxRecord;
34775ca98fd9SDimitry Andric if (Record.size() == 4) {
3478145449b1SDimitry Andric unsigned IdxTyID = Record[2];
3479145449b1SDimitry Andric Type *IdxTy = getTypeByID(IdxTyID);
34805ca98fd9SDimitry Andric if (!IdxTy)
3481145449b1SDimitry Andric return error("Invalid extractelement constexpr record");
3482145449b1SDimitry Andric IdxRecord = Record[3];
3483cfca06d7SDimitry Andric } else {
3484cfca06d7SDimitry Andric // Deprecated, but still needed to read old bitcode files.
3485145449b1SDimitry Andric IdxRecord = Record[2];
3486cfca06d7SDimitry Andric }
3487145449b1SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
3488145449b1SDimitry Andric {(unsigned)Record[1], IdxRecord});
3489009b1c42SEd Schouten break;
3490009b1c42SEd Schouten }
34915ca98fd9SDimitry Andric case bitc::CST_CODE_CE_INSERTELT
34925ca98fd9SDimitry Andric : { // CE_INSERTELT: [opval, opval, opty, opval]
349330815c53SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy);
34945ca98fd9SDimitry Andric if (Record.size() < 3 || !OpTy)
3495145449b1SDimitry Andric return error("Invalid insertelement constexpr record");
3496145449b1SDimitry Andric unsigned IdxRecord;
34975ca98fd9SDimitry Andric if (Record.size() == 4) {
3498145449b1SDimitry Andric unsigned IdxTyID = Record[2];
3499145449b1SDimitry Andric Type *IdxTy = getTypeByID(IdxTyID);
35005ca98fd9SDimitry Andric if (!IdxTy)
3501145449b1SDimitry Andric return error("Invalid insertelement constexpr record");
3502145449b1SDimitry Andric IdxRecord = Record[3];
3503cfca06d7SDimitry Andric } else {
3504cfca06d7SDimitry Andric // Deprecated, but still needed to read old bitcode files.
3505145449b1SDimitry Andric IdxRecord = Record[2];
3506cfca06d7SDimitry Andric }
3507145449b1SDimitry Andric V = BitcodeConstant::create(
3508145449b1SDimitry Andric Alloc, CurTy, Instruction::InsertElement,
3509145449b1SDimitry Andric {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
3510009b1c42SEd Schouten break;
3511009b1c42SEd Schouten }
3512009b1c42SEd Schouten case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
351330815c53SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy);
35145ca98fd9SDimitry Andric if (Record.size() < 3 || !OpTy)
3515145449b1SDimitry Andric return error("Invalid shufflevector constexpr record");
3516145449b1SDimitry Andric V = BitcodeConstant::create(
3517145449b1SDimitry Andric Alloc, CurTy, Instruction::ShuffleVector,
3518145449b1SDimitry Andric {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3519145449b1SDimitry Andric break;
3520009b1c42SEd Schouten }
3521009b1c42SEd Schouten case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
352230815c53SDimitry Andric VectorType *RTy = dyn_cast<VectorType>(CurTy);
352330815c53SDimitry Andric VectorType *OpTy =
3524cf099d11SDimitry Andric dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
35255ca98fd9SDimitry Andric if (Record.size() < 4 || !RTy || !OpTy)
3526145449b1SDimitry Andric return error("Invalid shufflevector constexpr record");
3527145449b1SDimitry Andric V = BitcodeConstant::create(
3528145449b1SDimitry Andric Alloc, CurTy, Instruction::ShuffleVector,
3529145449b1SDimitry Andric {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]});
3530145449b1SDimitry Andric break;
3531009b1c42SEd Schouten }
3532009b1c42SEd Schouten case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
3533f8af5cf6SDimitry Andric if (Record.size() < 4)
3534145449b1SDimitry Andric return error("Invalid cmp constexpt record");
3535145449b1SDimitry Andric unsigned OpTyID = Record[0];
3536145449b1SDimitry Andric Type *OpTy = getTypeByID(OpTyID);
35375ca98fd9SDimitry Andric if (!OpTy)
3538145449b1SDimitry Andric return error("Invalid cmp constexpr record");
3539145449b1SDimitry Andric V = BitcodeConstant::create(
3540145449b1SDimitry Andric Alloc, CurTy,
3541145449b1SDimitry Andric {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
3542145449b1SDimitry Andric : Instruction::ICmp),
3543145449b1SDimitry Andric (uint8_t)Record[3]},
3544145449b1SDimitry Andric {(unsigned)Record[1], (unsigned)Record[2]});
3545009b1c42SEd Schouten break;
3546009b1c42SEd Schouten }
3547522600a2SDimitry Andric // This maintains backward compatibility, pre-asm dialect keywords.
3548cfca06d7SDimitry Andric // Deprecated, but still needed to read old bitcode files.
3549522600a2SDimitry Andric case bitc::CST_CODE_INLINEASM_OLD: {
3550f8af5cf6SDimitry Andric if (Record.size() < 2)
3551145449b1SDimitry Andric return error("Invalid inlineasm record");
3552009b1c42SEd Schouten std::string AsmStr, ConstrStr;
355359850d08SRoman Divacky bool HasSideEffects = Record[0] & 1;
35544a142eb2SRoman Divacky bool IsAlignStack = Record[0] >> 1;
3555009b1c42SEd Schouten unsigned AsmStrSize = Record[1];
3556009b1c42SEd Schouten if (2+AsmStrSize >= Record.size())
3557145449b1SDimitry Andric return error("Invalid inlineasm record");
3558009b1c42SEd Schouten unsigned ConstStrSize = Record[2+AsmStrSize];
3559009b1c42SEd Schouten if (3+AsmStrSize+ConstStrSize > Record.size())
3560145449b1SDimitry Andric return error("Invalid inlineasm record");
3561009b1c42SEd Schouten
3562009b1c42SEd Schouten for (unsigned i = 0; i != AsmStrSize; ++i)
3563009b1c42SEd Schouten AsmStr += (char)Record[2+i];
3564009b1c42SEd Schouten for (unsigned i = 0; i != ConstStrSize; ++i)
3565009b1c42SEd Schouten ConstrStr += (char)Record[3+AsmStrSize+i];
3566eb11fae6SDimitry Andric UpgradeInlineAsmString(&AsmStr);
3567145449b1SDimitry Andric if (!CurElemTy)
3568145449b1SDimitry Andric return error("Missing element type for old-style inlineasm");
3569145449b1SDimitry Andric V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3570145449b1SDimitry Andric HasSideEffects, IsAlignStack);
3571009b1c42SEd Schouten break;
3572009b1c42SEd Schouten }
3573522600a2SDimitry Andric // This version adds support for the asm dialect keywords (e.g.,
3574522600a2SDimitry Andric // inteldialect).
3575344a3780SDimitry Andric case bitc::CST_CODE_INLINEASM_OLD2: {
3576f8af5cf6SDimitry Andric if (Record.size() < 2)
3577145449b1SDimitry Andric return error("Invalid inlineasm record");
3578522600a2SDimitry Andric std::string AsmStr, ConstrStr;
3579522600a2SDimitry Andric bool HasSideEffects = Record[0] & 1;
3580522600a2SDimitry Andric bool IsAlignStack = (Record[0] >> 1) & 1;
3581522600a2SDimitry Andric unsigned AsmDialect = Record[0] >> 2;
3582522600a2SDimitry Andric unsigned AsmStrSize = Record[1];
3583522600a2SDimitry Andric if (2+AsmStrSize >= Record.size())
3584145449b1SDimitry Andric return error("Invalid inlineasm record");
3585522600a2SDimitry Andric unsigned ConstStrSize = Record[2+AsmStrSize];
3586522600a2SDimitry Andric if (3+AsmStrSize+ConstStrSize > Record.size())
3587145449b1SDimitry Andric return error("Invalid inlineasm record");
3588522600a2SDimitry Andric
3589522600a2SDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i)
3590522600a2SDimitry Andric AsmStr += (char)Record[2+i];
3591522600a2SDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i)
3592522600a2SDimitry Andric ConstrStr += (char)Record[3+AsmStrSize+i];
3593eb11fae6SDimitry Andric UpgradeInlineAsmString(&AsmStr);
3594145449b1SDimitry Andric if (!CurElemTy)
3595145449b1SDimitry Andric return error("Missing element type for old-style inlineasm");
3596145449b1SDimitry Andric V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3597145449b1SDimitry Andric HasSideEffects, IsAlignStack,
3598522600a2SDimitry Andric InlineAsm::AsmDialect(AsmDialect));
3599522600a2SDimitry Andric break;
3600522600a2SDimitry Andric }
3601344a3780SDimitry Andric // This version adds support for the unwind keyword.
36026f8fc217SDimitry Andric case bitc::CST_CODE_INLINEASM_OLD3: {
3603344a3780SDimitry Andric if (Record.size() < 2)
3604145449b1SDimitry Andric return error("Invalid inlineasm record");
36056f8fc217SDimitry Andric unsigned OpNum = 0;
3606344a3780SDimitry Andric std::string AsmStr, ConstrStr;
36076f8fc217SDimitry Andric bool HasSideEffects = Record[OpNum] & 1;
36086f8fc217SDimitry Andric bool IsAlignStack = (Record[OpNum] >> 1) & 1;
36096f8fc217SDimitry Andric unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
36106f8fc217SDimitry Andric bool CanThrow = (Record[OpNum] >> 3) & 1;
36116f8fc217SDimitry Andric ++OpNum;
36126f8fc217SDimitry Andric unsigned AsmStrSize = Record[OpNum];
36136f8fc217SDimitry Andric ++OpNum;
36146f8fc217SDimitry Andric if (OpNum + AsmStrSize >= Record.size())
3615145449b1SDimitry Andric return error("Invalid inlineasm record");
36166f8fc217SDimitry Andric unsigned ConstStrSize = Record[OpNum + AsmStrSize];
36176f8fc217SDimitry Andric if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3618145449b1SDimitry Andric return error("Invalid inlineasm record");
3619344a3780SDimitry Andric
3620344a3780SDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i)
36216f8fc217SDimitry Andric AsmStr += (char)Record[OpNum + i];
36226f8fc217SDimitry Andric ++OpNum;
3623344a3780SDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i)
36246f8fc217SDimitry Andric ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3625344a3780SDimitry Andric UpgradeInlineAsmString(&AsmStr);
3626145449b1SDimitry Andric if (!CurElemTy)
3627145449b1SDimitry Andric return error("Missing element type for old-style inlineasm");
3628145449b1SDimitry Andric V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3629145449b1SDimitry Andric HasSideEffects, IsAlignStack,
3630344a3780SDimitry Andric InlineAsm::AsmDialect(AsmDialect), CanThrow);
3631344a3780SDimitry Andric break;
3632344a3780SDimitry Andric }
36336f8fc217SDimitry Andric // This version adds explicit function type.
36346f8fc217SDimitry Andric case bitc::CST_CODE_INLINEASM: {
36356f8fc217SDimitry Andric if (Record.size() < 3)
3636145449b1SDimitry Andric return error("Invalid inlineasm record");
36376f8fc217SDimitry Andric unsigned OpNum = 0;
36386f8fc217SDimitry Andric auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
36396f8fc217SDimitry Andric ++OpNum;
36406f8fc217SDimitry Andric if (!FnTy)
3641145449b1SDimitry Andric return error("Invalid inlineasm record");
36426f8fc217SDimitry Andric std::string AsmStr, ConstrStr;
36436f8fc217SDimitry Andric bool HasSideEffects = Record[OpNum] & 1;
36446f8fc217SDimitry Andric bool IsAlignStack = (Record[OpNum] >> 1) & 1;
36456f8fc217SDimitry Andric unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
36466f8fc217SDimitry Andric bool CanThrow = (Record[OpNum] >> 3) & 1;
36476f8fc217SDimitry Andric ++OpNum;
36486f8fc217SDimitry Andric unsigned AsmStrSize = Record[OpNum];
36496f8fc217SDimitry Andric ++OpNum;
36506f8fc217SDimitry Andric if (OpNum + AsmStrSize >= Record.size())
3651145449b1SDimitry Andric return error("Invalid inlineasm record");
36526f8fc217SDimitry Andric unsigned ConstStrSize = Record[OpNum + AsmStrSize];
36536f8fc217SDimitry Andric if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3654145449b1SDimitry Andric return error("Invalid inlineasm record");
36556f8fc217SDimitry Andric
36566f8fc217SDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i)
36576f8fc217SDimitry Andric AsmStr += (char)Record[OpNum + i];
36586f8fc217SDimitry Andric ++OpNum;
36596f8fc217SDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i)
36606f8fc217SDimitry Andric ConstrStr += (char)Record[OpNum + AsmStrSize + i];
36616f8fc217SDimitry Andric UpgradeInlineAsmString(&AsmStr);
36626f8fc217SDimitry Andric V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
36636f8fc217SDimitry Andric InlineAsm::AsmDialect(AsmDialect), CanThrow);
36646f8fc217SDimitry Andric break;
36656f8fc217SDimitry Andric }
366636bf506aSRoman Divacky case bitc::CST_CODE_BLOCKADDRESS:{
3667f8af5cf6SDimitry Andric if (Record.size() < 3)
3668145449b1SDimitry Andric return error("Invalid blockaddress record");
3669145449b1SDimitry Andric unsigned FnTyID = Record[0];
3670145449b1SDimitry Andric Type *FnTy = getTypeByID(FnTyID);
36715ca98fd9SDimitry Andric if (!FnTy)
3672145449b1SDimitry Andric return error("Invalid blockaddress record");
3673145449b1SDimitry Andric V = BitcodeConstant::create(
3674145449b1SDimitry Andric Alloc, CurTy,
3675145449b1SDimitry Andric {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3676145449b1SDimitry Andric Record[1]);
367736bf506aSRoman Divacky break;
367836bf506aSRoman Divacky }
3679344a3780SDimitry Andric case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
3680344a3780SDimitry Andric if (Record.size() < 2)
3681145449b1SDimitry Andric return error("Invalid dso_local record");
3682145449b1SDimitry Andric unsigned GVTyID = Record[0];
3683145449b1SDimitry Andric Type *GVTy = getTypeByID(GVTyID);
3684344a3780SDimitry Andric if (!GVTy)
3685145449b1SDimitry Andric return error("Invalid dso_local record");
3686145449b1SDimitry Andric V = BitcodeConstant::create(
3687145449b1SDimitry Andric Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3688344a3780SDimitry Andric break;
3689344a3780SDimitry Andric }
369077fc4c14SDimitry Andric case bitc::CST_CODE_NO_CFI_VALUE: {
369177fc4c14SDimitry Andric if (Record.size() < 2)
3692145449b1SDimitry Andric return error("Invalid no_cfi record");
3693145449b1SDimitry Andric unsigned GVTyID = Record[0];
3694145449b1SDimitry Andric Type *GVTy = getTypeByID(GVTyID);
369577fc4c14SDimitry Andric if (!GVTy)
3696145449b1SDimitry Andric return error("Invalid no_cfi record");
3697145449b1SDimitry Andric V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3698145449b1SDimitry Andric Record[1]);
369977fc4c14SDimitry Andric break;
370077fc4c14SDimitry Andric }
3701ac9a064cSDimitry Andric case bitc::CST_CODE_PTRAUTH: {
3702ac9a064cSDimitry Andric if (Record.size() < 4)
3703ac9a064cSDimitry Andric return error("Invalid ptrauth record");
3704ac9a064cSDimitry Andric // Ptr, Key, Disc, AddrDisc
3705ac9a064cSDimitry Andric V = BitcodeConstant::create(Alloc, CurTy,
3706ac9a064cSDimitry Andric BitcodeConstant::ConstantPtrAuthOpcode,
3707ac9a064cSDimitry Andric {(unsigned)Record[0], (unsigned)Record[1],
3708ac9a064cSDimitry Andric (unsigned)Record[2], (unsigned)Record[3]});
3709ac9a064cSDimitry Andric break;
3710ac9a064cSDimitry Andric }
3711009b1c42SEd Schouten }
3712009b1c42SEd Schouten
3713145449b1SDimitry Andric assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
3714145449b1SDimitry Andric if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))
3715145449b1SDimitry Andric return Err;
3716009b1c42SEd Schouten ++NextCstNo;
3717009b1c42SEd Schouten }
3718009b1c42SEd Schouten }
3719009b1c42SEd Schouten
parseUseLists()3720b915e9e0SDimitry Andric Error BitcodeReader::parseUseLists() {
3721e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3722e6d15924SDimitry Andric return Err;
372363faed5bSDimitry Andric
372463faed5bSDimitry Andric // Read all the records.
372567c32a98SDimitry Andric SmallVector<uint64_t, 64> Record;
3726b915e9e0SDimitry Andric
3727b915e9e0SDimitry Andric while (true) {
3728e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3729e6d15924SDimitry Andric if (!MaybeEntry)
3730e6d15924SDimitry Andric return MaybeEntry.takeError();
3731e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
37324a16efa3SDimitry Andric
37334a16efa3SDimitry Andric switch (Entry.Kind) {
37344a16efa3SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
37354a16efa3SDimitry Andric case BitstreamEntry::Error:
37363a0822f0SDimitry Andric return error("Malformed block");
37374a16efa3SDimitry Andric case BitstreamEntry::EndBlock:
3738b915e9e0SDimitry Andric return Error::success();
37394a16efa3SDimitry Andric case BitstreamEntry::Record:
37404a16efa3SDimitry Andric // The interesting case.
37414a16efa3SDimitry Andric break;
374263faed5bSDimitry Andric }
374363faed5bSDimitry Andric
374463faed5bSDimitry Andric // Read a use list record.
374563faed5bSDimitry Andric Record.clear();
374667c32a98SDimitry Andric bool IsBB = false;
3747e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3748e6d15924SDimitry Andric if (!MaybeRecord)
3749e6d15924SDimitry Andric return MaybeRecord.takeError();
3750e6d15924SDimitry Andric switch (MaybeRecord.get()) {
375163faed5bSDimitry Andric default: // Default behavior: unknown type.
375263faed5bSDimitry Andric break;
375367c32a98SDimitry Andric case bitc::USELIST_CODE_BB:
375467c32a98SDimitry Andric IsBB = true;
3755e3b55780SDimitry Andric [[fallthrough]];
375667c32a98SDimitry Andric case bitc::USELIST_CODE_DEFAULT: {
375763faed5bSDimitry Andric unsigned RecordLength = Record.size();
375867c32a98SDimitry Andric if (RecordLength < 3)
375967c32a98SDimitry Andric // Records should have at least an ID and two indexes.
37603a0822f0SDimitry Andric return error("Invalid record");
3761b60736ecSDimitry Andric unsigned ID = Record.pop_back_val();
376267c32a98SDimitry Andric
376367c32a98SDimitry Andric Value *V;
376467c32a98SDimitry Andric if (IsBB) {
376567c32a98SDimitry Andric assert(ID < FunctionBBs.size() && "Basic block not found");
376667c32a98SDimitry Andric V = FunctionBBs[ID];
376767c32a98SDimitry Andric } else
376867c32a98SDimitry Andric V = ValueList[ID];
376967c32a98SDimitry Andric unsigned NumUses = 0;
377067c32a98SDimitry Andric SmallDenseMap<const Use *, unsigned, 16> Order;
3771dd58ef01SDimitry Andric for (const Use &U : V->materialized_uses()) {
377267c32a98SDimitry Andric if (++NumUses > Record.size())
377367c32a98SDimitry Andric break;
377467c32a98SDimitry Andric Order[&U] = Record[NumUses - 1];
377567c32a98SDimitry Andric }
377667c32a98SDimitry Andric if (Order.size() != Record.size() || NumUses > Record.size())
377767c32a98SDimitry Andric // Mismatches can happen if the functions are being materialized lazily
377867c32a98SDimitry Andric // (out-of-order), or a value has been upgraded.
377967c32a98SDimitry Andric break;
378067c32a98SDimitry Andric
378167c32a98SDimitry Andric V->sortUseList([&](const Use &L, const Use &R) {
378267c32a98SDimitry Andric return Order.lookup(&L) < Order.lookup(&R);
378367c32a98SDimitry Andric });
378463faed5bSDimitry Andric break;
378563faed5bSDimitry Andric }
378663faed5bSDimitry Andric }
378763faed5bSDimitry Andric }
378863faed5bSDimitry Andric }
378963faed5bSDimitry Andric
37905a5ac124SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it.
37915a5ac124SDimitry Andric /// This lets us lazily deserialize the metadata.
rememberAndSkipMetadata()3792b915e9e0SDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() {
37935a5ac124SDimitry Andric // Save the current stream state.
37945a5ac124SDimitry Andric uint64_t CurBit = Stream.GetCurrentBitNo();
37955a5ac124SDimitry Andric DeferredMetadataInfo.push_back(CurBit);
37965a5ac124SDimitry Andric
37975a5ac124SDimitry Andric // Skip over the block for now.
3798e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
3799e6d15924SDimitry Andric return Err;
3800b915e9e0SDimitry Andric return Error::success();
38015a5ac124SDimitry Andric }
38025a5ac124SDimitry Andric
materializeMetadata()3803b915e9e0SDimitry Andric Error BitcodeReader::materializeMetadata() {
38045a5ac124SDimitry Andric for (uint64_t BitPos : DeferredMetadataInfo) {
38055a5ac124SDimitry Andric // Move the bit stream to the saved position.
3806e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(BitPos))
3807e6d15924SDimitry Andric return JumpFailed;
3808b915e9e0SDimitry Andric if (Error Err = MDLoader->parseModuleMetadata())
3809b915e9e0SDimitry Andric return Err;
38105a5ac124SDimitry Andric }
38117c7aba6eSDimitry Andric
38127c7aba6eSDimitry Andric // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3813b60736ecSDimitry Andric // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3814b60736ecSDimitry Andric // multiple times.
3815b60736ecSDimitry Andric if (!TheModule->getNamedMetadata("llvm.linker.options")) {
38167c7aba6eSDimitry Andric if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
38177c7aba6eSDimitry Andric NamedMDNode *LinkerOpts =
38187c7aba6eSDimitry Andric TheModule->getOrInsertNamedMetadata("llvm.linker.options");
38197c7aba6eSDimitry Andric for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
38207c7aba6eSDimitry Andric LinkerOpts->addOperand(cast<MDNode>(MDOptions));
38217c7aba6eSDimitry Andric }
3822b60736ecSDimitry Andric }
38237c7aba6eSDimitry Andric
38245a5ac124SDimitry Andric DeferredMetadataInfo.clear();
3825b915e9e0SDimitry Andric return Error::success();
38265a5ac124SDimitry Andric }
38275a5ac124SDimitry Andric
setStripDebugInfo()38285a5ac124SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
38295a5ac124SDimitry Andric
38303a0822f0SDimitry Andric /// When we see the block for a function body, remember where it is and then
38313a0822f0SDimitry Andric /// skip it. This lets us lazily deserialize the functions.
rememberAndSkipFunctionBody()3832b915e9e0SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() {
3833009b1c42SEd Schouten // Get the function we are talking about.
3834009b1c42SEd Schouten if (FunctionsWithBodies.empty())
38353a0822f0SDimitry Andric return error("Insufficient function protos");
3836009b1c42SEd Schouten
3837009b1c42SEd Schouten Function *Fn = FunctionsWithBodies.back();
3838009b1c42SEd Schouten FunctionsWithBodies.pop_back();
3839009b1c42SEd Schouten
3840009b1c42SEd Schouten // Save the current stream state.
3841009b1c42SEd Schouten uint64_t CurBit = Stream.GetCurrentBitNo();
3842dd58ef01SDimitry Andric assert(
3843dd58ef01SDimitry Andric (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3844dd58ef01SDimitry Andric "Mismatch between VST and scanned function offsets");
38456fe5c7aaSRoman Divacky DeferredFunctionInfo[Fn] = CurBit;
3846009b1c42SEd Schouten
3847009b1c42SEd Schouten // Skip over the function block for now.
3848e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
3849e6d15924SDimitry Andric return Err;
3850b915e9e0SDimitry Andric return Error::success();
3851009b1c42SEd Schouten }
3852009b1c42SEd Schouten
globalCleanup()3853b915e9e0SDimitry Andric Error BitcodeReader::globalCleanup() {
3854009b1c42SEd Schouten // Patch the initializers for globals and aliases up.
3855b915e9e0SDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits())
3856b915e9e0SDimitry Andric return Err;
385701095a5dSDimitry Andric if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
38583a0822f0SDimitry Andric return error("Malformed global initializer set");
3859009b1c42SEd Schouten
3860009b1c42SEd Schouten // Look for intrinsic functions which need to be upgraded at some point
3861cfca06d7SDimitry Andric // and functions that need to have their function attributes upgraded.
38623a0822f0SDimitry Andric for (Function &F : *TheModule) {
3863d99dafe2SDimitry Andric MDLoader->upgradeDebugIntrinsics(F);
3864009b1c42SEd Schouten Function *NewFn;
3865ac9a064cSDimitry Andric // If PreserveInputDbgFormat=true, then we don't know whether we want
3866ac9a064cSDimitry Andric // intrinsics or records, and we won't perform any conversions in either
3867ac9a064cSDimitry Andric // case, so don't upgrade intrinsics to records.
3868ac9a064cSDimitry Andric if (UpgradeIntrinsicFunction(
3869ac9a064cSDimitry Andric &F, NewFn, PreserveInputDbgFormat != cl::boolOrDefault::BOU_TRUE))
38701a82d4c0SDimitry Andric UpgradedIntrinsics[&F] = NewFn;
3871cfca06d7SDimitry Andric // Look for functions that rely on old function attribute behavior.
3872cfca06d7SDimitry Andric UpgradeFunctionAttributes(F);
3873009b1c42SEd Schouten }
3874009b1c42SEd Schouten
3875d39c594dSDimitry Andric // Look for global variables which need to be renamed.
3876e6d15924SDimitry Andric std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
38773a0822f0SDimitry Andric for (GlobalVariable &GV : TheModule->globals())
3878e6d15924SDimitry Andric if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
3879e6d15924SDimitry Andric UpgradedVariables.emplace_back(&GV, Upgraded);
3880e6d15924SDimitry Andric for (auto &Pair : UpgradedVariables) {
3881e6d15924SDimitry Andric Pair.first->eraseFromParent();
38827fa27ce4SDimitry Andric TheModule->insertGlobalVariable(Pair.second);
3883e6d15924SDimitry Andric }
38845ca98fd9SDimitry Andric
3885009b1c42SEd Schouten // Force deallocation of memory for these vectors to favor the client that
3886009b1c42SEd Schouten // want lazy deserialization.
3887009b1c42SEd Schouten std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3888c0981da4SDimitry Andric std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
3889b915e9e0SDimitry Andric return Error::success();
3890009b1c42SEd Schouten }
3891009b1c42SEd Schouten
3892dd58ef01SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we
3893dd58ef01SDimitry Andric /// either have an old bitcode file without a VST forward declaration record,
3894dd58ef01SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous
3895dd58ef01SDimitry Andric /// functions do not have a name and are therefore not in the VST.
rememberAndSkipFunctionBodies()3896b915e9e0SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() {
3897e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3898e6d15924SDimitry Andric return JumpFailed;
3899dd58ef01SDimitry Andric
3900dd58ef01SDimitry Andric if (Stream.AtEndOfStream())
3901dd58ef01SDimitry Andric return error("Could not find function in stream");
3902dd58ef01SDimitry Andric
3903dd58ef01SDimitry Andric if (!SeenFirstFunctionBody)
3904dd58ef01SDimitry Andric return error("Trying to materialize functions before seeing function blocks");
3905dd58ef01SDimitry Andric
3906dd58ef01SDimitry Andric // An old bitcode file with the symbol table at the end would have
3907dd58ef01SDimitry Andric // finished the parse greedily.
3908dd58ef01SDimitry Andric assert(SeenValueSymbolTable);
3909dd58ef01SDimitry Andric
3910dd58ef01SDimitry Andric SmallVector<uint64_t, 64> Record;
3911dd58ef01SDimitry Andric
3912b915e9e0SDimitry Andric while (true) {
3913e6d15924SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3914e6d15924SDimitry Andric if (!MaybeEntry)
3915e6d15924SDimitry Andric return MaybeEntry.takeError();
3916e6d15924SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get();
3917e6d15924SDimitry Andric
3918dd58ef01SDimitry Andric switch (Entry.Kind) {
3919dd58ef01SDimitry Andric default:
3920dd58ef01SDimitry Andric return error("Expect SubBlock");
3921dd58ef01SDimitry Andric case BitstreamEntry::SubBlock:
3922dd58ef01SDimitry Andric switch (Entry.ID) {
3923dd58ef01SDimitry Andric default:
3924dd58ef01SDimitry Andric return error("Expect function block");
3925dd58ef01SDimitry Andric case bitc::FUNCTION_BLOCK_ID:
3926b915e9e0SDimitry Andric if (Error Err = rememberAndSkipFunctionBody())
3927b915e9e0SDimitry Andric return Err;
3928dd58ef01SDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo();
3929b915e9e0SDimitry Andric return Error::success();
3930dd58ef01SDimitry Andric }
3931dd58ef01SDimitry Andric }
3932dd58ef01SDimitry Andric }
3933dd58ef01SDimitry Andric }
3934dd58ef01SDimitry Andric
readBlockInfo()3935145449b1SDimitry Andric Error BitcodeReaderBase::readBlockInfo() {
3936e3b55780SDimitry Andric Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
3937e6d15924SDimitry Andric Stream.ReadBlockInfoBlock();
3938e6d15924SDimitry Andric if (!MaybeNewBlockInfo)
3939145449b1SDimitry Andric return MaybeNewBlockInfo.takeError();
3940e3b55780SDimitry Andric std::optional<BitstreamBlockInfo> NewBlockInfo =
3941e6d15924SDimitry Andric std::move(MaybeNewBlockInfo.get());
3942b915e9e0SDimitry Andric if (!NewBlockInfo)
3943145449b1SDimitry Andric return error("Malformed block");
3944b915e9e0SDimitry Andric BlockInfo = std::move(*NewBlockInfo);
3945145449b1SDimitry Andric return Error::success();
3946dd58ef01SDimitry Andric }
3947dd58ef01SDimitry Andric
parseComdatRecord(ArrayRef<uint64_t> Record)394871d5a254SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
3949d99dafe2SDimitry Andric // v1: [selection_kind, name]
3950d99dafe2SDimitry Andric // v2: [strtab_offset, strtab_size, selection_kind]
3951d99dafe2SDimitry Andric StringRef Name;
3952d99dafe2SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record);
3953d99dafe2SDimitry Andric
3954044eb2f6SDimitry Andric if (Record.empty())
395571d5a254SDimitry Andric return error("Invalid record");
395671d5a254SDimitry Andric Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3957d99dafe2SDimitry Andric std::string OldFormatName;
3958d99dafe2SDimitry Andric if (!UseStrtab) {
3959d99dafe2SDimitry Andric if (Record.size() < 2)
3960d99dafe2SDimitry Andric return error("Invalid record");
396171d5a254SDimitry Andric unsigned ComdatNameSize = Record[1];
3962145449b1SDimitry Andric if (ComdatNameSize > Record.size() - 2)
3963145449b1SDimitry Andric return error("Comdat name size too large");
3964d99dafe2SDimitry Andric OldFormatName.reserve(ComdatNameSize);
396571d5a254SDimitry Andric for (unsigned i = 0; i != ComdatNameSize; ++i)
3966d99dafe2SDimitry Andric OldFormatName += (char)Record[2 + i];
3967d99dafe2SDimitry Andric Name = OldFormatName;
3968d99dafe2SDimitry Andric }
396971d5a254SDimitry Andric Comdat *C = TheModule->getOrInsertComdat(Name);
397071d5a254SDimitry Andric C->setSelectionKind(SK);
397171d5a254SDimitry Andric ComdatList.push_back(C);
397271d5a254SDimitry Andric return Error::success();
397371d5a254SDimitry Andric }
397471d5a254SDimitry Andric
inferDSOLocal(GlobalValue * GV)3975eb11fae6SDimitry Andric static void inferDSOLocal(GlobalValue *GV) {
3976eb11fae6SDimitry Andric // infer dso_local from linkage and visibility if it is not encoded.
3977eb11fae6SDimitry Andric if (GV->hasLocalLinkage() ||
3978eb11fae6SDimitry Andric (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
3979eb11fae6SDimitry Andric GV->setDSOLocal(true);
3980eb11fae6SDimitry Andric }
3981eb11fae6SDimitry Andric
deserializeSanitizerMetadata(unsigned V)3982145449b1SDimitry Andric GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) {
3983145449b1SDimitry Andric GlobalValue::SanitizerMetadata Meta;
3984145449b1SDimitry Andric if (V & (1 << 0))
3985145449b1SDimitry Andric Meta.NoAddress = true;
3986145449b1SDimitry Andric if (V & (1 << 1))
3987145449b1SDimitry Andric Meta.NoHWAddress = true;
3988145449b1SDimitry Andric if (V & (1 << 2))
39891f917f69SDimitry Andric Meta.Memtag = true;
3990145449b1SDimitry Andric if (V & (1 << 3))
3991145449b1SDimitry Andric Meta.IsDynInit = true;
3992145449b1SDimitry Andric return Meta;
3993145449b1SDimitry Andric }
3994145449b1SDimitry Andric
parseGlobalVarRecord(ArrayRef<uint64_t> Record)399571d5a254SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
3996d99dafe2SDimitry Andric // v1: [pointer type, isconst, initid, linkage, alignment, section,
399771d5a254SDimitry Andric // visibility, threadlocal, unnamed_addr, externally_initialized,
3998e6d15924SDimitry Andric // dllstorageclass, comdat, attributes, preemption specifier,
3999e6d15924SDimitry Andric // partition strtab offset, partition strtab size] (name in VST)
4000d99dafe2SDimitry Andric // v2: [strtab_offset, strtab_size, v1]
4001b1c73532SDimitry Andric // v3: [v2, code_model]
4002d99dafe2SDimitry Andric StringRef Name;
4003d99dafe2SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record);
4004d99dafe2SDimitry Andric
400571d5a254SDimitry Andric if (Record.size() < 6)
400671d5a254SDimitry Andric return error("Invalid record");
4007145449b1SDimitry Andric unsigned TyID = Record[0];
4008145449b1SDimitry Andric Type *Ty = getTypeByID(TyID);
400971d5a254SDimitry Andric if (!Ty)
401071d5a254SDimitry Andric return error("Invalid record");
401171d5a254SDimitry Andric bool isConstant = Record[1] & 1;
401271d5a254SDimitry Andric bool explicitType = Record[1] & 2;
401371d5a254SDimitry Andric unsigned AddressSpace;
401471d5a254SDimitry Andric if (explicitType) {
401571d5a254SDimitry Andric AddressSpace = Record[1] >> 2;
401671d5a254SDimitry Andric } else {
401771d5a254SDimitry Andric if (!Ty->isPointerTy())
401871d5a254SDimitry Andric return error("Invalid type for value");
401971d5a254SDimitry Andric AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
4020145449b1SDimitry Andric TyID = getContainedTypeID(TyID);
4021145449b1SDimitry Andric Ty = getTypeByID(TyID);
4022145449b1SDimitry Andric if (!Ty)
4023145449b1SDimitry Andric return error("Missing element type for old-style global");
402471d5a254SDimitry Andric }
402571d5a254SDimitry Andric
402671d5a254SDimitry Andric uint64_t RawLinkage = Record[3];
402771d5a254SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
40281d5ae102SDimitry Andric MaybeAlign Alignment;
402971d5a254SDimitry Andric if (Error Err = parseAlignmentValue(Record[4], Alignment))
403071d5a254SDimitry Andric return Err;
403171d5a254SDimitry Andric std::string Section;
403271d5a254SDimitry Andric if (Record[5]) {
403371d5a254SDimitry Andric if (Record[5] - 1 >= SectionTable.size())
403471d5a254SDimitry Andric return error("Invalid ID");
403571d5a254SDimitry Andric Section = SectionTable[Record[5] - 1];
403671d5a254SDimitry Andric }
403771d5a254SDimitry Andric GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
403871d5a254SDimitry Andric // Local linkage must have default visibility.
4039cfca06d7SDimitry Andric // auto-upgrade `hidden` and `protected` for old bitcode.
404071d5a254SDimitry Andric if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
404171d5a254SDimitry Andric Visibility = getDecodedVisibility(Record[6]);
404271d5a254SDimitry Andric
404371d5a254SDimitry Andric GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
404471d5a254SDimitry Andric if (Record.size() > 7)
404571d5a254SDimitry Andric TLM = getDecodedThreadLocalMode(Record[7]);
404671d5a254SDimitry Andric
404771d5a254SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
404871d5a254SDimitry Andric if (Record.size() > 8)
404971d5a254SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
405071d5a254SDimitry Andric
405171d5a254SDimitry Andric bool ExternallyInitialized = false;
405271d5a254SDimitry Andric if (Record.size() > 9)
405371d5a254SDimitry Andric ExternallyInitialized = Record[9];
405471d5a254SDimitry Andric
405571d5a254SDimitry Andric GlobalVariable *NewGV =
4056d99dafe2SDimitry Andric new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
405771d5a254SDimitry Andric nullptr, TLM, AddressSpace, ExternallyInitialized);
40587fa27ce4SDimitry Andric if (Alignment)
40597fa27ce4SDimitry Andric NewGV->setAlignment(*Alignment);
406071d5a254SDimitry Andric if (!Section.empty())
406171d5a254SDimitry Andric NewGV->setSection(Section);
406271d5a254SDimitry Andric NewGV->setVisibility(Visibility);
406371d5a254SDimitry Andric NewGV->setUnnamedAddr(UnnamedAddr);
406471d5a254SDimitry Andric
4065e3b55780SDimitry Andric if (Record.size() > 10) {
4066e3b55780SDimitry Andric // A GlobalValue with local linkage cannot have a DLL storage class.
4067e3b55780SDimitry Andric if (!NewGV->hasLocalLinkage()) {
406871d5a254SDimitry Andric NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
4069e3b55780SDimitry Andric }
4070e3b55780SDimitry Andric } else {
407171d5a254SDimitry Andric upgradeDLLImportExportLinkage(NewGV, RawLinkage);
4072e3b55780SDimitry Andric }
407371d5a254SDimitry Andric
4074145449b1SDimitry Andric ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));
407571d5a254SDimitry Andric
407671d5a254SDimitry Andric // Remember which value to use for the global initializer.
407771d5a254SDimitry Andric if (unsigned InitID = Record[2])
407871d5a254SDimitry Andric GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
407971d5a254SDimitry Andric
408071d5a254SDimitry Andric if (Record.size() > 11) {
408171d5a254SDimitry Andric if (unsigned ComdatID = Record[11]) {
408271d5a254SDimitry Andric if (ComdatID > ComdatList.size())
408371d5a254SDimitry Andric return error("Invalid global variable comdat ID");
408471d5a254SDimitry Andric NewGV->setComdat(ComdatList[ComdatID - 1]);
408571d5a254SDimitry Andric }
408671d5a254SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) {
408777fc4c14SDimitry Andric ImplicitComdatObjects.insert(NewGV);
408871d5a254SDimitry Andric }
40896b3f41edSDimitry Andric
40906b3f41edSDimitry Andric if (Record.size() > 12) {
4091c0981da4SDimitry Andric auto AS = getAttributes(Record[12]).getFnAttrs();
40926b3f41edSDimitry Andric NewGV->setAttributes(AS);
40936b3f41edSDimitry Andric }
4094044eb2f6SDimitry Andric
4095044eb2f6SDimitry Andric if (Record.size() > 13) {
4096044eb2f6SDimitry Andric NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
4097044eb2f6SDimitry Andric }
4098eb11fae6SDimitry Andric inferDSOLocal(NewGV);
4099044eb2f6SDimitry Andric
4100e6d15924SDimitry Andric // Check whether we have enough values to read a partition name.
4101e6d15924SDimitry Andric if (Record.size() > 15)
4102e6d15924SDimitry Andric NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
4103e6d15924SDimitry Andric
4104145449b1SDimitry Andric if (Record.size() > 16 && Record[16]) {
4105145449b1SDimitry Andric llvm::GlobalValue::SanitizerMetadata Meta =
4106145449b1SDimitry Andric deserializeSanitizerMetadata(Record[16]);
4107145449b1SDimitry Andric NewGV->setSanitizerMetadata(Meta);
4108145449b1SDimitry Andric }
4109145449b1SDimitry Andric
4110b1c73532SDimitry Andric if (Record.size() > 17 && Record[17]) {
4111b1c73532SDimitry Andric if (auto CM = getDecodedCodeModel(Record[17]))
4112b1c73532SDimitry Andric NewGV->setCodeModel(*CM);
4113b1c73532SDimitry Andric else
4114b1c73532SDimitry Andric return error("Invalid global variable code model");
4115b1c73532SDimitry Andric }
4116b1c73532SDimitry Andric
411771d5a254SDimitry Andric return Error::success();
411871d5a254SDimitry Andric }
411971d5a254SDimitry Andric
callValueTypeCallback(Value * F,unsigned TypeID)4120e3b55780SDimitry Andric void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) {
4121e3b55780SDimitry Andric if (ValueTypeCallback) {
4122e3b55780SDimitry Andric (*ValueTypeCallback)(
4123e3b55780SDimitry Andric F, TypeID, [this](unsigned I) { return getTypeByID(I); },
4124e3b55780SDimitry Andric [this](unsigned I, unsigned J) { return getContainedTypeID(I, J); });
4125e3b55780SDimitry Andric }
4126e3b55780SDimitry Andric }
4127e3b55780SDimitry Andric
parseFunctionRecord(ArrayRef<uint64_t> Record)412871d5a254SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
4129d99dafe2SDimitry Andric // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
413071d5a254SDimitry Andric // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
4131d8e91e46SDimitry Andric // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
4132d99dafe2SDimitry Andric // v2: [strtab_offset, strtab_size, v1]
4133d99dafe2SDimitry Andric StringRef Name;
4134d99dafe2SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record);
4135d99dafe2SDimitry Andric
413671d5a254SDimitry Andric if (Record.size() < 8)
413771d5a254SDimitry Andric return error("Invalid record");
4138145449b1SDimitry Andric unsigned FTyID = Record[0];
4139145449b1SDimitry Andric Type *FTy = getTypeByID(FTyID);
414071d5a254SDimitry Andric if (!FTy)
4141e6d15924SDimitry Andric return error("Invalid record");
4142145449b1SDimitry Andric if (isa<PointerType>(FTy)) {
4143145449b1SDimitry Andric FTyID = getContainedTypeID(FTyID, 0);
4144145449b1SDimitry Andric FTy = getTypeByID(FTyID);
4145145449b1SDimitry Andric if (!FTy)
4146145449b1SDimitry Andric return error("Missing element type for old-style function");
4147145449b1SDimitry Andric }
4148e6d15924SDimitry Andric
4149e6d15924SDimitry Andric if (!isa<FunctionType>(FTy))
415071d5a254SDimitry Andric return error("Invalid type for value");
415171d5a254SDimitry Andric auto CC = static_cast<CallingConv::ID>(Record[1]);
415271d5a254SDimitry Andric if (CC & ~CallingConv::MaxID)
415371d5a254SDimitry Andric return error("Invalid calling convention ID");
415471d5a254SDimitry Andric
4155d8e91e46SDimitry Andric unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
4156d8e91e46SDimitry Andric if (Record.size() > 16)
4157d8e91e46SDimitry Andric AddrSpace = Record[16];
4158d8e91e46SDimitry Andric
4159e6d15924SDimitry Andric Function *Func =
4160e6d15924SDimitry Andric Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
4161d8e91e46SDimitry Andric AddrSpace, Name, TheModule);
416271d5a254SDimitry Andric
4163344a3780SDimitry Andric assert(Func->getFunctionType() == FTy &&
4164e6d15924SDimitry Andric "Incorrect fully specified type provided for function");
4165145449b1SDimitry Andric FunctionTypeIDs[Func] = FTyID;
4166e6d15924SDimitry Andric
416771d5a254SDimitry Andric Func->setCallingConv(CC);
416871d5a254SDimitry Andric bool isProto = Record[2];
416971d5a254SDimitry Andric uint64_t RawLinkage = Record[3];
417071d5a254SDimitry Andric Func->setLinkage(getDecodedLinkage(RawLinkage));
417171d5a254SDimitry Andric Func->setAttributes(getAttributes(Record[4]));
4172e3b55780SDimitry Andric callValueTypeCallback(Func, FTyID);
417371d5a254SDimitry Andric
4174b60736ecSDimitry Andric // Upgrade any old-style byval or sret without a type by propagating the
4175b60736ecSDimitry Andric // argument's pointee type. There should be no opaque pointers where the byval
4176b60736ecSDimitry Andric // type is implicit.
4177e6d15924SDimitry Andric for (unsigned i = 0; i != Func->arg_size(); ++i) {
4178344a3780SDimitry Andric for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4179344a3780SDimitry Andric Attribute::InAlloca}) {
4180b60736ecSDimitry Andric if (!Func->hasParamAttribute(i, Kind))
4181e6d15924SDimitry Andric continue;
4182e6d15924SDimitry Andric
4183344a3780SDimitry Andric if (Func->getParamAttribute(i, Kind).getValueAsType())
4184344a3780SDimitry Andric continue;
4185344a3780SDimitry Andric
4186b60736ecSDimitry Andric Func->removeParamAttr(i, Kind);
4187b60736ecSDimitry Andric
4188145449b1SDimitry Andric unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4189145449b1SDimitry Andric Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4190145449b1SDimitry Andric if (!PtrEltTy)
4191145449b1SDimitry Andric return error("Missing param element type for attribute upgrade");
4192145449b1SDimitry Andric
4193344a3780SDimitry Andric Attribute NewAttr;
4194344a3780SDimitry Andric switch (Kind) {
4195344a3780SDimitry Andric case Attribute::ByVal:
4196344a3780SDimitry Andric NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4197344a3780SDimitry Andric break;
4198344a3780SDimitry Andric case Attribute::StructRet:
4199344a3780SDimitry Andric NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4200344a3780SDimitry Andric break;
4201344a3780SDimitry Andric case Attribute::InAlloca:
4202344a3780SDimitry Andric NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4203344a3780SDimitry Andric break;
4204344a3780SDimitry Andric default:
4205344a3780SDimitry Andric llvm_unreachable("not an upgraded type attribute");
4206344a3780SDimitry Andric }
4207344a3780SDimitry Andric
4208b60736ecSDimitry Andric Func->addParamAttr(i, NewAttr);
4209b60736ecSDimitry Andric }
4210e6d15924SDimitry Andric }
4211e6d15924SDimitry Andric
4212145449b1SDimitry Andric if (Func->getCallingConv() == CallingConv::X86_INTR &&
4213145449b1SDimitry Andric !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {
4214145449b1SDimitry Andric unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4215145449b1SDimitry Andric Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4216145449b1SDimitry Andric if (!ByValTy)
4217145449b1SDimitry Andric return error("Missing param element type for x86_intrcc upgrade");
4218145449b1SDimitry Andric Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
4219145449b1SDimitry Andric Func->addParamAttr(0, NewAttr);
4220145449b1SDimitry Andric }
4221145449b1SDimitry Andric
42221d5ae102SDimitry Andric MaybeAlign Alignment;
422371d5a254SDimitry Andric if (Error Err = parseAlignmentValue(Record[5], Alignment))
422471d5a254SDimitry Andric return Err;
42257fa27ce4SDimitry Andric if (Alignment)
42267fa27ce4SDimitry Andric Func->setAlignment(*Alignment);
422771d5a254SDimitry Andric if (Record[6]) {
422871d5a254SDimitry Andric if (Record[6] - 1 >= SectionTable.size())
422971d5a254SDimitry Andric return error("Invalid ID");
423071d5a254SDimitry Andric Func->setSection(SectionTable[Record[6] - 1]);
423171d5a254SDimitry Andric }
423271d5a254SDimitry Andric // Local linkage must have default visibility.
4233cfca06d7SDimitry Andric // auto-upgrade `hidden` and `protected` for old bitcode.
423471d5a254SDimitry Andric if (!Func->hasLocalLinkage())
423571d5a254SDimitry Andric Func->setVisibility(getDecodedVisibility(Record[7]));
423671d5a254SDimitry Andric if (Record.size() > 8 && Record[8]) {
423771d5a254SDimitry Andric if (Record[8] - 1 >= GCTable.size())
423871d5a254SDimitry Andric return error("Invalid ID");
423971d5a254SDimitry Andric Func->setGC(GCTable[Record[8] - 1]);
424071d5a254SDimitry Andric }
424171d5a254SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
424271d5a254SDimitry Andric if (Record.size() > 9)
424371d5a254SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
424471d5a254SDimitry Andric Func->setUnnamedAddr(UnnamedAddr);
4245c0981da4SDimitry Andric
4246c0981da4SDimitry Andric FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
4247c0981da4SDimitry Andric if (Record.size() > 10)
4248c0981da4SDimitry Andric OperandInfo.Prologue = Record[10];
424971d5a254SDimitry Andric
4250e3b55780SDimitry Andric if (Record.size() > 11) {
4251e3b55780SDimitry Andric // A GlobalValue with local linkage cannot have a DLL storage class.
4252e3b55780SDimitry Andric if (!Func->hasLocalLinkage()) {
425371d5a254SDimitry Andric Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
4254e3b55780SDimitry Andric }
4255e3b55780SDimitry Andric } else {
425671d5a254SDimitry Andric upgradeDLLImportExportLinkage(Func, RawLinkage);
4257e3b55780SDimitry Andric }
425871d5a254SDimitry Andric
425971d5a254SDimitry Andric if (Record.size() > 12) {
426071d5a254SDimitry Andric if (unsigned ComdatID = Record[12]) {
426171d5a254SDimitry Andric if (ComdatID > ComdatList.size())
426271d5a254SDimitry Andric return error("Invalid function comdat ID");
426371d5a254SDimitry Andric Func->setComdat(ComdatList[ComdatID - 1]);
426471d5a254SDimitry Andric }
426571d5a254SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) {
426677fc4c14SDimitry Andric ImplicitComdatObjects.insert(Func);
426771d5a254SDimitry Andric }
426871d5a254SDimitry Andric
4269c0981da4SDimitry Andric if (Record.size() > 13)
4270c0981da4SDimitry Andric OperandInfo.Prefix = Record[13];
427171d5a254SDimitry Andric
4272c0981da4SDimitry Andric if (Record.size() > 14)
4273c0981da4SDimitry Andric OperandInfo.PersonalityFn = Record[14];
427471d5a254SDimitry Andric
4275044eb2f6SDimitry Andric if (Record.size() > 15) {
4276044eb2f6SDimitry Andric Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
4277044eb2f6SDimitry Andric }
4278eb11fae6SDimitry Andric inferDSOLocal(Func);
4279044eb2f6SDimitry Andric
4280e6d15924SDimitry Andric // Record[16] is the address space number.
4281e6d15924SDimitry Andric
4282344a3780SDimitry Andric // Check whether we have enough values to read a partition name. Also make
4283344a3780SDimitry Andric // sure Strtab has enough values.
4284344a3780SDimitry Andric if (Record.size() > 18 && Strtab.data() &&
4285344a3780SDimitry Andric Record[17] + Record[18] <= Strtab.size()) {
4286e6d15924SDimitry Andric Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
4287344a3780SDimitry Andric }
4288e6d15924SDimitry Andric
4289145449b1SDimitry Andric ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
429071d5a254SDimitry Andric
4291c0981da4SDimitry Andric if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4292c0981da4SDimitry Andric FunctionOperands.push_back(OperandInfo);
4293c0981da4SDimitry Andric
429471d5a254SDimitry Andric // If this is a function with a body, remember the prototype we are
429571d5a254SDimitry Andric // creating now, so that we can match up the body with them later.
429671d5a254SDimitry Andric if (!isProto) {
429771d5a254SDimitry Andric Func->setIsMaterializable(true);
429871d5a254SDimitry Andric FunctionsWithBodies.push_back(Func);
429971d5a254SDimitry Andric DeferredFunctionInfo[Func] = 0;
430071d5a254SDimitry Andric }
430171d5a254SDimitry Andric return Error::success();
430271d5a254SDimitry Andric }
430371d5a254SDimitry Andric
parseGlobalIndirectSymbolRecord(unsigned BitCode,ArrayRef<uint64_t> Record)430471d5a254SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord(
430571d5a254SDimitry Andric unsigned BitCode, ArrayRef<uint64_t> Record) {
4306d99dafe2SDimitry Andric // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
4307d99dafe2SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
4308044eb2f6SDimitry Andric // dllstorageclass, threadlocal, unnamed_addr,
4309044eb2f6SDimitry Andric // preemption specifier] (name in VST)
4310d99dafe2SDimitry Andric // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
4311044eb2f6SDimitry Andric // visibility, dllstorageclass, threadlocal, unnamed_addr,
4312044eb2f6SDimitry Andric // preemption specifier] (name in VST)
4313d99dafe2SDimitry Andric // v2: [strtab_offset, strtab_size, v1]
4314d99dafe2SDimitry Andric StringRef Name;
4315d99dafe2SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record);
4316d99dafe2SDimitry Andric
431771d5a254SDimitry Andric bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
431871d5a254SDimitry Andric if (Record.size() < (3 + (unsigned)NewRecord))
431971d5a254SDimitry Andric return error("Invalid record");
432071d5a254SDimitry Andric unsigned OpNum = 0;
4321145449b1SDimitry Andric unsigned TypeID = Record[OpNum++];
4322145449b1SDimitry Andric Type *Ty = getTypeByID(TypeID);
432371d5a254SDimitry Andric if (!Ty)
432471d5a254SDimitry Andric return error("Invalid record");
432571d5a254SDimitry Andric
432671d5a254SDimitry Andric unsigned AddrSpace;
432771d5a254SDimitry Andric if (!NewRecord) {
432871d5a254SDimitry Andric auto *PTy = dyn_cast<PointerType>(Ty);
432971d5a254SDimitry Andric if (!PTy)
433071d5a254SDimitry Andric return error("Invalid type for value");
433171d5a254SDimitry Andric AddrSpace = PTy->getAddressSpace();
4332145449b1SDimitry Andric TypeID = getContainedTypeID(TypeID);
4333145449b1SDimitry Andric Ty = getTypeByID(TypeID);
4334145449b1SDimitry Andric if (!Ty)
4335145449b1SDimitry Andric return error("Missing element type for old-style indirect symbol");
433671d5a254SDimitry Andric } else {
433771d5a254SDimitry Andric AddrSpace = Record[OpNum++];
433871d5a254SDimitry Andric }
433971d5a254SDimitry Andric
434071d5a254SDimitry Andric auto Val = Record[OpNum++];
434171d5a254SDimitry Andric auto Linkage = Record[OpNum++];
4342c0981da4SDimitry Andric GlobalValue *NewGA;
434371d5a254SDimitry Andric if (BitCode == bitc::MODULE_CODE_ALIAS ||
434471d5a254SDimitry Andric BitCode == bitc::MODULE_CODE_ALIAS_OLD)
4345d99dafe2SDimitry Andric NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
434671d5a254SDimitry Andric TheModule);
434771d5a254SDimitry Andric else
4348d99dafe2SDimitry Andric NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
434971d5a254SDimitry Andric nullptr, TheModule);
4350e6d15924SDimitry Andric
435171d5a254SDimitry Andric // Local linkage must have default visibility.
4352cfca06d7SDimitry Andric // auto-upgrade `hidden` and `protected` for old bitcode.
435371d5a254SDimitry Andric if (OpNum != Record.size()) {
435471d5a254SDimitry Andric auto VisInd = OpNum++;
435571d5a254SDimitry Andric if (!NewGA->hasLocalLinkage())
435671d5a254SDimitry Andric NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
435771d5a254SDimitry Andric }
4358eb11fae6SDimitry Andric if (BitCode == bitc::MODULE_CODE_ALIAS ||
4359eb11fae6SDimitry Andric BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
4360e3b55780SDimitry Andric if (OpNum != Record.size()) {
4361e3b55780SDimitry Andric auto S = Record[OpNum++];
4362e3b55780SDimitry Andric // A GlobalValue with local linkage cannot have a DLL storage class.
4363e3b55780SDimitry Andric if (!NewGA->hasLocalLinkage())
4364e3b55780SDimitry Andric NewGA->setDLLStorageClass(getDecodedDLLStorageClass(S));
4365e3b55780SDimitry Andric }
436671d5a254SDimitry Andric else
436771d5a254SDimitry Andric upgradeDLLImportExportLinkage(NewGA, Linkage);
436871d5a254SDimitry Andric if (OpNum != Record.size())
436971d5a254SDimitry Andric NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
437071d5a254SDimitry Andric if (OpNum != Record.size())
437171d5a254SDimitry Andric NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
4372eb11fae6SDimitry Andric }
4373044eb2f6SDimitry Andric if (OpNum != Record.size())
4374044eb2f6SDimitry Andric NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
4375eb11fae6SDimitry Andric inferDSOLocal(NewGA);
4376eb11fae6SDimitry Andric
4377e6d15924SDimitry Andric // Check whether we have enough values to read a partition name.
4378e6d15924SDimitry Andric if (OpNum + 1 < Record.size()) {
437977dbea07SDimitry Andric // Check Strtab has enough values for the partition.
438077dbea07SDimitry Andric if (Record[OpNum] + Record[OpNum + 1] > Strtab.size())
438177dbea07SDimitry Andric return error("Malformed partition, too large.");
4382e6d15924SDimitry Andric NewGA->setPartition(
4383e6d15924SDimitry Andric StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
4384e6d15924SDimitry Andric }
4385e6d15924SDimitry Andric
4386145449b1SDimitry Andric ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
438771d5a254SDimitry Andric IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
438871d5a254SDimitry Andric return Error::success();
438971d5a254SDimitry Andric }
439071d5a254SDimitry Andric
parseModule(uint64_t ResumeBit,bool ShouldLazyLoadMetadata,ParserCallbacks Callbacks)4391b915e9e0SDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit,
4392cfca06d7SDimitry Andric bool ShouldLazyLoadMetadata,
4393e3b55780SDimitry Andric ParserCallbacks Callbacks) {
4394ac9a064cSDimitry Andric // Load directly into RemoveDIs format if LoadBitcodeIntoNewDbgInfoFormat
4395ac9a064cSDimitry Andric // has been set to true and we aren't attempting to preserve the existing
4396ac9a064cSDimitry Andric // format in the bitcode (default action: load into the old debug format).
4397ac9a064cSDimitry Andric if (PreserveInputDbgFormat != cl::boolOrDefault::BOU_TRUE) {
4398ac9a064cSDimitry Andric TheModule->IsNewDbgInfoFormat =
4399ac9a064cSDimitry Andric UseNewDbgInfoFormat &&
4400ac9a064cSDimitry Andric LoadBitcodeIntoNewDbgInfoFormat != cl::boolOrDefault::BOU_FALSE;
4401ac9a064cSDimitry Andric }
4402ac9a064cSDimitry Andric
4403e3b55780SDimitry Andric this->ValueTypeCallback = std::move(Callbacks.ValueType);
4404e6d15924SDimitry Andric if (ResumeBit) {
4405e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
4406e6d15924SDimitry Andric return JumpFailed;
4407e6d15924SDimitry Andric } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4408e6d15924SDimitry Andric return Err;
440963faed5bSDimitry Andric
441063faed5bSDimitry Andric SmallVector<uint64_t, 64> Record;
441163faed5bSDimitry Andric
4412cfca06d7SDimitry Andric // Parts of bitcode parsing depend on the datalayout. Make sure we
4413cfca06d7SDimitry Andric // finalize the datalayout before we run any of that code.
4414cfca06d7SDimitry Andric bool ResolvedDataLayout = false;
4415e3b55780SDimitry Andric // In order to support importing modules with illegal data layout strings,
4416e3b55780SDimitry Andric // delay parsing the data layout string until after upgrades and overrides
4417e3b55780SDimitry Andric // have been applied, allowing to fix illegal data layout strings.
4418e3b55780SDimitry Andric // Initialize to the current module's layout string in case none is specified.
4419e3b55780SDimitry Andric std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4420cfca06d7SDimitry Andric
4421e3b55780SDimitry Andric auto ResolveDataLayout = [&]() -> Error {
4422e3b55780SDimitry Andric if (ResolvedDataLayout)
4423e3b55780SDimitry Andric return Error::success();
4424e3b55780SDimitry Andric
4425e3b55780SDimitry Andric // Datalayout and triple can't be parsed after this point.
4426cfca06d7SDimitry Andric ResolvedDataLayout = true;
4427cfca06d7SDimitry Andric
4428e3b55780SDimitry Andric // Auto-upgrade the layout string
4429e3b55780SDimitry Andric TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
4430e3b55780SDimitry Andric TentativeDataLayoutStr, TheModule->getTargetTriple());
4431cfca06d7SDimitry Andric
4432e3b55780SDimitry Andric // Apply override
4433e3b55780SDimitry Andric if (Callbacks.DataLayout) {
4434e3b55780SDimitry Andric if (auto LayoutOverride = (*Callbacks.DataLayout)(
4435e3b55780SDimitry Andric TheModule->getTargetTriple(), TentativeDataLayoutStr))
4436e3b55780SDimitry Andric TentativeDataLayoutStr = *LayoutOverride;
4437e3b55780SDimitry Andric }
4438e3b55780SDimitry Andric
4439e3b55780SDimitry Andric // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4440e3b55780SDimitry Andric Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr);
4441e3b55780SDimitry Andric if (!MaybeDL)
4442e3b55780SDimitry Andric return MaybeDL.takeError();
4443e3b55780SDimitry Andric
4444e3b55780SDimitry Andric TheModule->setDataLayout(MaybeDL.get());
4445e3b55780SDimitry Andric return Error::success();
4446cfca06d7SDimitry Andric };
4447cfca06d7SDimitry Andric
444863faed5bSDimitry Andric // Read all the records for this module.
4449b915e9e0SDimitry Andric while (true) {
4450e6d15924SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4451e6d15924SDimitry Andric if (!MaybeEntry)
4452e6d15924SDimitry Andric return MaybeEntry.takeError();
4453e6d15924SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get();
445463faed5bSDimitry Andric
44554a16efa3SDimitry Andric switch (Entry.Kind) {
44564a16efa3SDimitry Andric case BitstreamEntry::Error:
44573a0822f0SDimitry Andric return error("Malformed block");
44584a16efa3SDimitry Andric case BitstreamEntry::EndBlock:
4459e3b55780SDimitry Andric if (Error Err = ResolveDataLayout())
4460e3b55780SDimitry Andric return Err;
44613a0822f0SDimitry Andric return globalCleanup();
446263faed5bSDimitry Andric
44634a16efa3SDimitry Andric case BitstreamEntry::SubBlock:
44644a16efa3SDimitry Andric switch (Entry.ID) {
4465009b1c42SEd Schouten default: // Skip unknown content.
4466e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
4467e6d15924SDimitry Andric return Err;
4468009b1c42SEd Schouten break;
4469009b1c42SEd Schouten case bitc::BLOCKINFO_BLOCK_ID:
4470145449b1SDimitry Andric if (Error Err = readBlockInfo())
4471145449b1SDimitry Andric return Err;
4472009b1c42SEd Schouten break;
4473009b1c42SEd Schouten case bitc::PARAMATTR_BLOCK_ID:
4474b915e9e0SDimitry Andric if (Error Err = parseAttributeBlock())
4475b915e9e0SDimitry Andric return Err;
4476009b1c42SEd Schouten break;
44774a16efa3SDimitry Andric case bitc::PARAMATTR_GROUP_BLOCK_ID:
4478b915e9e0SDimitry Andric if (Error Err = parseAttributeGroupBlock())
4479b915e9e0SDimitry Andric return Err;
44804a16efa3SDimitry Andric break;
4481411bd29eSDimitry Andric case bitc::TYPE_BLOCK_ID_NEW:
4482b915e9e0SDimitry Andric if (Error Err = parseTypeTable())
4483b915e9e0SDimitry Andric return Err;
4484009b1c42SEd Schouten break;
4485009b1c42SEd Schouten case bitc::VALUE_SYMTAB_BLOCK_ID:
4486dd58ef01SDimitry Andric if (!SeenValueSymbolTable) {
4487dd58ef01SDimitry Andric // Either this is an old form VST without function index and an
4488dd58ef01SDimitry Andric // associated VST forward declaration record (which would have caused
4489dd58ef01SDimitry Andric // the VST to be jumped to and parsed before it was encountered
4490dd58ef01SDimitry Andric // normally in the stream), or there were no function blocks to
4491dd58ef01SDimitry Andric // trigger an earlier parsing of the VST.
4492dd58ef01SDimitry Andric assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4493b915e9e0SDimitry Andric if (Error Err = parseValueSymbolTable())
4494b915e9e0SDimitry Andric return Err;
449563faed5bSDimitry Andric SeenValueSymbolTable = true;
4496dd58ef01SDimitry Andric } else {
4497dd58ef01SDimitry Andric // We must have had a VST forward declaration record, which caused
4498dd58ef01SDimitry Andric // the parser to jump to and parse the VST earlier.
4499dd58ef01SDimitry Andric assert(VSTOffset > 0);
4500e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
4501e6d15924SDimitry Andric return Err;
4502dd58ef01SDimitry Andric }
4503009b1c42SEd Schouten break;
4504009b1c42SEd Schouten case bitc::CONSTANTS_BLOCK_ID:
4505b915e9e0SDimitry Andric if (Error Err = parseConstants())
4506b915e9e0SDimitry Andric return Err;
4507b915e9e0SDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits())
4508b915e9e0SDimitry Andric return Err;
4509009b1c42SEd Schouten break;
451059850d08SRoman Divacky case bitc::METADATA_BLOCK_ID:
4511b915e9e0SDimitry Andric if (ShouldLazyLoadMetadata) {
4512b915e9e0SDimitry Andric if (Error Err = rememberAndSkipMetadata())
4513b915e9e0SDimitry Andric return Err;
45145a5ac124SDimitry Andric break;
45155a5ac124SDimitry Andric }
45165a5ac124SDimitry Andric assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
4517b915e9e0SDimitry Andric if (Error Err = MDLoader->parseModuleMetadata())
4518b915e9e0SDimitry Andric return Err;
4519dd58ef01SDimitry Andric break;
4520dd58ef01SDimitry Andric case bitc::METADATA_KIND_BLOCK_ID:
4521b915e9e0SDimitry Andric if (Error Err = MDLoader->parseMetadataKinds())
4522b915e9e0SDimitry Andric return Err;
452359850d08SRoman Divacky break;
4524009b1c42SEd Schouten case bitc::FUNCTION_BLOCK_ID:
4525e3b55780SDimitry Andric if (Error Err = ResolveDataLayout())
4526e3b55780SDimitry Andric return Err;
4527cfca06d7SDimitry Andric
4528009b1c42SEd Schouten // If this is the first function body we've seen, reverse the
4529009b1c42SEd Schouten // FunctionsWithBodies list.
453063faed5bSDimitry Andric if (!SeenFirstFunctionBody) {
4531009b1c42SEd Schouten std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4532b915e9e0SDimitry Andric if (Error Err = globalCleanup())
4533b915e9e0SDimitry Andric return Err;
453463faed5bSDimitry Andric SeenFirstFunctionBody = true;
4535009b1c42SEd Schouten }
4536009b1c42SEd Schouten
4537dd58ef01SDimitry Andric if (VSTOffset > 0) {
4538dd58ef01SDimitry Andric // If we have a VST forward declaration record, make sure we
4539dd58ef01SDimitry Andric // parse the VST now if we haven't already. It is needed to
4540dd58ef01SDimitry Andric // set up the DeferredFunctionInfo vector for lazy reading.
4541dd58ef01SDimitry Andric if (!SeenValueSymbolTable) {
4542b915e9e0SDimitry Andric if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4543b915e9e0SDimitry Andric return Err;
4544dd58ef01SDimitry Andric SeenValueSymbolTable = true;
4545dd58ef01SDimitry Andric // Fall through so that we record the NextUnreadBit below.
4546dd58ef01SDimitry Andric // This is necessary in case we have an anonymous function that
4547dd58ef01SDimitry Andric // is later materialized. Since it will not have a VST entry we
4548dd58ef01SDimitry Andric // need to fall back to the lazy parse to find its offset.
4549dd58ef01SDimitry Andric } else {
4550dd58ef01SDimitry Andric // If we have a VST forward declaration record, but have already
4551dd58ef01SDimitry Andric // parsed the VST (just above, when the first function body was
4552dd58ef01SDimitry Andric // encountered here), then we are resuming the parse after
4553dd58ef01SDimitry Andric // materializing functions. The ResumeBit points to the
4554dd58ef01SDimitry Andric // start of the last function block recorded in the
4555dd58ef01SDimitry Andric // DeferredFunctionInfo map. Skip it.
4556e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
4557e6d15924SDimitry Andric return Err;
4558dd58ef01SDimitry Andric continue;
4559dd58ef01SDimitry Andric }
4560dd58ef01SDimitry Andric }
4561dd58ef01SDimitry Andric
4562dd58ef01SDimitry Andric // Support older bitcode files that did not have the function
4563dd58ef01SDimitry Andric // index in the VST, nor a VST forward declaration record, as
4564dd58ef01SDimitry Andric // well as anonymous functions that do not have VST entries.
4565dd58ef01SDimitry Andric // Build the DeferredFunctionInfo vector on the fly.
4566b915e9e0SDimitry Andric if (Error Err = rememberAndSkipFunctionBody())
4567b915e9e0SDimitry Andric return Err;
4568dd58ef01SDimitry Andric
45691a82d4c0SDimitry Andric // Suspend parsing when we reach the function bodies. Subsequent
45701a82d4c0SDimitry Andric // materialization calls will resume it when necessary. If the bitcode
45711a82d4c0SDimitry Andric // file is old, the symbol table will be at the end instead and will not
45721a82d4c0SDimitry Andric // have been seen yet. In this case, just finish the parse now.
45731a82d4c0SDimitry Andric if (SeenValueSymbolTable) {
457463faed5bSDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo();
4575b915e9e0SDimitry Andric // After the VST has been parsed, we need to make sure intrinsic name
4576b915e9e0SDimitry Andric // are auto-upgraded.
4577b915e9e0SDimitry Andric return globalCleanup();
457863faed5bSDimitry Andric }
457963faed5bSDimitry Andric break;
458063faed5bSDimitry Andric case bitc::USELIST_BLOCK_ID:
4581b915e9e0SDimitry Andric if (Error Err = parseUseLists())
4582b915e9e0SDimitry Andric return Err;
4583009b1c42SEd Schouten break;
4584dd58ef01SDimitry Andric case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
4585b915e9e0SDimitry Andric if (Error Err = parseOperandBundleTags())
4586b915e9e0SDimitry Andric return Err;
4587dd58ef01SDimitry Andric break;
4588ca089b24SDimitry Andric case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
4589ca089b24SDimitry Andric if (Error Err = parseSyncScopeNames())
4590ca089b24SDimitry Andric return Err;
4591ca089b24SDimitry Andric break;
4592009b1c42SEd Schouten }
4593009b1c42SEd Schouten continue;
45944a16efa3SDimitry Andric
45954a16efa3SDimitry Andric case BitstreamEntry::Record:
45964a16efa3SDimitry Andric // The interesting case.
45974a16efa3SDimitry Andric break;
4598009b1c42SEd Schouten }
4599009b1c42SEd Schouten
4600009b1c42SEd Schouten // Read a record.
4601e6d15924SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4602e6d15924SDimitry Andric if (!MaybeBitCode)
4603e6d15924SDimitry Andric return MaybeBitCode.takeError();
4604e6d15924SDimitry Andric switch (unsigned BitCode = MaybeBitCode.get()) {
4605009b1c42SEd Schouten default: break; // Default behavior, ignore unknown content.
460671d5a254SDimitry Andric case bitc::MODULE_CODE_VERSION: {
460771d5a254SDimitry Andric Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
460871d5a254SDimitry Andric if (!VersionOrErr)
460971d5a254SDimitry Andric return VersionOrErr.takeError();
461071d5a254SDimitry Andric UseRelativeIDs = *VersionOrErr >= 1;
4611522600a2SDimitry Andric break;
4612522600a2SDimitry Andric }
4613009b1c42SEd Schouten case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
4614cfca06d7SDimitry Andric if (ResolvedDataLayout)
4615cfca06d7SDimitry Andric return error("target triple too late in module");
4616009b1c42SEd Schouten std::string S;
46173a0822f0SDimitry Andric if (convertToString(Record, 0, S))
46183a0822f0SDimitry Andric return error("Invalid record");
4619009b1c42SEd Schouten TheModule->setTargetTriple(S);
4620009b1c42SEd Schouten break;
4621009b1c42SEd Schouten }
4622009b1c42SEd Schouten case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
4623cfca06d7SDimitry Andric if (ResolvedDataLayout)
4624cfca06d7SDimitry Andric return error("datalayout too late in module");
4625e3b55780SDimitry Andric if (convertToString(Record, 0, TentativeDataLayoutStr))
46263a0822f0SDimitry Andric return error("Invalid record");
4627009b1c42SEd Schouten break;
4628009b1c42SEd Schouten }
4629009b1c42SEd Schouten case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
4630009b1c42SEd Schouten std::string S;
46313a0822f0SDimitry Andric if (convertToString(Record, 0, S))
46323a0822f0SDimitry Andric return error("Invalid record");
4633009b1c42SEd Schouten TheModule->setModuleInlineAsm(S);
4634009b1c42SEd Schouten break;
4635009b1c42SEd Schouten }
4636009b1c42SEd Schouten case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
4637cfca06d7SDimitry Andric // Deprecated, but still needed to read old bitcode files.
4638009b1c42SEd Schouten std::string S;
46393a0822f0SDimitry Andric if (convertToString(Record, 0, S))
46403a0822f0SDimitry Andric return error("Invalid record");
46414a16efa3SDimitry Andric // Ignore value.
4642009b1c42SEd Schouten break;
4643009b1c42SEd Schouten }
4644009b1c42SEd Schouten case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
4645009b1c42SEd Schouten std::string S;
46463a0822f0SDimitry Andric if (convertToString(Record, 0, S))
46473a0822f0SDimitry Andric return error("Invalid record");
4648009b1c42SEd Schouten SectionTable.push_back(S);
4649009b1c42SEd Schouten break;
4650009b1c42SEd Schouten }
4651009b1c42SEd Schouten case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
4652009b1c42SEd Schouten std::string S;
46533a0822f0SDimitry Andric if (convertToString(Record, 0, S))
46543a0822f0SDimitry Andric return error("Invalid record");
4655009b1c42SEd Schouten GCTable.push_back(S);
4656009b1c42SEd Schouten break;
4657009b1c42SEd Schouten }
4658044eb2f6SDimitry Andric case bitc::MODULE_CODE_COMDAT:
465971d5a254SDimitry Andric if (Error Err = parseComdatRecord(Record))
466071d5a254SDimitry Andric return Err;
46615ca98fd9SDimitry Andric break;
46626f8fc217SDimitry Andric // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
46636f8fc217SDimitry Andric // written by ThinLinkBitcodeWriter. See
46646f8fc217SDimitry Andric // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
46656f8fc217SDimitry Andric // record
46666f8fc217SDimitry Andric // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4667044eb2f6SDimitry Andric case bitc::MODULE_CODE_GLOBALVAR:
466871d5a254SDimitry Andric if (Error Err = parseGlobalVarRecord(Record))
4669b915e9e0SDimitry Andric return Err;
4670009b1c42SEd Schouten break;
4671044eb2f6SDimitry Andric case bitc::MODULE_CODE_FUNCTION:
4672e3b55780SDimitry Andric if (Error Err = ResolveDataLayout())
4673e3b55780SDimitry Andric return Err;
467471d5a254SDimitry Andric if (Error Err = parseFunctionRecord(Record))
4675b915e9e0SDimitry Andric return Err;
4676009b1c42SEd Schouten break;
467701095a5dSDimitry Andric case bitc::MODULE_CODE_IFUNC:
4678dd58ef01SDimitry Andric case bitc::MODULE_CODE_ALIAS:
4679044eb2f6SDimitry Andric case bitc::MODULE_CODE_ALIAS_OLD:
468071d5a254SDimitry Andric if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
468171d5a254SDimitry Andric return Err;
4682009b1c42SEd Schouten break;
4683dd58ef01SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset]
4684dd58ef01SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET:
4685b60736ecSDimitry Andric if (Record.empty())
4686dd58ef01SDimitry Andric return error("Invalid record");
4687b915e9e0SDimitry Andric // Note that we subtract 1 here because the offset is relative to one word
4688b915e9e0SDimitry Andric // before the start of the identification or module block, which was
4689b915e9e0SDimitry Andric // historically always the start of the regular bitcode header.
4690b915e9e0SDimitry Andric VSTOffset = Record[0] - 1;
4691dd58ef01SDimitry Andric break;
469201095a5dSDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
469301095a5dSDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME:
469401095a5dSDimitry Andric SmallString<128> ValueName;
469501095a5dSDimitry Andric if (convertToString(Record, 0, ValueName))
4696dd58ef01SDimitry Andric return error("Invalid record");
469701095a5dSDimitry Andric TheModule->setSourceFileName(ValueName);
4698dd58ef01SDimitry Andric break;
4699009b1c42SEd Schouten }
4700009b1c42SEd Schouten Record.clear();
4701009b1c42SEd Schouten }
4702e3b55780SDimitry Andric this->ValueTypeCallback = std::nullopt;
4703e3b55780SDimitry Andric return Error::success();
4704009b1c42SEd Schouten }
4705009b1c42SEd Schouten
parseBitcodeInto(Module * M,bool ShouldLazyLoadMetadata,bool IsImporting,ParserCallbacks Callbacks)4706b915e9e0SDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
4707cfca06d7SDimitry Andric bool IsImporting,
4708e3b55780SDimitry Andric ParserCallbacks Callbacks) {
47093a0822f0SDimitry Andric TheModule = M;
4710e3b55780SDimitry Andric MetadataLoaderCallbacks MDCallbacks;
4711e3b55780SDimitry Andric MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); };
4712e3b55780SDimitry Andric MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) {
4713e3b55780SDimitry Andric return getContainedTypeID(I, J);
4714e3b55780SDimitry Andric };
4715e3b55780SDimitry Andric MDCallbacks.MDType = Callbacks.MDType;
4716e3b55780SDimitry Andric MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4717e3b55780SDimitry Andric return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4718009b1c42SEd Schouten }
4719009b1c42SEd Schouten
typeCheckLoadStoreInst(Type * ValType,Type * PtrType)4720b915e9e0SDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
47215a5ac124SDimitry Andric if (!isa<PointerType>(PtrType))
4722b915e9e0SDimitry Andric return error("Load/Store operand is not a pointer type");
4723344a3780SDimitry Andric if (!PointerType::isLoadableOrStorableType(ValType))
4724b915e9e0SDimitry Andric return error("Cannot load/store from pointer");
4725b915e9e0SDimitry Andric return Error::success();
47265a5ac124SDimitry Andric }
47275a5ac124SDimitry Andric
propagateAttributeTypes(CallBase * CB,ArrayRef<unsigned> ArgTyIDs)4728145449b1SDimitry Andric Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4729145449b1SDimitry Andric ArrayRef<unsigned> ArgTyIDs) {
4730145449b1SDimitry Andric AttributeList Attrs = CB->getAttributes();
4731e6d15924SDimitry Andric for (unsigned i = 0; i != CB->arg_size(); ++i) {
4732344a3780SDimitry Andric for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4733344a3780SDimitry Andric Attribute::InAlloca}) {
4734145449b1SDimitry Andric if (!Attrs.hasParamAttr(i, Kind) ||
4735145449b1SDimitry Andric Attrs.getParamAttr(i, Kind).getValueAsType())
4736e6d15924SDimitry Andric continue;
4737e6d15924SDimitry Andric
4738145449b1SDimitry Andric Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4739145449b1SDimitry Andric if (!PtrEltTy)
4740145449b1SDimitry Andric return error("Missing element type for typed attribute upgrade");
4741b60736ecSDimitry Andric
4742344a3780SDimitry Andric Attribute NewAttr;
4743344a3780SDimitry Andric switch (Kind) {
4744344a3780SDimitry Andric case Attribute::ByVal:
4745344a3780SDimitry Andric NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4746344a3780SDimitry Andric break;
4747344a3780SDimitry Andric case Attribute::StructRet:
4748344a3780SDimitry Andric NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4749344a3780SDimitry Andric break;
4750344a3780SDimitry Andric case Attribute::InAlloca:
4751344a3780SDimitry Andric NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4752344a3780SDimitry Andric break;
4753344a3780SDimitry Andric default:
4754344a3780SDimitry Andric llvm_unreachable("not an upgraded type attribute");
4755344a3780SDimitry Andric }
4756344a3780SDimitry Andric
4757145449b1SDimitry Andric Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
4758b60736ecSDimitry Andric }
4759e6d15924SDimitry Andric }
4760344a3780SDimitry Andric
47616f8fc217SDimitry Andric if (CB->isInlineAsm()) {
47626f8fc217SDimitry Andric const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
47636f8fc217SDimitry Andric unsigned ArgNo = 0;
47646f8fc217SDimitry Andric for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
47656f8fc217SDimitry Andric if (!CI.hasArg())
47666f8fc217SDimitry Andric continue;
47676f8fc217SDimitry Andric
4768145449b1SDimitry Andric if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
4769145449b1SDimitry Andric Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4770145449b1SDimitry Andric if (!ElemTy)
4771145449b1SDimitry Andric return error("Missing element type for inline asm upgrade");
4772145449b1SDimitry Andric Attrs = Attrs.addParamAttribute(
4773145449b1SDimitry Andric Context, ArgNo,
4774145449b1SDimitry Andric Attribute::get(Context, Attribute::ElementType, ElemTy));
47756f8fc217SDimitry Andric }
47766f8fc217SDimitry Andric
47776f8fc217SDimitry Andric ArgNo++;
47786f8fc217SDimitry Andric }
47796f8fc217SDimitry Andric }
47806f8fc217SDimitry Andric
4781344a3780SDimitry Andric switch (CB->getIntrinsicID()) {
4782344a3780SDimitry Andric case Intrinsic::preserve_array_access_index:
4783344a3780SDimitry Andric case Intrinsic::preserve_struct_access_index:
4784145449b1SDimitry Andric case Intrinsic::aarch64_ldaxr:
4785145449b1SDimitry Andric case Intrinsic::aarch64_ldxr:
4786145449b1SDimitry Andric case Intrinsic::aarch64_stlxr:
4787145449b1SDimitry Andric case Intrinsic::aarch64_stxr:
4788145449b1SDimitry Andric case Intrinsic::arm_ldaex:
4789145449b1SDimitry Andric case Intrinsic::arm_ldrex:
4790145449b1SDimitry Andric case Intrinsic::arm_stlex:
4791145449b1SDimitry Andric case Intrinsic::arm_strex: {
4792145449b1SDimitry Andric unsigned ArgNo;
4793145449b1SDimitry Andric switch (CB->getIntrinsicID()) {
4794145449b1SDimitry Andric case Intrinsic::aarch64_stlxr:
4795145449b1SDimitry Andric case Intrinsic::aarch64_stxr:
4796145449b1SDimitry Andric case Intrinsic::arm_stlex:
4797145449b1SDimitry Andric case Intrinsic::arm_strex:
4798145449b1SDimitry Andric ArgNo = 1;
4799145449b1SDimitry Andric break;
4800145449b1SDimitry Andric default:
4801145449b1SDimitry Andric ArgNo = 0;
4802145449b1SDimitry Andric break;
4803145449b1SDimitry Andric }
4804145449b1SDimitry Andric if (!Attrs.getParamElementType(ArgNo)) {
4805145449b1SDimitry Andric Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4806145449b1SDimitry Andric if (!ElTy)
4807145449b1SDimitry Andric return error("Missing element type for elementtype upgrade");
4808344a3780SDimitry Andric Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
4809145449b1SDimitry Andric Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4810344a3780SDimitry Andric }
4811344a3780SDimitry Andric break;
4812145449b1SDimitry Andric }
4813344a3780SDimitry Andric default:
4814344a3780SDimitry Andric break;
4815344a3780SDimitry Andric }
4816145449b1SDimitry Andric
4817145449b1SDimitry Andric CB->setAttributes(Attrs);
4818145449b1SDimitry Andric return Error::success();
4819e6d15924SDimitry Andric }
4820e6d15924SDimitry Andric
48213a0822f0SDimitry Andric /// Lazily parse the specified function body block.
parseFunctionBody(Function * F)4822b915e9e0SDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) {
4823e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4824e6d15924SDimitry Andric return Err;
4825009b1c42SEd Schouten
482601095a5dSDimitry Andric // Unexpected unresolved metadata when parsing function.
4827b915e9e0SDimitry Andric if (MDLoader->hasFwdRefs())
482801095a5dSDimitry Andric return error("Invalid function metadata: incoming forward references");
482901095a5dSDimitry Andric
483067a71b31SRoman Divacky InstructionList.clear();
4831009b1c42SEd Schouten unsigned ModuleValueListSize = ValueList.size();
4832b915e9e0SDimitry Andric unsigned ModuleMDLoaderSize = MDLoader->size();
4833009b1c42SEd Schouten
4834009b1c42SEd Schouten // Add all the function arguments to the value table.
4835e6d15924SDimitry Andric unsigned ArgNo = 0;
4836145449b1SDimitry Andric unsigned FTyID = FunctionTypeIDs[F];
4837e6d15924SDimitry Andric for (Argument &I : F->args()) {
4838145449b1SDimitry Andric unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4839145449b1SDimitry Andric assert(I.getType() == getTypeByID(ArgTyID) &&
4840e6d15924SDimitry Andric "Incorrect fully specified type for Function Argument");
4841145449b1SDimitry Andric ValueList.push_back(&I, ArgTyID);
4842145449b1SDimitry Andric ++ArgNo;
4843e6d15924SDimitry Andric }
4844009b1c42SEd Schouten unsigned NextValueNo = ValueList.size();
48455ca98fd9SDimitry Andric BasicBlock *CurBB = nullptr;
4846009b1c42SEd Schouten unsigned CurBBNo = 0;
4847145449b1SDimitry Andric // Block into which constant expressions from phi nodes are materialized.
4848145449b1SDimitry Andric BasicBlock *PhiConstExprBB = nullptr;
4849145449b1SDimitry Andric // Edge blocks for phi nodes into which constant expressions have been
4850145449b1SDimitry Andric // expanded.
4851145449b1SDimitry Andric SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4>
4852145449b1SDimitry Andric ConstExprEdgeBBs;
4853009b1c42SEd Schouten
4854b5efedafSRoman Divacky DebugLoc LastLoc;
485567c32a98SDimitry Andric auto getLastInstruction = [&]() -> Instruction * {
485667c32a98SDimitry Andric if (CurBB && !CurBB->empty())
485767c32a98SDimitry Andric return &CurBB->back();
485867c32a98SDimitry Andric else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
485967c32a98SDimitry Andric !FunctionBBs[CurBBNo - 1]->empty())
486067c32a98SDimitry Andric return &FunctionBBs[CurBBNo - 1]->back();
486167c32a98SDimitry Andric return nullptr;
486267c32a98SDimitry Andric };
4863b5efedafSRoman Divacky
4864dd58ef01SDimitry Andric std::vector<OperandBundleDef> OperandBundles;
4865dd58ef01SDimitry Andric
4866009b1c42SEd Schouten // Read all the records.
4867009b1c42SEd Schouten SmallVector<uint64_t, 64> Record;
4868b915e9e0SDimitry Andric
4869b915e9e0SDimitry Andric while (true) {
4870e6d15924SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4871e6d15924SDimitry Andric if (!MaybeEntry)
4872e6d15924SDimitry Andric return MaybeEntry.takeError();
4873e6d15924SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get();
4874009b1c42SEd Schouten
48754a16efa3SDimitry Andric switch (Entry.Kind) {
48764a16efa3SDimitry Andric case BitstreamEntry::Error:
48773a0822f0SDimitry Andric return error("Malformed block");
48784a16efa3SDimitry Andric case BitstreamEntry::EndBlock:
48794a16efa3SDimitry Andric goto OutOfRecordLoop;
48804a16efa3SDimitry Andric
48814a16efa3SDimitry Andric case BitstreamEntry::SubBlock:
48824a16efa3SDimitry Andric switch (Entry.ID) {
4883009b1c42SEd Schouten default: // Skip unknown content.
4884e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
4885e6d15924SDimitry Andric return Err;
4886009b1c42SEd Schouten break;
4887009b1c42SEd Schouten case bitc::CONSTANTS_BLOCK_ID:
4888b915e9e0SDimitry Andric if (Error Err = parseConstants())
4889b915e9e0SDimitry Andric return Err;
4890009b1c42SEd Schouten NextValueNo = ValueList.size();
4891009b1c42SEd Schouten break;
4892009b1c42SEd Schouten case bitc::VALUE_SYMTAB_BLOCK_ID:
4893b915e9e0SDimitry Andric if (Error Err = parseValueSymbolTable())
4894b915e9e0SDimitry Andric return Err;
4895009b1c42SEd Schouten break;
489659850d08SRoman Divacky case bitc::METADATA_ATTACHMENT_ID:
4897b915e9e0SDimitry Andric if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
4898b915e9e0SDimitry Andric return Err;
489959850d08SRoman Divacky break;
4900829000e0SRoman Divacky case bitc::METADATA_BLOCK_ID:
4901b915e9e0SDimitry Andric assert(DeferredMetadataInfo.empty() &&
4902b915e9e0SDimitry Andric "Must read all module-level metadata before function-level");
4903b915e9e0SDimitry Andric if (Error Err = MDLoader->parseFunctionMetadata())
4904b915e9e0SDimitry Andric return Err;
4905829000e0SRoman Divacky break;
490667c32a98SDimitry Andric case bitc::USELIST_BLOCK_ID:
4907b915e9e0SDimitry Andric if (Error Err = parseUseLists())
4908b915e9e0SDimitry Andric return Err;
490967c32a98SDimitry Andric break;
4910009b1c42SEd Schouten }
4911009b1c42SEd Schouten continue;
4912009b1c42SEd Schouten
49134a16efa3SDimitry Andric case BitstreamEntry::Record:
49144a16efa3SDimitry Andric // The interesting case.
49154a16efa3SDimitry Andric break;
4916009b1c42SEd Schouten }
4917009b1c42SEd Schouten
4918009b1c42SEd Schouten // Read a record.
4919009b1c42SEd Schouten Record.clear();
49205ca98fd9SDimitry Andric Instruction *I = nullptr;
4921145449b1SDimitry Andric unsigned ResTypeID = InvalidTypeID;
4922e6d15924SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4923e6d15924SDimitry Andric if (!MaybeBitCode)
4924e6d15924SDimitry Andric return MaybeBitCode.takeError();
4925e6d15924SDimitry Andric switch (unsigned BitCode = MaybeBitCode.get()) {
4926009b1c42SEd Schouten default: // Default behavior: reject
49273a0822f0SDimitry Andric return error("Invalid value");
492867c32a98SDimitry Andric case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
4929b60736ecSDimitry Andric if (Record.empty() || Record[0] == 0)
49303a0822f0SDimitry Andric return error("Invalid record");
4931009b1c42SEd Schouten // Create all the basic blocks for the function.
4932009b1c42SEd Schouten FunctionBBs.resize(Record[0]);
493367c32a98SDimitry Andric
493467c32a98SDimitry Andric // See if anything took the address of blocks in this function.
493567c32a98SDimitry Andric auto BBFRI = BasicBlockFwdRefs.find(F);
493667c32a98SDimitry Andric if (BBFRI == BasicBlockFwdRefs.end()) {
4937f65dcba8SDimitry Andric for (BasicBlock *&BB : FunctionBBs)
4938f65dcba8SDimitry Andric BB = BasicBlock::Create(Context, "", F);
493967c32a98SDimitry Andric } else {
494067c32a98SDimitry Andric auto &BBRefs = BBFRI->second;
494167c32a98SDimitry Andric // Check for invalid basic block references.
494267c32a98SDimitry Andric if (BBRefs.size() > FunctionBBs.size())
49433a0822f0SDimitry Andric return error("Invalid ID");
494467c32a98SDimitry Andric assert(!BBRefs.empty() && "Unexpected empty array");
494567c32a98SDimitry Andric assert(!BBRefs.front() && "Invalid reference to entry block");
494667c32a98SDimitry Andric for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
494767c32a98SDimitry Andric ++I)
494867c32a98SDimitry Andric if (I < RE && BBRefs[I]) {
494967c32a98SDimitry Andric BBRefs[I]->insertInto(F);
495067c32a98SDimitry Andric FunctionBBs[I] = BBRefs[I];
495167c32a98SDimitry Andric } else {
495267c32a98SDimitry Andric FunctionBBs[I] = BasicBlock::Create(Context, "", F);
495367c32a98SDimitry Andric }
495467c32a98SDimitry Andric
495567c32a98SDimitry Andric // Erase from the table.
495667c32a98SDimitry Andric BasicBlockFwdRefs.erase(BBFRI);
495767c32a98SDimitry Andric }
495867c32a98SDimitry Andric
4959009b1c42SEd Schouten CurBB = FunctionBBs[0];
4960009b1c42SEd Schouten continue;
496167c32a98SDimitry Andric }
4962009b1c42SEd Schouten
4963145449b1SDimitry Andric case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
4964145449b1SDimitry Andric // The record should not be emitted if it's an empty list.
4965145449b1SDimitry Andric if (Record.empty())
4966145449b1SDimitry Andric return error("Invalid record");
4967145449b1SDimitry Andric // When we have the RARE case of a BlockAddress Constant that is not
4968145449b1SDimitry Andric // scoped to the Function it refers to, we need to conservatively
4969145449b1SDimitry Andric // materialize the referred to Function, regardless of whether or not
4970145449b1SDimitry Andric // that Function will ultimately be linked, otherwise users of
4971145449b1SDimitry Andric // BitcodeReader might start splicing out Function bodies such that we
4972145449b1SDimitry Andric // might no longer be able to materialize the BlockAddress since the
4973145449b1SDimitry Andric // BasicBlock (and entire body of the Function) the BlockAddress refers
4974145449b1SDimitry Andric // to may have been moved. In the case that the user of BitcodeReader
4975145449b1SDimitry Andric // decides ultimately not to link the Function body, materializing here
4976145449b1SDimitry Andric // could be considered wasteful, but it's better than a deserialization
4977145449b1SDimitry Andric // failure as described. This keeps BitcodeReader unaware of complex
4978145449b1SDimitry Andric // linkage policy decisions such as those use by LTO, leaving those
4979145449b1SDimitry Andric // decisions "one layer up."
4980145449b1SDimitry Andric for (uint64_t ValID : Record)
4981145449b1SDimitry Andric if (auto *F = dyn_cast<Function>(ValueList[ValID]))
4982145449b1SDimitry Andric BackwardRefFunctions.push_back(F);
4983145449b1SDimitry Andric else
4984145449b1SDimitry Andric return error("Invalid record");
4985145449b1SDimitry Andric
4986145449b1SDimitry Andric continue;
4987145449b1SDimitry Andric
4988b5efedafSRoman Divacky case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4989b5efedafSRoman Divacky // This record indicates that the last instruction is at the same
4990b5efedafSRoman Divacky // location as the previous instruction with a location.
499167c32a98SDimitry Andric I = getLastInstruction();
4992b5efedafSRoman Divacky
49935ca98fd9SDimitry Andric if (!I)
49943a0822f0SDimitry Andric return error("Invalid record");
4995b5efedafSRoman Divacky I->setDebugLoc(LastLoc);
49965ca98fd9SDimitry Andric I = nullptr;
4997b5efedafSRoman Divacky continue;
4998b5efedafSRoman Divacky
4999411bd29eSDimitry Andric case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
500067c32a98SDimitry Andric I = getLastInstruction();
50015ca98fd9SDimitry Andric if (!I || Record.size() < 4)
50023a0822f0SDimitry Andric return error("Invalid record");
5003b5efedafSRoman Divacky
5004b5efedafSRoman Divacky unsigned Line = Record[0], Col = Record[1];
5005b5efedafSRoman Divacky unsigned ScopeID = Record[2], IAID = Record[3];
5006d8e91e46SDimitry Andric bool isImplicitCode = Record.size() == 5 && Record[4];
5007b5efedafSRoman Divacky
50085ca98fd9SDimitry Andric MDNode *Scope = nullptr, *IA = nullptr;
500901095a5dSDimitry Andric if (ScopeID) {
5010d8e91e46SDimitry Andric Scope = dyn_cast_or_null<MDNode>(
5011d8e91e46SDimitry Andric MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
501201095a5dSDimitry Andric if (!Scope)
501301095a5dSDimitry Andric return error("Invalid record");
501401095a5dSDimitry Andric }
501501095a5dSDimitry Andric if (IAID) {
5016d8e91e46SDimitry Andric IA = dyn_cast_or_null<MDNode>(
5017d8e91e46SDimitry Andric MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
501801095a5dSDimitry Andric if (!IA)
501901095a5dSDimitry Andric return error("Invalid record");
502001095a5dSDimitry Andric }
5021b60736ecSDimitry Andric LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
5022b60736ecSDimitry Andric isImplicitCode);
5023b5efedafSRoman Divacky I->setDebugLoc(LastLoc);
50245ca98fd9SDimitry Andric I = nullptr;
5025b5efedafSRoman Divacky continue;
5026b5efedafSRoman Divacky }
5027d8e91e46SDimitry Andric case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
5028d8e91e46SDimitry Andric unsigned OpNum = 0;
5029d8e91e46SDimitry Andric Value *LHS;
5030145449b1SDimitry Andric unsigned TypeID;
5031145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
5032d8e91e46SDimitry Andric OpNum+1 > Record.size())
5033d8e91e46SDimitry Andric return error("Invalid record");
5034b5efedafSRoman Divacky
5035d8e91e46SDimitry Andric int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
5036d8e91e46SDimitry Andric if (Opc == -1)
5037d8e91e46SDimitry Andric return error("Invalid record");
5038d8e91e46SDimitry Andric I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
5039145449b1SDimitry Andric ResTypeID = TypeID;
5040d8e91e46SDimitry Andric InstructionList.push_back(I);
5041d8e91e46SDimitry Andric if (OpNum < Record.size()) {
5042d8e91e46SDimitry Andric if (isa<FPMathOperator>(I)) {
5043d8e91e46SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5044d8e91e46SDimitry Andric if (FMF.any())
5045d8e91e46SDimitry Andric I->setFastMathFlags(FMF);
5046d8e91e46SDimitry Andric }
5047d8e91e46SDimitry Andric }
5048d8e91e46SDimitry Andric break;
5049d8e91e46SDimitry Andric }
5050009b1c42SEd Schouten case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
5051009b1c42SEd Schouten unsigned OpNum = 0;
5052009b1c42SEd Schouten Value *LHS, *RHS;
5053145449b1SDimitry Andric unsigned TypeID;
5054145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
5055145449b1SDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
5056145449b1SDimitry Andric CurBB) ||
505759850d08SRoman Divacky OpNum+1 > Record.size())
50583a0822f0SDimitry Andric return error("Invalid record");
5059009b1c42SEd Schouten
50603a0822f0SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
5061f8af5cf6SDimitry Andric if (Opc == -1)
50623a0822f0SDimitry Andric return error("Invalid record");
5063009b1c42SEd Schouten I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
5064145449b1SDimitry Andric ResTypeID = TypeID;
506559850d08SRoman Divacky InstructionList.push_back(I);
506659850d08SRoman Divacky if (OpNum < Record.size()) {
506759850d08SRoman Divacky if (Opc == Instruction::Add ||
506859850d08SRoman Divacky Opc == Instruction::Sub ||
5069cf099d11SDimitry Andric Opc == Instruction::Mul ||
5070cf099d11SDimitry Andric Opc == Instruction::Shl) {
50716fe5c7aaSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
507259850d08SRoman Divacky cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
50736fe5c7aaSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
507459850d08SRoman Divacky cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
5075cf099d11SDimitry Andric } else if (Opc == Instruction::SDiv ||
5076cf099d11SDimitry Andric Opc == Instruction::UDiv ||
5077cf099d11SDimitry Andric Opc == Instruction::LShr ||
5078cf099d11SDimitry Andric Opc == Instruction::AShr) {
5079cf099d11SDimitry Andric if (Record[OpNum] & (1 << bitc::PEO_EXACT))
508059850d08SRoman Divacky cast<BinaryOperator>(I)->setIsExact(true);
5081b1c73532SDimitry Andric } else if (Opc == Instruction::Or) {
5082b1c73532SDimitry Andric if (Record[OpNum] & (1 << bitc::PDI_DISJOINT))
5083b1c73532SDimitry Andric cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
50844a16efa3SDimitry Andric } else if (isa<FPMathOperator>(I)) {
5085ee8648bdSDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
50864a16efa3SDimitry Andric if (FMF.any())
50874a16efa3SDimitry Andric I->setFastMathFlags(FMF);
508859850d08SRoman Divacky }
508959850d08SRoman Divacky }
5090009b1c42SEd Schouten break;
5091009b1c42SEd Schouten }
5092009b1c42SEd Schouten case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
5093009b1c42SEd Schouten unsigned OpNum = 0;
5094009b1c42SEd Schouten Value *Op;
5095145449b1SDimitry Andric unsigned OpTypeID;
5096145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
5097b1c73532SDimitry Andric OpNum + 1 > Record.size())
50983a0822f0SDimitry Andric return error("Invalid record");
5099009b1c42SEd Schouten
5100b1c73532SDimitry Andric ResTypeID = Record[OpNum++];
5101145449b1SDimitry Andric Type *ResTy = getTypeByID(ResTypeID);
5102b1c73532SDimitry Andric int Opc = getDecodedCastOpcode(Record[OpNum++]);
5103b1c73532SDimitry Andric
51045ca98fd9SDimitry Andric if (Opc == -1 || !ResTy)
51053a0822f0SDimitry Andric return error("Invalid record");
51065ca98fd9SDimitry Andric Instruction *Temp = nullptr;
5107f8af5cf6SDimitry Andric if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
5108f8af5cf6SDimitry Andric if (Temp) {
5109f8af5cf6SDimitry Andric InstructionList.push_back(Temp);
5110706b4fc4SDimitry Andric assert(CurBB && "No current BB?");
5111e3b55780SDimitry Andric Temp->insertInto(CurBB, CurBB->end());
5112f8af5cf6SDimitry Andric }
5113f8af5cf6SDimitry Andric } else {
5114dd58ef01SDimitry Andric auto CastOp = (Instruction::CastOps)Opc;
5115dd58ef01SDimitry Andric if (!CastInst::castIsValid(CastOp, Op, ResTy))
5116dd58ef01SDimitry Andric return error("Invalid cast");
5117dd58ef01SDimitry Andric I = CastInst::Create(CastOp, Op, ResTy);
5118f8af5cf6SDimitry Andric }
5119ac9a064cSDimitry Andric
5120ac9a064cSDimitry Andric if (OpNum < Record.size()) {
5121ac9a064cSDimitry Andric if (Opc == Instruction::ZExt || Opc == Instruction::UIToFP) {
5122ac9a064cSDimitry Andric if (Record[OpNum] & (1 << bitc::PNNI_NON_NEG))
5123ac9a064cSDimitry Andric cast<PossiblyNonNegInst>(I)->setNonNeg(true);
5124ac9a064cSDimitry Andric } else if (Opc == Instruction::Trunc) {
5125ac9a064cSDimitry Andric if (Record[OpNum] & (1 << bitc::TIO_NO_UNSIGNED_WRAP))
5126ac9a064cSDimitry Andric cast<TruncInst>(I)->setHasNoUnsignedWrap(true);
5127ac9a064cSDimitry Andric if (Record[OpNum] & (1 << bitc::TIO_NO_SIGNED_WRAP))
5128ac9a064cSDimitry Andric cast<TruncInst>(I)->setHasNoSignedWrap(true);
5129ac9a064cSDimitry Andric }
5130ac9a064cSDimitry Andric }
5131ac9a064cSDimitry Andric
513259850d08SRoman Divacky InstructionList.push_back(I);
5133009b1c42SEd Schouten break;
5134009b1c42SEd Schouten }
51355a5ac124SDimitry Andric case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
51365a5ac124SDimitry Andric case bitc::FUNC_CODE_INST_GEP_OLD:
51375a5ac124SDimitry Andric case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
5138009b1c42SEd Schouten unsigned OpNum = 0;
51395a5ac124SDimitry Andric
5140145449b1SDimitry Andric unsigned TyID;
51415a5ac124SDimitry Andric Type *Ty;
5142ac9a064cSDimitry Andric GEPNoWrapFlags NW;
51435a5ac124SDimitry Andric
51445a5ac124SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_GEP) {
5145ac9a064cSDimitry Andric NW = toGEPNoWrapFlags(Record[OpNum++]);
5146145449b1SDimitry Andric TyID = Record[OpNum++];
5147145449b1SDimitry Andric Ty = getTypeByID(TyID);
51485a5ac124SDimitry Andric } else {
5149ac9a064cSDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD)
5150ac9a064cSDimitry Andric NW = GEPNoWrapFlags::inBounds();
5151145449b1SDimitry Andric TyID = InvalidTypeID;
51525a5ac124SDimitry Andric Ty = nullptr;
51535a5ac124SDimitry Andric }
51545a5ac124SDimitry Andric
5155009b1c42SEd Schouten Value *BasePtr;
5156145449b1SDimitry Andric unsigned BasePtrTypeID;
5157145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5158145449b1SDimitry Andric CurBB))
51593a0822f0SDimitry Andric return error("Invalid record");
5160009b1c42SEd Schouten
5161e6d15924SDimitry Andric if (!Ty) {
5162145449b1SDimitry Andric TyID = getContainedTypeID(BasePtrTypeID);
5163145449b1SDimitry Andric if (BasePtr->getType()->isVectorTy())
5164145449b1SDimitry Andric TyID = getContainedTypeID(TyID);
5165145449b1SDimitry Andric Ty = getTypeByID(TyID);
5166344a3780SDimitry Andric }
51675a5ac124SDimitry Andric
5168009b1c42SEd Schouten SmallVector<Value*, 16> GEPIdx;
5169009b1c42SEd Schouten while (OpNum != Record.size()) {
5170009b1c42SEd Schouten Value *Op;
5171145449b1SDimitry Andric unsigned OpTypeID;
5172145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
51733a0822f0SDimitry Andric return error("Invalid record");
5174009b1c42SEd Schouten GEPIdx.push_back(Op);
5175009b1c42SEd Schouten }
5176009b1c42SEd Schouten
5177ac9a064cSDimitry Andric auto *GEP = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
5178ac9a064cSDimitry Andric I = GEP;
51795a5ac124SDimitry Andric
5180145449b1SDimitry Andric ResTypeID = TyID;
5181145449b1SDimitry Andric if (cast<GEPOperator>(I)->getNumIndices() != 0) {
5182145449b1SDimitry Andric auto GTI = std::next(gep_type_begin(I));
5183145449b1SDimitry Andric for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
5184145449b1SDimitry Andric unsigned SubType = 0;
5185145449b1SDimitry Andric if (GTI.isStruct()) {
5186145449b1SDimitry Andric ConstantInt *IdxC =
5187145449b1SDimitry Andric Idx->getType()->isVectorTy()
5188145449b1SDimitry Andric ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
5189145449b1SDimitry Andric : cast<ConstantInt>(Idx);
5190145449b1SDimitry Andric SubType = IdxC->getZExtValue();
5191145449b1SDimitry Andric }
5192145449b1SDimitry Andric ResTypeID = getContainedTypeID(ResTypeID, SubType);
5193145449b1SDimitry Andric ++GTI;
5194145449b1SDimitry Andric }
5195145449b1SDimitry Andric }
5196145449b1SDimitry Andric
5197145449b1SDimitry Andric // At this point ResTypeID is the result element type. We need a pointer
5198145449b1SDimitry Andric // or vector of pointer to it.
5199145449b1SDimitry Andric ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
5200145449b1SDimitry Andric if (I->getType()->isVectorTy())
5201145449b1SDimitry Andric ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5202145449b1SDimitry Andric
520359850d08SRoman Divacky InstructionList.push_back(I);
5204ac9a064cSDimitry Andric GEP->setNoWrapFlags(NW);
5205009b1c42SEd Schouten break;
5206009b1c42SEd Schouten }
5207009b1c42SEd Schouten
5208009b1c42SEd Schouten case bitc::FUNC_CODE_INST_EXTRACTVAL: {
5209009b1c42SEd Schouten // EXTRACTVAL: [opty, opval, n x indices]
5210009b1c42SEd Schouten unsigned OpNum = 0;
5211009b1c42SEd Schouten Value *Agg;
5212145449b1SDimitry Andric unsigned AggTypeID;
5213145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
52143a0822f0SDimitry Andric return error("Invalid record");
5215344a3780SDimitry Andric Type *Ty = Agg->getType();
5216009b1c42SEd Schouten
52175a5ac124SDimitry Andric unsigned RecSize = Record.size();
52185a5ac124SDimitry Andric if (OpNum == RecSize)
52193a0822f0SDimitry Andric return error("EXTRACTVAL: Invalid instruction with 0 indices");
52205a5ac124SDimitry Andric
5221009b1c42SEd Schouten SmallVector<unsigned, 4> EXTRACTVALIdx;
5222145449b1SDimitry Andric ResTypeID = AggTypeID;
52235a5ac124SDimitry Andric for (; OpNum != RecSize; ++OpNum) {
5224344a3780SDimitry Andric bool IsArray = Ty->isArrayTy();
5225344a3780SDimitry Andric bool IsStruct = Ty->isStructTy();
5226009b1c42SEd Schouten uint64_t Index = Record[OpNum];
52275a5ac124SDimitry Andric
52285a5ac124SDimitry Andric if (!IsStruct && !IsArray)
52293a0822f0SDimitry Andric return error("EXTRACTVAL: Invalid type");
5230009b1c42SEd Schouten if ((unsigned)Index != Index)
52313a0822f0SDimitry Andric return error("Invalid value");
5232344a3780SDimitry Andric if (IsStruct && Index >= Ty->getStructNumElements())
52333a0822f0SDimitry Andric return error("EXTRACTVAL: Invalid struct index");
5234344a3780SDimitry Andric if (IsArray && Index >= Ty->getArrayNumElements())
52353a0822f0SDimitry Andric return error("EXTRACTVAL: Invalid array index");
5236009b1c42SEd Schouten EXTRACTVALIdx.push_back((unsigned)Index);
52375a5ac124SDimitry Andric
5238145449b1SDimitry Andric if (IsStruct) {
5239344a3780SDimitry Andric Ty = Ty->getStructElementType(Index);
5240145449b1SDimitry Andric ResTypeID = getContainedTypeID(ResTypeID, Index);
5241145449b1SDimitry Andric } else {
5242344a3780SDimitry Andric Ty = Ty->getArrayElementType();
5243145449b1SDimitry Andric ResTypeID = getContainedTypeID(ResTypeID);
5244145449b1SDimitry Andric }
5245009b1c42SEd Schouten }
5246009b1c42SEd Schouten
5247411bd29eSDimitry Andric I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
524859850d08SRoman Divacky InstructionList.push_back(I);
5249009b1c42SEd Schouten break;
5250009b1c42SEd Schouten }
5251009b1c42SEd Schouten
5252009b1c42SEd Schouten case bitc::FUNC_CODE_INST_INSERTVAL: {
5253009b1c42SEd Schouten // INSERTVAL: [opty, opval, opty, opval, n x indices]
5254009b1c42SEd Schouten unsigned OpNum = 0;
5255009b1c42SEd Schouten Value *Agg;
5256145449b1SDimitry Andric unsigned AggTypeID;
5257145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
52583a0822f0SDimitry Andric return error("Invalid record");
5259009b1c42SEd Schouten Value *Val;
5260145449b1SDimitry Andric unsigned ValTypeID;
5261145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
52623a0822f0SDimitry Andric return error("Invalid record");
5263009b1c42SEd Schouten
52645a5ac124SDimitry Andric unsigned RecSize = Record.size();
52655a5ac124SDimitry Andric if (OpNum == RecSize)
52663a0822f0SDimitry Andric return error("INSERTVAL: Invalid instruction with 0 indices");
52675a5ac124SDimitry Andric
5268009b1c42SEd Schouten SmallVector<unsigned, 4> INSERTVALIdx;
52695a5ac124SDimitry Andric Type *CurTy = Agg->getType();
52705a5ac124SDimitry Andric for (; OpNum != RecSize; ++OpNum) {
52715a5ac124SDimitry Andric bool IsArray = CurTy->isArrayTy();
52725a5ac124SDimitry Andric bool IsStruct = CurTy->isStructTy();
5273009b1c42SEd Schouten uint64_t Index = Record[OpNum];
52745a5ac124SDimitry Andric
52755a5ac124SDimitry Andric if (!IsStruct && !IsArray)
52763a0822f0SDimitry Andric return error("INSERTVAL: Invalid type");
5277009b1c42SEd Schouten if ((unsigned)Index != Index)
52783a0822f0SDimitry Andric return error("Invalid value");
5279d8e91e46SDimitry Andric if (IsStruct && Index >= CurTy->getStructNumElements())
52803a0822f0SDimitry Andric return error("INSERTVAL: Invalid struct index");
52815a5ac124SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements())
52823a0822f0SDimitry Andric return error("INSERTVAL: Invalid array index");
52835a5ac124SDimitry Andric
5284009b1c42SEd Schouten INSERTVALIdx.push_back((unsigned)Index);
52855a5ac124SDimitry Andric if (IsStruct)
5286d8e91e46SDimitry Andric CurTy = CurTy->getStructElementType(Index);
52875a5ac124SDimitry Andric else
5288d8e91e46SDimitry Andric CurTy = CurTy->getArrayElementType();
5289009b1c42SEd Schouten }
5290009b1c42SEd Schouten
52915a5ac124SDimitry Andric if (CurTy != Val->getType())
52923a0822f0SDimitry Andric return error("Inserted value type doesn't match aggregate type");
52935a5ac124SDimitry Andric
5294411bd29eSDimitry Andric I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
5295145449b1SDimitry Andric ResTypeID = AggTypeID;
529659850d08SRoman Divacky InstructionList.push_back(I);
5297009b1c42SEd Schouten break;
5298009b1c42SEd Schouten }
5299009b1c42SEd Schouten
5300009b1c42SEd Schouten case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
5301009b1c42SEd Schouten // obsolete form of select
5302009b1c42SEd Schouten // handles select i1 ... in old bitcode
5303009b1c42SEd Schouten unsigned OpNum = 0;
5304009b1c42SEd Schouten Value *TrueVal, *FalseVal, *Cond;
5305145449b1SDimitry Andric unsigned TypeID;
5306145449b1SDimitry Andric Type *CondType = Type::getInt1Ty(Context);
5307145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
5308145449b1SDimitry Andric CurBB) ||
5309145449b1SDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
5310145449b1SDimitry Andric FalseVal, CurBB) ||
5311145449b1SDimitry Andric popValue(Record, OpNum, NextValueNo, CondType,
5312145449b1SDimitry Andric getVirtualTypeID(CondType), Cond, CurBB))
53133a0822f0SDimitry Andric return error("Invalid record");
5314009b1c42SEd Schouten
5315009b1c42SEd Schouten I = SelectInst::Create(Cond, TrueVal, FalseVal);
5316145449b1SDimitry Andric ResTypeID = TypeID;
531759850d08SRoman Divacky InstructionList.push_back(I);
5318009b1c42SEd Schouten break;
5319009b1c42SEd Schouten }
5320009b1c42SEd Schouten
5321009b1c42SEd Schouten case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
5322009b1c42SEd Schouten // new form of select
5323009b1c42SEd Schouten // handles select i1 or select [N x i1]
5324009b1c42SEd Schouten unsigned OpNum = 0;
5325009b1c42SEd Schouten Value *TrueVal, *FalseVal, *Cond;
5326145449b1SDimitry Andric unsigned ValTypeID, CondTypeID;
5327145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5328145449b1SDimitry Andric CurBB) ||
5329145449b1SDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
5330145449b1SDimitry Andric FalseVal, CurBB) ||
5331145449b1SDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
53323a0822f0SDimitry Andric return error("Invalid record");
5333009b1c42SEd Schouten
5334009b1c42SEd Schouten // select condition can be either i1 or [N x i1]
533530815c53SDimitry Andric if (VectorType* vector_type =
533630815c53SDimitry Andric dyn_cast<VectorType>(Cond->getType())) {
5337009b1c42SEd Schouten // expect <n x i1>
533859850d08SRoman Divacky if (vector_type->getElementType() != Type::getInt1Ty(Context))
53393a0822f0SDimitry Andric return error("Invalid type for value");
5340009b1c42SEd Schouten } else {
5341009b1c42SEd Schouten // expect i1
534259850d08SRoman Divacky if (Cond->getType() != Type::getInt1Ty(Context))
53433a0822f0SDimitry Andric return error("Invalid type for value");
5344009b1c42SEd Schouten }
5345009b1c42SEd Schouten
5346009b1c42SEd Schouten I = SelectInst::Create(Cond, TrueVal, FalseVal);
5347145449b1SDimitry Andric ResTypeID = ValTypeID;
534859850d08SRoman Divacky InstructionList.push_back(I);
5349e6d15924SDimitry Andric if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
5350e6d15924SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5351e6d15924SDimitry Andric if (FMF.any())
5352e6d15924SDimitry Andric I->setFastMathFlags(FMF);
5353e6d15924SDimitry Andric }
5354009b1c42SEd Schouten break;
5355009b1c42SEd Schouten }
5356009b1c42SEd Schouten
5357009b1c42SEd Schouten case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
5358009b1c42SEd Schouten unsigned OpNum = 0;
5359009b1c42SEd Schouten Value *Vec, *Idx;
5360145449b1SDimitry Andric unsigned VecTypeID, IdxTypeID;
5361145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5362145449b1SDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
53633a0822f0SDimitry Andric return error("Invalid record");
53645a5ac124SDimitry Andric if (!Vec->getType()->isVectorTy())
53653a0822f0SDimitry Andric return error("Invalid type for value");
536659850d08SRoman Divacky I = ExtractElementInst::Create(Vec, Idx);
5367145449b1SDimitry Andric ResTypeID = getContainedTypeID(VecTypeID);
536859850d08SRoman Divacky InstructionList.push_back(I);
5369009b1c42SEd Schouten break;
5370009b1c42SEd Schouten }
5371009b1c42SEd Schouten
5372009b1c42SEd Schouten case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
5373009b1c42SEd Schouten unsigned OpNum = 0;
5374009b1c42SEd Schouten Value *Vec, *Elt, *Idx;
5375145449b1SDimitry Andric unsigned VecTypeID, IdxTypeID;
5376145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
53773a0822f0SDimitry Andric return error("Invalid record");
53785a5ac124SDimitry Andric if (!Vec->getType()->isVectorTy())
53793a0822f0SDimitry Andric return error("Invalid type for value");
53805a5ac124SDimitry Andric if (popValue(Record, OpNum, NextValueNo,
5381145449b1SDimitry Andric cast<VectorType>(Vec->getType())->getElementType(),
5382145449b1SDimitry Andric getContainedTypeID(VecTypeID), Elt, CurBB) ||
5383145449b1SDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
53843a0822f0SDimitry Andric return error("Invalid record");
5385009b1c42SEd Schouten I = InsertElementInst::Create(Vec, Elt, Idx);
5386145449b1SDimitry Andric ResTypeID = VecTypeID;
538759850d08SRoman Divacky InstructionList.push_back(I);
5388009b1c42SEd Schouten break;
5389009b1c42SEd Schouten }
5390009b1c42SEd Schouten
5391009b1c42SEd Schouten case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
5392009b1c42SEd Schouten unsigned OpNum = 0;
5393009b1c42SEd Schouten Value *Vec1, *Vec2, *Mask;
5394145449b1SDimitry Andric unsigned Vec1TypeID;
5395145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5396145449b1SDimitry Andric CurBB) ||
5397145449b1SDimitry Andric popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
5398145449b1SDimitry Andric Vec2, CurBB))
53993a0822f0SDimitry Andric return error("Invalid record");
5400009b1c42SEd Schouten
5401145449b1SDimitry Andric unsigned MaskTypeID;
5402145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
54033a0822f0SDimitry Andric return error("Invalid record");
54045a5ac124SDimitry Andric if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
54053a0822f0SDimitry Andric return error("Invalid type for value");
5406cfca06d7SDimitry Andric
5407009b1c42SEd Schouten I = new ShuffleVectorInst(Vec1, Vec2, Mask);
5408145449b1SDimitry Andric ResTypeID =
5409145449b1SDimitry Andric getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
541059850d08SRoman Divacky InstructionList.push_back(I);
5411009b1c42SEd Schouten break;
5412009b1c42SEd Schouten }
5413009b1c42SEd Schouten
541459850d08SRoman Divacky case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
541559850d08SRoman Divacky // Old form of ICmp/FCmp returning bool
541659850d08SRoman Divacky // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
541759850d08SRoman Divacky // both legal on vectors but had different behaviour.
541859850d08SRoman Divacky case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
541959850d08SRoman Divacky // FCmp/ICmp returning bool or vector of bool
542059850d08SRoman Divacky
5421009b1c42SEd Schouten unsigned OpNum = 0;
5422009b1c42SEd Schouten Value *LHS, *RHS;
5423145449b1SDimitry Andric unsigned LHSTypeID;
5424145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
5425145449b1SDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
5426145449b1SDimitry Andric CurBB))
5427ee8648bdSDimitry Andric return error("Invalid record");
5428ee8648bdSDimitry Andric
5429e6d15924SDimitry Andric if (OpNum >= Record.size())
5430e6d15924SDimitry Andric return error(
5431e6d15924SDimitry Andric "Invalid record: operand number exceeded available operands");
5432e6d15924SDimitry Andric
5433312c0ed1SDimitry Andric CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]);
5434ee8648bdSDimitry Andric bool IsFP = LHS->getType()->isFPOrFPVectorTy();
5435ee8648bdSDimitry Andric FastMathFlags FMF;
5436ee8648bdSDimitry Andric if (IsFP && Record.size() > OpNum+1)
5437ee8648bdSDimitry Andric FMF = getDecodedFastMathFlags(Record[++OpNum]);
5438ee8648bdSDimitry Andric
5439ee8648bdSDimitry Andric if (OpNum+1 != Record.size())
54403a0822f0SDimitry Andric return error("Invalid record");
5441009b1c42SEd Schouten
5442312c0ed1SDimitry Andric if (IsFP) {
5443312c0ed1SDimitry Andric if (!CmpInst::isFPPredicate(PredVal))
5444312c0ed1SDimitry Andric return error("Invalid fcmp predicate");
5445312c0ed1SDimitry Andric I = new FCmpInst(PredVal, LHS, RHS);
5446312c0ed1SDimitry Andric } else {
5447312c0ed1SDimitry Andric if (!CmpInst::isIntPredicate(PredVal))
5448312c0ed1SDimitry Andric return error("Invalid icmp predicate");
5449312c0ed1SDimitry Andric I = new ICmpInst(PredVal, LHS, RHS);
5450312c0ed1SDimitry Andric }
5451ee8648bdSDimitry Andric
5452145449b1SDimitry Andric ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
5453145449b1SDimitry Andric if (LHS->getType()->isVectorTy())
5454145449b1SDimitry Andric ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5455145449b1SDimitry Andric
5456ee8648bdSDimitry Andric if (FMF.any())
5457ee8648bdSDimitry Andric I->setFastMathFlags(FMF);
545859850d08SRoman Divacky InstructionList.push_back(I);
5459009b1c42SEd Schouten break;
5460009b1c42SEd Schouten }
546159850d08SRoman Divacky
5462009b1c42SEd Schouten case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
5463009b1c42SEd Schouten {
5464009b1c42SEd Schouten unsigned Size = Record.size();
5465009b1c42SEd Schouten if (Size == 0) {
546659850d08SRoman Divacky I = ReturnInst::Create(Context);
546759850d08SRoman Divacky InstructionList.push_back(I);
5468009b1c42SEd Schouten break;
5469009b1c42SEd Schouten }
5470009b1c42SEd Schouten
5471009b1c42SEd Schouten unsigned OpNum = 0;
54725ca98fd9SDimitry Andric Value *Op = nullptr;
5473145449b1SDimitry Andric unsigned OpTypeID;
5474145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
54753a0822f0SDimitry Andric return error("Invalid record");
5476411bd29eSDimitry Andric if (OpNum != Record.size())
54773a0822f0SDimitry Andric return error("Invalid record");
5478009b1c42SEd Schouten
5479411bd29eSDimitry Andric I = ReturnInst::Create(Context, Op);
548059850d08SRoman Divacky InstructionList.push_back(I);
5481009b1c42SEd Schouten break;
5482009b1c42SEd Schouten }
5483009b1c42SEd Schouten case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
5484009b1c42SEd Schouten if (Record.size() != 1 && Record.size() != 3)
54853a0822f0SDimitry Andric return error("Invalid record");
5486009b1c42SEd Schouten BasicBlock *TrueDest = getBasicBlock(Record[0]);
54875ca98fd9SDimitry Andric if (!TrueDest)
54883a0822f0SDimitry Andric return error("Invalid record");
5489009b1c42SEd Schouten
549059850d08SRoman Divacky if (Record.size() == 1) {
5491009b1c42SEd Schouten I = BranchInst::Create(TrueDest);
549259850d08SRoman Divacky InstructionList.push_back(I);
549359850d08SRoman Divacky }
5494009b1c42SEd Schouten else {
5495009b1c42SEd Schouten BasicBlock *FalseDest = getBasicBlock(Record[1]);
5496145449b1SDimitry Andric Type *CondType = Type::getInt1Ty(Context);
5497145449b1SDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, CondType,
5498145449b1SDimitry Andric getVirtualTypeID(CondType), CurBB);
54995ca98fd9SDimitry Andric if (!FalseDest || !Cond)
55003a0822f0SDimitry Andric return error("Invalid record");
5501009b1c42SEd Schouten I = BranchInst::Create(TrueDest, FalseDest, Cond);
550259850d08SRoman Divacky InstructionList.push_back(I);
5503009b1c42SEd Schouten }
5504009b1c42SEd Schouten break;
5505009b1c42SEd Schouten }
5506dd58ef01SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
5507dd58ef01SDimitry Andric if (Record.size() != 1 && Record.size() != 2)
5508dd58ef01SDimitry Andric return error("Invalid record");
5509dd58ef01SDimitry Andric unsigned Idx = 0;
5510145449b1SDimitry Andric Type *TokenTy = Type::getTokenTy(Context);
5511145449b1SDimitry Andric Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5512145449b1SDimitry Andric getVirtualTypeID(TokenTy), CurBB);
5513dd58ef01SDimitry Andric if (!CleanupPad)
5514dd58ef01SDimitry Andric return error("Invalid record");
5515dd58ef01SDimitry Andric BasicBlock *UnwindDest = nullptr;
5516dd58ef01SDimitry Andric if (Record.size() == 2) {
5517dd58ef01SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]);
5518dd58ef01SDimitry Andric if (!UnwindDest)
5519dd58ef01SDimitry Andric return error("Invalid record");
5520dd58ef01SDimitry Andric }
5521dd58ef01SDimitry Andric
5522dd58ef01SDimitry Andric I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
5523dd58ef01SDimitry Andric InstructionList.push_back(I);
5524dd58ef01SDimitry Andric break;
5525dd58ef01SDimitry Andric }
5526dd58ef01SDimitry Andric case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5527dd58ef01SDimitry Andric if (Record.size() != 2)
5528dd58ef01SDimitry Andric return error("Invalid record");
5529dd58ef01SDimitry Andric unsigned Idx = 0;
5530145449b1SDimitry Andric Type *TokenTy = Type::getTokenTy(Context);
5531145449b1SDimitry Andric Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5532145449b1SDimitry Andric getVirtualTypeID(TokenTy), CurBB);
5533dd58ef01SDimitry Andric if (!CatchPad)
5534dd58ef01SDimitry Andric return error("Invalid record");
5535dd58ef01SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]);
5536dd58ef01SDimitry Andric if (!BB)
5537dd58ef01SDimitry Andric return error("Invalid record");
5538dd58ef01SDimitry Andric
5539dd58ef01SDimitry Andric I = CatchReturnInst::Create(CatchPad, BB);
5540dd58ef01SDimitry Andric InstructionList.push_back(I);
5541dd58ef01SDimitry Andric break;
5542dd58ef01SDimitry Andric }
5543dd58ef01SDimitry Andric case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5544dd58ef01SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments.
5545dd58ef01SDimitry Andric if (Record.size() < 2)
5546dd58ef01SDimitry Andric return error("Invalid record");
5547dd58ef01SDimitry Andric
5548dd58ef01SDimitry Andric unsigned Idx = 0;
5549dd58ef01SDimitry Andric
5550145449b1SDimitry Andric Type *TokenTy = Type::getTokenTy(Context);
5551145449b1SDimitry Andric Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5552145449b1SDimitry Andric getVirtualTypeID(TokenTy), CurBB);
5553312c0ed1SDimitry Andric if (!ParentPad)
5554312c0ed1SDimitry Andric return error("Invalid record");
5555dd58ef01SDimitry Andric
5556dd58ef01SDimitry Andric unsigned NumHandlers = Record[Idx++];
5557dd58ef01SDimitry Andric
5558dd58ef01SDimitry Andric SmallVector<BasicBlock *, 2> Handlers;
5559dd58ef01SDimitry Andric for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5560dd58ef01SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]);
5561dd58ef01SDimitry Andric if (!BB)
5562dd58ef01SDimitry Andric return error("Invalid record");
5563dd58ef01SDimitry Andric Handlers.push_back(BB);
5564dd58ef01SDimitry Andric }
5565dd58ef01SDimitry Andric
5566dd58ef01SDimitry Andric BasicBlock *UnwindDest = nullptr;
5567dd58ef01SDimitry Andric if (Idx + 1 == Record.size()) {
5568dd58ef01SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]);
5569dd58ef01SDimitry Andric if (!UnwindDest)
5570dd58ef01SDimitry Andric return error("Invalid record");
5571dd58ef01SDimitry Andric }
5572dd58ef01SDimitry Andric
5573dd58ef01SDimitry Andric if (Record.size() != Idx)
5574dd58ef01SDimitry Andric return error("Invalid record");
5575dd58ef01SDimitry Andric
5576dd58ef01SDimitry Andric auto *CatchSwitch =
5577dd58ef01SDimitry Andric CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5578dd58ef01SDimitry Andric for (BasicBlock *Handler : Handlers)
5579dd58ef01SDimitry Andric CatchSwitch->addHandler(Handler);
5580dd58ef01SDimitry Andric I = CatchSwitch;
5581145449b1SDimitry Andric ResTypeID = getVirtualTypeID(I->getType());
5582dd58ef01SDimitry Andric InstructionList.push_back(I);
5583dd58ef01SDimitry Andric break;
5584dd58ef01SDimitry Andric }
5585dd58ef01SDimitry Andric case bitc::FUNC_CODE_INST_CATCHPAD:
5586dd58ef01SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
5587dd58ef01SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments.
5588dd58ef01SDimitry Andric if (Record.size() < 2)
5589dd58ef01SDimitry Andric return error("Invalid record");
5590dd58ef01SDimitry Andric
5591dd58ef01SDimitry Andric unsigned Idx = 0;
5592dd58ef01SDimitry Andric
5593145449b1SDimitry Andric Type *TokenTy = Type::getTokenTy(Context);
5594145449b1SDimitry Andric Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5595145449b1SDimitry Andric getVirtualTypeID(TokenTy), CurBB);
5596312c0ed1SDimitry Andric if (!ParentPad)
5597312c0ed1SDimitry Andric return error("Invald record");
5598dd58ef01SDimitry Andric
5599dd58ef01SDimitry Andric unsigned NumArgOperands = Record[Idx++];
5600dd58ef01SDimitry Andric
5601dd58ef01SDimitry Andric SmallVector<Value *, 2> Args;
5602dd58ef01SDimitry Andric for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5603dd58ef01SDimitry Andric Value *Val;
5604145449b1SDimitry Andric unsigned ValTypeID;
5605145449b1SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
5606dd58ef01SDimitry Andric return error("Invalid record");
5607dd58ef01SDimitry Andric Args.push_back(Val);
5608dd58ef01SDimitry Andric }
5609dd58ef01SDimitry Andric
5610dd58ef01SDimitry Andric if (Record.size() != Idx)
5611dd58ef01SDimitry Andric return error("Invalid record");
5612dd58ef01SDimitry Andric
5613dd58ef01SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5614dd58ef01SDimitry Andric I = CleanupPadInst::Create(ParentPad, Args);
5615dd58ef01SDimitry Andric else
5616dd58ef01SDimitry Andric I = CatchPadInst::Create(ParentPad, Args);
5617145449b1SDimitry Andric ResTypeID = getVirtualTypeID(I->getType());
5618dd58ef01SDimitry Andric InstructionList.push_back(I);
5619dd58ef01SDimitry Andric break;
5620dd58ef01SDimitry Andric }
562136bf506aSRoman Divacky case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
562258b69754SDimitry Andric // Check magic
562358b69754SDimitry Andric if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5624f8af5cf6SDimitry Andric // "New" SwitchInst format with case ranges. The changes to write this
5625f8af5cf6SDimitry Andric // format were reverted but we still recognize bitcode that uses it.
5626f8af5cf6SDimitry Andric // Hopefully someday we will have support for case ranges and can use
5627f8af5cf6SDimitry Andric // this format again.
562858b69754SDimitry Andric
5629145449b1SDimitry Andric unsigned OpTyID = Record[1];
5630145449b1SDimitry Andric Type *OpTy = getTypeByID(OpTyID);
563158b69754SDimitry Andric unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
563258b69754SDimitry Andric
5633145449b1SDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
563458b69754SDimitry Andric BasicBlock *Default = getBasicBlock(Record[3]);
56355ca98fd9SDimitry Andric if (!OpTy || !Cond || !Default)
56363a0822f0SDimitry Andric return error("Invalid record");
563758b69754SDimitry Andric
563858b69754SDimitry Andric unsigned NumCases = Record[4];
563958b69754SDimitry Andric
564058b69754SDimitry Andric SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
564158b69754SDimitry Andric InstructionList.push_back(SI);
564258b69754SDimitry Andric
564358b69754SDimitry Andric unsigned CurIdx = 5;
564458b69754SDimitry Andric for (unsigned i = 0; i != NumCases; ++i) {
5645f8af5cf6SDimitry Andric SmallVector<ConstantInt*, 1> CaseVals;
564658b69754SDimitry Andric unsigned NumItems = Record[CurIdx++];
564758b69754SDimitry Andric for (unsigned ci = 0; ci != NumItems; ++ci) {
564858b69754SDimitry Andric bool isSingleNumber = Record[CurIdx++];
564958b69754SDimitry Andric
565058b69754SDimitry Andric APInt Low;
565158b69754SDimitry Andric unsigned ActiveWords = 1;
565258b69754SDimitry Andric if (ValueBitWidth > 64)
565358b69754SDimitry Andric ActiveWords = Record[CurIdx++];
5654e3b55780SDimitry Andric Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
565558b69754SDimitry Andric ValueBitWidth);
565658b69754SDimitry Andric CurIdx += ActiveWords;
565758b69754SDimitry Andric
565858b69754SDimitry Andric if (!isSingleNumber) {
565958b69754SDimitry Andric ActiveWords = 1;
566058b69754SDimitry Andric if (ValueBitWidth > 64)
566158b69754SDimitry Andric ActiveWords = Record[CurIdx++];
5662e3b55780SDimitry Andric APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5663e3b55780SDimitry Andric ValueBitWidth);
566458b69754SDimitry Andric CurIdx += ActiveWords;
5665f8af5cf6SDimitry Andric
5666f8af5cf6SDimitry Andric // FIXME: It is not clear whether values in the range should be
5667f8af5cf6SDimitry Andric // compared as signed or unsigned values. The partially
5668f8af5cf6SDimitry Andric // implemented changes that used this format in the past used
5669f8af5cf6SDimitry Andric // unsigned comparisons.
5670f8af5cf6SDimitry Andric for ( ; Low.ule(High); ++Low)
5671f8af5cf6SDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low));
567258b69754SDimitry Andric } else
5673f8af5cf6SDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low));
567458b69754SDimitry Andric }
567558b69754SDimitry Andric BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5676f65dcba8SDimitry Andric for (ConstantInt *Cst : CaseVals)
5677f65dcba8SDimitry Andric SI->addCase(Cst, DestBB);
567858b69754SDimitry Andric }
567958b69754SDimitry Andric I = SI;
568058b69754SDimitry Andric break;
568158b69754SDimitry Andric }
568258b69754SDimitry Andric
568358b69754SDimitry Andric // Old SwitchInst format without case ranges.
568458b69754SDimitry Andric
5685009b1c42SEd Schouten if (Record.size() < 3 || (Record.size() & 1) == 0)
56863a0822f0SDimitry Andric return error("Invalid record");
5687145449b1SDimitry Andric unsigned OpTyID = Record[0];
5688145449b1SDimitry Andric Type *OpTy = getTypeByID(OpTyID);
5689145449b1SDimitry Andric Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5690009b1c42SEd Schouten BasicBlock *Default = getBasicBlock(Record[2]);
56915ca98fd9SDimitry Andric if (!OpTy || !Cond || !Default)
56923a0822f0SDimitry Andric return error("Invalid record");
5693009b1c42SEd Schouten unsigned NumCases = (Record.size()-3)/2;
5694009b1c42SEd Schouten SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
569559850d08SRoman Divacky InstructionList.push_back(SI);
5696009b1c42SEd Schouten for (unsigned i = 0, e = NumCases; i != e; ++i) {
5697145449b1SDimitry Andric ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
5698145449b1SDimitry Andric getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
5699009b1c42SEd Schouten BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
57005ca98fd9SDimitry Andric if (!CaseVal || !DestBB) {
5701009b1c42SEd Schouten delete SI;
57023a0822f0SDimitry Andric return error("Invalid record");
5703009b1c42SEd Schouten }
5704009b1c42SEd Schouten SI->addCase(CaseVal, DestBB);
5705009b1c42SEd Schouten }
5706009b1c42SEd Schouten I = SI;
5707009b1c42SEd Schouten break;
5708009b1c42SEd Schouten }
570936bf506aSRoman Divacky case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
571036bf506aSRoman Divacky if (Record.size() < 2)
57113a0822f0SDimitry Andric return error("Invalid record");
5712145449b1SDimitry Andric unsigned OpTyID = Record[0];
5713145449b1SDimitry Andric Type *OpTy = getTypeByID(OpTyID);
5714145449b1SDimitry Andric Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
57155ca98fd9SDimitry Andric if (!OpTy || !Address)
57163a0822f0SDimitry Andric return error("Invalid record");
571736bf506aSRoman Divacky unsigned NumDests = Record.size()-2;
571836bf506aSRoman Divacky IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
571936bf506aSRoman Divacky InstructionList.push_back(IBI);
572036bf506aSRoman Divacky for (unsigned i = 0, e = NumDests; i != e; ++i) {
572136bf506aSRoman Divacky if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
572236bf506aSRoman Divacky IBI->addDestination(DestBB);
572336bf506aSRoman Divacky } else {
572436bf506aSRoman Divacky delete IBI;
57253a0822f0SDimitry Andric return error("Invalid record");
572636bf506aSRoman Divacky }
572736bf506aSRoman Divacky }
572836bf506aSRoman Divacky I = IBI;
572936bf506aSRoman Divacky break;
573036bf506aSRoman Divacky }
5731009b1c42SEd Schouten
5732009b1c42SEd Schouten case bitc::FUNC_CODE_INST_INVOKE: {
5733009b1c42SEd Schouten // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5734f8af5cf6SDimitry Andric if (Record.size() < 4)
57353a0822f0SDimitry Andric return error("Invalid record");
57365a5ac124SDimitry Andric unsigned OpNum = 0;
573771d5a254SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]);
57385a5ac124SDimitry Andric unsigned CCInfo = Record[OpNum++];
57395a5ac124SDimitry Andric BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
57405a5ac124SDimitry Andric BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5741009b1c42SEd Schouten
5742145449b1SDimitry Andric unsigned FTyID = InvalidTypeID;
57435a5ac124SDimitry Andric FunctionType *FTy = nullptr;
5744e6d15924SDimitry Andric if ((CCInfo >> 13) & 1) {
5745145449b1SDimitry Andric FTyID = Record[OpNum++];
5746145449b1SDimitry Andric FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5747344a3780SDimitry Andric if (!FTy)
57483a0822f0SDimitry Andric return error("Explicit invoke type is not a function type");
5749e6d15924SDimitry Andric }
57505a5ac124SDimitry Andric
5751009b1c42SEd Schouten Value *Callee;
5752145449b1SDimitry Andric unsigned CalleeTypeID;
5753145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5754145449b1SDimitry Andric CurBB))
57553a0822f0SDimitry Andric return error("Invalid record");
5756009b1c42SEd Schouten
575730815c53SDimitry Andric PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
57585a5ac124SDimitry Andric if (!CalleeTy)
57593a0822f0SDimitry Andric return error("Callee is not a pointer");
57605a5ac124SDimitry Andric if (!FTy) {
5761145449b1SDimitry Andric FTyID = getContainedTypeID(CalleeTypeID);
5762145449b1SDimitry Andric FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5763344a3780SDimitry Andric if (!FTy)
57643a0822f0SDimitry Andric return error("Callee is not of pointer to function type");
57657fa27ce4SDimitry Andric }
57665a5ac124SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum)
57673a0822f0SDimitry Andric return error("Insufficient operands to call");
5768009b1c42SEd Schouten
5769009b1c42SEd Schouten SmallVector<Value*, 16> Ops;
5770145449b1SDimitry Andric SmallVector<unsigned, 16> ArgTyIDs;
5771009b1c42SEd Schouten for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5772145449b1SDimitry Andric unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5773145449b1SDimitry Andric Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5774145449b1SDimitry Andric ArgTyID, CurBB));
5775145449b1SDimitry Andric ArgTyIDs.push_back(ArgTyID);
57765ca98fd9SDimitry Andric if (!Ops.back())
57773a0822f0SDimitry Andric return error("Invalid record");
5778009b1c42SEd Schouten }
5779009b1c42SEd Schouten
5780009b1c42SEd Schouten if (!FTy->isVarArg()) {
5781009b1c42SEd Schouten if (Record.size() != OpNum)
57823a0822f0SDimitry Andric return error("Invalid record");
5783009b1c42SEd Schouten } else {
5784009b1c42SEd Schouten // Read type/value pairs for varargs params.
5785009b1c42SEd Schouten while (OpNum != Record.size()) {
5786009b1c42SEd Schouten Value *Op;
5787145449b1SDimitry Andric unsigned OpTypeID;
5788145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
57893a0822f0SDimitry Andric return error("Invalid record");
5790009b1c42SEd Schouten Ops.push_back(Op);
5791145449b1SDimitry Andric ArgTyIDs.push_back(OpTypeID);
5792009b1c42SEd Schouten }
5793009b1c42SEd Schouten }
5794009b1c42SEd Schouten
5795145449b1SDimitry Andric // Upgrade the bundles if needed.
5796145449b1SDimitry Andric if (!OperandBundles.empty())
5797145449b1SDimitry Andric UpgradeOperandBundles(OperandBundles);
5798145449b1SDimitry Andric
5799e6d15924SDimitry Andric I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
5800e6d15924SDimitry Andric OperandBundles);
5801145449b1SDimitry Andric ResTypeID = getContainedTypeID(FTyID);
5802dd58ef01SDimitry Andric OperandBundles.clear();
580359850d08SRoman Divacky InstructionList.push_back(I);
5804dd58ef01SDimitry Andric cast<InvokeInst>(I)->setCallingConv(
5805dd58ef01SDimitry Andric static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5806009b1c42SEd Schouten cast<InvokeInst>(I)->setAttributes(PAL);
5807145449b1SDimitry Andric if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
5808145449b1SDimitry Andric I->deleteValue();
5809145449b1SDimitry Andric return Err;
5810145449b1SDimitry Andric }
5811e6d15924SDimitry Andric
5812009b1c42SEd Schouten break;
5813009b1c42SEd Schouten }
581430815c53SDimitry Andric case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
581530815c53SDimitry Andric unsigned Idx = 0;
58165ca98fd9SDimitry Andric Value *Val = nullptr;
5817145449b1SDimitry Andric unsigned ValTypeID;
5818145449b1SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
58193a0822f0SDimitry Andric return error("Invalid record");
582030815c53SDimitry Andric I = ResumeInst::Create(Val);
582130815c53SDimitry Andric InstructionList.push_back(I);
582230815c53SDimitry Andric break;
582330815c53SDimitry Andric }
5824e6d15924SDimitry Andric case bitc::FUNC_CODE_INST_CALLBR: {
5825e6d15924SDimitry Andric // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
5826e6d15924SDimitry Andric unsigned OpNum = 0;
5827e6d15924SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]);
5828e6d15924SDimitry Andric unsigned CCInfo = Record[OpNum++];
5829e6d15924SDimitry Andric
5830e6d15924SDimitry Andric BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5831e6d15924SDimitry Andric unsigned NumIndirectDests = Record[OpNum++];
5832e6d15924SDimitry Andric SmallVector<BasicBlock *, 16> IndirectDests;
5833e6d15924SDimitry Andric for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
5834e6d15924SDimitry Andric IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
5835e6d15924SDimitry Andric
5836145449b1SDimitry Andric unsigned FTyID = InvalidTypeID;
5837e6d15924SDimitry Andric FunctionType *FTy = nullptr;
5838e6d15924SDimitry Andric if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5839145449b1SDimitry Andric FTyID = Record[OpNum++];
5840145449b1SDimitry Andric FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5841344a3780SDimitry Andric if (!FTy)
5842e6d15924SDimitry Andric return error("Explicit call type is not a function type");
5843e6d15924SDimitry Andric }
5844e6d15924SDimitry Andric
5845e6d15924SDimitry Andric Value *Callee;
5846145449b1SDimitry Andric unsigned CalleeTypeID;
5847145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5848145449b1SDimitry Andric CurBB))
5849e6d15924SDimitry Andric return error("Invalid record");
5850e6d15924SDimitry Andric
5851e6d15924SDimitry Andric PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5852e6d15924SDimitry Andric if (!OpTy)
5853e6d15924SDimitry Andric return error("Callee is not a pointer type");
5854e6d15924SDimitry Andric if (!FTy) {
5855145449b1SDimitry Andric FTyID = getContainedTypeID(CalleeTypeID);
5856145449b1SDimitry Andric FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5857344a3780SDimitry Andric if (!FTy)
5858e6d15924SDimitry Andric return error("Callee is not of pointer to function type");
58597fa27ce4SDimitry Andric }
5860e6d15924SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum)
5861e6d15924SDimitry Andric return error("Insufficient operands to call");
5862e6d15924SDimitry Andric
5863e6d15924SDimitry Andric SmallVector<Value*, 16> Args;
5864145449b1SDimitry Andric SmallVector<unsigned, 16> ArgTyIDs;
5865e6d15924SDimitry Andric // Read the fixed params.
5866e6d15924SDimitry Andric for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
58676f8fc217SDimitry Andric Value *Arg;
5868145449b1SDimitry Andric unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5869e6d15924SDimitry Andric if (FTy->getParamType(i)->isLabelTy())
58706f8fc217SDimitry Andric Arg = getBasicBlock(Record[OpNum]);
5871e6d15924SDimitry Andric else
5872145449b1SDimitry Andric Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5873145449b1SDimitry Andric ArgTyID, CurBB);
58746f8fc217SDimitry Andric if (!Arg)
5875e6d15924SDimitry Andric return error("Invalid record");
58766f8fc217SDimitry Andric Args.push_back(Arg);
5877145449b1SDimitry Andric ArgTyIDs.push_back(ArgTyID);
5878e6d15924SDimitry Andric }
5879e6d15924SDimitry Andric
5880e6d15924SDimitry Andric // Read type/value pairs for varargs params.
5881e6d15924SDimitry Andric if (!FTy->isVarArg()) {
5882e6d15924SDimitry Andric if (OpNum != Record.size())
5883e6d15924SDimitry Andric return error("Invalid record");
5884e6d15924SDimitry Andric } else {
5885e6d15924SDimitry Andric while (OpNum != Record.size()) {
5886e6d15924SDimitry Andric Value *Op;
5887145449b1SDimitry Andric unsigned OpTypeID;
5888145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5889e6d15924SDimitry Andric return error("Invalid record");
5890e6d15924SDimitry Andric Args.push_back(Op);
5891145449b1SDimitry Andric ArgTyIDs.push_back(OpTypeID);
5892e6d15924SDimitry Andric }
5893e6d15924SDimitry Andric }
5894e6d15924SDimitry Andric
5895145449b1SDimitry Andric // Upgrade the bundles if needed.
5896145449b1SDimitry Andric if (!OperandBundles.empty())
5897145449b1SDimitry Andric UpgradeOperandBundles(OperandBundles);
5898145449b1SDimitry Andric
58994b4fe385SDimitry Andric if (auto *IA = dyn_cast<InlineAsm>(Callee)) {
59004b4fe385SDimitry Andric InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints();
59014b4fe385SDimitry Andric auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) {
59024b4fe385SDimitry Andric return CI.Type == InlineAsm::isLabel;
59034b4fe385SDimitry Andric };
59044b4fe385SDimitry Andric if (none_of(ConstraintInfo, IsLabelConstraint)) {
59054b4fe385SDimitry Andric // Upgrade explicit blockaddress arguments to label constraints.
59064b4fe385SDimitry Andric // Verify that the last arguments are blockaddress arguments that
59074b4fe385SDimitry Andric // match the indirect destinations. Clang always generates callbr
59084b4fe385SDimitry Andric // in this form. We could support reordering with more effort.
59094b4fe385SDimitry Andric unsigned FirstBlockArg = Args.size() - IndirectDests.size();
59104b4fe385SDimitry Andric for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) {
59114b4fe385SDimitry Andric unsigned LabelNo = ArgNo - FirstBlockArg;
59124b4fe385SDimitry Andric auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
59134b4fe385SDimitry Andric if (!BA || BA->getFunction() != F ||
59144b4fe385SDimitry Andric LabelNo > IndirectDests.size() ||
59154b4fe385SDimitry Andric BA->getBasicBlock() != IndirectDests[LabelNo])
59164b4fe385SDimitry Andric return error("callbr argument does not match indirect dest");
59174b4fe385SDimitry Andric }
59184b4fe385SDimitry Andric
59194b4fe385SDimitry Andric // Remove blockaddress arguments.
59204b4fe385SDimitry Andric Args.erase(Args.begin() + FirstBlockArg, Args.end());
59214b4fe385SDimitry Andric ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end());
59224b4fe385SDimitry Andric
59234b4fe385SDimitry Andric // Recreate the function type with less arguments.
59244b4fe385SDimitry Andric SmallVector<Type *> ArgTys;
59254b4fe385SDimitry Andric for (Value *Arg : Args)
59264b4fe385SDimitry Andric ArgTys.push_back(Arg->getType());
59274b4fe385SDimitry Andric FTy =
59284b4fe385SDimitry Andric FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
59294b4fe385SDimitry Andric
59304b4fe385SDimitry Andric // Update constraint string to use label constraints.
59314b4fe385SDimitry Andric std::string Constraints = IA->getConstraintString();
59324b4fe385SDimitry Andric unsigned ArgNo = 0;
59334b4fe385SDimitry Andric size_t Pos = 0;
59344b4fe385SDimitry Andric for (const auto &CI : ConstraintInfo) {
59354b4fe385SDimitry Andric if (CI.hasArg()) {
59364b4fe385SDimitry Andric if (ArgNo >= FirstBlockArg)
59374b4fe385SDimitry Andric Constraints.insert(Pos, "!");
59384b4fe385SDimitry Andric ++ArgNo;
59394b4fe385SDimitry Andric }
59404b4fe385SDimitry Andric
59414b4fe385SDimitry Andric // Go to next constraint in string.
59424b4fe385SDimitry Andric Pos = Constraints.find(',', Pos);
59434b4fe385SDimitry Andric if (Pos == std::string::npos)
59444b4fe385SDimitry Andric break;
59454b4fe385SDimitry Andric ++Pos;
59464b4fe385SDimitry Andric }
59474b4fe385SDimitry Andric
59484b4fe385SDimitry Andric Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints,
59494b4fe385SDimitry Andric IA->hasSideEffects(), IA->isAlignStack(),
59504b4fe385SDimitry Andric IA->getDialect(), IA->canThrow());
59514b4fe385SDimitry Andric }
59524b4fe385SDimitry Andric }
59534b4fe385SDimitry Andric
5954e6d15924SDimitry Andric I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
5955e6d15924SDimitry Andric OperandBundles);
5956145449b1SDimitry Andric ResTypeID = getContainedTypeID(FTyID);
5957e6d15924SDimitry Andric OperandBundles.clear();
5958e6d15924SDimitry Andric InstructionList.push_back(I);
5959e6d15924SDimitry Andric cast<CallBrInst>(I)->setCallingConv(
5960e6d15924SDimitry Andric static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5961e6d15924SDimitry Andric cast<CallBrInst>(I)->setAttributes(PAL);
5962145449b1SDimitry Andric if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
5963145449b1SDimitry Andric I->deleteValue();
5964145449b1SDimitry Andric return Err;
5965145449b1SDimitry Andric }
5966e6d15924SDimitry Andric break;
5967e6d15924SDimitry Andric }
5968009b1c42SEd Schouten case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
596959850d08SRoman Divacky I = new UnreachableInst(Context);
597059850d08SRoman Divacky InstructionList.push_back(I);
5971009b1c42SEd Schouten break;
5972009b1c42SEd Schouten case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5973b60736ecSDimitry Andric if (Record.empty())
5974145449b1SDimitry Andric return error("Invalid phi record");
59751d5ae102SDimitry Andric // The first record specifies the type.
5976145449b1SDimitry Andric unsigned TyID = Record[0];
5977145449b1SDimitry Andric Type *Ty = getTypeByID(TyID);
5978f8af5cf6SDimitry Andric if (!Ty)
5979145449b1SDimitry Andric return error("Invalid phi record");
5980009b1c42SEd Schouten
59811d5ae102SDimitry Andric // Phi arguments are pairs of records of [value, basic block].
59821d5ae102SDimitry Andric // There is an optional final record for fast-math-flags if this phi has a
59831d5ae102SDimitry Andric // floating-point type.
59841d5ae102SDimitry Andric size_t NumArgs = (Record.size() - 1) / 2;
59851d5ae102SDimitry Andric PHINode *PN = PHINode::Create(Ty, NumArgs);
5986145449b1SDimitry Andric if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
5987145449b1SDimitry Andric PN->deleteValue();
5988145449b1SDimitry Andric return error("Invalid phi record");
5989145449b1SDimitry Andric }
599059850d08SRoman Divacky InstructionList.push_back(PN);
5991009b1c42SEd Schouten
5992145449b1SDimitry Andric SmallDenseMap<BasicBlock *, Value *> Args;
59931d5ae102SDimitry Andric for (unsigned i = 0; i != NumArgs; i++) {
5994145449b1SDimitry Andric BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
5995145449b1SDimitry Andric if (!BB) {
5996145449b1SDimitry Andric PN->deleteValue();
5997145449b1SDimitry Andric return error("Invalid phi BB");
5998145449b1SDimitry Andric }
5999145449b1SDimitry Andric
6000145449b1SDimitry Andric // Phi nodes may contain the same predecessor multiple times, in which
6001145449b1SDimitry Andric // case the incoming value must be identical. Directly reuse the already
6002145449b1SDimitry Andric // seen value here, to avoid expanding a constant expression multiple
6003145449b1SDimitry Andric // times.
6004145449b1SDimitry Andric auto It = Args.find(BB);
6005145449b1SDimitry Andric if (It != Args.end()) {
6006145449b1SDimitry Andric PN->addIncoming(It->second, BB);
6007145449b1SDimitry Andric continue;
6008145449b1SDimitry Andric }
6009145449b1SDimitry Andric
6010145449b1SDimitry Andric // If there already is a block for this edge (from a different phi),
6011145449b1SDimitry Andric // use it.
6012145449b1SDimitry Andric BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
6013145449b1SDimitry Andric if (!EdgeBB) {
6014145449b1SDimitry Andric // Otherwise, use a temporary block (that we will discard if it
6015145449b1SDimitry Andric // turns out to be unnecessary).
6016145449b1SDimitry Andric if (!PhiConstExprBB)
6017145449b1SDimitry Andric PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F);
6018145449b1SDimitry Andric EdgeBB = PhiConstExprBB;
6019145449b1SDimitry Andric }
6020145449b1SDimitry Andric
6021522600a2SDimitry Andric // With the new function encoding, it is possible that operands have
6022522600a2SDimitry Andric // negative IDs (for forward references). Use a signed VBR
6023522600a2SDimitry Andric // representation to keep the encoding small.
6024145449b1SDimitry Andric Value *V;
6025522600a2SDimitry Andric if (UseRelativeIDs)
6026145449b1SDimitry Andric V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6027522600a2SDimitry Andric else
6028145449b1SDimitry Andric V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6029145449b1SDimitry Andric if (!V) {
6030145449b1SDimitry Andric PN->deleteValue();
6031145449b1SDimitry Andric PhiConstExprBB->eraseFromParent();
6032145449b1SDimitry Andric return error("Invalid phi record");
6033145449b1SDimitry Andric }
6034145449b1SDimitry Andric
6035145449b1SDimitry Andric if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
6036145449b1SDimitry Andric ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
6037145449b1SDimitry Andric PhiConstExprBB = nullptr;
6038145449b1SDimitry Andric }
6039009b1c42SEd Schouten PN->addIncoming(V, BB);
6040145449b1SDimitry Andric Args.insert({BB, V});
6041009b1c42SEd Schouten }
6042009b1c42SEd Schouten I = PN;
6043145449b1SDimitry Andric ResTypeID = TyID;
60441d5ae102SDimitry Andric
60451d5ae102SDimitry Andric // If there are an even number of records, the final record must be FMF.
60461d5ae102SDimitry Andric if (Record.size() % 2 == 0) {
60471d5ae102SDimitry Andric assert(isa<FPMathOperator>(I) && "Unexpected phi type");
60481d5ae102SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
60491d5ae102SDimitry Andric if (FMF.any())
60501d5ae102SDimitry Andric I->setFastMathFlags(FMF);
60511d5ae102SDimitry Andric }
60521d5ae102SDimitry Andric
6053009b1c42SEd Schouten break;
6054009b1c42SEd Schouten }
6055009b1c42SEd Schouten
60563a0822f0SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD:
60573a0822f0SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
605830815c53SDimitry Andric // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
605930815c53SDimitry Andric unsigned Idx = 0;
60603a0822f0SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
60613a0822f0SDimitry Andric if (Record.size() < 3)
60623a0822f0SDimitry Andric return error("Invalid record");
60633a0822f0SDimitry Andric } else {
60643a0822f0SDimitry Andric assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
606530815c53SDimitry Andric if (Record.size() < 4)
60663a0822f0SDimitry Andric return error("Invalid record");
60673a0822f0SDimitry Andric }
6068145449b1SDimitry Andric ResTypeID = Record[Idx++];
6069145449b1SDimitry Andric Type *Ty = getTypeByID(ResTypeID);
6070f8af5cf6SDimitry Andric if (!Ty)
60713a0822f0SDimitry Andric return error("Invalid record");
60723a0822f0SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
60735ca98fd9SDimitry Andric Value *PersFn = nullptr;
6074145449b1SDimitry Andric unsigned PersFnTypeID;
6075145449b1SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6076145449b1SDimitry Andric nullptr))
60773a0822f0SDimitry Andric return error("Invalid record");
60783a0822f0SDimitry Andric
60793a0822f0SDimitry Andric if (!F->hasPersonalityFn())
60803a0822f0SDimitry Andric F->setPersonalityFn(cast<Constant>(PersFn));
60813a0822f0SDimitry Andric else if (F->getPersonalityFn() != cast<Constant>(PersFn))
60823a0822f0SDimitry Andric return error("Personality function mismatch");
60833a0822f0SDimitry Andric }
608430815c53SDimitry Andric
608530815c53SDimitry Andric bool IsCleanup = !!Record[Idx++];
608630815c53SDimitry Andric unsigned NumClauses = Record[Idx++];
60873a0822f0SDimitry Andric LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
608830815c53SDimitry Andric LP->setCleanup(IsCleanup);
608930815c53SDimitry Andric for (unsigned J = 0; J != NumClauses; ++J) {
609030815c53SDimitry Andric LandingPadInst::ClauseType CT =
609130815c53SDimitry Andric LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
609230815c53SDimitry Andric Value *Val;
6093145449b1SDimitry Andric unsigned ValTypeID;
609430815c53SDimitry Andric
6095145449b1SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6096145449b1SDimitry Andric nullptr)) {
609730815c53SDimitry Andric delete LP;
60983a0822f0SDimitry Andric return error("Invalid record");
609930815c53SDimitry Andric }
610030815c53SDimitry Andric
610130815c53SDimitry Andric assert((CT != LandingPadInst::Catch ||
610230815c53SDimitry Andric !isa<ArrayType>(Val->getType())) &&
610330815c53SDimitry Andric "Catch clause has a invalid type!");
610430815c53SDimitry Andric assert((CT != LandingPadInst::Filter ||
610530815c53SDimitry Andric isa<ArrayType>(Val->getType())) &&
610630815c53SDimitry Andric "Filter clause has invalid type!");
61075ca98fd9SDimitry Andric LP->addClause(cast<Constant>(Val));
610830815c53SDimitry Andric }
610930815c53SDimitry Andric
611030815c53SDimitry Andric I = LP;
611130815c53SDimitry Andric InstructionList.push_back(I);
611230815c53SDimitry Andric break;
611330815c53SDimitry Andric }
611430815c53SDimitry Andric
6115411bd29eSDimitry Andric case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
6116145449b1SDimitry Andric if (Record.size() != 4 && Record.size() != 5)
61173a0822f0SDimitry Andric return error("Invalid record");
6118b60736ecSDimitry Andric using APV = AllocaPackedValues;
6119b60736ecSDimitry Andric const uint64_t Rec = Record[3];
6120b60736ecSDimitry Andric const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
6121b60736ecSDimitry Andric const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
6122145449b1SDimitry Andric unsigned TyID = Record[0];
6123145449b1SDimitry Andric Type *Ty = getTypeByID(TyID);
6124b60736ecSDimitry Andric if (!Bitfield::get<APV::ExplicitType>(Rec)) {
6125145449b1SDimitry Andric TyID = getContainedTypeID(TyID);
6126145449b1SDimitry Andric Ty = getTypeByID(TyID);
6127145449b1SDimitry Andric if (!Ty)
6128145449b1SDimitry Andric return error("Missing element type for old-style alloca");
61295a5ac124SDimitry Andric }
6130145449b1SDimitry Andric unsigned OpTyID = Record[1];
6131145449b1SDimitry Andric Type *OpTy = getTypeByID(OpTyID);
6132145449b1SDimitry Andric Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
61331d5ae102SDimitry Andric MaybeAlign Align;
6134c0981da4SDimitry Andric uint64_t AlignExp =
6135c0981da4SDimitry Andric Bitfield::get<APV::AlignLower>(Rec) |
6136c0981da4SDimitry Andric (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
6137c0981da4SDimitry Andric if (Error Err = parseAlignmentValue(AlignExp, Align)) {
6138b915e9e0SDimitry Andric return Err;
61395a5ac124SDimitry Andric }
6140f8af5cf6SDimitry Andric if (!Ty || !Size)
61413a0822f0SDimitry Andric return error("Invalid record");
614271d5a254SDimitry Andric
614371d5a254SDimitry Andric const DataLayout &DL = TheModule->getDataLayout();
6144145449b1SDimitry Andric unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
614571d5a254SDimitry Andric
6146cfca06d7SDimitry Andric SmallPtrSet<Type *, 4> Visited;
6147cfca06d7SDimitry Andric if (!Align && !Ty->isSized(&Visited))
6148cfca06d7SDimitry Andric return error("alloca of unsized type");
6149cfca06d7SDimitry Andric if (!Align)
6150cfca06d7SDimitry Andric Align = DL.getPrefTypeAlign(Ty);
6151cfca06d7SDimitry Andric
6152312c0ed1SDimitry Andric if (!Size->getType()->isIntegerTy())
6153312c0ed1SDimitry Andric return error("alloca element count must have integer type");
6154312c0ed1SDimitry Andric
6155cfca06d7SDimitry Andric AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
61565ca98fd9SDimitry Andric AI->setUsedWithInAlloca(InAlloca);
615701095a5dSDimitry Andric AI->setSwiftError(SwiftError);
61585ca98fd9SDimitry Andric I = AI;
6159145449b1SDimitry Andric ResTypeID = getVirtualTypeID(AI->getType(), TyID);
616059850d08SRoman Divacky InstructionList.push_back(I);
6161009b1c42SEd Schouten break;
6162009b1c42SEd Schouten }
6163009b1c42SEd Schouten case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
6164009b1c42SEd Schouten unsigned OpNum = 0;
6165009b1c42SEd Schouten Value *Op;
6166145449b1SDimitry Andric unsigned OpTypeID;
6167145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
61685a5ac124SDimitry Andric (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
61693a0822f0SDimitry Andric return error("Invalid record");
6170009b1c42SEd Schouten
6171e6d15924SDimitry Andric if (!isa<PointerType>(Op->getType()))
6172e6d15924SDimitry Andric return error("Load operand is not a pointer type");
6173e6d15924SDimitry Andric
61745a5ac124SDimitry Andric Type *Ty = nullptr;
6175e6d15924SDimitry Andric if (OpNum + 3 == Record.size()) {
6176145449b1SDimitry Andric ResTypeID = Record[OpNum++];
6177145449b1SDimitry Andric Ty = getTypeByID(ResTypeID);
6178344a3780SDimitry Andric } else {
6179145449b1SDimitry Andric ResTypeID = getContainedTypeID(OpTypeID);
6180145449b1SDimitry Andric Ty = getTypeByID(ResTypeID);
6181344a3780SDimitry Andric }
6182e6d15924SDimitry Andric
6183b1c73532SDimitry Andric if (!Ty)
6184b1c73532SDimitry Andric return error("Missing load type");
6185b1c73532SDimitry Andric
6186b915e9e0SDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6187b915e9e0SDimitry Andric return Err;
61885a5ac124SDimitry Andric
61891d5ae102SDimitry Andric MaybeAlign Align;
6190b915e9e0SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6191b915e9e0SDimitry Andric return Err;
6192cfca06d7SDimitry Andric SmallPtrSet<Type *, 4> Visited;
6193cfca06d7SDimitry Andric if (!Align && !Ty->isSized(&Visited))
6194cfca06d7SDimitry Andric return error("load of unsized type");
6195cfca06d7SDimitry Andric if (!Align)
6196cfca06d7SDimitry Andric Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6197cfca06d7SDimitry Andric I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
619859850d08SRoman Divacky InstructionList.push_back(I);
6199009b1c42SEd Schouten break;
6200009b1c42SEd Schouten }
620130815c53SDimitry Andric case bitc::FUNC_CODE_INST_LOADATOMIC: {
6202ca089b24SDimitry Andric // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
620330815c53SDimitry Andric unsigned OpNum = 0;
620430815c53SDimitry Andric Value *Op;
6205145449b1SDimitry Andric unsigned OpTypeID;
6206145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
62075a5ac124SDimitry Andric (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
62083a0822f0SDimitry Andric return error("Invalid record");
620930815c53SDimitry Andric
6210e6d15924SDimitry Andric if (!isa<PointerType>(Op->getType()))
6211e6d15924SDimitry Andric return error("Load operand is not a pointer type");
6212e6d15924SDimitry Andric
62135a5ac124SDimitry Andric Type *Ty = nullptr;
6214e6d15924SDimitry Andric if (OpNum + 5 == Record.size()) {
6215145449b1SDimitry Andric ResTypeID = Record[OpNum++];
6216145449b1SDimitry Andric Ty = getTypeByID(ResTypeID);
6217344a3780SDimitry Andric } else {
6218145449b1SDimitry Andric ResTypeID = getContainedTypeID(OpTypeID);
6219145449b1SDimitry Andric Ty = getTypeByID(ResTypeID);
6220344a3780SDimitry Andric }
6221e6d15924SDimitry Andric
6222b1c73532SDimitry Andric if (!Ty)
6223b1c73532SDimitry Andric return error("Missing atomic load type");
6224b1c73532SDimitry Andric
6225b915e9e0SDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6226b915e9e0SDimitry Andric return Err;
62275a5ac124SDimitry Andric
62283a0822f0SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
622901095a5dSDimitry Andric if (Ordering == AtomicOrdering::NotAtomic ||
623001095a5dSDimitry Andric Ordering == AtomicOrdering::Release ||
623101095a5dSDimitry Andric Ordering == AtomicOrdering::AcquireRelease)
62323a0822f0SDimitry Andric return error("Invalid record");
623301095a5dSDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
62343a0822f0SDimitry Andric return error("Invalid record");
6235ca089b24SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
623630815c53SDimitry Andric
62371d5ae102SDimitry Andric MaybeAlign Align;
6238b915e9e0SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6239b915e9e0SDimitry Andric return Err;
6240cfca06d7SDimitry Andric if (!Align)
6241cfca06d7SDimitry Andric return error("Alignment missing from atomic load");
6242cfca06d7SDimitry Andric I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
624330815c53SDimitry Andric InstructionList.push_back(I);
624430815c53SDimitry Andric break;
624530815c53SDimitry Andric }
62465a5ac124SDimitry Andric case bitc::FUNC_CODE_INST_STORE:
62475a5ac124SDimitry Andric case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
6248009b1c42SEd Schouten unsigned OpNum = 0;
6249009b1c42SEd Schouten Value *Val, *Ptr;
6250145449b1SDimitry Andric unsigned PtrTypeID, ValTypeID;
6251145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6252145449b1SDimitry Andric return error("Invalid record");
6253145449b1SDimitry Andric
6254145449b1SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_STORE) {
6255145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6256145449b1SDimitry Andric return error("Invalid record");
6257145449b1SDimitry Andric } else {
6258145449b1SDimitry Andric ValTypeID = getContainedTypeID(PtrTypeID);
6259145449b1SDimitry Andric if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6260145449b1SDimitry Andric ValTypeID, Val, CurBB))
6261145449b1SDimitry Andric return error("Invalid record");
6262145449b1SDimitry Andric }
6263145449b1SDimitry Andric
6264145449b1SDimitry Andric if (OpNum + 2 != Record.size())
62653a0822f0SDimitry Andric return error("Invalid record");
6266009b1c42SEd Schouten
6267b915e9e0SDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6268b915e9e0SDimitry Andric return Err;
62691d5ae102SDimitry Andric MaybeAlign Align;
6270b915e9e0SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6271b915e9e0SDimitry Andric return Err;
6272cfca06d7SDimitry Andric SmallPtrSet<Type *, 4> Visited;
6273cfca06d7SDimitry Andric if (!Align && !Val->getType()->isSized(&Visited))
6274cfca06d7SDimitry Andric return error("store of unsized type");
6275cfca06d7SDimitry Andric if (!Align)
6276cfca06d7SDimitry Andric Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
6277cfca06d7SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
627859850d08SRoman Divacky InstructionList.push_back(I);
6279009b1c42SEd Schouten break;
6280009b1c42SEd Schouten }
62815a5ac124SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC:
62825a5ac124SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
6283ca089b24SDimitry Andric // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
628430815c53SDimitry Andric unsigned OpNum = 0;
628530815c53SDimitry Andric Value *Val, *Ptr;
6286145449b1SDimitry Andric unsigned PtrTypeID, ValTypeID;
6287145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6288145449b1SDimitry Andric !isa<PointerType>(Ptr->getType()))
6289145449b1SDimitry Andric return error("Invalid record");
6290145449b1SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
6291145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6292145449b1SDimitry Andric return error("Invalid record");
6293145449b1SDimitry Andric } else {
6294145449b1SDimitry Andric ValTypeID = getContainedTypeID(PtrTypeID);
6295145449b1SDimitry Andric if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6296145449b1SDimitry Andric ValTypeID, Val, CurBB))
6297145449b1SDimitry Andric return error("Invalid record");
6298145449b1SDimitry Andric }
6299145449b1SDimitry Andric
6300145449b1SDimitry Andric if (OpNum + 4 != Record.size())
63013a0822f0SDimitry Andric return error("Invalid record");
630230815c53SDimitry Andric
6303b915e9e0SDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6304b915e9e0SDimitry Andric return Err;
63053a0822f0SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
630601095a5dSDimitry Andric if (Ordering == AtomicOrdering::NotAtomic ||
630701095a5dSDimitry Andric Ordering == AtomicOrdering::Acquire ||
630801095a5dSDimitry Andric Ordering == AtomicOrdering::AcquireRelease)
63093a0822f0SDimitry Andric return error("Invalid record");
6310ca089b24SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
631101095a5dSDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
63123a0822f0SDimitry Andric return error("Invalid record");
631330815c53SDimitry Andric
63141d5ae102SDimitry Andric MaybeAlign Align;
6315b915e9e0SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6316b915e9e0SDimitry Andric return Err;
6317cfca06d7SDimitry Andric if (!Align)
6318cfca06d7SDimitry Andric return error("Alignment missing from atomic store");
6319cfca06d7SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
632030815c53SDimitry Andric InstructionList.push_back(I);
632130815c53SDimitry Andric break;
632230815c53SDimitry Andric }
6323b60736ecSDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
6324b60736ecSDimitry Andric // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
6325b60736ecSDimitry Andric // failure_ordering?, weak?]
6326b60736ecSDimitry Andric const size_t NumRecords = Record.size();
632730815c53SDimitry Andric unsigned OpNum = 0;
6328b60736ecSDimitry Andric Value *Ptr = nullptr;
6329145449b1SDimitry Andric unsigned PtrTypeID;
6330145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6331e6d15924SDimitry Andric return error("Invalid record");
6332e6d15924SDimitry Andric
6333e6d15924SDimitry Andric if (!isa<PointerType>(Ptr->getType()))
6334e6d15924SDimitry Andric return error("Cmpxchg operand is not a pointer type");
6335e6d15924SDimitry Andric
6336b60736ecSDimitry Andric Value *Cmp = nullptr;
6337145449b1SDimitry Andric unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6338145449b1SDimitry Andric if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6339145449b1SDimitry Andric CmpTypeID, Cmp, CurBB))
6340e6d15924SDimitry Andric return error("Invalid record");
6341b60736ecSDimitry Andric
6342b60736ecSDimitry Andric Value *New = nullptr;
6343145449b1SDimitry Andric if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
6344145449b1SDimitry Andric New, CurBB) ||
6345b60736ecSDimitry Andric NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
63463a0822f0SDimitry Andric return error("Invalid record");
6347e6d15924SDimitry Andric
6348b60736ecSDimitry Andric const AtomicOrdering SuccessOrdering =
6349b60736ecSDimitry Andric getDecodedOrdering(Record[OpNum + 1]);
635001095a5dSDimitry Andric if (SuccessOrdering == AtomicOrdering::NotAtomic ||
635101095a5dSDimitry Andric SuccessOrdering == AtomicOrdering::Unordered)
63523a0822f0SDimitry Andric return error("Invalid record");
6353b60736ecSDimitry Andric
6354b60736ecSDimitry Andric const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
63555ca98fd9SDimitry Andric
6356b915e9e0SDimitry Andric if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6357b915e9e0SDimitry Andric return Err;
63585ca98fd9SDimitry Andric
6359b60736ecSDimitry Andric const AtomicOrdering FailureOrdering =
6360b60736ecSDimitry Andric NumRecords < 7
6361b60736ecSDimitry Andric ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
6362b60736ecSDimitry Andric : getDecodedOrdering(Record[OpNum + 3]);
6363b60736ecSDimitry Andric
6364344a3780SDimitry Andric if (FailureOrdering == AtomicOrdering::NotAtomic ||
6365344a3780SDimitry Andric FailureOrdering == AtomicOrdering::Unordered)
6366344a3780SDimitry Andric return error("Invalid record");
6367344a3780SDimitry Andric
6368b60736ecSDimitry Andric const Align Alignment(
6369cfca06d7SDimitry Andric TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6370b60736ecSDimitry Andric
6371cfca06d7SDimitry Andric I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6372cfca06d7SDimitry Andric FailureOrdering, SSID);
637330815c53SDimitry Andric cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
63745ca98fd9SDimitry Andric
6375b60736ecSDimitry Andric if (NumRecords < 8) {
63765ca98fd9SDimitry Andric // Before weak cmpxchgs existed, the instruction simply returned the
63775ca98fd9SDimitry Andric // value loaded from memory, so bitcode files from that era will be
63785ca98fd9SDimitry Andric // expecting the first component of a modern cmpxchg.
6379e3b55780SDimitry Andric I->insertInto(CurBB, CurBB->end());
63805ca98fd9SDimitry Andric I = ExtractValueInst::Create(I, 0);
6381145449b1SDimitry Andric ResTypeID = CmpTypeID;
63825ca98fd9SDimitry Andric } else {
63835ca98fd9SDimitry Andric cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
6384145449b1SDimitry Andric unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6385145449b1SDimitry Andric ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
63865ca98fd9SDimitry Andric }
63875ca98fd9SDimitry Andric
638830815c53SDimitry Andric InstructionList.push_back(I);
638930815c53SDimitry Andric break;
639030815c53SDimitry Andric }
6391b60736ecSDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG: {
6392b60736ecSDimitry Andric // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
6393344a3780SDimitry Andric // failure_ordering, weak, align?]
6394b60736ecSDimitry Andric const size_t NumRecords = Record.size();
6395b60736ecSDimitry Andric unsigned OpNum = 0;
6396b60736ecSDimitry Andric Value *Ptr = nullptr;
6397145449b1SDimitry Andric unsigned PtrTypeID;
6398145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6399b60736ecSDimitry Andric return error("Invalid record");
6400b60736ecSDimitry Andric
6401b60736ecSDimitry Andric if (!isa<PointerType>(Ptr->getType()))
6402b60736ecSDimitry Andric return error("Cmpxchg operand is not a pointer type");
6403b60736ecSDimitry Andric
6404b60736ecSDimitry Andric Value *Cmp = nullptr;
6405145449b1SDimitry Andric unsigned CmpTypeID;
6406145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6407b60736ecSDimitry Andric return error("Invalid record");
6408b60736ecSDimitry Andric
6409b60736ecSDimitry Andric Value *Val = nullptr;
6410145449b1SDimitry Andric if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
6411145449b1SDimitry Andric CurBB))
6412b60736ecSDimitry Andric return error("Invalid record");
6413b60736ecSDimitry Andric
6414344a3780SDimitry Andric if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6415344a3780SDimitry Andric return error("Invalid record");
6416344a3780SDimitry Andric
6417344a3780SDimitry Andric const bool IsVol = Record[OpNum];
6418344a3780SDimitry Andric
6419b60736ecSDimitry Andric const AtomicOrdering SuccessOrdering =
6420b60736ecSDimitry Andric getDecodedOrdering(Record[OpNum + 1]);
6421344a3780SDimitry Andric if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
6422344a3780SDimitry Andric return error("Invalid cmpxchg success ordering");
6423b60736ecSDimitry Andric
6424b60736ecSDimitry Andric const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6425b60736ecSDimitry Andric
6426b60736ecSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6427b60736ecSDimitry Andric return Err;
6428b60736ecSDimitry Andric
6429b60736ecSDimitry Andric const AtomicOrdering FailureOrdering =
6430b60736ecSDimitry Andric getDecodedOrdering(Record[OpNum + 3]);
6431344a3780SDimitry Andric if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
6432344a3780SDimitry Andric return error("Invalid cmpxchg failure ordering");
6433b60736ecSDimitry Andric
6434344a3780SDimitry Andric const bool IsWeak = Record[OpNum + 4];
6435b60736ecSDimitry Andric
6436344a3780SDimitry Andric MaybeAlign Alignment;
6437344a3780SDimitry Andric
6438344a3780SDimitry Andric if (NumRecords == (OpNum + 6)) {
6439344a3780SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6440344a3780SDimitry Andric return Err;
6441344a3780SDimitry Andric }
6442344a3780SDimitry Andric if (!Alignment)
6443344a3780SDimitry Andric Alignment =
6444344a3780SDimitry Andric Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6445344a3780SDimitry Andric
6446344a3780SDimitry Andric I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6447b60736ecSDimitry Andric FailureOrdering, SSID);
6448344a3780SDimitry Andric cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
6449344a3780SDimitry Andric cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
6450b60736ecSDimitry Andric
6451145449b1SDimitry Andric unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6452145449b1SDimitry Andric ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6453145449b1SDimitry Andric
6454b60736ecSDimitry Andric InstructionList.push_back(I);
6455b60736ecSDimitry Andric break;
6456b60736ecSDimitry Andric }
6457344a3780SDimitry Andric case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
645830815c53SDimitry Andric case bitc::FUNC_CODE_INST_ATOMICRMW: {
6459344a3780SDimitry Andric // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6460344a3780SDimitry Andric // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6461344a3780SDimitry Andric const size_t NumRecords = Record.size();
646230815c53SDimitry Andric unsigned OpNum = 0;
6463344a3780SDimitry Andric
6464344a3780SDimitry Andric Value *Ptr = nullptr;
6465145449b1SDimitry Andric unsigned PtrTypeID;
6466145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
64673a0822f0SDimitry Andric return error("Invalid record");
6468344a3780SDimitry Andric
6469344a3780SDimitry Andric if (!isa<PointerType>(Ptr->getType()))
6470344a3780SDimitry Andric return error("Invalid record");
6471344a3780SDimitry Andric
6472344a3780SDimitry Andric Value *Val = nullptr;
6473145449b1SDimitry Andric unsigned ValTypeID = InvalidTypeID;
6474344a3780SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
6475145449b1SDimitry Andric ValTypeID = getContainedTypeID(PtrTypeID);
6476344a3780SDimitry Andric if (popValue(Record, OpNum, NextValueNo,
6477145449b1SDimitry Andric getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6478344a3780SDimitry Andric return error("Invalid record");
6479344a3780SDimitry Andric } else {
6480145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6481344a3780SDimitry Andric return error("Invalid record");
6482344a3780SDimitry Andric }
6483344a3780SDimitry Andric
6484344a3780SDimitry Andric if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6485344a3780SDimitry Andric return error("Invalid record");
6486344a3780SDimitry Andric
6487344a3780SDimitry Andric const AtomicRMWInst::BinOp Operation =
6488344a3780SDimitry Andric getDecodedRMWOperation(Record[OpNum]);
648930815c53SDimitry Andric if (Operation < AtomicRMWInst::FIRST_BINOP ||
649030815c53SDimitry Andric Operation > AtomicRMWInst::LAST_BINOP)
64913a0822f0SDimitry Andric return error("Invalid record");
6492344a3780SDimitry Andric
6493344a3780SDimitry Andric const bool IsVol = Record[OpNum + 1];
6494344a3780SDimitry Andric
6495344a3780SDimitry Andric const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
649601095a5dSDimitry Andric if (Ordering == AtomicOrdering::NotAtomic ||
649701095a5dSDimitry Andric Ordering == AtomicOrdering::Unordered)
64983a0822f0SDimitry Andric return error("Invalid record");
6499344a3780SDimitry Andric
6500344a3780SDimitry Andric const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6501344a3780SDimitry Andric
6502344a3780SDimitry Andric MaybeAlign Alignment;
6503344a3780SDimitry Andric
6504344a3780SDimitry Andric if (NumRecords == (OpNum + 5)) {
6505344a3780SDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6506344a3780SDimitry Andric return Err;
6507344a3780SDimitry Andric }
6508344a3780SDimitry Andric
6509344a3780SDimitry Andric if (!Alignment)
6510344a3780SDimitry Andric Alignment =
6511344a3780SDimitry Andric Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
6512344a3780SDimitry Andric
6513344a3780SDimitry Andric I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
6514145449b1SDimitry Andric ResTypeID = ValTypeID;
6515344a3780SDimitry Andric cast<AtomicRMWInst>(I)->setVolatile(IsVol);
6516344a3780SDimitry Andric
651730815c53SDimitry Andric InstructionList.push_back(I);
651830815c53SDimitry Andric break;
651930815c53SDimitry Andric }
6520ca089b24SDimitry Andric case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
652130815c53SDimitry Andric if (2 != Record.size())
65223a0822f0SDimitry Andric return error("Invalid record");
65233a0822f0SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
652401095a5dSDimitry Andric if (Ordering == AtomicOrdering::NotAtomic ||
652501095a5dSDimitry Andric Ordering == AtomicOrdering::Unordered ||
652601095a5dSDimitry Andric Ordering == AtomicOrdering::Monotonic)
65273a0822f0SDimitry Andric return error("Invalid record");
6528ca089b24SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
6529ca089b24SDimitry Andric I = new FenceInst(Context, Ordering, SSID);
653030815c53SDimitry Andric InstructionList.push_back(I);
653130815c53SDimitry Andric break;
653230815c53SDimitry Andric }
6533ac9a064cSDimitry Andric case bitc::FUNC_CODE_DEBUG_RECORD_LABEL: {
6534ac9a064cSDimitry Andric // DbgLabelRecords are placed after the Instructions that they are
6535ac9a064cSDimitry Andric // attached to.
6536ac9a064cSDimitry Andric SeenDebugRecord = true;
6537ac9a064cSDimitry Andric Instruction *Inst = getLastInstruction();
6538ac9a064cSDimitry Andric if (!Inst)
6539ac9a064cSDimitry Andric return error("Invalid dbg record: missing instruction");
6540ac9a064cSDimitry Andric DILocation *DIL = cast<DILocation>(getFnMetadataByID(Record[0]));
6541ac9a064cSDimitry Andric DILabel *Label = cast<DILabel>(getFnMetadataByID(Record[1]));
6542ac9a064cSDimitry Andric Inst->getParent()->insertDbgRecordBefore(
6543ac9a064cSDimitry Andric new DbgLabelRecord(Label, DebugLoc(DIL)), Inst->getIterator());
6544ac9a064cSDimitry Andric continue; // This isn't an instruction.
6545ac9a064cSDimitry Andric }
6546ac9a064cSDimitry Andric case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE:
6547ac9a064cSDimitry Andric case bitc::FUNC_CODE_DEBUG_RECORD_VALUE:
6548ac9a064cSDimitry Andric case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE:
6549ac9a064cSDimitry Andric case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN: {
6550ac9a064cSDimitry Andric // DbgVariableRecords are placed after the Instructions that they are
6551ac9a064cSDimitry Andric // attached to.
6552ac9a064cSDimitry Andric SeenDebugRecord = true;
6553ac9a064cSDimitry Andric Instruction *Inst = getLastInstruction();
6554ac9a064cSDimitry Andric if (!Inst)
6555ac9a064cSDimitry Andric return error("Invalid dbg record: missing instruction");
6556ac9a064cSDimitry Andric
6557ac9a064cSDimitry Andric // First 3 fields are common to all kinds:
6558ac9a064cSDimitry Andric // DILocation, DILocalVariable, DIExpression
6559ac9a064cSDimitry Andric // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
6560ac9a064cSDimitry Andric // ..., LocationMetadata
6561ac9a064cSDimitry Andric // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
6562ac9a064cSDimitry Andric // ..., Value
6563ac9a064cSDimitry Andric // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
6564ac9a064cSDimitry Andric // ..., LocationMetadata
6565ac9a064cSDimitry Andric // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
6566ac9a064cSDimitry Andric // ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
6567ac9a064cSDimitry Andric unsigned Slot = 0;
6568ac9a064cSDimitry Andric // Common fields (0-2).
6569ac9a064cSDimitry Andric DILocation *DIL = cast<DILocation>(getFnMetadataByID(Record[Slot++]));
6570ac9a064cSDimitry Andric DILocalVariable *Var =
6571ac9a064cSDimitry Andric cast<DILocalVariable>(getFnMetadataByID(Record[Slot++]));
6572ac9a064cSDimitry Andric DIExpression *Expr =
6573ac9a064cSDimitry Andric cast<DIExpression>(getFnMetadataByID(Record[Slot++]));
6574ac9a064cSDimitry Andric
6575ac9a064cSDimitry Andric // Union field (3: LocationMetadata | Value).
6576ac9a064cSDimitry Andric Metadata *RawLocation = nullptr;
6577ac9a064cSDimitry Andric if (BitCode == bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE) {
6578ac9a064cSDimitry Andric Value *V = nullptr;
6579ac9a064cSDimitry Andric unsigned TyID = 0;
6580ac9a064cSDimitry Andric // We never expect to see a fwd reference value here because
6581ac9a064cSDimitry Andric // use-before-defs are encoded with the standard non-abbrev record
6582ac9a064cSDimitry Andric // type (they'd require encoding the type too, and they're rare). As a
6583ac9a064cSDimitry Andric // result, getValueTypePair only ever increments Slot by one here (once
6584ac9a064cSDimitry Andric // for the value, never twice for value and type).
6585ac9a064cSDimitry Andric unsigned SlotBefore = Slot;
6586ac9a064cSDimitry Andric if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6587ac9a064cSDimitry Andric return error("Invalid dbg record: invalid value");
6588ac9a064cSDimitry Andric (void)SlotBefore;
6589ac9a064cSDimitry Andric assert((SlotBefore == Slot - 1) && "unexpected fwd ref");
6590ac9a064cSDimitry Andric RawLocation = ValueAsMetadata::get(V);
6591ac9a064cSDimitry Andric } else {
6592ac9a064cSDimitry Andric RawLocation = getFnMetadataByID(Record[Slot++]);
6593ac9a064cSDimitry Andric }
6594ac9a064cSDimitry Andric
6595ac9a064cSDimitry Andric DbgVariableRecord *DVR = nullptr;
6596ac9a064cSDimitry Andric switch (BitCode) {
6597ac9a064cSDimitry Andric case bitc::FUNC_CODE_DEBUG_RECORD_VALUE:
6598ac9a064cSDimitry Andric case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE:
6599ac9a064cSDimitry Andric DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6600ac9a064cSDimitry Andric DbgVariableRecord::LocationType::Value);
6601ac9a064cSDimitry Andric break;
6602ac9a064cSDimitry Andric case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE:
6603ac9a064cSDimitry Andric DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6604ac9a064cSDimitry Andric DbgVariableRecord::LocationType::Declare);
6605ac9a064cSDimitry Andric break;
6606ac9a064cSDimitry Andric case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN: {
6607ac9a064cSDimitry Andric DIAssignID *ID = cast<DIAssignID>(getFnMetadataByID(Record[Slot++]));
6608ac9a064cSDimitry Andric DIExpression *AddrExpr =
6609ac9a064cSDimitry Andric cast<DIExpression>(getFnMetadataByID(Record[Slot++]));
6610ac9a064cSDimitry Andric Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6611ac9a064cSDimitry Andric DVR = new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr,
6612ac9a064cSDimitry Andric DIL);
6613ac9a064cSDimitry Andric break;
6614ac9a064cSDimitry Andric }
6615ac9a064cSDimitry Andric default:
6616ac9a064cSDimitry Andric llvm_unreachable("Unknown DbgVariableRecord bitcode");
6617ac9a064cSDimitry Andric }
6618ac9a064cSDimitry Andric Inst->getParent()->insertDbgRecordBefore(DVR, Inst->getIterator());
6619ac9a064cSDimitry Andric continue; // This isn't an instruction.
6620ac9a064cSDimitry Andric }
6621411bd29eSDimitry Andric case bitc::FUNC_CODE_INST_CALL: {
6622dd58ef01SDimitry Andric // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
6623009b1c42SEd Schouten if (Record.size() < 3)
66243a0822f0SDimitry Andric return error("Invalid record");
6625009b1c42SEd Schouten
66265a5ac124SDimitry Andric unsigned OpNum = 0;
662771d5a254SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]);
66285a5ac124SDimitry Andric unsigned CCInfo = Record[OpNum++];
6629009b1c42SEd Schouten
6630dd58ef01SDimitry Andric FastMathFlags FMF;
6631dd58ef01SDimitry Andric if ((CCInfo >> bitc::CALL_FMF) & 1) {
6632dd58ef01SDimitry Andric FMF = getDecodedFastMathFlags(Record[OpNum++]);
6633dd58ef01SDimitry Andric if (!FMF.any())
6634dd58ef01SDimitry Andric return error("Fast math flags indicator set for call with no FMF");
6635dd58ef01SDimitry Andric }
6636dd58ef01SDimitry Andric
6637145449b1SDimitry Andric unsigned FTyID = InvalidTypeID;
66385a5ac124SDimitry Andric FunctionType *FTy = nullptr;
6639e6d15924SDimitry Andric if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
6640145449b1SDimitry Andric FTyID = Record[OpNum++];
6641145449b1SDimitry Andric FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6642344a3780SDimitry Andric if (!FTy)
66433a0822f0SDimitry Andric return error("Explicit call type is not a function type");
6644e6d15924SDimitry Andric }
66455a5ac124SDimitry Andric
6646009b1c42SEd Schouten Value *Callee;
6647145449b1SDimitry Andric unsigned CalleeTypeID;
6648145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6649145449b1SDimitry Andric CurBB))
66503a0822f0SDimitry Andric return error("Invalid record");
6651009b1c42SEd Schouten
665230815c53SDimitry Andric PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
66535a5ac124SDimitry Andric if (!OpTy)
66543a0822f0SDimitry Andric return error("Callee is not a pointer type");
66555a5ac124SDimitry Andric if (!FTy) {
6656145449b1SDimitry Andric FTyID = getContainedTypeID(CalleeTypeID);
6657145449b1SDimitry Andric FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6658344a3780SDimitry Andric if (!FTy)
66593a0822f0SDimitry Andric return error("Callee is not of pointer to function type");
66607fa27ce4SDimitry Andric }
66615a5ac124SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum)
66623a0822f0SDimitry Andric return error("Insufficient operands to call");
6663009b1c42SEd Schouten
6664009b1c42SEd Schouten SmallVector<Value*, 16> Args;
6665145449b1SDimitry Andric SmallVector<unsigned, 16> ArgTyIDs;
6666009b1c42SEd Schouten // Read the fixed params.
6667009b1c42SEd Schouten for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6668145449b1SDimitry Andric unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6669411bd29eSDimitry Andric if (FTy->getParamType(i)->isLabelTy())
6670009b1c42SEd Schouten Args.push_back(getBasicBlock(Record[OpNum]));
6671009b1c42SEd Schouten else
6672522600a2SDimitry Andric Args.push_back(getValue(Record, OpNum, NextValueNo,
6673145449b1SDimitry Andric FTy->getParamType(i), ArgTyID, CurBB));
6674145449b1SDimitry Andric ArgTyIDs.push_back(ArgTyID);
66755ca98fd9SDimitry Andric if (!Args.back())
66763a0822f0SDimitry Andric return error("Invalid record");
6677009b1c42SEd Schouten }
6678009b1c42SEd Schouten
6679009b1c42SEd Schouten // Read type/value pairs for varargs params.
6680009b1c42SEd Schouten if (!FTy->isVarArg()) {
6681009b1c42SEd Schouten if (OpNum != Record.size())
66823a0822f0SDimitry Andric return error("Invalid record");
6683009b1c42SEd Schouten } else {
6684009b1c42SEd Schouten while (OpNum != Record.size()) {
6685009b1c42SEd Schouten Value *Op;
6686145449b1SDimitry Andric unsigned OpTypeID;
6687145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
66883a0822f0SDimitry Andric return error("Invalid record");
6689009b1c42SEd Schouten Args.push_back(Op);
6690145449b1SDimitry Andric ArgTyIDs.push_back(OpTypeID);
6691009b1c42SEd Schouten }
6692009b1c42SEd Schouten }
6693009b1c42SEd Schouten
6694145449b1SDimitry Andric // Upgrade the bundles if needed.
6695145449b1SDimitry Andric if (!OperandBundles.empty())
6696145449b1SDimitry Andric UpgradeOperandBundles(OperandBundles);
6697145449b1SDimitry Andric
6698dd58ef01SDimitry Andric I = CallInst::Create(FTy, Callee, Args, OperandBundles);
6699145449b1SDimitry Andric ResTypeID = getContainedTypeID(FTyID);
6700dd58ef01SDimitry Andric OperandBundles.clear();
670159850d08SRoman Divacky InstructionList.push_back(I);
670259850d08SRoman Divacky cast<CallInst>(I)->setCallingConv(
6703dd58ef01SDimitry Andric static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
67045ca98fd9SDimitry Andric CallInst::TailCallKind TCK = CallInst::TCK_None;
6705b1c73532SDimitry Andric if (CCInfo & (1 << bitc::CALL_TAIL))
67065ca98fd9SDimitry Andric TCK = CallInst::TCK_Tail;
6707dd58ef01SDimitry Andric if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
67085ca98fd9SDimitry Andric TCK = CallInst::TCK_MustTail;
6709dd58ef01SDimitry Andric if (CCInfo & (1 << bitc::CALL_NOTAIL))
6710dd58ef01SDimitry Andric TCK = CallInst::TCK_NoTail;
67115ca98fd9SDimitry Andric cast<CallInst>(I)->setTailCallKind(TCK);
6712009b1c42SEd Schouten cast<CallInst>(I)->setAttributes(PAL);
6713ac9a064cSDimitry Andric if (isa<DbgInfoIntrinsic>(I))
6714ac9a064cSDimitry Andric SeenDebugIntrinsic = true;
6715145449b1SDimitry Andric if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
6716145449b1SDimitry Andric I->deleteValue();
6717145449b1SDimitry Andric return Err;
6718145449b1SDimitry Andric }
6719dd58ef01SDimitry Andric if (FMF.any()) {
6720dd58ef01SDimitry Andric if (!isa<FPMathOperator>(I))
6721dd58ef01SDimitry Andric return error("Fast-math-flags specified for call without "
6722dd58ef01SDimitry Andric "floating-point scalar or vector return type");
6723dd58ef01SDimitry Andric I->setFastMathFlags(FMF);
6724dd58ef01SDimitry Andric }
6725009b1c42SEd Schouten break;
6726009b1c42SEd Schouten }
6727009b1c42SEd Schouten case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
6728009b1c42SEd Schouten if (Record.size() < 3)
67293a0822f0SDimitry Andric return error("Invalid record");
6730145449b1SDimitry Andric unsigned OpTyID = Record[0];
6731145449b1SDimitry Andric Type *OpTy = getTypeByID(OpTyID);
6732145449b1SDimitry Andric Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6733145449b1SDimitry Andric ResTypeID = Record[2];
6734145449b1SDimitry Andric Type *ResTy = getTypeByID(ResTypeID);
6735009b1c42SEd Schouten if (!OpTy || !Op || !ResTy)
67363a0822f0SDimitry Andric return error("Invalid record");
6737009b1c42SEd Schouten I = new VAArgInst(Op, ResTy);
673859850d08SRoman Divacky InstructionList.push_back(I);
6739009b1c42SEd Schouten break;
6740009b1c42SEd Schouten }
6741dd58ef01SDimitry Andric
6742dd58ef01SDimitry Andric case bitc::FUNC_CODE_OPERAND_BUNDLE: {
6743dd58ef01SDimitry Andric // A call or an invoke can be optionally prefixed with some variable
6744dd58ef01SDimitry Andric // number of operand bundle blocks. These blocks are read into
6745dd58ef01SDimitry Andric // OperandBundles and consumed at the next call or invoke instruction.
6746dd58ef01SDimitry Andric
6747b60736ecSDimitry Andric if (Record.empty() || Record[0] >= BundleTags.size())
6748dd58ef01SDimitry Andric return error("Invalid record");
6749dd58ef01SDimitry Andric
6750dd58ef01SDimitry Andric std::vector<Value *> Inputs;
6751dd58ef01SDimitry Andric
6752dd58ef01SDimitry Andric unsigned OpNum = 1;
6753dd58ef01SDimitry Andric while (OpNum != Record.size()) {
6754dd58ef01SDimitry Andric Value *Op;
6755145449b1SDimitry Andric unsigned OpTypeID;
6756145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6757dd58ef01SDimitry Andric return error("Invalid record");
6758dd58ef01SDimitry Andric Inputs.push_back(Op);
6759dd58ef01SDimitry Andric }
6760dd58ef01SDimitry Andric
6761dd58ef01SDimitry Andric OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6762dd58ef01SDimitry Andric continue;
6763dd58ef01SDimitry Andric }
6764706b4fc4SDimitry Andric
6765706b4fc4SDimitry Andric case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6766706b4fc4SDimitry Andric unsigned OpNum = 0;
6767706b4fc4SDimitry Andric Value *Op = nullptr;
6768145449b1SDimitry Andric unsigned OpTypeID;
6769145449b1SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6770706b4fc4SDimitry Andric return error("Invalid record");
6771706b4fc4SDimitry Andric if (OpNum != Record.size())
6772706b4fc4SDimitry Andric return error("Invalid record");
6773706b4fc4SDimitry Andric
6774706b4fc4SDimitry Andric I = new FreezeInst(Op);
6775145449b1SDimitry Andric ResTypeID = OpTypeID;
6776706b4fc4SDimitry Andric InstructionList.push_back(I);
6777706b4fc4SDimitry Andric break;
6778706b4fc4SDimitry Andric }
6779009b1c42SEd Schouten }
6780009b1c42SEd Schouten
6781009b1c42SEd Schouten // Add instruction to end of current BB. If there is no current BB, reject
6782009b1c42SEd Schouten // this file.
67835ca98fd9SDimitry Andric if (!CurBB) {
6784b5630dbaSDimitry Andric I->deleteValue();
67853a0822f0SDimitry Andric return error("Invalid instruction with no BB");
6786009b1c42SEd Schouten }
6787dd58ef01SDimitry Andric if (!OperandBundles.empty()) {
6788b5630dbaSDimitry Andric I->deleteValue();
6789dd58ef01SDimitry Andric return error("Operand bundles found with no consumer");
6790dd58ef01SDimitry Andric }
6791e3b55780SDimitry Andric I->insertInto(CurBB, CurBB->end());
6792009b1c42SEd Schouten
6793009b1c42SEd Schouten // If this was a terminator instruction, move to the next block.
6794d8e91e46SDimitry Andric if (I->isTerminator()) {
6795009b1c42SEd Schouten ++CurBBNo;
67965ca98fd9SDimitry Andric CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
6797009b1c42SEd Schouten }
6798009b1c42SEd Schouten
6799009b1c42SEd Schouten // Non-void values get registered in the value table for future use.
6800145449b1SDimitry Andric if (!I->getType()->isVoidTy()) {
6801145449b1SDimitry Andric assert(I->getType() == getTypeByID(ResTypeID) &&
6802145449b1SDimitry Andric "Incorrect result type ID");
6803145449b1SDimitry Andric if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
6804145449b1SDimitry Andric return Err;
6805145449b1SDimitry Andric }
6806009b1c42SEd Schouten }
6807009b1c42SEd Schouten
68084a16efa3SDimitry Andric OutOfRecordLoop:
68094a16efa3SDimitry Andric
6810dd58ef01SDimitry Andric if (!OperandBundles.empty())
6811dd58ef01SDimitry Andric return error("Operand bundles found with no consumer");
6812dd58ef01SDimitry Andric
6813009b1c42SEd Schouten // Check the function list for unresolved values.
6814009b1c42SEd Schouten if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
68155ca98fd9SDimitry Andric if (!A->getParent()) {
6816009b1c42SEd Schouten // We found at least one unresolved value. Nuke them all to avoid leaks.
6817009b1c42SEd Schouten for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
68185ca98fd9SDimitry Andric if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
6819e3b55780SDimitry Andric A->replaceAllUsesWith(PoisonValue::get(A->getType()));
6820009b1c42SEd Schouten delete A;
6821009b1c42SEd Schouten }
6822009b1c42SEd Schouten }
68233a0822f0SDimitry Andric return error("Never resolved value found in function");
6824009b1c42SEd Schouten }
6825009b1c42SEd Schouten }
6826009b1c42SEd Schouten
682701095a5dSDimitry Andric // Unexpected unresolved metadata about to be dropped.
6828b915e9e0SDimitry Andric if (MDLoader->hasFwdRefs())
682901095a5dSDimitry Andric return error("Invalid function metadata: outgoing forward refs");
6830d39c594dSDimitry Andric
6831145449b1SDimitry Andric if (PhiConstExprBB)
6832145449b1SDimitry Andric PhiConstExprBB->eraseFromParent();
6833145449b1SDimitry Andric
6834145449b1SDimitry Andric for (const auto &Pair : ConstExprEdgeBBs) {
6835145449b1SDimitry Andric BasicBlock *From = Pair.first.first;
6836145449b1SDimitry Andric BasicBlock *To = Pair.first.second;
6837145449b1SDimitry Andric BasicBlock *EdgeBB = Pair.second;
6838145449b1SDimitry Andric BranchInst::Create(To, EdgeBB);
6839145449b1SDimitry Andric From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
6840145449b1SDimitry Andric To->replacePhiUsesWith(From, EdgeBB);
6841145449b1SDimitry Andric EdgeBB->moveBefore(To);
6842145449b1SDimitry Andric }
6843145449b1SDimitry Andric
6844009b1c42SEd Schouten // Trim the value list down to the size it was before we parsed this function.
6845009b1c42SEd Schouten ValueList.shrinkTo(ModuleValueListSize);
6846b915e9e0SDimitry Andric MDLoader->shrinkTo(ModuleMDLoaderSize);
6847009b1c42SEd Schouten std::vector<BasicBlock*>().swap(FunctionBBs);
6848b915e9e0SDimitry Andric return Error::success();
6849009b1c42SEd Schouten }
6850009b1c42SEd Schouten
6851f8af5cf6SDimitry Andric /// Find the function body in the bitcode stream
findFunctionInStream(Function * F,DenseMap<Function *,uint64_t>::iterator DeferredFunctionInfoIterator)6852b915e9e0SDimitry Andric Error BitcodeReader::findFunctionInStream(
68535ca98fd9SDimitry Andric Function *F,
685463faed5bSDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
685563faed5bSDimitry Andric while (DeferredFunctionInfoIterator->second == 0) {
6856dd58ef01SDimitry Andric // This is the fallback handling for the old format bitcode that
6857dd58ef01SDimitry Andric // didn't contain the function index in the VST, or when we have
6858dd58ef01SDimitry Andric // an anonymous function which would not have a VST entry.
6859dd58ef01SDimitry Andric // Assert that we have one of those two cases.
6860dd58ef01SDimitry Andric assert(VSTOffset == 0 || !F->hasName());
6861dd58ef01SDimitry Andric // Parse the next body in the stream and set its position in the
6862dd58ef01SDimitry Andric // DeferredFunctionInfo map.
6863b915e9e0SDimitry Andric if (Error Err = rememberAndSkipFunctionBodies())
6864b915e9e0SDimitry Andric return Err;
686563faed5bSDimitry Andric }
6866b915e9e0SDimitry Andric return Error::success();
686763faed5bSDimitry Andric }
686863faed5bSDimitry Andric
getDecodedSyncScopeID(unsigned Val)6869ca089b24SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
6870ca089b24SDimitry Andric if (Val == SyncScope::SingleThread || Val == SyncScope::System)
6871ca089b24SDimitry Andric return SyncScope::ID(Val);
6872ca089b24SDimitry Andric if (Val >= SSIDs.size())
6873ca089b24SDimitry Andric return SyncScope::System; // Map unknown synchronization scopes to system.
6874ca089b24SDimitry Andric return SSIDs[Val];
6875ca089b24SDimitry Andric }
6876ca089b24SDimitry Andric
6877009b1c42SEd Schouten //===----------------------------------------------------------------------===//
68786fe5c7aaSRoman Divacky // GVMaterializer implementation
6879009b1c42SEd Schouten //===----------------------------------------------------------------------===//
6880009b1c42SEd Schouten
materialize(GlobalValue * GV)6881b915e9e0SDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) {
68826fe5c7aaSRoman Divacky Function *F = dyn_cast<Function>(GV);
68836fe5c7aaSRoman Divacky // If it's not a function or is already material, ignore the request.
6884f8af5cf6SDimitry Andric if (!F || !F->isMaterializable())
6885b915e9e0SDimitry Andric return Error::success();
68866fe5c7aaSRoman Divacky
68876fe5c7aaSRoman Divacky DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
6888009b1c42SEd Schouten assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
688963faed5bSDimitry Andric // If its position is recorded as 0, its body is somewhere in the stream
689063faed5bSDimitry Andric // but we haven't seen it yet.
68911a82d4c0SDimitry Andric if (DFII->second == 0)
6892b915e9e0SDimitry Andric if (Error Err = findFunctionInStream(F, DFII))
6893b915e9e0SDimitry Andric return Err;
6894009b1c42SEd Schouten
689501095a5dSDimitry Andric // Materialize metadata before parsing any function bodies.
6896b915e9e0SDimitry Andric if (Error Err = materializeMetadata())
6897b915e9e0SDimitry Andric return Err;
689801095a5dSDimitry Andric
68996fe5c7aaSRoman Divacky // Move the bit stream to the saved position of the deferred function body.
6900e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(DFII->second))
6901e6d15924SDimitry Andric return JumpFailed;
6902ac9a064cSDimitry Andric
6903ac9a064cSDimitry Andric // Regardless of the debug info format we want to end up in, we need
6904ac9a064cSDimitry Andric // IsNewDbgInfoFormat=true to construct any debug records seen in the bitcode.
6905ac9a064cSDimitry Andric F->IsNewDbgInfoFormat = true;
6906ac9a064cSDimitry Andric
6907b915e9e0SDimitry Andric if (Error Err = parseFunctionBody(F))
6908b915e9e0SDimitry Andric return Err;
690967c32a98SDimitry Andric F->setIsMaterializable(false);
6910009b1c42SEd Schouten
6911ac9a064cSDimitry Andric // All parsed Functions should load into the debug info format dictated by the
6912ac9a064cSDimitry Andric // Module, unless we're attempting to preserve the input debug info format.
6913ac9a064cSDimitry Andric if (SeenDebugIntrinsic && SeenDebugRecord)
6914ac9a064cSDimitry Andric return error("Mixed debug intrinsics and debug records in bitcode module!");
6915ac9a064cSDimitry Andric if (PreserveInputDbgFormat == cl::boolOrDefault::BOU_TRUE) {
6916ac9a064cSDimitry Andric bool SeenAnyDebugInfo = SeenDebugIntrinsic || SeenDebugRecord;
6917ac9a064cSDimitry Andric bool NewDbgInfoFormatDesired =
6918ac9a064cSDimitry Andric SeenAnyDebugInfo ? SeenDebugRecord : F->getParent()->IsNewDbgInfoFormat;
6919ac9a064cSDimitry Andric if (SeenAnyDebugInfo) {
6920ac9a064cSDimitry Andric UseNewDbgInfoFormat = SeenDebugRecord;
6921ac9a064cSDimitry Andric WriteNewDbgInfoFormatToBitcode = SeenDebugRecord;
6922ac9a064cSDimitry Andric WriteNewDbgInfoFormat = SeenDebugRecord;
6923ac9a064cSDimitry Andric }
6924ac9a064cSDimitry Andric // If the module's debug info format doesn't match the observed input
6925ac9a064cSDimitry Andric // format, then set its format now; we don't need to call the conversion
6926ac9a064cSDimitry Andric // function because there must be no existing intrinsics to convert.
6927ac9a064cSDimitry Andric // Otherwise, just set the format on this function now.
6928ac9a064cSDimitry Andric if (NewDbgInfoFormatDesired != F->getParent()->IsNewDbgInfoFormat)
6929ac9a064cSDimitry Andric F->getParent()->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired);
6930ac9a064cSDimitry Andric else
6931ac9a064cSDimitry Andric F->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired);
6932ac9a064cSDimitry Andric } else {
6933ac9a064cSDimitry Andric // If we aren't preserving formats, we use the Module flag to get our
6934ac9a064cSDimitry Andric // desired format instead of reading flags, in case we are lazy-loading and
6935ac9a064cSDimitry Andric // the format of the module has been changed since it was set by the flags.
6936ac9a064cSDimitry Andric // We only need to convert debug info here if we have debug records but
6937ac9a064cSDimitry Andric // desire the intrinsic format; everything else is a no-op or handled by the
6938ac9a064cSDimitry Andric // autoupgrader.
6939ac9a064cSDimitry Andric bool ModuleIsNewDbgInfoFormat = F->getParent()->IsNewDbgInfoFormat;
6940ac9a064cSDimitry Andric if (ModuleIsNewDbgInfoFormat || !SeenDebugRecord)
6941ac9a064cSDimitry Andric F->setNewDbgInfoFormatFlag(ModuleIsNewDbgInfoFormat);
6942ac9a064cSDimitry Andric else
6943ac9a064cSDimitry Andric F->setIsNewDbgInfoFormat(ModuleIsNewDbgInfoFormat);
6944ac9a064cSDimitry Andric }
6945ac9a064cSDimitry Andric
69465a5ac124SDimitry Andric if (StripDebugInfo)
69475a5ac124SDimitry Andric stripDebugInfo(*F);
69485a5ac124SDimitry Andric
6949009b1c42SEd Schouten // Upgrade any old intrinsic calls in the function.
69501a82d4c0SDimitry Andric for (auto &I : UpgradedIntrinsics) {
6951c0981da4SDimitry Andric for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
69521a82d4c0SDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U))
69531a82d4c0SDimitry Andric UpgradeIntrinsicCall(CI, I.second);
6954009b1c42SEd Schouten }
6955009b1c42SEd Schouten
6956dd58ef01SDimitry Andric // Finish fn->subprogram upgrade for materialized functions.
6957b915e9e0SDimitry Andric if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
6958dd58ef01SDimitry Andric F->setSubprogram(SP);
6959dd58ef01SDimitry Andric
6960b915e9e0SDimitry Andric // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
6961b915e9e0SDimitry Andric if (!MDLoader->isStrippingTBAA()) {
6962b915e9e0SDimitry Andric for (auto &I : instructions(F)) {
6963b915e9e0SDimitry Andric MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
6964b915e9e0SDimitry Andric if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
6965b915e9e0SDimitry Andric continue;
6966b915e9e0SDimitry Andric MDLoader->setStripTBAA(true);
6967b915e9e0SDimitry Andric stripTBAA(F->getParent());
6968b915e9e0SDimitry Andric }
6969b915e9e0SDimitry Andric }
6970b915e9e0SDimitry Andric
6971b60736ecSDimitry Andric for (auto &I : instructions(F)) {
6972344a3780SDimitry Andric // "Upgrade" older incorrect branch weights by dropping them.
6973b60736ecSDimitry Andric if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
6974b60736ecSDimitry Andric if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
6975b60736ecSDimitry Andric MDString *MDS = cast<MDString>(MD->getOperand(0));
6976b60736ecSDimitry Andric StringRef ProfName = MDS->getString();
6977b60736ecSDimitry Andric // Check consistency of !prof branch_weights metadata.
6978ac9a064cSDimitry Andric if (ProfName != "branch_weights")
6979b60736ecSDimitry Andric continue;
6980b60736ecSDimitry Andric unsigned ExpectedNumOperands = 0;
6981b60736ecSDimitry Andric if (BranchInst *BI = dyn_cast<BranchInst>(&I))
6982b60736ecSDimitry Andric ExpectedNumOperands = BI->getNumSuccessors();
6983b60736ecSDimitry Andric else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
6984b60736ecSDimitry Andric ExpectedNumOperands = SI->getNumSuccessors();
6985b60736ecSDimitry Andric else if (isa<CallInst>(&I))
6986b60736ecSDimitry Andric ExpectedNumOperands = 1;
6987b60736ecSDimitry Andric else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
6988b60736ecSDimitry Andric ExpectedNumOperands = IBI->getNumDestinations();
6989b60736ecSDimitry Andric else if (isa<SelectInst>(&I))
6990b60736ecSDimitry Andric ExpectedNumOperands = 2;
6991b60736ecSDimitry Andric else
6992b60736ecSDimitry Andric continue; // ignore and continue.
6993b60736ecSDimitry Andric
6994ac9a064cSDimitry Andric unsigned Offset = getBranchWeightOffset(MD);
6995ac9a064cSDimitry Andric
6996b60736ecSDimitry Andric // If branch weight doesn't match, just strip branch weight.
6997ac9a064cSDimitry Andric if (MD->getNumOperands() != Offset + ExpectedNumOperands)
6998b60736ecSDimitry Andric I.setMetadata(LLVMContext::MD_prof, nullptr);
6999b60736ecSDimitry Andric }
7000b60736ecSDimitry Andric }
7001344a3780SDimitry Andric
7002344a3780SDimitry Andric // Remove incompatible attributes on function calls.
7003344a3780SDimitry Andric if (auto *CI = dyn_cast<CallBase>(&I)) {
7004c0981da4SDimitry Andric CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7005344a3780SDimitry Andric CI->getFunctionType()->getReturnType()));
7006344a3780SDimitry Andric
7007344a3780SDimitry Andric for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7008344a3780SDimitry Andric CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7009344a3780SDimitry Andric CI->getArgOperand(ArgNo)->getType()));
7010344a3780SDimitry Andric }
7011b60736ecSDimitry Andric }
7012b60736ecSDimitry Andric
7013cfca06d7SDimitry Andric // Look for functions that rely on old function attribute behavior.
7014cfca06d7SDimitry Andric UpgradeFunctionAttributes(*F);
7015cfca06d7SDimitry Andric
701667c32a98SDimitry Andric // Bring in any functions that this function forward-referenced via
701767c32a98SDimitry Andric // blockaddresses.
701867c32a98SDimitry Andric return materializeForwardReferencedFunctions();
7019009b1c42SEd Schouten }
7020009b1c42SEd Schouten
materializeModule()7021b915e9e0SDimitry Andric Error BitcodeReader::materializeModule() {
7022b915e9e0SDimitry Andric if (Error Err = materializeMetadata())
7023b915e9e0SDimitry Andric return Err;
70245a5ac124SDimitry Andric
702567c32a98SDimitry Andric // Promise to materialize all forward references.
702667c32a98SDimitry Andric WillMaterializeAllForwardRefs = true;
702767c32a98SDimitry Andric
7028b2f21fb0SEd Schouten // Iterate over the module, deserializing any functions that are still on
7029b2f21fb0SEd Schouten // disk.
7030dd58ef01SDimitry Andric for (Function &F : *TheModule) {
7031b915e9e0SDimitry Andric if (Error Err = materialize(&F))
7032b915e9e0SDimitry Andric return Err;
7033f8af5cf6SDimitry Andric }
7034dd58ef01SDimitry Andric // At this point, if there are any function bodies, parse the rest of
7035dd58ef01SDimitry Andric // the bits in the module past the last function block we have recorded
7036dd58ef01SDimitry Andric // through either lazy scanning or the VST.
7037dd58ef01SDimitry Andric if (LastFunctionBlockBit || NextUnreadBit)
7038b915e9e0SDimitry Andric if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
7039b915e9e0SDimitry Andric ? LastFunctionBlockBit
7040b915e9e0SDimitry Andric : NextUnreadBit))
7041b915e9e0SDimitry Andric return Err;
704263faed5bSDimitry Andric
704367c32a98SDimitry Andric // Check that all block address forward references got resolved (as we
704467c32a98SDimitry Andric // promised above).
704567c32a98SDimitry Andric if (!BasicBlockFwdRefs.empty())
70463a0822f0SDimitry Andric return error("Never resolved function from blockaddress");
704767c32a98SDimitry Andric
7048009b1c42SEd Schouten // Upgrade any intrinsic calls that slipped through (should not happen!) and
7049009b1c42SEd Schouten // delete the old functions to clean up. We can't do this unless the entire
7050009b1c42SEd Schouten // module is materialized because there could always be another function body
7051009b1c42SEd Schouten // with calls to the old function.
70521a82d4c0SDimitry Andric for (auto &I : UpgradedIntrinsics) {
70531a82d4c0SDimitry Andric for (auto *U : I.first->users()) {
70541a82d4c0SDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U))
70551a82d4c0SDimitry Andric UpgradeIntrinsicCall(CI, I.second);
7056009b1c42SEd Schouten }
70571a82d4c0SDimitry Andric if (!I.first->use_empty())
70581a82d4c0SDimitry Andric I.first->replaceAllUsesWith(I.second);
70591a82d4c0SDimitry Andric I.first->eraseFromParent();
7060009b1c42SEd Schouten }
70611a82d4c0SDimitry Andric UpgradedIntrinsics.clear();
7062f8af5cf6SDimitry Andric
7063dd58ef01SDimitry Andric UpgradeDebugInfo(*TheModule);
706401095a5dSDimitry Andric
706501095a5dSDimitry Andric UpgradeModuleFlags(*TheModule);
7066eb11fae6SDimitry Andric
70671d5ae102SDimitry Andric UpgradeARCRuntime(*TheModule);
7068eb11fae6SDimitry Andric
7069b915e9e0SDimitry Andric return Error::success();
707063faed5bSDimitry Andric }
707130815c53SDimitry Andric
getIdentifiedStructTypes() const707267c32a98SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
707367c32a98SDimitry Andric return IdentifiedStructTypes;
707467c32a98SDimitry Andric }
707567c32a98SDimitry Andric
ModuleSummaryIndexBitcodeReader(BitstreamCursor Cursor,StringRef Strtab,ModuleSummaryIndex & TheIndex,StringRef ModulePath,std::function<bool (GlobalValue::GUID)> IsPrevailing)707601095a5dSDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7077a303c417SDimitry Andric BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7078b1c73532SDimitry Andric StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
7079a303c417SDimitry Andric : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
7080b1c73532SDimitry Andric ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7081a303c417SDimitry Andric
addThisModule()7082eb11fae6SDimitry Andric void ModuleSummaryIndexBitcodeReader::addThisModule() {
7083b1c73532SDimitry Andric TheIndex.addModule(ModulePath);
7084eb11fae6SDimitry Andric }
7085eb11fae6SDimitry Andric
70867c7aba6eSDimitry Andric ModuleSummaryIndex::ModuleInfo *
getThisModule()7087eb11fae6SDimitry Andric ModuleSummaryIndexBitcodeReader::getThisModule() {
7088eb11fae6SDimitry Andric return TheIndex.getModule(ModulePath);
7089a303c417SDimitry Andric }
709001095a5dSDimitry Andric
7091e3b55780SDimitry Andric template <bool AllowNullValueInfo>
7092e3b55780SDimitry Andric std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
getValueInfoFromValueId(unsigned ValueId)7093c46e6a59SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
7094c46e6a59SDimitry Andric auto VGI = ValueIdToValueInfoMap[ValueId];
7095e3b55780SDimitry Andric // We can have a null value info for memprof callsite info records in
7096e3b55780SDimitry Andric // distributed ThinLTO index files when the callee function summary is not
7097e3b55780SDimitry Andric // included in the index. The bitcode writer records 0 in that case,
7098e3b55780SDimitry Andric // and the caller of this helper will set AllowNullValueInfo to true.
7099e3b55780SDimitry Andric assert(AllowNullValueInfo || std::get<0>(VGI));
7100c46e6a59SDimitry Andric return VGI;
7101dd58ef01SDimitry Andric }
7102dd58ef01SDimitry Andric
setValueGUID(uint64_t ValueID,StringRef ValueName,GlobalValue::LinkageTypes Linkage,StringRef SourceFileName)7103d99dafe2SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID(
7104d99dafe2SDimitry Andric uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
7105d99dafe2SDimitry Andric StringRef SourceFileName) {
7106d99dafe2SDimitry Andric std::string GlobalId =
7107d99dafe2SDimitry Andric GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
7108d99dafe2SDimitry Andric auto ValueGUID = GlobalValue::getGUID(GlobalId);
7109d99dafe2SDimitry Andric auto OriginalNameID = ValueGUID;
7110d99dafe2SDimitry Andric if (GlobalValue::isLocalLinkage(Linkage))
7111d99dafe2SDimitry Andric OriginalNameID = GlobalValue::getGUID(ValueName);
7112d99dafe2SDimitry Andric if (PrintSummaryGUIDs)
7113d99dafe2SDimitry Andric dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
7114d99dafe2SDimitry Andric << ValueName << "\n";
7115eb11fae6SDimitry Andric
7116eb11fae6SDimitry Andric // UseStrtab is false for legacy summary formats and value names are
7117eb11fae6SDimitry Andric // created on stack. In that case we save the name in a string saver in
7118eb11fae6SDimitry Andric // the index so that the value name can be recorded.
7119e3b55780SDimitry Andric ValueIdToValueInfoMap[ValueID] = std::make_tuple(
7120eb11fae6SDimitry Andric TheIndex.getOrInsertValueInfo(
7121e3b55780SDimitry Andric ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
7122e3b55780SDimitry Andric OriginalNameID, ValueGUID);
7123d99dafe2SDimitry Andric }
7124d99dafe2SDimitry Andric
712501095a5dSDimitry Andric // Specialized value symbol table parser used when reading module index
712601095a5dSDimitry Andric // blocks where we don't actually create global values. The parsed information
712701095a5dSDimitry Andric // is saved in the bitcode reader for use when later parsing summaries.
parseValueSymbolTable(uint64_t Offset,DenseMap<unsigned,GlobalValue::LinkageTypes> & ValueIdToLinkageMap)7128b915e9e0SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
712901095a5dSDimitry Andric uint64_t Offset,
713001095a5dSDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7131d99dafe2SDimitry Andric // With a strtab the VST is not required to parse the summary.
7132d99dafe2SDimitry Andric if (UseStrtab)
7133d99dafe2SDimitry Andric return Error::success();
7134d99dafe2SDimitry Andric
713501095a5dSDimitry Andric assert(Offset > 0 && "Expected non-zero VST offset");
7136e6d15924SDimitry Andric Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
7137e6d15924SDimitry Andric if (!MaybeCurrentBit)
7138e6d15924SDimitry Andric return MaybeCurrentBit.takeError();
7139e6d15924SDimitry Andric uint64_t CurrentBit = MaybeCurrentBit.get();
7140dd58ef01SDimitry Andric
7141e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
7142e6d15924SDimitry Andric return Err;
7143dd58ef01SDimitry Andric
7144dd58ef01SDimitry Andric SmallVector<uint64_t, 64> Record;
7145dd58ef01SDimitry Andric
7146dd58ef01SDimitry Andric // Read all the records for this value table.
7147dd58ef01SDimitry Andric SmallString<128> ValueName;
7148b915e9e0SDimitry Andric
7149b915e9e0SDimitry Andric while (true) {
7150e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7151e6d15924SDimitry Andric if (!MaybeEntry)
7152e6d15924SDimitry Andric return MaybeEntry.takeError();
7153e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
7154dd58ef01SDimitry Andric
7155dd58ef01SDimitry Andric switch (Entry.Kind) {
7156dd58ef01SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
7157dd58ef01SDimitry Andric case BitstreamEntry::Error:
7158dd58ef01SDimitry Andric return error("Malformed block");
7159dd58ef01SDimitry Andric case BitstreamEntry::EndBlock:
716001095a5dSDimitry Andric // Done parsing VST, jump back to wherever we came from.
7161e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
7162e6d15924SDimitry Andric return JumpFailed;
7163b915e9e0SDimitry Andric return Error::success();
7164dd58ef01SDimitry Andric case BitstreamEntry::Record:
7165dd58ef01SDimitry Andric // The interesting case.
7166dd58ef01SDimitry Andric break;
7167dd58ef01SDimitry Andric }
7168dd58ef01SDimitry Andric
7169dd58ef01SDimitry Andric // Read a record.
7170dd58ef01SDimitry Andric Record.clear();
7171e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7172e6d15924SDimitry Andric if (!MaybeRecord)
7173e6d15924SDimitry Andric return MaybeRecord.takeError();
7174e6d15924SDimitry Andric switch (MaybeRecord.get()) {
7175dd58ef01SDimitry Andric default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
7176dd58ef01SDimitry Andric break;
717701095a5dSDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
717801095a5dSDimitry Andric if (convertToString(Record, 1, ValueName))
717901095a5dSDimitry Andric return error("Invalid record");
718001095a5dSDimitry Andric unsigned ValueID = Record[0];
718101095a5dSDimitry Andric assert(!SourceFileName.empty());
718201095a5dSDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID);
718301095a5dSDimitry Andric assert(VLI != ValueIdToLinkageMap.end() &&
718401095a5dSDimitry Andric "No linkage found for VST entry?");
718501095a5dSDimitry Andric auto Linkage = VLI->second;
7186d99dafe2SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
718701095a5dSDimitry Andric ValueName.clear();
718801095a5dSDimitry Andric break;
718901095a5dSDimitry Andric }
7190dd58ef01SDimitry Andric case bitc::VST_CODE_FNENTRY: {
719101095a5dSDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
7192dd58ef01SDimitry Andric if (convertToString(Record, 2, ValueName))
7193dd58ef01SDimitry Andric return error("Invalid record");
7194dd58ef01SDimitry Andric unsigned ValueID = Record[0];
719501095a5dSDimitry Andric assert(!SourceFileName.empty());
719601095a5dSDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID);
719701095a5dSDimitry Andric assert(VLI != ValueIdToLinkageMap.end() &&
719801095a5dSDimitry Andric "No linkage found for VST entry?");
719901095a5dSDimitry Andric auto Linkage = VLI->second;
7200d99dafe2SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
7201dd58ef01SDimitry Andric ValueName.clear();
7202dd58ef01SDimitry Andric break;
7203dd58ef01SDimitry Andric }
720401095a5dSDimitry Andric case bitc::VST_CODE_COMBINED_ENTRY: {
720501095a5dSDimitry Andric // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
720601095a5dSDimitry Andric unsigned ValueID = Record[0];
720701095a5dSDimitry Andric GlobalValue::GUID RefGUID = Record[1];
720801095a5dSDimitry Andric // The "original name", which is the second value of the pair will be
720901095a5dSDimitry Andric // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
7210e3b55780SDimitry Andric ValueIdToValueInfoMap[ValueID] = std::make_tuple(
7211e3b55780SDimitry Andric TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
7212dd58ef01SDimitry Andric break;
7213dd58ef01SDimitry Andric }
7214dd58ef01SDimitry Andric }
7215dd58ef01SDimitry Andric }
7216dd58ef01SDimitry Andric }
7217dd58ef01SDimitry Andric
721801095a5dSDimitry Andric // Parse just the blocks needed for building the index out of the module.
721901095a5dSDimitry Andric // At the end of this routine the module Index is populated with a map
722001095a5dSDimitry Andric // from global value id to GlobalValueSummary objects.
parseModule()7221a303c417SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() {
7222e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
7223e6d15924SDimitry Andric return Err;
7224dd58ef01SDimitry Andric
722501095a5dSDimitry Andric SmallVector<uint64_t, 64> Record;
722601095a5dSDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
722701095a5dSDimitry Andric unsigned ValueId = 0;
722801095a5dSDimitry Andric
722901095a5dSDimitry Andric // Read the index for this module.
7230b915e9e0SDimitry Andric while (true) {
7231e6d15924SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7232e6d15924SDimitry Andric if (!MaybeEntry)
7233e6d15924SDimitry Andric return MaybeEntry.takeError();
7234e6d15924SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get();
7235dd58ef01SDimitry Andric
7236dd58ef01SDimitry Andric switch (Entry.Kind) {
7237dd58ef01SDimitry Andric case BitstreamEntry::Error:
7238dd58ef01SDimitry Andric return error("Malformed block");
7239dd58ef01SDimitry Andric case BitstreamEntry::EndBlock:
7240b915e9e0SDimitry Andric return Error::success();
7241dd58ef01SDimitry Andric
7242dd58ef01SDimitry Andric case BitstreamEntry::SubBlock:
7243dd58ef01SDimitry Andric switch (Entry.ID) {
7244dd58ef01SDimitry Andric default: // Skip unknown content.
7245e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
7246e6d15924SDimitry Andric return Err;
7247dd58ef01SDimitry Andric break;
7248dd58ef01SDimitry Andric case bitc::BLOCKINFO_BLOCK_ID:
7249dd58ef01SDimitry Andric // Need to parse these to get abbrev ids (e.g. for VST)
7250145449b1SDimitry Andric if (Error Err = readBlockInfo())
7251145449b1SDimitry Andric return Err;
7252dd58ef01SDimitry Andric break;
7253dd58ef01SDimitry Andric case bitc::VALUE_SYMTAB_BLOCK_ID:
725401095a5dSDimitry Andric // Should have been parsed earlier via VSTOffset, unless there
725501095a5dSDimitry Andric // is no summary section.
725601095a5dSDimitry Andric assert(((SeenValueSymbolTable && VSTOffset > 0) ||
725701095a5dSDimitry Andric !SeenGlobalValSummary) &&
725801095a5dSDimitry Andric "Expected early VST parse via VSTOffset record");
7259e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
7260e6d15924SDimitry Andric return Err;
726101095a5dSDimitry Andric break;
726201095a5dSDimitry Andric case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
72637c7aba6eSDimitry Andric case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
7264eb11fae6SDimitry Andric // Add the module if it is a per-module index (has a source file name).
7265eb11fae6SDimitry Andric if (!SourceFileName.empty())
7266eb11fae6SDimitry Andric addThisModule();
726701095a5dSDimitry Andric assert(!SeenValueSymbolTable &&
726801095a5dSDimitry Andric "Already read VST when parsing summary block?");
7269b915e9e0SDimitry Andric // We might not have a VST if there were no values in the
7270b915e9e0SDimitry Andric // summary. An empty summary block generated when we are
7271b915e9e0SDimitry Andric // performing ThinLTO compiles so we don't later invoke
7272b915e9e0SDimitry Andric // the regular LTO process on them.
7273b915e9e0SDimitry Andric if (VSTOffset > 0) {
7274b915e9e0SDimitry Andric if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7275b915e9e0SDimitry Andric return Err;
727601095a5dSDimitry Andric SeenValueSymbolTable = true;
7277b915e9e0SDimitry Andric }
727801095a5dSDimitry Andric SeenGlobalValSummary = true;
72797c7aba6eSDimitry Andric if (Error Err = parseEntireSummary(Entry.ID))
7280b915e9e0SDimitry Andric return Err;
7281dd58ef01SDimitry Andric break;
7282dd58ef01SDimitry Andric case bitc::MODULE_STRTAB_BLOCK_ID:
7283b915e9e0SDimitry Andric if (Error Err = parseModuleStringTable())
7284b915e9e0SDimitry Andric return Err;
7285dd58ef01SDimitry Andric break;
7286dd58ef01SDimitry Andric }
7287dd58ef01SDimitry Andric continue;
7288dd58ef01SDimitry Andric
728901095a5dSDimitry Andric case BitstreamEntry::Record: {
729001095a5dSDimitry Andric Record.clear();
7291e6d15924SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7292e6d15924SDimitry Andric if (!MaybeBitCode)
7293e6d15924SDimitry Andric return MaybeBitCode.takeError();
7294e6d15924SDimitry Andric switch (MaybeBitCode.get()) {
729501095a5dSDimitry Andric default:
729601095a5dSDimitry Andric break; // Default behavior, ignore unknown content.
7297d99dafe2SDimitry Andric case bitc::MODULE_CODE_VERSION: {
7298d99dafe2SDimitry Andric if (Error Err = parseVersionRecord(Record).takeError())
7299d99dafe2SDimitry Andric return Err;
7300d99dafe2SDimitry Andric break;
7301d99dafe2SDimitry Andric }
730201095a5dSDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
730301095a5dSDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME: {
730401095a5dSDimitry Andric SmallString<128> ValueName;
730501095a5dSDimitry Andric if (convertToString(Record, 0, ValueName))
730601095a5dSDimitry Andric return error("Invalid record");
730701095a5dSDimitry Andric SourceFileName = ValueName.c_str();
730801095a5dSDimitry Andric break;
730901095a5dSDimitry Andric }
731001095a5dSDimitry Andric /// MODULE_CODE_HASH: [5*i32]
731101095a5dSDimitry Andric case bitc::MODULE_CODE_HASH: {
731201095a5dSDimitry Andric if (Record.size() != 5)
731301095a5dSDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str());
7314b1c73532SDimitry Andric auto &Hash = getThisModule()->second;
731501095a5dSDimitry Andric int Pos = 0;
731601095a5dSDimitry Andric for (auto &Val : Record) {
731701095a5dSDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set");
731801095a5dSDimitry Andric Hash[Pos++] = Val;
731901095a5dSDimitry Andric }
732001095a5dSDimitry Andric break;
732101095a5dSDimitry Andric }
732201095a5dSDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset]
732301095a5dSDimitry Andric case bitc::MODULE_CODE_VSTOFFSET:
7324b60736ecSDimitry Andric if (Record.empty())
732501095a5dSDimitry Andric return error("Invalid record");
7326b915e9e0SDimitry Andric // Note that we subtract 1 here because the offset is relative to one
7327b915e9e0SDimitry Andric // word before the start of the identification or module block, which
7328b915e9e0SDimitry Andric // was historically always the start of the regular bitcode header.
7329b915e9e0SDimitry Andric VSTOffset = Record[0] - 1;
733001095a5dSDimitry Andric break;
7331d99dafe2SDimitry Andric // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
7332d99dafe2SDimitry Andric // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
7333d99dafe2SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
7334d99dafe2SDimitry Andric // v2: [strtab offset, strtab size, v1]
733571d5a254SDimitry Andric case bitc::MODULE_CODE_GLOBALVAR:
733671d5a254SDimitry Andric case bitc::MODULE_CODE_FUNCTION:
733701095a5dSDimitry Andric case bitc::MODULE_CODE_ALIAS: {
7338d99dafe2SDimitry Andric StringRef Name;
7339d99dafe2SDimitry Andric ArrayRef<uint64_t> GVRecord;
7340d99dafe2SDimitry Andric std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7341d99dafe2SDimitry Andric if (GVRecord.size() <= 3)
734201095a5dSDimitry Andric return error("Invalid record");
7343d99dafe2SDimitry Andric uint64_t RawLinkage = GVRecord[3];
734401095a5dSDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
7345d99dafe2SDimitry Andric if (!UseStrtab) {
734601095a5dSDimitry Andric ValueIdToLinkageMap[ValueId++] = Linkage;
734701095a5dSDimitry Andric break;
734801095a5dSDimitry Andric }
7349d99dafe2SDimitry Andric
7350d99dafe2SDimitry Andric setValueGUID(ValueId++, Name, Linkage, SourceFileName);
7351d99dafe2SDimitry Andric break;
7352d99dafe2SDimitry Andric }
735301095a5dSDimitry Andric }
735401095a5dSDimitry Andric }
7355dd58ef01SDimitry Andric continue;
7356dd58ef01SDimitry Andric }
7357dd58ef01SDimitry Andric }
7358dd58ef01SDimitry Andric }
7359dd58ef01SDimitry Andric
7360b915e9e0SDimitry Andric std::vector<ValueInfo>
makeRefList(ArrayRef<uint64_t> Record)7361b915e9e0SDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7362b915e9e0SDimitry Andric std::vector<ValueInfo> Ret;
7363b915e9e0SDimitry Andric Ret.reserve(Record.size());
7364b915e9e0SDimitry Andric for (uint64_t RefValueId : Record)
7365e3b55780SDimitry Andric Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7366b915e9e0SDimitry Andric return Ret;
7367b915e9e0SDimitry Andric }
7368b915e9e0SDimitry Andric
7369eb11fae6SDimitry Andric std::vector<FunctionSummary::EdgeTy>
makeCallList(ArrayRef<uint64_t> Record,bool IsOldProfileFormat,bool HasProfile,bool HasRelBF)7370eb11fae6SDimitry Andric ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7371eb11fae6SDimitry Andric bool IsOldProfileFormat,
7372eb11fae6SDimitry Andric bool HasProfile, bool HasRelBF) {
7373b915e9e0SDimitry Andric std::vector<FunctionSummary::EdgeTy> Ret;
7374ac9a064cSDimitry Andric // In the case of new profile formats, there are two Record entries per
7375ac9a064cSDimitry Andric // Edge. Otherwise, conservatively reserve up to Record.size.
7376ac9a064cSDimitry Andric if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7377ac9a064cSDimitry Andric Ret.reserve(Record.size() / 2);
7378ac9a064cSDimitry Andric else
7379b915e9e0SDimitry Andric Ret.reserve(Record.size());
7380ac9a064cSDimitry Andric
7381b915e9e0SDimitry Andric for (unsigned I = 0, E = Record.size(); I != E; ++I) {
7382b915e9e0SDimitry Andric CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7383b1c73532SDimitry Andric bool HasTailCall = false;
7384eb11fae6SDimitry Andric uint64_t RelBF = 0;
7385e3b55780SDimitry Andric ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7386b915e9e0SDimitry Andric if (IsOldProfileFormat) {
7387b915e9e0SDimitry Andric I += 1; // Skip old callsitecount field
7388b915e9e0SDimitry Andric if (HasProfile)
7389b915e9e0SDimitry Andric I += 1; // Skip old profilecount field
7390b915e9e0SDimitry Andric } else if (HasProfile)
7391b1c73532SDimitry Andric std::tie(Hotness, HasTailCall) =
7392b1c73532SDimitry Andric getDecodedHotnessCallEdgeInfo(Record[++I]);
7393eb11fae6SDimitry Andric else if (HasRelBF)
7394b1c73532SDimitry Andric getDecodedRelBFCallEdgeInfo(Record[++I], RelBF, HasTailCall);
7395b1c73532SDimitry Andric Ret.push_back(FunctionSummary::EdgeTy{
7396b1c73532SDimitry Andric Callee, CalleeInfo(Hotness, HasTailCall, RelBF)});
7397b915e9e0SDimitry Andric }
7398b915e9e0SDimitry Andric return Ret;
7399b915e9e0SDimitry Andric }
7400b915e9e0SDimitry Andric
7401eb11fae6SDimitry Andric static void
parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record,size_t & Slot,WholeProgramDevirtResolution & Wpd)7402eb11fae6SDimitry Andric parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
7403eb11fae6SDimitry Andric WholeProgramDevirtResolution &Wpd) {
7404eb11fae6SDimitry Andric uint64_t ArgNum = Record[Slot++];
7405eb11fae6SDimitry Andric WholeProgramDevirtResolution::ByArg &B =
7406eb11fae6SDimitry Andric Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
7407eb11fae6SDimitry Andric Slot += ArgNum;
7408eb11fae6SDimitry Andric
7409eb11fae6SDimitry Andric B.TheKind =
7410eb11fae6SDimitry Andric static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
7411eb11fae6SDimitry Andric B.Info = Record[Slot++];
7412eb11fae6SDimitry Andric B.Byte = Record[Slot++];
7413eb11fae6SDimitry Andric B.Bit = Record[Slot++];
7414eb11fae6SDimitry Andric }
7415eb11fae6SDimitry Andric
parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,StringRef Strtab,size_t & Slot,TypeIdSummary & TypeId)7416eb11fae6SDimitry Andric static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
7417eb11fae6SDimitry Andric StringRef Strtab, size_t &Slot,
7418eb11fae6SDimitry Andric TypeIdSummary &TypeId) {
7419eb11fae6SDimitry Andric uint64_t Id = Record[Slot++];
7420eb11fae6SDimitry Andric WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
7421eb11fae6SDimitry Andric
7422eb11fae6SDimitry Andric Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
7423eb11fae6SDimitry Andric Wpd.SingleImplName = {Strtab.data() + Record[Slot],
7424eb11fae6SDimitry Andric static_cast<size_t>(Record[Slot + 1])};
7425eb11fae6SDimitry Andric Slot += 2;
7426eb11fae6SDimitry Andric
7427eb11fae6SDimitry Andric uint64_t ResByArgNum = Record[Slot++];
7428eb11fae6SDimitry Andric for (uint64_t I = 0; I != ResByArgNum; ++I)
7429eb11fae6SDimitry Andric parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
7430eb11fae6SDimitry Andric }
7431eb11fae6SDimitry Andric
parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,StringRef Strtab,ModuleSummaryIndex & TheIndex)7432eb11fae6SDimitry Andric static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
7433eb11fae6SDimitry Andric StringRef Strtab,
7434eb11fae6SDimitry Andric ModuleSummaryIndex &TheIndex) {
7435eb11fae6SDimitry Andric size_t Slot = 0;
7436eb11fae6SDimitry Andric TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
7437eb11fae6SDimitry Andric {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
7438eb11fae6SDimitry Andric Slot += 2;
7439eb11fae6SDimitry Andric
7440eb11fae6SDimitry Andric TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
7441eb11fae6SDimitry Andric TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
7442eb11fae6SDimitry Andric TypeId.TTRes.AlignLog2 = Record[Slot++];
7443eb11fae6SDimitry Andric TypeId.TTRes.SizeM1 = Record[Slot++];
7444eb11fae6SDimitry Andric TypeId.TTRes.BitMask = Record[Slot++];
7445eb11fae6SDimitry Andric TypeId.TTRes.InlineBits = Record[Slot++];
7446eb11fae6SDimitry Andric
7447eb11fae6SDimitry Andric while (Slot < Record.size())
7448eb11fae6SDimitry Andric parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
7449eb11fae6SDimitry Andric }
7450eb11fae6SDimitry Andric
7451b60736ecSDimitry Andric std::vector<FunctionSummary::ParamAccess>
parseParamAccesses(ArrayRef<uint64_t> Record)7452b60736ecSDimitry Andric ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7453cfca06d7SDimitry Andric auto ReadRange = [&]() {
7454cfca06d7SDimitry Andric APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
7455cfca06d7SDimitry Andric BitcodeReader::decodeSignRotatedValue(Record.front()));
7456cfca06d7SDimitry Andric Record = Record.drop_front();
7457cfca06d7SDimitry Andric APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
7458cfca06d7SDimitry Andric BitcodeReader::decodeSignRotatedValue(Record.front()));
7459cfca06d7SDimitry Andric Record = Record.drop_front();
7460cfca06d7SDimitry Andric ConstantRange Range{Lower, Upper};
7461cfca06d7SDimitry Andric assert(!Range.isFullSet());
7462cfca06d7SDimitry Andric assert(!Range.isUpperSignWrapped());
7463cfca06d7SDimitry Andric return Range;
7464cfca06d7SDimitry Andric };
7465cfca06d7SDimitry Andric
7466cfca06d7SDimitry Andric std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7467cfca06d7SDimitry Andric while (!Record.empty()) {
7468cfca06d7SDimitry Andric PendingParamAccesses.emplace_back();
7469cfca06d7SDimitry Andric FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7470cfca06d7SDimitry Andric ParamAccess.ParamNo = Record.front();
7471cfca06d7SDimitry Andric Record = Record.drop_front();
7472cfca06d7SDimitry Andric ParamAccess.Use = ReadRange();
7473cfca06d7SDimitry Andric ParamAccess.Calls.resize(Record.front());
7474cfca06d7SDimitry Andric Record = Record.drop_front();
7475cfca06d7SDimitry Andric for (auto &Call : ParamAccess.Calls) {
7476cfca06d7SDimitry Andric Call.ParamNo = Record.front();
7477cfca06d7SDimitry Andric Record = Record.drop_front();
7478e3b55780SDimitry Andric Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front()));
7479cfca06d7SDimitry Andric Record = Record.drop_front();
7480cfca06d7SDimitry Andric Call.Offsets = ReadRange();
7481cfca06d7SDimitry Andric }
7482cfca06d7SDimitry Andric }
7483cfca06d7SDimitry Andric return PendingParamAccesses;
7484cfca06d7SDimitry Andric }
7485cfca06d7SDimitry Andric
parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,size_t & Slot,TypeIdCompatibleVtableInfo & TypeId)7486e6d15924SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7487e6d15924SDimitry Andric ArrayRef<uint64_t> Record, size_t &Slot,
7488e6d15924SDimitry Andric TypeIdCompatibleVtableInfo &TypeId) {
7489e6d15924SDimitry Andric uint64_t Offset = Record[Slot++];
7490e3b55780SDimitry Andric ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7491e6d15924SDimitry Andric TypeId.push_back({Offset, Callee});
7492e6d15924SDimitry Andric }
7493e6d15924SDimitry Andric
parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record)7494e6d15924SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7495e6d15924SDimitry Andric ArrayRef<uint64_t> Record) {
7496e6d15924SDimitry Andric size_t Slot = 0;
7497e6d15924SDimitry Andric TypeIdCompatibleVtableInfo &TypeId =
7498e6d15924SDimitry Andric TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
7499e6d15924SDimitry Andric {Strtab.data() + Record[Slot],
7500e6d15924SDimitry Andric static_cast<size_t>(Record[Slot + 1])});
7501e6d15924SDimitry Andric Slot += 2;
7502e6d15924SDimitry Andric
7503e6d15924SDimitry Andric while (Slot < Record.size())
7504e6d15924SDimitry Andric parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7505e6d15924SDimitry Andric }
7506e6d15924SDimitry Andric
setSpecialRefs(std::vector<ValueInfo> & Refs,unsigned ROCnt,unsigned WOCnt)7507e6d15924SDimitry Andric static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
7508e6d15924SDimitry Andric unsigned WOCnt) {
7509e6d15924SDimitry Andric // Readonly and writeonly refs are in the end of the refs list.
7510e6d15924SDimitry Andric assert(ROCnt + WOCnt <= Refs.size());
7511e6d15924SDimitry Andric unsigned FirstWORef = Refs.size() - WOCnt;
7512e6d15924SDimitry Andric unsigned RefNo = FirstWORef - ROCnt;
7513e6d15924SDimitry Andric for (; RefNo < FirstWORef; ++RefNo)
7514d8e91e46SDimitry Andric Refs[RefNo].setReadOnly();
7515e6d15924SDimitry Andric for (; RefNo < Refs.size(); ++RefNo)
7516e6d15924SDimitry Andric Refs[RefNo].setWriteOnly();
7517d8e91e46SDimitry Andric }
7518d8e91e46SDimitry Andric
751901095a5dSDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary
752001095a5dSDimitry Andric // objects in the index.
parseEntireSummary(unsigned ID)75217c7aba6eSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
7522e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(ID))
7523e6d15924SDimitry Andric return Err;
7524dd58ef01SDimitry Andric SmallVector<uint64_t, 64> Record;
7525dd58ef01SDimitry Andric
752601095a5dSDimitry Andric // Parse version
752701095a5dSDimitry Andric {
7528e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7529e6d15924SDimitry Andric if (!MaybeEntry)
7530e6d15924SDimitry Andric return MaybeEntry.takeError();
7531e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
7532e6d15924SDimitry Andric
753301095a5dSDimitry Andric if (Entry.Kind != BitstreamEntry::Record)
753401095a5dSDimitry Andric return error("Invalid Summary Block: record for version expected");
7535e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7536e6d15924SDimitry Andric if (!MaybeRecord)
7537e6d15924SDimitry Andric return MaybeRecord.takeError();
7538e6d15924SDimitry Andric if (MaybeRecord.get() != bitc::FS_VERSION)
753901095a5dSDimitry Andric return error("Invalid Summary Block: version expected");
754001095a5dSDimitry Andric }
754101095a5dSDimitry Andric const uint64_t Version = Record[0];
7542b915e9e0SDimitry Andric const bool IsOldProfileFormat = Version == 1;
7543706b4fc4SDimitry Andric if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
7544b915e9e0SDimitry Andric return error("Invalid summary version " + Twine(Version) +
7545706b4fc4SDimitry Andric ". Version should be in the range [1-" +
7546706b4fc4SDimitry Andric Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
7547706b4fc4SDimitry Andric "].");
754801095a5dSDimitry Andric Record.clear();
754901095a5dSDimitry Andric
755001095a5dSDimitry Andric // Keep around the last seen summary to be used when we see an optional
755101095a5dSDimitry Andric // "OriginalName" attachement.
755201095a5dSDimitry Andric GlobalValueSummary *LastSeenSummary = nullptr;
755371d5a254SDimitry Andric GlobalValue::GUID LastSeenGUID = 0;
755471d5a254SDimitry Andric
755571d5a254SDimitry Andric // We can expect to see any number of type ID information records before
755671d5a254SDimitry Andric // each function summary records; these variables store the information
755771d5a254SDimitry Andric // collected so far so that it can be used to create the summary object.
7558b915e9e0SDimitry Andric std::vector<GlobalValue::GUID> PendingTypeTests;
755971d5a254SDimitry Andric std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
756071d5a254SDimitry Andric PendingTypeCheckedLoadVCalls;
756171d5a254SDimitry Andric std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
756271d5a254SDimitry Andric PendingTypeCheckedLoadConstVCalls;
7563cfca06d7SDimitry Andric std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7564b915e9e0SDimitry Andric
7565e3b55780SDimitry Andric std::vector<CallsiteInfo> PendingCallsites;
7566e3b55780SDimitry Andric std::vector<AllocInfo> PendingAllocs;
7567e3b55780SDimitry Andric
7568b915e9e0SDimitry Andric while (true) {
7569e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7570e6d15924SDimitry Andric if (!MaybeEntry)
7571e6d15924SDimitry Andric return MaybeEntry.takeError();
7572e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
7573dd58ef01SDimitry Andric
7574dd58ef01SDimitry Andric switch (Entry.Kind) {
7575dd58ef01SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
7576dd58ef01SDimitry Andric case BitstreamEntry::Error:
7577dd58ef01SDimitry Andric return error("Malformed block");
7578dd58ef01SDimitry Andric case BitstreamEntry::EndBlock:
7579b915e9e0SDimitry Andric return Error::success();
7580dd58ef01SDimitry Andric case BitstreamEntry::Record:
7581dd58ef01SDimitry Andric // The interesting case.
7582dd58ef01SDimitry Andric break;
7583dd58ef01SDimitry Andric }
7584dd58ef01SDimitry Andric
7585dd58ef01SDimitry Andric // Read a record. The record format depends on whether this
7586dd58ef01SDimitry Andric // is a per-module index or a combined index file. In the per-module
7587dd58ef01SDimitry Andric // case the records contain the associated value's ID for correlation
7588dd58ef01SDimitry Andric // with VST entries. In the combined index the correlation is done
7589dd58ef01SDimitry Andric // via the bitcode offset of the summary records (which were saved
7590dd58ef01SDimitry Andric // in the combined index VST entries). The records also contain
7591dd58ef01SDimitry Andric // information used for ThinLTO renaming and importing.
7592dd58ef01SDimitry Andric Record.clear();
7593e6d15924SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7594e6d15924SDimitry Andric if (!MaybeBitCode)
7595e6d15924SDimitry Andric return MaybeBitCode.takeError();
7596e6d15924SDimitry Andric switch (unsigned BitCode = MaybeBitCode.get()) {
7597dd58ef01SDimitry Andric default: // Default behavior: ignore.
7598dd58ef01SDimitry Andric break;
7599eb11fae6SDimitry Andric case bitc::FS_FLAGS: { // [flags]
7600cfca06d7SDimitry Andric TheIndex.setFlags(Record[0]);
7601eb11fae6SDimitry Andric break;
7602eb11fae6SDimitry Andric }
7603d99dafe2SDimitry Andric case bitc::FS_VALUE_GUID: { // [valueid, refguid]
7604d99dafe2SDimitry Andric uint64_t ValueID = Record[0];
7605d99dafe2SDimitry Andric GlobalValue::GUID RefGUID = Record[1];
7606e3b55780SDimitry Andric ValueIdToValueInfoMap[ValueID] = std::make_tuple(
7607e3b55780SDimitry Andric TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
7608d99dafe2SDimitry Andric break;
7609d99dafe2SDimitry Andric }
7610b1c73532SDimitry Andric // FS_PERMODULE is legacy and does not have support for the tail call flag.
7611044eb2f6SDimitry Andric // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
7612044eb2f6SDimitry Andric // numrefs x valueid, n x (valueid)]
7613044eb2f6SDimitry Andric // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
761401095a5dSDimitry Andric // numrefs x valueid,
7615b1c73532SDimitry Andric // n x (valueid, hotness+tailcall flags)]
7616eb11fae6SDimitry Andric // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
7617eb11fae6SDimitry Andric // numrefs x valueid,
7618b1c73532SDimitry Andric // n x (valueid, relblockfreq+tailcall)]
761901095a5dSDimitry Andric case bitc::FS_PERMODULE:
7620eb11fae6SDimitry Andric case bitc::FS_PERMODULE_RELBF:
762101095a5dSDimitry Andric case bitc::FS_PERMODULE_PROFILE: {
7622dd58ef01SDimitry Andric unsigned ValueID = Record[0];
762301095a5dSDimitry Andric uint64_t RawFlags = Record[1];
7624dd58ef01SDimitry Andric unsigned InstCount = Record[2];
7625044eb2f6SDimitry Andric uint64_t RawFunFlags = 0;
762601095a5dSDimitry Andric unsigned NumRefs = Record[3];
7627e6d15924SDimitry Andric unsigned NumRORefs = 0, NumWORefs = 0;
7628044eb2f6SDimitry Andric int RefListStartIndex = 4;
7629044eb2f6SDimitry Andric if (Version >= 4) {
7630044eb2f6SDimitry Andric RawFunFlags = Record[3];
7631044eb2f6SDimitry Andric NumRefs = Record[4];
7632044eb2f6SDimitry Andric RefListStartIndex = 5;
7633d8e91e46SDimitry Andric if (Version >= 5) {
7634e6d15924SDimitry Andric NumRORefs = Record[5];
7635d8e91e46SDimitry Andric RefListStartIndex = 6;
7636e6d15924SDimitry Andric if (Version >= 7) {
7637e6d15924SDimitry Andric NumWORefs = Record[6];
7638e6d15924SDimitry Andric RefListStartIndex = 7;
7639e6d15924SDimitry Andric }
7640d8e91e46SDimitry Andric }
7641044eb2f6SDimitry Andric }
7642044eb2f6SDimitry Andric
764301095a5dSDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7644dd58ef01SDimitry Andric // The module path string ref set in the summary must be owned by the
7645dd58ef01SDimitry Andric // index's module string table. Since we don't have a module path
7646dd58ef01SDimitry Andric // string table section in the per-module index, we create a single
7647dd58ef01SDimitry Andric // module path string table entry with an empty (0) ID to take
7648dd58ef01SDimitry Andric // ownership.
764901095a5dSDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
765001095a5dSDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs &&
765101095a5dSDimitry Andric "Record size inconsistent with number of references");
7652b915e9e0SDimitry Andric std::vector<ValueInfo> Refs = makeRefList(
7653b915e9e0SDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
765401095a5dSDimitry Andric bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
7655eb11fae6SDimitry Andric bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
7656b915e9e0SDimitry Andric std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
7657b915e9e0SDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7658eb11fae6SDimitry Andric IsOldProfileFormat, HasProfile, HasRelBF);
7659e6d15924SDimitry Andric setSpecialRefs(Refs, NumRORefs, NumWORefs);
7660e3b55780SDimitry Andric auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7661e3b55780SDimitry Andric // In order to save memory, only record the memprof summaries if this is
7662e3b55780SDimitry Andric // the prevailing copy of a symbol. The linker doesn't resolve local
7663e3b55780SDimitry Andric // linkage values so don't check whether those are prevailing.
7664e3b55780SDimitry Andric auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
7665e3b55780SDimitry Andric if (IsPrevailing &&
7666e3b55780SDimitry Andric !GlobalValue::isLocalLinkage(LT) &&
7667e3b55780SDimitry Andric !IsPrevailing(std::get<2>(VIAndOriginalGUID))) {
7668e3b55780SDimitry Andric PendingCallsites.clear();
7669e3b55780SDimitry Andric PendingAllocs.clear();
7670e3b55780SDimitry Andric }
76711d5ae102SDimitry Andric auto FS = std::make_unique<FunctionSummary>(
7672d8e91e46SDimitry Andric Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
7673d8e91e46SDimitry Andric std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
7674044eb2f6SDimitry Andric std::move(PendingTypeTestAssumeVCalls),
767571d5a254SDimitry Andric std::move(PendingTypeCheckedLoadVCalls),
767671d5a254SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls),
7677cfca06d7SDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls),
7678e3b55780SDimitry Andric std::move(PendingParamAccesses), std::move(PendingCallsites),
7679e3b55780SDimitry Andric std::move(PendingAllocs));
7680eb11fae6SDimitry Andric FS->setModulePath(getThisModule()->first());
7681e3b55780SDimitry Andric FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7682e3b55780SDimitry Andric TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID),
7683e3b55780SDimitry Andric std::move(FS));
768401095a5dSDimitry Andric break;
768501095a5dSDimitry Andric }
768601095a5dSDimitry Andric // FS_ALIAS: [valueid, flags, valueid]
768701095a5dSDimitry Andric // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
768801095a5dSDimitry Andric // they expect all aliasee summaries to be available.
768901095a5dSDimitry Andric case bitc::FS_ALIAS: {
769001095a5dSDimitry Andric unsigned ValueID = Record[0];
769101095a5dSDimitry Andric uint64_t RawFlags = Record[1];
769201095a5dSDimitry Andric unsigned AliaseeID = Record[2];
769301095a5dSDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
76941d5ae102SDimitry Andric auto AS = std::make_unique<AliasSummary>(Flags);
769501095a5dSDimitry Andric // The module path string ref set in the summary must be owned by the
769601095a5dSDimitry Andric // index's module string table. Since we don't have a module path
769701095a5dSDimitry Andric // string table section in the per-module index, we create a single
769801095a5dSDimitry Andric // module path string table entry with an empty (0) ID to take
769901095a5dSDimitry Andric // ownership.
7700eb11fae6SDimitry Andric AS->setModulePath(getThisModule()->first());
770101095a5dSDimitry Andric
7702e3b55780SDimitry Andric auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7703e6d15924SDimitry Andric auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
7704a303c417SDimitry Andric if (!AliaseeInModule)
770501095a5dSDimitry Andric return error("Alias expects aliasee summary to be parsed");
7706e6d15924SDimitry Andric AS->setAliasee(AliaseeVI, AliaseeInModule);
770701095a5dSDimitry Andric
7708c46e6a59SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID);
7709e3b55780SDimitry Andric AS->setOriginalName(std::get<1>(GUID));
7710e3b55780SDimitry Andric TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS));
771101095a5dSDimitry Andric break;
771201095a5dSDimitry Andric }
7713d8e91e46SDimitry Andric // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
771401095a5dSDimitry Andric case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
771501095a5dSDimitry Andric unsigned ValueID = Record[0];
771601095a5dSDimitry Andric uint64_t RawFlags = Record[1];
7717d8e91e46SDimitry Andric unsigned RefArrayStart = 2;
7718e6d15924SDimitry Andric GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7719cfca06d7SDimitry Andric /* WriteOnly */ false,
7720cfca06d7SDimitry Andric /* Constant */ false,
7721cfca06d7SDimitry Andric GlobalObject::VCallVisibilityPublic);
772201095a5dSDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7723d8e91e46SDimitry Andric if (Version >= 5) {
7724d8e91e46SDimitry Andric GVF = getDecodedGVarFlags(Record[2]);
7725d8e91e46SDimitry Andric RefArrayStart = 3;
7726d8e91e46SDimitry Andric }
7727b915e9e0SDimitry Andric std::vector<ValueInfo> Refs =
7728d8e91e46SDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7729d8e91e46SDimitry Andric auto FS =
77301d5ae102SDimitry Andric std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7731eb11fae6SDimitry Andric FS->setModulePath(getThisModule()->first());
7732c46e6a59SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID);
7733e3b55780SDimitry Andric FS->setOriginalName(std::get<1>(GUID));
7734e3b55780SDimitry Andric TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS));
773501095a5dSDimitry Andric break;
773601095a5dSDimitry Andric }
7737e6d15924SDimitry Andric // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
7738e6d15924SDimitry Andric // numrefs, numrefs x valueid,
7739e6d15924SDimitry Andric // n x (valueid, offset)]
7740e6d15924SDimitry Andric case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
7741e6d15924SDimitry Andric unsigned ValueID = Record[0];
7742e6d15924SDimitry Andric uint64_t RawFlags = Record[1];
7743e6d15924SDimitry Andric GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
7744e6d15924SDimitry Andric unsigned NumRefs = Record[3];
7745e6d15924SDimitry Andric unsigned RefListStartIndex = 4;
7746e6d15924SDimitry Andric unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7747e6d15924SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7748e6d15924SDimitry Andric std::vector<ValueInfo> Refs = makeRefList(
7749e6d15924SDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7750e6d15924SDimitry Andric VTableFuncList VTableFuncs;
7751e6d15924SDimitry Andric for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
7752e3b55780SDimitry Andric ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7753e6d15924SDimitry Andric uint64_t Offset = Record[++I];
7754e6d15924SDimitry Andric VTableFuncs.push_back({Callee, Offset});
7755e6d15924SDimitry Andric }
7756e6d15924SDimitry Andric auto VS =
77571d5ae102SDimitry Andric std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7758e6d15924SDimitry Andric VS->setModulePath(getThisModule()->first());
7759e6d15924SDimitry Andric VS->setVTableFuncs(VTableFuncs);
7760e6d15924SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID);
7761e3b55780SDimitry Andric VS->setOriginalName(std::get<1>(GUID));
7762e3b55780SDimitry Andric TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS));
7763e6d15924SDimitry Andric break;
7764e6d15924SDimitry Andric }
7765b1c73532SDimitry Andric // FS_COMBINED is legacy and does not have support for the tail call flag.
7766044eb2f6SDimitry Andric // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
7767b915e9e0SDimitry Andric // numrefs x valueid, n x (valueid)]
7768044eb2f6SDimitry Andric // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
7769b1c73532SDimitry Andric // numrefs x valueid,
7770b1c73532SDimitry Andric // n x (valueid, hotness+tailcall flags)]
777101095a5dSDimitry Andric case bitc::FS_COMBINED:
777201095a5dSDimitry Andric case bitc::FS_COMBINED_PROFILE: {
777301095a5dSDimitry Andric unsigned ValueID = Record[0];
777401095a5dSDimitry Andric uint64_t ModuleId = Record[1];
777501095a5dSDimitry Andric uint64_t RawFlags = Record[2];
777601095a5dSDimitry Andric unsigned InstCount = Record[3];
7777044eb2f6SDimitry Andric uint64_t RawFunFlags = 0;
7778d8e91e46SDimitry Andric uint64_t EntryCount = 0;
777901095a5dSDimitry Andric unsigned NumRefs = Record[4];
7780e6d15924SDimitry Andric unsigned NumRORefs = 0, NumWORefs = 0;
7781044eb2f6SDimitry Andric int RefListStartIndex = 5;
7782044eb2f6SDimitry Andric
7783044eb2f6SDimitry Andric if (Version >= 4) {
7784044eb2f6SDimitry Andric RawFunFlags = Record[4];
7785044eb2f6SDimitry Andric RefListStartIndex = 6;
7786d8e91e46SDimitry Andric size_t NumRefsIndex = 5;
7787d8e91e46SDimitry Andric if (Version >= 5) {
7788e6d15924SDimitry Andric unsigned NumRORefsOffset = 1;
7789d8e91e46SDimitry Andric RefListStartIndex = 7;
7790d8e91e46SDimitry Andric if (Version >= 6) {
7791d8e91e46SDimitry Andric NumRefsIndex = 6;
7792d8e91e46SDimitry Andric EntryCount = Record[5];
7793d8e91e46SDimitry Andric RefListStartIndex = 8;
7794e6d15924SDimitry Andric if (Version >= 7) {
7795e6d15924SDimitry Andric RefListStartIndex = 9;
7796e6d15924SDimitry Andric NumWORefs = Record[8];
7797e6d15924SDimitry Andric NumRORefsOffset = 2;
7798d8e91e46SDimitry Andric }
7799e6d15924SDimitry Andric }
7800e6d15924SDimitry Andric NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
7801d8e91e46SDimitry Andric }
7802d8e91e46SDimitry Andric NumRefs = Record[NumRefsIndex];
7803044eb2f6SDimitry Andric }
7804044eb2f6SDimitry Andric
780501095a5dSDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
780601095a5dSDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
780701095a5dSDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs &&
780801095a5dSDimitry Andric "Record size inconsistent with number of references");
7809b915e9e0SDimitry Andric std::vector<ValueInfo> Refs = makeRefList(
7810b915e9e0SDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
781101095a5dSDimitry Andric bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
7812b915e9e0SDimitry Andric std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
7813b915e9e0SDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7814eb11fae6SDimitry Andric IsOldProfileFormat, HasProfile, false);
7815e3b55780SDimitry Andric ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7816e6d15924SDimitry Andric setSpecialRefs(Refs, NumRORefs, NumWORefs);
78171d5ae102SDimitry Andric auto FS = std::make_unique<FunctionSummary>(
7818d8e91e46SDimitry Andric Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
7819d8e91e46SDimitry Andric std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
7820044eb2f6SDimitry Andric std::move(PendingTypeTestAssumeVCalls),
782171d5a254SDimitry Andric std::move(PendingTypeCheckedLoadVCalls),
782271d5a254SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls),
7823cfca06d7SDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls),
7824e3b55780SDimitry Andric std::move(PendingParamAccesses), std::move(PendingCallsites),
7825e3b55780SDimitry Andric std::move(PendingAllocs));
7826b915e9e0SDimitry Andric LastSeenSummary = FS.get();
7827c46e6a59SDimitry Andric LastSeenGUID = VI.getGUID();
7828b915e9e0SDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]);
7829c46e6a59SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS));
783001095a5dSDimitry Andric break;
783101095a5dSDimitry Andric }
783201095a5dSDimitry Andric // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
783301095a5dSDimitry Andric // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
783401095a5dSDimitry Andric // they expect all aliasee summaries to be available.
783501095a5dSDimitry Andric case bitc::FS_COMBINED_ALIAS: {
783601095a5dSDimitry Andric unsigned ValueID = Record[0];
783701095a5dSDimitry Andric uint64_t ModuleId = Record[1];
783801095a5dSDimitry Andric uint64_t RawFlags = Record[2];
783901095a5dSDimitry Andric unsigned AliaseeValueId = Record[3];
784001095a5dSDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
78411d5ae102SDimitry Andric auto AS = std::make_unique<AliasSummary>(Flags);
784201095a5dSDimitry Andric LastSeenSummary = AS.get();
784301095a5dSDimitry Andric AS->setModulePath(ModuleIdMap[ModuleId]);
784401095a5dSDimitry Andric
7845e3b55780SDimitry Andric auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
7846e6d15924SDimitry Andric auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
7847e6d15924SDimitry Andric AS->setAliasee(AliaseeVI, AliaseeInModule);
784801095a5dSDimitry Andric
7849e3b55780SDimitry Andric ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7850c46e6a59SDimitry Andric LastSeenGUID = VI.getGUID();
7851c46e6a59SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(AS));
785201095a5dSDimitry Andric break;
785301095a5dSDimitry Andric }
785401095a5dSDimitry Andric // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
785501095a5dSDimitry Andric case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
785601095a5dSDimitry Andric unsigned ValueID = Record[0];
785701095a5dSDimitry Andric uint64_t ModuleId = Record[1];
785801095a5dSDimitry Andric uint64_t RawFlags = Record[2];
7859d8e91e46SDimitry Andric unsigned RefArrayStart = 3;
7860e6d15924SDimitry Andric GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7861cfca06d7SDimitry Andric /* WriteOnly */ false,
7862cfca06d7SDimitry Andric /* Constant */ false,
7863cfca06d7SDimitry Andric GlobalObject::VCallVisibilityPublic);
786401095a5dSDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7865d8e91e46SDimitry Andric if (Version >= 5) {
7866d8e91e46SDimitry Andric GVF = getDecodedGVarFlags(Record[3]);
7867d8e91e46SDimitry Andric RefArrayStart = 4;
7868d8e91e46SDimitry Andric }
7869b915e9e0SDimitry Andric std::vector<ValueInfo> Refs =
7870d8e91e46SDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7871d8e91e46SDimitry Andric auto FS =
78721d5ae102SDimitry Andric std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
787301095a5dSDimitry Andric LastSeenSummary = FS.get();
787401095a5dSDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]);
7875e3b55780SDimitry Andric ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7876c46e6a59SDimitry Andric LastSeenGUID = VI.getGUID();
7877c46e6a59SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS));
787801095a5dSDimitry Andric break;
787901095a5dSDimitry Andric }
788001095a5dSDimitry Andric // FS_COMBINED_ORIGINAL_NAME: [original_name]
788101095a5dSDimitry Andric case bitc::FS_COMBINED_ORIGINAL_NAME: {
788201095a5dSDimitry Andric uint64_t OriginalName = Record[0];
788301095a5dSDimitry Andric if (!LastSeenSummary)
788401095a5dSDimitry Andric return error("Name attachment that does not follow a combined record");
788501095a5dSDimitry Andric LastSeenSummary->setOriginalName(OriginalName);
788671d5a254SDimitry Andric TheIndex.addOriginalName(LastSeenGUID, OriginalName);
788701095a5dSDimitry Andric // Reset the LastSeenSummary
788801095a5dSDimitry Andric LastSeenSummary = nullptr;
788971d5a254SDimitry Andric LastSeenGUID = 0;
7890b915e9e0SDimitry Andric break;
7891b915e9e0SDimitry Andric }
7892044eb2f6SDimitry Andric case bitc::FS_TYPE_TESTS:
7893b915e9e0SDimitry Andric assert(PendingTypeTests.empty());
7894b60736ecSDimitry Andric llvm::append_range(PendingTypeTests, Record);
7895b915e9e0SDimitry Andric break;
7896044eb2f6SDimitry Andric
7897044eb2f6SDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
789871d5a254SDimitry Andric assert(PendingTypeTestAssumeVCalls.empty());
789971d5a254SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2)
790071d5a254SDimitry Andric PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
790171d5a254SDimitry Andric break;
7902044eb2f6SDimitry Andric
7903044eb2f6SDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
790471d5a254SDimitry Andric assert(PendingTypeCheckedLoadVCalls.empty());
790571d5a254SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2)
790671d5a254SDimitry Andric PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
790771d5a254SDimitry Andric break;
7908044eb2f6SDimitry Andric
7909044eb2f6SDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
791071d5a254SDimitry Andric PendingTypeTestAssumeConstVCalls.push_back(
791171d5a254SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
791271d5a254SDimitry Andric break;
7913044eb2f6SDimitry Andric
7914044eb2f6SDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
791571d5a254SDimitry Andric PendingTypeCheckedLoadConstVCalls.push_back(
791671d5a254SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
791771d5a254SDimitry Andric break;
7918044eb2f6SDimitry Andric
79197c7aba6eSDimitry Andric case bitc::FS_CFI_FUNCTION_DEFS: {
79207c7aba6eSDimitry Andric std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
79217c7aba6eSDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2)
79227c7aba6eSDimitry Andric CfiFunctionDefs.insert(
79237c7aba6eSDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
79247c7aba6eSDimitry Andric break;
79257c7aba6eSDimitry Andric }
7926eb11fae6SDimitry Andric
79277c7aba6eSDimitry Andric case bitc::FS_CFI_FUNCTION_DECLS: {
79287c7aba6eSDimitry Andric std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
79297c7aba6eSDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2)
79307c7aba6eSDimitry Andric CfiFunctionDecls.insert(
79317c7aba6eSDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
79327c7aba6eSDimitry Andric break;
79337c7aba6eSDimitry Andric }
7934eb11fae6SDimitry Andric
7935eb11fae6SDimitry Andric case bitc::FS_TYPE_ID:
7936eb11fae6SDimitry Andric parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
7937eb11fae6SDimitry Andric break;
7938e6d15924SDimitry Andric
7939e6d15924SDimitry Andric case bitc::FS_TYPE_ID_METADATA:
7940e6d15924SDimitry Andric parseTypeIdCompatibleVtableSummaryRecord(Record);
7941e6d15924SDimitry Andric break;
7942cfca06d7SDimitry Andric
7943cfca06d7SDimitry Andric case bitc::FS_BLOCK_COUNT:
7944cfca06d7SDimitry Andric TheIndex.addBlockCount(Record[0]);
7945cfca06d7SDimitry Andric break;
7946cfca06d7SDimitry Andric
7947cfca06d7SDimitry Andric case bitc::FS_PARAM_ACCESS: {
7948cfca06d7SDimitry Andric PendingParamAccesses = parseParamAccesses(Record);
7949cfca06d7SDimitry Andric break;
7950cfca06d7SDimitry Andric }
7951e3b55780SDimitry Andric
7952e3b55780SDimitry Andric case bitc::FS_STACK_IDS: { // [n x stackid]
7953e3b55780SDimitry Andric // Save stack ids in the reader to consult when adding stack ids from the
7954e3b55780SDimitry Andric // lists in the stack node and alloc node entries.
7955e3b55780SDimitry Andric StackIds = ArrayRef<uint64_t>(Record);
7956e3b55780SDimitry Andric break;
7957e3b55780SDimitry Andric }
7958e3b55780SDimitry Andric
7959e3b55780SDimitry Andric case bitc::FS_PERMODULE_CALLSITE_INFO: {
7960e3b55780SDimitry Andric unsigned ValueID = Record[0];
7961e3b55780SDimitry Andric SmallVector<unsigned> StackIdList;
7962e3b55780SDimitry Andric for (auto R = Record.begin() + 1; R != Record.end(); R++) {
7963e3b55780SDimitry Andric assert(*R < StackIds.size());
7964e3b55780SDimitry Andric StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R]));
7965e3b55780SDimitry Andric }
7966e3b55780SDimitry Andric ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7967e3b55780SDimitry Andric PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)}));
7968e3b55780SDimitry Andric break;
7969e3b55780SDimitry Andric }
7970e3b55780SDimitry Andric
7971e3b55780SDimitry Andric case bitc::FS_COMBINED_CALLSITE_INFO: {
7972e3b55780SDimitry Andric auto RecordIter = Record.begin();
7973e3b55780SDimitry Andric unsigned ValueID = *RecordIter++;
7974e3b55780SDimitry Andric unsigned NumStackIds = *RecordIter++;
7975e3b55780SDimitry Andric unsigned NumVersions = *RecordIter++;
7976e3b55780SDimitry Andric assert(Record.size() == 3 + NumStackIds + NumVersions);
7977e3b55780SDimitry Andric SmallVector<unsigned> StackIdList;
7978e3b55780SDimitry Andric for (unsigned J = 0; J < NumStackIds; J++) {
7979e3b55780SDimitry Andric assert(*RecordIter < StackIds.size());
7980e3b55780SDimitry Andric StackIdList.push_back(
7981e3b55780SDimitry Andric TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++]));
7982e3b55780SDimitry Andric }
7983e3b55780SDimitry Andric SmallVector<unsigned> Versions;
7984e3b55780SDimitry Andric for (unsigned J = 0; J < NumVersions; J++)
7985e3b55780SDimitry Andric Versions.push_back(*RecordIter++);
7986e3b55780SDimitry Andric ValueInfo VI = std::get<0>(
7987e3b55780SDimitry Andric getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
7988e3b55780SDimitry Andric PendingCallsites.push_back(
7989e3b55780SDimitry Andric CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
7990e3b55780SDimitry Andric break;
7991e3b55780SDimitry Andric }
7992e3b55780SDimitry Andric
7993e3b55780SDimitry Andric case bitc::FS_PERMODULE_ALLOC_INFO: {
7994e3b55780SDimitry Andric unsigned I = 0;
7995e3b55780SDimitry Andric std::vector<MIBInfo> MIBs;
7996ac9a064cSDimitry Andric unsigned NumMIBs = 0;
7997ac9a064cSDimitry Andric if (Version >= 10)
7998ac9a064cSDimitry Andric NumMIBs = Record[I++];
7999ac9a064cSDimitry Andric unsigned MIBsRead = 0;
8000ac9a064cSDimitry Andric while ((Version >= 10 && MIBsRead++ < NumMIBs) ||
8001ac9a064cSDimitry Andric (Version < 10 && I < Record.size())) {
8002e3b55780SDimitry Andric assert(Record.size() - I >= 2);
8003e3b55780SDimitry Andric AllocationType AllocType = (AllocationType)Record[I++];
8004e3b55780SDimitry Andric unsigned NumStackEntries = Record[I++];
8005e3b55780SDimitry Andric assert(Record.size() - I >= NumStackEntries);
8006e3b55780SDimitry Andric SmallVector<unsigned> StackIdList;
8007e3b55780SDimitry Andric for (unsigned J = 0; J < NumStackEntries; J++) {
8008e3b55780SDimitry Andric assert(Record[I] < StackIds.size());
8009e3b55780SDimitry Andric StackIdList.push_back(
8010e3b55780SDimitry Andric TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
8011e3b55780SDimitry Andric }
8012e3b55780SDimitry Andric MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8013e3b55780SDimitry Andric }
8014ac9a064cSDimitry Andric std::vector<uint64_t> TotalSizes;
8015ac9a064cSDimitry Andric // We either have no sizes or NumMIBs of them.
8016ac9a064cSDimitry Andric assert(I == Record.size() || Record.size() - I == NumMIBs);
8017ac9a064cSDimitry Andric if (I < Record.size()) {
8018ac9a064cSDimitry Andric MIBsRead = 0;
8019ac9a064cSDimitry Andric while (MIBsRead++ < NumMIBs)
8020ac9a064cSDimitry Andric TotalSizes.push_back(Record[I++]);
8021ac9a064cSDimitry Andric }
8022e3b55780SDimitry Andric PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
8023ac9a064cSDimitry Andric if (!TotalSizes.empty()) {
8024ac9a064cSDimitry Andric assert(PendingAllocs.back().MIBs.size() == TotalSizes.size());
8025ac9a064cSDimitry Andric PendingAllocs.back().TotalSizes = std::move(TotalSizes);
8026ac9a064cSDimitry Andric }
8027e3b55780SDimitry Andric break;
8028e3b55780SDimitry Andric }
8029e3b55780SDimitry Andric
8030e3b55780SDimitry Andric case bitc::FS_COMBINED_ALLOC_INFO: {
8031e3b55780SDimitry Andric unsigned I = 0;
8032e3b55780SDimitry Andric std::vector<MIBInfo> MIBs;
8033e3b55780SDimitry Andric unsigned NumMIBs = Record[I++];
8034e3b55780SDimitry Andric unsigned NumVersions = Record[I++];
8035e3b55780SDimitry Andric unsigned MIBsRead = 0;
8036e3b55780SDimitry Andric while (MIBsRead++ < NumMIBs) {
8037e3b55780SDimitry Andric assert(Record.size() - I >= 2);
8038e3b55780SDimitry Andric AllocationType AllocType = (AllocationType)Record[I++];
8039e3b55780SDimitry Andric unsigned NumStackEntries = Record[I++];
8040e3b55780SDimitry Andric assert(Record.size() - I >= NumStackEntries);
8041e3b55780SDimitry Andric SmallVector<unsigned> StackIdList;
8042e3b55780SDimitry Andric for (unsigned J = 0; J < NumStackEntries; J++) {
8043e3b55780SDimitry Andric assert(Record[I] < StackIds.size());
8044e3b55780SDimitry Andric StackIdList.push_back(
8045e3b55780SDimitry Andric TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
8046e3b55780SDimitry Andric }
8047e3b55780SDimitry Andric MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8048e3b55780SDimitry Andric }
8049e3b55780SDimitry Andric assert(Record.size() - I >= NumVersions);
8050e3b55780SDimitry Andric SmallVector<uint8_t> Versions;
8051e3b55780SDimitry Andric for (unsigned J = 0; J < NumVersions; J++)
8052e3b55780SDimitry Andric Versions.push_back(Record[I++]);
8053ac9a064cSDimitry Andric std::vector<uint64_t> TotalSizes;
8054ac9a064cSDimitry Andric // We either have no sizes or NumMIBs of them.
8055ac9a064cSDimitry Andric assert(I == Record.size() || Record.size() - I == NumMIBs);
8056ac9a064cSDimitry Andric if (I < Record.size()) {
8057ac9a064cSDimitry Andric MIBsRead = 0;
8058ac9a064cSDimitry Andric while (MIBsRead++ < NumMIBs) {
8059ac9a064cSDimitry Andric TotalSizes.push_back(Record[I++]);
8060ac9a064cSDimitry Andric }
8061ac9a064cSDimitry Andric }
8062e3b55780SDimitry Andric PendingAllocs.push_back(
8063e3b55780SDimitry Andric AllocInfo(std::move(Versions), std::move(MIBs)));
8064ac9a064cSDimitry Andric if (!TotalSizes.empty()) {
8065ac9a064cSDimitry Andric assert(PendingAllocs.back().MIBs.size() == TotalSizes.size());
8066ac9a064cSDimitry Andric PendingAllocs.back().TotalSizes = std::move(TotalSizes);
8067ac9a064cSDimitry Andric }
8068e3b55780SDimitry Andric break;
8069e3b55780SDimitry Andric }
8070dd58ef01SDimitry Andric }
8071dd58ef01SDimitry Andric }
8072dd58ef01SDimitry Andric llvm_unreachable("Exit infinite loop");
8073dd58ef01SDimitry Andric }
8074dd58ef01SDimitry Andric
8075dd58ef01SDimitry Andric // Parse the module string table block into the Index.
8076dd58ef01SDimitry Andric // This populates the ModulePathStringTable map in the index.
parseModuleStringTable()8077b915e9e0SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8078e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
8079e6d15924SDimitry Andric return Err;
8080dd58ef01SDimitry Andric
8081dd58ef01SDimitry Andric SmallVector<uint64_t, 64> Record;
8082dd58ef01SDimitry Andric
8083dd58ef01SDimitry Andric SmallString<128> ModulePath;
80847c7aba6eSDimitry Andric ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
8085b915e9e0SDimitry Andric
8086b915e9e0SDimitry Andric while (true) {
8087e6d15924SDimitry Andric Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
8088e6d15924SDimitry Andric if (!MaybeEntry)
8089e6d15924SDimitry Andric return MaybeEntry.takeError();
8090e6d15924SDimitry Andric BitstreamEntry Entry = MaybeEntry.get();
8091dd58ef01SDimitry Andric
8092dd58ef01SDimitry Andric switch (Entry.Kind) {
8093dd58ef01SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
8094dd58ef01SDimitry Andric case BitstreamEntry::Error:
8095dd58ef01SDimitry Andric return error("Malformed block");
8096dd58ef01SDimitry Andric case BitstreamEntry::EndBlock:
8097b915e9e0SDimitry Andric return Error::success();
8098dd58ef01SDimitry Andric case BitstreamEntry::Record:
8099dd58ef01SDimitry Andric // The interesting case.
8100dd58ef01SDimitry Andric break;
8101dd58ef01SDimitry Andric }
8102dd58ef01SDimitry Andric
8103dd58ef01SDimitry Andric Record.clear();
8104e6d15924SDimitry Andric Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
8105e6d15924SDimitry Andric if (!MaybeRecord)
8106e6d15924SDimitry Andric return MaybeRecord.takeError();
8107e6d15924SDimitry Andric switch (MaybeRecord.get()) {
8108dd58ef01SDimitry Andric default: // Default behavior: ignore.
8109dd58ef01SDimitry Andric break;
8110dd58ef01SDimitry Andric case bitc::MST_CODE_ENTRY: {
8111dd58ef01SDimitry Andric // MST_ENTRY: [modid, namechar x N]
811201095a5dSDimitry Andric uint64_t ModuleId = Record[0];
811301095a5dSDimitry Andric
8114dd58ef01SDimitry Andric if (convertToString(Record, 1, ModulePath))
8115dd58ef01SDimitry Andric return error("Invalid record");
811601095a5dSDimitry Andric
8117b1c73532SDimitry Andric LastSeenModule = TheIndex.addModule(ModulePath);
81187c7aba6eSDimitry Andric ModuleIdMap[ModuleId] = LastSeenModule->first();
811901095a5dSDimitry Andric
8120dd58ef01SDimitry Andric ModulePath.clear();
8121dd58ef01SDimitry Andric break;
8122dd58ef01SDimitry Andric }
812301095a5dSDimitry Andric /// MST_CODE_HASH: [5*i32]
812401095a5dSDimitry Andric case bitc::MST_CODE_HASH: {
812501095a5dSDimitry Andric if (Record.size() != 5)
812601095a5dSDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str());
81277c7aba6eSDimitry Andric if (!LastSeenModule)
812801095a5dSDimitry Andric return error("Invalid hash that does not follow a module path");
812901095a5dSDimitry Andric int Pos = 0;
813001095a5dSDimitry Andric for (auto &Val : Record) {
813101095a5dSDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set");
8132b1c73532SDimitry Andric LastSeenModule->second[Pos++] = Val;
813301095a5dSDimitry Andric }
81347c7aba6eSDimitry Andric // Reset LastSeenModule to avoid overriding the hash unexpectedly.
81357c7aba6eSDimitry Andric LastSeenModule = nullptr;
813601095a5dSDimitry Andric break;
813701095a5dSDimitry Andric }
8138dd58ef01SDimitry Andric }
8139dd58ef01SDimitry Andric }
8140dd58ef01SDimitry Andric llvm_unreachable("Exit infinite loop");
8141dd58ef01SDimitry Andric }
8142dd58ef01SDimitry Andric
8143f8af5cf6SDimitry Andric namespace {
8144b915e9e0SDimitry Andric
814501095a5dSDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
814601095a5dSDimitry Andric // will be removed once this transition is complete. Clients should prefer to
814701095a5dSDimitry Andric // deal with the Error value directly, rather than converting to error_code.
81485ca98fd9SDimitry Andric class BitcodeErrorCategoryType : public std::error_category {
name() const8149b915e9e0SDimitry Andric const char *name() const noexcept override {
8150f8af5cf6SDimitry Andric return "llvm.bitcode";
8151f8af5cf6SDimitry Andric }
8152044eb2f6SDimitry Andric
message(int IE) const81535ca98fd9SDimitry Andric std::string message(int IE) const override {
815467c32a98SDimitry Andric BitcodeError E = static_cast<BitcodeError>(IE);
8155f8af5cf6SDimitry Andric switch (E) {
815667c32a98SDimitry Andric case BitcodeError::CorruptedBitcode:
815767c32a98SDimitry Andric return "Corrupted bitcode";
8158f8af5cf6SDimitry Andric }
8159f8af5cf6SDimitry Andric llvm_unreachable("Unknown error type!");
8160f8af5cf6SDimitry Andric }
8161f8af5cf6SDimitry Andric };
8162b915e9e0SDimitry Andric
816301095a5dSDimitry Andric } // end anonymous namespace
8164f8af5cf6SDimitry Andric
BitcodeErrorCategory()816567c32a98SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() {
81661f917f69SDimitry Andric static BitcodeErrorCategoryType ErrorCategory;
81671f917f69SDimitry Andric return ErrorCategory;
816863faed5bSDimitry Andric }
8169009b1c42SEd Schouten
readBlobInRecord(BitstreamCursor & Stream,unsigned Block,unsigned RecordID)81709df3605dSDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
81719df3605dSDimitry Andric unsigned Block, unsigned RecordID) {
8172e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(Block))
8173e6d15924SDimitry Andric return std::move(Err);
8174d99dafe2SDimitry Andric
8175d99dafe2SDimitry Andric StringRef Strtab;
8176044eb2f6SDimitry Andric while (true) {
8177e6d15924SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8178e6d15924SDimitry Andric if (!MaybeEntry)
8179e6d15924SDimitry Andric return MaybeEntry.takeError();
8180e6d15924SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get();
8181e6d15924SDimitry Andric
8182d99dafe2SDimitry Andric switch (Entry.Kind) {
8183d99dafe2SDimitry Andric case BitstreamEntry::EndBlock:
8184d99dafe2SDimitry Andric return Strtab;
8185d99dafe2SDimitry Andric
8186d99dafe2SDimitry Andric case BitstreamEntry::Error:
8187d99dafe2SDimitry Andric return error("Malformed block");
8188d99dafe2SDimitry Andric
8189d99dafe2SDimitry Andric case BitstreamEntry::SubBlock:
8190e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
8191e6d15924SDimitry Andric return std::move(Err);
8192d99dafe2SDimitry Andric break;
8193d99dafe2SDimitry Andric
8194d99dafe2SDimitry Andric case BitstreamEntry::Record:
8195d99dafe2SDimitry Andric StringRef Blob;
8196d99dafe2SDimitry Andric SmallVector<uint64_t, 1> Record;
8197e6d15924SDimitry Andric Expected<unsigned> MaybeRecord =
8198e6d15924SDimitry Andric Stream.readRecord(Entry.ID, Record, &Blob);
8199e6d15924SDimitry Andric if (!MaybeRecord)
8200e6d15924SDimitry Andric return MaybeRecord.takeError();
8201e6d15924SDimitry Andric if (MaybeRecord.get() == RecordID)
8202d99dafe2SDimitry Andric Strtab = Blob;
8203d99dafe2SDimitry Andric break;
8204d99dafe2SDimitry Andric }
8205d99dafe2SDimitry Andric }
8206d99dafe2SDimitry Andric }
8207d99dafe2SDimitry Andric
8208009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8209009b1c42SEd Schouten // External interface
8210009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8211009b1c42SEd Schouten
8212b915e9e0SDimitry Andric Expected<std::vector<BitcodeModule>>
getBitcodeModuleList(MemoryBufferRef Buffer)8213b915e9e0SDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
82147ab83427SDimitry Andric auto FOrErr = getBitcodeFileContents(Buffer);
82157ab83427SDimitry Andric if (!FOrErr)
82167ab83427SDimitry Andric return FOrErr.takeError();
82177ab83427SDimitry Andric return std::move(FOrErr->Mods);
82187ab83427SDimitry Andric }
82197ab83427SDimitry Andric
82207ab83427SDimitry Andric Expected<BitcodeFileContents>
getBitcodeFileContents(MemoryBufferRef Buffer)82217ab83427SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
8222b915e9e0SDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8223b915e9e0SDimitry Andric if (!StreamOrErr)
8224b915e9e0SDimitry Andric return StreamOrErr.takeError();
8225b915e9e0SDimitry Andric BitstreamCursor &Stream = *StreamOrErr;
82263a0822f0SDimitry Andric
82277ab83427SDimitry Andric BitcodeFileContents F;
8228b915e9e0SDimitry Andric while (true) {
8229b915e9e0SDimitry Andric uint64_t BCBegin = Stream.getCurrentByteNo();
82303a0822f0SDimitry Andric
8231b915e9e0SDimitry Andric // We may be consuming bitcode from a client that leaves garbage at the end
8232b915e9e0SDimitry Andric // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
8233b915e9e0SDimitry Andric // the end that there cannot possibly be another module, stop looking.
8234b915e9e0SDimitry Andric if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
82357ab83427SDimitry Andric return F;
82363a0822f0SDimitry Andric
8237e6d15924SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8238e6d15924SDimitry Andric if (!MaybeEntry)
8239e6d15924SDimitry Andric return MaybeEntry.takeError();
8240e6d15924SDimitry Andric llvm::BitstreamEntry Entry = MaybeEntry.get();
8241e6d15924SDimitry Andric
8242b915e9e0SDimitry Andric switch (Entry.Kind) {
8243b915e9e0SDimitry Andric case BitstreamEntry::EndBlock:
8244b915e9e0SDimitry Andric case BitstreamEntry::Error:
8245b915e9e0SDimitry Andric return error("Malformed block");
8246b915e9e0SDimitry Andric
8247b915e9e0SDimitry Andric case BitstreamEntry::SubBlock: {
8248b915e9e0SDimitry Andric uint64_t IdentificationBit = -1ull;
8249b915e9e0SDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
8250b915e9e0SDimitry Andric IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8251e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
8252e6d15924SDimitry Andric return std::move(Err);
8253b915e9e0SDimitry Andric
8254e6d15924SDimitry Andric {
8255e6d15924SDimitry Andric Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8256e6d15924SDimitry Andric if (!MaybeEntry)
8257e6d15924SDimitry Andric return MaybeEntry.takeError();
8258e6d15924SDimitry Andric Entry = MaybeEntry.get();
8259e6d15924SDimitry Andric }
8260e6d15924SDimitry Andric
8261b915e9e0SDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock ||
8262b915e9e0SDimitry Andric Entry.ID != bitc::MODULE_BLOCK_ID)
8263b915e9e0SDimitry Andric return error("Malformed block");
82643a0822f0SDimitry Andric }
8265b915e9e0SDimitry Andric
8266b915e9e0SDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) {
8267b915e9e0SDimitry Andric uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8268e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
8269e6d15924SDimitry Andric return std::move(Err);
8270b915e9e0SDimitry Andric
82717ab83427SDimitry Andric F.Mods.push_back({Stream.getBitcodeBytes().slice(
8272b915e9e0SDimitry Andric BCBegin, Stream.getCurrentByteNo() - BCBegin),
8273b915e9e0SDimitry Andric Buffer.getBufferIdentifier(), IdentificationBit,
8274b915e9e0SDimitry Andric ModuleBit});
8275b915e9e0SDimitry Andric continue;
8276b915e9e0SDimitry Andric }
8277b915e9e0SDimitry Andric
8278d99dafe2SDimitry Andric if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
82799df3605dSDimitry Andric Expected<StringRef> Strtab =
82809df3605dSDimitry Andric readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
8281d99dafe2SDimitry Andric if (!Strtab)
8282d99dafe2SDimitry Andric return Strtab.takeError();
8283d99dafe2SDimitry Andric // This string table is used by every preceding bitcode module that does
8284d99dafe2SDimitry Andric // not have its own string table. A bitcode file may have multiple
8285d99dafe2SDimitry Andric // string tables if it was created by binary concatenation, for example
8286d99dafe2SDimitry Andric // with "llvm-cat -b".
828777fc4c14SDimitry Andric for (BitcodeModule &I : llvm::reverse(F.Mods)) {
828877fc4c14SDimitry Andric if (!I.Strtab.empty())
8289d99dafe2SDimitry Andric break;
829077fc4c14SDimitry Andric I.Strtab = *Strtab;
8291d99dafe2SDimitry Andric }
82929df3605dSDimitry Andric // Similarly, the string table is used by every preceding symbol table;
82939df3605dSDimitry Andric // normally there will be just one unless the bitcode file was created
82949df3605dSDimitry Andric // by binary concatenation.
82959df3605dSDimitry Andric if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
82969df3605dSDimitry Andric F.StrtabForSymtab = *Strtab;
82979df3605dSDimitry Andric continue;
82989df3605dSDimitry Andric }
82999df3605dSDimitry Andric
83009df3605dSDimitry Andric if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
83019df3605dSDimitry Andric Expected<StringRef> SymtabOrErr =
83029df3605dSDimitry Andric readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
83039df3605dSDimitry Andric if (!SymtabOrErr)
83049df3605dSDimitry Andric return SymtabOrErr.takeError();
83059df3605dSDimitry Andric
83069df3605dSDimitry Andric // We can expect the bitcode file to have multiple symbol tables if it
83079df3605dSDimitry Andric // was created by binary concatenation. In that case we silently
83089df3605dSDimitry Andric // ignore any subsequent symbol tables, which is fine because this is a
83099df3605dSDimitry Andric // low level function. The client is expected to notice that the number
83109df3605dSDimitry Andric // of modules in the symbol table does not match the number of modules
83119df3605dSDimitry Andric // in the input file and regenerate the symbol table.
83129df3605dSDimitry Andric if (F.Symtab.empty())
83139df3605dSDimitry Andric F.Symtab = *SymtabOrErr;
8314d99dafe2SDimitry Andric continue;
8315d99dafe2SDimitry Andric }
8316d99dafe2SDimitry Andric
8317e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
8318e6d15924SDimitry Andric return std::move(Err);
8319b915e9e0SDimitry Andric continue;
8320b915e9e0SDimitry Andric }
8321b915e9e0SDimitry Andric case BitstreamEntry::Record:
8322c0981da4SDimitry Andric if (Error E = Stream.skipRecord(Entry.ID).takeError())
8323c0981da4SDimitry Andric return std::move(E);
8324b915e9e0SDimitry Andric continue;
8325b915e9e0SDimitry Andric }
8326b915e9e0SDimitry Andric }
83273a0822f0SDimitry Andric }
83283a0822f0SDimitry Andric
8329eb11fae6SDimitry Andric /// Get a lazy one-at-time loading module from bitcode.
8330009b1c42SEd Schouten ///
833167c32a98SDimitry Andric /// This isn't always used in a lazy context. In particular, it's also used by
8332b915e9e0SDimitry Andric /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
833367c32a98SDimitry Andric /// in forward-referenced functions from block address references.
833467c32a98SDimitry Andric ///
83353a0822f0SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize
83363a0822f0SDimitry Andric /// everything.
8337b915e9e0SDimitry Andric Expected<std::unique_ptr<Module>>
getModuleImpl(LLVMContext & Context,bool MaterializeAll,bool ShouldLazyLoadMetadata,bool IsImporting,ParserCallbacks Callbacks)8338b915e9e0SDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
8339cfca06d7SDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting,
8340e3b55780SDimitry Andric ParserCallbacks Callbacks) {
8341b915e9e0SDimitry Andric BitstreamCursor Stream(Buffer);
834267c32a98SDimitry Andric
8343b915e9e0SDimitry Andric std::string ProducerIdentification;
8344b915e9e0SDimitry Andric if (IdentificationBit != -1ull) {
8345e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
8346e6d15924SDimitry Andric return std::move(JumpFailed);
8347c0981da4SDimitry Andric if (Error E =
8348c0981da4SDimitry Andric readIdentificationBlock(Stream).moveInto(ProducerIdentification))
8349c0981da4SDimitry Andric return std::move(E);
835063faed5bSDimitry Andric }
835163faed5bSDimitry Andric
8352e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8353e6d15924SDimitry Andric return std::move(JumpFailed);
8354d99dafe2SDimitry Andric auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8355d99dafe2SDimitry Andric Context);
8356b915e9e0SDimitry Andric
8357b915e9e0SDimitry Andric std::unique_ptr<Module> M =
83581d5ae102SDimitry Andric std::make_unique<Module>(ModuleIdentifier, Context);
8359b915e9e0SDimitry Andric M->setMaterializer(R);
8360b915e9e0SDimitry Andric
8361b915e9e0SDimitry Andric // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
8362cfca06d7SDimitry Andric if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
8363e3b55780SDimitry Andric IsImporting, Callbacks))
8364b915e9e0SDimitry Andric return std::move(Err);
8365b915e9e0SDimitry Andric
8366b915e9e0SDimitry Andric if (MaterializeAll) {
8367b915e9e0SDimitry Andric // Read in the entire module, and destroy the BitcodeReader.
8368b915e9e0SDimitry Andric if (Error Err = M->materializeAll())
8369b915e9e0SDimitry Andric return std::move(Err);
8370b915e9e0SDimitry Andric } else {
8371b915e9e0SDimitry Andric // Resolve forward references from blockaddresses.
8372b915e9e0SDimitry Andric if (Error Err = R->materializeForwardReferencedFunctions())
8373b915e9e0SDimitry Andric return std::move(Err);
8374b915e9e0SDimitry Andric }
8375ac9a064cSDimitry Andric
8376b915e9e0SDimitry Andric return std::move(M);
8377009b1c42SEd Schouten }
8378009b1c42SEd Schouten
8379b915e9e0SDimitry Andric Expected<std::unique_ptr<Module>>
getLazyModule(LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting,ParserCallbacks Callbacks)8380b915e9e0SDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
8381e3b55780SDimitry Andric bool IsImporting, ParserCallbacks Callbacks) {
8382cfca06d7SDimitry Andric return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
8383e3b55780SDimitry Andric Callbacks);
8384dd58ef01SDimitry Andric }
8385dd58ef01SDimitry Andric
8386a303c417SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex.
83877c7aba6eSDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the
83887c7aba6eSDimitry Andric // module path used in the combined summary (e.g. when reading summaries for
83897c7aba6eSDimitry Andric // regular LTO modules).
readSummary(ModuleSummaryIndex & CombinedIndex,StringRef ModulePath,std::function<bool (GlobalValue::GUID)> IsPrevailing)8390e3b55780SDimitry Andric Error BitcodeModule::readSummary(
8391b1c73532SDimitry Andric ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
8392e3b55780SDimitry Andric std::function<bool(GlobalValue::GUID)> IsPrevailing) {
8393a303c417SDimitry Andric BitstreamCursor Stream(Buffer);
8394e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8395e6d15924SDimitry Andric return JumpFailed;
8396a303c417SDimitry Andric
8397a303c417SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8398b1c73532SDimitry Andric ModulePath, IsPrevailing);
8399a303c417SDimitry Andric return R.parseModule();
8400a303c417SDimitry Andric }
8401a303c417SDimitry Andric
8402dd58ef01SDimitry Andric // Parse the specified bitcode buffer, returning the function info index.
getSummary()8403b915e9e0SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
8404b915e9e0SDimitry Andric BitstreamCursor Stream(Buffer);
8405e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8406e6d15924SDimitry Andric return std::move(JumpFailed);
8407dd58ef01SDimitry Andric
84081d5ae102SDimitry Andric auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
8409a303c417SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8410a303c417SDimitry Andric ModuleIdentifier, 0);
8411dd58ef01SDimitry Andric
8412a303c417SDimitry Andric if (Error Err = R.parseModule())
8413b915e9e0SDimitry Andric return std::move(Err);
8414dd58ef01SDimitry Andric
8415dd58ef01SDimitry Andric return std::move(Index);
8416dd58ef01SDimitry Andric }
8417dd58ef01SDimitry Andric
84187fa27ce4SDimitry Andric static Expected<std::pair<bool, bool>>
getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor & Stream,unsigned ID,BitcodeLTOInfo & LTOInfo)84197fa27ce4SDimitry Andric getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream,
84207fa27ce4SDimitry Andric unsigned ID,
84217fa27ce4SDimitry Andric BitcodeLTOInfo <OInfo) {
8422e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(ID))
8423e6d15924SDimitry Andric return std::move(Err);
8424d8e91e46SDimitry Andric SmallVector<uint64_t, 64> Record;
8425d8e91e46SDimitry Andric
8426d8e91e46SDimitry Andric while (true) {
8427c0981da4SDimitry Andric BitstreamEntry Entry;
84287fa27ce4SDimitry Andric std::pair<bool, bool> Result = {false,false};
8429c0981da4SDimitry Andric if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
8430c0981da4SDimitry Andric return std::move(E);
8431d8e91e46SDimitry Andric
8432d8e91e46SDimitry Andric switch (Entry.Kind) {
8433d8e91e46SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
8434d8e91e46SDimitry Andric case BitstreamEntry::Error:
8435d8e91e46SDimitry Andric return error("Malformed block");
84367fa27ce4SDimitry Andric case BitstreamEntry::EndBlock: {
84377fa27ce4SDimitry Andric // If no flags record found, set both flags to false.
84387fa27ce4SDimitry Andric return Result;
84397fa27ce4SDimitry Andric }
8440d8e91e46SDimitry Andric case BitstreamEntry::Record:
8441d8e91e46SDimitry Andric // The interesting case.
8442d8e91e46SDimitry Andric break;
8443d8e91e46SDimitry Andric }
8444d8e91e46SDimitry Andric
8445d8e91e46SDimitry Andric // Look for the FS_FLAGS record.
8446d8e91e46SDimitry Andric Record.clear();
8447e6d15924SDimitry Andric Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
8448e6d15924SDimitry Andric if (!MaybeBitCode)
8449e6d15924SDimitry Andric return MaybeBitCode.takeError();
8450e6d15924SDimitry Andric switch (MaybeBitCode.get()) {
8451d8e91e46SDimitry Andric default: // Default behavior: ignore.
8452d8e91e46SDimitry Andric break;
8453d8e91e46SDimitry Andric case bitc::FS_FLAGS: { // [flags]
8454d8e91e46SDimitry Andric uint64_t Flags = Record[0];
8455d8e91e46SDimitry Andric // Scan flags.
84567fa27ce4SDimitry Andric assert(Flags <= 0x2ff && "Unexpected bits in flag");
8457d8e91e46SDimitry Andric
84587fa27ce4SDimitry Andric bool EnableSplitLTOUnit = Flags & 0x8;
84597fa27ce4SDimitry Andric bool UnifiedLTO = Flags & 0x200;
84607fa27ce4SDimitry Andric Result = {EnableSplitLTOUnit, UnifiedLTO};
84617fa27ce4SDimitry Andric
84627fa27ce4SDimitry Andric return Result;
8463d8e91e46SDimitry Andric }
8464d8e91e46SDimitry Andric }
8465d8e91e46SDimitry Andric }
8466d8e91e46SDimitry Andric llvm_unreachable("Exit infinite loop");
8467d8e91e46SDimitry Andric }
8468d8e91e46SDimitry Andric
846901095a5dSDimitry Andric // Check if the given bitcode buffer contains a global value summary block.
getLTOInfo()84707c7aba6eSDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
8471b915e9e0SDimitry Andric BitstreamCursor Stream(Buffer);
8472e6d15924SDimitry Andric if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8473e6d15924SDimitry Andric return std::move(JumpFailed);
8474dd58ef01SDimitry Andric
8475e6d15924SDimitry Andric if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
8476e6d15924SDimitry Andric return std::move(Err);
8477b915e9e0SDimitry Andric
8478b915e9e0SDimitry Andric while (true) {
8479c0981da4SDimitry Andric llvm::BitstreamEntry Entry;
8480c0981da4SDimitry Andric if (Error E = Stream.advance().moveInto(Entry))
8481c0981da4SDimitry Andric return std::move(E);
8482b915e9e0SDimitry Andric
8483b915e9e0SDimitry Andric switch (Entry.Kind) {
8484b915e9e0SDimitry Andric case BitstreamEntry::Error:
8485b915e9e0SDimitry Andric return error("Malformed block");
8486b915e9e0SDimitry Andric case BitstreamEntry::EndBlock:
8487d8e91e46SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
84887fa27ce4SDimitry Andric /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
8489dd58ef01SDimitry Andric
8490b915e9e0SDimitry Andric case BitstreamEntry::SubBlock:
8491d8e91e46SDimitry Andric if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
84927fa27ce4SDimitry Andric BitcodeLTOInfo LTOInfo;
84937fa27ce4SDimitry Andric Expected<std::pair<bool, bool>> Flags =
84947fa27ce4SDimitry Andric getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
84957fa27ce4SDimitry Andric if (!Flags)
84967fa27ce4SDimitry Andric return Flags.takeError();
84977fa27ce4SDimitry Andric std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
84987fa27ce4SDimitry Andric LTOInfo.IsThinLTO = true;
84997fa27ce4SDimitry Andric LTOInfo.HasSummary = true;
85007fa27ce4SDimitry Andric return LTOInfo;
8501d8e91e46SDimitry Andric }
85027c7aba6eSDimitry Andric
8503d8e91e46SDimitry Andric if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
85047fa27ce4SDimitry Andric BitcodeLTOInfo LTOInfo;
85057fa27ce4SDimitry Andric Expected<std::pair<bool, bool>> Flags =
85067fa27ce4SDimitry Andric getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
85077fa27ce4SDimitry Andric if (!Flags)
85087fa27ce4SDimitry Andric return Flags.takeError();
85097fa27ce4SDimitry Andric std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
85107fa27ce4SDimitry Andric LTOInfo.IsThinLTO = false;
85117fa27ce4SDimitry Andric LTOInfo.HasSummary = true;
85127fa27ce4SDimitry Andric return LTOInfo;
8513d8e91e46SDimitry Andric }
8514dd58ef01SDimitry Andric
8515b915e9e0SDimitry Andric // Ignore other sub-blocks.
8516e6d15924SDimitry Andric if (Error Err = Stream.SkipBlock())
8517e6d15924SDimitry Andric return std::move(Err);
8518b915e9e0SDimitry Andric continue;
8519b915e9e0SDimitry Andric
8520b915e9e0SDimitry Andric case BitstreamEntry::Record:
8521e6d15924SDimitry Andric if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
8522b915e9e0SDimitry Andric continue;
8523e6d15924SDimitry Andric else
8524e6d15924SDimitry Andric return StreamFailed.takeError();
8525b915e9e0SDimitry Andric }
8526b915e9e0SDimitry Andric }
8527b915e9e0SDimitry Andric }
8528b915e9e0SDimitry Andric
getSingleModule(MemoryBufferRef Buffer)8529b915e9e0SDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
8530b915e9e0SDimitry Andric Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
8531b915e9e0SDimitry Andric if (!MsOrErr)
8532b915e9e0SDimitry Andric return MsOrErr.takeError();
8533b915e9e0SDimitry Andric
8534b915e9e0SDimitry Andric if (MsOrErr->size() != 1)
8535b915e9e0SDimitry Andric return error("Expected a single module");
8536b915e9e0SDimitry Andric
8537b915e9e0SDimitry Andric return (*MsOrErr)[0];
8538b915e9e0SDimitry Andric }
8539b915e9e0SDimitry Andric
8540b915e9e0SDimitry Andric Expected<std::unique_ptr<Module>>
getLazyBitcodeModule(MemoryBufferRef Buffer,LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting,ParserCallbacks Callbacks)8541b915e9e0SDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
8542e3b55780SDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting,
8543e3b55780SDimitry Andric ParserCallbacks Callbacks) {
8544b915e9e0SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer);
8545b915e9e0SDimitry Andric if (!BM)
8546b915e9e0SDimitry Andric return BM.takeError();
8547b915e9e0SDimitry Andric
8548e3b55780SDimitry Andric return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8549e3b55780SDimitry Andric Callbacks);
8550b915e9e0SDimitry Andric }
8551b915e9e0SDimitry Andric
getOwningLazyBitcodeModule(std::unique_ptr<MemoryBuffer> && Buffer,LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting,ParserCallbacks Callbacks)8552b915e9e0SDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
8553b915e9e0SDimitry Andric std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
8554e3b55780SDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
8555b915e9e0SDimitry Andric auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
8556e3b55780SDimitry Andric IsImporting, Callbacks);
8557b915e9e0SDimitry Andric if (MOrErr)
8558b915e9e0SDimitry Andric (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8559b915e9e0SDimitry Andric return MOrErr;
8560b915e9e0SDimitry Andric }
8561b915e9e0SDimitry Andric
8562b915e9e0SDimitry Andric Expected<std::unique_ptr<Module>>
parseModule(LLVMContext & Context,ParserCallbacks Callbacks)8563e3b55780SDimitry Andric BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) {
8564e3b55780SDimitry Andric return getModuleImpl(Context, true, false, false, Callbacks);
8565b915e9e0SDimitry Andric // TODO: Restore the use-lists to the in-memory state when the bitcode was
8566b915e9e0SDimitry Andric // written. We must defer until the Module has been fully materialized.
8567b915e9e0SDimitry Andric }
8568b915e9e0SDimitry Andric
8569cfca06d7SDimitry Andric Expected<std::unique_ptr<Module>>
parseBitcodeFile(MemoryBufferRef Buffer,LLVMContext & Context,ParserCallbacks Callbacks)8570cfca06d7SDimitry Andric llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
8571e3b55780SDimitry Andric ParserCallbacks Callbacks) {
8572b915e9e0SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer);
8573b915e9e0SDimitry Andric if (!BM)
8574b915e9e0SDimitry Andric return BM.takeError();
8575b915e9e0SDimitry Andric
8576e3b55780SDimitry Andric return BM->parseModule(Context, Callbacks);
8577b915e9e0SDimitry Andric }
8578b915e9e0SDimitry Andric
getBitcodeTargetTriple(MemoryBufferRef Buffer)8579b915e9e0SDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
8580b915e9e0SDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8581b915e9e0SDimitry Andric if (!StreamOrErr)
8582b915e9e0SDimitry Andric return StreamOrErr.takeError();
8583b915e9e0SDimitry Andric
8584b915e9e0SDimitry Andric return readTriple(*StreamOrErr);
8585b915e9e0SDimitry Andric }
8586b915e9e0SDimitry Andric
isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)8587b915e9e0SDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
8588b915e9e0SDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8589b915e9e0SDimitry Andric if (!StreamOrErr)
8590b915e9e0SDimitry Andric return StreamOrErr.takeError();
8591b915e9e0SDimitry Andric
8592b915e9e0SDimitry Andric return hasObjCCategory(*StreamOrErr);
8593b915e9e0SDimitry Andric }
8594b915e9e0SDimitry Andric
getBitcodeProducerString(MemoryBufferRef Buffer)8595b915e9e0SDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
8596b915e9e0SDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8597b915e9e0SDimitry Andric if (!StreamOrErr)
8598b915e9e0SDimitry Andric return StreamOrErr.takeError();
8599b915e9e0SDimitry Andric
8600b915e9e0SDimitry Andric return readIdentificationCode(*StreamOrErr);
8601b915e9e0SDimitry Andric }
8602b915e9e0SDimitry Andric
readModuleSummaryIndex(MemoryBufferRef Buffer,ModuleSummaryIndex & CombinedIndex)8603a303c417SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
8604b1c73532SDimitry Andric ModuleSummaryIndex &CombinedIndex) {
8605a303c417SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer);
8606a303c417SDimitry Andric if (!BM)
8607a303c417SDimitry Andric return BM.takeError();
8608a303c417SDimitry Andric
8609b1c73532SDimitry Andric return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8610a303c417SDimitry Andric }
8611a303c417SDimitry Andric
8612b915e9e0SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
getModuleSummaryIndex(MemoryBufferRef Buffer)8613b915e9e0SDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
8614b915e9e0SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer);
8615b915e9e0SDimitry Andric if (!BM)
8616b915e9e0SDimitry Andric return BM.takeError();
8617b915e9e0SDimitry Andric
8618b915e9e0SDimitry Andric return BM->getSummary();
8619b915e9e0SDimitry Andric }
8620b915e9e0SDimitry Andric
getBitcodeLTOInfo(MemoryBufferRef Buffer)86217c7aba6eSDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
8622b915e9e0SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer);
8623b915e9e0SDimitry Andric if (!BM)
8624b915e9e0SDimitry Andric return BM.takeError();
8625b915e9e0SDimitry Andric
86267c7aba6eSDimitry Andric return BM->getLTOInfo();
8627dd58ef01SDimitry Andric }
8628a303c417SDimitry Andric
8629a303c417SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
getModuleSummaryIndexForFile(StringRef Path,bool IgnoreEmptyThinLTOIndexFile)86306b3f41edSDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path,
86316b3f41edSDimitry Andric bool IgnoreEmptyThinLTOIndexFile) {
8632a303c417SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
8633a303c417SDimitry Andric MemoryBuffer::getFileOrSTDIN(Path);
8634a303c417SDimitry Andric if (!FileOrErr)
8635a303c417SDimitry Andric return errorCodeToError(FileOrErr.getError());
8636a303c417SDimitry Andric if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
8637a303c417SDimitry Andric return nullptr;
8638a303c417SDimitry Andric return getModuleSummaryIndex(**FileOrErr);
8639a303c417SDimitry Andric }
8640