1f22ef01cSRoman Divacky //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky // The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky
10d88c1a5aSDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
11d88c1a5aSDimitry Andric #include "MetadataLoader.h"
12d88c1a5aSDimitry Andric #include "ValueList.h"
13d88c1a5aSDimitry Andric #include "llvm/ADT/APFloat.h"
14d88c1a5aSDimitry Andric #include "llvm/ADT/APInt.h"
15d88c1a5aSDimitry Andric #include "llvm/ADT/ArrayRef.h"
16d88c1a5aSDimitry Andric #include "llvm/ADT/DenseMap.h"
172cab237bSDimitry Andric #include "llvm/ADT/Optional.h"
18ff0cc061SDimitry Andric #include "llvm/ADT/STLExtras.h"
19f22ef01cSRoman Divacky #include "llvm/ADT/SmallString.h"
20f22ef01cSRoman Divacky #include "llvm/ADT/SmallVector.h"
21d88c1a5aSDimitry Andric #include "llvm/ADT/StringRef.h"
22ff0cc061SDimitry Andric #include "llvm/ADT/Triple.h"
23d88c1a5aSDimitry Andric #include "llvm/ADT/Twine.h"
24ff0cc061SDimitry Andric #include "llvm/Bitcode/BitstreamReader.h"
25f785676fSDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
264ba319b5SDimitry Andric #include "llvm/Config/llvm-config.h"
27d88c1a5aSDimitry Andric #include "llvm/IR/Argument.h"
28d88c1a5aSDimitry Andric #include "llvm/IR/Attributes.h"
2991bc56edSDimitry Andric #include "llvm/IR/AutoUpgrade.h"
30d88c1a5aSDimitry Andric #include "llvm/IR/BasicBlock.h"
313ca95b02SDimitry Andric #include "llvm/IR/CallSite.h"
32db17bf38SDimitry Andric #include "llvm/IR/CallingConv.h"
33d88c1a5aSDimitry Andric #include "llvm/IR/Comdat.h"
34d88c1a5aSDimitry Andric #include "llvm/IR/Constant.h"
35139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
362cab237bSDimitry Andric #include "llvm/IR/DataLayout.h"
37ff0cc061SDimitry Andric #include "llvm/IR/DebugInfo.h"
38ff0cc061SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
39d88c1a5aSDimitry Andric #include "llvm/IR/DebugLoc.h"
40139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
41d88c1a5aSDimitry Andric #include "llvm/IR/Function.h"
42db17bf38SDimitry Andric #include "llvm/IR/GVMaterializer.h"
43d88c1a5aSDimitry Andric #include "llvm/IR/GlobalAlias.h"
44d88c1a5aSDimitry Andric #include "llvm/IR/GlobalIFunc.h"
45d88c1a5aSDimitry Andric #include "llvm/IR/GlobalIndirectSymbol.h"
46d88c1a5aSDimitry Andric #include "llvm/IR/GlobalObject.h"
47d88c1a5aSDimitry Andric #include "llvm/IR/GlobalValue.h"
48d88c1a5aSDimitry Andric #include "llvm/IR/GlobalVariable.h"
49139f7f9bSDimitry Andric #include "llvm/IR/InlineAsm.h"
50d88c1a5aSDimitry Andric #include "llvm/IR/InstIterator.h"
51d88c1a5aSDimitry Andric #include "llvm/IR/InstrTypes.h"
52d88c1a5aSDimitry Andric #include "llvm/IR/Instruction.h"
53d88c1a5aSDimitry Andric #include "llvm/IR/Instructions.h"
54d88c1a5aSDimitry Andric #include "llvm/IR/Intrinsics.h"
55f785676fSDimitry Andric #include "llvm/IR/LLVMContext.h"
562cab237bSDimitry Andric #include "llvm/IR/Metadata.h"
57139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
583ca95b02SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
59139f7f9bSDimitry Andric #include "llvm/IR/Operator.h"
60d88c1a5aSDimitry Andric #include "llvm/IR/Type.h"
612cab237bSDimitry Andric #include "llvm/IR/Value.h"
62d88c1a5aSDimitry Andric #include "llvm/IR/Verifier.h"
63d88c1a5aSDimitry Andric #include "llvm/Support/AtomicOrdering.h"
64d88c1a5aSDimitry Andric #include "llvm/Support/Casting.h"
653ca95b02SDimitry Andric #include "llvm/Support/CommandLine.h"
66d88c1a5aSDimitry Andric #include "llvm/Support/Compiler.h"
673ca95b02SDimitry Andric #include "llvm/Support/Debug.h"
68d88c1a5aSDimitry Andric #include "llvm/Support/Error.h"
69d88c1a5aSDimitry Andric #include "llvm/Support/ErrorHandling.h"
702cab237bSDimitry Andric #include "llvm/Support/ErrorOr.h"
7139d628a0SDimitry Andric #include "llvm/Support/ManagedStatic.h"
722cab237bSDimitry Andric #include "llvm/Support/MathExtras.h"
73f22ef01cSRoman Divacky #include "llvm/Support/MemoryBuffer.h"
74f785676fSDimitry Andric #include "llvm/Support/raw_ostream.h"
75d88c1a5aSDimitry Andric #include <algorithm>
76d88c1a5aSDimitry Andric #include <cassert>
77d88c1a5aSDimitry Andric #include <cstddef>
78d88c1a5aSDimitry Andric #include <cstdint>
79ff0cc061SDimitry Andric #include <deque>
80d88c1a5aSDimitry Andric #include <map>
81d88c1a5aSDimitry Andric #include <memory>
822cab237bSDimitry Andric #include <set>
83d88c1a5aSDimitry Andric #include <string>
84d88c1a5aSDimitry Andric #include <system_error>
85d88c1a5aSDimitry Andric #include <tuple>
863ca95b02SDimitry Andric #include <utility>
87d88c1a5aSDimitry Andric #include <vector>
883ca95b02SDimitry Andric
89f22ef01cSRoman Divacky using namespace llvm;
90f22ef01cSRoman Divacky
913ca95b02SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs(
923ca95b02SDimitry Andric "print-summary-global-ids", cl::init(false), cl::Hidden,
933ca95b02SDimitry Andric cl::desc(
943ca95b02SDimitry Andric "Print the global id for each value when reading the module summary"));
953ca95b02SDimitry Andric
96ff0cc061SDimitry Andric namespace {
97d88c1a5aSDimitry Andric
987ae0e2c9SDimitry Andric enum {
997ae0e2c9SDimitry Andric SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
1007ae0e2c9SDimitry Andric };
1017ae0e2c9SDimitry Andric
1022cab237bSDimitry Andric } // end anonymous namespace
1032cab237bSDimitry Andric
error(const Twine & Message)1042cab237bSDimitry Andric static Error error(const Twine &Message) {
105d88c1a5aSDimitry Andric return make_error<StringError>(
106d88c1a5aSDimitry Andric Message, make_error_code(BitcodeError::CorruptedBitcode));
107ff0cc061SDimitry Andric }
108ff0cc061SDimitry Andric
109d88c1a5aSDimitry Andric /// Helper to read the header common to all bitcode files.
hasValidBitcodeHeader(BitstreamCursor & Stream)1102cab237bSDimitry Andric static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
111d88c1a5aSDimitry Andric // Sniff for the signature.
112d88c1a5aSDimitry Andric if (!Stream.canSkipToPos(4) ||
113d88c1a5aSDimitry Andric Stream.Read(8) != 'B' ||
114d88c1a5aSDimitry Andric Stream.Read(8) != 'C' ||
115d88c1a5aSDimitry Andric Stream.Read(4) != 0x0 ||
116d88c1a5aSDimitry Andric Stream.Read(4) != 0xC ||
117d88c1a5aSDimitry Andric Stream.Read(4) != 0xE ||
118d88c1a5aSDimitry Andric Stream.Read(4) != 0xD)
119d88c1a5aSDimitry Andric return false;
120d88c1a5aSDimitry Andric return true;
121ff0cc061SDimitry Andric }
122ff0cc061SDimitry Andric
initStream(MemoryBufferRef Buffer)1232cab237bSDimitry Andric static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
124d88c1a5aSDimitry Andric const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
125d88c1a5aSDimitry Andric const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
126d88c1a5aSDimitry Andric
127d88c1a5aSDimitry Andric if (Buffer.getBufferSize() & 3)
128d88c1a5aSDimitry Andric return error("Invalid bitcode signature");
129d88c1a5aSDimitry Andric
130d88c1a5aSDimitry Andric // If we have a wrapper header, parse it and ignore the non-bc file contents.
131d88c1a5aSDimitry Andric // The magic number is 0x0B17C0DE stored in little endian.
132d88c1a5aSDimitry Andric if (isBitcodeWrapper(BufPtr, BufEnd))
133d88c1a5aSDimitry Andric if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
134d88c1a5aSDimitry Andric return error("Invalid bitcode wrapper header");
135d88c1a5aSDimitry Andric
136d88c1a5aSDimitry Andric BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
137d88c1a5aSDimitry Andric if (!hasValidBitcodeHeader(Stream))
138d88c1a5aSDimitry Andric return error("Invalid bitcode signature");
139d88c1a5aSDimitry Andric
140d88c1a5aSDimitry Andric return std::move(Stream);
141ff0cc061SDimitry Andric }
142ff0cc061SDimitry Andric
143d88c1a5aSDimitry Andric /// Convert a string from a record into an std::string, return true on failure.
144d88c1a5aSDimitry Andric template <typename StrTy>
convertToString(ArrayRef<uint64_t> Record,unsigned Idx,StrTy & Result)145d88c1a5aSDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
146d88c1a5aSDimitry Andric StrTy &Result) {
147d88c1a5aSDimitry Andric if (Idx > Record.size())
148d88c1a5aSDimitry Andric return true;
149d88c1a5aSDimitry Andric
150d88c1a5aSDimitry Andric for (unsigned i = Idx, e = Record.size(); i != e; ++i)
151d88c1a5aSDimitry Andric Result += (char)Record[i];
152d88c1a5aSDimitry Andric return false;
153ff0cc061SDimitry Andric }
154ff0cc061SDimitry Andric
155d88c1a5aSDimitry Andric // Strip all the TBAA attachment for the module.
stripTBAA(Module * M)1562cab237bSDimitry Andric static void stripTBAA(Module *M) {
157d88c1a5aSDimitry Andric for (auto &F : *M) {
158d88c1a5aSDimitry Andric if (F.isMaterializable())
159d88c1a5aSDimitry Andric continue;
160d88c1a5aSDimitry Andric for (auto &I : instructions(F))
161d88c1a5aSDimitry Andric I.setMetadata(LLVMContext::MD_tbaa, nullptr);
162d88c1a5aSDimitry Andric }
163d88c1a5aSDimitry Andric }
164ff0cc061SDimitry Andric
165d88c1a5aSDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
166d88c1a5aSDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any.
readIdentificationBlock(BitstreamCursor & Stream)1672cab237bSDimitry Andric static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
168d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
169d88c1a5aSDimitry Andric return error("Invalid record");
170ff0cc061SDimitry Andric
171d88c1a5aSDimitry Andric // Read all the records.
172d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record;
173d88c1a5aSDimitry Andric
174d88c1a5aSDimitry Andric std::string ProducerIdentification;
175d88c1a5aSDimitry Andric
176d88c1a5aSDimitry Andric while (true) {
177d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance();
178d88c1a5aSDimitry Andric
179d88c1a5aSDimitry Andric switch (Entry.Kind) {
180d88c1a5aSDimitry Andric default:
181d88c1a5aSDimitry Andric case BitstreamEntry::Error:
182d88c1a5aSDimitry Andric return error("Malformed block");
183d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock:
184d88c1a5aSDimitry Andric return ProducerIdentification;
185d88c1a5aSDimitry Andric case BitstreamEntry::Record:
186d88c1a5aSDimitry Andric // The interesting case.
187d88c1a5aSDimitry Andric break;
188d88c1a5aSDimitry Andric }
189d88c1a5aSDimitry Andric
190d88c1a5aSDimitry Andric // Read a record.
191d88c1a5aSDimitry Andric Record.clear();
192d88c1a5aSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record);
193d88c1a5aSDimitry Andric switch (BitCode) {
194d88c1a5aSDimitry Andric default: // Default behavior: reject
195d88c1a5aSDimitry Andric return error("Invalid value");
196d88c1a5aSDimitry Andric case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
197d88c1a5aSDimitry Andric convertToString(Record, 0, ProducerIdentification);
198d88c1a5aSDimitry Andric break;
199d88c1a5aSDimitry Andric case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
200d88c1a5aSDimitry Andric unsigned epoch = (unsigned)Record[0];
201d88c1a5aSDimitry Andric if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
202d88c1a5aSDimitry Andric return error(
203d88c1a5aSDimitry Andric Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
204d88c1a5aSDimitry Andric "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
205d88c1a5aSDimitry Andric }
206d88c1a5aSDimitry Andric }
207d88c1a5aSDimitry Andric }
208d88c1a5aSDimitry Andric }
209d88c1a5aSDimitry Andric }
210d88c1a5aSDimitry Andric
readIdentificationCode(BitstreamCursor & Stream)2112cab237bSDimitry Andric static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
212d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily
213d88c1a5aSDimitry Andric // need to understand them all.
214d88c1a5aSDimitry Andric while (true) {
215d88c1a5aSDimitry Andric if (Stream.AtEndOfStream())
216d88c1a5aSDimitry Andric return "";
217d88c1a5aSDimitry Andric
218d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance();
219d88c1a5aSDimitry Andric switch (Entry.Kind) {
220d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock:
221d88c1a5aSDimitry Andric case BitstreamEntry::Error:
222d88c1a5aSDimitry Andric return error("Malformed block");
223d88c1a5aSDimitry Andric
224d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock:
225d88c1a5aSDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
226d88c1a5aSDimitry Andric return readIdentificationBlock(Stream);
227d88c1a5aSDimitry Andric
228d88c1a5aSDimitry Andric // Ignore other sub-blocks.
229d88c1a5aSDimitry Andric if (Stream.SkipBlock())
230d88c1a5aSDimitry Andric return error("Malformed block");
231d88c1a5aSDimitry Andric continue;
232d88c1a5aSDimitry Andric case BitstreamEntry::Record:
233d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID);
234d88c1a5aSDimitry Andric continue;
235d88c1a5aSDimitry Andric }
236d88c1a5aSDimitry Andric }
237d88c1a5aSDimitry Andric }
238d88c1a5aSDimitry Andric
hasObjCCategoryInModule(BitstreamCursor & Stream)2392cab237bSDimitry Andric static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
240d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
241d88c1a5aSDimitry Andric return error("Invalid record");
242d88c1a5aSDimitry Andric
243d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record;
244d88c1a5aSDimitry Andric // Read all the records for this module.
245d88c1a5aSDimitry Andric
246d88c1a5aSDimitry Andric while (true) {
247d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
248d88c1a5aSDimitry Andric
249d88c1a5aSDimitry Andric switch (Entry.Kind) {
250d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
251d88c1a5aSDimitry Andric case BitstreamEntry::Error:
252d88c1a5aSDimitry Andric return error("Malformed block");
253d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock:
254d88c1a5aSDimitry Andric return false;
255d88c1a5aSDimitry Andric case BitstreamEntry::Record:
256d88c1a5aSDimitry Andric // The interesting case.
257d88c1a5aSDimitry Andric break;
258d88c1a5aSDimitry Andric }
259d88c1a5aSDimitry Andric
260d88c1a5aSDimitry Andric // Read a record.
261d88c1a5aSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) {
262d88c1a5aSDimitry Andric default:
263d88c1a5aSDimitry Andric break; // Default behavior, ignore unknown content.
264d88c1a5aSDimitry Andric case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
265d88c1a5aSDimitry Andric std::string S;
266d88c1a5aSDimitry Andric if (convertToString(Record, 0, S))
267d88c1a5aSDimitry Andric return error("Invalid record");
268d88c1a5aSDimitry Andric // Check for the i386 and other (x86_64, ARM) conventions
269d88c1a5aSDimitry Andric if (S.find("__DATA,__objc_catlist") != std::string::npos ||
270d88c1a5aSDimitry Andric S.find("__OBJC,__category") != std::string::npos)
271d88c1a5aSDimitry Andric return true;
272d88c1a5aSDimitry Andric break;
273d88c1a5aSDimitry Andric }
274d88c1a5aSDimitry Andric }
275d88c1a5aSDimitry Andric Record.clear();
276d88c1a5aSDimitry Andric }
277d88c1a5aSDimitry Andric llvm_unreachable("Exit infinite loop");
278d88c1a5aSDimitry Andric }
279d88c1a5aSDimitry Andric
hasObjCCategory(BitstreamCursor & Stream)2802cab237bSDimitry Andric static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
281d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily
282d88c1a5aSDimitry Andric // need to understand them all.
283d88c1a5aSDimitry Andric while (true) {
284d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance();
285d88c1a5aSDimitry Andric
286d88c1a5aSDimitry Andric switch (Entry.Kind) {
287d88c1a5aSDimitry Andric case BitstreamEntry::Error:
288d88c1a5aSDimitry Andric return error("Malformed block");
289d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock:
290d88c1a5aSDimitry Andric return false;
291d88c1a5aSDimitry Andric
292d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock:
293d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID)
294d88c1a5aSDimitry Andric return hasObjCCategoryInModule(Stream);
295d88c1a5aSDimitry Andric
296d88c1a5aSDimitry Andric // Ignore other sub-blocks.
297d88c1a5aSDimitry Andric if (Stream.SkipBlock())
298d88c1a5aSDimitry Andric return error("Malformed block");
299d88c1a5aSDimitry Andric continue;
300d88c1a5aSDimitry Andric
301d88c1a5aSDimitry Andric case BitstreamEntry::Record:
302d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID);
303d88c1a5aSDimitry Andric continue;
304d88c1a5aSDimitry Andric }
305d88c1a5aSDimitry Andric }
306d88c1a5aSDimitry Andric }
307d88c1a5aSDimitry Andric
readModuleTriple(BitstreamCursor & Stream)3082cab237bSDimitry Andric static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
309d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
310d88c1a5aSDimitry Andric return error("Invalid record");
311d88c1a5aSDimitry Andric
312d88c1a5aSDimitry Andric SmallVector<uint64_t, 64> Record;
313d88c1a5aSDimitry Andric
314d88c1a5aSDimitry Andric std::string Triple;
315d88c1a5aSDimitry Andric
316d88c1a5aSDimitry Andric // Read all the records for this module.
317d88c1a5aSDimitry Andric while (true) {
318d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
319d88c1a5aSDimitry Andric
320d88c1a5aSDimitry Andric switch (Entry.Kind) {
321d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
322d88c1a5aSDimitry Andric case BitstreamEntry::Error:
323d88c1a5aSDimitry Andric return error("Malformed block");
324d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock:
325d88c1a5aSDimitry Andric return Triple;
326d88c1a5aSDimitry Andric case BitstreamEntry::Record:
327d88c1a5aSDimitry Andric // The interesting case.
328d88c1a5aSDimitry Andric break;
329d88c1a5aSDimitry Andric }
330d88c1a5aSDimitry Andric
331d88c1a5aSDimitry Andric // Read a record.
332d88c1a5aSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) {
333d88c1a5aSDimitry Andric default: break; // Default behavior, ignore unknown content.
334d88c1a5aSDimitry Andric case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
335d88c1a5aSDimitry Andric std::string S;
336d88c1a5aSDimitry Andric if (convertToString(Record, 0, S))
337d88c1a5aSDimitry Andric return error("Invalid record");
338d88c1a5aSDimitry Andric Triple = S;
339d88c1a5aSDimitry Andric break;
340d88c1a5aSDimitry Andric }
341d88c1a5aSDimitry Andric }
342d88c1a5aSDimitry Andric Record.clear();
343d88c1a5aSDimitry Andric }
344d88c1a5aSDimitry Andric llvm_unreachable("Exit infinite loop");
345d88c1a5aSDimitry Andric }
346d88c1a5aSDimitry Andric
readTriple(BitstreamCursor & Stream)3472cab237bSDimitry Andric static Expected<std::string> readTriple(BitstreamCursor &Stream) {
348d88c1a5aSDimitry Andric // We expect a number of well-defined blocks, though we don't necessarily
349d88c1a5aSDimitry Andric // need to understand them all.
350d88c1a5aSDimitry Andric while (true) {
351d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance();
352d88c1a5aSDimitry Andric
353d88c1a5aSDimitry Andric switch (Entry.Kind) {
354d88c1a5aSDimitry Andric case BitstreamEntry::Error:
355d88c1a5aSDimitry Andric return error("Malformed block");
356d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock:
357d88c1a5aSDimitry Andric return "";
358d88c1a5aSDimitry Andric
359d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock:
360d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID)
361d88c1a5aSDimitry Andric return readModuleTriple(Stream);
362d88c1a5aSDimitry Andric
363d88c1a5aSDimitry Andric // Ignore other sub-blocks.
364d88c1a5aSDimitry Andric if (Stream.SkipBlock())
365d88c1a5aSDimitry Andric return error("Malformed block");
366d88c1a5aSDimitry Andric continue;
367d88c1a5aSDimitry Andric
368d88c1a5aSDimitry Andric case BitstreamEntry::Record:
369d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID);
370d88c1a5aSDimitry Andric continue;
371d88c1a5aSDimitry Andric }
372d88c1a5aSDimitry Andric }
373d88c1a5aSDimitry Andric }
374d88c1a5aSDimitry Andric
3752cab237bSDimitry Andric namespace {
3762cab237bSDimitry Andric
377d88c1a5aSDimitry Andric class BitcodeReaderBase {
378d88c1a5aSDimitry Andric protected:
BitcodeReaderBase(BitstreamCursor Stream,StringRef Strtab)3796bc11b14SDimitry Andric BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
3806bc11b14SDimitry Andric : Stream(std::move(Stream)), Strtab(Strtab) {
381d88c1a5aSDimitry Andric this->Stream.setBlockInfo(&BlockInfo);
382d88c1a5aSDimitry Andric }
383d88c1a5aSDimitry Andric
384d88c1a5aSDimitry Andric BitstreamBlockInfo BlockInfo;
385d88c1a5aSDimitry Andric BitstreamCursor Stream;
3866bc11b14SDimitry Andric StringRef Strtab;
3876bc11b14SDimitry Andric
3886bc11b14SDimitry Andric /// In version 2 of the bitcode we store names of global values and comdats in
3896bc11b14SDimitry Andric /// a string table rather than in the VST.
3906bc11b14SDimitry Andric bool UseStrtab = false;
391d88c1a5aSDimitry Andric
3927a7e6055SDimitry Andric Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
3937a7e6055SDimitry Andric
3946bc11b14SDimitry Andric /// If this module uses a string table, pop the reference to the string table
3956bc11b14SDimitry Andric /// and return the referenced string and the rest of the record. Otherwise
3966bc11b14SDimitry Andric /// just return the record itself.
3976bc11b14SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>>
3986bc11b14SDimitry Andric readNameFromStrtab(ArrayRef<uint64_t> Record);
3996bc11b14SDimitry Andric
400d88c1a5aSDimitry Andric bool readBlockInfo();
401d88c1a5aSDimitry Andric
402d88c1a5aSDimitry Andric // Contains an arbitrary and optional string identifying the bitcode producer
403d88c1a5aSDimitry Andric std::string ProducerIdentification;
404d88c1a5aSDimitry Andric
405d88c1a5aSDimitry Andric Error error(const Twine &Message);
406ff0cc061SDimitry Andric };
407ff0cc061SDimitry Andric
4082cab237bSDimitry Andric } // end anonymous namespace
4092cab237bSDimitry Andric
error(const Twine & Message)410d88c1a5aSDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) {
411d88c1a5aSDimitry Andric std::string FullMsg = Message.str();
412d88c1a5aSDimitry Andric if (!ProducerIdentification.empty())
413d88c1a5aSDimitry Andric FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
414d88c1a5aSDimitry Andric LLVM_VERSION_STRING "')";
415d88c1a5aSDimitry Andric return ::error(FullMsg);
416ff0cc061SDimitry Andric }
417ff0cc061SDimitry Andric
4187a7e6055SDimitry Andric Expected<unsigned>
parseVersionRecord(ArrayRef<uint64_t> Record)4197a7e6055SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
4202cab237bSDimitry Andric if (Record.empty())
4217a7e6055SDimitry Andric return error("Invalid record");
4227a7e6055SDimitry Andric unsigned ModuleVersion = Record[0];
4236bc11b14SDimitry Andric if (ModuleVersion > 2)
4247a7e6055SDimitry Andric return error("Invalid value");
4256bc11b14SDimitry Andric UseStrtab = ModuleVersion >= 2;
4267a7e6055SDimitry Andric return ModuleVersion;
4277a7e6055SDimitry Andric }
4287a7e6055SDimitry Andric
4296bc11b14SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>>
readNameFromStrtab(ArrayRef<uint64_t> Record)4306bc11b14SDimitry Andric BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
4316bc11b14SDimitry Andric if (!UseStrtab)
4326bc11b14SDimitry Andric return {"", Record};
4336bc11b14SDimitry Andric // Invalid reference. Let the caller complain about the record being empty.
4346bc11b14SDimitry Andric if (Record[0] + Record[1] > Strtab.size())
4356bc11b14SDimitry Andric return {"", {}};
4366bc11b14SDimitry Andric return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
4376bc11b14SDimitry Andric }
4386bc11b14SDimitry Andric
4392cab237bSDimitry Andric namespace {
4402cab237bSDimitry Andric
441d88c1a5aSDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
442ff0cc061SDimitry Andric LLVMContext &Context;
4438f0fd8f6SDimitry Andric Module *TheModule = nullptr;
4447d523365SDimitry Andric // Next offset to start scanning for lazy parsing of function bodies.
4458f0fd8f6SDimitry Andric uint64_t NextUnreadBit = 0;
4467d523365SDimitry Andric // Last function offset found in the VST.
4477d523365SDimitry Andric uint64_t LastFunctionBlockBit = 0;
4488f0fd8f6SDimitry Andric bool SeenValueSymbolTable = false;
4497d523365SDimitry Andric uint64_t VSTOffset = 0;
450ff0cc061SDimitry Andric
4517a7e6055SDimitry Andric std::vector<std::string> SectionTable;
4527a7e6055SDimitry Andric std::vector<std::string> GCTable;
4537a7e6055SDimitry Andric
454ff0cc061SDimitry Andric std::vector<Type*> TypeList;
455ff0cc061SDimitry Andric BitcodeReaderValueList ValueList;
456d88c1a5aSDimitry Andric Optional<MetadataLoader> MDLoader;
457ff0cc061SDimitry Andric std::vector<Comdat *> ComdatList;
458ff0cc061SDimitry Andric SmallVector<Instruction *, 64> InstructionList;
459ff0cc061SDimitry Andric
460ff0cc061SDimitry Andric std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
4613ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
462ff0cc061SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
463ff0cc061SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
4648f0fd8f6SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
465ff0cc061SDimitry Andric
4668f0fd8f6SDimitry Andric /// The set of attributes by index. Index zero in the file is for null, and
4678f0fd8f6SDimitry Andric /// is thus not represented here. As such all indices are off by one.
4687a7e6055SDimitry Andric std::vector<AttributeList> MAttributes;
469ff0cc061SDimitry Andric
4707d523365SDimitry Andric /// The set of attribute groups.
4717a7e6055SDimitry Andric std::map<unsigned, AttributeList> MAttributeGroups;
472ff0cc061SDimitry Andric
4738f0fd8f6SDimitry Andric /// While parsing a function body, this is a list of the basic blocks for the
4748f0fd8f6SDimitry Andric /// function.
475ff0cc061SDimitry Andric std::vector<BasicBlock*> FunctionBBs;
476ff0cc061SDimitry Andric
477ff0cc061SDimitry Andric // When reading the module header, this list is populated with functions that
478ff0cc061SDimitry Andric // have bodies later in the file.
479ff0cc061SDimitry Andric std::vector<Function*> FunctionsWithBodies;
480ff0cc061SDimitry Andric
481ff0cc061SDimitry Andric // When intrinsic functions are encountered which require upgrading they are
482ff0cc061SDimitry Andric // stored here with their replacement function.
4832cab237bSDimitry Andric using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
4843ca95b02SDimitry Andric UpdatedIntrinsicMap UpgradedIntrinsics;
4853ca95b02SDimitry Andric // Intrinsics which were remangled because of types rename
4863ca95b02SDimitry Andric UpdatedIntrinsicMap RemangledIntrinsics;
487ff0cc061SDimitry Andric
488ff0cc061SDimitry Andric // Several operations happen after the module header has been read, but
489ff0cc061SDimitry Andric // before function bodies are processed. This keeps track of whether
490ff0cc061SDimitry Andric // we've done this yet.
4918f0fd8f6SDimitry Andric bool SeenFirstFunctionBody = false;
492ff0cc061SDimitry Andric
4938f0fd8f6SDimitry Andric /// When function bodies are initially scanned, this map contains info about
4948f0fd8f6SDimitry Andric /// where to find deferred function body in the stream.
495ff0cc061SDimitry Andric DenseMap<Function*, uint64_t> DeferredFunctionInfo;
496ff0cc061SDimitry Andric
497ff0cc061SDimitry Andric /// When Metadata block is initially scanned when parsing the module, we may
498ff0cc061SDimitry Andric /// choose to defer parsing of the metadata. This vector contains info about
499ff0cc061SDimitry Andric /// which Metadata blocks are deferred.
500ff0cc061SDimitry Andric std::vector<uint64_t> DeferredMetadataInfo;
501ff0cc061SDimitry Andric
502ff0cc061SDimitry Andric /// These are basic blocks forward-referenced by block addresses. They are
503ff0cc061SDimitry Andric /// inserted lazily into functions when they're loaded. The basic block ID is
504ff0cc061SDimitry Andric /// its index into the vector.
505ff0cc061SDimitry Andric DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
506ff0cc061SDimitry Andric std::deque<Function *> BasicBlockFwdRefQueue;
507ff0cc061SDimitry Andric
5088f0fd8f6SDimitry Andric /// Indicates that we are using a new encoding for instruction operands where
5098f0fd8f6SDimitry Andric /// most operands in the current FUNCTION_BLOCK are encoded relative to the
5108f0fd8f6SDimitry Andric /// instruction number, for a more compact encoding. Some instruction
5118f0fd8f6SDimitry Andric /// operands are not relative to the instruction ID: basic block numbers, and
5128f0fd8f6SDimitry Andric /// types. Once the old style function blocks have been phased out, we would
513ff0cc061SDimitry Andric /// not need this flag.
5148f0fd8f6SDimitry Andric bool UseRelativeIDs = false;
515ff0cc061SDimitry Andric
516ff0cc061SDimitry Andric /// True if all functions will be materialized, negating the need to process
517ff0cc061SDimitry Andric /// (e.g.) blockaddress forward references.
5188f0fd8f6SDimitry Andric bool WillMaterializeAllForwardRefs = false;
519ff0cc061SDimitry Andric
520ff0cc061SDimitry Andric bool StripDebugInfo = false;
521d88c1a5aSDimitry Andric TBAAVerifier TBAAVerifyHelper;
5227d523365SDimitry Andric
5237d523365SDimitry Andric std::vector<std::string> BundleTags;
524c4394386SDimitry Andric SmallVector<SyncScope::ID, 8> SSIDs;
5257d523365SDimitry Andric
526ff0cc061SDimitry Andric public:
5276bc11b14SDimitry Andric BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
5286bc11b14SDimitry Andric StringRef ProducerIdentification, LLVMContext &Context);
529ff0cc061SDimitry Andric
530d88c1a5aSDimitry Andric Error materializeForwardReferencedFunctions();
531ff0cc061SDimitry Andric
532d88c1a5aSDimitry Andric Error materialize(GlobalValue *GV) override;
533d88c1a5aSDimitry Andric Error materializeModule() override;
534ff0cc061SDimitry Andric std::vector<StructType *> getIdentifiedStructTypes() const override;
535ff0cc061SDimitry Andric
5364ba319b5SDimitry Andric /// Main interface to parsing a bitcode buffer.
5378f0fd8f6SDimitry Andric /// \returns true if an error occurred.
538d88c1a5aSDimitry Andric Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
539d88c1a5aSDimitry Andric bool IsImporting = false);
5403ca95b02SDimitry Andric
541ff0cc061SDimitry Andric static uint64_t decodeSignRotatedValue(uint64_t V);
542ff0cc061SDimitry Andric
543ff0cc061SDimitry Andric /// Materialize any deferred Metadata block.
544d88c1a5aSDimitry Andric Error materializeMetadata() override;
545ff0cc061SDimitry Andric
546ff0cc061SDimitry Andric void setStripDebugInfo() override;
547ff0cc061SDimitry Andric
548ff0cc061SDimitry Andric private:
549ff0cc061SDimitry Andric std::vector<StructType *> IdentifiedStructTypes;
550ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
551ff0cc061SDimitry Andric StructType *createIdentifiedStructType(LLVMContext &Context);
552ff0cc061SDimitry Andric
553ff0cc061SDimitry Andric Type *getTypeByID(unsigned ID);
554d88c1a5aSDimitry Andric
getFnValueByID(unsigned ID,Type * Ty)555ff0cc061SDimitry Andric Value *getFnValueByID(unsigned ID, Type *Ty) {
556ff0cc061SDimitry Andric if (Ty && Ty->isMetadataTy())
557ff0cc061SDimitry Andric return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
558ff0cc061SDimitry Andric return ValueList.getValueFwdRef(ID, Ty);
559ff0cc061SDimitry Andric }
560d88c1a5aSDimitry Andric
getFnMetadataByID(unsigned ID)561ff0cc061SDimitry Andric Metadata *getFnMetadataByID(unsigned ID) {
562f8496407SDimitry Andric return MDLoader->getMetadataFwdRefOrLoad(ID);
563ff0cc061SDimitry Andric }
564d88c1a5aSDimitry Andric
getBasicBlock(unsigned ID) const565ff0cc061SDimitry Andric BasicBlock *getBasicBlock(unsigned ID) const {
566ff0cc061SDimitry Andric if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
567ff0cc061SDimitry Andric return FunctionBBs[ID];
568ff0cc061SDimitry Andric }
569d88c1a5aSDimitry Andric
getAttributes(unsigned i) const5707a7e6055SDimitry Andric AttributeList getAttributes(unsigned i) const {
571ff0cc061SDimitry Andric if (i-1 < MAttributes.size())
572ff0cc061SDimitry Andric return MAttributes[i-1];
5737a7e6055SDimitry Andric return AttributeList();
574ff0cc061SDimitry Andric }
575ff0cc061SDimitry Andric
5768f0fd8f6SDimitry Andric /// Read a value/type pair out of the specified record from slot 'Slot'.
5778f0fd8f6SDimitry Andric /// Increment Slot past the number of slots used in the record. Return true on
5788f0fd8f6SDimitry Andric /// failure.
getValueTypePair(SmallVectorImpl<uint64_t> & Record,unsigned & Slot,unsigned InstNum,Value * & ResVal)579ff0cc061SDimitry Andric bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
580ff0cc061SDimitry Andric unsigned InstNum, Value *&ResVal) {
581ff0cc061SDimitry Andric if (Slot == Record.size()) return true;
582ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot++];
583ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum.
584ff0cc061SDimitry Andric if (UseRelativeIDs)
585ff0cc061SDimitry Andric ValNo = InstNum - ValNo;
586ff0cc061SDimitry Andric if (ValNo < InstNum) {
587ff0cc061SDimitry Andric // If this is not a forward reference, just return the value we already
588ff0cc061SDimitry Andric // have.
589ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, nullptr);
590ff0cc061SDimitry Andric return ResVal == nullptr;
591ff0cc061SDimitry Andric }
592ff0cc061SDimitry Andric if (Slot == Record.size())
593ff0cc061SDimitry Andric return true;
594ff0cc061SDimitry Andric
595ff0cc061SDimitry Andric unsigned TypeNo = (unsigned)Record[Slot++];
596ff0cc061SDimitry Andric ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
597ff0cc061SDimitry Andric return ResVal == nullptr;
598ff0cc061SDimitry Andric }
599ff0cc061SDimitry Andric
6008f0fd8f6SDimitry Andric /// Read a value out of the specified record from slot 'Slot'. Increment Slot
6018f0fd8f6SDimitry Andric /// past the number of slots used by the value in the record. Return true if
6028f0fd8f6SDimitry Andric /// there is an error.
popValue(SmallVectorImpl<uint64_t> & Record,unsigned & Slot,unsigned InstNum,Type * Ty,Value * & ResVal)603ff0cc061SDimitry Andric bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
604ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) {
605ff0cc061SDimitry Andric if (getValue(Record, Slot, InstNum, Ty, ResVal))
606ff0cc061SDimitry Andric return true;
607ff0cc061SDimitry Andric // All values currently take a single record slot.
608ff0cc061SDimitry Andric ++Slot;
609ff0cc061SDimitry Andric return false;
610ff0cc061SDimitry Andric }
611ff0cc061SDimitry Andric
6128f0fd8f6SDimitry Andric /// Like popValue, but does not increment the Slot number.
getValue(SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty,Value * & ResVal)613ff0cc061SDimitry Andric bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
614ff0cc061SDimitry Andric unsigned InstNum, Type *Ty, Value *&ResVal) {
615ff0cc061SDimitry Andric ResVal = getValue(Record, Slot, InstNum, Ty);
616ff0cc061SDimitry Andric return ResVal == nullptr;
617ff0cc061SDimitry Andric }
618ff0cc061SDimitry Andric
6198f0fd8f6SDimitry Andric /// Version of getValue that returns ResVal directly, or 0 if there is an
6208f0fd8f6SDimitry Andric /// error.
getValue(SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty)621ff0cc061SDimitry Andric Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
622ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) {
623ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr;
624ff0cc061SDimitry Andric unsigned ValNo = (unsigned)Record[Slot];
625ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum.
626ff0cc061SDimitry Andric if (UseRelativeIDs)
627ff0cc061SDimitry Andric ValNo = InstNum - ValNo;
628ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty);
629ff0cc061SDimitry Andric }
630ff0cc061SDimitry Andric
6318f0fd8f6SDimitry Andric /// Like getValue, but decodes signed VBRs.
getValueSigned(SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty)632ff0cc061SDimitry Andric Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
633ff0cc061SDimitry Andric unsigned InstNum, Type *Ty) {
634ff0cc061SDimitry Andric if (Slot == Record.size()) return nullptr;
635ff0cc061SDimitry Andric unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
636ff0cc061SDimitry Andric // Adjust the ValNo, if it was encoded relative to the InstNum.
637ff0cc061SDimitry Andric if (UseRelativeIDs)
638ff0cc061SDimitry Andric ValNo = InstNum - ValNo;
639ff0cc061SDimitry Andric return getFnValueByID(ValNo, Ty);
640ff0cc061SDimitry Andric }
641ff0cc061SDimitry Andric
642ff0cc061SDimitry Andric /// Converts alignment exponent (i.e. power of two (or zero)) to the
643ff0cc061SDimitry Andric /// corresponding alignment to use. If alignment is too large, returns
644ff0cc061SDimitry Andric /// a corresponding error code.
645d88c1a5aSDimitry Andric Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
646d88c1a5aSDimitry Andric Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
647d88c1a5aSDimitry Andric Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
6487a7e6055SDimitry Andric
6497a7e6055SDimitry Andric Error parseComdatRecord(ArrayRef<uint64_t> Record);
6507a7e6055SDimitry Andric Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
6517a7e6055SDimitry Andric Error parseFunctionRecord(ArrayRef<uint64_t> Record);
6527a7e6055SDimitry Andric Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
6537a7e6055SDimitry Andric ArrayRef<uint64_t> Record);
6547a7e6055SDimitry Andric
655d88c1a5aSDimitry Andric Error parseAttributeBlock();
656d88c1a5aSDimitry Andric Error parseAttributeGroupBlock();
657d88c1a5aSDimitry Andric Error parseTypeTable();
658d88c1a5aSDimitry Andric Error parseTypeTableBody();
659d88c1a5aSDimitry Andric Error parseOperandBundleTags();
660c4394386SDimitry Andric Error parseSyncScopeNames();
661ff0cc061SDimitry Andric
662d88c1a5aSDimitry Andric Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
6637d523365SDimitry Andric unsigned NameIndex, Triple &TT);
6646bc11b14SDimitry Andric void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
6656bc11b14SDimitry Andric ArrayRef<uint64_t> Record);
666d88c1a5aSDimitry Andric Error parseValueSymbolTable(uint64_t Offset = 0);
6676bc11b14SDimitry Andric Error parseGlobalValueSymbolTable();
668d88c1a5aSDimitry Andric Error parseConstants();
669d88c1a5aSDimitry Andric Error rememberAndSkipFunctionBodies();
670d88c1a5aSDimitry Andric Error rememberAndSkipFunctionBody();
671ff0cc061SDimitry Andric /// Save the positions of the Metadata blocks and skip parsing the blocks.
672d88c1a5aSDimitry Andric Error rememberAndSkipMetadata();
673d88c1a5aSDimitry Andric Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
674d88c1a5aSDimitry Andric Error parseFunctionBody(Function *F);
675d88c1a5aSDimitry Andric Error globalCleanup();
676d88c1a5aSDimitry Andric Error resolveGlobalAndIndirectSymbolInits();
677d88c1a5aSDimitry Andric Error parseUseLists();
678d88c1a5aSDimitry Andric Error findFunctionInStream(
679ff0cc061SDimitry Andric Function *F,
680ff0cc061SDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
681c4394386SDimitry Andric
682c4394386SDimitry Andric SyncScope::ID getDecodedSyncScopeID(unsigned Val);
683ff0cc061SDimitry Andric };
6847d523365SDimitry Andric
6857d523365SDimitry Andric /// Class to manage reading and parsing function summary index bitcode
6867d523365SDimitry Andric /// files/sections.
687d88c1a5aSDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
688d88c1a5aSDimitry Andric /// The module index built during parsing.
689d88c1a5aSDimitry Andric ModuleSummaryIndex &TheIndex;
6907d523365SDimitry Andric
6913ca95b02SDimitry Andric /// Indicates whether we have encountered a global value summary section
692d88c1a5aSDimitry Andric /// yet during parsing.
6933ca95b02SDimitry Andric bool SeenGlobalValSummary = false;
6947d523365SDimitry Andric
6953ca95b02SDimitry Andric /// Indicates whether we have already parsed the VST, used for error checking.
6963ca95b02SDimitry Andric bool SeenValueSymbolTable = false;
6973ca95b02SDimitry Andric
6983ca95b02SDimitry Andric /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
6993ca95b02SDimitry Andric /// Used to enable on-demand parsing of the VST.
7003ca95b02SDimitry Andric uint64_t VSTOffset = 0;
7013ca95b02SDimitry Andric
7020f5676f4SDimitry Andric // Map to save ValueId to ValueInfo association that was recorded in the
7033ca95b02SDimitry Andric // ValueSymbolTable. It is used after the VST is parsed to convert
7043ca95b02SDimitry Andric // call graph edges read from the function summary from referencing
7050f5676f4SDimitry Andric // callees by their ValueId to using the ValueInfo instead, which is how
7063ca95b02SDimitry Andric // they are recorded in the summary index being built.
7070f5676f4SDimitry Andric // We save a GUID which refers to the same global as the ValueInfo, but
7080f5676f4SDimitry Andric // ignoring the linkage, i.e. for values other than local linkage they are
7090f5676f4SDimitry Andric // identical.
7100f5676f4SDimitry Andric DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
7110f5676f4SDimitry Andric ValueIdToValueInfoMap;
7127d523365SDimitry Andric
7137d523365SDimitry Andric /// Map populated during module path string table parsing, from the
7147d523365SDimitry Andric /// module ID to a string reference owned by the index's module
7153ca95b02SDimitry Andric /// path string table, used to correlate with combined index
7167d523365SDimitry Andric /// summary records.
7177d523365SDimitry Andric DenseMap<uint64_t, StringRef> ModuleIdMap;
7187d523365SDimitry Andric
7193ca95b02SDimitry Andric /// Original source file name recorded in a bitcode record.
7203ca95b02SDimitry Andric std::string SourceFileName;
7213ca95b02SDimitry Andric
722f37b6182SDimitry Andric /// The string identifier given to this module by the client, normally the
723f37b6182SDimitry Andric /// path to the bitcode file.
724f37b6182SDimitry Andric StringRef ModulePath;
725f37b6182SDimitry Andric
726f37b6182SDimitry Andric /// For per-module summary indexes, the unique numerical identifier given to
727f37b6182SDimitry Andric /// this module by the client.
728f37b6182SDimitry Andric unsigned ModuleId;
729f37b6182SDimitry Andric
7307d523365SDimitry Andric public:
7316bc11b14SDimitry Andric ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
732f37b6182SDimitry Andric ModuleSummaryIndex &TheIndex,
733f37b6182SDimitry Andric StringRef ModulePath, unsigned ModuleId);
7347d523365SDimitry Andric
735f37b6182SDimitry Andric Error parseModule();
7367d523365SDimitry Andric
7377d523365SDimitry Andric private:
7386bc11b14SDimitry Andric void setValueGUID(uint64_t ValueID, StringRef ValueName,
7396bc11b14SDimitry Andric GlobalValue::LinkageTypes Linkage,
7406bc11b14SDimitry Andric StringRef SourceFileName);
741d88c1a5aSDimitry Andric Error parseValueSymbolTable(
7423ca95b02SDimitry Andric uint64_t Offset,
7433ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
744d88c1a5aSDimitry Andric std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
745d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
746d88c1a5aSDimitry Andric bool IsOldProfileFormat,
7474ba319b5SDimitry Andric bool HasProfile,
7484ba319b5SDimitry Andric bool HasRelBF);
74924d58133SDimitry Andric Error parseEntireSummary(unsigned ID);
750d88c1a5aSDimitry Andric Error parseModuleStringTable();
751d88c1a5aSDimitry Andric
7520f5676f4SDimitry Andric std::pair<ValueInfo, GlobalValue::GUID>
7530f5676f4SDimitry Andric getValueInfoFromValueId(unsigned ValueId);
754f37b6182SDimitry Andric
7554ba319b5SDimitry Andric void addThisModule();
7564ba319b5SDimitry Andric ModuleSummaryIndex::ModuleInfo *getThisModule();
7577d523365SDimitry Andric };
758d88c1a5aSDimitry Andric
7593ca95b02SDimitry Andric } // end anonymous namespace
760ff0cc061SDimitry Andric
errorToErrorCodeAndEmitErrors(LLVMContext & Ctx,Error Err)761d88c1a5aSDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
762d88c1a5aSDimitry Andric Error Err) {
763d88c1a5aSDimitry Andric if (Err) {
764d88c1a5aSDimitry Andric std::error_code EC;
765d88c1a5aSDimitry Andric handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
766d88c1a5aSDimitry Andric EC = EIB.convertToErrorCode();
767d88c1a5aSDimitry Andric Ctx.emitError(EIB.message());
768d88c1a5aSDimitry Andric });
76939d628a0SDimitry Andric return EC;
770dff0c46cSDimitry Andric }
77139d628a0SDimitry Andric return std::error_code();
772d88c1a5aSDimitry Andric }
773d88c1a5aSDimitry Andric
BitcodeReader(BitstreamCursor Stream,StringRef Strtab,StringRef ProducerIdentification,LLVMContext & Context)7746bc11b14SDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
775d88c1a5aSDimitry Andric StringRef ProducerIdentification,
776d88c1a5aSDimitry Andric LLVMContext &Context)
7776bc11b14SDimitry Andric : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
778d88c1a5aSDimitry Andric ValueList(Context) {
779d88c1a5aSDimitry Andric this->ProducerIdentification = ProducerIdentification;
780d88c1a5aSDimitry Andric }
781d88c1a5aSDimitry Andric
materializeForwardReferencedFunctions()782d88c1a5aSDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() {
783d88c1a5aSDimitry Andric if (WillMaterializeAllForwardRefs)
784d88c1a5aSDimitry Andric return Error::success();
78539d628a0SDimitry Andric
78639d628a0SDimitry Andric // Prevent recursion.
78739d628a0SDimitry Andric WillMaterializeAllForwardRefs = true;
78839d628a0SDimitry Andric
78939d628a0SDimitry Andric while (!BasicBlockFwdRefQueue.empty()) {
79039d628a0SDimitry Andric Function *F = BasicBlockFwdRefQueue.front();
79139d628a0SDimitry Andric BasicBlockFwdRefQueue.pop_front();
79239d628a0SDimitry Andric assert(F && "Expected valid function");
79339d628a0SDimitry Andric if (!BasicBlockFwdRefs.count(F))
79439d628a0SDimitry Andric // Already materialized.
79539d628a0SDimitry Andric continue;
79639d628a0SDimitry Andric
79739d628a0SDimitry Andric // Check for a function that isn't materializable to prevent an infinite
79839d628a0SDimitry Andric // loop. When parsing a blockaddress stored in a global variable, there
79939d628a0SDimitry Andric // isn't a trivial way to check if a function will have a body without a
80039d628a0SDimitry Andric // linear search through FunctionsWithBodies, so just check it here.
80139d628a0SDimitry Andric if (!F->isMaterializable())
8028f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress");
80339d628a0SDimitry Andric
80439d628a0SDimitry Andric // Try to materialize F.
805d88c1a5aSDimitry Andric if (Error Err = materialize(F))
806d88c1a5aSDimitry Andric return Err;
80739d628a0SDimitry Andric }
80839d628a0SDimitry Andric assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
80939d628a0SDimitry Andric
81039d628a0SDimitry Andric // Reset state.
81139d628a0SDimitry Andric WillMaterializeAllForwardRefs = false;
812d88c1a5aSDimitry Andric return Error::success();
813f22ef01cSRoman Divacky }
814f22ef01cSRoman Divacky
815f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
816f22ef01cSRoman Divacky // Helper functions to implement forward reference resolution, etc.
817f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
818f22ef01cSRoman Divacky
hasImplicitComdat(size_t Val)819ff0cc061SDimitry Andric static bool hasImplicitComdat(size_t Val) {
820ff0cc061SDimitry Andric switch (Val) {
821ff0cc061SDimitry Andric default:
822ff0cc061SDimitry Andric return false;
823ff0cc061SDimitry Andric case 1: // Old WeakAnyLinkage
824ff0cc061SDimitry Andric case 4: // Old LinkOnceAnyLinkage
825ff0cc061SDimitry Andric case 10: // Old WeakODRLinkage
826ff0cc061SDimitry Andric case 11: // Old LinkOnceODRLinkage
827ff0cc061SDimitry Andric return true;
828ff0cc061SDimitry Andric }
829ff0cc061SDimitry Andric }
830ff0cc061SDimitry Andric
getDecodedLinkage(unsigned Val)83139d628a0SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
832f22ef01cSRoman Divacky switch (Val) {
833f22ef01cSRoman Divacky default: // Map unknown/new linkages to external
83439d628a0SDimitry Andric case 0:
83539d628a0SDimitry Andric return GlobalValue::ExternalLinkage;
83639d628a0SDimitry Andric case 2:
83739d628a0SDimitry Andric return GlobalValue::AppendingLinkage;
83839d628a0SDimitry Andric case 3:
83939d628a0SDimitry Andric return GlobalValue::InternalLinkage;
84039d628a0SDimitry Andric case 5:
84139d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
84239d628a0SDimitry Andric case 6:
84339d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
84439d628a0SDimitry Andric case 7:
84539d628a0SDimitry Andric return GlobalValue::ExternalWeakLinkage;
84639d628a0SDimitry Andric case 8:
84739d628a0SDimitry Andric return GlobalValue::CommonLinkage;
84839d628a0SDimitry Andric case 9:
84939d628a0SDimitry Andric return GlobalValue::PrivateLinkage;
85039d628a0SDimitry Andric case 12:
85139d628a0SDimitry Andric return GlobalValue::AvailableExternallyLinkage;
85291bc56edSDimitry Andric case 13:
85391bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
85491bc56edSDimitry Andric case 14:
85591bc56edSDimitry Andric return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
85639d628a0SDimitry Andric case 15:
85739d628a0SDimitry Andric return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
858ff0cc061SDimitry Andric case 1: // Old value with implicit comdat.
859ff0cc061SDimitry Andric case 16:
860ff0cc061SDimitry Andric return GlobalValue::WeakAnyLinkage;
861ff0cc061SDimitry Andric case 10: // Old value with implicit comdat.
862ff0cc061SDimitry Andric case 17:
863ff0cc061SDimitry Andric return GlobalValue::WeakODRLinkage;
864ff0cc061SDimitry Andric case 4: // Old value with implicit comdat.
865ff0cc061SDimitry Andric case 18:
866ff0cc061SDimitry Andric return GlobalValue::LinkOnceAnyLinkage;
867ff0cc061SDimitry Andric case 11: // Old value with implicit comdat.
868ff0cc061SDimitry Andric case 19:
869ff0cc061SDimitry Andric return GlobalValue::LinkOnceODRLinkage;
870f22ef01cSRoman Divacky }
871f22ef01cSRoman Divacky }
872f22ef01cSRoman Divacky
getDecodedFFlags(uint64_t RawFlags)8732cab237bSDimitry Andric static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
8742cab237bSDimitry Andric FunctionSummary::FFlags Flags;
8752cab237bSDimitry Andric Flags.ReadNone = RawFlags & 0x1;
8762cab237bSDimitry Andric Flags.ReadOnly = (RawFlags >> 1) & 0x1;
8772cab237bSDimitry Andric Flags.NoRecurse = (RawFlags >> 2) & 0x1;
8782cab237bSDimitry Andric Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
879*b5893f02SDimitry Andric Flags.NoInline = (RawFlags >> 4) & 0x1;
8802cab237bSDimitry Andric return Flags;
8812cab237bSDimitry Andric }
8822cab237bSDimitry Andric
883d88c1a5aSDimitry Andric /// Decode the flags for GlobalValue in the summary.
getDecodedGVSummaryFlags(uint64_t RawFlags,uint64_t Version)8843ca95b02SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
8853ca95b02SDimitry Andric uint64_t Version) {
8863ca95b02SDimitry Andric // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
8873ca95b02SDimitry Andric // like getDecodedLinkage() above. Any future change to the linkage enum and
8883ca95b02SDimitry Andric // to getDecodedLinkage() will need to be taken into account here as above.
8893ca95b02SDimitry Andric auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
8903ca95b02SDimitry Andric RawFlags = RawFlags >> 4;
89195ec533aSDimitry Andric bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
8926d97bb29SDimitry Andric // The Live flag wasn't introduced until version 3. For dead stripping
89395ec533aSDimitry Andric // to work correctly on earlier versions, we must conservatively treat all
89495ec533aSDimitry Andric // values as live.
8956d97bb29SDimitry Andric bool Live = (RawFlags & 0x2) || Version < 3;
8962cab237bSDimitry Andric bool Local = (RawFlags & 0x4);
8972cab237bSDimitry Andric
8982cab237bSDimitry Andric return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local);
8993ca95b02SDimitry Andric }
9003ca95b02SDimitry Andric
901*b5893f02SDimitry Andric // Decode the flags for GlobalVariable in the summary
getDecodedGVarFlags(uint64_t RawFlags)902*b5893f02SDimitry Andric static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
903*b5893f02SDimitry Andric return GlobalVarSummary::GVarFlags((RawFlags & 0x1) ? true : false);
904*b5893f02SDimitry Andric }
905*b5893f02SDimitry Andric
getDecodedVisibility(unsigned Val)9068f0fd8f6SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
907f22ef01cSRoman Divacky switch (Val) {
908f22ef01cSRoman Divacky default: // Map unknown visibilities to default.
909f22ef01cSRoman Divacky case 0: return GlobalValue::DefaultVisibility;
910f22ef01cSRoman Divacky case 1: return GlobalValue::HiddenVisibility;
911f22ef01cSRoman Divacky case 2: return GlobalValue::ProtectedVisibility;
912f22ef01cSRoman Divacky }
913f22ef01cSRoman Divacky }
914f22ef01cSRoman Divacky
91591bc56edSDimitry Andric static GlobalValue::DLLStorageClassTypes
getDecodedDLLStorageClass(unsigned Val)9168f0fd8f6SDimitry Andric getDecodedDLLStorageClass(unsigned Val) {
91791bc56edSDimitry Andric switch (Val) {
91891bc56edSDimitry Andric default: // Map unknown values to default.
91991bc56edSDimitry Andric case 0: return GlobalValue::DefaultStorageClass;
92091bc56edSDimitry Andric case 1: return GlobalValue::DLLImportStorageClass;
92191bc56edSDimitry Andric case 2: return GlobalValue::DLLExportStorageClass;
92291bc56edSDimitry Andric }
92391bc56edSDimitry Andric }
92491bc56edSDimitry Andric
getDecodedDSOLocal(unsigned Val)9252cab237bSDimitry Andric static bool getDecodedDSOLocal(unsigned Val) {
9262cab237bSDimitry Andric switch(Val) {
9272cab237bSDimitry Andric default: // Map unknown values to preemptable.
9282cab237bSDimitry Andric case 0: return false;
9292cab237bSDimitry Andric case 1: return true;
9302cab237bSDimitry Andric }
9312cab237bSDimitry Andric }
9322cab237bSDimitry Andric
getDecodedThreadLocalMode(unsigned Val)9338f0fd8f6SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
9347ae0e2c9SDimitry Andric switch (Val) {
9357ae0e2c9SDimitry Andric case 0: return GlobalVariable::NotThreadLocal;
9367ae0e2c9SDimitry Andric default: // Map unknown non-zero value to general dynamic.
9377ae0e2c9SDimitry Andric case 1: return GlobalVariable::GeneralDynamicTLSModel;
9387ae0e2c9SDimitry Andric case 2: return GlobalVariable::LocalDynamicTLSModel;
9397ae0e2c9SDimitry Andric case 3: return GlobalVariable::InitialExecTLSModel;
9407ae0e2c9SDimitry Andric case 4: return GlobalVariable::LocalExecTLSModel;
9417ae0e2c9SDimitry Andric }
9427ae0e2c9SDimitry Andric }
9437ae0e2c9SDimitry Andric
getDecodedUnnamedAddrType(unsigned Val)9443ca95b02SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
9453ca95b02SDimitry Andric switch (Val) {
9463ca95b02SDimitry Andric default: // Map unknown to UnnamedAddr::None.
9473ca95b02SDimitry Andric case 0: return GlobalVariable::UnnamedAddr::None;
9483ca95b02SDimitry Andric case 1: return GlobalVariable::UnnamedAddr::Global;
9493ca95b02SDimitry Andric case 2: return GlobalVariable::UnnamedAddr::Local;
9503ca95b02SDimitry Andric }
9513ca95b02SDimitry Andric }
9523ca95b02SDimitry Andric
getDecodedCastOpcode(unsigned Val)9538f0fd8f6SDimitry Andric static int getDecodedCastOpcode(unsigned Val) {
954f22ef01cSRoman Divacky switch (Val) {
955f22ef01cSRoman Divacky default: return -1;
956f22ef01cSRoman Divacky case bitc::CAST_TRUNC : return Instruction::Trunc;
957f22ef01cSRoman Divacky case bitc::CAST_ZEXT : return Instruction::ZExt;
958f22ef01cSRoman Divacky case bitc::CAST_SEXT : return Instruction::SExt;
959f22ef01cSRoman Divacky case bitc::CAST_FPTOUI : return Instruction::FPToUI;
960f22ef01cSRoman Divacky case bitc::CAST_FPTOSI : return Instruction::FPToSI;
961f22ef01cSRoman Divacky case bitc::CAST_UITOFP : return Instruction::UIToFP;
962f22ef01cSRoman Divacky case bitc::CAST_SITOFP : return Instruction::SIToFP;
963f22ef01cSRoman Divacky case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
964f22ef01cSRoman Divacky case bitc::CAST_FPEXT : return Instruction::FPExt;
965f22ef01cSRoman Divacky case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
966f22ef01cSRoman Divacky case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
967f22ef01cSRoman Divacky case bitc::CAST_BITCAST : return Instruction::BitCast;
968f785676fSDimitry Andric case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
969f22ef01cSRoman Divacky }
970f22ef01cSRoman Divacky }
971ff0cc061SDimitry Andric
getDecodedUnaryOpcode(unsigned Val,Type * Ty)972*b5893f02SDimitry Andric static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
973*b5893f02SDimitry Andric bool IsFP = Ty->isFPOrFPVectorTy();
974*b5893f02SDimitry Andric // UnOps are only valid for int/fp or vector of int/fp types
975*b5893f02SDimitry Andric if (!IsFP && !Ty->isIntOrIntVectorTy())
976*b5893f02SDimitry Andric return -1;
977*b5893f02SDimitry Andric
978*b5893f02SDimitry Andric switch (Val) {
979*b5893f02SDimitry Andric default:
980*b5893f02SDimitry Andric return -1;
981*b5893f02SDimitry Andric case bitc::UNOP_NEG:
982*b5893f02SDimitry Andric return IsFP ? Instruction::FNeg : -1;
983*b5893f02SDimitry Andric }
984*b5893f02SDimitry Andric }
985*b5893f02SDimitry Andric
getDecodedBinaryOpcode(unsigned Val,Type * Ty)9868f0fd8f6SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
987ff0cc061SDimitry Andric bool IsFP = Ty->isFPOrFPVectorTy();
988ff0cc061SDimitry Andric // BinOps are only valid for int/fp or vector of int/fp types
989ff0cc061SDimitry Andric if (!IsFP && !Ty->isIntOrIntVectorTy())
990ff0cc061SDimitry Andric return -1;
991ff0cc061SDimitry Andric
992f22ef01cSRoman Divacky switch (Val) {
993ff0cc061SDimitry Andric default:
994ff0cc061SDimitry Andric return -1;
995f22ef01cSRoman Divacky case bitc::BINOP_ADD:
996ff0cc061SDimitry Andric return IsFP ? Instruction::FAdd : Instruction::Add;
997f22ef01cSRoman Divacky case bitc::BINOP_SUB:
998ff0cc061SDimitry Andric return IsFP ? Instruction::FSub : Instruction::Sub;
999f22ef01cSRoman Divacky case bitc::BINOP_MUL:
1000ff0cc061SDimitry Andric return IsFP ? Instruction::FMul : Instruction::Mul;
1001ff0cc061SDimitry Andric case bitc::BINOP_UDIV:
1002ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::UDiv;
1003f22ef01cSRoman Divacky case bitc::BINOP_SDIV:
1004ff0cc061SDimitry Andric return IsFP ? Instruction::FDiv : Instruction::SDiv;
1005ff0cc061SDimitry Andric case bitc::BINOP_UREM:
1006ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::URem;
1007f22ef01cSRoman Divacky case bitc::BINOP_SREM:
1008ff0cc061SDimitry Andric return IsFP ? Instruction::FRem : Instruction::SRem;
1009ff0cc061SDimitry Andric case bitc::BINOP_SHL:
1010ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Shl;
1011ff0cc061SDimitry Andric case bitc::BINOP_LSHR:
1012ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::LShr;
1013ff0cc061SDimitry Andric case bitc::BINOP_ASHR:
1014ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::AShr;
1015ff0cc061SDimitry Andric case bitc::BINOP_AND:
1016ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::And;
1017ff0cc061SDimitry Andric case bitc::BINOP_OR:
1018ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Or;
1019ff0cc061SDimitry Andric case bitc::BINOP_XOR:
1020ff0cc061SDimitry Andric return IsFP ? -1 : Instruction::Xor;
1021f22ef01cSRoman Divacky }
1022f22ef01cSRoman Divacky }
1023f22ef01cSRoman Divacky
getDecodedRMWOperation(unsigned Val)10248f0fd8f6SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
10256122f3e6SDimitry Andric switch (Val) {
10266122f3e6SDimitry Andric default: return AtomicRMWInst::BAD_BINOP;
10276122f3e6SDimitry Andric case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
10286122f3e6SDimitry Andric case bitc::RMW_ADD: return AtomicRMWInst::Add;
10296122f3e6SDimitry Andric case bitc::RMW_SUB: return AtomicRMWInst::Sub;
10306122f3e6SDimitry Andric case bitc::RMW_AND: return AtomicRMWInst::And;
10316122f3e6SDimitry Andric case bitc::RMW_NAND: return AtomicRMWInst::Nand;
10326122f3e6SDimitry Andric case bitc::RMW_OR: return AtomicRMWInst::Or;
10336122f3e6SDimitry Andric case bitc::RMW_XOR: return AtomicRMWInst::Xor;
10346122f3e6SDimitry Andric case bitc::RMW_MAX: return AtomicRMWInst::Max;
10356122f3e6SDimitry Andric case bitc::RMW_MIN: return AtomicRMWInst::Min;
10366122f3e6SDimitry Andric case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
10376122f3e6SDimitry Andric case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
10386122f3e6SDimitry Andric }
10396122f3e6SDimitry Andric }
10406122f3e6SDimitry Andric
getDecodedOrdering(unsigned Val)10418f0fd8f6SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) {
10426122f3e6SDimitry Andric switch (Val) {
10433ca95b02SDimitry Andric case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
10443ca95b02SDimitry Andric case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
10453ca95b02SDimitry Andric case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
10463ca95b02SDimitry Andric case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
10473ca95b02SDimitry Andric case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
10483ca95b02SDimitry Andric case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
10496122f3e6SDimitry Andric default: // Map unknown orderings to sequentially-consistent.
10503ca95b02SDimitry Andric case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
10516122f3e6SDimitry Andric }
10526122f3e6SDimitry Andric }
10536122f3e6SDimitry Andric
getDecodedComdatSelectionKind(unsigned Val)105491bc56edSDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
105591bc56edSDimitry Andric switch (Val) {
105691bc56edSDimitry Andric default: // Map unknown selection kinds to any.
105791bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_ANY:
105891bc56edSDimitry Andric return Comdat::Any;
105991bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
106091bc56edSDimitry Andric return Comdat::ExactMatch;
106191bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_LARGEST:
106291bc56edSDimitry Andric return Comdat::Largest;
106391bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
106491bc56edSDimitry Andric return Comdat::NoDuplicates;
106591bc56edSDimitry Andric case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
106691bc56edSDimitry Andric return Comdat::SameSize;
106791bc56edSDimitry Andric }
106891bc56edSDimitry Andric }
106991bc56edSDimitry Andric
getDecodedFastMathFlags(unsigned Val)1070875ed548SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1071875ed548SDimitry Andric FastMathFlags FMF;
10724f8786afSDimitry Andric if (0 != (Val & bitc::UnsafeAlgebra))
10734f8786afSDimitry Andric FMF.setFast();
10744f8786afSDimitry Andric if (0 != (Val & bitc::AllowReassoc))
10752cab237bSDimitry Andric FMF.setAllowReassoc();
10764f8786afSDimitry Andric if (0 != (Val & bitc::NoNaNs))
1077875ed548SDimitry Andric FMF.setNoNaNs();
10784f8786afSDimitry Andric if (0 != (Val & bitc::NoInfs))
1079875ed548SDimitry Andric FMF.setNoInfs();
10804f8786afSDimitry Andric if (0 != (Val & bitc::NoSignedZeros))
1081875ed548SDimitry Andric FMF.setNoSignedZeros();
10824f8786afSDimitry Andric if (0 != (Val & bitc::AllowReciprocal))
1083875ed548SDimitry Andric FMF.setAllowReciprocal();
10844f8786afSDimitry Andric if (0 != (Val & bitc::AllowContract))
10857a7e6055SDimitry Andric FMF.setAllowContract(true);
10864f8786afSDimitry Andric if (0 != (Val & bitc::ApproxFunc))
10872cab237bSDimitry Andric FMF.setApproxFunc();
1088875ed548SDimitry Andric return FMF;
1089875ed548SDimitry Andric }
1090875ed548SDimitry Andric
upgradeDLLImportExportLinkage(GlobalValue * GV,unsigned Val)1091d88c1a5aSDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
109291bc56edSDimitry Andric switch (Val) {
109391bc56edSDimitry Andric case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
109491bc56edSDimitry Andric case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
109591bc56edSDimitry Andric }
109691bc56edSDimitry Andric }
109791bc56edSDimitry Andric
getTypeByID(unsigned ID)109817a519f9SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) {
109917a519f9SDimitry Andric // The type table size is always specified correctly.
110017a519f9SDimitry Andric if (ID >= TypeList.size())
110191bc56edSDimitry Andric return nullptr;
1102f22ef01cSRoman Divacky
110317a519f9SDimitry Andric if (Type *Ty = TypeList[ID])
110417a519f9SDimitry Andric return Ty;
110517a519f9SDimitry Andric
110617a519f9SDimitry Andric // If we have a forward reference, the only possible case is when it is to a
110717a519f9SDimitry Andric // named struct. Just create a placeholder for now.
110839d628a0SDimitry Andric return TypeList[ID] = createIdentifiedStructType(Context);
110939d628a0SDimitry Andric }
111039d628a0SDimitry Andric
createIdentifiedStructType(LLVMContext & Context,StringRef Name)111139d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
111239d628a0SDimitry Andric StringRef Name) {
111339d628a0SDimitry Andric auto *Ret = StructType::create(Context, Name);
111439d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret);
111539d628a0SDimitry Andric return Ret;
111639d628a0SDimitry Andric }
111739d628a0SDimitry Andric
createIdentifiedStructType(LLVMContext & Context)111839d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
111939d628a0SDimitry Andric auto *Ret = StructType::create(Context);
112039d628a0SDimitry Andric IdentifiedStructTypes.push_back(Ret);
112139d628a0SDimitry Andric return Ret;
1122f22ef01cSRoman Divacky }
1123f22ef01cSRoman Divacky
1124f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1125f22ef01cSRoman Divacky // Functions for parsing blocks from the bitcode file
1126f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1127f22ef01cSRoman Divacky
getRawAttributeMask(Attribute::AttrKind Val)1128d88c1a5aSDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1129d88c1a5aSDimitry Andric switch (Val) {
1130d88c1a5aSDimitry Andric case Attribute::EndAttrKinds:
1131d88c1a5aSDimitry Andric llvm_unreachable("Synthetic enumerators which should never get here");
1132d88c1a5aSDimitry Andric
1133d88c1a5aSDimitry Andric case Attribute::None: return 0;
1134d88c1a5aSDimitry Andric case Attribute::ZExt: return 1 << 0;
1135d88c1a5aSDimitry Andric case Attribute::SExt: return 1 << 1;
1136d88c1a5aSDimitry Andric case Attribute::NoReturn: return 1 << 2;
1137d88c1a5aSDimitry Andric case Attribute::InReg: return 1 << 3;
1138d88c1a5aSDimitry Andric case Attribute::StructRet: return 1 << 4;
1139d88c1a5aSDimitry Andric case Attribute::NoUnwind: return 1 << 5;
1140d88c1a5aSDimitry Andric case Attribute::NoAlias: return 1 << 6;
1141d88c1a5aSDimitry Andric case Attribute::ByVal: return 1 << 7;
1142d88c1a5aSDimitry Andric case Attribute::Nest: return 1 << 8;
1143d88c1a5aSDimitry Andric case Attribute::ReadNone: return 1 << 9;
1144d88c1a5aSDimitry Andric case Attribute::ReadOnly: return 1 << 10;
1145d88c1a5aSDimitry Andric case Attribute::NoInline: return 1 << 11;
1146d88c1a5aSDimitry Andric case Attribute::AlwaysInline: return 1 << 12;
1147d88c1a5aSDimitry Andric case Attribute::OptimizeForSize: return 1 << 13;
1148d88c1a5aSDimitry Andric case Attribute::StackProtect: return 1 << 14;
1149d88c1a5aSDimitry Andric case Attribute::StackProtectReq: return 1 << 15;
1150d88c1a5aSDimitry Andric case Attribute::Alignment: return 31 << 16;
1151d88c1a5aSDimitry Andric case Attribute::NoCapture: return 1 << 21;
1152d88c1a5aSDimitry Andric case Attribute::NoRedZone: return 1 << 22;
1153d88c1a5aSDimitry Andric case Attribute::NoImplicitFloat: return 1 << 23;
1154d88c1a5aSDimitry Andric case Attribute::Naked: return 1 << 24;
1155d88c1a5aSDimitry Andric case Attribute::InlineHint: return 1 << 25;
1156d88c1a5aSDimitry Andric case Attribute::StackAlignment: return 7 << 26;
1157d88c1a5aSDimitry Andric case Attribute::ReturnsTwice: return 1 << 29;
1158d88c1a5aSDimitry Andric case Attribute::UWTable: return 1 << 30;
1159d88c1a5aSDimitry Andric case Attribute::NonLazyBind: return 1U << 31;
1160d88c1a5aSDimitry Andric case Attribute::SanitizeAddress: return 1ULL << 32;
1161d88c1a5aSDimitry Andric case Attribute::MinSize: return 1ULL << 33;
1162d88c1a5aSDimitry Andric case Attribute::NoDuplicate: return 1ULL << 34;
1163d88c1a5aSDimitry Andric case Attribute::StackProtectStrong: return 1ULL << 35;
1164d88c1a5aSDimitry Andric case Attribute::SanitizeThread: return 1ULL << 36;
1165d88c1a5aSDimitry Andric case Attribute::SanitizeMemory: return 1ULL << 37;
1166d88c1a5aSDimitry Andric case Attribute::NoBuiltin: return 1ULL << 38;
1167d88c1a5aSDimitry Andric case Attribute::Returned: return 1ULL << 39;
1168d88c1a5aSDimitry Andric case Attribute::Cold: return 1ULL << 40;
1169d88c1a5aSDimitry Andric case Attribute::Builtin: return 1ULL << 41;
1170d88c1a5aSDimitry Andric case Attribute::OptimizeNone: return 1ULL << 42;
1171d88c1a5aSDimitry Andric case Attribute::InAlloca: return 1ULL << 43;
1172d88c1a5aSDimitry Andric case Attribute::NonNull: return 1ULL << 44;
1173d88c1a5aSDimitry Andric case Attribute::JumpTable: return 1ULL << 45;
1174d88c1a5aSDimitry Andric case Attribute::Convergent: return 1ULL << 46;
1175d88c1a5aSDimitry Andric case Attribute::SafeStack: return 1ULL << 47;
1176d88c1a5aSDimitry Andric case Attribute::NoRecurse: return 1ULL << 48;
1177d88c1a5aSDimitry Andric case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1178d88c1a5aSDimitry Andric case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1179d88c1a5aSDimitry Andric case Attribute::SwiftSelf: return 1ULL << 51;
1180d88c1a5aSDimitry Andric case Attribute::SwiftError: return 1ULL << 52;
1181d88c1a5aSDimitry Andric case Attribute::WriteOnly: return 1ULL << 53;
1182f37b6182SDimitry Andric case Attribute::Speculatable: return 1ULL << 54;
11832cab237bSDimitry Andric case Attribute::StrictFP: return 1ULL << 55;
11842cab237bSDimitry Andric case Attribute::SanitizeHWAddress: return 1ULL << 56;
11854ba319b5SDimitry Andric case Attribute::NoCfCheck: return 1ULL << 57;
11864ba319b5SDimitry Andric case Attribute::OptForFuzzing: return 1ULL << 58;
11874ba319b5SDimitry Andric case Attribute::ShadowCallStack: return 1ULL << 59;
1188*b5893f02SDimitry Andric case Attribute::SpeculativeLoadHardening:
1189*b5893f02SDimitry Andric return 1ULL << 60;
1190d88c1a5aSDimitry Andric case Attribute::Dereferenceable:
1191d88c1a5aSDimitry Andric llvm_unreachable("dereferenceable attribute not supported in raw format");
1192d88c1a5aSDimitry Andric break;
1193d88c1a5aSDimitry Andric case Attribute::DereferenceableOrNull:
1194d88c1a5aSDimitry Andric llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1195d88c1a5aSDimitry Andric "format");
1196d88c1a5aSDimitry Andric break;
1197d88c1a5aSDimitry Andric case Attribute::ArgMemOnly:
1198d88c1a5aSDimitry Andric llvm_unreachable("argmemonly attribute not supported in raw format");
1199d88c1a5aSDimitry Andric break;
1200d88c1a5aSDimitry Andric case Attribute::AllocSize:
1201d88c1a5aSDimitry Andric llvm_unreachable("allocsize not supported in raw format");
1202d88c1a5aSDimitry Andric break;
1203d88c1a5aSDimitry Andric }
1204d88c1a5aSDimitry Andric llvm_unreachable("Unsupported attribute type");
1205d88c1a5aSDimitry Andric }
1206d88c1a5aSDimitry Andric
addRawAttributeValue(AttrBuilder & B,uint64_t Val)1207d88c1a5aSDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1208d88c1a5aSDimitry Andric if (!Val) return;
1209d88c1a5aSDimitry Andric
1210d88c1a5aSDimitry Andric for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1211d88c1a5aSDimitry Andric I = Attribute::AttrKind(I + 1)) {
1212d88c1a5aSDimitry Andric if (I == Attribute::Dereferenceable ||
1213d88c1a5aSDimitry Andric I == Attribute::DereferenceableOrNull ||
1214d88c1a5aSDimitry Andric I == Attribute::ArgMemOnly ||
1215d88c1a5aSDimitry Andric I == Attribute::AllocSize)
1216d88c1a5aSDimitry Andric continue;
1217d88c1a5aSDimitry Andric if (uint64_t A = (Val & getRawAttributeMask(I))) {
1218d88c1a5aSDimitry Andric if (I == Attribute::Alignment)
1219d88c1a5aSDimitry Andric B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1220d88c1a5aSDimitry Andric else if (I == Attribute::StackAlignment)
1221d88c1a5aSDimitry Andric B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1222d88c1a5aSDimitry Andric else
1223d88c1a5aSDimitry Andric B.addAttribute(I);
1224d88c1a5aSDimitry Andric }
1225d88c1a5aSDimitry Andric }
1226d88c1a5aSDimitry Andric }
1227139f7f9bSDimitry Andric
12284ba319b5SDimitry Andric /// This fills an AttrBuilder object with the LLVM attributes that have
1229139f7f9bSDimitry Andric /// been decoded from the given integer. This function must stay in sync with
1230139f7f9bSDimitry Andric /// 'encodeLLVMAttributesForBitcode'.
decodeLLVMAttributesForBitcode(AttrBuilder & B,uint64_t EncodedAttrs)1231139f7f9bSDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1232139f7f9bSDimitry Andric uint64_t EncodedAttrs) {
1233139f7f9bSDimitry Andric // FIXME: Remove in 4.0.
1234139f7f9bSDimitry Andric
1235139f7f9bSDimitry Andric // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1236139f7f9bSDimitry Andric // the bits above 31 down by 11 bits.
1237139f7f9bSDimitry Andric unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1238139f7f9bSDimitry Andric assert((!Alignment || isPowerOf2_32(Alignment)) &&
1239139f7f9bSDimitry Andric "Alignment must be a power of two.");
1240139f7f9bSDimitry Andric
1241139f7f9bSDimitry Andric if (Alignment)
1242139f7f9bSDimitry Andric B.addAlignmentAttr(Alignment);
1243d88c1a5aSDimitry Andric addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1244139f7f9bSDimitry Andric (EncodedAttrs & 0xffff));
1245139f7f9bSDimitry Andric }
1246139f7f9bSDimitry Andric
parseAttributeBlock()1247d88c1a5aSDimitry Andric Error BitcodeReader::parseAttributeBlock() {
1248f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
12498f0fd8f6SDimitry Andric return error("Invalid record");
1250f22ef01cSRoman Divacky
1251f22ef01cSRoman Divacky if (!MAttributes.empty())
12528f0fd8f6SDimitry Andric return error("Invalid multiple blocks");
1253f22ef01cSRoman Divacky
1254f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record;
1255f22ef01cSRoman Divacky
12567a7e6055SDimitry Andric SmallVector<AttributeList, 8> Attrs;
1257f22ef01cSRoman Divacky
1258f22ef01cSRoman Divacky // Read all the records.
1259d88c1a5aSDimitry Andric while (true) {
1260139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1261139f7f9bSDimitry Andric
1262139f7f9bSDimitry Andric switch (Entry.Kind) {
1263139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
1264139f7f9bSDimitry Andric case BitstreamEntry::Error:
12658f0fd8f6SDimitry Andric return error("Malformed block");
1266139f7f9bSDimitry Andric case BitstreamEntry::EndBlock:
1267d88c1a5aSDimitry Andric return Error::success();
1268139f7f9bSDimitry Andric case BitstreamEntry::Record:
1269139f7f9bSDimitry Andric // The interesting case.
1270139f7f9bSDimitry Andric break;
1271f22ef01cSRoman Divacky }
1272f22ef01cSRoman Divacky
1273f22ef01cSRoman Divacky // Read a record.
1274f22ef01cSRoman Divacky Record.clear();
1275139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) {
1276f22ef01cSRoman Divacky default: // Default behavior: ignore.
1277f22ef01cSRoman Divacky break;
12782cab237bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1279139f7f9bSDimitry Andric // FIXME: Remove in 4.0.
1280f22ef01cSRoman Divacky if (Record.size() & 1)
12818f0fd8f6SDimitry Andric return error("Invalid record");
1282f22ef01cSRoman Divacky
1283f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1284139f7f9bSDimitry Andric AttrBuilder B;
1285139f7f9bSDimitry Andric decodeLLVMAttributesForBitcode(B, Record[i+1]);
12867a7e6055SDimitry Andric Attrs.push_back(AttributeList::get(Context, Record[i], B));
1287f22ef01cSRoman Divacky }
1288f22ef01cSRoman Divacky
12897a7e6055SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs));
1290f22ef01cSRoman Divacky Attrs.clear();
1291f22ef01cSRoman Divacky break;
12922cab237bSDimitry Andric case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1293139f7f9bSDimitry Andric for (unsigned i = 0, e = Record.size(); i != e; ++i)
1294139f7f9bSDimitry Andric Attrs.push_back(MAttributeGroups[Record[i]]);
1295139f7f9bSDimitry Andric
12967a7e6055SDimitry Andric MAttributes.push_back(AttributeList::get(Context, Attrs));
1297139f7f9bSDimitry Andric Attrs.clear();
1298139f7f9bSDimitry Andric break;
1299139f7f9bSDimitry Andric }
1300139f7f9bSDimitry Andric }
1301139f7f9bSDimitry Andric }
1302139f7f9bSDimitry Andric
1303f785676fSDimitry Andric // Returns Attribute::None on unrecognized codes.
getAttrFromCode(uint64_t Code)13048f0fd8f6SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1305f785676fSDimitry Andric switch (Code) {
1306f785676fSDimitry Andric default:
1307f785676fSDimitry Andric return Attribute::None;
1308f785676fSDimitry Andric case bitc::ATTR_KIND_ALIGNMENT:
1309f785676fSDimitry Andric return Attribute::Alignment;
1310f785676fSDimitry Andric case bitc::ATTR_KIND_ALWAYS_INLINE:
1311f785676fSDimitry Andric return Attribute::AlwaysInline;
1312875ed548SDimitry Andric case bitc::ATTR_KIND_ARGMEMONLY:
1313875ed548SDimitry Andric return Attribute::ArgMemOnly;
1314f785676fSDimitry Andric case bitc::ATTR_KIND_BUILTIN:
1315f785676fSDimitry Andric return Attribute::Builtin;
1316f785676fSDimitry Andric case bitc::ATTR_KIND_BY_VAL:
1317f785676fSDimitry Andric return Attribute::ByVal;
131891bc56edSDimitry Andric case bitc::ATTR_KIND_IN_ALLOCA:
131991bc56edSDimitry Andric return Attribute::InAlloca;
1320f785676fSDimitry Andric case bitc::ATTR_KIND_COLD:
1321f785676fSDimitry Andric return Attribute::Cold;
1322ff0cc061SDimitry Andric case bitc::ATTR_KIND_CONVERGENT:
1323ff0cc061SDimitry Andric return Attribute::Convergent;
13247d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
13257d523365SDimitry Andric return Attribute::InaccessibleMemOnly;
13267d523365SDimitry Andric case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
13277d523365SDimitry Andric return Attribute::InaccessibleMemOrArgMemOnly;
1328f785676fSDimitry Andric case bitc::ATTR_KIND_INLINE_HINT:
1329f785676fSDimitry Andric return Attribute::InlineHint;
1330f785676fSDimitry Andric case bitc::ATTR_KIND_IN_REG:
1331f785676fSDimitry Andric return Attribute::InReg;
133291bc56edSDimitry Andric case bitc::ATTR_KIND_JUMP_TABLE:
133391bc56edSDimitry Andric return Attribute::JumpTable;
1334f785676fSDimitry Andric case bitc::ATTR_KIND_MIN_SIZE:
1335f785676fSDimitry Andric return Attribute::MinSize;
1336f785676fSDimitry Andric case bitc::ATTR_KIND_NAKED:
1337f785676fSDimitry Andric return Attribute::Naked;
1338f785676fSDimitry Andric case bitc::ATTR_KIND_NEST:
1339f785676fSDimitry Andric return Attribute::Nest;
1340f785676fSDimitry Andric case bitc::ATTR_KIND_NO_ALIAS:
1341f785676fSDimitry Andric return Attribute::NoAlias;
1342f785676fSDimitry Andric case bitc::ATTR_KIND_NO_BUILTIN:
1343f785676fSDimitry Andric return Attribute::NoBuiltin;
1344f785676fSDimitry Andric case bitc::ATTR_KIND_NO_CAPTURE:
1345f785676fSDimitry Andric return Attribute::NoCapture;
1346f785676fSDimitry Andric case bitc::ATTR_KIND_NO_DUPLICATE:
1347f785676fSDimitry Andric return Attribute::NoDuplicate;
1348f785676fSDimitry Andric case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1349f785676fSDimitry Andric return Attribute::NoImplicitFloat;
1350f785676fSDimitry Andric case bitc::ATTR_KIND_NO_INLINE:
1351f785676fSDimitry Andric return Attribute::NoInline;
13527d523365SDimitry Andric case bitc::ATTR_KIND_NO_RECURSE:
13537d523365SDimitry Andric return Attribute::NoRecurse;
1354f785676fSDimitry Andric case bitc::ATTR_KIND_NON_LAZY_BIND:
1355f785676fSDimitry Andric return Attribute::NonLazyBind;
135691bc56edSDimitry Andric case bitc::ATTR_KIND_NON_NULL:
135791bc56edSDimitry Andric return Attribute::NonNull;
135891bc56edSDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE:
135991bc56edSDimitry Andric return Attribute::Dereferenceable;
1360ff0cc061SDimitry Andric case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1361ff0cc061SDimitry Andric return Attribute::DereferenceableOrNull;
13623ca95b02SDimitry Andric case bitc::ATTR_KIND_ALLOC_SIZE:
13633ca95b02SDimitry Andric return Attribute::AllocSize;
1364f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RED_ZONE:
1365f785676fSDimitry Andric return Attribute::NoRedZone;
1366f785676fSDimitry Andric case bitc::ATTR_KIND_NO_RETURN:
1367f785676fSDimitry Andric return Attribute::NoReturn;
13684ba319b5SDimitry Andric case bitc::ATTR_KIND_NOCF_CHECK:
13694ba319b5SDimitry Andric return Attribute::NoCfCheck;
1370f785676fSDimitry Andric case bitc::ATTR_KIND_NO_UNWIND:
1371f785676fSDimitry Andric return Attribute::NoUnwind;
13724ba319b5SDimitry Andric case bitc::ATTR_KIND_OPT_FOR_FUZZING:
13734ba319b5SDimitry Andric return Attribute::OptForFuzzing;
1374f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1375f785676fSDimitry Andric return Attribute::OptimizeForSize;
1376f785676fSDimitry Andric case bitc::ATTR_KIND_OPTIMIZE_NONE:
1377f785676fSDimitry Andric return Attribute::OptimizeNone;
1378f785676fSDimitry Andric case bitc::ATTR_KIND_READ_NONE:
1379f785676fSDimitry Andric return Attribute::ReadNone;
1380f785676fSDimitry Andric case bitc::ATTR_KIND_READ_ONLY:
1381f785676fSDimitry Andric return Attribute::ReadOnly;
1382f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNED:
1383f785676fSDimitry Andric return Attribute::Returned;
1384f785676fSDimitry Andric case bitc::ATTR_KIND_RETURNS_TWICE:
1385f785676fSDimitry Andric return Attribute::ReturnsTwice;
1386f785676fSDimitry Andric case bitc::ATTR_KIND_S_EXT:
1387f785676fSDimitry Andric return Attribute::SExt;
1388f37b6182SDimitry Andric case bitc::ATTR_KIND_SPECULATABLE:
1389f37b6182SDimitry Andric return Attribute::Speculatable;
1390f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_ALIGNMENT:
1391f785676fSDimitry Andric return Attribute::StackAlignment;
1392f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT:
1393f785676fSDimitry Andric return Attribute::StackProtect;
1394f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1395f785676fSDimitry Andric return Attribute::StackProtectReq;
1396f785676fSDimitry Andric case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1397f785676fSDimitry Andric return Attribute::StackProtectStrong;
13988f0fd8f6SDimitry Andric case bitc::ATTR_KIND_SAFESTACK:
13998f0fd8f6SDimitry Andric return Attribute::SafeStack;
14004ba319b5SDimitry Andric case bitc::ATTR_KIND_SHADOWCALLSTACK:
14014ba319b5SDimitry Andric return Attribute::ShadowCallStack;
14022cab237bSDimitry Andric case bitc::ATTR_KIND_STRICT_FP:
14032cab237bSDimitry Andric return Attribute::StrictFP;
1404f785676fSDimitry Andric case bitc::ATTR_KIND_STRUCT_RET:
1405f785676fSDimitry Andric return Attribute::StructRet;
1406f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1407f785676fSDimitry Andric return Attribute::SanitizeAddress;
14082cab237bSDimitry Andric case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
14092cab237bSDimitry Andric return Attribute::SanitizeHWAddress;
1410f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_THREAD:
1411f785676fSDimitry Andric return Attribute::SanitizeThread;
1412f785676fSDimitry Andric case bitc::ATTR_KIND_SANITIZE_MEMORY:
1413f785676fSDimitry Andric return Attribute::SanitizeMemory;
1414*b5893f02SDimitry Andric case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
1415*b5893f02SDimitry Andric return Attribute::SpeculativeLoadHardening;
14163ca95b02SDimitry Andric case bitc::ATTR_KIND_SWIFT_ERROR:
14173ca95b02SDimitry Andric return Attribute::SwiftError;
14183ca95b02SDimitry Andric case bitc::ATTR_KIND_SWIFT_SELF:
14193ca95b02SDimitry Andric return Attribute::SwiftSelf;
1420f785676fSDimitry Andric case bitc::ATTR_KIND_UW_TABLE:
1421f785676fSDimitry Andric return Attribute::UWTable;
14223ca95b02SDimitry Andric case bitc::ATTR_KIND_WRITEONLY:
14233ca95b02SDimitry Andric return Attribute::WriteOnly;
1424f785676fSDimitry Andric case bitc::ATTR_KIND_Z_EXT:
1425f785676fSDimitry Andric return Attribute::ZExt;
1426f785676fSDimitry Andric }
1427f785676fSDimitry Andric }
1428f785676fSDimitry Andric
parseAlignmentValue(uint64_t Exponent,unsigned & Alignment)1429d88c1a5aSDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1430ff0cc061SDimitry Andric unsigned &Alignment) {
1431ff0cc061SDimitry Andric // Note: Alignment in bitcode files is incremented by 1, so that zero
1432ff0cc061SDimitry Andric // can be used for default alignment.
1433ff0cc061SDimitry Andric if (Exponent > Value::MaxAlignmentExponent + 1)
14348f0fd8f6SDimitry Andric return error("Invalid alignment value");
1435ff0cc061SDimitry Andric Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1436d88c1a5aSDimitry Andric return Error::success();
1437ff0cc061SDimitry Andric }
1438ff0cc061SDimitry Andric
parseAttrKind(uint64_t Code,Attribute::AttrKind * Kind)1439d88c1a5aSDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
14408f0fd8f6SDimitry Andric *Kind = getAttrFromCode(Code);
1441f785676fSDimitry Andric if (*Kind == Attribute::None)
1442d88c1a5aSDimitry Andric return error("Unknown attribute kind (" + Twine(Code) + ")");
1443d88c1a5aSDimitry Andric return Error::success();
1444f785676fSDimitry Andric }
1445f785676fSDimitry Andric
parseAttributeGroupBlock()1446d88c1a5aSDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() {
1447139f7f9bSDimitry Andric if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
14488f0fd8f6SDimitry Andric return error("Invalid record");
1449139f7f9bSDimitry Andric
1450139f7f9bSDimitry Andric if (!MAttributeGroups.empty())
14518f0fd8f6SDimitry Andric return error("Invalid multiple blocks");
1452139f7f9bSDimitry Andric
1453139f7f9bSDimitry Andric SmallVector<uint64_t, 64> Record;
1454139f7f9bSDimitry Andric
1455139f7f9bSDimitry Andric // Read all the records.
1456d88c1a5aSDimitry Andric while (true) {
1457139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1458139f7f9bSDimitry Andric
1459139f7f9bSDimitry Andric switch (Entry.Kind) {
1460139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
1461139f7f9bSDimitry Andric case BitstreamEntry::Error:
14628f0fd8f6SDimitry Andric return error("Malformed block");
1463139f7f9bSDimitry Andric case BitstreamEntry::EndBlock:
1464d88c1a5aSDimitry Andric return Error::success();
1465139f7f9bSDimitry Andric case BitstreamEntry::Record:
1466139f7f9bSDimitry Andric // The interesting case.
1467139f7f9bSDimitry Andric break;
1468139f7f9bSDimitry Andric }
1469139f7f9bSDimitry Andric
1470139f7f9bSDimitry Andric // Read a record.
1471139f7f9bSDimitry Andric Record.clear();
1472139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) {
1473139f7f9bSDimitry Andric default: // Default behavior: ignore.
1474139f7f9bSDimitry Andric break;
1475139f7f9bSDimitry Andric case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1476139f7f9bSDimitry Andric if (Record.size() < 3)
14778f0fd8f6SDimitry Andric return error("Invalid record");
1478139f7f9bSDimitry Andric
1479139f7f9bSDimitry Andric uint64_t GrpID = Record[0];
1480139f7f9bSDimitry Andric uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1481139f7f9bSDimitry Andric
1482139f7f9bSDimitry Andric AttrBuilder B;
1483139f7f9bSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1484139f7f9bSDimitry Andric if (Record[i] == 0) { // Enum attribute
1485f785676fSDimitry Andric Attribute::AttrKind Kind;
1486d88c1a5aSDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind))
1487d88c1a5aSDimitry Andric return Err;
1488f785676fSDimitry Andric
1489f785676fSDimitry Andric B.addAttribute(Kind);
149091bc56edSDimitry Andric } else if (Record[i] == 1) { // Integer attribute
1491f785676fSDimitry Andric Attribute::AttrKind Kind;
1492d88c1a5aSDimitry Andric if (Error Err = parseAttrKind(Record[++i], &Kind))
1493d88c1a5aSDimitry Andric return Err;
1494f785676fSDimitry Andric if (Kind == Attribute::Alignment)
1495139f7f9bSDimitry Andric B.addAlignmentAttr(Record[++i]);
149691bc56edSDimitry Andric else if (Kind == Attribute::StackAlignment)
1497139f7f9bSDimitry Andric B.addStackAlignmentAttr(Record[++i]);
149891bc56edSDimitry Andric else if (Kind == Attribute::Dereferenceable)
149991bc56edSDimitry Andric B.addDereferenceableAttr(Record[++i]);
1500ff0cc061SDimitry Andric else if (Kind == Attribute::DereferenceableOrNull)
1501ff0cc061SDimitry Andric B.addDereferenceableOrNullAttr(Record[++i]);
15023ca95b02SDimitry Andric else if (Kind == Attribute::AllocSize)
15033ca95b02SDimitry Andric B.addAllocSizeAttrFromRawRepr(Record[++i]);
1504139f7f9bSDimitry Andric } else { // String attribute
1505139f7f9bSDimitry Andric assert((Record[i] == 3 || Record[i] == 4) &&
1506139f7f9bSDimitry Andric "Invalid attribute group entry");
1507139f7f9bSDimitry Andric bool HasValue = (Record[i++] == 4);
1508139f7f9bSDimitry Andric SmallString<64> KindStr;
1509139f7f9bSDimitry Andric SmallString<64> ValStr;
1510139f7f9bSDimitry Andric
1511139f7f9bSDimitry Andric while (Record[i] != 0 && i != e)
1512139f7f9bSDimitry Andric KindStr += Record[i++];
1513139f7f9bSDimitry Andric assert(Record[i] == 0 && "Kind string not null terminated");
1514139f7f9bSDimitry Andric
1515139f7f9bSDimitry Andric if (HasValue) {
1516139f7f9bSDimitry Andric // Has a value associated with it.
1517139f7f9bSDimitry Andric ++i; // Skip the '0' that terminates the "kind" string.
1518139f7f9bSDimitry Andric while (Record[i] != 0 && i != e)
1519139f7f9bSDimitry Andric ValStr += Record[i++];
1520139f7f9bSDimitry Andric assert(Record[i] == 0 && "Value string not null terminated");
1521139f7f9bSDimitry Andric }
1522139f7f9bSDimitry Andric
1523139f7f9bSDimitry Andric B.addAttribute(KindStr.str(), ValStr.str());
1524139f7f9bSDimitry Andric }
1525139f7f9bSDimitry Andric }
1526139f7f9bSDimitry Andric
15277a7e6055SDimitry Andric MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1528139f7f9bSDimitry Andric break;
1529139f7f9bSDimitry Andric }
1530f22ef01cSRoman Divacky }
1531f22ef01cSRoman Divacky }
1532f22ef01cSRoman Divacky }
1533f22ef01cSRoman Divacky
parseTypeTable()1534d88c1a5aSDimitry Andric Error BitcodeReader::parseTypeTable() {
153517a519f9SDimitry Andric if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
15368f0fd8f6SDimitry Andric return error("Invalid record");
1537f22ef01cSRoman Divacky
15388f0fd8f6SDimitry Andric return parseTypeTableBody();
153917a519f9SDimitry Andric }
154017a519f9SDimitry Andric
parseTypeTableBody()1541d88c1a5aSDimitry Andric Error BitcodeReader::parseTypeTableBody() {
1542f22ef01cSRoman Divacky if (!TypeList.empty())
15438f0fd8f6SDimitry Andric return error("Invalid multiple blocks");
1544f22ef01cSRoman Divacky
1545f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record;
1546f22ef01cSRoman Divacky unsigned NumRecords = 0;
1547f22ef01cSRoman Divacky
154817a519f9SDimitry Andric SmallString<64> TypeName;
154917a519f9SDimitry Andric
1550f22ef01cSRoman Divacky // Read all the records for this type table.
1551d88c1a5aSDimitry Andric while (true) {
1552139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1553139f7f9bSDimitry Andric
1554139f7f9bSDimitry Andric switch (Entry.Kind) {
1555139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
1556139f7f9bSDimitry Andric case BitstreamEntry::Error:
15578f0fd8f6SDimitry Andric return error("Malformed block");
1558139f7f9bSDimitry Andric case BitstreamEntry::EndBlock:
1559f22ef01cSRoman Divacky if (NumRecords != TypeList.size())
15608f0fd8f6SDimitry Andric return error("Malformed block");
1561d88c1a5aSDimitry Andric return Error::success();
1562139f7f9bSDimitry Andric case BitstreamEntry::Record:
1563139f7f9bSDimitry Andric // The interesting case.
1564139f7f9bSDimitry Andric break;
1565f22ef01cSRoman Divacky }
1566f22ef01cSRoman Divacky
1567f22ef01cSRoman Divacky // Read a record.
1568f22ef01cSRoman Divacky Record.clear();
156991bc56edSDimitry Andric Type *ResultTy = nullptr;
1570139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) {
1571f785676fSDimitry Andric default:
15728f0fd8f6SDimitry Andric return error("Invalid value");
1573f22ef01cSRoman Divacky case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1574f22ef01cSRoman Divacky // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1575f22ef01cSRoman Divacky // type list. This allows us to reserve space.
1576f22ef01cSRoman Divacky if (Record.size() < 1)
15778f0fd8f6SDimitry Andric return error("Invalid record");
157817a519f9SDimitry Andric TypeList.resize(Record[0]);
1579f22ef01cSRoman Divacky continue;
1580f22ef01cSRoman Divacky case bitc::TYPE_CODE_VOID: // VOID
1581f22ef01cSRoman Divacky ResultTy = Type::getVoidTy(Context);
1582f22ef01cSRoman Divacky break;
1583dff0c46cSDimitry Andric case bitc::TYPE_CODE_HALF: // HALF
1584dff0c46cSDimitry Andric ResultTy = Type::getHalfTy(Context);
1585dff0c46cSDimitry Andric break;
1586f22ef01cSRoman Divacky case bitc::TYPE_CODE_FLOAT: // FLOAT
1587f22ef01cSRoman Divacky ResultTy = Type::getFloatTy(Context);
1588f22ef01cSRoman Divacky break;
1589f22ef01cSRoman Divacky case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1590f22ef01cSRoman Divacky ResultTy = Type::getDoubleTy(Context);
1591f22ef01cSRoman Divacky break;
1592f22ef01cSRoman Divacky case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1593f22ef01cSRoman Divacky ResultTy = Type::getX86_FP80Ty(Context);
1594f22ef01cSRoman Divacky break;
1595f22ef01cSRoman Divacky case bitc::TYPE_CODE_FP128: // FP128
1596f22ef01cSRoman Divacky ResultTy = Type::getFP128Ty(Context);
1597f22ef01cSRoman Divacky break;
1598f22ef01cSRoman Divacky case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1599f22ef01cSRoman Divacky ResultTy = Type::getPPC_FP128Ty(Context);
1600f22ef01cSRoman Divacky break;
1601f22ef01cSRoman Divacky case bitc::TYPE_CODE_LABEL: // LABEL
1602f22ef01cSRoman Divacky ResultTy = Type::getLabelTy(Context);
1603f22ef01cSRoman Divacky break;
1604f22ef01cSRoman Divacky case bitc::TYPE_CODE_METADATA: // METADATA
1605f22ef01cSRoman Divacky ResultTy = Type::getMetadataTy(Context);
1606f22ef01cSRoman Divacky break;
16072754fe60SDimitry Andric case bitc::TYPE_CODE_X86_MMX: // X86_MMX
16082754fe60SDimitry Andric ResultTy = Type::getX86_MMXTy(Context);
16092754fe60SDimitry Andric break;
16107d523365SDimitry Andric case bitc::TYPE_CODE_TOKEN: // TOKEN
16117d523365SDimitry Andric ResultTy = Type::getTokenTy(Context);
16127d523365SDimitry Andric break;
1613ff0cc061SDimitry Andric case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1614f22ef01cSRoman Divacky if (Record.size() < 1)
16158f0fd8f6SDimitry Andric return error("Invalid record");
1616f22ef01cSRoman Divacky
1617ff0cc061SDimitry Andric uint64_t NumBits = Record[0];
1618ff0cc061SDimitry Andric if (NumBits < IntegerType::MIN_INT_BITS ||
1619ff0cc061SDimitry Andric NumBits > IntegerType::MAX_INT_BITS)
16208f0fd8f6SDimitry Andric return error("Bitwidth for integer type out of range");
1621ff0cc061SDimitry Andric ResultTy = IntegerType::get(Context, NumBits);
1622f22ef01cSRoman Divacky break;
1623ff0cc061SDimitry Andric }
1624f22ef01cSRoman Divacky case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1625f22ef01cSRoman Divacky // [pointee type, address space]
1626f22ef01cSRoman Divacky if (Record.size() < 1)
16278f0fd8f6SDimitry Andric return error("Invalid record");
1628f22ef01cSRoman Divacky unsigned AddressSpace = 0;
1629f22ef01cSRoman Divacky if (Record.size() == 2)
1630f22ef01cSRoman Divacky AddressSpace = Record[1];
163117a519f9SDimitry Andric ResultTy = getTypeByID(Record[0]);
1632ff0cc061SDimitry Andric if (!ResultTy ||
1633ff0cc061SDimitry Andric !PointerType::isValidElementType(ResultTy))
16348f0fd8f6SDimitry Andric return error("Invalid type");
163517a519f9SDimitry Andric ResultTy = PointerType::get(ResultTy, AddressSpace);
1636f22ef01cSRoman Divacky break;
1637f22ef01cSRoman Divacky }
1638dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION_OLD: {
16397ae0e2c9SDimitry Andric // FIXME: attrid is dead, remove it in LLVM 4.0
1640f22ef01cSRoman Divacky // FUNCTION: [vararg, attrid, retty, paramty x N]
1641f22ef01cSRoman Divacky if (Record.size() < 3)
16428f0fd8f6SDimitry Andric return error("Invalid record");
1643dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys;
164417a519f9SDimitry Andric for (unsigned i = 3, e = Record.size(); i != e; ++i) {
164517a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i]))
164617a519f9SDimitry Andric ArgTys.push_back(T);
164717a519f9SDimitry Andric else
1648f22ef01cSRoman Divacky break;
1649f22ef01cSRoman Divacky }
165017a519f9SDimitry Andric
165117a519f9SDimitry Andric ResultTy = getTypeByID(Record[2]);
165291bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-3)
16538f0fd8f6SDimitry Andric return error("Invalid type");
165417a519f9SDimitry Andric
165517a519f9SDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
165617a519f9SDimitry Andric break;
165717a519f9SDimitry Andric }
1658dff0c46cSDimitry Andric case bitc::TYPE_CODE_FUNCTION: {
1659dff0c46cSDimitry Andric // FUNCTION: [vararg, retty, paramty x N]
1660dff0c46cSDimitry Andric if (Record.size() < 2)
16618f0fd8f6SDimitry Andric return error("Invalid record");
1662dff0c46cSDimitry Andric SmallVector<Type*, 8> ArgTys;
1663dff0c46cSDimitry Andric for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1664ff0cc061SDimitry Andric if (Type *T = getTypeByID(Record[i])) {
1665ff0cc061SDimitry Andric if (!FunctionType::isValidArgumentType(T))
16668f0fd8f6SDimitry Andric return error("Invalid function argument type");
1667dff0c46cSDimitry Andric ArgTys.push_back(T);
1668ff0cc061SDimitry Andric }
1669dff0c46cSDimitry Andric else
1670dff0c46cSDimitry Andric break;
1671dff0c46cSDimitry Andric }
1672dff0c46cSDimitry Andric
1673dff0c46cSDimitry Andric ResultTy = getTypeByID(Record[1]);
167491bc56edSDimitry Andric if (!ResultTy || ArgTys.size() < Record.size()-2)
16758f0fd8f6SDimitry Andric return error("Invalid type");
1676dff0c46cSDimitry Andric
1677dff0c46cSDimitry Andric ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1678dff0c46cSDimitry Andric break;
1679dff0c46cSDimitry Andric }
168017a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1681f22ef01cSRoman Divacky if (Record.size() < 1)
16828f0fd8f6SDimitry Andric return error("Invalid record");
1683dff0c46cSDimitry Andric SmallVector<Type*, 8> EltTys;
168417a519f9SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) {
168517a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i]))
168617a519f9SDimitry Andric EltTys.push_back(T);
168717a519f9SDimitry Andric else
168817a519f9SDimitry Andric break;
168917a519f9SDimitry Andric }
169017a519f9SDimitry Andric if (EltTys.size() != Record.size()-1)
16918f0fd8f6SDimitry Andric return error("Invalid type");
1692f22ef01cSRoman Divacky ResultTy = StructType::get(Context, EltTys, Record[0]);
1693f22ef01cSRoman Divacky break;
1694f22ef01cSRoman Divacky }
169517a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
16968f0fd8f6SDimitry Andric if (convertToString(Record, 0, TypeName))
16978f0fd8f6SDimitry Andric return error("Invalid record");
169817a519f9SDimitry Andric continue;
169917a519f9SDimitry Andric
170017a519f9SDimitry Andric case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
170117a519f9SDimitry Andric if (Record.size() < 1)
17028f0fd8f6SDimitry Andric return error("Invalid record");
170317a519f9SDimitry Andric
170417a519f9SDimitry Andric if (NumRecords >= TypeList.size())
17058f0fd8f6SDimitry Andric return error("Invalid TYPE table");
170617a519f9SDimitry Andric
170717a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp.
170817a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
170917a519f9SDimitry Andric if (Res) {
171017a519f9SDimitry Andric Res->setName(TypeName);
171191bc56edSDimitry Andric TypeList[NumRecords] = nullptr;
171217a519f9SDimitry Andric } else // Otherwise, create a new struct.
171339d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName);
171417a519f9SDimitry Andric TypeName.clear();
171517a519f9SDimitry Andric
171617a519f9SDimitry Andric SmallVector<Type*, 8> EltTys;
171717a519f9SDimitry Andric for (unsigned i = 1, e = Record.size(); i != e; ++i) {
171817a519f9SDimitry Andric if (Type *T = getTypeByID(Record[i]))
171917a519f9SDimitry Andric EltTys.push_back(T);
172017a519f9SDimitry Andric else
172117a519f9SDimitry Andric break;
172217a519f9SDimitry Andric }
172317a519f9SDimitry Andric if (EltTys.size() != Record.size()-1)
17248f0fd8f6SDimitry Andric return error("Invalid record");
172517a519f9SDimitry Andric Res->setBody(EltTys, Record[0]);
172617a519f9SDimitry Andric ResultTy = Res;
172717a519f9SDimitry Andric break;
172817a519f9SDimitry Andric }
172917a519f9SDimitry Andric case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
173017a519f9SDimitry Andric if (Record.size() != 1)
17318f0fd8f6SDimitry Andric return error("Invalid record");
173217a519f9SDimitry Andric
173317a519f9SDimitry Andric if (NumRecords >= TypeList.size())
17348f0fd8f6SDimitry Andric return error("Invalid TYPE table");
173517a519f9SDimitry Andric
173617a519f9SDimitry Andric // Check to see if this was forward referenced, if so fill in the temp.
173717a519f9SDimitry Andric StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
173817a519f9SDimitry Andric if (Res) {
173917a519f9SDimitry Andric Res->setName(TypeName);
174091bc56edSDimitry Andric TypeList[NumRecords] = nullptr;
174117a519f9SDimitry Andric } else // Otherwise, create a new struct with no body.
174239d628a0SDimitry Andric Res = createIdentifiedStructType(Context, TypeName);
174317a519f9SDimitry Andric TypeName.clear();
174417a519f9SDimitry Andric ResultTy = Res;
174517a519f9SDimitry Andric break;
174617a519f9SDimitry Andric }
1747f22ef01cSRoman Divacky case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1748f22ef01cSRoman Divacky if (Record.size() < 2)
17498f0fd8f6SDimitry Andric return error("Invalid record");
1750ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]);
1751ff0cc061SDimitry Andric if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
17528f0fd8f6SDimitry Andric return error("Invalid type");
1753ff0cc061SDimitry Andric ResultTy = ArrayType::get(ResultTy, Record[0]);
1754f22ef01cSRoman Divacky break;
1755f22ef01cSRoman Divacky case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1756f22ef01cSRoman Divacky if (Record.size() < 2)
17578f0fd8f6SDimitry Andric return error("Invalid record");
175897bc6c73SDimitry Andric if (Record[0] == 0)
17598f0fd8f6SDimitry Andric return error("Invalid vector length");
1760ff0cc061SDimitry Andric ResultTy = getTypeByID(Record[1]);
1761ff0cc061SDimitry Andric if (!ResultTy || !StructType::isValidElementType(ResultTy))
17628f0fd8f6SDimitry Andric return error("Invalid type");
1763ff0cc061SDimitry Andric ResultTy = VectorType::get(ResultTy, Record[0]);
1764f22ef01cSRoman Divacky break;
1765f22ef01cSRoman Divacky }
1766f22ef01cSRoman Divacky
176717a519f9SDimitry Andric if (NumRecords >= TypeList.size())
17688f0fd8f6SDimitry Andric return error("Invalid TYPE table");
1769ff0cc061SDimitry Andric if (TypeList[NumRecords])
17708f0fd8f6SDimitry Andric return error(
1771ff0cc061SDimitry Andric "Invalid TYPE table: Only named structs can be forward referenced");
177217a519f9SDimitry Andric assert(ResultTy && "Didn't read a type?");
177317a519f9SDimitry Andric TypeList[NumRecords++] = ResultTy;
1774f22ef01cSRoman Divacky }
1775f22ef01cSRoman Divacky }
177617a519f9SDimitry Andric
parseOperandBundleTags()1777d88c1a5aSDimitry Andric Error BitcodeReader::parseOperandBundleTags() {
17787d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
17797d523365SDimitry Andric return error("Invalid record");
17807d523365SDimitry Andric
17817d523365SDimitry Andric if (!BundleTags.empty())
17827d523365SDimitry Andric return error("Invalid multiple blocks");
17837d523365SDimitry Andric
17847d523365SDimitry Andric SmallVector<uint64_t, 64> Record;
17857d523365SDimitry Andric
1786d88c1a5aSDimitry Andric while (true) {
17877d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
17887d523365SDimitry Andric
17897d523365SDimitry Andric switch (Entry.Kind) {
17907d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
17917d523365SDimitry Andric case BitstreamEntry::Error:
17927d523365SDimitry Andric return error("Malformed block");
17937d523365SDimitry Andric case BitstreamEntry::EndBlock:
1794d88c1a5aSDimitry Andric return Error::success();
17957d523365SDimitry Andric case BitstreamEntry::Record:
17967d523365SDimitry Andric // The interesting case.
17977d523365SDimitry Andric break;
17987d523365SDimitry Andric }
17997d523365SDimitry Andric
18007d523365SDimitry Andric // Tags are implicitly mapped to integers by their order.
18017d523365SDimitry Andric
18027d523365SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
18037d523365SDimitry Andric return error("Invalid record");
18047d523365SDimitry Andric
18057d523365SDimitry Andric // OPERAND_BUNDLE_TAG: [strchr x N]
18067d523365SDimitry Andric BundleTags.emplace_back();
18077d523365SDimitry Andric if (convertToString(Record, 0, BundleTags.back()))
18087d523365SDimitry Andric return error("Invalid record");
18097d523365SDimitry Andric Record.clear();
18107d523365SDimitry Andric }
18117d523365SDimitry Andric }
18127d523365SDimitry Andric
parseSyncScopeNames()1813c4394386SDimitry Andric Error BitcodeReader::parseSyncScopeNames() {
1814c4394386SDimitry Andric if (Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1815c4394386SDimitry Andric return error("Invalid record");
1816c4394386SDimitry Andric
1817c4394386SDimitry Andric if (!SSIDs.empty())
1818c4394386SDimitry Andric return error("Invalid multiple synchronization scope names blocks");
1819c4394386SDimitry Andric
1820c4394386SDimitry Andric SmallVector<uint64_t, 64> Record;
1821c4394386SDimitry Andric while (true) {
1822c4394386SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1823c4394386SDimitry Andric switch (Entry.Kind) {
1824c4394386SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
1825c4394386SDimitry Andric case BitstreamEntry::Error:
1826c4394386SDimitry Andric return error("Malformed block");
1827c4394386SDimitry Andric case BitstreamEntry::EndBlock:
1828c4394386SDimitry Andric if (SSIDs.empty())
1829c4394386SDimitry Andric return error("Invalid empty synchronization scope names block");
1830c4394386SDimitry Andric return Error::success();
1831c4394386SDimitry Andric case BitstreamEntry::Record:
1832c4394386SDimitry Andric // The interesting case.
1833c4394386SDimitry Andric break;
1834c4394386SDimitry Andric }
1835c4394386SDimitry Andric
1836c4394386SDimitry Andric // Synchronization scope names are implicitly mapped to synchronization
1837c4394386SDimitry Andric // scope IDs by their order.
1838c4394386SDimitry Andric
1839c4394386SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::SYNC_SCOPE_NAME)
1840c4394386SDimitry Andric return error("Invalid record");
1841c4394386SDimitry Andric
1842c4394386SDimitry Andric SmallString<16> SSN;
1843c4394386SDimitry Andric if (convertToString(Record, 0, SSN))
1844c4394386SDimitry Andric return error("Invalid record");
1845c4394386SDimitry Andric
1846c4394386SDimitry Andric SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
1847c4394386SDimitry Andric Record.clear();
1848c4394386SDimitry Andric }
1849c4394386SDimitry Andric }
1850c4394386SDimitry Andric
18517d523365SDimitry Andric /// Associate a value with its name from the given index in the provided record.
recordValue(SmallVectorImpl<uint64_t> & Record,unsigned NameIndex,Triple & TT)1852d88c1a5aSDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
18537d523365SDimitry Andric unsigned NameIndex, Triple &TT) {
18547d523365SDimitry Andric SmallString<128> ValueName;
18557d523365SDimitry Andric if (convertToString(Record, NameIndex, ValueName))
18567d523365SDimitry Andric return error("Invalid record");
18577d523365SDimitry Andric unsigned ValueID = Record[0];
18587d523365SDimitry Andric if (ValueID >= ValueList.size() || !ValueList[ValueID])
18597d523365SDimitry Andric return error("Invalid record");
18607d523365SDimitry Andric Value *V = ValueList[ValueID];
18617d523365SDimitry Andric
18627d523365SDimitry Andric StringRef NameStr(ValueName.data(), ValueName.size());
18637d523365SDimitry Andric if (NameStr.find_first_of(0) != StringRef::npos)
18647d523365SDimitry Andric return error("Invalid value name");
18657d523365SDimitry Andric V->setName(NameStr);
18667d523365SDimitry Andric auto *GO = dyn_cast<GlobalObject>(V);
18677d523365SDimitry Andric if (GO) {
18687d523365SDimitry Andric if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
18692cab237bSDimitry Andric if (TT.supportsCOMDAT())
18707d523365SDimitry Andric GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
18712cab237bSDimitry Andric else
18722cab237bSDimitry Andric GO->setComdat(nullptr);
18737d523365SDimitry Andric }
18747d523365SDimitry Andric }
18757d523365SDimitry Andric return V;
18767d523365SDimitry Andric }
18777d523365SDimitry Andric
18783ca95b02SDimitry Andric /// Helper to note and return the current location, and jump to the given
18793ca95b02SDimitry Andric /// offset.
jumpToValueSymbolTable(uint64_t Offset,BitstreamCursor & Stream)18803ca95b02SDimitry Andric static uint64_t jumpToValueSymbolTable(uint64_t Offset,
18813ca95b02SDimitry Andric BitstreamCursor &Stream) {
18827d523365SDimitry Andric // Save the current parsing location so we can jump back at the end
18837d523365SDimitry Andric // of the VST read.
18843ca95b02SDimitry Andric uint64_t CurrentBit = Stream.GetCurrentBitNo();
18857d523365SDimitry Andric Stream.JumpToBit(Offset * 32);
18867d523365SDimitry Andric #ifndef NDEBUG
18877d523365SDimitry Andric // Do some checking if we are in debug mode.
18887d523365SDimitry Andric BitstreamEntry Entry = Stream.advance();
18897d523365SDimitry Andric assert(Entry.Kind == BitstreamEntry::SubBlock);
18907d523365SDimitry Andric assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
18917d523365SDimitry Andric #else
18927d523365SDimitry Andric // In NDEBUG mode ignore the output so we don't get an unused variable
18937d523365SDimitry Andric // warning.
18947d523365SDimitry Andric Stream.advance();
18957d523365SDimitry Andric #endif
18963ca95b02SDimitry Andric return CurrentBit;
18977d523365SDimitry Andric }
18987d523365SDimitry Andric
setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,Function * F,ArrayRef<uint64_t> Record)18996bc11b14SDimitry Andric void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
19006bc11b14SDimitry Andric Function *F,
19016bc11b14SDimitry Andric ArrayRef<uint64_t> Record) {
19026bc11b14SDimitry Andric // Note that we subtract 1 here because the offset is relative to one word
19036bc11b14SDimitry Andric // before the start of the identification or module block, which was
19046bc11b14SDimitry Andric // historically always the start of the regular bitcode header.
19056bc11b14SDimitry Andric uint64_t FuncWordOffset = Record[1] - 1;
19066bc11b14SDimitry Andric uint64_t FuncBitOffset = FuncWordOffset * 32;
19076bc11b14SDimitry Andric DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
19086bc11b14SDimitry Andric // Set the LastFunctionBlockBit to point to the last function block.
19096bc11b14SDimitry Andric // Later when parsing is resumed after function materialization,
19106bc11b14SDimitry Andric // we can simply skip that last function block.
19116bc11b14SDimitry Andric if (FuncBitOffset > LastFunctionBlockBit)
19126bc11b14SDimitry Andric LastFunctionBlockBit = FuncBitOffset;
19136bc11b14SDimitry Andric }
19146bc11b14SDimitry Andric
19156bc11b14SDimitry Andric /// Read a new-style GlobalValue symbol table.
parseGlobalValueSymbolTable()19166bc11b14SDimitry Andric Error BitcodeReader::parseGlobalValueSymbolTable() {
19176bc11b14SDimitry Andric unsigned FuncBitcodeOffsetDelta =
19186bc11b14SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
19196bc11b14SDimitry Andric
19206bc11b14SDimitry Andric if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
19216bc11b14SDimitry Andric return error("Invalid record");
19226bc11b14SDimitry Andric
19236bc11b14SDimitry Andric SmallVector<uint64_t, 64> Record;
19246bc11b14SDimitry Andric while (true) {
19256bc11b14SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
19266bc11b14SDimitry Andric
19276bc11b14SDimitry Andric switch (Entry.Kind) {
19286bc11b14SDimitry Andric case BitstreamEntry::SubBlock:
19296bc11b14SDimitry Andric case BitstreamEntry::Error:
19306bc11b14SDimitry Andric return error("Malformed block");
19316bc11b14SDimitry Andric case BitstreamEntry::EndBlock:
19326bc11b14SDimitry Andric return Error::success();
19336bc11b14SDimitry Andric case BitstreamEntry::Record:
19346bc11b14SDimitry Andric break;
19356bc11b14SDimitry Andric }
19366bc11b14SDimitry Andric
19376bc11b14SDimitry Andric Record.clear();
19386bc11b14SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) {
19396bc11b14SDimitry Andric case bitc::VST_CODE_FNENTRY: // [valueid, offset]
19406bc11b14SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
19416bc11b14SDimitry Andric cast<Function>(ValueList[Record[0]]), Record);
19426bc11b14SDimitry Andric break;
19436bc11b14SDimitry Andric }
19446bc11b14SDimitry Andric }
19456bc11b14SDimitry Andric }
19466bc11b14SDimitry Andric
19473ca95b02SDimitry Andric /// Parse the value symbol table at either the current parsing location or
19483ca95b02SDimitry Andric /// at the given bit offset if provided.
parseValueSymbolTable(uint64_t Offset)1949d88c1a5aSDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
19503ca95b02SDimitry Andric uint64_t CurrentBit;
19513ca95b02SDimitry Andric // Pass in the Offset to distinguish between calling for the module-level
19523ca95b02SDimitry Andric // VST (where we want to jump to the VST offset) and the function-level
19533ca95b02SDimitry Andric // VST (where we don't).
19546bc11b14SDimitry Andric if (Offset > 0) {
19553ca95b02SDimitry Andric CurrentBit = jumpToValueSymbolTable(Offset, Stream);
19566bc11b14SDimitry Andric // If this module uses a string table, read this as a module-level VST.
19576bc11b14SDimitry Andric if (UseStrtab) {
19586bc11b14SDimitry Andric if (Error Err = parseGlobalValueSymbolTable())
19596bc11b14SDimitry Andric return Err;
19606bc11b14SDimitry Andric Stream.JumpToBit(CurrentBit);
19616bc11b14SDimitry Andric return Error::success();
19626bc11b14SDimitry Andric }
19636bc11b14SDimitry Andric // Otherwise, the VST will be in a similar format to a function-level VST,
19646bc11b14SDimitry Andric // and will contain symbol names.
19656bc11b14SDimitry Andric }
19663ca95b02SDimitry Andric
19677d523365SDimitry Andric // Compute the delta between the bitcode indices in the VST (the word offset
19687d523365SDimitry Andric // to the word-aligned ENTER_SUBBLOCK for the function block, and that
19697d523365SDimitry Andric // expected by the lazy reader. The reader's EnterSubBlock expects to have
19707d523365SDimitry Andric // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
19717d523365SDimitry Andric // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
19727d523365SDimitry Andric // just before entering the VST subblock because: 1) the EnterSubBlock
19737d523365SDimitry Andric // changes the AbbrevID width; 2) the VST block is nested within the same
19747d523365SDimitry Andric // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
19757d523365SDimitry Andric // AbbrevID width before calling EnterSubBlock; and 3) when we want to
19767d523365SDimitry Andric // jump to the FUNCTION_BLOCK using this offset later, we don't want
19777d523365SDimitry Andric // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
19787d523365SDimitry Andric unsigned FuncBitcodeOffsetDelta =
19797d523365SDimitry Andric Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
19807d523365SDimitry Andric
1981f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
19828f0fd8f6SDimitry Andric return error("Invalid record");
1983f22ef01cSRoman Divacky
1984f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record;
1985f22ef01cSRoman Divacky
1986ff0cc061SDimitry Andric Triple TT(TheModule->getTargetTriple());
1987ff0cc061SDimitry Andric
1988f22ef01cSRoman Divacky // Read all the records for this value table.
1989f22ef01cSRoman Divacky SmallString<128> ValueName;
1990d88c1a5aSDimitry Andric
1991d88c1a5aSDimitry Andric while (true) {
1992139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1993f22ef01cSRoman Divacky
1994139f7f9bSDimitry Andric switch (Entry.Kind) {
1995139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
1996139f7f9bSDimitry Andric case BitstreamEntry::Error:
19978f0fd8f6SDimitry Andric return error("Malformed block");
1998139f7f9bSDimitry Andric case BitstreamEntry::EndBlock:
19997d523365SDimitry Andric if (Offset > 0)
20007d523365SDimitry Andric Stream.JumpToBit(CurrentBit);
2001d88c1a5aSDimitry Andric return Error::success();
2002139f7f9bSDimitry Andric case BitstreamEntry::Record:
2003139f7f9bSDimitry Andric // The interesting case.
2004139f7f9bSDimitry Andric break;
2005f22ef01cSRoman Divacky }
2006f22ef01cSRoman Divacky
2007f22ef01cSRoman Divacky // Read a record.
2008f22ef01cSRoman Divacky Record.clear();
2009139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) {
2010f22ef01cSRoman Divacky default: // Default behavior: unknown type.
2011f22ef01cSRoman Divacky break;
20123ca95b02SDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
2013d88c1a5aSDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2014d88c1a5aSDimitry Andric if (Error Err = ValOrErr.takeError())
2015d88c1a5aSDimitry Andric return Err;
20167d523365SDimitry Andric ValOrErr.get();
20177d523365SDimitry Andric break;
20187d523365SDimitry Andric }
20197d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: {
20203ca95b02SDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2021d88c1a5aSDimitry Andric Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2022d88c1a5aSDimitry Andric if (Error Err = ValOrErr.takeError())
2023d88c1a5aSDimitry Andric return Err;
20247d523365SDimitry Andric Value *V = ValOrErr.get();
2025f22ef01cSRoman Divacky
20267a7e6055SDimitry Andric // Ignore function offsets emitted for aliases of functions in older
20277a7e6055SDimitry Andric // versions of LLVM.
20286bc11b14SDimitry Andric if (auto *F = dyn_cast<Function>(V))
20296bc11b14SDimitry Andric setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2030f22ef01cSRoman Divacky break;
2031f22ef01cSRoman Divacky }
2032f22ef01cSRoman Divacky case bitc::VST_CODE_BBENTRY: {
20338f0fd8f6SDimitry Andric if (convertToString(Record, 1, ValueName))
20348f0fd8f6SDimitry Andric return error("Invalid record");
2035f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[0]);
203691bc56edSDimitry Andric if (!BB)
20378f0fd8f6SDimitry Andric return error("Invalid record");
2038f22ef01cSRoman Divacky
2039f22ef01cSRoman Divacky BB->setName(StringRef(ValueName.data(), ValueName.size()));
2040f22ef01cSRoman Divacky ValueName.clear();
2041f22ef01cSRoman Divacky break;
2042f22ef01cSRoman Divacky }
2043f22ef01cSRoman Divacky }
2044f22ef01cSRoman Divacky }
2045f22ef01cSRoman Divacky }
2046f22ef01cSRoman Divacky
20478f0fd8f6SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR
20488f0fd8f6SDimitry Andric /// encoding.
decodeSignRotatedValue(uint64_t V)20493861d79fSDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2050f22ef01cSRoman Divacky if ((V & 1) == 0)
2051f22ef01cSRoman Divacky return V >> 1;
2052f22ef01cSRoman Divacky if (V != 1)
2053f22ef01cSRoman Divacky return -(V >> 1);
2054f22ef01cSRoman Divacky // There is no such thing as -0 with integers. "-0" really means MININT.
2055f22ef01cSRoman Divacky return 1ULL << 63;
2056f22ef01cSRoman Divacky }
2057f22ef01cSRoman Divacky
20588f0fd8f6SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can.
resolveGlobalAndIndirectSymbolInits()2059d88c1a5aSDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2060f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
20613ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
20623ca95b02SDimitry Andric IndirectSymbolInitWorklist;
2063f785676fSDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
206439d628a0SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
20658f0fd8f6SDimitry Andric std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
2066f22ef01cSRoman Divacky
2067f22ef01cSRoman Divacky GlobalInitWorklist.swap(GlobalInits);
20683ca95b02SDimitry Andric IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2069f785676fSDimitry Andric FunctionPrefixWorklist.swap(FunctionPrefixes);
207039d628a0SDimitry Andric FunctionPrologueWorklist.swap(FunctionPrologues);
20718f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2072f22ef01cSRoman Divacky
2073f22ef01cSRoman Divacky while (!GlobalInitWorklist.empty()) {
2074f22ef01cSRoman Divacky unsigned ValID = GlobalInitWorklist.back().second;
2075f22ef01cSRoman Divacky if (ValID >= ValueList.size()) {
2076f22ef01cSRoman Divacky // Not ready to resolve this yet, it requires something later in the file.
2077f22ef01cSRoman Divacky GlobalInits.push_back(GlobalInitWorklist.back());
2078f22ef01cSRoman Divacky } else {
207991bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2080f22ef01cSRoman Divacky GlobalInitWorklist.back().first->setInitializer(C);
2081f22ef01cSRoman Divacky else
20828f0fd8f6SDimitry Andric return error("Expected a constant");
2083f22ef01cSRoman Divacky }
2084f22ef01cSRoman Divacky GlobalInitWorklist.pop_back();
2085f22ef01cSRoman Divacky }
2086f22ef01cSRoman Divacky
20873ca95b02SDimitry Andric while (!IndirectSymbolInitWorklist.empty()) {
20883ca95b02SDimitry Andric unsigned ValID = IndirectSymbolInitWorklist.back().second;
2089f22ef01cSRoman Divacky if (ValID >= ValueList.size()) {
20903ca95b02SDimitry Andric IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2091f22ef01cSRoman Divacky } else {
209297bc6c73SDimitry Andric Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
209397bc6c73SDimitry Andric if (!C)
20948f0fd8f6SDimitry Andric return error("Expected a constant");
20953ca95b02SDimitry Andric GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
20963ca95b02SDimitry Andric if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
20978f0fd8f6SDimitry Andric return error("Alias and aliasee types don't match");
20983ca95b02SDimitry Andric GIS->setIndirectSymbol(C);
2099f22ef01cSRoman Divacky }
21003ca95b02SDimitry Andric IndirectSymbolInitWorklist.pop_back();
2101f22ef01cSRoman Divacky }
2102f785676fSDimitry Andric
2103f785676fSDimitry Andric while (!FunctionPrefixWorklist.empty()) {
2104f785676fSDimitry Andric unsigned ValID = FunctionPrefixWorklist.back().second;
2105f785676fSDimitry Andric if (ValID >= ValueList.size()) {
2106f785676fSDimitry Andric FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2107f785676fSDimitry Andric } else {
210891bc56edSDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2109f785676fSDimitry Andric FunctionPrefixWorklist.back().first->setPrefixData(C);
2110f785676fSDimitry Andric else
21118f0fd8f6SDimitry Andric return error("Expected a constant");
2112f785676fSDimitry Andric }
2113f785676fSDimitry Andric FunctionPrefixWorklist.pop_back();
2114f785676fSDimitry Andric }
2115f785676fSDimitry Andric
211639d628a0SDimitry Andric while (!FunctionPrologueWorklist.empty()) {
211739d628a0SDimitry Andric unsigned ValID = FunctionPrologueWorklist.back().second;
211839d628a0SDimitry Andric if (ValID >= ValueList.size()) {
211939d628a0SDimitry Andric FunctionPrologues.push_back(FunctionPrologueWorklist.back());
212039d628a0SDimitry Andric } else {
212139d628a0SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
212239d628a0SDimitry Andric FunctionPrologueWorklist.back().first->setPrologueData(C);
212339d628a0SDimitry Andric else
21248f0fd8f6SDimitry Andric return error("Expected a constant");
212539d628a0SDimitry Andric }
212639d628a0SDimitry Andric FunctionPrologueWorklist.pop_back();
212739d628a0SDimitry Andric }
212839d628a0SDimitry Andric
21298f0fd8f6SDimitry Andric while (!FunctionPersonalityFnWorklist.empty()) {
21308f0fd8f6SDimitry Andric unsigned ValID = FunctionPersonalityFnWorklist.back().second;
21318f0fd8f6SDimitry Andric if (ValID >= ValueList.size()) {
21328f0fd8f6SDimitry Andric FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
21338f0fd8f6SDimitry Andric } else {
21348f0fd8f6SDimitry Andric if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
21358f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
21368f0fd8f6SDimitry Andric else
21378f0fd8f6SDimitry Andric return error("Expected a constant");
21388f0fd8f6SDimitry Andric }
21398f0fd8f6SDimitry Andric FunctionPersonalityFnWorklist.pop_back();
21408f0fd8f6SDimitry Andric }
21418f0fd8f6SDimitry Andric
2142d88c1a5aSDimitry Andric return Error::success();
2143f22ef01cSRoman Divacky }
2144f22ef01cSRoman Divacky
readWideAPInt(ArrayRef<uint64_t> Vals,unsigned TypeBits)21458f0fd8f6SDimitry Andric static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
21467ae0e2c9SDimitry Andric SmallVector<uint64_t, 8> Words(Vals.size());
2147d88c1a5aSDimitry Andric transform(Vals, Words.begin(),
21483861d79fSDimitry Andric BitcodeReader::decodeSignRotatedValue);
21497ae0e2c9SDimitry Andric
21507ae0e2c9SDimitry Andric return APInt(TypeBits, Words);
21517ae0e2c9SDimitry Andric }
21527ae0e2c9SDimitry Andric
parseConstants()2153d88c1a5aSDimitry Andric Error BitcodeReader::parseConstants() {
2154f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
21558f0fd8f6SDimitry Andric return error("Invalid record");
2156f22ef01cSRoman Divacky
2157f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record;
2158f22ef01cSRoman Divacky
2159f22ef01cSRoman Divacky // Read all the records for this value table.
21606122f3e6SDimitry Andric Type *CurTy = Type::getInt32Ty(Context);
2161f22ef01cSRoman Divacky unsigned NextCstNo = ValueList.size();
2162d88c1a5aSDimitry Andric
2163d88c1a5aSDimitry Andric while (true) {
2164139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2165139f7f9bSDimitry Andric
2166139f7f9bSDimitry Andric switch (Entry.Kind) {
2167139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
2168139f7f9bSDimitry Andric case BitstreamEntry::Error:
21698f0fd8f6SDimitry Andric return error("Malformed block");
2170139f7f9bSDimitry Andric case BitstreamEntry::EndBlock:
2171139f7f9bSDimitry Andric if (NextCstNo != ValueList.size())
21723ca95b02SDimitry Andric return error("Invalid constant reference");
2173139f7f9bSDimitry Andric
2174139f7f9bSDimitry Andric // Once all the constants have been read, go through and resolve forward
2175139f7f9bSDimitry Andric // references.
21768f0fd8f6SDimitry Andric ValueList.resolveConstantForwardRefs();
2177d88c1a5aSDimitry Andric return Error::success();
2178139f7f9bSDimitry Andric case BitstreamEntry::Record:
2179139f7f9bSDimitry Andric // The interesting case.
2180f22ef01cSRoman Divacky break;
2181f22ef01cSRoman Divacky }
2182f22ef01cSRoman Divacky
2183f22ef01cSRoman Divacky // Read a record.
2184f22ef01cSRoman Divacky Record.clear();
21853ca95b02SDimitry Andric Type *VoidType = Type::getVoidTy(Context);
218691bc56edSDimitry Andric Value *V = nullptr;
2187139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record);
2188f22ef01cSRoman Divacky switch (BitCode) {
2189f22ef01cSRoman Divacky default: // Default behavior: unknown constant
2190f22ef01cSRoman Divacky case bitc::CST_CODE_UNDEF: // UNDEF
2191f22ef01cSRoman Divacky V = UndefValue::get(CurTy);
2192f22ef01cSRoman Divacky break;
2193f22ef01cSRoman Divacky case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2194f22ef01cSRoman Divacky if (Record.empty())
21958f0fd8f6SDimitry Andric return error("Invalid record");
219691bc56edSDimitry Andric if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
21978f0fd8f6SDimitry Andric return error("Invalid record");
21983ca95b02SDimitry Andric if (TypeList[Record[0]] == VoidType)
21993ca95b02SDimitry Andric return error("Invalid constant type");
2200f22ef01cSRoman Divacky CurTy = TypeList[Record[0]];
2201f22ef01cSRoman Divacky continue; // Skip the ValueList manipulation.
2202f22ef01cSRoman Divacky case bitc::CST_CODE_NULL: // NULL
2203f22ef01cSRoman Divacky V = Constant::getNullValue(CurTy);
2204f22ef01cSRoman Divacky break;
2205f22ef01cSRoman Divacky case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2206f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty())
22078f0fd8f6SDimitry Andric return error("Invalid record");
22083861d79fSDimitry Andric V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2209f22ef01cSRoman Divacky break;
2210f22ef01cSRoman Divacky case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2211f22ef01cSRoman Divacky if (!CurTy->isIntegerTy() || Record.empty())
22128f0fd8f6SDimitry Andric return error("Invalid record");
2213f22ef01cSRoman Divacky
22148f0fd8f6SDimitry Andric APInt VInt =
22158f0fd8f6SDimitry Andric readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
22167ae0e2c9SDimitry Andric V = ConstantInt::get(Context, VInt);
22177ae0e2c9SDimitry Andric
2218f22ef01cSRoman Divacky break;
2219f22ef01cSRoman Divacky }
2220f22ef01cSRoman Divacky case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2221f22ef01cSRoman Divacky if (Record.empty())
22228f0fd8f6SDimitry Andric return error("Invalid record");
2223dff0c46cSDimitry Andric if (CurTy->isHalfTy())
2224d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2225139f7f9bSDimitry Andric APInt(16, (uint16_t)Record[0])));
2226dff0c46cSDimitry Andric else if (CurTy->isFloatTy())
2227d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2228139f7f9bSDimitry Andric APInt(32, (uint32_t)Record[0])));
2229f22ef01cSRoman Divacky else if (CurTy->isDoubleTy())
2230d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2231139f7f9bSDimitry Andric APInt(64, Record[0])));
2232f22ef01cSRoman Divacky else if (CurTy->isX86_FP80Ty()) {
2233f22ef01cSRoman Divacky // Bits are not stored the same way as a normal i80 APInt, compensate.
2234f22ef01cSRoman Divacky uint64_t Rearrange[2];
2235f22ef01cSRoman Divacky Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2236f22ef01cSRoman Divacky Rearrange[1] = Record[0] >> 48;
2237d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2238139f7f9bSDimitry Andric APInt(80, Rearrange)));
2239f22ef01cSRoman Divacky } else if (CurTy->isFP128Ty())
2240d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2241139f7f9bSDimitry Andric APInt(128, Record)));
2242f22ef01cSRoman Divacky else if (CurTy->isPPC_FP128Ty())
2243d88c1a5aSDimitry Andric V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2244139f7f9bSDimitry Andric APInt(128, Record)));
2245f22ef01cSRoman Divacky else
2246f22ef01cSRoman Divacky V = UndefValue::get(CurTy);
2247f22ef01cSRoman Divacky break;
2248f22ef01cSRoman Divacky }
2249f22ef01cSRoman Divacky
2250f22ef01cSRoman Divacky case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2251f22ef01cSRoman Divacky if (Record.empty())
22528f0fd8f6SDimitry Andric return error("Invalid record");
2253f22ef01cSRoman Divacky
2254f22ef01cSRoman Divacky unsigned Size = Record.size();
2255dff0c46cSDimitry Andric SmallVector<Constant*, 16> Elts;
2256f22ef01cSRoman Divacky
22576122f3e6SDimitry Andric if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2258f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i)
2259f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2260f22ef01cSRoman Divacky STy->getElementType(i)));
2261f22ef01cSRoman Divacky V = ConstantStruct::get(STy, Elts);
22626122f3e6SDimitry Andric } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
22636122f3e6SDimitry Andric Type *EltTy = ATy->getElementType();
2264f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i)
2265f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2266f22ef01cSRoman Divacky V = ConstantArray::get(ATy, Elts);
22676122f3e6SDimitry Andric } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
22686122f3e6SDimitry Andric Type *EltTy = VTy->getElementType();
2269f22ef01cSRoman Divacky for (unsigned i = 0; i != Size; ++i)
2270f22ef01cSRoman Divacky Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2271f22ef01cSRoman Divacky V = ConstantVector::get(Elts);
2272f22ef01cSRoman Divacky } else {
2273f22ef01cSRoman Divacky V = UndefValue::get(CurTy);
2274f22ef01cSRoman Divacky }
2275f22ef01cSRoman Divacky break;
2276f22ef01cSRoman Divacky }
2277dff0c46cSDimitry Andric case bitc::CST_CODE_STRING: // STRING: [values]
2278f22ef01cSRoman Divacky case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2279f22ef01cSRoman Divacky if (Record.empty())
22808f0fd8f6SDimitry Andric return error("Invalid record");
2281f22ef01cSRoman Divacky
22827ae0e2c9SDimitry Andric SmallString<16> Elts(Record.begin(), Record.end());
2283dff0c46cSDimitry Andric V = ConstantDataArray::getString(Context, Elts,
2284dff0c46cSDimitry Andric BitCode == bitc::CST_CODE_CSTRING);
2285f22ef01cSRoman Divacky break;
2286f22ef01cSRoman Divacky }
2287dff0c46cSDimitry Andric case bitc::CST_CODE_DATA: {// DATA: [n x value]
2288dff0c46cSDimitry Andric if (Record.empty())
22898f0fd8f6SDimitry Andric return error("Invalid record");
2290dff0c46cSDimitry Andric
2291dff0c46cSDimitry Andric Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2292dff0c46cSDimitry Andric if (EltTy->isIntegerTy(8)) {
2293dff0c46cSDimitry Andric SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2294dff0c46cSDimitry Andric if (isa<VectorType>(CurTy))
2295dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts);
2296dff0c46cSDimitry Andric else
2297dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts);
2298dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(16)) {
2299dff0c46cSDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2300dff0c46cSDimitry Andric if (isa<VectorType>(CurTy))
2301dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts);
2302dff0c46cSDimitry Andric else
2303dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts);
2304dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(32)) {
2305dff0c46cSDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2306dff0c46cSDimitry Andric if (isa<VectorType>(CurTy))
2307dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts);
2308dff0c46cSDimitry Andric else
2309dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts);
2310dff0c46cSDimitry Andric } else if (EltTy->isIntegerTy(64)) {
2311dff0c46cSDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2312dff0c46cSDimitry Andric if (isa<VectorType>(CurTy))
2313dff0c46cSDimitry Andric V = ConstantDataVector::get(Context, Elts);
2314dff0c46cSDimitry Andric else
2315dff0c46cSDimitry Andric V = ConstantDataArray::get(Context, Elts);
2316444ed5c5SDimitry Andric } else if (EltTy->isHalfTy()) {
2317444ed5c5SDimitry Andric SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2318444ed5c5SDimitry Andric if (isa<VectorType>(CurTy))
2319444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts);
2320444ed5c5SDimitry Andric else
2321444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts);
2322dff0c46cSDimitry Andric } else if (EltTy->isFloatTy()) {
2323444ed5c5SDimitry Andric SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2324dff0c46cSDimitry Andric if (isa<VectorType>(CurTy))
2325444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts);
2326dff0c46cSDimitry Andric else
2327444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts);
2328dff0c46cSDimitry Andric } else if (EltTy->isDoubleTy()) {
2329444ed5c5SDimitry Andric SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2330dff0c46cSDimitry Andric if (isa<VectorType>(CurTy))
2331444ed5c5SDimitry Andric V = ConstantDataVector::getFP(Context, Elts);
2332dff0c46cSDimitry Andric else
2333444ed5c5SDimitry Andric V = ConstantDataArray::getFP(Context, Elts);
2334dff0c46cSDimitry Andric } else {
23358f0fd8f6SDimitry Andric return error("Invalid type for value");
2336dff0c46cSDimitry Andric }
2337dff0c46cSDimitry Andric break;
2338dff0c46cSDimitry Andric }
2339*b5893f02SDimitry Andric case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
2340*b5893f02SDimitry Andric if (Record.size() < 2)
2341*b5893f02SDimitry Andric return error("Invalid record");
2342*b5893f02SDimitry Andric int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
2343*b5893f02SDimitry Andric if (Opc < 0) {
2344*b5893f02SDimitry Andric V = UndefValue::get(CurTy); // Unknown unop.
2345*b5893f02SDimitry Andric } else {
2346*b5893f02SDimitry Andric Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2347*b5893f02SDimitry Andric unsigned Flags = 0;
2348*b5893f02SDimitry Andric V = ConstantExpr::get(Opc, LHS, Flags);
2349*b5893f02SDimitry Andric }
2350*b5893f02SDimitry Andric break;
2351*b5893f02SDimitry Andric }
2352f22ef01cSRoman Divacky case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2353f785676fSDimitry Andric if (Record.size() < 3)
23548f0fd8f6SDimitry Andric return error("Invalid record");
23558f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2356f22ef01cSRoman Divacky if (Opc < 0) {
2357f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown binop.
2358f22ef01cSRoman Divacky } else {
2359f22ef01cSRoman Divacky Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2360f22ef01cSRoman Divacky Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2361f22ef01cSRoman Divacky unsigned Flags = 0;
2362f22ef01cSRoman Divacky if (Record.size() >= 4) {
2363f22ef01cSRoman Divacky if (Opc == Instruction::Add ||
2364f22ef01cSRoman Divacky Opc == Instruction::Sub ||
23652754fe60SDimitry Andric Opc == Instruction::Mul ||
23662754fe60SDimitry Andric Opc == Instruction::Shl) {
2367f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2368f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoSignedWrap;
2369f22ef01cSRoman Divacky if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2370f22ef01cSRoman Divacky Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
23712754fe60SDimitry Andric } else if (Opc == Instruction::SDiv ||
23722754fe60SDimitry Andric Opc == Instruction::UDiv ||
23732754fe60SDimitry Andric Opc == Instruction::LShr ||
23742754fe60SDimitry Andric Opc == Instruction::AShr) {
23752754fe60SDimitry Andric if (Record[3] & (1 << bitc::PEO_EXACT))
2376f22ef01cSRoman Divacky Flags |= SDivOperator::IsExact;
2377f22ef01cSRoman Divacky }
2378f22ef01cSRoman Divacky }
2379f22ef01cSRoman Divacky V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2380f22ef01cSRoman Divacky }
2381f22ef01cSRoman Divacky break;
2382f22ef01cSRoman Divacky }
2383f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2384f785676fSDimitry Andric if (Record.size() < 3)
23858f0fd8f6SDimitry Andric return error("Invalid record");
23868f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[0]);
2387f22ef01cSRoman Divacky if (Opc < 0) {
2388f22ef01cSRoman Divacky V = UndefValue::get(CurTy); // Unknown cast.
2389f22ef01cSRoman Divacky } else {
23906122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]);
2391f785676fSDimitry Andric if (!OpTy)
23928f0fd8f6SDimitry Andric return error("Invalid record");
2393f22ef01cSRoman Divacky Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2394f785676fSDimitry Andric V = UpgradeBitCastExpr(Opc, Op, CurTy);
2395f785676fSDimitry Andric if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2396f22ef01cSRoman Divacky }
2397f22ef01cSRoman Divacky break;
2398f22ef01cSRoman Divacky }
2399d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2400d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2401d88c1a5aSDimitry Andric case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2402d88c1a5aSDimitry Andric // operands]
2403ff0cc061SDimitry Andric unsigned OpNum = 0;
2404ff0cc061SDimitry Andric Type *PointeeType = nullptr;
2405d88c1a5aSDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2406d88c1a5aSDimitry Andric Record.size() % 2)
2407ff0cc061SDimitry Andric PointeeType = getTypeByID(Record[OpNum++]);
2408d88c1a5aSDimitry Andric
2409d88c1a5aSDimitry Andric bool InBounds = false;
2410d88c1a5aSDimitry Andric Optional<unsigned> InRangeIndex;
2411d88c1a5aSDimitry Andric if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2412d88c1a5aSDimitry Andric uint64_t Op = Record[OpNum++];
2413d88c1a5aSDimitry Andric InBounds = Op & 1;
2414d88c1a5aSDimitry Andric InRangeIndex = Op >> 1;
2415d88c1a5aSDimitry Andric } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2416d88c1a5aSDimitry Andric InBounds = true;
2417d88c1a5aSDimitry Andric
2418f22ef01cSRoman Divacky SmallVector<Constant*, 16> Elts;
2419ff0cc061SDimitry Andric while (OpNum != Record.size()) {
2420ff0cc061SDimitry Andric Type *ElTy = getTypeByID(Record[OpNum++]);
2421f785676fSDimitry Andric if (!ElTy)
24228f0fd8f6SDimitry Andric return error("Invalid record");
2423ff0cc061SDimitry Andric Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2424f22ef01cSRoman Divacky }
2425ff0cc061SDimitry Andric
2426ff0cc061SDimitry Andric if (PointeeType &&
2427ff0cc061SDimitry Andric PointeeType !=
2428d88c1a5aSDimitry Andric cast<PointerType>(Elts[0]->getType()->getScalarType())
2429ff0cc061SDimitry Andric ->getElementType())
24308f0fd8f6SDimitry Andric return error("Explicit gep operator type does not match pointee type "
2431ff0cc061SDimitry Andric "of pointer operand");
2432ff0cc061SDimitry Andric
24333ca95b02SDimitry Andric if (Elts.size() < 1)
24343ca95b02SDimitry Andric return error("Invalid gep with no operands");
24353ca95b02SDimitry Andric
24366122f3e6SDimitry Andric ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2437ff0cc061SDimitry Andric V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2438d88c1a5aSDimitry Andric InBounds, InRangeIndex);
2439f22ef01cSRoman Divacky break;
2440f22ef01cSRoman Divacky }
2441f785676fSDimitry Andric case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2442f785676fSDimitry Andric if (Record.size() < 3)
24438f0fd8f6SDimitry Andric return error("Invalid record");
2444f785676fSDimitry Andric
2445f785676fSDimitry Andric Type *SelectorTy = Type::getInt1Ty(Context);
2446f785676fSDimitry Andric
24477d523365SDimitry Andric // The selector might be an i1 or an <n x i1>
24487d523365SDimitry Andric // Get the type from the ValueList before getting a forward ref.
2449f785676fSDimitry Andric if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
24507d523365SDimitry Andric if (Value *V = ValueList[Record[0]])
24517d523365SDimitry Andric if (SelectorTy != V->getType())
24527d523365SDimitry Andric SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2453f785676fSDimitry Andric
2454f785676fSDimitry Andric V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2455f785676fSDimitry Andric SelectorTy),
2456f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[1],CurTy),
2457f22ef01cSRoman Divacky ValueList.getConstantFwdRef(Record[2],CurTy));
2458f22ef01cSRoman Divacky break;
2459f785676fSDimitry Andric }
246091bc56edSDimitry Andric case bitc::CST_CODE_CE_EXTRACTELT
246191bc56edSDimitry Andric : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2462f785676fSDimitry Andric if (Record.size() < 3)
24638f0fd8f6SDimitry Andric return error("Invalid record");
24646122f3e6SDimitry Andric VectorType *OpTy =
2465f22ef01cSRoman Divacky dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
246691bc56edSDimitry Andric if (!OpTy)
24678f0fd8f6SDimitry Andric return error("Invalid record");
2468f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
246991bc56edSDimitry Andric Constant *Op1 = nullptr;
247091bc56edSDimitry Andric if (Record.size() == 4) {
247191bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]);
247291bc56edSDimitry Andric if (!IdxTy)
24738f0fd8f6SDimitry Andric return error("Invalid record");
247491bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
247591bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0
247691bc56edSDimitry Andric Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
247791bc56edSDimitry Andric if (!Op1)
24788f0fd8f6SDimitry Andric return error("Invalid record");
2479f22ef01cSRoman Divacky V = ConstantExpr::getExtractElement(Op0, Op1);
2480f22ef01cSRoman Divacky break;
2481f22ef01cSRoman Divacky }
248291bc56edSDimitry Andric case bitc::CST_CODE_CE_INSERTELT
248391bc56edSDimitry Andric : { // CE_INSERTELT: [opval, opval, opty, opval]
24846122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy);
248591bc56edSDimitry Andric if (Record.size() < 3 || !OpTy)
24868f0fd8f6SDimitry Andric return error("Invalid record");
2487f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2488f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2489f22ef01cSRoman Divacky OpTy->getElementType());
249091bc56edSDimitry Andric Constant *Op2 = nullptr;
249191bc56edSDimitry Andric if (Record.size() == 4) {
249291bc56edSDimitry Andric Type *IdxTy = getTypeByID(Record[2]);
249391bc56edSDimitry Andric if (!IdxTy)
24948f0fd8f6SDimitry Andric return error("Invalid record");
249591bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
249691bc56edSDimitry Andric } else // TODO: Remove with llvm 4.0
249791bc56edSDimitry Andric Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
249891bc56edSDimitry Andric if (!Op2)
24998f0fd8f6SDimitry Andric return error("Invalid record");
2500f22ef01cSRoman Divacky V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2501f22ef01cSRoman Divacky break;
2502f22ef01cSRoman Divacky }
2503f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
25046122f3e6SDimitry Andric VectorType *OpTy = dyn_cast<VectorType>(CurTy);
250591bc56edSDimitry Andric if (Record.size() < 3 || !OpTy)
25068f0fd8f6SDimitry Andric return error("Invalid record");
2507f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2508f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
25096122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2510f22ef01cSRoman Divacky OpTy->getNumElements());
2511f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2512f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2513f22ef01cSRoman Divacky break;
2514f22ef01cSRoman Divacky }
2515f22ef01cSRoman Divacky case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
25166122f3e6SDimitry Andric VectorType *RTy = dyn_cast<VectorType>(CurTy);
25176122f3e6SDimitry Andric VectorType *OpTy =
25182754fe60SDimitry Andric dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
251991bc56edSDimitry Andric if (Record.size() < 4 || !RTy || !OpTy)
25208f0fd8f6SDimitry Andric return error("Invalid record");
2521f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2522f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
25236122f3e6SDimitry Andric Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2524f22ef01cSRoman Divacky RTy->getNumElements());
2525f22ef01cSRoman Divacky Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2526f22ef01cSRoman Divacky V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2527f22ef01cSRoman Divacky break;
2528f22ef01cSRoman Divacky }
2529f22ef01cSRoman Divacky case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2530f785676fSDimitry Andric if (Record.size() < 4)
25318f0fd8f6SDimitry Andric return error("Invalid record");
25326122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]);
253391bc56edSDimitry Andric if (!OpTy)
25348f0fd8f6SDimitry Andric return error("Invalid record");
2535f22ef01cSRoman Divacky Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2536f22ef01cSRoman Divacky Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2537f22ef01cSRoman Divacky
2538f22ef01cSRoman Divacky if (OpTy->isFPOrFPVectorTy())
2539f22ef01cSRoman Divacky V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2540f22ef01cSRoman Divacky else
2541f22ef01cSRoman Divacky V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2542f22ef01cSRoman Divacky break;
2543f22ef01cSRoman Divacky }
25443861d79fSDimitry Andric // This maintains backward compatibility, pre-asm dialect keywords.
25453861d79fSDimitry Andric // FIXME: Remove with the 4.0 release.
25463861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM_OLD: {
2547f785676fSDimitry Andric if (Record.size() < 2)
25488f0fd8f6SDimitry Andric return error("Invalid record");
2549f22ef01cSRoman Divacky std::string AsmStr, ConstrStr;
2550f22ef01cSRoman Divacky bool HasSideEffects = Record[0] & 1;
2551f22ef01cSRoman Divacky bool IsAlignStack = Record[0] >> 1;
2552f22ef01cSRoman Divacky unsigned AsmStrSize = Record[1];
2553f22ef01cSRoman Divacky if (2+AsmStrSize >= Record.size())
25548f0fd8f6SDimitry Andric return error("Invalid record");
2555f22ef01cSRoman Divacky unsigned ConstStrSize = Record[2+AsmStrSize];
2556f22ef01cSRoman Divacky if (3+AsmStrSize+ConstStrSize > Record.size())
25578f0fd8f6SDimitry Andric return error("Invalid record");
2558f22ef01cSRoman Divacky
2559f22ef01cSRoman Divacky for (unsigned i = 0; i != AsmStrSize; ++i)
2560f22ef01cSRoman Divacky AsmStr += (char)Record[2+i];
2561f22ef01cSRoman Divacky for (unsigned i = 0; i != ConstStrSize; ++i)
2562f22ef01cSRoman Divacky ConstrStr += (char)Record[3+AsmStrSize+i];
25636122f3e6SDimitry Andric PointerType *PTy = cast<PointerType>(CurTy);
25644ba319b5SDimitry Andric UpgradeInlineAsmString(&AsmStr);
2565f22ef01cSRoman Divacky V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2566f22ef01cSRoman Divacky AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2567f22ef01cSRoman Divacky break;
2568f22ef01cSRoman Divacky }
25693861d79fSDimitry Andric // This version adds support for the asm dialect keywords (e.g.,
25703861d79fSDimitry Andric // inteldialect).
25713861d79fSDimitry Andric case bitc::CST_CODE_INLINEASM: {
2572f785676fSDimitry Andric if (Record.size() < 2)
25738f0fd8f6SDimitry Andric return error("Invalid record");
25743861d79fSDimitry Andric std::string AsmStr, ConstrStr;
25753861d79fSDimitry Andric bool HasSideEffects = Record[0] & 1;
25763861d79fSDimitry Andric bool IsAlignStack = (Record[0] >> 1) & 1;
25773861d79fSDimitry Andric unsigned AsmDialect = Record[0] >> 2;
25783861d79fSDimitry Andric unsigned AsmStrSize = Record[1];
25793861d79fSDimitry Andric if (2+AsmStrSize >= Record.size())
25808f0fd8f6SDimitry Andric return error("Invalid record");
25813861d79fSDimitry Andric unsigned ConstStrSize = Record[2+AsmStrSize];
25823861d79fSDimitry Andric if (3+AsmStrSize+ConstStrSize > Record.size())
25838f0fd8f6SDimitry Andric return error("Invalid record");
25843861d79fSDimitry Andric
25853861d79fSDimitry Andric for (unsigned i = 0; i != AsmStrSize; ++i)
25863861d79fSDimitry Andric AsmStr += (char)Record[2+i];
25873861d79fSDimitry Andric for (unsigned i = 0; i != ConstStrSize; ++i)
25883861d79fSDimitry Andric ConstrStr += (char)Record[3+AsmStrSize+i];
25893861d79fSDimitry Andric PointerType *PTy = cast<PointerType>(CurTy);
25904ba319b5SDimitry Andric UpgradeInlineAsmString(&AsmStr);
25913861d79fSDimitry Andric V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
25923861d79fSDimitry Andric AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
25933861d79fSDimitry Andric InlineAsm::AsmDialect(AsmDialect));
25943861d79fSDimitry Andric break;
25953861d79fSDimitry Andric }
2596f22ef01cSRoman Divacky case bitc::CST_CODE_BLOCKADDRESS:{
2597f785676fSDimitry Andric if (Record.size() < 3)
25988f0fd8f6SDimitry Andric return error("Invalid record");
25996122f3e6SDimitry Andric Type *FnTy = getTypeByID(Record[0]);
260091bc56edSDimitry Andric if (!FnTy)
26018f0fd8f6SDimitry Andric return error("Invalid record");
2602f22ef01cSRoman Divacky Function *Fn =
2603f22ef01cSRoman Divacky dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
260491bc56edSDimitry Andric if (!Fn)
26058f0fd8f6SDimitry Andric return error("Invalid record");
260639d628a0SDimitry Andric
26073861d79fSDimitry Andric // If the function is already parsed we can insert the block address right
26083861d79fSDimitry Andric // away.
260939d628a0SDimitry Andric BasicBlock *BB;
261039d628a0SDimitry Andric unsigned BBID = Record[2];
261139d628a0SDimitry Andric if (!BBID)
261239d628a0SDimitry Andric // Invalid reference to entry block.
26138f0fd8f6SDimitry Andric return error("Invalid ID");
26143861d79fSDimitry Andric if (!Fn->empty()) {
26153861d79fSDimitry Andric Function::iterator BBI = Fn->begin(), BBE = Fn->end();
261639d628a0SDimitry Andric for (size_t I = 0, E = BBID; I != E; ++I) {
26173861d79fSDimitry Andric if (BBI == BBE)
26188f0fd8f6SDimitry Andric return error("Invalid ID");
26193861d79fSDimitry Andric ++BBI;
26203861d79fSDimitry Andric }
26217d523365SDimitry Andric BB = &*BBI;
26223861d79fSDimitry Andric } else {
26233861d79fSDimitry Andric // Otherwise insert a placeholder and remember it so it can be inserted
26243861d79fSDimitry Andric // when the function is parsed.
262539d628a0SDimitry Andric auto &FwdBBs = BasicBlockFwdRefs[Fn];
262639d628a0SDimitry Andric if (FwdBBs.empty())
262739d628a0SDimitry Andric BasicBlockFwdRefQueue.push_back(Fn);
262839d628a0SDimitry Andric if (FwdBBs.size() < BBID + 1)
262939d628a0SDimitry Andric FwdBBs.resize(BBID + 1);
263039d628a0SDimitry Andric if (!FwdBBs[BBID])
263139d628a0SDimitry Andric FwdBBs[BBID] = BasicBlock::Create(Context);
263239d628a0SDimitry Andric BB = FwdBBs[BBID];
26333861d79fSDimitry Andric }
263439d628a0SDimitry Andric V = BlockAddress::get(Fn, BB);
2635f22ef01cSRoman Divacky break;
2636f22ef01cSRoman Divacky }
2637f22ef01cSRoman Divacky }
2638f22ef01cSRoman Divacky
26398f0fd8f6SDimitry Andric ValueList.assignValue(V, NextCstNo);
2640f22ef01cSRoman Divacky ++NextCstNo;
2641f22ef01cSRoman Divacky }
2642f22ef01cSRoman Divacky }
2643f22ef01cSRoman Divacky
parseUseLists()2644d88c1a5aSDimitry Andric Error BitcodeReader::parseUseLists() {
2645dff0c46cSDimitry Andric if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
26468f0fd8f6SDimitry Andric return error("Invalid record");
2647dff0c46cSDimitry Andric
2648dff0c46cSDimitry Andric // Read all the records.
264939d628a0SDimitry Andric SmallVector<uint64_t, 64> Record;
2650d88c1a5aSDimitry Andric
2651d88c1a5aSDimitry Andric while (true) {
2652139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2653139f7f9bSDimitry Andric
2654139f7f9bSDimitry Andric switch (Entry.Kind) {
2655139f7f9bSDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
2656139f7f9bSDimitry Andric case BitstreamEntry::Error:
26578f0fd8f6SDimitry Andric return error("Malformed block");
2658139f7f9bSDimitry Andric case BitstreamEntry::EndBlock:
2659d88c1a5aSDimitry Andric return Error::success();
2660139f7f9bSDimitry Andric case BitstreamEntry::Record:
2661139f7f9bSDimitry Andric // The interesting case.
2662139f7f9bSDimitry Andric break;
2663dff0c46cSDimitry Andric }
2664dff0c46cSDimitry Andric
2665dff0c46cSDimitry Andric // Read a use list record.
2666dff0c46cSDimitry Andric Record.clear();
266739d628a0SDimitry Andric bool IsBB = false;
2668139f7f9bSDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) {
2669dff0c46cSDimitry Andric default: // Default behavior: unknown type.
2670dff0c46cSDimitry Andric break;
267139d628a0SDimitry Andric case bitc::USELIST_CODE_BB:
267239d628a0SDimitry Andric IsBB = true;
2673d88c1a5aSDimitry Andric LLVM_FALLTHROUGH;
267439d628a0SDimitry Andric case bitc::USELIST_CODE_DEFAULT: {
2675dff0c46cSDimitry Andric unsigned RecordLength = Record.size();
267639d628a0SDimitry Andric if (RecordLength < 3)
267739d628a0SDimitry Andric // Records should have at least an ID and two indexes.
26788f0fd8f6SDimitry Andric return error("Invalid record");
267939d628a0SDimitry Andric unsigned ID = Record.back();
268039d628a0SDimitry Andric Record.pop_back();
268139d628a0SDimitry Andric
268239d628a0SDimitry Andric Value *V;
268339d628a0SDimitry Andric if (IsBB) {
268439d628a0SDimitry Andric assert(ID < FunctionBBs.size() && "Basic block not found");
268539d628a0SDimitry Andric V = FunctionBBs[ID];
268639d628a0SDimitry Andric } else
268739d628a0SDimitry Andric V = ValueList[ID];
268839d628a0SDimitry Andric unsigned NumUses = 0;
268939d628a0SDimitry Andric SmallDenseMap<const Use *, unsigned, 16> Order;
26907d523365SDimitry Andric for (const Use &U : V->materialized_uses()) {
269139d628a0SDimitry Andric if (++NumUses > Record.size())
269239d628a0SDimitry Andric break;
269339d628a0SDimitry Andric Order[&U] = Record[NumUses - 1];
269439d628a0SDimitry Andric }
269539d628a0SDimitry Andric if (Order.size() != Record.size() || NumUses > Record.size())
269639d628a0SDimitry Andric // Mismatches can happen if the functions are being materialized lazily
269739d628a0SDimitry Andric // (out-of-order), or a value has been upgraded.
269839d628a0SDimitry Andric break;
269939d628a0SDimitry Andric
270039d628a0SDimitry Andric V->sortUseList([&](const Use &L, const Use &R) {
270139d628a0SDimitry Andric return Order.lookup(&L) < Order.lookup(&R);
270239d628a0SDimitry Andric });
2703dff0c46cSDimitry Andric break;
2704dff0c46cSDimitry Andric }
2705dff0c46cSDimitry Andric }
2706dff0c46cSDimitry Andric }
2707dff0c46cSDimitry Andric }
2708dff0c46cSDimitry Andric
2709ff0cc061SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it.
2710ff0cc061SDimitry Andric /// This lets us lazily deserialize the metadata.
rememberAndSkipMetadata()2711d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() {
2712ff0cc061SDimitry Andric // Save the current stream state.
2713ff0cc061SDimitry Andric uint64_t CurBit = Stream.GetCurrentBitNo();
2714ff0cc061SDimitry Andric DeferredMetadataInfo.push_back(CurBit);
2715ff0cc061SDimitry Andric
2716ff0cc061SDimitry Andric // Skip over the block for now.
2717ff0cc061SDimitry Andric if (Stream.SkipBlock())
27188f0fd8f6SDimitry Andric return error("Invalid record");
2719d88c1a5aSDimitry Andric return Error::success();
2720ff0cc061SDimitry Andric }
2721ff0cc061SDimitry Andric
materializeMetadata()2722d88c1a5aSDimitry Andric Error BitcodeReader::materializeMetadata() {
2723ff0cc061SDimitry Andric for (uint64_t BitPos : DeferredMetadataInfo) {
2724ff0cc061SDimitry Andric // Move the bit stream to the saved position.
2725ff0cc061SDimitry Andric Stream.JumpToBit(BitPos);
2726d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseModuleMetadata())
2727d88c1a5aSDimitry Andric return Err;
2728ff0cc061SDimitry Andric }
272924d58133SDimitry Andric
273024d58133SDimitry Andric // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
273124d58133SDimitry Andric // metadata.
273224d58133SDimitry Andric if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
273324d58133SDimitry Andric NamedMDNode *LinkerOpts =
273424d58133SDimitry Andric TheModule->getOrInsertNamedMetadata("llvm.linker.options");
273524d58133SDimitry Andric for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
273624d58133SDimitry Andric LinkerOpts->addOperand(cast<MDNode>(MDOptions));
273724d58133SDimitry Andric }
273824d58133SDimitry Andric
2739ff0cc061SDimitry Andric DeferredMetadataInfo.clear();
2740d88c1a5aSDimitry Andric return Error::success();
2741ff0cc061SDimitry Andric }
2742ff0cc061SDimitry Andric
setStripDebugInfo()2743ff0cc061SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2744ff0cc061SDimitry Andric
27458f0fd8f6SDimitry Andric /// When we see the block for a function body, remember where it is and then
27468f0fd8f6SDimitry Andric /// skip it. This lets us lazily deserialize the functions.
rememberAndSkipFunctionBody()2747d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() {
2748f22ef01cSRoman Divacky // Get the function we are talking about.
2749f22ef01cSRoman Divacky if (FunctionsWithBodies.empty())
27508f0fd8f6SDimitry Andric return error("Insufficient function protos");
2751f22ef01cSRoman Divacky
2752f22ef01cSRoman Divacky Function *Fn = FunctionsWithBodies.back();
2753f22ef01cSRoman Divacky FunctionsWithBodies.pop_back();
2754f22ef01cSRoman Divacky
2755f22ef01cSRoman Divacky // Save the current stream state.
2756f22ef01cSRoman Divacky uint64_t CurBit = Stream.GetCurrentBitNo();
27577d523365SDimitry Andric assert(
27587d523365SDimitry Andric (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
27597d523365SDimitry Andric "Mismatch between VST and scanned function offsets");
2760f22ef01cSRoman Divacky DeferredFunctionInfo[Fn] = CurBit;
2761f22ef01cSRoman Divacky
2762f22ef01cSRoman Divacky // Skip over the function block for now.
2763f22ef01cSRoman Divacky if (Stream.SkipBlock())
27648f0fd8f6SDimitry Andric return error("Invalid record");
2765d88c1a5aSDimitry Andric return Error::success();
2766f22ef01cSRoman Divacky }
2767f22ef01cSRoman Divacky
globalCleanup()2768d88c1a5aSDimitry Andric Error BitcodeReader::globalCleanup() {
2769f22ef01cSRoman Divacky // Patch the initializers for globals and aliases up.
2770d88c1a5aSDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits())
2771d88c1a5aSDimitry Andric return Err;
27723ca95b02SDimitry Andric if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
27738f0fd8f6SDimitry Andric return error("Malformed global initializer set");
2774f22ef01cSRoman Divacky
2775f22ef01cSRoman Divacky // Look for intrinsic functions which need to be upgraded at some point
27768f0fd8f6SDimitry Andric for (Function &F : *TheModule) {
27776bc11b14SDimitry Andric MDLoader->upgradeDebugIntrinsics(F);
2778f22ef01cSRoman Divacky Function *NewFn;
27798f0fd8f6SDimitry Andric if (UpgradeIntrinsicFunction(&F, NewFn))
27803dac3a9bSDimitry Andric UpgradedIntrinsics[&F] = NewFn;
27813ca95b02SDimitry Andric else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
27823ca95b02SDimitry Andric // Some types could be renamed during loading if several modules are
27833ca95b02SDimitry Andric // loaded in the same LLVMContext (LTO scenario). In this case we should
27843ca95b02SDimitry Andric // remangle intrinsics names as well.
27853ca95b02SDimitry Andric RemangledIntrinsics[&F] = Remangled.getValue();
2786f22ef01cSRoman Divacky }
2787f22ef01cSRoman Divacky
2788e580952dSDimitry Andric // Look for global variables which need to be renamed.
27898f0fd8f6SDimitry Andric for (GlobalVariable &GV : TheModule->globals())
27908f0fd8f6SDimitry Andric UpgradeGlobalVariable(&GV);
279191bc56edSDimitry Andric
2792f22ef01cSRoman Divacky // Force deallocation of memory for these vectors to favor the client that
2793f22ef01cSRoman Divacky // want lazy deserialization.
2794f22ef01cSRoman Divacky std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
27953ca95b02SDimitry Andric std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
27963ca95b02SDimitry Andric IndirectSymbolInits);
2797d88c1a5aSDimitry Andric return Error::success();
2798f22ef01cSRoman Divacky }
2799f22ef01cSRoman Divacky
28007d523365SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we
28017d523365SDimitry Andric /// either have an old bitcode file without a VST forward declaration record,
28027d523365SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous
28037d523365SDimitry Andric /// functions do not have a name and are therefore not in the VST.
rememberAndSkipFunctionBodies()2804d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() {
2805dff0c46cSDimitry Andric Stream.JumpToBit(NextUnreadBit);
28067d523365SDimitry Andric
28077d523365SDimitry Andric if (Stream.AtEndOfStream())
28087d523365SDimitry Andric return error("Could not find function in stream");
28097d523365SDimitry Andric
28107d523365SDimitry Andric if (!SeenFirstFunctionBody)
28117d523365SDimitry Andric return error("Trying to materialize functions before seeing function blocks");
28127d523365SDimitry Andric
28137d523365SDimitry Andric // An old bitcode file with the symbol table at the end would have
28147d523365SDimitry Andric // finished the parse greedily.
28157d523365SDimitry Andric assert(SeenValueSymbolTable);
28167d523365SDimitry Andric
28177d523365SDimitry Andric SmallVector<uint64_t, 64> Record;
28187d523365SDimitry Andric
2819d88c1a5aSDimitry Andric while (true) {
28207d523365SDimitry Andric BitstreamEntry Entry = Stream.advance();
28217d523365SDimitry Andric switch (Entry.Kind) {
28227d523365SDimitry Andric default:
28237d523365SDimitry Andric return error("Expect SubBlock");
28247d523365SDimitry Andric case BitstreamEntry::SubBlock:
28257d523365SDimitry Andric switch (Entry.ID) {
28267d523365SDimitry Andric default:
28277d523365SDimitry Andric return error("Expect function block");
28287d523365SDimitry Andric case bitc::FUNCTION_BLOCK_ID:
2829d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBody())
2830d88c1a5aSDimitry Andric return Err;
28317d523365SDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo();
2832d88c1a5aSDimitry Andric return Error::success();
28337d523365SDimitry Andric }
28347d523365SDimitry Andric }
28357d523365SDimitry Andric }
28367d523365SDimitry Andric }
28377d523365SDimitry Andric
readBlockInfo()2838d88c1a5aSDimitry Andric bool BitcodeReaderBase::readBlockInfo() {
2839d88c1a5aSDimitry Andric Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2840d88c1a5aSDimitry Andric if (!NewBlockInfo)
2841d88c1a5aSDimitry Andric return true;
2842d88c1a5aSDimitry Andric BlockInfo = std::move(*NewBlockInfo);
2843d88c1a5aSDimitry Andric return false;
28447d523365SDimitry Andric }
28457d523365SDimitry Andric
parseComdatRecord(ArrayRef<uint64_t> Record)28467a7e6055SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
28476bc11b14SDimitry Andric // v1: [selection_kind, name]
28486bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, selection_kind]
28496bc11b14SDimitry Andric StringRef Name;
28506bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record);
28516bc11b14SDimitry Andric
28522cab237bSDimitry Andric if (Record.empty())
28537a7e6055SDimitry Andric return error("Invalid record");
28547a7e6055SDimitry Andric Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
28556bc11b14SDimitry Andric std::string OldFormatName;
28566bc11b14SDimitry Andric if (!UseStrtab) {
28576bc11b14SDimitry Andric if (Record.size() < 2)
28586bc11b14SDimitry Andric return error("Invalid record");
28597a7e6055SDimitry Andric unsigned ComdatNameSize = Record[1];
28606bc11b14SDimitry Andric OldFormatName.reserve(ComdatNameSize);
28617a7e6055SDimitry Andric for (unsigned i = 0; i != ComdatNameSize; ++i)
28626bc11b14SDimitry Andric OldFormatName += (char)Record[2 + i];
28636bc11b14SDimitry Andric Name = OldFormatName;
28646bc11b14SDimitry Andric }
28657a7e6055SDimitry Andric Comdat *C = TheModule->getOrInsertComdat(Name);
28667a7e6055SDimitry Andric C->setSelectionKind(SK);
28677a7e6055SDimitry Andric ComdatList.push_back(C);
28687a7e6055SDimitry Andric return Error::success();
28697a7e6055SDimitry Andric }
28707a7e6055SDimitry Andric
inferDSOLocal(GlobalValue * GV)28714ba319b5SDimitry Andric static void inferDSOLocal(GlobalValue *GV) {
28724ba319b5SDimitry Andric // infer dso_local from linkage and visibility if it is not encoded.
28734ba319b5SDimitry Andric if (GV->hasLocalLinkage() ||
28744ba319b5SDimitry Andric (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
28754ba319b5SDimitry Andric GV->setDSOLocal(true);
28764ba319b5SDimitry Andric }
28774ba319b5SDimitry Andric
parseGlobalVarRecord(ArrayRef<uint64_t> Record)28787a7e6055SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
28796bc11b14SDimitry Andric // v1: [pointer type, isconst, initid, linkage, alignment, section,
28807a7e6055SDimitry Andric // visibility, threadlocal, unnamed_addr, externally_initialized,
28812cab237bSDimitry Andric // dllstorageclass, comdat, attributes, preemption specifier] (name in VST)
28826bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1]
28836bc11b14SDimitry Andric StringRef Name;
28846bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record);
28856bc11b14SDimitry Andric
28867a7e6055SDimitry Andric if (Record.size() < 6)
28877a7e6055SDimitry Andric return error("Invalid record");
28887a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[0]);
28897a7e6055SDimitry Andric if (!Ty)
28907a7e6055SDimitry Andric return error("Invalid record");
28917a7e6055SDimitry Andric bool isConstant = Record[1] & 1;
28927a7e6055SDimitry Andric bool explicitType = Record[1] & 2;
28937a7e6055SDimitry Andric unsigned AddressSpace;
28947a7e6055SDimitry Andric if (explicitType) {
28957a7e6055SDimitry Andric AddressSpace = Record[1] >> 2;
28967a7e6055SDimitry Andric } else {
28977a7e6055SDimitry Andric if (!Ty->isPointerTy())
28987a7e6055SDimitry Andric return error("Invalid type for value");
28997a7e6055SDimitry Andric AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
29007a7e6055SDimitry Andric Ty = cast<PointerType>(Ty)->getElementType();
29017a7e6055SDimitry Andric }
29027a7e6055SDimitry Andric
29037a7e6055SDimitry Andric uint64_t RawLinkage = Record[3];
29047a7e6055SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
29057a7e6055SDimitry Andric unsigned Alignment;
29067a7e6055SDimitry Andric if (Error Err = parseAlignmentValue(Record[4], Alignment))
29077a7e6055SDimitry Andric return Err;
29087a7e6055SDimitry Andric std::string Section;
29097a7e6055SDimitry Andric if (Record[5]) {
29107a7e6055SDimitry Andric if (Record[5] - 1 >= SectionTable.size())
29117a7e6055SDimitry Andric return error("Invalid ID");
29127a7e6055SDimitry Andric Section = SectionTable[Record[5] - 1];
29137a7e6055SDimitry Andric }
29147a7e6055SDimitry Andric GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
29157a7e6055SDimitry Andric // Local linkage must have default visibility.
29167a7e6055SDimitry Andric if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
29177a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0.
29187a7e6055SDimitry Andric Visibility = getDecodedVisibility(Record[6]);
29197a7e6055SDimitry Andric
29207a7e6055SDimitry Andric GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
29217a7e6055SDimitry Andric if (Record.size() > 7)
29227a7e6055SDimitry Andric TLM = getDecodedThreadLocalMode(Record[7]);
29237a7e6055SDimitry Andric
29247a7e6055SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
29257a7e6055SDimitry Andric if (Record.size() > 8)
29267a7e6055SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
29277a7e6055SDimitry Andric
29287a7e6055SDimitry Andric bool ExternallyInitialized = false;
29297a7e6055SDimitry Andric if (Record.size() > 9)
29307a7e6055SDimitry Andric ExternallyInitialized = Record[9];
29317a7e6055SDimitry Andric
29327a7e6055SDimitry Andric GlobalVariable *NewGV =
29336bc11b14SDimitry Andric new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
29347a7e6055SDimitry Andric nullptr, TLM, AddressSpace, ExternallyInitialized);
29357a7e6055SDimitry Andric NewGV->setAlignment(Alignment);
29367a7e6055SDimitry Andric if (!Section.empty())
29377a7e6055SDimitry Andric NewGV->setSection(Section);
29387a7e6055SDimitry Andric NewGV->setVisibility(Visibility);
29397a7e6055SDimitry Andric NewGV->setUnnamedAddr(UnnamedAddr);
29407a7e6055SDimitry Andric
29417a7e6055SDimitry Andric if (Record.size() > 10)
29427a7e6055SDimitry Andric NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
29437a7e6055SDimitry Andric else
29447a7e6055SDimitry Andric upgradeDLLImportExportLinkage(NewGV, RawLinkage);
29457a7e6055SDimitry Andric
29467a7e6055SDimitry Andric ValueList.push_back(NewGV);
29477a7e6055SDimitry Andric
29487a7e6055SDimitry Andric // Remember which value to use for the global initializer.
29497a7e6055SDimitry Andric if (unsigned InitID = Record[2])
29507a7e6055SDimitry Andric GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
29517a7e6055SDimitry Andric
29527a7e6055SDimitry Andric if (Record.size() > 11) {
29537a7e6055SDimitry Andric if (unsigned ComdatID = Record[11]) {
29547a7e6055SDimitry Andric if (ComdatID > ComdatList.size())
29557a7e6055SDimitry Andric return error("Invalid global variable comdat ID");
29567a7e6055SDimitry Andric NewGV->setComdat(ComdatList[ComdatID - 1]);
29577a7e6055SDimitry Andric }
29587a7e6055SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) {
29597a7e6055SDimitry Andric NewGV->setComdat(reinterpret_cast<Comdat *>(1));
29607a7e6055SDimitry Andric }
29615517e702SDimitry Andric
29625517e702SDimitry Andric if (Record.size() > 12) {
29635517e702SDimitry Andric auto AS = getAttributes(Record[12]).getFnAttributes();
29645517e702SDimitry Andric NewGV->setAttributes(AS);
29655517e702SDimitry Andric }
29662cab237bSDimitry Andric
29672cab237bSDimitry Andric if (Record.size() > 13) {
29682cab237bSDimitry Andric NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
29692cab237bSDimitry Andric }
29704ba319b5SDimitry Andric inferDSOLocal(NewGV);
29712cab237bSDimitry Andric
29727a7e6055SDimitry Andric return Error::success();
29737a7e6055SDimitry Andric }
29747a7e6055SDimitry Andric
parseFunctionRecord(ArrayRef<uint64_t> Record)29757a7e6055SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
29766bc11b14SDimitry Andric // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
29777a7e6055SDimitry Andric // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
2978*b5893f02SDimitry Andric // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
29796bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1]
29806bc11b14SDimitry Andric StringRef Name;
29816bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record);
29826bc11b14SDimitry Andric
29837a7e6055SDimitry Andric if (Record.size() < 8)
29847a7e6055SDimitry Andric return error("Invalid record");
29857a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[0]);
29867a7e6055SDimitry Andric if (!Ty)
29877a7e6055SDimitry Andric return error("Invalid record");
29887a7e6055SDimitry Andric if (auto *PTy = dyn_cast<PointerType>(Ty))
29897a7e6055SDimitry Andric Ty = PTy->getElementType();
29907a7e6055SDimitry Andric auto *FTy = dyn_cast<FunctionType>(Ty);
29917a7e6055SDimitry Andric if (!FTy)
29927a7e6055SDimitry Andric return error("Invalid type for value");
29937a7e6055SDimitry Andric auto CC = static_cast<CallingConv::ID>(Record[1]);
29947a7e6055SDimitry Andric if (CC & ~CallingConv::MaxID)
29957a7e6055SDimitry Andric return error("Invalid calling convention ID");
29967a7e6055SDimitry Andric
2997*b5893f02SDimitry Andric unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
2998*b5893f02SDimitry Andric if (Record.size() > 16)
2999*b5893f02SDimitry Andric AddrSpace = Record[16];
3000*b5893f02SDimitry Andric
3001*b5893f02SDimitry Andric Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3002*b5893f02SDimitry Andric AddrSpace, Name, TheModule);
30037a7e6055SDimitry Andric
30047a7e6055SDimitry Andric Func->setCallingConv(CC);
30057a7e6055SDimitry Andric bool isProto = Record[2];
30067a7e6055SDimitry Andric uint64_t RawLinkage = Record[3];
30077a7e6055SDimitry Andric Func->setLinkage(getDecodedLinkage(RawLinkage));
30087a7e6055SDimitry Andric Func->setAttributes(getAttributes(Record[4]));
30097a7e6055SDimitry Andric
30107a7e6055SDimitry Andric unsigned Alignment;
30117a7e6055SDimitry Andric if (Error Err = parseAlignmentValue(Record[5], Alignment))
30127a7e6055SDimitry Andric return Err;
30137a7e6055SDimitry Andric Func->setAlignment(Alignment);
30147a7e6055SDimitry Andric if (Record[6]) {
30157a7e6055SDimitry Andric if (Record[6] - 1 >= SectionTable.size())
30167a7e6055SDimitry Andric return error("Invalid ID");
30177a7e6055SDimitry Andric Func->setSection(SectionTable[Record[6] - 1]);
30187a7e6055SDimitry Andric }
30197a7e6055SDimitry Andric // Local linkage must have default visibility.
30207a7e6055SDimitry Andric if (!Func->hasLocalLinkage())
30217a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0.
30227a7e6055SDimitry Andric Func->setVisibility(getDecodedVisibility(Record[7]));
30237a7e6055SDimitry Andric if (Record.size() > 8 && Record[8]) {
30247a7e6055SDimitry Andric if (Record[8] - 1 >= GCTable.size())
30257a7e6055SDimitry Andric return error("Invalid ID");
30267a7e6055SDimitry Andric Func->setGC(GCTable[Record[8] - 1]);
30277a7e6055SDimitry Andric }
30287a7e6055SDimitry Andric GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
30297a7e6055SDimitry Andric if (Record.size() > 9)
30307a7e6055SDimitry Andric UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
30317a7e6055SDimitry Andric Func->setUnnamedAddr(UnnamedAddr);
30327a7e6055SDimitry Andric if (Record.size() > 10 && Record[10] != 0)
30337a7e6055SDimitry Andric FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
30347a7e6055SDimitry Andric
30357a7e6055SDimitry Andric if (Record.size() > 11)
30367a7e6055SDimitry Andric Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
30377a7e6055SDimitry Andric else
30387a7e6055SDimitry Andric upgradeDLLImportExportLinkage(Func, RawLinkage);
30397a7e6055SDimitry Andric
30407a7e6055SDimitry Andric if (Record.size() > 12) {
30417a7e6055SDimitry Andric if (unsigned ComdatID = Record[12]) {
30427a7e6055SDimitry Andric if (ComdatID > ComdatList.size())
30437a7e6055SDimitry Andric return error("Invalid function comdat ID");
30447a7e6055SDimitry Andric Func->setComdat(ComdatList[ComdatID - 1]);
30457a7e6055SDimitry Andric }
30467a7e6055SDimitry Andric } else if (hasImplicitComdat(RawLinkage)) {
30477a7e6055SDimitry Andric Func->setComdat(reinterpret_cast<Comdat *>(1));
30487a7e6055SDimitry Andric }
30497a7e6055SDimitry Andric
30507a7e6055SDimitry Andric if (Record.size() > 13 && Record[13] != 0)
30517a7e6055SDimitry Andric FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
30527a7e6055SDimitry Andric
30537a7e6055SDimitry Andric if (Record.size() > 14 && Record[14] != 0)
30547a7e6055SDimitry Andric FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
30557a7e6055SDimitry Andric
30562cab237bSDimitry Andric if (Record.size() > 15) {
30572cab237bSDimitry Andric Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
30582cab237bSDimitry Andric }
30594ba319b5SDimitry Andric inferDSOLocal(Func);
30602cab237bSDimitry Andric
30617a7e6055SDimitry Andric ValueList.push_back(Func);
30627a7e6055SDimitry Andric
30637a7e6055SDimitry Andric // If this is a function with a body, remember the prototype we are
30647a7e6055SDimitry Andric // creating now, so that we can match up the body with them later.
30657a7e6055SDimitry Andric if (!isProto) {
30667a7e6055SDimitry Andric Func->setIsMaterializable(true);
30677a7e6055SDimitry Andric FunctionsWithBodies.push_back(Func);
30687a7e6055SDimitry Andric DeferredFunctionInfo[Func] = 0;
30697a7e6055SDimitry Andric }
30707a7e6055SDimitry Andric return Error::success();
30717a7e6055SDimitry Andric }
30727a7e6055SDimitry Andric
parseGlobalIndirectSymbolRecord(unsigned BitCode,ArrayRef<uint64_t> Record)30737a7e6055SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord(
30747a7e6055SDimitry Andric unsigned BitCode, ArrayRef<uint64_t> Record) {
30756bc11b14SDimitry Andric // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
30766bc11b14SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
30772cab237bSDimitry Andric // dllstorageclass, threadlocal, unnamed_addr,
30782cab237bSDimitry Andric // preemption specifier] (name in VST)
30796bc11b14SDimitry Andric // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
30802cab237bSDimitry Andric // visibility, dllstorageclass, threadlocal, unnamed_addr,
30812cab237bSDimitry Andric // preemption specifier] (name in VST)
30826bc11b14SDimitry Andric // v2: [strtab_offset, strtab_size, v1]
30836bc11b14SDimitry Andric StringRef Name;
30846bc11b14SDimitry Andric std::tie(Name, Record) = readNameFromStrtab(Record);
30856bc11b14SDimitry Andric
30867a7e6055SDimitry Andric bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
30877a7e6055SDimitry Andric if (Record.size() < (3 + (unsigned)NewRecord))
30887a7e6055SDimitry Andric return error("Invalid record");
30897a7e6055SDimitry Andric unsigned OpNum = 0;
30907a7e6055SDimitry Andric Type *Ty = getTypeByID(Record[OpNum++]);
30917a7e6055SDimitry Andric if (!Ty)
30927a7e6055SDimitry Andric return error("Invalid record");
30937a7e6055SDimitry Andric
30947a7e6055SDimitry Andric unsigned AddrSpace;
30957a7e6055SDimitry Andric if (!NewRecord) {
30967a7e6055SDimitry Andric auto *PTy = dyn_cast<PointerType>(Ty);
30977a7e6055SDimitry Andric if (!PTy)
30987a7e6055SDimitry Andric return error("Invalid type for value");
30997a7e6055SDimitry Andric Ty = PTy->getElementType();
31007a7e6055SDimitry Andric AddrSpace = PTy->getAddressSpace();
31017a7e6055SDimitry Andric } else {
31027a7e6055SDimitry Andric AddrSpace = Record[OpNum++];
31037a7e6055SDimitry Andric }
31047a7e6055SDimitry Andric
31057a7e6055SDimitry Andric auto Val = Record[OpNum++];
31067a7e6055SDimitry Andric auto Linkage = Record[OpNum++];
31077a7e6055SDimitry Andric GlobalIndirectSymbol *NewGA;
31087a7e6055SDimitry Andric if (BitCode == bitc::MODULE_CODE_ALIAS ||
31097a7e6055SDimitry Andric BitCode == bitc::MODULE_CODE_ALIAS_OLD)
31106bc11b14SDimitry Andric NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
31117a7e6055SDimitry Andric TheModule);
31127a7e6055SDimitry Andric else
31136bc11b14SDimitry Andric NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
31147a7e6055SDimitry Andric nullptr, TheModule);
31157a7e6055SDimitry Andric // Old bitcode files didn't have visibility field.
31167a7e6055SDimitry Andric // Local linkage must have default visibility.
31177a7e6055SDimitry Andric if (OpNum != Record.size()) {
31187a7e6055SDimitry Andric auto VisInd = OpNum++;
31197a7e6055SDimitry Andric if (!NewGA->hasLocalLinkage())
31207a7e6055SDimitry Andric // FIXME: Change to an error if non-default in 4.0.
31217a7e6055SDimitry Andric NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
31227a7e6055SDimitry Andric }
31234ba319b5SDimitry Andric if (BitCode == bitc::MODULE_CODE_ALIAS ||
31244ba319b5SDimitry Andric BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
31257a7e6055SDimitry Andric if (OpNum != Record.size())
31267a7e6055SDimitry Andric NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
31277a7e6055SDimitry Andric else
31287a7e6055SDimitry Andric upgradeDLLImportExportLinkage(NewGA, Linkage);
31297a7e6055SDimitry Andric if (OpNum != Record.size())
31307a7e6055SDimitry Andric NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
31317a7e6055SDimitry Andric if (OpNum != Record.size())
31327a7e6055SDimitry Andric NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
31334ba319b5SDimitry Andric }
31342cab237bSDimitry Andric if (OpNum != Record.size())
31352cab237bSDimitry Andric NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
31364ba319b5SDimitry Andric inferDSOLocal(NewGA);
31374ba319b5SDimitry Andric
31387a7e6055SDimitry Andric ValueList.push_back(NewGA);
31397a7e6055SDimitry Andric IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
31407a7e6055SDimitry Andric return Error::success();
31417a7e6055SDimitry Andric }
31427a7e6055SDimitry Andric
parseModule(uint64_t ResumeBit,bool ShouldLazyLoadMetadata)3143d88c1a5aSDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit,
31447d523365SDimitry Andric bool ShouldLazyLoadMetadata) {
31457d523365SDimitry Andric if (ResumeBit)
31467d523365SDimitry Andric Stream.JumpToBit(ResumeBit);
3147dff0c46cSDimitry Andric else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
31488f0fd8f6SDimitry Andric return error("Invalid record");
3149dff0c46cSDimitry Andric
3150dff0c46cSDimitry Andric SmallVector<uint64_t, 64> Record;
3151dff0c46cSDimitry Andric
3152dff0c46cSDimitry Andric // Read all the records for this module.
3153d88c1a5aSDimitry Andric while (true) {
3154139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance();
3155dff0c46cSDimitry Andric
3156139f7f9bSDimitry Andric switch (Entry.Kind) {
3157139f7f9bSDimitry Andric case BitstreamEntry::Error:
31588f0fd8f6SDimitry Andric return error("Malformed block");
3159139f7f9bSDimitry Andric case BitstreamEntry::EndBlock:
31608f0fd8f6SDimitry Andric return globalCleanup();
3161dff0c46cSDimitry Andric
3162139f7f9bSDimitry Andric case BitstreamEntry::SubBlock:
3163139f7f9bSDimitry Andric switch (Entry.ID) {
3164f22ef01cSRoman Divacky default: // Skip unknown content.
3165f22ef01cSRoman Divacky if (Stream.SkipBlock())
31668f0fd8f6SDimitry Andric return error("Invalid record");
3167f22ef01cSRoman Divacky break;
3168f22ef01cSRoman Divacky case bitc::BLOCKINFO_BLOCK_ID:
3169d88c1a5aSDimitry Andric if (readBlockInfo())
31708f0fd8f6SDimitry Andric return error("Malformed block");
3171f22ef01cSRoman Divacky break;
3172f22ef01cSRoman Divacky case bitc::PARAMATTR_BLOCK_ID:
3173d88c1a5aSDimitry Andric if (Error Err = parseAttributeBlock())
3174d88c1a5aSDimitry Andric return Err;
3175f22ef01cSRoman Divacky break;
3176139f7f9bSDimitry Andric case bitc::PARAMATTR_GROUP_BLOCK_ID:
3177d88c1a5aSDimitry Andric if (Error Err = parseAttributeGroupBlock())
3178d88c1a5aSDimitry Andric return Err;
3179139f7f9bSDimitry Andric break;
318017a519f9SDimitry Andric case bitc::TYPE_BLOCK_ID_NEW:
3181d88c1a5aSDimitry Andric if (Error Err = parseTypeTable())
3182d88c1a5aSDimitry Andric return Err;
3183f22ef01cSRoman Divacky break;
3184f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID:
31857d523365SDimitry Andric if (!SeenValueSymbolTable) {
31867d523365SDimitry Andric // Either this is an old form VST without function index and an
31877d523365SDimitry Andric // associated VST forward declaration record (which would have caused
31887d523365SDimitry Andric // the VST to be jumped to and parsed before it was encountered
31897d523365SDimitry Andric // normally in the stream), or there were no function blocks to
31907d523365SDimitry Andric // trigger an earlier parsing of the VST.
31917d523365SDimitry Andric assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3192d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable())
3193d88c1a5aSDimitry Andric return Err;
3194dff0c46cSDimitry Andric SeenValueSymbolTable = true;
31957d523365SDimitry Andric } else {
31967d523365SDimitry Andric // We must have had a VST forward declaration record, which caused
31977d523365SDimitry Andric // the parser to jump to and parse the VST earlier.
31987d523365SDimitry Andric assert(VSTOffset > 0);
31997d523365SDimitry Andric if (Stream.SkipBlock())
32007d523365SDimitry Andric return error("Invalid record");
32017d523365SDimitry Andric }
3202f22ef01cSRoman Divacky break;
3203f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID:
3204d88c1a5aSDimitry Andric if (Error Err = parseConstants())
3205d88c1a5aSDimitry Andric return Err;
3206d88c1a5aSDimitry Andric if (Error Err = resolveGlobalAndIndirectSymbolInits())
3207d88c1a5aSDimitry Andric return Err;
3208f22ef01cSRoman Divacky break;
3209f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID:
3210d88c1a5aSDimitry Andric if (ShouldLazyLoadMetadata) {
3211d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipMetadata())
3212d88c1a5aSDimitry Andric return Err;
3213ff0cc061SDimitry Andric break;
3214ff0cc061SDimitry Andric }
3215ff0cc061SDimitry Andric assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3216d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseModuleMetadata())
3217d88c1a5aSDimitry Andric return Err;
32187d523365SDimitry Andric break;
32197d523365SDimitry Andric case bitc::METADATA_KIND_BLOCK_ID:
3220d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseMetadataKinds())
3221d88c1a5aSDimitry Andric return Err;
3222f22ef01cSRoman Divacky break;
3223f22ef01cSRoman Divacky case bitc::FUNCTION_BLOCK_ID:
3224f22ef01cSRoman Divacky // If this is the first function body we've seen, reverse the
3225f22ef01cSRoman Divacky // FunctionsWithBodies list.
3226dff0c46cSDimitry Andric if (!SeenFirstFunctionBody) {
3227f22ef01cSRoman Divacky std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3228d88c1a5aSDimitry Andric if (Error Err = globalCleanup())
3229d88c1a5aSDimitry Andric return Err;
3230dff0c46cSDimitry Andric SeenFirstFunctionBody = true;
3231f22ef01cSRoman Divacky }
3232f22ef01cSRoman Divacky
32337d523365SDimitry Andric if (VSTOffset > 0) {
32347d523365SDimitry Andric // If we have a VST forward declaration record, make sure we
32357d523365SDimitry Andric // parse the VST now if we haven't already. It is needed to
32367d523365SDimitry Andric // set up the DeferredFunctionInfo vector for lazy reading.
32377d523365SDimitry Andric if (!SeenValueSymbolTable) {
3238d88c1a5aSDimitry Andric if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3239d88c1a5aSDimitry Andric return Err;
32407d523365SDimitry Andric SeenValueSymbolTable = true;
32417d523365SDimitry Andric // Fall through so that we record the NextUnreadBit below.
32427d523365SDimitry Andric // This is necessary in case we have an anonymous function that
32437d523365SDimitry Andric // is later materialized. Since it will not have a VST entry we
32447d523365SDimitry Andric // need to fall back to the lazy parse to find its offset.
32457d523365SDimitry Andric } else {
32467d523365SDimitry Andric // If we have a VST forward declaration record, but have already
32477d523365SDimitry Andric // parsed the VST (just above, when the first function body was
32487d523365SDimitry Andric // encountered here), then we are resuming the parse after
32497d523365SDimitry Andric // materializing functions. The ResumeBit points to the
32507d523365SDimitry Andric // start of the last function block recorded in the
32517d523365SDimitry Andric // DeferredFunctionInfo map. Skip it.
32527d523365SDimitry Andric if (Stream.SkipBlock())
32537d523365SDimitry Andric return error("Invalid record");
32547d523365SDimitry Andric continue;
32557d523365SDimitry Andric }
32567d523365SDimitry Andric }
32577d523365SDimitry Andric
32587d523365SDimitry Andric // Support older bitcode files that did not have the function
32597d523365SDimitry Andric // index in the VST, nor a VST forward declaration record, as
32607d523365SDimitry Andric // well as anonymous functions that do not have VST entries.
32617d523365SDimitry Andric // Build the DeferredFunctionInfo vector on the fly.
3262d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBody())
3263d88c1a5aSDimitry Andric return Err;
32647d523365SDimitry Andric
32653dac3a9bSDimitry Andric // Suspend parsing when we reach the function bodies. Subsequent
32663dac3a9bSDimitry Andric // materialization calls will resume it when necessary. If the bitcode
32673dac3a9bSDimitry Andric // file is old, the symbol table will be at the end instead and will not
32683dac3a9bSDimitry Andric // have been seen yet. In this case, just finish the parse now.
32693dac3a9bSDimitry Andric if (SeenValueSymbolTable) {
3270dff0c46cSDimitry Andric NextUnreadBit = Stream.GetCurrentBitNo();
3271d88c1a5aSDimitry Andric // After the VST has been parsed, we need to make sure intrinsic name
3272d88c1a5aSDimitry Andric // are auto-upgraded.
3273d88c1a5aSDimitry Andric return globalCleanup();
3274dff0c46cSDimitry Andric }
3275dff0c46cSDimitry Andric break;
3276dff0c46cSDimitry Andric case bitc::USELIST_BLOCK_ID:
3277d88c1a5aSDimitry Andric if (Error Err = parseUseLists())
3278d88c1a5aSDimitry Andric return Err;
3279f22ef01cSRoman Divacky break;
32807d523365SDimitry Andric case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3281d88c1a5aSDimitry Andric if (Error Err = parseOperandBundleTags())
3282d88c1a5aSDimitry Andric return Err;
32837d523365SDimitry Andric break;
3284c4394386SDimitry Andric case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3285c4394386SDimitry Andric if (Error Err = parseSyncScopeNames())
3286c4394386SDimitry Andric return Err;
3287c4394386SDimitry Andric break;
3288f22ef01cSRoman Divacky }
3289f22ef01cSRoman Divacky continue;
3290139f7f9bSDimitry Andric
3291139f7f9bSDimitry Andric case BitstreamEntry::Record:
3292139f7f9bSDimitry Andric // The interesting case.
3293139f7f9bSDimitry Andric break;
3294f22ef01cSRoman Divacky }
3295f22ef01cSRoman Divacky
3296f22ef01cSRoman Divacky // Read a record.
32977d523365SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record);
32987d523365SDimitry Andric switch (BitCode) {
3299f22ef01cSRoman Divacky default: break; // Default behavior, ignore unknown content.
33007a7e6055SDimitry Andric case bitc::MODULE_CODE_VERSION: {
33017a7e6055SDimitry Andric Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
33027a7e6055SDimitry Andric if (!VersionOrErr)
33037a7e6055SDimitry Andric return VersionOrErr.takeError();
33047a7e6055SDimitry Andric UseRelativeIDs = *VersionOrErr >= 1;
33053861d79fSDimitry Andric break;
33063861d79fSDimitry Andric }
3307f22ef01cSRoman Divacky case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
3308f22ef01cSRoman Divacky std::string S;
33098f0fd8f6SDimitry Andric if (convertToString(Record, 0, S))
33108f0fd8f6SDimitry Andric return error("Invalid record");
3311f22ef01cSRoman Divacky TheModule->setTargetTriple(S);
3312f22ef01cSRoman Divacky break;
3313f22ef01cSRoman Divacky }
3314f22ef01cSRoman Divacky case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
3315f22ef01cSRoman Divacky std::string S;
33168f0fd8f6SDimitry Andric if (convertToString(Record, 0, S))
33178f0fd8f6SDimitry Andric return error("Invalid record");
3318f22ef01cSRoman Divacky TheModule->setDataLayout(S);
3319f22ef01cSRoman Divacky break;
3320f22ef01cSRoman Divacky }
3321f22ef01cSRoman Divacky case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
3322f22ef01cSRoman Divacky std::string S;
33238f0fd8f6SDimitry Andric if (convertToString(Record, 0, S))
33248f0fd8f6SDimitry Andric return error("Invalid record");
3325f22ef01cSRoman Divacky TheModule->setModuleInlineAsm(S);
3326f22ef01cSRoman Divacky break;
3327f22ef01cSRoman Divacky }
3328f22ef01cSRoman Divacky case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3329139f7f9bSDimitry Andric // FIXME: Remove in 4.0.
3330f22ef01cSRoman Divacky std::string S;
33318f0fd8f6SDimitry Andric if (convertToString(Record, 0, S))
33328f0fd8f6SDimitry Andric return error("Invalid record");
3333139f7f9bSDimitry Andric // Ignore value.
3334f22ef01cSRoman Divacky break;
3335f22ef01cSRoman Divacky }
3336f22ef01cSRoman Divacky case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
3337f22ef01cSRoman Divacky std::string S;
33388f0fd8f6SDimitry Andric if (convertToString(Record, 0, S))
33398f0fd8f6SDimitry Andric return error("Invalid record");
3340f22ef01cSRoman Divacky SectionTable.push_back(S);
3341f22ef01cSRoman Divacky break;
3342f22ef01cSRoman Divacky }
3343f22ef01cSRoman Divacky case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
3344f22ef01cSRoman Divacky std::string S;
33458f0fd8f6SDimitry Andric if (convertToString(Record, 0, S))
33468f0fd8f6SDimitry Andric return error("Invalid record");
3347f22ef01cSRoman Divacky GCTable.push_back(S);
3348f22ef01cSRoman Divacky break;
3349f22ef01cSRoman Divacky }
33502cab237bSDimitry Andric case bitc::MODULE_CODE_COMDAT:
33517a7e6055SDimitry Andric if (Error Err = parseComdatRecord(Record))
33527a7e6055SDimitry Andric return Err;
335391bc56edSDimitry Andric break;
33542cab237bSDimitry Andric case bitc::MODULE_CODE_GLOBALVAR:
33557a7e6055SDimitry Andric if (Error Err = parseGlobalVarRecord(Record))
3356d88c1a5aSDimitry Andric return Err;
3357f22ef01cSRoman Divacky break;
33582cab237bSDimitry Andric case bitc::MODULE_CODE_FUNCTION:
33597a7e6055SDimitry Andric if (Error Err = parseFunctionRecord(Record))
3360d88c1a5aSDimitry Andric return Err;
3361f22ef01cSRoman Divacky break;
33623ca95b02SDimitry Andric case bitc::MODULE_CODE_IFUNC:
33637d523365SDimitry Andric case bitc::MODULE_CODE_ALIAS:
33642cab237bSDimitry Andric case bitc::MODULE_CODE_ALIAS_OLD:
33657a7e6055SDimitry Andric if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
33667a7e6055SDimitry Andric return Err;
3367f22ef01cSRoman Divacky break;
33687d523365SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset]
33697d523365SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET:
33707d523365SDimitry Andric if (Record.size() < 1)
33717d523365SDimitry Andric return error("Invalid record");
3372d88c1a5aSDimitry Andric // Note that we subtract 1 here because the offset is relative to one word
3373d88c1a5aSDimitry Andric // before the start of the identification or module block, which was
3374d88c1a5aSDimitry Andric // historically always the start of the regular bitcode header.
3375d88c1a5aSDimitry Andric VSTOffset = Record[0] - 1;
33767d523365SDimitry Andric break;
33773ca95b02SDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
33783ca95b02SDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME:
33793ca95b02SDimitry Andric SmallString<128> ValueName;
33803ca95b02SDimitry Andric if (convertToString(Record, 0, ValueName))
33817d523365SDimitry Andric return error("Invalid record");
33823ca95b02SDimitry Andric TheModule->setSourceFileName(ValueName);
33837d523365SDimitry Andric break;
3384f22ef01cSRoman Divacky }
3385f22ef01cSRoman Divacky Record.clear();
3386f22ef01cSRoman Divacky }
3387f22ef01cSRoman Divacky }
3388f22ef01cSRoman Divacky
parseBitcodeInto(Module * M,bool ShouldLazyLoadMetadata,bool IsImporting)3389d88c1a5aSDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3390d88c1a5aSDimitry Andric bool IsImporting) {
33918f0fd8f6SDimitry Andric TheModule = M;
3392d88c1a5aSDimitry Andric MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3393d88c1a5aSDimitry Andric [&](unsigned ID) { return getTypeByID(ID); });
33947d523365SDimitry Andric return parseModule(0, ShouldLazyLoadMetadata);
3395f22ef01cSRoman Divacky }
3396f22ef01cSRoman Divacky
typeCheckLoadStoreInst(Type * ValType,Type * PtrType)3397d88c1a5aSDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3398ff0cc061SDimitry Andric if (!isa<PointerType>(PtrType))
3399d88c1a5aSDimitry Andric return error("Load/Store operand is not a pointer type");
3400ff0cc061SDimitry Andric Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3401ff0cc061SDimitry Andric
3402ff0cc061SDimitry Andric if (ValType && ValType != ElemType)
3403d88c1a5aSDimitry Andric return error("Explicit load/store type does not match pointee "
34047d523365SDimitry Andric "type of pointer operand");
3405ff0cc061SDimitry Andric if (!PointerType::isLoadableOrStorableType(ElemType))
3406d88c1a5aSDimitry Andric return error("Cannot load/store from pointer");
3407d88c1a5aSDimitry Andric return Error::success();
3408ff0cc061SDimitry Andric }
3409ff0cc061SDimitry Andric
34108f0fd8f6SDimitry Andric /// Lazily parse the specified function body block.
parseFunctionBody(Function * F)3411d88c1a5aSDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) {
3412f22ef01cSRoman Divacky if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
34138f0fd8f6SDimitry Andric return error("Invalid record");
3414f22ef01cSRoman Divacky
34153ca95b02SDimitry Andric // Unexpected unresolved metadata when parsing function.
3416d88c1a5aSDimitry Andric if (MDLoader->hasFwdRefs())
34173ca95b02SDimitry Andric return error("Invalid function metadata: incoming forward references");
34183ca95b02SDimitry Andric
3419f22ef01cSRoman Divacky InstructionList.clear();
3420f22ef01cSRoman Divacky unsigned ModuleValueListSize = ValueList.size();
3421d88c1a5aSDimitry Andric unsigned ModuleMDLoaderSize = MDLoader->size();
3422f22ef01cSRoman Divacky
3423f22ef01cSRoman Divacky // Add all the function arguments to the value table.
34247d523365SDimitry Andric for (Argument &I : F->args())
34257d523365SDimitry Andric ValueList.push_back(&I);
3426f22ef01cSRoman Divacky
3427f22ef01cSRoman Divacky unsigned NextValueNo = ValueList.size();
342891bc56edSDimitry Andric BasicBlock *CurBB = nullptr;
3429f22ef01cSRoman Divacky unsigned CurBBNo = 0;
3430f22ef01cSRoman Divacky
3431f22ef01cSRoman Divacky DebugLoc LastLoc;
343239d628a0SDimitry Andric auto getLastInstruction = [&]() -> Instruction * {
343339d628a0SDimitry Andric if (CurBB && !CurBB->empty())
343439d628a0SDimitry Andric return &CurBB->back();
343539d628a0SDimitry Andric else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
343639d628a0SDimitry Andric !FunctionBBs[CurBBNo - 1]->empty())
343739d628a0SDimitry Andric return &FunctionBBs[CurBBNo - 1]->back();
343839d628a0SDimitry Andric return nullptr;
343939d628a0SDimitry Andric };
3440f22ef01cSRoman Divacky
34417d523365SDimitry Andric std::vector<OperandBundleDef> OperandBundles;
34427d523365SDimitry Andric
3443f22ef01cSRoman Divacky // Read all the records.
3444f22ef01cSRoman Divacky SmallVector<uint64_t, 64> Record;
3445d88c1a5aSDimitry Andric
3446d88c1a5aSDimitry Andric while (true) {
3447139f7f9bSDimitry Andric BitstreamEntry Entry = Stream.advance();
3448f22ef01cSRoman Divacky
3449139f7f9bSDimitry Andric switch (Entry.Kind) {
3450139f7f9bSDimitry Andric case BitstreamEntry::Error:
34518f0fd8f6SDimitry Andric return error("Malformed block");
3452139f7f9bSDimitry Andric case BitstreamEntry::EndBlock:
3453139f7f9bSDimitry Andric goto OutOfRecordLoop;
3454139f7f9bSDimitry Andric
3455139f7f9bSDimitry Andric case BitstreamEntry::SubBlock:
3456139f7f9bSDimitry Andric switch (Entry.ID) {
3457f22ef01cSRoman Divacky default: // Skip unknown content.
3458f22ef01cSRoman Divacky if (Stream.SkipBlock())
34598f0fd8f6SDimitry Andric return error("Invalid record");
3460f22ef01cSRoman Divacky break;
3461f22ef01cSRoman Divacky case bitc::CONSTANTS_BLOCK_ID:
3462d88c1a5aSDimitry Andric if (Error Err = parseConstants())
3463d88c1a5aSDimitry Andric return Err;
3464f22ef01cSRoman Divacky NextValueNo = ValueList.size();
3465f22ef01cSRoman Divacky break;
3466f22ef01cSRoman Divacky case bitc::VALUE_SYMTAB_BLOCK_ID:
3467d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable())
3468d88c1a5aSDimitry Andric return Err;
3469f22ef01cSRoman Divacky break;
3470f22ef01cSRoman Divacky case bitc::METADATA_ATTACHMENT_ID:
3471d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3472d88c1a5aSDimitry Andric return Err;
3473f22ef01cSRoman Divacky break;
3474f22ef01cSRoman Divacky case bitc::METADATA_BLOCK_ID:
3475d88c1a5aSDimitry Andric assert(DeferredMetadataInfo.empty() &&
3476d88c1a5aSDimitry Andric "Must read all module-level metadata before function-level");
3477d88c1a5aSDimitry Andric if (Error Err = MDLoader->parseFunctionMetadata())
3478d88c1a5aSDimitry Andric return Err;
3479f22ef01cSRoman Divacky break;
348039d628a0SDimitry Andric case bitc::USELIST_BLOCK_ID:
3481d88c1a5aSDimitry Andric if (Error Err = parseUseLists())
3482d88c1a5aSDimitry Andric return Err;
348339d628a0SDimitry Andric break;
3484f22ef01cSRoman Divacky }
3485f22ef01cSRoman Divacky continue;
3486f22ef01cSRoman Divacky
3487139f7f9bSDimitry Andric case BitstreamEntry::Record:
3488139f7f9bSDimitry Andric // The interesting case.
3489139f7f9bSDimitry Andric break;
3490f22ef01cSRoman Divacky }
3491f22ef01cSRoman Divacky
3492f22ef01cSRoman Divacky // Read a record.
3493f22ef01cSRoman Divacky Record.clear();
349491bc56edSDimitry Andric Instruction *I = nullptr;
3495139f7f9bSDimitry Andric unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3496f22ef01cSRoman Divacky switch (BitCode) {
3497f22ef01cSRoman Divacky default: // Default behavior: reject
34988f0fd8f6SDimitry Andric return error("Invalid value");
349939d628a0SDimitry Andric case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3500f22ef01cSRoman Divacky if (Record.size() < 1 || Record[0] == 0)
35018f0fd8f6SDimitry Andric return error("Invalid record");
3502f22ef01cSRoman Divacky // Create all the basic blocks for the function.
3503f22ef01cSRoman Divacky FunctionBBs.resize(Record[0]);
350439d628a0SDimitry Andric
350539d628a0SDimitry Andric // See if anything took the address of blocks in this function.
350639d628a0SDimitry Andric auto BBFRI = BasicBlockFwdRefs.find(F);
350739d628a0SDimitry Andric if (BBFRI == BasicBlockFwdRefs.end()) {
3508f22ef01cSRoman Divacky for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3509f22ef01cSRoman Divacky FunctionBBs[i] = BasicBlock::Create(Context, "", F);
351039d628a0SDimitry Andric } else {
351139d628a0SDimitry Andric auto &BBRefs = BBFRI->second;
351239d628a0SDimitry Andric // Check for invalid basic block references.
351339d628a0SDimitry Andric if (BBRefs.size() > FunctionBBs.size())
35148f0fd8f6SDimitry Andric return error("Invalid ID");
351539d628a0SDimitry Andric assert(!BBRefs.empty() && "Unexpected empty array");
351639d628a0SDimitry Andric assert(!BBRefs.front() && "Invalid reference to entry block");
351739d628a0SDimitry Andric for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
351839d628a0SDimitry Andric ++I)
351939d628a0SDimitry Andric if (I < RE && BBRefs[I]) {
352039d628a0SDimitry Andric BBRefs[I]->insertInto(F);
352139d628a0SDimitry Andric FunctionBBs[I] = BBRefs[I];
352239d628a0SDimitry Andric } else {
352339d628a0SDimitry Andric FunctionBBs[I] = BasicBlock::Create(Context, "", F);
352439d628a0SDimitry Andric }
352539d628a0SDimitry Andric
352639d628a0SDimitry Andric // Erase from the table.
352739d628a0SDimitry Andric BasicBlockFwdRefs.erase(BBFRI);
352839d628a0SDimitry Andric }
352939d628a0SDimitry Andric
3530f22ef01cSRoman Divacky CurBB = FunctionBBs[0];
3531f22ef01cSRoman Divacky continue;
353239d628a0SDimitry Andric }
3533f22ef01cSRoman Divacky
3534f22ef01cSRoman Divacky case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3535f22ef01cSRoman Divacky // This record indicates that the last instruction is at the same
3536f22ef01cSRoman Divacky // location as the previous instruction with a location.
353739d628a0SDimitry Andric I = getLastInstruction();
3538f22ef01cSRoman Divacky
353991bc56edSDimitry Andric if (!I)
35408f0fd8f6SDimitry Andric return error("Invalid record");
3541f22ef01cSRoman Divacky I->setDebugLoc(LastLoc);
354291bc56edSDimitry Andric I = nullptr;
3543f22ef01cSRoman Divacky continue;
3544f22ef01cSRoman Divacky
354517a519f9SDimitry Andric case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
354639d628a0SDimitry Andric I = getLastInstruction();
354791bc56edSDimitry Andric if (!I || Record.size() < 4)
35488f0fd8f6SDimitry Andric return error("Invalid record");
3549f22ef01cSRoman Divacky
3550f22ef01cSRoman Divacky unsigned Line = Record[0], Col = Record[1];
3551f22ef01cSRoman Divacky unsigned ScopeID = Record[2], IAID = Record[3];
3552*b5893f02SDimitry Andric bool isImplicitCode = Record.size() == 5 && Record[4];
3553f22ef01cSRoman Divacky
355491bc56edSDimitry Andric MDNode *Scope = nullptr, *IA = nullptr;
35553ca95b02SDimitry Andric if (ScopeID) {
3556*b5893f02SDimitry Andric Scope = dyn_cast_or_null<MDNode>(
3557*b5893f02SDimitry Andric MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
35583ca95b02SDimitry Andric if (!Scope)
35593ca95b02SDimitry Andric return error("Invalid record");
35603ca95b02SDimitry Andric }
35613ca95b02SDimitry Andric if (IAID) {
3562*b5893f02SDimitry Andric IA = dyn_cast_or_null<MDNode>(
3563*b5893f02SDimitry Andric MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
35643ca95b02SDimitry Andric if (!IA)
35653ca95b02SDimitry Andric return error("Invalid record");
35663ca95b02SDimitry Andric }
3567*b5893f02SDimitry Andric LastLoc = DebugLoc::get(Line, Col, Scope, IA, isImplicitCode);
3568f22ef01cSRoman Divacky I->setDebugLoc(LastLoc);
356991bc56edSDimitry Andric I = nullptr;
3570f22ef01cSRoman Divacky continue;
3571f22ef01cSRoman Divacky }
3572*b5893f02SDimitry Andric case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
3573*b5893f02SDimitry Andric unsigned OpNum = 0;
3574*b5893f02SDimitry Andric Value *LHS;
3575*b5893f02SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3576*b5893f02SDimitry Andric OpNum+1 > Record.size())
3577*b5893f02SDimitry Andric return error("Invalid record");
3578f22ef01cSRoman Divacky
3579*b5893f02SDimitry Andric int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
3580*b5893f02SDimitry Andric if (Opc == -1)
3581*b5893f02SDimitry Andric return error("Invalid record");
3582*b5893f02SDimitry Andric I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
3583*b5893f02SDimitry Andric InstructionList.push_back(I);
3584*b5893f02SDimitry Andric if (OpNum < Record.size()) {
3585*b5893f02SDimitry Andric if (isa<FPMathOperator>(I)) {
3586*b5893f02SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3587*b5893f02SDimitry Andric if (FMF.any())
3588*b5893f02SDimitry Andric I->setFastMathFlags(FMF);
3589*b5893f02SDimitry Andric }
3590*b5893f02SDimitry Andric }
3591*b5893f02SDimitry Andric break;
3592*b5893f02SDimitry Andric }
3593f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3594f22ef01cSRoman Divacky unsigned OpNum = 0;
3595f22ef01cSRoman Divacky Value *LHS, *RHS;
3596f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
35973861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3598f22ef01cSRoman Divacky OpNum+1 > Record.size())
35998f0fd8f6SDimitry Andric return error("Invalid record");
3600f22ef01cSRoman Divacky
36018f0fd8f6SDimitry Andric int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3602f785676fSDimitry Andric if (Opc == -1)
36038f0fd8f6SDimitry Andric return error("Invalid record");
3604f22ef01cSRoman Divacky I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3605f22ef01cSRoman Divacky InstructionList.push_back(I);
3606f22ef01cSRoman Divacky if (OpNum < Record.size()) {
3607f22ef01cSRoman Divacky if (Opc == Instruction::Add ||
3608f22ef01cSRoman Divacky Opc == Instruction::Sub ||
36092754fe60SDimitry Andric Opc == Instruction::Mul ||
36102754fe60SDimitry Andric Opc == Instruction::Shl) {
3611f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3612f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3613f22ef01cSRoman Divacky if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3614f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
36152754fe60SDimitry Andric } else if (Opc == Instruction::SDiv ||
36162754fe60SDimitry Andric Opc == Instruction::UDiv ||
36172754fe60SDimitry Andric Opc == Instruction::LShr ||
36182754fe60SDimitry Andric Opc == Instruction::AShr) {
36192754fe60SDimitry Andric if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3620f22ef01cSRoman Divacky cast<BinaryOperator>(I)->setIsExact(true);
3621139f7f9bSDimitry Andric } else if (isa<FPMathOperator>(I)) {
3622875ed548SDimitry Andric FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3623139f7f9bSDimitry Andric if (FMF.any())
3624139f7f9bSDimitry Andric I->setFastMathFlags(FMF);
3625f22ef01cSRoman Divacky }
3626139f7f9bSDimitry Andric
3627f22ef01cSRoman Divacky }
3628f22ef01cSRoman Divacky break;
3629f22ef01cSRoman Divacky }
3630f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3631f22ef01cSRoman Divacky unsigned OpNum = 0;
3632f22ef01cSRoman Divacky Value *Op;
3633f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3634f22ef01cSRoman Divacky OpNum+2 != Record.size())
36358f0fd8f6SDimitry Andric return error("Invalid record");
3636f22ef01cSRoman Divacky
36376122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[OpNum]);
36388f0fd8f6SDimitry Andric int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
363991bc56edSDimitry Andric if (Opc == -1 || !ResTy)
36408f0fd8f6SDimitry Andric return error("Invalid record");
364191bc56edSDimitry Andric Instruction *Temp = nullptr;
3642f785676fSDimitry Andric if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3643f785676fSDimitry Andric if (Temp) {
3644f785676fSDimitry Andric InstructionList.push_back(Temp);
3645f785676fSDimitry Andric CurBB->getInstList().push_back(Temp);
3646f785676fSDimitry Andric }
3647f785676fSDimitry Andric } else {
36487d523365SDimitry Andric auto CastOp = (Instruction::CastOps)Opc;
36497d523365SDimitry Andric if (!CastInst::castIsValid(CastOp, Op, ResTy))
36507d523365SDimitry Andric return error("Invalid cast");
36517d523365SDimitry Andric I = CastInst::Create(CastOp, Op, ResTy);
3652f785676fSDimitry Andric }
3653f22ef01cSRoman Divacky InstructionList.push_back(I);
3654f22ef01cSRoman Divacky break;
3655f22ef01cSRoman Divacky }
3656ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3657ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP_OLD:
3658ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3659f22ef01cSRoman Divacky unsigned OpNum = 0;
3660ff0cc061SDimitry Andric
3661ff0cc061SDimitry Andric Type *Ty;
3662ff0cc061SDimitry Andric bool InBounds;
3663ff0cc061SDimitry Andric
3664ff0cc061SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3665ff0cc061SDimitry Andric InBounds = Record[OpNum++];
3666ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]);
3667ff0cc061SDimitry Andric } else {
3668ff0cc061SDimitry Andric InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3669ff0cc061SDimitry Andric Ty = nullptr;
3670ff0cc061SDimitry Andric }
3671ff0cc061SDimitry Andric
3672f22ef01cSRoman Divacky Value *BasePtr;
3673f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
36748f0fd8f6SDimitry Andric return error("Invalid record");
3675f22ef01cSRoman Divacky
3676ff0cc061SDimitry Andric if (!Ty)
3677d88c1a5aSDimitry Andric Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
3678ff0cc061SDimitry Andric ->getElementType();
3679ff0cc061SDimitry Andric else if (Ty !=
3680d88c1a5aSDimitry Andric cast<PointerType>(BasePtr->getType()->getScalarType())
3681ff0cc061SDimitry Andric ->getElementType())
36828f0fd8f6SDimitry Andric return error(
3683ff0cc061SDimitry Andric "Explicit gep type does not match pointee type of pointer operand");
3684ff0cc061SDimitry Andric
3685f22ef01cSRoman Divacky SmallVector<Value*, 16> GEPIdx;
3686f22ef01cSRoman Divacky while (OpNum != Record.size()) {
3687f22ef01cSRoman Divacky Value *Op;
3688f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op))
36898f0fd8f6SDimitry Andric return error("Invalid record");
3690f22ef01cSRoman Divacky GEPIdx.push_back(Op);
3691f22ef01cSRoman Divacky }
3692f22ef01cSRoman Divacky
3693ff0cc061SDimitry Andric I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3694ff0cc061SDimitry Andric
3695f22ef01cSRoman Divacky InstructionList.push_back(I);
3696ff0cc061SDimitry Andric if (InBounds)
3697f22ef01cSRoman Divacky cast<GetElementPtrInst>(I)->setIsInBounds(true);
3698f22ef01cSRoman Divacky break;
3699f22ef01cSRoman Divacky }
3700f22ef01cSRoman Divacky
3701f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3702f22ef01cSRoman Divacky // EXTRACTVAL: [opty, opval, n x indices]
3703f22ef01cSRoman Divacky unsigned OpNum = 0;
3704f22ef01cSRoman Divacky Value *Agg;
3705f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
37068f0fd8f6SDimitry Andric return error("Invalid record");
3707f22ef01cSRoman Divacky
3708ff0cc061SDimitry Andric unsigned RecSize = Record.size();
3709ff0cc061SDimitry Andric if (OpNum == RecSize)
37108f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid instruction with 0 indices");
3711ff0cc061SDimitry Andric
3712f22ef01cSRoman Divacky SmallVector<unsigned, 4> EXTRACTVALIdx;
3713ff0cc061SDimitry Andric Type *CurTy = Agg->getType();
3714ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) {
3715ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy();
3716ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy();
3717f22ef01cSRoman Divacky uint64_t Index = Record[OpNum];
3718ff0cc061SDimitry Andric
3719ff0cc061SDimitry Andric if (!IsStruct && !IsArray)
37208f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid type");
3721f22ef01cSRoman Divacky if ((unsigned)Index != Index)
37228f0fd8f6SDimitry Andric return error("Invalid value");
3723*b5893f02SDimitry Andric if (IsStruct && Index >= CurTy->getStructNumElements())
37248f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid struct index");
3725ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements())
37268f0fd8f6SDimitry Andric return error("EXTRACTVAL: Invalid array index");
3727f22ef01cSRoman Divacky EXTRACTVALIdx.push_back((unsigned)Index);
3728ff0cc061SDimitry Andric
3729ff0cc061SDimitry Andric if (IsStruct)
3730*b5893f02SDimitry Andric CurTy = CurTy->getStructElementType(Index);
3731ff0cc061SDimitry Andric else
3732*b5893f02SDimitry Andric CurTy = CurTy->getArrayElementType();
3733f22ef01cSRoman Divacky }
3734f22ef01cSRoman Divacky
373517a519f9SDimitry Andric I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3736f22ef01cSRoman Divacky InstructionList.push_back(I);
3737f22ef01cSRoman Divacky break;
3738f22ef01cSRoman Divacky }
3739f22ef01cSRoman Divacky
3740f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTVAL: {
3741f22ef01cSRoman Divacky // INSERTVAL: [opty, opval, opty, opval, n x indices]
3742f22ef01cSRoman Divacky unsigned OpNum = 0;
3743f22ef01cSRoman Divacky Value *Agg;
3744f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
37458f0fd8f6SDimitry Andric return error("Invalid record");
3746f22ef01cSRoman Divacky Value *Val;
3747f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Val))
37488f0fd8f6SDimitry Andric return error("Invalid record");
3749f22ef01cSRoman Divacky
3750ff0cc061SDimitry Andric unsigned RecSize = Record.size();
3751ff0cc061SDimitry Andric if (OpNum == RecSize)
37528f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid instruction with 0 indices");
3753ff0cc061SDimitry Andric
3754f22ef01cSRoman Divacky SmallVector<unsigned, 4> INSERTVALIdx;
3755ff0cc061SDimitry Andric Type *CurTy = Agg->getType();
3756ff0cc061SDimitry Andric for (; OpNum != RecSize; ++OpNum) {
3757ff0cc061SDimitry Andric bool IsArray = CurTy->isArrayTy();
3758ff0cc061SDimitry Andric bool IsStruct = CurTy->isStructTy();
3759f22ef01cSRoman Divacky uint64_t Index = Record[OpNum];
3760ff0cc061SDimitry Andric
3761ff0cc061SDimitry Andric if (!IsStruct && !IsArray)
37628f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid type");
3763f22ef01cSRoman Divacky if ((unsigned)Index != Index)
37648f0fd8f6SDimitry Andric return error("Invalid value");
3765*b5893f02SDimitry Andric if (IsStruct && Index >= CurTy->getStructNumElements())
37668f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid struct index");
3767ff0cc061SDimitry Andric if (IsArray && Index >= CurTy->getArrayNumElements())
37688f0fd8f6SDimitry Andric return error("INSERTVAL: Invalid array index");
3769ff0cc061SDimitry Andric
3770f22ef01cSRoman Divacky INSERTVALIdx.push_back((unsigned)Index);
3771ff0cc061SDimitry Andric if (IsStruct)
3772*b5893f02SDimitry Andric CurTy = CurTy->getStructElementType(Index);
3773ff0cc061SDimitry Andric else
3774*b5893f02SDimitry Andric CurTy = CurTy->getArrayElementType();
3775f22ef01cSRoman Divacky }
3776f22ef01cSRoman Divacky
3777ff0cc061SDimitry Andric if (CurTy != Val->getType())
37788f0fd8f6SDimitry Andric return error("Inserted value type doesn't match aggregate type");
3779ff0cc061SDimitry Andric
378017a519f9SDimitry Andric I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3781f22ef01cSRoman Divacky InstructionList.push_back(I);
3782f22ef01cSRoman Divacky break;
3783f22ef01cSRoman Divacky }
3784f22ef01cSRoman Divacky
3785f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3786f22ef01cSRoman Divacky // obsolete form of select
3787f22ef01cSRoman Divacky // handles select i1 ... in old bitcode
3788f22ef01cSRoman Divacky unsigned OpNum = 0;
3789f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond;
3790f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
37913861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
37923861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
37938f0fd8f6SDimitry Andric return error("Invalid record");
3794f22ef01cSRoman Divacky
3795f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal);
3796f22ef01cSRoman Divacky InstructionList.push_back(I);
3797f22ef01cSRoman Divacky break;
3798f22ef01cSRoman Divacky }
3799f22ef01cSRoman Divacky
3800f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3801f22ef01cSRoman Divacky // new form of select
3802f22ef01cSRoman Divacky // handles select i1 or select [N x i1]
3803f22ef01cSRoman Divacky unsigned OpNum = 0;
3804f22ef01cSRoman Divacky Value *TrueVal, *FalseVal, *Cond;
3805f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
38063861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3807f22ef01cSRoman Divacky getValueTypePair(Record, OpNum, NextValueNo, Cond))
38088f0fd8f6SDimitry Andric return error("Invalid record");
3809f22ef01cSRoman Divacky
3810f22ef01cSRoman Divacky // select condition can be either i1 or [N x i1]
38116122f3e6SDimitry Andric if (VectorType* vector_type =
38126122f3e6SDimitry Andric dyn_cast<VectorType>(Cond->getType())) {
3813f22ef01cSRoman Divacky // expect <n x i1>
3814f22ef01cSRoman Divacky if (vector_type->getElementType() != Type::getInt1Ty(Context))
38158f0fd8f6SDimitry Andric return error("Invalid type for value");
3816f22ef01cSRoman Divacky } else {
3817f22ef01cSRoman Divacky // expect i1
3818f22ef01cSRoman Divacky if (Cond->getType() != Type::getInt1Ty(Context))
38198f0fd8f6SDimitry Andric return error("Invalid type for value");
3820f22ef01cSRoman Divacky }
3821f22ef01cSRoman Divacky
3822f22ef01cSRoman Divacky I = SelectInst::Create(Cond, TrueVal, FalseVal);
3823f22ef01cSRoman Divacky InstructionList.push_back(I);
3824f22ef01cSRoman Divacky break;
3825f22ef01cSRoman Divacky }
3826f22ef01cSRoman Divacky
3827f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3828f22ef01cSRoman Divacky unsigned OpNum = 0;
3829f22ef01cSRoman Divacky Value *Vec, *Idx;
3830f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
383191bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx))
38328f0fd8f6SDimitry Andric return error("Invalid record");
3833ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy())
38348f0fd8f6SDimitry Andric return error("Invalid type for value");
3835f22ef01cSRoman Divacky I = ExtractElementInst::Create(Vec, Idx);
3836f22ef01cSRoman Divacky InstructionList.push_back(I);
3837f22ef01cSRoman Divacky break;
3838f22ef01cSRoman Divacky }
3839f22ef01cSRoman Divacky
3840f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3841f22ef01cSRoman Divacky unsigned OpNum = 0;
3842f22ef01cSRoman Divacky Value *Vec, *Elt, *Idx;
3843ff0cc061SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
38448f0fd8f6SDimitry Andric return error("Invalid record");
3845ff0cc061SDimitry Andric if (!Vec->getType()->isVectorTy())
38468f0fd8f6SDimitry Andric return error("Invalid type for value");
3847ff0cc061SDimitry Andric if (popValue(Record, OpNum, NextValueNo,
3848f22ef01cSRoman Divacky cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
384991bc56edSDimitry Andric getValueTypePair(Record, OpNum, NextValueNo, Idx))
38508f0fd8f6SDimitry Andric return error("Invalid record");
3851f22ef01cSRoman Divacky I = InsertElementInst::Create(Vec, Elt, Idx);
3852f22ef01cSRoman Divacky InstructionList.push_back(I);
3853f22ef01cSRoman Divacky break;
3854f22ef01cSRoman Divacky }
3855f22ef01cSRoman Divacky
3856f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3857f22ef01cSRoman Divacky unsigned OpNum = 0;
3858f22ef01cSRoman Divacky Value *Vec1, *Vec2, *Mask;
3859f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
38603861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
38618f0fd8f6SDimitry Andric return error("Invalid record");
3862f22ef01cSRoman Divacky
3863f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
38648f0fd8f6SDimitry Andric return error("Invalid record");
3865ff0cc061SDimitry Andric if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
38668f0fd8f6SDimitry Andric return error("Invalid type for value");
3867f22ef01cSRoman Divacky I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3868f22ef01cSRoman Divacky InstructionList.push_back(I);
3869f22ef01cSRoman Divacky break;
3870f22ef01cSRoman Divacky }
3871f22ef01cSRoman Divacky
3872f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3873f22ef01cSRoman Divacky // Old form of ICmp/FCmp returning bool
3874f22ef01cSRoman Divacky // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3875f22ef01cSRoman Divacky // both legal on vectors but had different behaviour.
3876f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3877f22ef01cSRoman Divacky // FCmp/ICmp returning bool or vector of bool
3878f22ef01cSRoman Divacky
3879f22ef01cSRoman Divacky unsigned OpNum = 0;
3880f22ef01cSRoman Divacky Value *LHS, *RHS;
3881f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3882875ed548SDimitry Andric popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3883875ed548SDimitry Andric return error("Invalid record");
3884875ed548SDimitry Andric
3885875ed548SDimitry Andric unsigned PredVal = Record[OpNum];
3886875ed548SDimitry Andric bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3887875ed548SDimitry Andric FastMathFlags FMF;
3888875ed548SDimitry Andric if (IsFP && Record.size() > OpNum+1)
3889875ed548SDimitry Andric FMF = getDecodedFastMathFlags(Record[++OpNum]);
3890875ed548SDimitry Andric
3891875ed548SDimitry Andric if (OpNum+1 != Record.size())
38928f0fd8f6SDimitry Andric return error("Invalid record");
3893f22ef01cSRoman Divacky
3894f22ef01cSRoman Divacky if (LHS->getType()->isFPOrFPVectorTy())
3895875ed548SDimitry Andric I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3896f22ef01cSRoman Divacky else
3897875ed548SDimitry Andric I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3898875ed548SDimitry Andric
3899875ed548SDimitry Andric if (FMF.any())
3900875ed548SDimitry Andric I->setFastMathFlags(FMF);
3901f22ef01cSRoman Divacky InstructionList.push_back(I);
3902f22ef01cSRoman Divacky break;
3903f22ef01cSRoman Divacky }
3904f22ef01cSRoman Divacky
3905f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3906f22ef01cSRoman Divacky {
3907f22ef01cSRoman Divacky unsigned Size = Record.size();
3908f22ef01cSRoman Divacky if (Size == 0) {
3909f22ef01cSRoman Divacky I = ReturnInst::Create(Context);
3910f22ef01cSRoman Divacky InstructionList.push_back(I);
3911f22ef01cSRoman Divacky break;
3912f22ef01cSRoman Divacky }
3913f22ef01cSRoman Divacky
3914f22ef01cSRoman Divacky unsigned OpNum = 0;
391591bc56edSDimitry Andric Value *Op = nullptr;
3916f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op))
39178f0fd8f6SDimitry Andric return error("Invalid record");
391817a519f9SDimitry Andric if (OpNum != Record.size())
39198f0fd8f6SDimitry Andric return error("Invalid record");
3920f22ef01cSRoman Divacky
392117a519f9SDimitry Andric I = ReturnInst::Create(Context, Op);
3922f22ef01cSRoman Divacky InstructionList.push_back(I);
3923f22ef01cSRoman Divacky break;
3924f22ef01cSRoman Divacky }
3925f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3926f22ef01cSRoman Divacky if (Record.size() != 1 && Record.size() != 3)
39278f0fd8f6SDimitry Andric return error("Invalid record");
3928f22ef01cSRoman Divacky BasicBlock *TrueDest = getBasicBlock(Record[0]);
392991bc56edSDimitry Andric if (!TrueDest)
39308f0fd8f6SDimitry Andric return error("Invalid record");
3931f22ef01cSRoman Divacky
3932f22ef01cSRoman Divacky if (Record.size() == 1) {
3933f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest);
3934f22ef01cSRoman Divacky InstructionList.push_back(I);
3935f22ef01cSRoman Divacky }
3936f22ef01cSRoman Divacky else {
3937f22ef01cSRoman Divacky BasicBlock *FalseDest = getBasicBlock(Record[1]);
39383861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo,
39393861d79fSDimitry Andric Type::getInt1Ty(Context));
394091bc56edSDimitry Andric if (!FalseDest || !Cond)
39418f0fd8f6SDimitry Andric return error("Invalid record");
3942f22ef01cSRoman Divacky I = BranchInst::Create(TrueDest, FalseDest, Cond);
3943f22ef01cSRoman Divacky InstructionList.push_back(I);
3944f22ef01cSRoman Divacky }
3945f22ef01cSRoman Divacky break;
3946f22ef01cSRoman Divacky }
39477d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
39487d523365SDimitry Andric if (Record.size() != 1 && Record.size() != 2)
39497d523365SDimitry Andric return error("Invalid record");
39507d523365SDimitry Andric unsigned Idx = 0;
39517d523365SDimitry Andric Value *CleanupPad =
39527d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
39537d523365SDimitry Andric if (!CleanupPad)
39547d523365SDimitry Andric return error("Invalid record");
39557d523365SDimitry Andric BasicBlock *UnwindDest = nullptr;
39567d523365SDimitry Andric if (Record.size() == 2) {
39577d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]);
39587d523365SDimitry Andric if (!UnwindDest)
39597d523365SDimitry Andric return error("Invalid record");
39607d523365SDimitry Andric }
39617d523365SDimitry Andric
39627d523365SDimitry Andric I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
39637d523365SDimitry Andric InstructionList.push_back(I);
39647d523365SDimitry Andric break;
39657d523365SDimitry Andric }
39667d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
39677d523365SDimitry Andric if (Record.size() != 2)
39687d523365SDimitry Andric return error("Invalid record");
39697d523365SDimitry Andric unsigned Idx = 0;
39707d523365SDimitry Andric Value *CatchPad =
39717d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
39727d523365SDimitry Andric if (!CatchPad)
39737d523365SDimitry Andric return error("Invalid record");
39747d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]);
39757d523365SDimitry Andric if (!BB)
39767d523365SDimitry Andric return error("Invalid record");
39777d523365SDimitry Andric
39787d523365SDimitry Andric I = CatchReturnInst::Create(CatchPad, BB);
39797d523365SDimitry Andric InstructionList.push_back(I);
39807d523365SDimitry Andric break;
39817d523365SDimitry Andric }
39827d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
39837d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments.
39847d523365SDimitry Andric if (Record.size() < 2)
39857d523365SDimitry Andric return error("Invalid record");
39867d523365SDimitry Andric
39877d523365SDimitry Andric unsigned Idx = 0;
39887d523365SDimitry Andric
39897d523365SDimitry Andric Value *ParentPad =
39907d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
39917d523365SDimitry Andric
39927d523365SDimitry Andric unsigned NumHandlers = Record[Idx++];
39937d523365SDimitry Andric
39947d523365SDimitry Andric SmallVector<BasicBlock *, 2> Handlers;
39957d523365SDimitry Andric for (unsigned Op = 0; Op != NumHandlers; ++Op) {
39967d523365SDimitry Andric BasicBlock *BB = getBasicBlock(Record[Idx++]);
39977d523365SDimitry Andric if (!BB)
39987d523365SDimitry Andric return error("Invalid record");
39997d523365SDimitry Andric Handlers.push_back(BB);
40007d523365SDimitry Andric }
40017d523365SDimitry Andric
40027d523365SDimitry Andric BasicBlock *UnwindDest = nullptr;
40037d523365SDimitry Andric if (Idx + 1 == Record.size()) {
40047d523365SDimitry Andric UnwindDest = getBasicBlock(Record[Idx++]);
40057d523365SDimitry Andric if (!UnwindDest)
40067d523365SDimitry Andric return error("Invalid record");
40077d523365SDimitry Andric }
40087d523365SDimitry Andric
40097d523365SDimitry Andric if (Record.size() != Idx)
40107d523365SDimitry Andric return error("Invalid record");
40117d523365SDimitry Andric
40127d523365SDimitry Andric auto *CatchSwitch =
40137d523365SDimitry Andric CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
40147d523365SDimitry Andric for (BasicBlock *Handler : Handlers)
40157d523365SDimitry Andric CatchSwitch->addHandler(Handler);
40167d523365SDimitry Andric I = CatchSwitch;
40177d523365SDimitry Andric InstructionList.push_back(I);
40187d523365SDimitry Andric break;
40197d523365SDimitry Andric }
40207d523365SDimitry Andric case bitc::FUNC_CODE_INST_CATCHPAD:
40217d523365SDimitry Andric case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
40227d523365SDimitry Andric // We must have, at minimum, the outer scope and the number of arguments.
40237d523365SDimitry Andric if (Record.size() < 2)
40247d523365SDimitry Andric return error("Invalid record");
40257d523365SDimitry Andric
40267d523365SDimitry Andric unsigned Idx = 0;
40277d523365SDimitry Andric
40287d523365SDimitry Andric Value *ParentPad =
40297d523365SDimitry Andric getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
40307d523365SDimitry Andric
40317d523365SDimitry Andric unsigned NumArgOperands = Record[Idx++];
40327d523365SDimitry Andric
40337d523365SDimitry Andric SmallVector<Value *, 2> Args;
40347d523365SDimitry Andric for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
40357d523365SDimitry Andric Value *Val;
40367d523365SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val))
40377d523365SDimitry Andric return error("Invalid record");
40387d523365SDimitry Andric Args.push_back(Val);
40397d523365SDimitry Andric }
40407d523365SDimitry Andric
40417d523365SDimitry Andric if (Record.size() != Idx)
40427d523365SDimitry Andric return error("Invalid record");
40437d523365SDimitry Andric
40447d523365SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
40457d523365SDimitry Andric I = CleanupPadInst::Create(ParentPad, Args);
40467d523365SDimitry Andric else
40477d523365SDimitry Andric I = CatchPadInst::Create(ParentPad, Args);
40487d523365SDimitry Andric InstructionList.push_back(I);
40497d523365SDimitry Andric break;
40507d523365SDimitry Andric }
4051f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
40527ae0e2c9SDimitry Andric // Check magic
40537ae0e2c9SDimitry Andric if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4054f785676fSDimitry Andric // "New" SwitchInst format with case ranges. The changes to write this
4055f785676fSDimitry Andric // format were reverted but we still recognize bitcode that uses it.
4056f785676fSDimitry Andric // Hopefully someday we will have support for case ranges and can use
4057f785676fSDimitry Andric // this format again.
40587ae0e2c9SDimitry Andric
40597ae0e2c9SDimitry Andric Type *OpTy = getTypeByID(Record[1]);
40607ae0e2c9SDimitry Andric unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
40617ae0e2c9SDimitry Andric
40623861d79fSDimitry Andric Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
40637ae0e2c9SDimitry Andric BasicBlock *Default = getBasicBlock(Record[3]);
406491bc56edSDimitry Andric if (!OpTy || !Cond || !Default)
40658f0fd8f6SDimitry Andric return error("Invalid record");
40667ae0e2c9SDimitry Andric
40677ae0e2c9SDimitry Andric unsigned NumCases = Record[4];
40687ae0e2c9SDimitry Andric
40697ae0e2c9SDimitry Andric SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
40707ae0e2c9SDimitry Andric InstructionList.push_back(SI);
40717ae0e2c9SDimitry Andric
40727ae0e2c9SDimitry Andric unsigned CurIdx = 5;
40737ae0e2c9SDimitry Andric for (unsigned i = 0; i != NumCases; ++i) {
4074f785676fSDimitry Andric SmallVector<ConstantInt*, 1> CaseVals;
40757ae0e2c9SDimitry Andric unsigned NumItems = Record[CurIdx++];
40767ae0e2c9SDimitry Andric for (unsigned ci = 0; ci != NumItems; ++ci) {
40777ae0e2c9SDimitry Andric bool isSingleNumber = Record[CurIdx++];
40787ae0e2c9SDimitry Andric
40797ae0e2c9SDimitry Andric APInt Low;
40807ae0e2c9SDimitry Andric unsigned ActiveWords = 1;
40817ae0e2c9SDimitry Andric if (ValueBitWidth > 64)
40827ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++];
40838f0fd8f6SDimitry Andric Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
40847ae0e2c9SDimitry Andric ValueBitWidth);
40857ae0e2c9SDimitry Andric CurIdx += ActiveWords;
40867ae0e2c9SDimitry Andric
40877ae0e2c9SDimitry Andric if (!isSingleNumber) {
40887ae0e2c9SDimitry Andric ActiveWords = 1;
40897ae0e2c9SDimitry Andric if (ValueBitWidth > 64)
40907ae0e2c9SDimitry Andric ActiveWords = Record[CurIdx++];
40918f0fd8f6SDimitry Andric APInt High = readWideAPInt(
40928f0fd8f6SDimitry Andric makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
40937ae0e2c9SDimitry Andric CurIdx += ActiveWords;
4094f785676fSDimitry Andric
4095f785676fSDimitry Andric // FIXME: It is not clear whether values in the range should be
4096f785676fSDimitry Andric // compared as signed or unsigned values. The partially
4097f785676fSDimitry Andric // implemented changes that used this format in the past used
4098f785676fSDimitry Andric // unsigned comparisons.
4099f785676fSDimitry Andric for ( ; Low.ule(High); ++Low)
4100f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low));
41017ae0e2c9SDimitry Andric } else
4102f785676fSDimitry Andric CaseVals.push_back(ConstantInt::get(Context, Low));
41037ae0e2c9SDimitry Andric }
41047ae0e2c9SDimitry Andric BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4105f785676fSDimitry Andric for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4106f785676fSDimitry Andric cve = CaseVals.end(); cvi != cve; ++cvi)
4107f785676fSDimitry Andric SI->addCase(*cvi, DestBB);
41087ae0e2c9SDimitry Andric }
41097ae0e2c9SDimitry Andric I = SI;
41107ae0e2c9SDimitry Andric break;
41117ae0e2c9SDimitry Andric }
41127ae0e2c9SDimitry Andric
41137ae0e2c9SDimitry Andric // Old SwitchInst format without case ranges.
41147ae0e2c9SDimitry Andric
4115f22ef01cSRoman Divacky if (Record.size() < 3 || (Record.size() & 1) == 0)
41168f0fd8f6SDimitry Andric return error("Invalid record");
41176122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]);
41183861d79fSDimitry Andric Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4119f22ef01cSRoman Divacky BasicBlock *Default = getBasicBlock(Record[2]);
412091bc56edSDimitry Andric if (!OpTy || !Cond || !Default)
41218f0fd8f6SDimitry Andric return error("Invalid record");
4122f22ef01cSRoman Divacky unsigned NumCases = (Record.size()-3)/2;
4123f22ef01cSRoman Divacky SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4124f22ef01cSRoman Divacky InstructionList.push_back(SI);
4125f22ef01cSRoman Divacky for (unsigned i = 0, e = NumCases; i != e; ++i) {
4126f22ef01cSRoman Divacky ConstantInt *CaseVal =
4127f22ef01cSRoman Divacky dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4128f22ef01cSRoman Divacky BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
412991bc56edSDimitry Andric if (!CaseVal || !DestBB) {
4130f22ef01cSRoman Divacky delete SI;
41318f0fd8f6SDimitry Andric return error("Invalid record");
4132f22ef01cSRoman Divacky }
4133f22ef01cSRoman Divacky SI->addCase(CaseVal, DestBB);
4134f22ef01cSRoman Divacky }
4135f22ef01cSRoman Divacky I = SI;
4136f22ef01cSRoman Divacky break;
4137f22ef01cSRoman Divacky }
4138f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4139f22ef01cSRoman Divacky if (Record.size() < 2)
41408f0fd8f6SDimitry Andric return error("Invalid record");
41416122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]);
41423861d79fSDimitry Andric Value *Address = getValue(Record, 1, NextValueNo, OpTy);
414391bc56edSDimitry Andric if (!OpTy || !Address)
41448f0fd8f6SDimitry Andric return error("Invalid record");
4145f22ef01cSRoman Divacky unsigned NumDests = Record.size()-2;
4146f22ef01cSRoman Divacky IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4147f22ef01cSRoman Divacky InstructionList.push_back(IBI);
4148f22ef01cSRoman Divacky for (unsigned i = 0, e = NumDests; i != e; ++i) {
4149f22ef01cSRoman Divacky if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4150f22ef01cSRoman Divacky IBI->addDestination(DestBB);
4151f22ef01cSRoman Divacky } else {
4152f22ef01cSRoman Divacky delete IBI;
41538f0fd8f6SDimitry Andric return error("Invalid record");
4154f22ef01cSRoman Divacky }
4155f22ef01cSRoman Divacky }
4156f22ef01cSRoman Divacky I = IBI;
4157f22ef01cSRoman Divacky break;
4158f22ef01cSRoman Divacky }
4159f22ef01cSRoman Divacky
4160f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_INVOKE: {
4161f22ef01cSRoman Divacky // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4162f785676fSDimitry Andric if (Record.size() < 4)
41638f0fd8f6SDimitry Andric return error("Invalid record");
4164ff0cc061SDimitry Andric unsigned OpNum = 0;
41657a7e6055SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]);
4166ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++];
4167ff0cc061SDimitry Andric BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4168ff0cc061SDimitry Andric BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4169f22ef01cSRoman Divacky
4170ff0cc061SDimitry Andric FunctionType *FTy = nullptr;
4171ff0cc061SDimitry Andric if (CCInfo >> 13 & 1 &&
4172ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
41738f0fd8f6SDimitry Andric return error("Explicit invoke type is not a function type");
4174ff0cc061SDimitry Andric
4175f22ef01cSRoman Divacky Value *Callee;
4176f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
41778f0fd8f6SDimitry Andric return error("Invalid record");
4178f22ef01cSRoman Divacky
41796122f3e6SDimitry Andric PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4180ff0cc061SDimitry Andric if (!CalleeTy)
41818f0fd8f6SDimitry Andric return error("Callee is not a pointer");
4182ff0cc061SDimitry Andric if (!FTy) {
4183ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4184ff0cc061SDimitry Andric if (!FTy)
41858f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type");
4186ff0cc061SDimitry Andric } else if (CalleeTy->getElementType() != FTy)
41878f0fd8f6SDimitry Andric return error("Explicit invoke type does not match pointee type of "
4188ff0cc061SDimitry Andric "callee operand");
4189ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum)
41908f0fd8f6SDimitry Andric return error("Insufficient operands to call");
4191f22ef01cSRoman Divacky
4192f22ef01cSRoman Divacky SmallVector<Value*, 16> Ops;
4193f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
41943861d79fSDimitry Andric Ops.push_back(getValue(Record, OpNum, NextValueNo,
41953861d79fSDimitry Andric FTy->getParamType(i)));
419691bc56edSDimitry Andric if (!Ops.back())
41978f0fd8f6SDimitry Andric return error("Invalid record");
4198f22ef01cSRoman Divacky }
4199f22ef01cSRoman Divacky
4200f22ef01cSRoman Divacky if (!FTy->isVarArg()) {
4201f22ef01cSRoman Divacky if (Record.size() != OpNum)
42028f0fd8f6SDimitry Andric return error("Invalid record");
4203f22ef01cSRoman Divacky } else {
4204f22ef01cSRoman Divacky // Read type/value pairs for varargs params.
4205f22ef01cSRoman Divacky while (OpNum != Record.size()) {
4206f22ef01cSRoman Divacky Value *Op;
4207f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op))
42088f0fd8f6SDimitry Andric return error("Invalid record");
4209f22ef01cSRoman Divacky Ops.push_back(Op);
4210f22ef01cSRoman Divacky }
4211f22ef01cSRoman Divacky }
4212f22ef01cSRoman Divacky
42137d523365SDimitry Andric I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
42147d523365SDimitry Andric OperandBundles.clear();
4215f22ef01cSRoman Divacky InstructionList.push_back(I);
42167d523365SDimitry Andric cast<InvokeInst>(I)->setCallingConv(
42177d523365SDimitry Andric static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4218f22ef01cSRoman Divacky cast<InvokeInst>(I)->setAttributes(PAL);
4219f22ef01cSRoman Divacky break;
4220f22ef01cSRoman Divacky }
42216122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
42226122f3e6SDimitry Andric unsigned Idx = 0;
422391bc56edSDimitry Andric Value *Val = nullptr;
42246122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val))
42258f0fd8f6SDimitry Andric return error("Invalid record");
42266122f3e6SDimitry Andric I = ResumeInst::Create(Val);
42276122f3e6SDimitry Andric InstructionList.push_back(I);
42286122f3e6SDimitry Andric break;
42296122f3e6SDimitry Andric }
4230f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4231f22ef01cSRoman Divacky I = new UnreachableInst(Context);
4232f22ef01cSRoman Divacky InstructionList.push_back(I);
4233f22ef01cSRoman Divacky break;
4234f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4235f22ef01cSRoman Divacky if (Record.size() < 1 || ((Record.size()-1)&1))
42368f0fd8f6SDimitry Andric return error("Invalid record");
42376122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[0]);
4238f785676fSDimitry Andric if (!Ty)
42398f0fd8f6SDimitry Andric return error("Invalid record");
4240f22ef01cSRoman Divacky
42413b0f4066SDimitry Andric PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4242f22ef01cSRoman Divacky InstructionList.push_back(PN);
4243f22ef01cSRoman Divacky
4244f22ef01cSRoman Divacky for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
42453861d79fSDimitry Andric Value *V;
42463861d79fSDimitry Andric // With the new function encoding, it is possible that operands have
42473861d79fSDimitry Andric // negative IDs (for forward references). Use a signed VBR
42483861d79fSDimitry Andric // representation to keep the encoding small.
42493861d79fSDimitry Andric if (UseRelativeIDs)
42503861d79fSDimitry Andric V = getValueSigned(Record, 1+i, NextValueNo, Ty);
42513861d79fSDimitry Andric else
42523861d79fSDimitry Andric V = getValue(Record, 1+i, NextValueNo, Ty);
4253f22ef01cSRoman Divacky BasicBlock *BB = getBasicBlock(Record[2+i]);
4254f785676fSDimitry Andric if (!V || !BB)
42558f0fd8f6SDimitry Andric return error("Invalid record");
4256f22ef01cSRoman Divacky PN->addIncoming(V, BB);
4257f22ef01cSRoman Divacky }
4258f22ef01cSRoman Divacky I = PN;
4259f22ef01cSRoman Divacky break;
4260f22ef01cSRoman Divacky }
4261f22ef01cSRoman Divacky
42628f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD:
42638f0fd8f6SDimitry Andric case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
42646122f3e6SDimitry Andric // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
42656122f3e6SDimitry Andric unsigned Idx = 0;
42668f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
42678f0fd8f6SDimitry Andric if (Record.size() < 3)
42688f0fd8f6SDimitry Andric return error("Invalid record");
42698f0fd8f6SDimitry Andric } else {
42708f0fd8f6SDimitry Andric assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
42716122f3e6SDimitry Andric if (Record.size() < 4)
42728f0fd8f6SDimitry Andric return error("Invalid record");
42738f0fd8f6SDimitry Andric }
42746122f3e6SDimitry Andric Type *Ty = getTypeByID(Record[Idx++]);
4275f785676fSDimitry Andric if (!Ty)
42768f0fd8f6SDimitry Andric return error("Invalid record");
42778f0fd8f6SDimitry Andric if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
427891bc56edSDimitry Andric Value *PersFn = nullptr;
42796122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
42808f0fd8f6SDimitry Andric return error("Invalid record");
42818f0fd8f6SDimitry Andric
42828f0fd8f6SDimitry Andric if (!F->hasPersonalityFn())
42838f0fd8f6SDimitry Andric F->setPersonalityFn(cast<Constant>(PersFn));
42848f0fd8f6SDimitry Andric else if (F->getPersonalityFn() != cast<Constant>(PersFn))
42858f0fd8f6SDimitry Andric return error("Personality function mismatch");
42868f0fd8f6SDimitry Andric }
42876122f3e6SDimitry Andric
42886122f3e6SDimitry Andric bool IsCleanup = !!Record[Idx++];
42896122f3e6SDimitry Andric unsigned NumClauses = Record[Idx++];
42908f0fd8f6SDimitry Andric LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
42916122f3e6SDimitry Andric LP->setCleanup(IsCleanup);
42926122f3e6SDimitry Andric for (unsigned J = 0; J != NumClauses; ++J) {
42936122f3e6SDimitry Andric LandingPadInst::ClauseType CT =
42946122f3e6SDimitry Andric LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
42956122f3e6SDimitry Andric Value *Val;
42966122f3e6SDimitry Andric
42976122f3e6SDimitry Andric if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
42986122f3e6SDimitry Andric delete LP;
42998f0fd8f6SDimitry Andric return error("Invalid record");
43006122f3e6SDimitry Andric }
43016122f3e6SDimitry Andric
43026122f3e6SDimitry Andric assert((CT != LandingPadInst::Catch ||
43036122f3e6SDimitry Andric !isa<ArrayType>(Val->getType())) &&
43046122f3e6SDimitry Andric "Catch clause has a invalid type!");
43056122f3e6SDimitry Andric assert((CT != LandingPadInst::Filter ||
43066122f3e6SDimitry Andric isa<ArrayType>(Val->getType())) &&
43076122f3e6SDimitry Andric "Filter clause has invalid type!");
430891bc56edSDimitry Andric LP->addClause(cast<Constant>(Val));
43096122f3e6SDimitry Andric }
43106122f3e6SDimitry Andric
43116122f3e6SDimitry Andric I = LP;
43126122f3e6SDimitry Andric InstructionList.push_back(I);
43136122f3e6SDimitry Andric break;
43146122f3e6SDimitry Andric }
43156122f3e6SDimitry Andric
431617a519f9SDimitry Andric case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
431717a519f9SDimitry Andric if (Record.size() != 4)
43188f0fd8f6SDimitry Andric return error("Invalid record");
4319ff0cc061SDimitry Andric uint64_t AlignRecord = Record[3];
4320ff0cc061SDimitry Andric const uint64_t InAllocaMask = uint64_t(1) << 5;
4321ff0cc061SDimitry Andric const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
43223ca95b02SDimitry Andric const uint64_t SwiftErrorMask = uint64_t(1) << 7;
43233ca95b02SDimitry Andric const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
43243ca95b02SDimitry Andric SwiftErrorMask;
4325ff0cc061SDimitry Andric bool InAlloca = AlignRecord & InAllocaMask;
43263ca95b02SDimitry Andric bool SwiftError = AlignRecord & SwiftErrorMask;
4327ff0cc061SDimitry Andric Type *Ty = getTypeByID(Record[0]);
4328ff0cc061SDimitry Andric if ((AlignRecord & ExplicitTypeMask) == 0) {
4329ff0cc061SDimitry Andric auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4330ff0cc061SDimitry Andric if (!PTy)
43318f0fd8f6SDimitry Andric return error("Old-style alloca with a non-pointer type");
4332ff0cc061SDimitry Andric Ty = PTy->getElementType();
4333ff0cc061SDimitry Andric }
43346122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[1]);
433517a519f9SDimitry Andric Value *Size = getFnValueByID(Record[2], OpTy);
4336ff0cc061SDimitry Andric unsigned Align;
4337d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4338d88c1a5aSDimitry Andric return Err;
4339ff0cc061SDimitry Andric }
4340f785676fSDimitry Andric if (!Ty || !Size)
43418f0fd8f6SDimitry Andric return error("Invalid record");
43427a7e6055SDimitry Andric
43437a7e6055SDimitry Andric // FIXME: Make this an optional field.
43447a7e6055SDimitry Andric const DataLayout &DL = TheModule->getDataLayout();
43457a7e6055SDimitry Andric unsigned AS = DL.getAllocaAddrSpace();
43467a7e6055SDimitry Andric
43477a7e6055SDimitry Andric AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
434891bc56edSDimitry Andric AI->setUsedWithInAlloca(InAlloca);
43493ca95b02SDimitry Andric AI->setSwiftError(SwiftError);
435091bc56edSDimitry Andric I = AI;
4351f22ef01cSRoman Divacky InstructionList.push_back(I);
4352f22ef01cSRoman Divacky break;
4353f22ef01cSRoman Divacky }
4354f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4355f22ef01cSRoman Divacky unsigned OpNum = 0;
4356f22ef01cSRoman Divacky Value *Op;
4357f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4358ff0cc061SDimitry Andric (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
43598f0fd8f6SDimitry Andric return error("Invalid record");
4360f22ef01cSRoman Divacky
4361ff0cc061SDimitry Andric Type *Ty = nullptr;
4362ff0cc061SDimitry Andric if (OpNum + 3 == Record.size())
4363ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]);
4364d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4365d88c1a5aSDimitry Andric return Err;
4366ff0cc061SDimitry Andric if (!Ty)
4367ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType();
4368ff0cc061SDimitry Andric
4369ff0cc061SDimitry Andric unsigned Align;
4370d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4371d88c1a5aSDimitry Andric return Err;
4372ff0cc061SDimitry Andric I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4373ff0cc061SDimitry Andric
4374f22ef01cSRoman Divacky InstructionList.push_back(I);
4375f22ef01cSRoman Divacky break;
4376f22ef01cSRoman Divacky }
43776122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_LOADATOMIC: {
4378c4394386SDimitry Andric // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
43796122f3e6SDimitry Andric unsigned OpNum = 0;
43806122f3e6SDimitry Andric Value *Op;
43816122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4382ff0cc061SDimitry Andric (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
43838f0fd8f6SDimitry Andric return error("Invalid record");
43846122f3e6SDimitry Andric
4385ff0cc061SDimitry Andric Type *Ty = nullptr;
4386ff0cc061SDimitry Andric if (OpNum + 5 == Record.size())
4387ff0cc061SDimitry Andric Ty = getTypeByID(Record[OpNum++]);
4388d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4389d88c1a5aSDimitry Andric return Err;
4390ff0cc061SDimitry Andric if (!Ty)
4391ff0cc061SDimitry Andric Ty = cast<PointerType>(Op->getType())->getElementType();
4392ff0cc061SDimitry Andric
43938f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
43943ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic ||
43953ca95b02SDimitry Andric Ordering == AtomicOrdering::Release ||
43963ca95b02SDimitry Andric Ordering == AtomicOrdering::AcquireRelease)
43978f0fd8f6SDimitry Andric return error("Invalid record");
43983ca95b02SDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
43998f0fd8f6SDimitry Andric return error("Invalid record");
4400c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
44016122f3e6SDimitry Andric
4402ff0cc061SDimitry Andric unsigned Align;
4403d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4404d88c1a5aSDimitry Andric return Err;
4405c4394386SDimitry Andric I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SSID);
4406ff0cc061SDimitry Andric
44076122f3e6SDimitry Andric InstructionList.push_back(I);
44086122f3e6SDimitry Andric break;
44096122f3e6SDimitry Andric }
4410ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE:
4411ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4412f22ef01cSRoman Divacky unsigned OpNum = 0;
4413f22ef01cSRoman Divacky Value *Val, *Ptr;
4414f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4415ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STORE
4416ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4417ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo,
4418ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(),
4419ff0cc061SDimitry Andric Val)) ||
4420f22ef01cSRoman Divacky OpNum + 2 != Record.size())
44218f0fd8f6SDimitry Andric return error("Invalid record");
4422f22ef01cSRoman Divacky
4423d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4424d88c1a5aSDimitry Andric return Err;
4425ff0cc061SDimitry Andric unsigned Align;
4426d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4427d88c1a5aSDimitry Andric return Err;
4428ff0cc061SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4429f22ef01cSRoman Divacky InstructionList.push_back(I);
4430f22ef01cSRoman Divacky break;
4431f22ef01cSRoman Divacky }
4432ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC:
4433ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4434c4394386SDimitry Andric // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
44356122f3e6SDimitry Andric unsigned OpNum = 0;
44366122f3e6SDimitry Andric Value *Val, *Ptr;
44376122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
44383ca95b02SDimitry Andric !isa<PointerType>(Ptr->getType()) ||
4439ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4440ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4441ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo,
4442ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(),
4443ff0cc061SDimitry Andric Val)) ||
44446122f3e6SDimitry Andric OpNum + 4 != Record.size())
44458f0fd8f6SDimitry Andric return error("Invalid record");
44466122f3e6SDimitry Andric
4447d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4448d88c1a5aSDimitry Andric return Err;
44498f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
44503ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic ||
44513ca95b02SDimitry Andric Ordering == AtomicOrdering::Acquire ||
44523ca95b02SDimitry Andric Ordering == AtomicOrdering::AcquireRelease)
44538f0fd8f6SDimitry Andric return error("Invalid record");
4454c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
44553ca95b02SDimitry Andric if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
44568f0fd8f6SDimitry Andric return error("Invalid record");
44576122f3e6SDimitry Andric
4458ff0cc061SDimitry Andric unsigned Align;
4459d88c1a5aSDimitry Andric if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4460d88c1a5aSDimitry Andric return Err;
4461c4394386SDimitry Andric I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID);
44626122f3e6SDimitry Andric InstructionList.push_back(I);
44636122f3e6SDimitry Andric break;
44646122f3e6SDimitry Andric }
4465ff0cc061SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
44666122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_CMPXCHG: {
4467c4394386SDimitry Andric // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, ssid,
446891bc56edSDimitry Andric // failureordering?, isweak?]
44696122f3e6SDimitry Andric unsigned OpNum = 0;
44706122f3e6SDimitry Andric Value *Ptr, *Cmp, *New;
44716122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4472ff0cc061SDimitry Andric (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4473ff0cc061SDimitry Andric ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4474ff0cc061SDimitry Andric : popValue(Record, OpNum, NextValueNo,
4475ff0cc061SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(),
4476ff0cc061SDimitry Andric Cmp)) ||
4477ff0cc061SDimitry Andric popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4478ff0cc061SDimitry Andric Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
44798f0fd8f6SDimitry Andric return error("Invalid record");
44808f0fd8f6SDimitry Andric AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
44813ca95b02SDimitry Andric if (SuccessOrdering == AtomicOrdering::NotAtomic ||
44823ca95b02SDimitry Andric SuccessOrdering == AtomicOrdering::Unordered)
44838f0fd8f6SDimitry Andric return error("Invalid record");
4484c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
448591bc56edSDimitry Andric
4486d88c1a5aSDimitry Andric if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4487d88c1a5aSDimitry Andric return Err;
448891bc56edSDimitry Andric AtomicOrdering FailureOrdering;
448991bc56edSDimitry Andric if (Record.size() < 7)
449091bc56edSDimitry Andric FailureOrdering =
449191bc56edSDimitry Andric AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
449291bc56edSDimitry Andric else
44938f0fd8f6SDimitry Andric FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
449491bc56edSDimitry Andric
449591bc56edSDimitry Andric I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4496c4394386SDimitry Andric SSID);
44976122f3e6SDimitry Andric cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
449891bc56edSDimitry Andric
449991bc56edSDimitry Andric if (Record.size() < 8) {
450091bc56edSDimitry Andric // Before weak cmpxchgs existed, the instruction simply returned the
450191bc56edSDimitry Andric // value loaded from memory, so bitcode files from that era will be
450291bc56edSDimitry Andric // expecting the first component of a modern cmpxchg.
450391bc56edSDimitry Andric CurBB->getInstList().push_back(I);
450491bc56edSDimitry Andric I = ExtractValueInst::Create(I, 0);
450591bc56edSDimitry Andric } else {
450691bc56edSDimitry Andric cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
450791bc56edSDimitry Andric }
450891bc56edSDimitry Andric
45096122f3e6SDimitry Andric InstructionList.push_back(I);
45106122f3e6SDimitry Andric break;
45116122f3e6SDimitry Andric }
45126122f3e6SDimitry Andric case bitc::FUNC_CODE_INST_ATOMICRMW: {
4513c4394386SDimitry Andric // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid]
45146122f3e6SDimitry Andric unsigned OpNum = 0;
45156122f3e6SDimitry Andric Value *Ptr, *Val;
45166122f3e6SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
45173ca95b02SDimitry Andric !isa<PointerType>(Ptr->getType()) ||
45183861d79fSDimitry Andric popValue(Record, OpNum, NextValueNo,
45196122f3e6SDimitry Andric cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
45206122f3e6SDimitry Andric OpNum+4 != Record.size())
45218f0fd8f6SDimitry Andric return error("Invalid record");
45228f0fd8f6SDimitry Andric AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
45236122f3e6SDimitry Andric if (Operation < AtomicRMWInst::FIRST_BINOP ||
45246122f3e6SDimitry Andric Operation > AtomicRMWInst::LAST_BINOP)
45258f0fd8f6SDimitry Andric return error("Invalid record");
45268f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
45273ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic ||
45283ca95b02SDimitry Andric Ordering == AtomicOrdering::Unordered)
45298f0fd8f6SDimitry Andric return error("Invalid record");
4530c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
4531c4394386SDimitry Andric I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
45326122f3e6SDimitry Andric cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
45336122f3e6SDimitry Andric InstructionList.push_back(I);
45346122f3e6SDimitry Andric break;
45356122f3e6SDimitry Andric }
4536c4394386SDimitry Andric case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
45376122f3e6SDimitry Andric if (2 != Record.size())
45388f0fd8f6SDimitry Andric return error("Invalid record");
45398f0fd8f6SDimitry Andric AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
45403ca95b02SDimitry Andric if (Ordering == AtomicOrdering::NotAtomic ||
45413ca95b02SDimitry Andric Ordering == AtomicOrdering::Unordered ||
45423ca95b02SDimitry Andric Ordering == AtomicOrdering::Monotonic)
45438f0fd8f6SDimitry Andric return error("Invalid record");
4544c4394386SDimitry Andric SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
4545c4394386SDimitry Andric I = new FenceInst(Context, Ordering, SSID);
45466122f3e6SDimitry Andric InstructionList.push_back(I);
45476122f3e6SDimitry Andric break;
45486122f3e6SDimitry Andric }
454917a519f9SDimitry Andric case bitc::FUNC_CODE_INST_CALL: {
45507d523365SDimitry Andric // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4551f22ef01cSRoman Divacky if (Record.size() < 3)
45528f0fd8f6SDimitry Andric return error("Invalid record");
4553f22ef01cSRoman Divacky
4554ff0cc061SDimitry Andric unsigned OpNum = 0;
45557a7e6055SDimitry Andric AttributeList PAL = getAttributes(Record[OpNum++]);
4556ff0cc061SDimitry Andric unsigned CCInfo = Record[OpNum++];
4557f22ef01cSRoman Divacky
45587d523365SDimitry Andric FastMathFlags FMF;
45597d523365SDimitry Andric if ((CCInfo >> bitc::CALL_FMF) & 1) {
45607d523365SDimitry Andric FMF = getDecodedFastMathFlags(Record[OpNum++]);
45617d523365SDimitry Andric if (!FMF.any())
45627d523365SDimitry Andric return error("Fast math flags indicator set for call with no FMF");
45637d523365SDimitry Andric }
45647d523365SDimitry Andric
4565ff0cc061SDimitry Andric FunctionType *FTy = nullptr;
45667d523365SDimitry Andric if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4567ff0cc061SDimitry Andric !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
45688f0fd8f6SDimitry Andric return error("Explicit call type is not a function type");
4569ff0cc061SDimitry Andric
4570f22ef01cSRoman Divacky Value *Callee;
4571f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
45728f0fd8f6SDimitry Andric return error("Invalid record");
4573f22ef01cSRoman Divacky
45746122f3e6SDimitry Andric PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4575ff0cc061SDimitry Andric if (!OpTy)
45768f0fd8f6SDimitry Andric return error("Callee is not a pointer type");
4577ff0cc061SDimitry Andric if (!FTy) {
4578ff0cc061SDimitry Andric FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4579ff0cc061SDimitry Andric if (!FTy)
45808f0fd8f6SDimitry Andric return error("Callee is not of pointer to function type");
4581ff0cc061SDimitry Andric } else if (OpTy->getElementType() != FTy)
45828f0fd8f6SDimitry Andric return error("Explicit call type does not match pointee type of "
4583ff0cc061SDimitry Andric "callee operand");
4584ff0cc061SDimitry Andric if (Record.size() < FTy->getNumParams() + OpNum)
45858f0fd8f6SDimitry Andric return error("Insufficient operands to call");
4586f22ef01cSRoman Divacky
4587f22ef01cSRoman Divacky SmallVector<Value*, 16> Args;
4588f22ef01cSRoman Divacky // Read the fixed params.
4589f22ef01cSRoman Divacky for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
459017a519f9SDimitry Andric if (FTy->getParamType(i)->isLabelTy())
4591f22ef01cSRoman Divacky Args.push_back(getBasicBlock(Record[OpNum]));
4592f22ef01cSRoman Divacky else
45933861d79fSDimitry Andric Args.push_back(getValue(Record, OpNum, NextValueNo,
45943861d79fSDimitry Andric FTy->getParamType(i)));
459591bc56edSDimitry Andric if (!Args.back())
45968f0fd8f6SDimitry Andric return error("Invalid record");
4597f22ef01cSRoman Divacky }
4598f22ef01cSRoman Divacky
4599f22ef01cSRoman Divacky // Read type/value pairs for varargs params.
4600f22ef01cSRoman Divacky if (!FTy->isVarArg()) {
4601f22ef01cSRoman Divacky if (OpNum != Record.size())
46028f0fd8f6SDimitry Andric return error("Invalid record");
4603f22ef01cSRoman Divacky } else {
4604f22ef01cSRoman Divacky while (OpNum != Record.size()) {
4605f22ef01cSRoman Divacky Value *Op;
4606f22ef01cSRoman Divacky if (getValueTypePair(Record, OpNum, NextValueNo, Op))
46078f0fd8f6SDimitry Andric return error("Invalid record");
4608f22ef01cSRoman Divacky Args.push_back(Op);
4609f22ef01cSRoman Divacky }
4610f22ef01cSRoman Divacky }
4611f22ef01cSRoman Divacky
46127d523365SDimitry Andric I = CallInst::Create(FTy, Callee, Args, OperandBundles);
46137d523365SDimitry Andric OperandBundles.clear();
4614f22ef01cSRoman Divacky InstructionList.push_back(I);
4615f22ef01cSRoman Divacky cast<CallInst>(I)->setCallingConv(
46167d523365SDimitry Andric static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
461791bc56edSDimitry Andric CallInst::TailCallKind TCK = CallInst::TCK_None;
46187d523365SDimitry Andric if (CCInfo & 1 << bitc::CALL_TAIL)
461991bc56edSDimitry Andric TCK = CallInst::TCK_Tail;
46207d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
462191bc56edSDimitry Andric TCK = CallInst::TCK_MustTail;
46227d523365SDimitry Andric if (CCInfo & (1 << bitc::CALL_NOTAIL))
46237d523365SDimitry Andric TCK = CallInst::TCK_NoTail;
462491bc56edSDimitry Andric cast<CallInst>(I)->setTailCallKind(TCK);
4625f22ef01cSRoman Divacky cast<CallInst>(I)->setAttributes(PAL);
46267d523365SDimitry Andric if (FMF.any()) {
46277d523365SDimitry Andric if (!isa<FPMathOperator>(I))
46287d523365SDimitry Andric return error("Fast-math-flags specified for call without "
46297d523365SDimitry Andric "floating-point scalar or vector return type");
46307d523365SDimitry Andric I->setFastMathFlags(FMF);
46317d523365SDimitry Andric }
4632f22ef01cSRoman Divacky break;
4633f22ef01cSRoman Divacky }
4634f22ef01cSRoman Divacky case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4635f22ef01cSRoman Divacky if (Record.size() < 3)
46368f0fd8f6SDimitry Andric return error("Invalid record");
46376122f3e6SDimitry Andric Type *OpTy = getTypeByID(Record[0]);
46383861d79fSDimitry Andric Value *Op = getValue(Record, 1, NextValueNo, OpTy);
46396122f3e6SDimitry Andric Type *ResTy = getTypeByID(Record[2]);
4640f22ef01cSRoman Divacky if (!OpTy || !Op || !ResTy)
46418f0fd8f6SDimitry Andric return error("Invalid record");
4642f22ef01cSRoman Divacky I = new VAArgInst(Op, ResTy);
4643f22ef01cSRoman Divacky InstructionList.push_back(I);
4644f22ef01cSRoman Divacky break;
4645f22ef01cSRoman Divacky }
46467d523365SDimitry Andric
46477d523365SDimitry Andric case bitc::FUNC_CODE_OPERAND_BUNDLE: {
46487d523365SDimitry Andric // A call or an invoke can be optionally prefixed with some variable
46497d523365SDimitry Andric // number of operand bundle blocks. These blocks are read into
46507d523365SDimitry Andric // OperandBundles and consumed at the next call or invoke instruction.
46517d523365SDimitry Andric
46527d523365SDimitry Andric if (Record.size() < 1 || Record[0] >= BundleTags.size())
46537d523365SDimitry Andric return error("Invalid record");
46547d523365SDimitry Andric
46557d523365SDimitry Andric std::vector<Value *> Inputs;
46567d523365SDimitry Andric
46577d523365SDimitry Andric unsigned OpNum = 1;
46587d523365SDimitry Andric while (OpNum != Record.size()) {
46597d523365SDimitry Andric Value *Op;
46607d523365SDimitry Andric if (getValueTypePair(Record, OpNum, NextValueNo, Op))
46617d523365SDimitry Andric return error("Invalid record");
46627d523365SDimitry Andric Inputs.push_back(Op);
46637d523365SDimitry Andric }
46647d523365SDimitry Andric
46657d523365SDimitry Andric OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
46667d523365SDimitry Andric continue;
46677d523365SDimitry Andric }
4668f22ef01cSRoman Divacky }
4669f22ef01cSRoman Divacky
4670f22ef01cSRoman Divacky // Add instruction to end of current BB. If there is no current BB, reject
4671f22ef01cSRoman Divacky // this file.
467291bc56edSDimitry Andric if (!CurBB) {
4673d8866befSDimitry Andric I->deleteValue();
46748f0fd8f6SDimitry Andric return error("Invalid instruction with no BB");
4675f22ef01cSRoman Divacky }
46767d523365SDimitry Andric if (!OperandBundles.empty()) {
4677d8866befSDimitry Andric I->deleteValue();
46787d523365SDimitry Andric return error("Operand bundles found with no consumer");
46797d523365SDimitry Andric }
4680f22ef01cSRoman Divacky CurBB->getInstList().push_back(I);
4681f22ef01cSRoman Divacky
4682f22ef01cSRoman Divacky // If this was a terminator instruction, move to the next block.
4683*b5893f02SDimitry Andric if (I->isTerminator()) {
4684f22ef01cSRoman Divacky ++CurBBNo;
468591bc56edSDimitry Andric CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4686f22ef01cSRoman Divacky }
4687f22ef01cSRoman Divacky
4688f22ef01cSRoman Divacky // Non-void values get registered in the value table for future use.
4689f22ef01cSRoman Divacky if (I && !I->getType()->isVoidTy())
46908f0fd8f6SDimitry Andric ValueList.assignValue(I, NextValueNo++);
4691f22ef01cSRoman Divacky }
4692f22ef01cSRoman Divacky
4693139f7f9bSDimitry Andric OutOfRecordLoop:
4694139f7f9bSDimitry Andric
46957d523365SDimitry Andric if (!OperandBundles.empty())
46967d523365SDimitry Andric return error("Operand bundles found with no consumer");
46977d523365SDimitry Andric
4698f22ef01cSRoman Divacky // Check the function list for unresolved values.
4699f22ef01cSRoman Divacky if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
470091bc56edSDimitry Andric if (!A->getParent()) {
4701f22ef01cSRoman Divacky // We found at least one unresolved value. Nuke them all to avoid leaks.
4702f22ef01cSRoman Divacky for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
470391bc56edSDimitry Andric if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4704f22ef01cSRoman Divacky A->replaceAllUsesWith(UndefValue::get(A->getType()));
4705f22ef01cSRoman Divacky delete A;
4706f22ef01cSRoman Divacky }
4707f22ef01cSRoman Divacky }
47088f0fd8f6SDimitry Andric return error("Never resolved value found in function");
4709f22ef01cSRoman Divacky }
4710f22ef01cSRoman Divacky }
4711f22ef01cSRoman Divacky
47123ca95b02SDimitry Andric // Unexpected unresolved metadata about to be dropped.
4713d88c1a5aSDimitry Andric if (MDLoader->hasFwdRefs())
47143ca95b02SDimitry Andric return error("Invalid function metadata: outgoing forward refs");
4715e580952dSDimitry Andric
4716f22ef01cSRoman Divacky // Trim the value list down to the size it was before we parsed this function.
4717f22ef01cSRoman Divacky ValueList.shrinkTo(ModuleValueListSize);
4718d88c1a5aSDimitry Andric MDLoader->shrinkTo(ModuleMDLoaderSize);
4719f22ef01cSRoman Divacky std::vector<BasicBlock*>().swap(FunctionBBs);
4720d88c1a5aSDimitry Andric return Error::success();
4721f22ef01cSRoman Divacky }
4722f22ef01cSRoman Divacky
4723f785676fSDimitry Andric /// Find the function body in the bitcode stream
findFunctionInStream(Function * F,DenseMap<Function *,uint64_t>::iterator DeferredFunctionInfoIterator)4724d88c1a5aSDimitry Andric Error BitcodeReader::findFunctionInStream(
472591bc56edSDimitry Andric Function *F,
4726dff0c46cSDimitry Andric DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4727dff0c46cSDimitry Andric while (DeferredFunctionInfoIterator->second == 0) {
47287d523365SDimitry Andric // This is the fallback handling for the old format bitcode that
47297d523365SDimitry Andric // didn't contain the function index in the VST, or when we have
47307d523365SDimitry Andric // an anonymous function which would not have a VST entry.
47317d523365SDimitry Andric // Assert that we have one of those two cases.
47327d523365SDimitry Andric assert(VSTOffset == 0 || !F->hasName());
47337d523365SDimitry Andric // Parse the next body in the stream and set its position in the
47347d523365SDimitry Andric // DeferredFunctionInfo map.
4735d88c1a5aSDimitry Andric if (Error Err = rememberAndSkipFunctionBodies())
4736d88c1a5aSDimitry Andric return Err;
4737dff0c46cSDimitry Andric }
4738d88c1a5aSDimitry Andric return Error::success();
4739dff0c46cSDimitry Andric }
4740dff0c46cSDimitry Andric
getDecodedSyncScopeID(unsigned Val)4741c4394386SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
4742c4394386SDimitry Andric if (Val == SyncScope::SingleThread || Val == SyncScope::System)
4743c4394386SDimitry Andric return SyncScope::ID(Val);
4744c4394386SDimitry Andric if (Val >= SSIDs.size())
4745c4394386SDimitry Andric return SyncScope::System; // Map unknown synchronization scopes to system.
4746c4394386SDimitry Andric return SSIDs[Val];
4747c4394386SDimitry Andric }
4748c4394386SDimitry Andric
4749f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
4750f22ef01cSRoman Divacky // GVMaterializer implementation
4751f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
4752f22ef01cSRoman Divacky
materialize(GlobalValue * GV)4753d88c1a5aSDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) {
4754f22ef01cSRoman Divacky Function *F = dyn_cast<Function>(GV);
4755f22ef01cSRoman Divacky // If it's not a function or is already material, ignore the request.
4756f785676fSDimitry Andric if (!F || !F->isMaterializable())
4757d88c1a5aSDimitry Andric return Error::success();
4758f22ef01cSRoman Divacky
4759f22ef01cSRoman Divacky DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4760f22ef01cSRoman Divacky assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4761dff0c46cSDimitry Andric // If its position is recorded as 0, its body is somewhere in the stream
4762dff0c46cSDimitry Andric // but we haven't seen it yet.
47633dac3a9bSDimitry Andric if (DFII->second == 0)
4764d88c1a5aSDimitry Andric if (Error Err = findFunctionInStream(F, DFII))
4765d88c1a5aSDimitry Andric return Err;
4766f22ef01cSRoman Divacky
47673ca95b02SDimitry Andric // Materialize metadata before parsing any function bodies.
4768d88c1a5aSDimitry Andric if (Error Err = materializeMetadata())
4769d88c1a5aSDimitry Andric return Err;
47703ca95b02SDimitry Andric
4771f22ef01cSRoman Divacky // Move the bit stream to the saved position of the deferred function body.
4772f22ef01cSRoman Divacky Stream.JumpToBit(DFII->second);
4773f22ef01cSRoman Divacky
4774d88c1a5aSDimitry Andric if (Error Err = parseFunctionBody(F))
4775d88c1a5aSDimitry Andric return Err;
477639d628a0SDimitry Andric F->setIsMaterializable(false);
4777f22ef01cSRoman Divacky
4778ff0cc061SDimitry Andric if (StripDebugInfo)
4779ff0cc061SDimitry Andric stripDebugInfo(*F);
4780ff0cc061SDimitry Andric
4781f22ef01cSRoman Divacky // Upgrade any old intrinsic calls in the function.
47823dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) {
47837d523365SDimitry Andric for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
47847d523365SDimitry Andric UI != UE;) {
47853dac3a9bSDimitry Andric User *U = *UI;
47863dac3a9bSDimitry Andric ++UI;
47873dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U))
47883dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second);
4789f22ef01cSRoman Divacky }
4790f22ef01cSRoman Divacky }
4791f22ef01cSRoman Divacky
47923ca95b02SDimitry Andric // Update calls to the remangled intrinsics
47933ca95b02SDimitry Andric for (auto &I : RemangledIntrinsics)
47943ca95b02SDimitry Andric for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
47953ca95b02SDimitry Andric UI != UE;)
47963ca95b02SDimitry Andric // Don't expect any other users than call sites
47973ca95b02SDimitry Andric CallSite(*UI++).setCalledFunction(I.second);
47983ca95b02SDimitry Andric
47997d523365SDimitry Andric // Finish fn->subprogram upgrade for materialized functions.
4800d88c1a5aSDimitry Andric if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
48017d523365SDimitry Andric F->setSubprogram(SP);
48027d523365SDimitry Andric
4803d88c1a5aSDimitry Andric // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4804d88c1a5aSDimitry Andric if (!MDLoader->isStrippingTBAA()) {
4805d88c1a5aSDimitry Andric for (auto &I : instructions(F)) {
4806d88c1a5aSDimitry Andric MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4807d88c1a5aSDimitry Andric if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4808d88c1a5aSDimitry Andric continue;
4809d88c1a5aSDimitry Andric MDLoader->setStripTBAA(true);
4810d88c1a5aSDimitry Andric stripTBAA(F->getParent());
4811d88c1a5aSDimitry Andric }
4812d88c1a5aSDimitry Andric }
4813d88c1a5aSDimitry Andric
481439d628a0SDimitry Andric // Bring in any functions that this function forward-referenced via
481539d628a0SDimitry Andric // blockaddresses.
481639d628a0SDimitry Andric return materializeForwardReferencedFunctions();
4817f22ef01cSRoman Divacky }
4818f22ef01cSRoman Divacky
materializeModule()4819d88c1a5aSDimitry Andric Error BitcodeReader::materializeModule() {
4820d88c1a5aSDimitry Andric if (Error Err = materializeMetadata())
4821d88c1a5aSDimitry Andric return Err;
4822ff0cc061SDimitry Andric
482339d628a0SDimitry Andric // Promise to materialize all forward references.
482439d628a0SDimitry Andric WillMaterializeAllForwardRefs = true;
482539d628a0SDimitry Andric
4826f22ef01cSRoman Divacky // Iterate over the module, deserializing any functions that are still on
4827f22ef01cSRoman Divacky // disk.
48287d523365SDimitry Andric for (Function &F : *TheModule) {
4829d88c1a5aSDimitry Andric if (Error Err = materialize(&F))
4830d88c1a5aSDimitry Andric return Err;
4831f785676fSDimitry Andric }
48327d523365SDimitry Andric // At this point, if there are any function bodies, parse the rest of
48337d523365SDimitry Andric // the bits in the module past the last function block we have recorded
48347d523365SDimitry Andric // through either lazy scanning or the VST.
48357d523365SDimitry Andric if (LastFunctionBlockBit || NextUnreadBit)
4836d88c1a5aSDimitry Andric if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4837d88c1a5aSDimitry Andric ? LastFunctionBlockBit
4838d88c1a5aSDimitry Andric : NextUnreadBit))
4839d88c1a5aSDimitry Andric return Err;
4840dff0c46cSDimitry Andric
484139d628a0SDimitry Andric // Check that all block address forward references got resolved (as we
484239d628a0SDimitry Andric // promised above).
484339d628a0SDimitry Andric if (!BasicBlockFwdRefs.empty())
48448f0fd8f6SDimitry Andric return error("Never resolved function from blockaddress");
484539d628a0SDimitry Andric
4846f22ef01cSRoman Divacky // Upgrade any intrinsic calls that slipped through (should not happen!) and
4847f22ef01cSRoman Divacky // delete the old functions to clean up. We can't do this unless the entire
4848f22ef01cSRoman Divacky // module is materialized because there could always be another function body
4849f22ef01cSRoman Divacky // with calls to the old function.
48503dac3a9bSDimitry Andric for (auto &I : UpgradedIntrinsics) {
48513dac3a9bSDimitry Andric for (auto *U : I.first->users()) {
48523dac3a9bSDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(U))
48533dac3a9bSDimitry Andric UpgradeIntrinsicCall(CI, I.second);
4854f22ef01cSRoman Divacky }
48553dac3a9bSDimitry Andric if (!I.first->use_empty())
48563dac3a9bSDimitry Andric I.first->replaceAllUsesWith(I.second);
48573dac3a9bSDimitry Andric I.first->eraseFromParent();
4858f22ef01cSRoman Divacky }
48593dac3a9bSDimitry Andric UpgradedIntrinsics.clear();
48603ca95b02SDimitry Andric // Do the same for remangled intrinsics
48613ca95b02SDimitry Andric for (auto &I : RemangledIntrinsics) {
48623ca95b02SDimitry Andric I.first->replaceAllUsesWith(I.second);
48633ca95b02SDimitry Andric I.first->eraseFromParent();
48643ca95b02SDimitry Andric }
48653ca95b02SDimitry Andric RemangledIntrinsics.clear();
4866f785676fSDimitry Andric
48677d523365SDimitry Andric UpgradeDebugInfo(*TheModule);
48683ca95b02SDimitry Andric
48693ca95b02SDimitry Andric UpgradeModuleFlags(*TheModule);
48704ba319b5SDimitry Andric
48714ba319b5SDimitry Andric UpgradeRetainReleaseMarker(*TheModule);
48724ba319b5SDimitry Andric
4873d88c1a5aSDimitry Andric return Error::success();
4874dff0c46cSDimitry Andric }
48756122f3e6SDimitry Andric
getIdentifiedStructTypes() const487639d628a0SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
487739d628a0SDimitry Andric return IdentifiedStructTypes;
487839d628a0SDimitry Andric }
487939d628a0SDimitry Andric
ModuleSummaryIndexBitcodeReader(BitstreamCursor Cursor,StringRef Strtab,ModuleSummaryIndex & TheIndex,StringRef ModulePath,unsigned ModuleId)48803ca95b02SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4881f37b6182SDimitry Andric BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
4882f37b6182SDimitry Andric StringRef ModulePath, unsigned ModuleId)
4883f37b6182SDimitry Andric : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
4884f37b6182SDimitry Andric ModulePath(ModulePath), ModuleId(ModuleId) {}
4885f37b6182SDimitry Andric
addThisModule()48864ba319b5SDimitry Andric void ModuleSummaryIndexBitcodeReader::addThisModule() {
48874ba319b5SDimitry Andric TheIndex.addModule(ModulePath, ModuleId);
48884ba319b5SDimitry Andric }
48894ba319b5SDimitry Andric
489024d58133SDimitry Andric ModuleSummaryIndex::ModuleInfo *
getThisModule()48914ba319b5SDimitry Andric ModuleSummaryIndexBitcodeReader::getThisModule() {
48924ba319b5SDimitry Andric return TheIndex.getModule(ModulePath);
4893f37b6182SDimitry Andric }
48943ca95b02SDimitry Andric
48950f5676f4SDimitry Andric std::pair<ValueInfo, GlobalValue::GUID>
getValueInfoFromValueId(unsigned ValueId)48960f5676f4SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
48970f5676f4SDimitry Andric auto VGI = ValueIdToValueInfoMap[ValueId];
48980f5676f4SDimitry Andric assert(VGI.first);
48990f5676f4SDimitry Andric return VGI;
49007d523365SDimitry Andric }
49017d523365SDimitry Andric
setValueGUID(uint64_t ValueID,StringRef ValueName,GlobalValue::LinkageTypes Linkage,StringRef SourceFileName)49026bc11b14SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID(
49036bc11b14SDimitry Andric uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
49046bc11b14SDimitry Andric StringRef SourceFileName) {
49056bc11b14SDimitry Andric std::string GlobalId =
49066bc11b14SDimitry Andric GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
49076bc11b14SDimitry Andric auto ValueGUID = GlobalValue::getGUID(GlobalId);
49086bc11b14SDimitry Andric auto OriginalNameID = ValueGUID;
49096bc11b14SDimitry Andric if (GlobalValue::isLocalLinkage(Linkage))
49106bc11b14SDimitry Andric OriginalNameID = GlobalValue::getGUID(ValueName);
49116bc11b14SDimitry Andric if (PrintSummaryGUIDs)
49126bc11b14SDimitry Andric dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
49136bc11b14SDimitry Andric << ValueName << "\n";
49144ba319b5SDimitry Andric
49154ba319b5SDimitry Andric // UseStrtab is false for legacy summary formats and value names are
49164ba319b5SDimitry Andric // created on stack. In that case we save the name in a string saver in
49174ba319b5SDimitry Andric // the index so that the value name can be recorded.
49184ba319b5SDimitry Andric ValueIdToValueInfoMap[ValueID] = std::make_pair(
49194ba319b5SDimitry Andric TheIndex.getOrInsertValueInfo(
49204ba319b5SDimitry Andric ValueGUID,
4921*b5893f02SDimitry Andric UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
49224ba319b5SDimitry Andric OriginalNameID);
49236bc11b14SDimitry Andric }
49246bc11b14SDimitry Andric
49253ca95b02SDimitry Andric // Specialized value symbol table parser used when reading module index
49263ca95b02SDimitry Andric // blocks where we don't actually create global values. The parsed information
49273ca95b02SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries.
parseValueSymbolTable(uint64_t Offset,DenseMap<unsigned,GlobalValue::LinkageTypes> & ValueIdToLinkageMap)4928d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
49293ca95b02SDimitry Andric uint64_t Offset,
49303ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
49316bc11b14SDimitry Andric // With a strtab the VST is not required to parse the summary.
49326bc11b14SDimitry Andric if (UseStrtab)
49336bc11b14SDimitry Andric return Error::success();
49346bc11b14SDimitry Andric
49353ca95b02SDimitry Andric assert(Offset > 0 && "Expected non-zero VST offset");
49363ca95b02SDimitry Andric uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
49377d523365SDimitry Andric
49387d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
49397d523365SDimitry Andric return error("Invalid record");
49407d523365SDimitry Andric
49417d523365SDimitry Andric SmallVector<uint64_t, 64> Record;
49427d523365SDimitry Andric
49437d523365SDimitry Andric // Read all the records for this value table.
49447d523365SDimitry Andric SmallString<128> ValueName;
4945d88c1a5aSDimitry Andric
4946d88c1a5aSDimitry Andric while (true) {
49477d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
49487d523365SDimitry Andric
49497d523365SDimitry Andric switch (Entry.Kind) {
49507d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
49517d523365SDimitry Andric case BitstreamEntry::Error:
49527d523365SDimitry Andric return error("Malformed block");
49537d523365SDimitry Andric case BitstreamEntry::EndBlock:
49543ca95b02SDimitry Andric // Done parsing VST, jump back to wherever we came from.
49553ca95b02SDimitry Andric Stream.JumpToBit(CurrentBit);
4956d88c1a5aSDimitry Andric return Error::success();
49577d523365SDimitry Andric case BitstreamEntry::Record:
49587d523365SDimitry Andric // The interesting case.
49597d523365SDimitry Andric break;
49607d523365SDimitry Andric }
49617d523365SDimitry Andric
49627d523365SDimitry Andric // Read a record.
49637d523365SDimitry Andric Record.clear();
49647d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) {
49657d523365SDimitry Andric default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
49667d523365SDimitry Andric break;
49673ca95b02SDimitry Andric case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
49683ca95b02SDimitry Andric if (convertToString(Record, 1, ValueName))
49693ca95b02SDimitry Andric return error("Invalid record");
49703ca95b02SDimitry Andric unsigned ValueID = Record[0];
49713ca95b02SDimitry Andric assert(!SourceFileName.empty());
49723ca95b02SDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID);
49733ca95b02SDimitry Andric assert(VLI != ValueIdToLinkageMap.end() &&
49743ca95b02SDimitry Andric "No linkage found for VST entry?");
49753ca95b02SDimitry Andric auto Linkage = VLI->second;
49766bc11b14SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
49773ca95b02SDimitry Andric ValueName.clear();
49783ca95b02SDimitry Andric break;
49793ca95b02SDimitry Andric }
49807d523365SDimitry Andric case bitc::VST_CODE_FNENTRY: {
49813ca95b02SDimitry Andric // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
49827d523365SDimitry Andric if (convertToString(Record, 2, ValueName))
49837d523365SDimitry Andric return error("Invalid record");
49847d523365SDimitry Andric unsigned ValueID = Record[0];
49853ca95b02SDimitry Andric assert(!SourceFileName.empty());
49863ca95b02SDimitry Andric auto VLI = ValueIdToLinkageMap.find(ValueID);
49873ca95b02SDimitry Andric assert(VLI != ValueIdToLinkageMap.end() &&
49883ca95b02SDimitry Andric "No linkage found for VST entry?");
49893ca95b02SDimitry Andric auto Linkage = VLI->second;
49906bc11b14SDimitry Andric setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
49917d523365SDimitry Andric ValueName.clear();
49927d523365SDimitry Andric break;
49937d523365SDimitry Andric }
49943ca95b02SDimitry Andric case bitc::VST_CODE_COMBINED_ENTRY: {
49953ca95b02SDimitry Andric // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
49963ca95b02SDimitry Andric unsigned ValueID = Record[0];
49973ca95b02SDimitry Andric GlobalValue::GUID RefGUID = Record[1];
49983ca95b02SDimitry Andric // The "original name", which is the second value of the pair will be
49993ca95b02SDimitry Andric // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
50000f5676f4SDimitry Andric ValueIdToValueInfoMap[ValueID] =
50010f5676f4SDimitry Andric std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
50027d523365SDimitry Andric break;
50037d523365SDimitry Andric }
50047d523365SDimitry Andric }
50057d523365SDimitry Andric }
50067d523365SDimitry Andric }
50077d523365SDimitry Andric
50083ca95b02SDimitry Andric // Parse just the blocks needed for building the index out of the module.
50093ca95b02SDimitry Andric // At the end of this routine the module Index is populated with a map
50103ca95b02SDimitry Andric // from global value id to GlobalValueSummary objects.
parseModule()5011f37b6182SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() {
50127d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
50137d523365SDimitry Andric return error("Invalid record");
50147d523365SDimitry Andric
50153ca95b02SDimitry Andric SmallVector<uint64_t, 64> Record;
50163ca95b02SDimitry Andric DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
50173ca95b02SDimitry Andric unsigned ValueId = 0;
50183ca95b02SDimitry Andric
50193ca95b02SDimitry Andric // Read the index for this module.
5020d88c1a5aSDimitry Andric while (true) {
50217d523365SDimitry Andric BitstreamEntry Entry = Stream.advance();
50227d523365SDimitry Andric
50237d523365SDimitry Andric switch (Entry.Kind) {
50247d523365SDimitry Andric case BitstreamEntry::Error:
50257d523365SDimitry Andric return error("Malformed block");
50267d523365SDimitry Andric case BitstreamEntry::EndBlock:
5027d88c1a5aSDimitry Andric return Error::success();
50287d523365SDimitry Andric
50297d523365SDimitry Andric case BitstreamEntry::SubBlock:
50307d523365SDimitry Andric switch (Entry.ID) {
50317d523365SDimitry Andric default: // Skip unknown content.
50327d523365SDimitry Andric if (Stream.SkipBlock())
50337d523365SDimitry Andric return error("Invalid record");
50347d523365SDimitry Andric break;
50357d523365SDimitry Andric case bitc::BLOCKINFO_BLOCK_ID:
50367d523365SDimitry Andric // Need to parse these to get abbrev ids (e.g. for VST)
5037d88c1a5aSDimitry Andric if (readBlockInfo())
50387d523365SDimitry Andric return error("Malformed block");
50397d523365SDimitry Andric break;
50407d523365SDimitry Andric case bitc::VALUE_SYMTAB_BLOCK_ID:
50413ca95b02SDimitry Andric // Should have been parsed earlier via VSTOffset, unless there
50423ca95b02SDimitry Andric // is no summary section.
50433ca95b02SDimitry Andric assert(((SeenValueSymbolTable && VSTOffset > 0) ||
50443ca95b02SDimitry Andric !SeenGlobalValSummary) &&
50453ca95b02SDimitry Andric "Expected early VST parse via VSTOffset record");
50467d523365SDimitry Andric if (Stream.SkipBlock())
50477d523365SDimitry Andric return error("Invalid record");
50483ca95b02SDimitry Andric break;
50493ca95b02SDimitry Andric case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
505024d58133SDimitry Andric case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
50514ba319b5SDimitry Andric // Add the module if it is a per-module index (has a source file name).
50524ba319b5SDimitry Andric if (!SourceFileName.empty())
50534ba319b5SDimitry Andric addThisModule();
50543ca95b02SDimitry Andric assert(!SeenValueSymbolTable &&
50553ca95b02SDimitry Andric "Already read VST when parsing summary block?");
5056d88c1a5aSDimitry Andric // We might not have a VST if there were no values in the
5057d88c1a5aSDimitry Andric // summary. An empty summary block generated when we are
5058d88c1a5aSDimitry Andric // performing ThinLTO compiles so we don't later invoke
5059d88c1a5aSDimitry Andric // the regular LTO process on them.
5060d88c1a5aSDimitry Andric if (VSTOffset > 0) {
5061d88c1a5aSDimitry Andric if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5062d88c1a5aSDimitry Andric return Err;
50633ca95b02SDimitry Andric SeenValueSymbolTable = true;
5064d88c1a5aSDimitry Andric }
50653ca95b02SDimitry Andric SeenGlobalValSummary = true;
506624d58133SDimitry Andric if (Error Err = parseEntireSummary(Entry.ID))
5067d88c1a5aSDimitry Andric return Err;
50687d523365SDimitry Andric break;
50697d523365SDimitry Andric case bitc::MODULE_STRTAB_BLOCK_ID:
5070d88c1a5aSDimitry Andric if (Error Err = parseModuleStringTable())
5071d88c1a5aSDimitry Andric return Err;
50727d523365SDimitry Andric break;
50737d523365SDimitry Andric }
50747d523365SDimitry Andric continue;
50757d523365SDimitry Andric
50763ca95b02SDimitry Andric case BitstreamEntry::Record: {
50773ca95b02SDimitry Andric Record.clear();
50783ca95b02SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record);
50793ca95b02SDimitry Andric switch (BitCode) {
50803ca95b02SDimitry Andric default:
50813ca95b02SDimitry Andric break; // Default behavior, ignore unknown content.
50826bc11b14SDimitry Andric case bitc::MODULE_CODE_VERSION: {
50836bc11b14SDimitry Andric if (Error Err = parseVersionRecord(Record).takeError())
50846bc11b14SDimitry Andric return Err;
50856bc11b14SDimitry Andric break;
50866bc11b14SDimitry Andric }
50873ca95b02SDimitry Andric /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
50883ca95b02SDimitry Andric case bitc::MODULE_CODE_SOURCE_FILENAME: {
50893ca95b02SDimitry Andric SmallString<128> ValueName;
50903ca95b02SDimitry Andric if (convertToString(Record, 0, ValueName))
50913ca95b02SDimitry Andric return error("Invalid record");
50923ca95b02SDimitry Andric SourceFileName = ValueName.c_str();
50933ca95b02SDimitry Andric break;
50943ca95b02SDimitry Andric }
50953ca95b02SDimitry Andric /// MODULE_CODE_HASH: [5*i32]
50963ca95b02SDimitry Andric case bitc::MODULE_CODE_HASH: {
50973ca95b02SDimitry Andric if (Record.size() != 5)
50983ca95b02SDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str());
50994ba319b5SDimitry Andric auto &Hash = getThisModule()->second.second;
51003ca95b02SDimitry Andric int Pos = 0;
51013ca95b02SDimitry Andric for (auto &Val : Record) {
51023ca95b02SDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set");
51033ca95b02SDimitry Andric Hash[Pos++] = Val;
51043ca95b02SDimitry Andric }
51053ca95b02SDimitry Andric break;
51063ca95b02SDimitry Andric }
51073ca95b02SDimitry Andric /// MODULE_CODE_VSTOFFSET: [offset]
51083ca95b02SDimitry Andric case bitc::MODULE_CODE_VSTOFFSET:
51093ca95b02SDimitry Andric if (Record.size() < 1)
51103ca95b02SDimitry Andric return error("Invalid record");
5111d88c1a5aSDimitry Andric // Note that we subtract 1 here because the offset is relative to one
5112d88c1a5aSDimitry Andric // word before the start of the identification or module block, which
5113d88c1a5aSDimitry Andric // was historically always the start of the regular bitcode header.
5114d88c1a5aSDimitry Andric VSTOffset = Record[0] - 1;
51153ca95b02SDimitry Andric break;
51166bc11b14SDimitry Andric // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
51176bc11b14SDimitry Andric // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
51186bc11b14SDimitry Andric // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
51196bc11b14SDimitry Andric // v2: [strtab offset, strtab size, v1]
51207a7e6055SDimitry Andric case bitc::MODULE_CODE_GLOBALVAR:
51217a7e6055SDimitry Andric case bitc::MODULE_CODE_FUNCTION:
51223ca95b02SDimitry Andric case bitc::MODULE_CODE_ALIAS: {
51236bc11b14SDimitry Andric StringRef Name;
51246bc11b14SDimitry Andric ArrayRef<uint64_t> GVRecord;
51256bc11b14SDimitry Andric std::tie(Name, GVRecord) = readNameFromStrtab(Record);
51266bc11b14SDimitry Andric if (GVRecord.size() <= 3)
51273ca95b02SDimitry Andric return error("Invalid record");
51286bc11b14SDimitry Andric uint64_t RawLinkage = GVRecord[3];
51293ca95b02SDimitry Andric GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
51306bc11b14SDimitry Andric if (!UseStrtab) {
51313ca95b02SDimitry Andric ValueIdToLinkageMap[ValueId++] = Linkage;
51323ca95b02SDimitry Andric break;
51333ca95b02SDimitry Andric }
51346bc11b14SDimitry Andric
51356bc11b14SDimitry Andric setValueGUID(ValueId++, Name, Linkage, SourceFileName);
51366bc11b14SDimitry Andric break;
51376bc11b14SDimitry Andric }
51383ca95b02SDimitry Andric }
51393ca95b02SDimitry Andric }
51407d523365SDimitry Andric continue;
51417d523365SDimitry Andric }
51427d523365SDimitry Andric }
51437d523365SDimitry Andric }
51447d523365SDimitry Andric
5145d88c1a5aSDimitry Andric std::vector<ValueInfo>
makeRefList(ArrayRef<uint64_t> Record)5146d88c1a5aSDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
5147d88c1a5aSDimitry Andric std::vector<ValueInfo> Ret;
5148d88c1a5aSDimitry Andric Ret.reserve(Record.size());
5149d88c1a5aSDimitry Andric for (uint64_t RefValueId : Record)
51500f5676f4SDimitry Andric Ret.push_back(getValueInfoFromValueId(RefValueId).first);
5151d88c1a5aSDimitry Andric return Ret;
5152d88c1a5aSDimitry Andric }
5153d88c1a5aSDimitry Andric
51544ba319b5SDimitry Andric std::vector<FunctionSummary::EdgeTy>
makeCallList(ArrayRef<uint64_t> Record,bool IsOldProfileFormat,bool HasProfile,bool HasRelBF)51554ba319b5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
51564ba319b5SDimitry Andric bool IsOldProfileFormat,
51574ba319b5SDimitry Andric bool HasProfile, bool HasRelBF) {
5158d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Ret;
5159d88c1a5aSDimitry Andric Ret.reserve(Record.size());
5160d88c1a5aSDimitry Andric for (unsigned I = 0, E = Record.size(); I != E; ++I) {
5161d88c1a5aSDimitry Andric CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
51624ba319b5SDimitry Andric uint64_t RelBF = 0;
51630f5676f4SDimitry Andric ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
5164d88c1a5aSDimitry Andric if (IsOldProfileFormat) {
5165d88c1a5aSDimitry Andric I += 1; // Skip old callsitecount field
5166d88c1a5aSDimitry Andric if (HasProfile)
5167d88c1a5aSDimitry Andric I += 1; // Skip old profilecount field
5168d88c1a5aSDimitry Andric } else if (HasProfile)
5169d88c1a5aSDimitry Andric Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
51704ba319b5SDimitry Andric else if (HasRelBF)
51714ba319b5SDimitry Andric RelBF = Record[++I];
51724ba319b5SDimitry Andric Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
5173d88c1a5aSDimitry Andric }
5174d88c1a5aSDimitry Andric return Ret;
5175d88c1a5aSDimitry Andric }
5176d88c1a5aSDimitry Andric
51774ba319b5SDimitry Andric static void
parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record,size_t & Slot,WholeProgramDevirtResolution & Wpd)51784ba319b5SDimitry Andric parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
51794ba319b5SDimitry Andric WholeProgramDevirtResolution &Wpd) {
51804ba319b5SDimitry Andric uint64_t ArgNum = Record[Slot++];
51814ba319b5SDimitry Andric WholeProgramDevirtResolution::ByArg &B =
51824ba319b5SDimitry Andric Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
51834ba319b5SDimitry Andric Slot += ArgNum;
51844ba319b5SDimitry Andric
51854ba319b5SDimitry Andric B.TheKind =
51864ba319b5SDimitry Andric static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
51874ba319b5SDimitry Andric B.Info = Record[Slot++];
51884ba319b5SDimitry Andric B.Byte = Record[Slot++];
51894ba319b5SDimitry Andric B.Bit = Record[Slot++];
51904ba319b5SDimitry Andric }
51914ba319b5SDimitry Andric
parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,StringRef Strtab,size_t & Slot,TypeIdSummary & TypeId)51924ba319b5SDimitry Andric static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
51934ba319b5SDimitry Andric StringRef Strtab, size_t &Slot,
51944ba319b5SDimitry Andric TypeIdSummary &TypeId) {
51954ba319b5SDimitry Andric uint64_t Id = Record[Slot++];
51964ba319b5SDimitry Andric WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
51974ba319b5SDimitry Andric
51984ba319b5SDimitry Andric Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
51994ba319b5SDimitry Andric Wpd.SingleImplName = {Strtab.data() + Record[Slot],
52004ba319b5SDimitry Andric static_cast<size_t>(Record[Slot + 1])};
52014ba319b5SDimitry Andric Slot += 2;
52024ba319b5SDimitry Andric
52034ba319b5SDimitry Andric uint64_t ResByArgNum = Record[Slot++];
52044ba319b5SDimitry Andric for (uint64_t I = 0; I != ResByArgNum; ++I)
52054ba319b5SDimitry Andric parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
52064ba319b5SDimitry Andric }
52074ba319b5SDimitry Andric
parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,StringRef Strtab,ModuleSummaryIndex & TheIndex)52084ba319b5SDimitry Andric static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
52094ba319b5SDimitry Andric StringRef Strtab,
52104ba319b5SDimitry Andric ModuleSummaryIndex &TheIndex) {
52114ba319b5SDimitry Andric size_t Slot = 0;
52124ba319b5SDimitry Andric TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
52134ba319b5SDimitry Andric {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
52144ba319b5SDimitry Andric Slot += 2;
52154ba319b5SDimitry Andric
52164ba319b5SDimitry Andric TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
52174ba319b5SDimitry Andric TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
52184ba319b5SDimitry Andric TypeId.TTRes.AlignLog2 = Record[Slot++];
52194ba319b5SDimitry Andric TypeId.TTRes.SizeM1 = Record[Slot++];
52204ba319b5SDimitry Andric TypeId.TTRes.BitMask = Record[Slot++];
52214ba319b5SDimitry Andric TypeId.TTRes.InlineBits = Record[Slot++];
52224ba319b5SDimitry Andric
52234ba319b5SDimitry Andric while (Slot < Record.size())
52244ba319b5SDimitry Andric parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
52254ba319b5SDimitry Andric }
52264ba319b5SDimitry Andric
setImmutableRefs(std::vector<ValueInfo> & Refs,unsigned Count)5227*b5893f02SDimitry Andric static void setImmutableRefs(std::vector<ValueInfo> &Refs, unsigned Count) {
5228*b5893f02SDimitry Andric // Read-only refs are in the end of the refs list.
5229*b5893f02SDimitry Andric for (unsigned RefNo = Refs.size() - Count; RefNo < Refs.size(); ++RefNo)
5230*b5893f02SDimitry Andric Refs[RefNo].setReadOnly();
5231*b5893f02SDimitry Andric }
5232*b5893f02SDimitry Andric
52333ca95b02SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary
52343ca95b02SDimitry Andric // objects in the index.
parseEntireSummary(unsigned ID)523524d58133SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
523624d58133SDimitry Andric if (Stream.EnterSubBlock(ID))
52377d523365SDimitry Andric return error("Invalid record");
52387d523365SDimitry Andric SmallVector<uint64_t, 64> Record;
52397d523365SDimitry Andric
52403ca95b02SDimitry Andric // Parse version
52413ca95b02SDimitry Andric {
52423ca95b02SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
52433ca95b02SDimitry Andric if (Entry.Kind != BitstreamEntry::Record)
52443ca95b02SDimitry Andric return error("Invalid Summary Block: record for version expected");
52453ca95b02SDimitry Andric if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
52463ca95b02SDimitry Andric return error("Invalid Summary Block: version expected");
52473ca95b02SDimitry Andric }
52483ca95b02SDimitry Andric const uint64_t Version = Record[0];
5249d88c1a5aSDimitry Andric const bool IsOldProfileFormat = Version == 1;
5250*b5893f02SDimitry Andric if (Version < 1 || Version > 6)
5251d88c1a5aSDimitry Andric return error("Invalid summary version " + Twine(Version) +
5252*b5893f02SDimitry Andric ". Version should be in the range [1-6].");
52533ca95b02SDimitry Andric Record.clear();
52543ca95b02SDimitry Andric
52553ca95b02SDimitry Andric // Keep around the last seen summary to be used when we see an optional
52563ca95b02SDimitry Andric // "OriginalName" attachement.
52573ca95b02SDimitry Andric GlobalValueSummary *LastSeenSummary = nullptr;
52587a7e6055SDimitry Andric GlobalValue::GUID LastSeenGUID = 0;
52597a7e6055SDimitry Andric
52607a7e6055SDimitry Andric // We can expect to see any number of type ID information records before
52617a7e6055SDimitry Andric // each function summary records; these variables store the information
52627a7e6055SDimitry Andric // collected so far so that it can be used to create the summary object.
5263d88c1a5aSDimitry Andric std::vector<GlobalValue::GUID> PendingTypeTests;
52647a7e6055SDimitry Andric std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
52657a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls;
52667a7e6055SDimitry Andric std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
52677a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls;
5268d88c1a5aSDimitry Andric
5269d88c1a5aSDimitry Andric while (true) {
52707d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
52717d523365SDimitry Andric
52727d523365SDimitry Andric switch (Entry.Kind) {
52737d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
52747d523365SDimitry Andric case BitstreamEntry::Error:
52757d523365SDimitry Andric return error("Malformed block");
52767d523365SDimitry Andric case BitstreamEntry::EndBlock:
5277d88c1a5aSDimitry Andric return Error::success();
52787d523365SDimitry Andric case BitstreamEntry::Record:
52797d523365SDimitry Andric // The interesting case.
52807d523365SDimitry Andric break;
52817d523365SDimitry Andric }
52827d523365SDimitry Andric
52837d523365SDimitry Andric // Read a record. The record format depends on whether this
52847d523365SDimitry Andric // is a per-module index or a combined index file. In the per-module
52857d523365SDimitry Andric // case the records contain the associated value's ID for correlation
52867d523365SDimitry Andric // with VST entries. In the combined index the correlation is done
52877d523365SDimitry Andric // via the bitcode offset of the summary records (which were saved
52887d523365SDimitry Andric // in the combined index VST entries). The records also contain
52897d523365SDimitry Andric // information used for ThinLTO renaming and importing.
52907d523365SDimitry Andric Record.clear();
52913ca95b02SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record);
52923ca95b02SDimitry Andric switch (BitCode) {
52937d523365SDimitry Andric default: // Default behavior: ignore.
52947d523365SDimitry Andric break;
52954ba319b5SDimitry Andric case bitc::FS_FLAGS: { // [flags]
52964ba319b5SDimitry Andric uint64_t Flags = Record[0];
5297*b5893f02SDimitry Andric // Scan flags.
5298*b5893f02SDimitry Andric assert(Flags <= 0x1f && "Unexpected bits in flag");
52994ba319b5SDimitry Andric
53004ba319b5SDimitry Andric // 1 bit: WithGlobalValueDeadStripping flag.
5301*b5893f02SDimitry Andric // Set on combined index only.
53024ba319b5SDimitry Andric if (Flags & 0x1)
53034ba319b5SDimitry Andric TheIndex.setWithGlobalValueDeadStripping();
53044ba319b5SDimitry Andric // 1 bit: SkipModuleByDistributedBackend flag.
5305*b5893f02SDimitry Andric // Set on combined index only.
53064ba319b5SDimitry Andric if (Flags & 0x2)
53074ba319b5SDimitry Andric TheIndex.setSkipModuleByDistributedBackend();
5308*b5893f02SDimitry Andric // 1 bit: HasSyntheticEntryCounts flag.
5309*b5893f02SDimitry Andric // Set on combined index only.
5310*b5893f02SDimitry Andric if (Flags & 0x4)
5311*b5893f02SDimitry Andric TheIndex.setHasSyntheticEntryCounts();
5312*b5893f02SDimitry Andric // 1 bit: DisableSplitLTOUnit flag.
5313*b5893f02SDimitry Andric // Set on per module indexes. It is up to the client to validate
5314*b5893f02SDimitry Andric // the consistency of this flag across modules being linked.
5315*b5893f02SDimitry Andric if (Flags & 0x8)
5316*b5893f02SDimitry Andric TheIndex.setEnableSplitLTOUnit();
5317*b5893f02SDimitry Andric // 1 bit: PartiallySplitLTOUnits flag.
5318*b5893f02SDimitry Andric // Set on combined index only.
5319*b5893f02SDimitry Andric if (Flags & 0x10)
5320*b5893f02SDimitry Andric TheIndex.setPartiallySplitLTOUnits();
53214ba319b5SDimitry Andric break;
53224ba319b5SDimitry Andric }
53236bc11b14SDimitry Andric case bitc::FS_VALUE_GUID: { // [valueid, refguid]
53246bc11b14SDimitry Andric uint64_t ValueID = Record[0];
53256bc11b14SDimitry Andric GlobalValue::GUID RefGUID = Record[1];
53260f5676f4SDimitry Andric ValueIdToValueInfoMap[ValueID] =
53270f5676f4SDimitry Andric std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
53286bc11b14SDimitry Andric break;
53296bc11b14SDimitry Andric }
53302cab237bSDimitry Andric // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
53312cab237bSDimitry Andric // numrefs x valueid, n x (valueid)]
53322cab237bSDimitry Andric // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
53333ca95b02SDimitry Andric // numrefs x valueid,
5334d88c1a5aSDimitry Andric // n x (valueid, hotness)]
53354ba319b5SDimitry Andric // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
53364ba319b5SDimitry Andric // numrefs x valueid,
53374ba319b5SDimitry Andric // n x (valueid, relblockfreq)]
53383ca95b02SDimitry Andric case bitc::FS_PERMODULE:
53394ba319b5SDimitry Andric case bitc::FS_PERMODULE_RELBF:
53403ca95b02SDimitry Andric case bitc::FS_PERMODULE_PROFILE: {
53417d523365SDimitry Andric unsigned ValueID = Record[0];
53423ca95b02SDimitry Andric uint64_t RawFlags = Record[1];
53437d523365SDimitry Andric unsigned InstCount = Record[2];
53442cab237bSDimitry Andric uint64_t RawFunFlags = 0;
53453ca95b02SDimitry Andric unsigned NumRefs = Record[3];
5346*b5893f02SDimitry Andric unsigned NumImmutableRefs = 0;
53472cab237bSDimitry Andric int RefListStartIndex = 4;
53482cab237bSDimitry Andric if (Version >= 4) {
53492cab237bSDimitry Andric RawFunFlags = Record[3];
53502cab237bSDimitry Andric NumRefs = Record[4];
53512cab237bSDimitry Andric RefListStartIndex = 5;
5352*b5893f02SDimitry Andric if (Version >= 5) {
5353*b5893f02SDimitry Andric NumImmutableRefs = Record[5];
5354*b5893f02SDimitry Andric RefListStartIndex = 6;
5355*b5893f02SDimitry Andric }
53562cab237bSDimitry Andric }
53572cab237bSDimitry Andric
53583ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
53597d523365SDimitry Andric // The module path string ref set in the summary must be owned by the
53607d523365SDimitry Andric // index's module string table. Since we don't have a module path
53617d523365SDimitry Andric // string table section in the per-module index, we create a single
53627d523365SDimitry Andric // module path string table entry with an empty (0) ID to take
53637d523365SDimitry Andric // ownership.
53643ca95b02SDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
53653ca95b02SDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs &&
53663ca95b02SDimitry Andric "Record size inconsistent with number of references");
5367d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = makeRefList(
5368d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
53693ca95b02SDimitry Andric bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
53704ba319b5SDimitry Andric bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
5371d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
5372d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
53734ba319b5SDimitry Andric IsOldProfileFormat, HasProfile, HasRelBF);
5374*b5893f02SDimitry Andric setImmutableRefs(Refs, NumImmutableRefs);
5375d88c1a5aSDimitry Andric auto FS = llvm::make_unique<FunctionSummary>(
5376*b5893f02SDimitry Andric Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
5377*b5893f02SDimitry Andric std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
53782cab237bSDimitry Andric std::move(PendingTypeTestAssumeVCalls),
53797a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadVCalls),
53807a7e6055SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls),
53817a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls));
5382d88c1a5aSDimitry Andric PendingTypeTests.clear();
53837a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.clear();
53847a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.clear();
53857a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.clear();
53867a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.clear();
53870f5676f4SDimitry Andric auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
53884ba319b5SDimitry Andric FS->setModulePath(getThisModule()->first());
53890f5676f4SDimitry Andric FS->setOriginalName(VIAndOriginalGUID.second);
53900f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
53913ca95b02SDimitry Andric break;
53923ca95b02SDimitry Andric }
53933ca95b02SDimitry Andric // FS_ALIAS: [valueid, flags, valueid]
53943ca95b02SDimitry Andric // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
53953ca95b02SDimitry Andric // they expect all aliasee summaries to be available.
53963ca95b02SDimitry Andric case bitc::FS_ALIAS: {
53973ca95b02SDimitry Andric unsigned ValueID = Record[0];
53983ca95b02SDimitry Andric uint64_t RawFlags = Record[1];
53993ca95b02SDimitry Andric unsigned AliaseeID = Record[2];
54003ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
54012cab237bSDimitry Andric auto AS = llvm::make_unique<AliasSummary>(Flags);
54023ca95b02SDimitry Andric // The module path string ref set in the summary must be owned by the
54033ca95b02SDimitry Andric // index's module string table. Since we don't have a module path
54043ca95b02SDimitry Andric // string table section in the per-module index, we create a single
54053ca95b02SDimitry Andric // module path string table entry with an empty (0) ID to take
54063ca95b02SDimitry Andric // ownership.
54074ba319b5SDimitry Andric AS->setModulePath(getThisModule()->first());
54083ca95b02SDimitry Andric
54090f5676f4SDimitry Andric GlobalValue::GUID AliaseeGUID =
54100f5676f4SDimitry Andric getValueInfoFromValueId(AliaseeID).first.getGUID();
5411f37b6182SDimitry Andric auto AliaseeInModule =
5412f37b6182SDimitry Andric TheIndex.findSummaryInModule(AliaseeGUID, ModulePath);
5413f37b6182SDimitry Andric if (!AliaseeInModule)
54143ca95b02SDimitry Andric return error("Alias expects aliasee summary to be parsed");
5415f37b6182SDimitry Andric AS->setAliasee(AliaseeInModule);
54162cab237bSDimitry Andric AS->setAliaseeGUID(AliaseeGUID);
54173ca95b02SDimitry Andric
54180f5676f4SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID);
54193ca95b02SDimitry Andric AS->setOriginalName(GUID.second);
5420d88c1a5aSDimitry Andric TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
54213ca95b02SDimitry Andric break;
54223ca95b02SDimitry Andric }
5423*b5893f02SDimitry Andric // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
54243ca95b02SDimitry Andric case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
54253ca95b02SDimitry Andric unsigned ValueID = Record[0];
54263ca95b02SDimitry Andric uint64_t RawFlags = Record[1];
5427*b5893f02SDimitry Andric unsigned RefArrayStart = 2;
5428*b5893f02SDimitry Andric GlobalVarSummary::GVarFlags GVF;
54293ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5430*b5893f02SDimitry Andric if (Version >= 5) {
5431*b5893f02SDimitry Andric GVF = getDecodedGVarFlags(Record[2]);
5432*b5893f02SDimitry Andric RefArrayStart = 3;
5433*b5893f02SDimitry Andric }
5434d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs =
5435*b5893f02SDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
5436*b5893f02SDimitry Andric auto FS =
5437*b5893f02SDimitry Andric llvm::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
54384ba319b5SDimitry Andric FS->setModulePath(getThisModule()->first());
54390f5676f4SDimitry Andric auto GUID = getValueInfoFromValueId(ValueID);
54403ca95b02SDimitry Andric FS->setOriginalName(GUID.second);
5441d88c1a5aSDimitry Andric TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
54423ca95b02SDimitry Andric break;
54433ca95b02SDimitry Andric }
54442cab237bSDimitry Andric // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
5445d88c1a5aSDimitry Andric // numrefs x valueid, n x (valueid)]
54462cab237bSDimitry Andric // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
5447d88c1a5aSDimitry Andric // numrefs x valueid, n x (valueid, hotness)]
54483ca95b02SDimitry Andric case bitc::FS_COMBINED:
54493ca95b02SDimitry Andric case bitc::FS_COMBINED_PROFILE: {
54503ca95b02SDimitry Andric unsigned ValueID = Record[0];
54513ca95b02SDimitry Andric uint64_t ModuleId = Record[1];
54523ca95b02SDimitry Andric uint64_t RawFlags = Record[2];
54533ca95b02SDimitry Andric unsigned InstCount = Record[3];
54542cab237bSDimitry Andric uint64_t RawFunFlags = 0;
5455*b5893f02SDimitry Andric uint64_t EntryCount = 0;
54563ca95b02SDimitry Andric unsigned NumRefs = Record[4];
5457*b5893f02SDimitry Andric unsigned NumImmutableRefs = 0;
54582cab237bSDimitry Andric int RefListStartIndex = 5;
54592cab237bSDimitry Andric
54602cab237bSDimitry Andric if (Version >= 4) {
54612cab237bSDimitry Andric RawFunFlags = Record[4];
54622cab237bSDimitry Andric RefListStartIndex = 6;
5463*b5893f02SDimitry Andric size_t NumRefsIndex = 5;
5464*b5893f02SDimitry Andric if (Version >= 5) {
5465*b5893f02SDimitry Andric RefListStartIndex = 7;
5466*b5893f02SDimitry Andric if (Version >= 6) {
5467*b5893f02SDimitry Andric NumRefsIndex = 6;
5468*b5893f02SDimitry Andric EntryCount = Record[5];
5469*b5893f02SDimitry Andric RefListStartIndex = 8;
5470*b5893f02SDimitry Andric }
5471*b5893f02SDimitry Andric NumImmutableRefs = Record[RefListStartIndex - 1];
5472*b5893f02SDimitry Andric }
5473*b5893f02SDimitry Andric NumRefs = Record[NumRefsIndex];
54742cab237bSDimitry Andric }
54752cab237bSDimitry Andric
54763ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
54773ca95b02SDimitry Andric int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
54783ca95b02SDimitry Andric assert(Record.size() >= RefListStartIndex + NumRefs &&
54793ca95b02SDimitry Andric "Record size inconsistent with number of references");
5480d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs = makeRefList(
5481d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
54823ca95b02SDimitry Andric bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5483d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5484d88c1a5aSDimitry Andric ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
54854ba319b5SDimitry Andric IsOldProfileFormat, HasProfile, false);
54860f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first;
5487*b5893f02SDimitry Andric setImmutableRefs(Refs, NumImmutableRefs);
5488d88c1a5aSDimitry Andric auto FS = llvm::make_unique<FunctionSummary>(
5489*b5893f02SDimitry Andric Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
5490*b5893f02SDimitry Andric std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
54912cab237bSDimitry Andric std::move(PendingTypeTestAssumeVCalls),
54927a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadVCalls),
54937a7e6055SDimitry Andric std::move(PendingTypeTestAssumeConstVCalls),
54947a7e6055SDimitry Andric std::move(PendingTypeCheckedLoadConstVCalls));
5495d88c1a5aSDimitry Andric PendingTypeTests.clear();
54967a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.clear();
54977a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.clear();
54987a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.clear();
54997a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.clear();
5500d88c1a5aSDimitry Andric LastSeenSummary = FS.get();
55010f5676f4SDimitry Andric LastSeenGUID = VI.getGUID();
5502d88c1a5aSDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]);
55030f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS));
55043ca95b02SDimitry Andric break;
55053ca95b02SDimitry Andric }
55063ca95b02SDimitry Andric // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
55073ca95b02SDimitry Andric // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
55083ca95b02SDimitry Andric // they expect all aliasee summaries to be available.
55093ca95b02SDimitry Andric case bitc::FS_COMBINED_ALIAS: {
55103ca95b02SDimitry Andric unsigned ValueID = Record[0];
55113ca95b02SDimitry Andric uint64_t ModuleId = Record[1];
55123ca95b02SDimitry Andric uint64_t RawFlags = Record[2];
55133ca95b02SDimitry Andric unsigned AliaseeValueId = Record[3];
55143ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
55152cab237bSDimitry Andric auto AS = llvm::make_unique<AliasSummary>(Flags);
55163ca95b02SDimitry Andric LastSeenSummary = AS.get();
55173ca95b02SDimitry Andric AS->setModulePath(ModuleIdMap[ModuleId]);
55183ca95b02SDimitry Andric
55190f5676f4SDimitry Andric auto AliaseeGUID =
55200f5676f4SDimitry Andric getValueInfoFromValueId(AliaseeValueId).first.getGUID();
55213ca95b02SDimitry Andric auto AliaseeInModule =
5522d88c1a5aSDimitry Andric TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
55233ca95b02SDimitry Andric AS->setAliasee(AliaseeInModule);
55242cab237bSDimitry Andric AS->setAliaseeGUID(AliaseeGUID);
55253ca95b02SDimitry Andric
55260f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first;
55270f5676f4SDimitry Andric LastSeenGUID = VI.getGUID();
55280f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(AS));
55293ca95b02SDimitry Andric break;
55303ca95b02SDimitry Andric }
55313ca95b02SDimitry Andric // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
55323ca95b02SDimitry Andric case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
55333ca95b02SDimitry Andric unsigned ValueID = Record[0];
55343ca95b02SDimitry Andric uint64_t ModuleId = Record[1];
55353ca95b02SDimitry Andric uint64_t RawFlags = Record[2];
5536*b5893f02SDimitry Andric unsigned RefArrayStart = 3;
5537*b5893f02SDimitry Andric GlobalVarSummary::GVarFlags GVF;
55383ca95b02SDimitry Andric auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5539*b5893f02SDimitry Andric if (Version >= 5) {
5540*b5893f02SDimitry Andric GVF = getDecodedGVarFlags(Record[3]);
5541*b5893f02SDimitry Andric RefArrayStart = 4;
5542*b5893f02SDimitry Andric }
5543d88c1a5aSDimitry Andric std::vector<ValueInfo> Refs =
5544*b5893f02SDimitry Andric makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
5545*b5893f02SDimitry Andric auto FS =
5546*b5893f02SDimitry Andric llvm::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
55473ca95b02SDimitry Andric LastSeenSummary = FS.get();
55483ca95b02SDimitry Andric FS->setModulePath(ModuleIdMap[ModuleId]);
55490f5676f4SDimitry Andric ValueInfo VI = getValueInfoFromValueId(ValueID).first;
55500f5676f4SDimitry Andric LastSeenGUID = VI.getGUID();
55510f5676f4SDimitry Andric TheIndex.addGlobalValueSummary(VI, std::move(FS));
55523ca95b02SDimitry Andric break;
55533ca95b02SDimitry Andric }
55543ca95b02SDimitry Andric // FS_COMBINED_ORIGINAL_NAME: [original_name]
55553ca95b02SDimitry Andric case bitc::FS_COMBINED_ORIGINAL_NAME: {
55563ca95b02SDimitry Andric uint64_t OriginalName = Record[0];
55573ca95b02SDimitry Andric if (!LastSeenSummary)
55583ca95b02SDimitry Andric return error("Name attachment that does not follow a combined record");
55593ca95b02SDimitry Andric LastSeenSummary->setOriginalName(OriginalName);
55607a7e6055SDimitry Andric TheIndex.addOriginalName(LastSeenGUID, OriginalName);
55613ca95b02SDimitry Andric // Reset the LastSeenSummary
55623ca95b02SDimitry Andric LastSeenSummary = nullptr;
55637a7e6055SDimitry Andric LastSeenGUID = 0;
5564d88c1a5aSDimitry Andric break;
5565d88c1a5aSDimitry Andric }
55662cab237bSDimitry Andric case bitc::FS_TYPE_TESTS:
5567d88c1a5aSDimitry Andric assert(PendingTypeTests.empty());
5568d88c1a5aSDimitry Andric PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5569d88c1a5aSDimitry Andric Record.end());
5570d88c1a5aSDimitry Andric break;
55712cab237bSDimitry Andric
55722cab237bSDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
55737a7e6055SDimitry Andric assert(PendingTypeTestAssumeVCalls.empty());
55747a7e6055SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2)
55757a7e6055SDimitry Andric PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
55767a7e6055SDimitry Andric break;
55772cab237bSDimitry Andric
55782cab237bSDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
55797a7e6055SDimitry Andric assert(PendingTypeCheckedLoadVCalls.empty());
55807a7e6055SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2)
55817a7e6055SDimitry Andric PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
55827a7e6055SDimitry Andric break;
55832cab237bSDimitry Andric
55842cab237bSDimitry Andric case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
55857a7e6055SDimitry Andric PendingTypeTestAssumeConstVCalls.push_back(
55867a7e6055SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
55877a7e6055SDimitry Andric break;
55882cab237bSDimitry Andric
55892cab237bSDimitry Andric case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
55907a7e6055SDimitry Andric PendingTypeCheckedLoadConstVCalls.push_back(
55917a7e6055SDimitry Andric {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
55927a7e6055SDimitry Andric break;
55932cab237bSDimitry Andric
559424d58133SDimitry Andric case bitc::FS_CFI_FUNCTION_DEFS: {
559524d58133SDimitry Andric std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
559624d58133SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2)
559724d58133SDimitry Andric CfiFunctionDefs.insert(
559824d58133SDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
559924d58133SDimitry Andric break;
560024d58133SDimitry Andric }
56014ba319b5SDimitry Andric
560224d58133SDimitry Andric case bitc::FS_CFI_FUNCTION_DECLS: {
560324d58133SDimitry Andric std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
560424d58133SDimitry Andric for (unsigned I = 0; I != Record.size(); I += 2)
560524d58133SDimitry Andric CfiFunctionDecls.insert(
560624d58133SDimitry Andric {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
560724d58133SDimitry Andric break;
560824d58133SDimitry Andric }
56094ba319b5SDimitry Andric
56104ba319b5SDimitry Andric case bitc::FS_TYPE_ID:
56114ba319b5SDimitry Andric parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
56124ba319b5SDimitry Andric break;
56137d523365SDimitry Andric }
56147d523365SDimitry Andric }
56157d523365SDimitry Andric llvm_unreachable("Exit infinite loop");
56167d523365SDimitry Andric }
56177d523365SDimitry Andric
56187d523365SDimitry Andric // Parse the module string table block into the Index.
56197d523365SDimitry Andric // This populates the ModulePathStringTable map in the index.
parseModuleStringTable()5620d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
56217d523365SDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
56227d523365SDimitry Andric return error("Invalid record");
56237d523365SDimitry Andric
56247d523365SDimitry Andric SmallVector<uint64_t, 64> Record;
56257d523365SDimitry Andric
56267d523365SDimitry Andric SmallString<128> ModulePath;
562724d58133SDimitry Andric ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
5628d88c1a5aSDimitry Andric
5629d88c1a5aSDimitry Andric while (true) {
56307d523365SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
56317d523365SDimitry Andric
56327d523365SDimitry Andric switch (Entry.Kind) {
56337d523365SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
56347d523365SDimitry Andric case BitstreamEntry::Error:
56357d523365SDimitry Andric return error("Malformed block");
56367d523365SDimitry Andric case BitstreamEntry::EndBlock:
5637d88c1a5aSDimitry Andric return Error::success();
56387d523365SDimitry Andric case BitstreamEntry::Record:
56397d523365SDimitry Andric // The interesting case.
56407d523365SDimitry Andric break;
56417d523365SDimitry Andric }
56427d523365SDimitry Andric
56437d523365SDimitry Andric Record.clear();
56447d523365SDimitry Andric switch (Stream.readRecord(Entry.ID, Record)) {
56457d523365SDimitry Andric default: // Default behavior: ignore.
56467d523365SDimitry Andric break;
56477d523365SDimitry Andric case bitc::MST_CODE_ENTRY: {
56487d523365SDimitry Andric // MST_ENTRY: [modid, namechar x N]
56493ca95b02SDimitry Andric uint64_t ModuleId = Record[0];
56503ca95b02SDimitry Andric
56517d523365SDimitry Andric if (convertToString(Record, 1, ModulePath))
56527d523365SDimitry Andric return error("Invalid record");
56533ca95b02SDimitry Andric
565424d58133SDimitry Andric LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
565524d58133SDimitry Andric ModuleIdMap[ModuleId] = LastSeenModule->first();
56563ca95b02SDimitry Andric
56577d523365SDimitry Andric ModulePath.clear();
56587d523365SDimitry Andric break;
56597d523365SDimitry Andric }
56603ca95b02SDimitry Andric /// MST_CODE_HASH: [5*i32]
56613ca95b02SDimitry Andric case bitc::MST_CODE_HASH: {
56623ca95b02SDimitry Andric if (Record.size() != 5)
56633ca95b02SDimitry Andric return error("Invalid hash length " + Twine(Record.size()).str());
566424d58133SDimitry Andric if (!LastSeenModule)
56653ca95b02SDimitry Andric return error("Invalid hash that does not follow a module path");
56663ca95b02SDimitry Andric int Pos = 0;
56673ca95b02SDimitry Andric for (auto &Val : Record) {
56683ca95b02SDimitry Andric assert(!(Val >> 32) && "Unexpected high bits set");
566924d58133SDimitry Andric LastSeenModule->second.second[Pos++] = Val;
56703ca95b02SDimitry Andric }
567124d58133SDimitry Andric // Reset LastSeenModule to avoid overriding the hash unexpectedly.
567224d58133SDimitry Andric LastSeenModule = nullptr;
56733ca95b02SDimitry Andric break;
56743ca95b02SDimitry Andric }
56757d523365SDimitry Andric }
56767d523365SDimitry Andric }
56777d523365SDimitry Andric llvm_unreachable("Exit infinite loop");
56787d523365SDimitry Andric }
56797d523365SDimitry Andric
5680f785676fSDimitry Andric namespace {
5681d88c1a5aSDimitry Andric
56823ca95b02SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
56833ca95b02SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
56843ca95b02SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
568591bc56edSDimitry Andric class BitcodeErrorCategoryType : public std::error_category {
name() const5686d88c1a5aSDimitry Andric const char *name() const noexcept override {
5687f785676fSDimitry Andric return "llvm.bitcode";
5688f785676fSDimitry Andric }
56892cab237bSDimitry Andric
message(int IE) const569091bc56edSDimitry Andric std::string message(int IE) const override {
569139d628a0SDimitry Andric BitcodeError E = static_cast<BitcodeError>(IE);
5692f785676fSDimitry Andric switch (E) {
569339d628a0SDimitry Andric case BitcodeError::CorruptedBitcode:
569439d628a0SDimitry Andric return "Corrupted bitcode";
5695f785676fSDimitry Andric }
5696f785676fSDimitry Andric llvm_unreachable("Unknown error type!");
5697f785676fSDimitry Andric }
5698f785676fSDimitry Andric };
5699d88c1a5aSDimitry Andric
57003ca95b02SDimitry Andric } // end anonymous namespace
5701f785676fSDimitry Andric
570239d628a0SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
570339d628a0SDimitry Andric
BitcodeErrorCategory()570439d628a0SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() {
570539d628a0SDimitry Andric return *ErrorCategory;
5706dff0c46cSDimitry Andric }
5707f22ef01cSRoman Divacky
readBlobInRecord(BitstreamCursor & Stream,unsigned Block,unsigned RecordID)5708a580b014SDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
5709a580b014SDimitry Andric unsigned Block, unsigned RecordID) {
5710a580b014SDimitry Andric if (Stream.EnterSubBlock(Block))
57116bc11b14SDimitry Andric return error("Invalid record");
57126bc11b14SDimitry Andric
57136bc11b14SDimitry Andric StringRef Strtab;
57142cab237bSDimitry Andric while (true) {
57156bc11b14SDimitry Andric BitstreamEntry Entry = Stream.advance();
57166bc11b14SDimitry Andric switch (Entry.Kind) {
57176bc11b14SDimitry Andric case BitstreamEntry::EndBlock:
57186bc11b14SDimitry Andric return Strtab;
57196bc11b14SDimitry Andric
57206bc11b14SDimitry Andric case BitstreamEntry::Error:
57216bc11b14SDimitry Andric return error("Malformed block");
57226bc11b14SDimitry Andric
57236bc11b14SDimitry Andric case BitstreamEntry::SubBlock:
57246bc11b14SDimitry Andric if (Stream.SkipBlock())
57256bc11b14SDimitry Andric return error("Malformed block");
57266bc11b14SDimitry Andric break;
57276bc11b14SDimitry Andric
57286bc11b14SDimitry Andric case BitstreamEntry::Record:
57296bc11b14SDimitry Andric StringRef Blob;
57306bc11b14SDimitry Andric SmallVector<uint64_t, 1> Record;
5731a580b014SDimitry Andric if (Stream.readRecord(Entry.ID, Record, &Blob) == RecordID)
57326bc11b14SDimitry Andric Strtab = Blob;
57336bc11b14SDimitry Andric break;
57346bc11b14SDimitry Andric }
57356bc11b14SDimitry Andric }
57366bc11b14SDimitry Andric }
57376bc11b14SDimitry Andric
5738f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
5739f22ef01cSRoman Divacky // External interface
5740f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
5741f22ef01cSRoman Divacky
5742d88c1a5aSDimitry Andric Expected<std::vector<BitcodeModule>>
getBitcodeModuleList(MemoryBufferRef Buffer)5743d88c1a5aSDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
5744db17bf38SDimitry Andric auto FOrErr = getBitcodeFileContents(Buffer);
5745db17bf38SDimitry Andric if (!FOrErr)
5746db17bf38SDimitry Andric return FOrErr.takeError();
5747db17bf38SDimitry Andric return std::move(FOrErr->Mods);
5748db17bf38SDimitry Andric }
5749db17bf38SDimitry Andric
5750db17bf38SDimitry Andric Expected<BitcodeFileContents>
getBitcodeFileContents(MemoryBufferRef Buffer)5751db17bf38SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
5752d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5753d88c1a5aSDimitry Andric if (!StreamOrErr)
5754d88c1a5aSDimitry Andric return StreamOrErr.takeError();
5755d88c1a5aSDimitry Andric BitstreamCursor &Stream = *StreamOrErr;
57568f0fd8f6SDimitry Andric
5757db17bf38SDimitry Andric BitcodeFileContents F;
5758d88c1a5aSDimitry Andric while (true) {
5759d88c1a5aSDimitry Andric uint64_t BCBegin = Stream.getCurrentByteNo();
57608f0fd8f6SDimitry Andric
5761d88c1a5aSDimitry Andric // We may be consuming bitcode from a client that leaves garbage at the end
5762d88c1a5aSDimitry Andric // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5763d88c1a5aSDimitry Andric // the end that there cannot possibly be another module, stop looking.
5764d88c1a5aSDimitry Andric if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
5765db17bf38SDimitry Andric return F;
57668f0fd8f6SDimitry Andric
5767d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance();
5768d88c1a5aSDimitry Andric switch (Entry.Kind) {
5769d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock:
5770d88c1a5aSDimitry Andric case BitstreamEntry::Error:
5771d88c1a5aSDimitry Andric return error("Malformed block");
5772d88c1a5aSDimitry Andric
5773d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock: {
5774d88c1a5aSDimitry Andric uint64_t IdentificationBit = -1ull;
5775d88c1a5aSDimitry Andric if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5776d88c1a5aSDimitry Andric IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5777d88c1a5aSDimitry Andric if (Stream.SkipBlock())
5778d88c1a5aSDimitry Andric return error("Malformed block");
5779d88c1a5aSDimitry Andric
5780d88c1a5aSDimitry Andric Entry = Stream.advance();
5781d88c1a5aSDimitry Andric if (Entry.Kind != BitstreamEntry::SubBlock ||
5782d88c1a5aSDimitry Andric Entry.ID != bitc::MODULE_BLOCK_ID)
5783d88c1a5aSDimitry Andric return error("Malformed block");
57848f0fd8f6SDimitry Andric }
5785d88c1a5aSDimitry Andric
5786d88c1a5aSDimitry Andric if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5787d88c1a5aSDimitry Andric uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5788d88c1a5aSDimitry Andric if (Stream.SkipBlock())
5789d88c1a5aSDimitry Andric return error("Malformed block");
5790d88c1a5aSDimitry Andric
5791db17bf38SDimitry Andric F.Mods.push_back({Stream.getBitcodeBytes().slice(
5792d88c1a5aSDimitry Andric BCBegin, Stream.getCurrentByteNo() - BCBegin),
5793d88c1a5aSDimitry Andric Buffer.getBufferIdentifier(), IdentificationBit,
5794d88c1a5aSDimitry Andric ModuleBit});
5795d88c1a5aSDimitry Andric continue;
5796d88c1a5aSDimitry Andric }
5797d88c1a5aSDimitry Andric
57986bc11b14SDimitry Andric if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
5799a580b014SDimitry Andric Expected<StringRef> Strtab =
5800a580b014SDimitry Andric readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
58016bc11b14SDimitry Andric if (!Strtab)
58026bc11b14SDimitry Andric return Strtab.takeError();
58036bc11b14SDimitry Andric // This string table is used by every preceding bitcode module that does
58046bc11b14SDimitry Andric // not have its own string table. A bitcode file may have multiple
58056bc11b14SDimitry Andric // string tables if it was created by binary concatenation, for example
58066bc11b14SDimitry Andric // with "llvm-cat -b".
5807db17bf38SDimitry Andric for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
58086bc11b14SDimitry Andric if (!I->Strtab.empty())
58096bc11b14SDimitry Andric break;
58106bc11b14SDimitry Andric I->Strtab = *Strtab;
58116bc11b14SDimitry Andric }
5812a580b014SDimitry Andric // Similarly, the string table is used by every preceding symbol table;
5813a580b014SDimitry Andric // normally there will be just one unless the bitcode file was created
5814a580b014SDimitry Andric // by binary concatenation.
5815a580b014SDimitry Andric if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
5816a580b014SDimitry Andric F.StrtabForSymtab = *Strtab;
5817a580b014SDimitry Andric continue;
5818a580b014SDimitry Andric }
5819a580b014SDimitry Andric
5820a580b014SDimitry Andric if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
5821a580b014SDimitry Andric Expected<StringRef> SymtabOrErr =
5822a580b014SDimitry Andric readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
5823a580b014SDimitry Andric if (!SymtabOrErr)
5824a580b014SDimitry Andric return SymtabOrErr.takeError();
5825a580b014SDimitry Andric
5826a580b014SDimitry Andric // We can expect the bitcode file to have multiple symbol tables if it
5827a580b014SDimitry Andric // was created by binary concatenation. In that case we silently
5828a580b014SDimitry Andric // ignore any subsequent symbol tables, which is fine because this is a
5829a580b014SDimitry Andric // low level function. The client is expected to notice that the number
5830a580b014SDimitry Andric // of modules in the symbol table does not match the number of modules
5831a580b014SDimitry Andric // in the input file and regenerate the symbol table.
5832a580b014SDimitry Andric if (F.Symtab.empty())
5833a580b014SDimitry Andric F.Symtab = *SymtabOrErr;
58346bc11b14SDimitry Andric continue;
58356bc11b14SDimitry Andric }
58366bc11b14SDimitry Andric
5837d88c1a5aSDimitry Andric if (Stream.SkipBlock())
5838d88c1a5aSDimitry Andric return error("Malformed block");
5839d88c1a5aSDimitry Andric continue;
5840d88c1a5aSDimitry Andric }
5841d88c1a5aSDimitry Andric case BitstreamEntry::Record:
5842d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID);
5843d88c1a5aSDimitry Andric continue;
5844d88c1a5aSDimitry Andric }
5845d88c1a5aSDimitry Andric }
58468f0fd8f6SDimitry Andric }
58478f0fd8f6SDimitry Andric
58484ba319b5SDimitry Andric /// Get a lazy one-at-time loading module from bitcode.
5849f22ef01cSRoman Divacky ///
585039d628a0SDimitry Andric /// This isn't always used in a lazy context. In particular, it's also used by
5851d88c1a5aSDimitry Andric /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
585239d628a0SDimitry Andric /// in forward-referenced functions from block address references.
585339d628a0SDimitry Andric ///
58548f0fd8f6SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize
58558f0fd8f6SDimitry Andric /// everything.
5856d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>>
getModuleImpl(LLVMContext & Context,bool MaterializeAll,bool ShouldLazyLoadMetadata,bool IsImporting)5857d88c1a5aSDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
5858d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) {
5859d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer);
586039d628a0SDimitry Andric
5861d88c1a5aSDimitry Andric std::string ProducerIdentification;
5862d88c1a5aSDimitry Andric if (IdentificationBit != -1ull) {
5863d88c1a5aSDimitry Andric Stream.JumpToBit(IdentificationBit);
5864d88c1a5aSDimitry Andric Expected<std::string> ProducerIdentificationOrErr =
5865d88c1a5aSDimitry Andric readIdentificationBlock(Stream);
5866d88c1a5aSDimitry Andric if (!ProducerIdentificationOrErr)
5867d88c1a5aSDimitry Andric return ProducerIdentificationOrErr.takeError();
586839d628a0SDimitry Andric
5869d88c1a5aSDimitry Andric ProducerIdentification = *ProducerIdentificationOrErr;
5870dff0c46cSDimitry Andric }
5871dff0c46cSDimitry Andric
5872d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit);
58736bc11b14SDimitry Andric auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
58746bc11b14SDimitry Andric Context);
5875d88c1a5aSDimitry Andric
5876d88c1a5aSDimitry Andric std::unique_ptr<Module> M =
5877d88c1a5aSDimitry Andric llvm::make_unique<Module>(ModuleIdentifier, Context);
5878d88c1a5aSDimitry Andric M->setMaterializer(R);
5879d88c1a5aSDimitry Andric
5880d88c1a5aSDimitry Andric // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5881d88c1a5aSDimitry Andric if (Error Err =
5882d88c1a5aSDimitry Andric R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
5883d88c1a5aSDimitry Andric return std::move(Err);
5884d88c1a5aSDimitry Andric
5885d88c1a5aSDimitry Andric if (MaterializeAll) {
5886d88c1a5aSDimitry Andric // Read in the entire module, and destroy the BitcodeReader.
5887d88c1a5aSDimitry Andric if (Error Err = M->materializeAll())
5888d88c1a5aSDimitry Andric return std::move(Err);
5889d88c1a5aSDimitry Andric } else {
5890d88c1a5aSDimitry Andric // Resolve forward references from blockaddresses.
5891d88c1a5aSDimitry Andric if (Error Err = R->materializeForwardReferencedFunctions())
5892d88c1a5aSDimitry Andric return std::move(Err);
5893d88c1a5aSDimitry Andric }
5894d88c1a5aSDimitry Andric return std::move(M);
5895f22ef01cSRoman Divacky }
5896f22ef01cSRoman Divacky
5897d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>>
getLazyModule(LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting)5898d88c1a5aSDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5899d88c1a5aSDimitry Andric bool IsImporting) {
5900d88c1a5aSDimitry Andric return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
59017d523365SDimitry Andric }
59027d523365SDimitry Andric
5903f37b6182SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex.
590424d58133SDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the
590524d58133SDimitry Andric // module path used in the combined summary (e.g. when reading summaries for
590624d58133SDimitry Andric // regular LTO modules).
readSummary(ModuleSummaryIndex & CombinedIndex,StringRef ModulePath,uint64_t ModuleId)5907f37b6182SDimitry Andric Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
590824d58133SDimitry Andric StringRef ModulePath, uint64_t ModuleId) {
5909f37b6182SDimitry Andric BitstreamCursor Stream(Buffer);
5910f37b6182SDimitry Andric Stream.JumpToBit(ModuleBit);
5911f37b6182SDimitry Andric
5912f37b6182SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
591324d58133SDimitry Andric ModulePath, ModuleId);
5914f37b6182SDimitry Andric return R.parseModule();
5915f37b6182SDimitry Andric }
5916f37b6182SDimitry Andric
59177d523365SDimitry Andric // Parse the specified bitcode buffer, returning the function info index.
getSummary()5918d88c1a5aSDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5919d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer);
5920d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit);
59217d523365SDimitry Andric
59224ba319b5SDimitry Andric auto Index = llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
5923f37b6182SDimitry Andric ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
5924f37b6182SDimitry Andric ModuleIdentifier, 0);
59257d523365SDimitry Andric
5926f37b6182SDimitry Andric if (Error Err = R.parseModule())
5927d88c1a5aSDimitry Andric return std::move(Err);
59287d523365SDimitry Andric
59297d523365SDimitry Andric return std::move(Index);
59307d523365SDimitry Andric }
59317d523365SDimitry Andric
getEnableSplitLTOUnitFlag(BitstreamCursor & Stream,unsigned ID)5932*b5893f02SDimitry Andric static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
5933*b5893f02SDimitry Andric unsigned ID) {
5934*b5893f02SDimitry Andric if (Stream.EnterSubBlock(ID))
5935*b5893f02SDimitry Andric return error("Invalid record");
5936*b5893f02SDimitry Andric SmallVector<uint64_t, 64> Record;
5937*b5893f02SDimitry Andric
5938*b5893f02SDimitry Andric while (true) {
5939*b5893f02SDimitry Andric BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5940*b5893f02SDimitry Andric
5941*b5893f02SDimitry Andric switch (Entry.Kind) {
5942*b5893f02SDimitry Andric case BitstreamEntry::SubBlock: // Handled for us already.
5943*b5893f02SDimitry Andric case BitstreamEntry::Error:
5944*b5893f02SDimitry Andric return error("Malformed block");
5945*b5893f02SDimitry Andric case BitstreamEntry::EndBlock:
5946*b5893f02SDimitry Andric // If no flags record found, conservatively return true to mimic
5947*b5893f02SDimitry Andric // behavior before this flag was added.
5948*b5893f02SDimitry Andric return true;
5949*b5893f02SDimitry Andric case BitstreamEntry::Record:
5950*b5893f02SDimitry Andric // The interesting case.
5951*b5893f02SDimitry Andric break;
5952*b5893f02SDimitry Andric }
5953*b5893f02SDimitry Andric
5954*b5893f02SDimitry Andric // Look for the FS_FLAGS record.
5955*b5893f02SDimitry Andric Record.clear();
5956*b5893f02SDimitry Andric auto BitCode = Stream.readRecord(Entry.ID, Record);
5957*b5893f02SDimitry Andric switch (BitCode) {
5958*b5893f02SDimitry Andric default: // Default behavior: ignore.
5959*b5893f02SDimitry Andric break;
5960*b5893f02SDimitry Andric case bitc::FS_FLAGS: { // [flags]
5961*b5893f02SDimitry Andric uint64_t Flags = Record[0];
5962*b5893f02SDimitry Andric // Scan flags.
5963*b5893f02SDimitry Andric assert(Flags <= 0x1f && "Unexpected bits in flag");
5964*b5893f02SDimitry Andric
5965*b5893f02SDimitry Andric return Flags & 0x8;
5966*b5893f02SDimitry Andric }
5967*b5893f02SDimitry Andric }
5968*b5893f02SDimitry Andric }
5969*b5893f02SDimitry Andric llvm_unreachable("Exit infinite loop");
5970*b5893f02SDimitry Andric }
5971*b5893f02SDimitry Andric
59723ca95b02SDimitry Andric // Check if the given bitcode buffer contains a global value summary block.
getLTOInfo()597324d58133SDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
5974d88c1a5aSDimitry Andric BitstreamCursor Stream(Buffer);
5975d88c1a5aSDimitry Andric Stream.JumpToBit(ModuleBit);
59767d523365SDimitry Andric
5977d88c1a5aSDimitry Andric if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5978d88c1a5aSDimitry Andric return error("Invalid record");
5979d88c1a5aSDimitry Andric
5980d88c1a5aSDimitry Andric while (true) {
5981d88c1a5aSDimitry Andric BitstreamEntry Entry = Stream.advance();
5982d88c1a5aSDimitry Andric
5983d88c1a5aSDimitry Andric switch (Entry.Kind) {
5984d88c1a5aSDimitry Andric case BitstreamEntry::Error:
5985d88c1a5aSDimitry Andric return error("Malformed block");
5986d88c1a5aSDimitry Andric case BitstreamEntry::EndBlock:
5987*b5893f02SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
5988*b5893f02SDimitry Andric /*EnableSplitLTOUnit=*/false};
59897d523365SDimitry Andric
5990d88c1a5aSDimitry Andric case BitstreamEntry::SubBlock:
5991*b5893f02SDimitry Andric if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
5992*b5893f02SDimitry Andric Expected<bool> EnableSplitLTOUnit =
5993*b5893f02SDimitry Andric getEnableSplitLTOUnitFlag(Stream, Entry.ID);
5994*b5893f02SDimitry Andric if (!EnableSplitLTOUnit)
5995*b5893f02SDimitry Andric return EnableSplitLTOUnit.takeError();
5996*b5893f02SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
5997*b5893f02SDimitry Andric *EnableSplitLTOUnit};
5998*b5893f02SDimitry Andric }
599924d58133SDimitry Andric
6000*b5893f02SDimitry Andric if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
6001*b5893f02SDimitry Andric Expected<bool> EnableSplitLTOUnit =
6002*b5893f02SDimitry Andric getEnableSplitLTOUnitFlag(Stream, Entry.ID);
6003*b5893f02SDimitry Andric if (!EnableSplitLTOUnit)
6004*b5893f02SDimitry Andric return EnableSplitLTOUnit.takeError();
6005*b5893f02SDimitry Andric return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
6006*b5893f02SDimitry Andric *EnableSplitLTOUnit};
6007*b5893f02SDimitry Andric }
60087d523365SDimitry Andric
6009d88c1a5aSDimitry Andric // Ignore other sub-blocks.
6010d88c1a5aSDimitry Andric if (Stream.SkipBlock())
6011d88c1a5aSDimitry Andric return error("Malformed block");
6012d88c1a5aSDimitry Andric continue;
6013d88c1a5aSDimitry Andric
6014d88c1a5aSDimitry Andric case BitstreamEntry::Record:
6015d88c1a5aSDimitry Andric Stream.skipRecord(Entry.ID);
6016d88c1a5aSDimitry Andric continue;
6017d88c1a5aSDimitry Andric }
6018d88c1a5aSDimitry Andric }
6019d88c1a5aSDimitry Andric }
6020d88c1a5aSDimitry Andric
getSingleModule(MemoryBufferRef Buffer)6021d88c1a5aSDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
6022d88c1a5aSDimitry Andric Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
6023d88c1a5aSDimitry Andric if (!MsOrErr)
6024d88c1a5aSDimitry Andric return MsOrErr.takeError();
6025d88c1a5aSDimitry Andric
6026d88c1a5aSDimitry Andric if (MsOrErr->size() != 1)
6027d88c1a5aSDimitry Andric return error("Expected a single module");
6028d88c1a5aSDimitry Andric
6029d88c1a5aSDimitry Andric return (*MsOrErr)[0];
6030d88c1a5aSDimitry Andric }
6031d88c1a5aSDimitry Andric
6032d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>>
getLazyBitcodeModule(MemoryBufferRef Buffer,LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting)6033d88c1a5aSDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
6034d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) {
6035d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer);
6036d88c1a5aSDimitry Andric if (!BM)
6037d88c1a5aSDimitry Andric return BM.takeError();
6038d88c1a5aSDimitry Andric
6039d88c1a5aSDimitry Andric return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
6040d88c1a5aSDimitry Andric }
6041d88c1a5aSDimitry Andric
getOwningLazyBitcodeModule(std::unique_ptr<MemoryBuffer> && Buffer,LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting)6042d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
6043d88c1a5aSDimitry Andric std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
6044d88c1a5aSDimitry Andric bool ShouldLazyLoadMetadata, bool IsImporting) {
6045d88c1a5aSDimitry Andric auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
6046d88c1a5aSDimitry Andric IsImporting);
6047d88c1a5aSDimitry Andric if (MOrErr)
6048d88c1a5aSDimitry Andric (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
6049d88c1a5aSDimitry Andric return MOrErr;
6050d88c1a5aSDimitry Andric }
6051d88c1a5aSDimitry Andric
6052d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>>
parseModule(LLVMContext & Context)6053d88c1a5aSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context) {
6054d88c1a5aSDimitry Andric return getModuleImpl(Context, true, false, false);
6055d88c1a5aSDimitry Andric // TODO: Restore the use-lists to the in-memory state when the bitcode was
6056d88c1a5aSDimitry Andric // written. We must defer until the Module has been fully materialized.
6057d88c1a5aSDimitry Andric }
6058d88c1a5aSDimitry Andric
parseBitcodeFile(MemoryBufferRef Buffer,LLVMContext & Context)6059d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6060d88c1a5aSDimitry Andric LLVMContext &Context) {
6061d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer);
6062d88c1a5aSDimitry Andric if (!BM)
6063d88c1a5aSDimitry Andric return BM.takeError();
6064d88c1a5aSDimitry Andric
6065d88c1a5aSDimitry Andric return BM->parseModule(Context);
6066d88c1a5aSDimitry Andric }
6067d88c1a5aSDimitry Andric
getBitcodeTargetTriple(MemoryBufferRef Buffer)6068d88c1a5aSDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
6069d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6070d88c1a5aSDimitry Andric if (!StreamOrErr)
6071d88c1a5aSDimitry Andric return StreamOrErr.takeError();
6072d88c1a5aSDimitry Andric
6073d88c1a5aSDimitry Andric return readTriple(*StreamOrErr);
6074d88c1a5aSDimitry Andric }
6075d88c1a5aSDimitry Andric
isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)6076d88c1a5aSDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
6077d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6078d88c1a5aSDimitry Andric if (!StreamOrErr)
6079d88c1a5aSDimitry Andric return StreamOrErr.takeError();
6080d88c1a5aSDimitry Andric
6081d88c1a5aSDimitry Andric return hasObjCCategory(*StreamOrErr);
6082d88c1a5aSDimitry Andric }
6083d88c1a5aSDimitry Andric
getBitcodeProducerString(MemoryBufferRef Buffer)6084d88c1a5aSDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
6085d88c1a5aSDimitry Andric Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6086d88c1a5aSDimitry Andric if (!StreamOrErr)
6087d88c1a5aSDimitry Andric return StreamOrErr.takeError();
6088d88c1a5aSDimitry Andric
6089d88c1a5aSDimitry Andric return readIdentificationCode(*StreamOrErr);
6090d88c1a5aSDimitry Andric }
6091d88c1a5aSDimitry Andric
readModuleSummaryIndex(MemoryBufferRef Buffer,ModuleSummaryIndex & CombinedIndex,uint64_t ModuleId)6092f37b6182SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
6093f37b6182SDimitry Andric ModuleSummaryIndex &CombinedIndex,
609424d58133SDimitry Andric uint64_t ModuleId) {
6095f37b6182SDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer);
6096f37b6182SDimitry Andric if (!BM)
6097f37b6182SDimitry Andric return BM.takeError();
6098f37b6182SDimitry Andric
609924d58133SDimitry Andric return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
6100f37b6182SDimitry Andric }
6101f37b6182SDimitry Andric
6102d88c1a5aSDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
getModuleSummaryIndex(MemoryBufferRef Buffer)6103d88c1a5aSDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
6104d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer);
6105d88c1a5aSDimitry Andric if (!BM)
6106d88c1a5aSDimitry Andric return BM.takeError();
6107d88c1a5aSDimitry Andric
6108d88c1a5aSDimitry Andric return BM->getSummary();
6109d88c1a5aSDimitry Andric }
6110d88c1a5aSDimitry Andric
getBitcodeLTOInfo(MemoryBufferRef Buffer)611124d58133SDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
6112d88c1a5aSDimitry Andric Expected<BitcodeModule> BM = getSingleModule(Buffer);
6113d88c1a5aSDimitry Andric if (!BM)
6114d88c1a5aSDimitry Andric return BM.takeError();
6115d88c1a5aSDimitry Andric
611624d58133SDimitry Andric return BM->getLTOInfo();
61177d523365SDimitry Andric }
6118f37b6182SDimitry Andric
6119f37b6182SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
getModuleSummaryIndexForFile(StringRef Path,bool IgnoreEmptyThinLTOIndexFile)61205517e702SDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path,
61215517e702SDimitry Andric bool IgnoreEmptyThinLTOIndexFile) {
6122f37b6182SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6123f37b6182SDimitry Andric MemoryBuffer::getFileOrSTDIN(Path);
6124f37b6182SDimitry Andric if (!FileOrErr)
6125f37b6182SDimitry Andric return errorCodeToError(FileOrErr.getError());
6126f37b6182SDimitry Andric if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
6127f37b6182SDimitry Andric return nullptr;
6128f37b6182SDimitry Andric return getModuleSummaryIndex(**FileOrErr);
6129f37b6182SDimitry Andric }
6130