1*0b57cec5SDimitry Andric //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric 
9*0b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
10*0b57cec5SDimitry Andric #include "MetadataLoader.h"
11*0b57cec5SDimitry Andric #include "ValueList.h"
12*0b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
13*0b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
14*0b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
15*0b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
16*0b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
18*0b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
20*0b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
21*0b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
22*0b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
23e8d8bef9SDimitry Andric #include "llvm/Bitcode/BitcodeCommon.h"
24*0b57cec5SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
25e8d8bef9SDimitry Andric #include "llvm/Bitstream/BitstreamReader.h"
26*0b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
27*0b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
28*0b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
29*0b57cec5SDimitry Andric #include "llvm/IR/AutoUpgrade.h"
30*0b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
31*0b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
32*0b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
33*0b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
34*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
35*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
36*0b57cec5SDimitry Andric #include "llvm/IR/DebugInfo.h"
37*0b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
38*0b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
39*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
40*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
41*0b57cec5SDimitry Andric #include "llvm/IR/GVMaterializer.h"
42*0b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
43*0b57cec5SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
44*0b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
45*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
46*0b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
47*0b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
48*0b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
49*0b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
50*0b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
51*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
52*0b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
53*0b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
54*0b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
55*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
56*0b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
57*0b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
58*0b57cec5SDimitry Andric #include "llvm/IR/Type.h"
59*0b57cec5SDimitry Andric #include "llvm/IR/Value.h"
60*0b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
61*0b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
62*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
63*0b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
64*0b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
65*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
66*0b57cec5SDimitry Andric #include "llvm/Support/Error.h"
67*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
68*0b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
69*0b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
70*0b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
71*0b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
72*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
73*0b57cec5SDimitry Andric #include <algorithm>
74*0b57cec5SDimitry Andric #include <cassert>
75*0b57cec5SDimitry Andric #include <cstddef>
76*0b57cec5SDimitry Andric #include <cstdint>
77*0b57cec5SDimitry Andric #include <deque>
78*0b57cec5SDimitry Andric #include <map>
79*0b57cec5SDimitry Andric #include <memory>
80*0b57cec5SDimitry Andric #include <set>
81*0b57cec5SDimitry Andric #include <string>
82*0b57cec5SDimitry Andric #include <system_error>
83*0b57cec5SDimitry Andric #include <tuple>
84*0b57cec5SDimitry Andric #include <utility>
85*0b57cec5SDimitry Andric #include <vector>
86*0b57cec5SDimitry Andric 
87*0b57cec5SDimitry Andric using namespace llvm;
88*0b57cec5SDimitry Andric 
89*0b57cec5SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs(
90*0b57cec5SDimitry Andric     "print-summary-global-ids", cl::init(false), cl::Hidden,
91*0b57cec5SDimitry Andric     cl::desc(
92*0b57cec5SDimitry Andric         "Print the global id for each value when reading the module summary"));
93*0b57cec5SDimitry Andric 
94*0b57cec5SDimitry Andric namespace {
95*0b57cec5SDimitry Andric 
96*0b57cec5SDimitry Andric enum {
97*0b57cec5SDimitry Andric   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
98*0b57cec5SDimitry Andric };
99*0b57cec5SDimitry Andric 
100*0b57cec5SDimitry Andric } // end anonymous namespace
101*0b57cec5SDimitry Andric 
102*0b57cec5SDimitry Andric static Error error(const Twine &Message) {
103*0b57cec5SDimitry Andric   return make_error<StringError>(
104*0b57cec5SDimitry Andric       Message, make_error_code(BitcodeError::CorruptedBitcode));
105*0b57cec5SDimitry Andric }
106*0b57cec5SDimitry Andric 
107*0b57cec5SDimitry Andric static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
108*0b57cec5SDimitry Andric   if (!Stream.canSkipToPos(4))
109*0b57cec5SDimitry Andric     return createStringError(std::errc::illegal_byte_sequence,
110*0b57cec5SDimitry Andric                              "file too small to contain bitcode header");
111*0b57cec5SDimitry Andric   for (unsigned C : {'B', 'C'})
112*0b57cec5SDimitry Andric     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
113*0b57cec5SDimitry Andric       if (Res.get() != C)
114*0b57cec5SDimitry Andric         return createStringError(std::errc::illegal_byte_sequence,
115*0b57cec5SDimitry Andric                                  "file doesn't start with bitcode header");
116*0b57cec5SDimitry Andric     } else
117*0b57cec5SDimitry Andric       return Res.takeError();
118*0b57cec5SDimitry Andric   for (unsigned C : {0x0, 0xC, 0xE, 0xD})
119*0b57cec5SDimitry Andric     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
120*0b57cec5SDimitry Andric       if (Res.get() != C)
121*0b57cec5SDimitry Andric         return createStringError(std::errc::illegal_byte_sequence,
122*0b57cec5SDimitry Andric                                  "file doesn't start with bitcode header");
123*0b57cec5SDimitry Andric     } else
124*0b57cec5SDimitry Andric       return Res.takeError();
125*0b57cec5SDimitry Andric   return Error::success();
126*0b57cec5SDimitry Andric }
127*0b57cec5SDimitry Andric 
128*0b57cec5SDimitry Andric static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
129*0b57cec5SDimitry Andric   const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
130*0b57cec5SDimitry Andric   const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
131*0b57cec5SDimitry Andric 
132*0b57cec5SDimitry Andric   if (Buffer.getBufferSize() & 3)
133*0b57cec5SDimitry Andric     return error("Invalid bitcode signature");
134*0b57cec5SDimitry Andric 
135*0b57cec5SDimitry Andric   // If we have a wrapper header, parse it and ignore the non-bc file contents.
136*0b57cec5SDimitry Andric   // The magic number is 0x0B17C0DE stored in little endian.
137*0b57cec5SDimitry Andric   if (isBitcodeWrapper(BufPtr, BufEnd))
138*0b57cec5SDimitry Andric     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
139*0b57cec5SDimitry Andric       return error("Invalid bitcode wrapper header");
140*0b57cec5SDimitry Andric 
141*0b57cec5SDimitry Andric   BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
142*0b57cec5SDimitry Andric   if (Error Err = hasInvalidBitcodeHeader(Stream))
143*0b57cec5SDimitry Andric     return std::move(Err);
144*0b57cec5SDimitry Andric 
145*0b57cec5SDimitry Andric   return std::move(Stream);
146*0b57cec5SDimitry Andric }
147*0b57cec5SDimitry Andric 
148*0b57cec5SDimitry Andric /// Convert a string from a record into an std::string, return true on failure.
149*0b57cec5SDimitry Andric template <typename StrTy>
150*0b57cec5SDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
151*0b57cec5SDimitry Andric                             StrTy &Result) {
152*0b57cec5SDimitry Andric   if (Idx > Record.size())
153*0b57cec5SDimitry Andric     return true;
154*0b57cec5SDimitry Andric 
1555ffd83dbSDimitry Andric   Result.append(Record.begin() + Idx, Record.end());
156*0b57cec5SDimitry Andric   return false;
157*0b57cec5SDimitry Andric }
158*0b57cec5SDimitry Andric 
159*0b57cec5SDimitry Andric // Strip all the TBAA attachment for the module.
160*0b57cec5SDimitry Andric static void stripTBAA(Module *M) {
161*0b57cec5SDimitry Andric   for (auto &F : *M) {
162*0b57cec5SDimitry Andric     if (F.isMaterializable())
163*0b57cec5SDimitry Andric       continue;
164*0b57cec5SDimitry Andric     for (auto &I : instructions(F))
165*0b57cec5SDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, nullptr);
166*0b57cec5SDimitry Andric   }
167*0b57cec5SDimitry Andric }
168*0b57cec5SDimitry Andric 
169*0b57cec5SDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
170*0b57cec5SDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any.
171*0b57cec5SDimitry Andric static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
172*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
173*0b57cec5SDimitry Andric     return std::move(Err);
174*0b57cec5SDimitry Andric 
175*0b57cec5SDimitry Andric   // Read all the records.
176*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
177*0b57cec5SDimitry Andric 
178*0b57cec5SDimitry Andric   std::string ProducerIdentification;
179*0b57cec5SDimitry Andric 
180*0b57cec5SDimitry Andric   while (true) {
181*0b57cec5SDimitry Andric     BitstreamEntry Entry;
182349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
183349cc55cSDimitry Andric       return std::move(E);
184*0b57cec5SDimitry Andric 
185*0b57cec5SDimitry Andric     switch (Entry.Kind) {
186*0b57cec5SDimitry Andric     default:
187*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
188*0b57cec5SDimitry Andric       return error("Malformed block");
189*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
190*0b57cec5SDimitry Andric       return ProducerIdentification;
191*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
192*0b57cec5SDimitry Andric       // The interesting case.
193*0b57cec5SDimitry Andric       break;
194*0b57cec5SDimitry Andric     }
195*0b57cec5SDimitry Andric 
196*0b57cec5SDimitry Andric     // Read a record.
197*0b57cec5SDimitry Andric     Record.clear();
198*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
199*0b57cec5SDimitry Andric     if (!MaybeBitCode)
200*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
201*0b57cec5SDimitry Andric     switch (MaybeBitCode.get()) {
202*0b57cec5SDimitry Andric     default: // Default behavior: reject
203*0b57cec5SDimitry Andric       return error("Invalid value");
204*0b57cec5SDimitry Andric     case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
205*0b57cec5SDimitry Andric       convertToString(Record, 0, ProducerIdentification);
206*0b57cec5SDimitry Andric       break;
207*0b57cec5SDimitry Andric     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
208*0b57cec5SDimitry Andric       unsigned epoch = (unsigned)Record[0];
209*0b57cec5SDimitry Andric       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
210*0b57cec5SDimitry Andric         return error(
211*0b57cec5SDimitry Andric           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
212*0b57cec5SDimitry Andric           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
213*0b57cec5SDimitry Andric       }
214*0b57cec5SDimitry Andric     }
215*0b57cec5SDimitry Andric     }
216*0b57cec5SDimitry Andric   }
217*0b57cec5SDimitry Andric }
218*0b57cec5SDimitry Andric 
219*0b57cec5SDimitry Andric static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
220*0b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
221*0b57cec5SDimitry Andric   // need to understand them all.
222*0b57cec5SDimitry Andric   while (true) {
223*0b57cec5SDimitry Andric     if (Stream.AtEndOfStream())
224*0b57cec5SDimitry Andric       return "";
225*0b57cec5SDimitry Andric 
226*0b57cec5SDimitry Andric     BitstreamEntry Entry;
227349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
228349cc55cSDimitry Andric       return std::move(E);
229*0b57cec5SDimitry Andric 
230*0b57cec5SDimitry Andric     switch (Entry.Kind) {
231*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
232*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
233*0b57cec5SDimitry Andric       return error("Malformed block");
234*0b57cec5SDimitry Andric 
235*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
236*0b57cec5SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
237*0b57cec5SDimitry Andric         return readIdentificationBlock(Stream);
238*0b57cec5SDimitry Andric 
239*0b57cec5SDimitry Andric       // Ignore other sub-blocks.
240*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
241*0b57cec5SDimitry Andric         return std::move(Err);
242*0b57cec5SDimitry Andric       continue;
243*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
244349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
245349cc55cSDimitry Andric         return std::move(E);
246*0b57cec5SDimitry Andric       continue;
247*0b57cec5SDimitry Andric     }
248*0b57cec5SDimitry Andric   }
249*0b57cec5SDimitry Andric }
250*0b57cec5SDimitry Andric 
251*0b57cec5SDimitry Andric static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
252*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
253*0b57cec5SDimitry Andric     return std::move(Err);
254*0b57cec5SDimitry Andric 
255*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
256*0b57cec5SDimitry Andric   // Read all the records for this module.
257*0b57cec5SDimitry Andric 
258*0b57cec5SDimitry Andric   while (true) {
259*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
260*0b57cec5SDimitry Andric     if (!MaybeEntry)
261*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
262*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
263*0b57cec5SDimitry Andric 
264*0b57cec5SDimitry Andric     switch (Entry.Kind) {
265*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
266*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
267*0b57cec5SDimitry Andric       return error("Malformed block");
268*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
269*0b57cec5SDimitry Andric       return false;
270*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
271*0b57cec5SDimitry Andric       // The interesting case.
272*0b57cec5SDimitry Andric       break;
273*0b57cec5SDimitry Andric     }
274*0b57cec5SDimitry Andric 
275*0b57cec5SDimitry Andric     // Read a record.
276*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
277*0b57cec5SDimitry Andric     if (!MaybeRecord)
278*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
279*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
280*0b57cec5SDimitry Andric     default:
281*0b57cec5SDimitry Andric       break; // Default behavior, ignore unknown content.
282*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
283*0b57cec5SDimitry Andric       std::string S;
284*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
285*0b57cec5SDimitry Andric         return error("Invalid record");
286*0b57cec5SDimitry Andric       // Check for the i386 and other (x86_64, ARM) conventions
287*0b57cec5SDimitry Andric       if (S.find("__DATA,__objc_catlist") != std::string::npos ||
288*0b57cec5SDimitry Andric           S.find("__OBJC,__category") != std::string::npos)
289*0b57cec5SDimitry Andric         return true;
290*0b57cec5SDimitry Andric       break;
291*0b57cec5SDimitry Andric     }
292*0b57cec5SDimitry Andric     }
293*0b57cec5SDimitry Andric     Record.clear();
294*0b57cec5SDimitry Andric   }
295*0b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
296*0b57cec5SDimitry Andric }
297*0b57cec5SDimitry Andric 
298*0b57cec5SDimitry Andric static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
299*0b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
300*0b57cec5SDimitry Andric   // need to understand them all.
301*0b57cec5SDimitry Andric   while (true) {
302*0b57cec5SDimitry Andric     BitstreamEntry Entry;
303349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
304349cc55cSDimitry Andric       return std::move(E);
305*0b57cec5SDimitry Andric 
306*0b57cec5SDimitry Andric     switch (Entry.Kind) {
307*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
308*0b57cec5SDimitry Andric       return error("Malformed block");
309*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
310*0b57cec5SDimitry Andric       return false;
311*0b57cec5SDimitry Andric 
312*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
313*0b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
314*0b57cec5SDimitry Andric         return hasObjCCategoryInModule(Stream);
315*0b57cec5SDimitry Andric 
316*0b57cec5SDimitry Andric       // Ignore other sub-blocks.
317*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
318*0b57cec5SDimitry Andric         return std::move(Err);
319*0b57cec5SDimitry Andric       continue;
320*0b57cec5SDimitry Andric 
321*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
322349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
323349cc55cSDimitry Andric         return std::move(E);
324*0b57cec5SDimitry Andric       continue;
325*0b57cec5SDimitry Andric     }
326*0b57cec5SDimitry Andric   }
327*0b57cec5SDimitry Andric }
328*0b57cec5SDimitry Andric 
329*0b57cec5SDimitry Andric static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
330*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
331*0b57cec5SDimitry Andric     return std::move(Err);
332*0b57cec5SDimitry Andric 
333*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
334*0b57cec5SDimitry Andric 
335*0b57cec5SDimitry Andric   std::string Triple;
336*0b57cec5SDimitry Andric 
337*0b57cec5SDimitry Andric   // Read all the records for this module.
338*0b57cec5SDimitry Andric   while (true) {
339*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
340*0b57cec5SDimitry Andric     if (!MaybeEntry)
341*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
342*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
343*0b57cec5SDimitry Andric 
344*0b57cec5SDimitry Andric     switch (Entry.Kind) {
345*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
346*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
347*0b57cec5SDimitry Andric       return error("Malformed block");
348*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
349*0b57cec5SDimitry Andric       return Triple;
350*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
351*0b57cec5SDimitry Andric       // The interesting case.
352*0b57cec5SDimitry Andric       break;
353*0b57cec5SDimitry Andric     }
354*0b57cec5SDimitry Andric 
355*0b57cec5SDimitry Andric     // Read a record.
356*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
357*0b57cec5SDimitry Andric     if (!MaybeRecord)
358*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
359*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
360*0b57cec5SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
361*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
362*0b57cec5SDimitry Andric       std::string S;
363*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
364*0b57cec5SDimitry Andric         return error("Invalid record");
365*0b57cec5SDimitry Andric       Triple = S;
366*0b57cec5SDimitry Andric       break;
367*0b57cec5SDimitry Andric     }
368*0b57cec5SDimitry Andric     }
369*0b57cec5SDimitry Andric     Record.clear();
370*0b57cec5SDimitry Andric   }
371*0b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
372*0b57cec5SDimitry Andric }
373*0b57cec5SDimitry Andric 
374*0b57cec5SDimitry Andric static Expected<std::string> readTriple(BitstreamCursor &Stream) {
375*0b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
376*0b57cec5SDimitry Andric   // need to understand them all.
377*0b57cec5SDimitry Andric   while (true) {
378*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advance();
379*0b57cec5SDimitry Andric     if (!MaybeEntry)
380*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
381*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
382*0b57cec5SDimitry Andric 
383*0b57cec5SDimitry Andric     switch (Entry.Kind) {
384*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
385*0b57cec5SDimitry Andric       return error("Malformed block");
386*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
387*0b57cec5SDimitry Andric       return "";
388*0b57cec5SDimitry Andric 
389*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
390*0b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
391*0b57cec5SDimitry Andric         return readModuleTriple(Stream);
392*0b57cec5SDimitry Andric 
393*0b57cec5SDimitry Andric       // Ignore other sub-blocks.
394*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
395*0b57cec5SDimitry Andric         return std::move(Err);
396*0b57cec5SDimitry Andric       continue;
397*0b57cec5SDimitry Andric 
398*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
399*0b57cec5SDimitry Andric       if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
400*0b57cec5SDimitry Andric         continue;
401*0b57cec5SDimitry Andric       else
402*0b57cec5SDimitry Andric         return Skipped.takeError();
403*0b57cec5SDimitry Andric     }
404*0b57cec5SDimitry Andric   }
405*0b57cec5SDimitry Andric }
406*0b57cec5SDimitry Andric 
407*0b57cec5SDimitry Andric namespace {
408*0b57cec5SDimitry Andric 
409*0b57cec5SDimitry Andric class BitcodeReaderBase {
410*0b57cec5SDimitry Andric protected:
411*0b57cec5SDimitry Andric   BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
412*0b57cec5SDimitry Andric       : Stream(std::move(Stream)), Strtab(Strtab) {
413*0b57cec5SDimitry Andric     this->Stream.setBlockInfo(&BlockInfo);
414*0b57cec5SDimitry Andric   }
415*0b57cec5SDimitry Andric 
416*0b57cec5SDimitry Andric   BitstreamBlockInfo BlockInfo;
417*0b57cec5SDimitry Andric   BitstreamCursor Stream;
418*0b57cec5SDimitry Andric   StringRef Strtab;
419*0b57cec5SDimitry Andric 
420*0b57cec5SDimitry Andric   /// In version 2 of the bitcode we store names of global values and comdats in
421*0b57cec5SDimitry Andric   /// a string table rather than in the VST.
422*0b57cec5SDimitry Andric   bool UseStrtab = false;
423*0b57cec5SDimitry Andric 
424*0b57cec5SDimitry Andric   Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
425*0b57cec5SDimitry Andric 
426*0b57cec5SDimitry Andric   /// If this module uses a string table, pop the reference to the string table
427*0b57cec5SDimitry Andric   /// and return the referenced string and the rest of the record. Otherwise
428*0b57cec5SDimitry Andric   /// just return the record itself.
429*0b57cec5SDimitry Andric   std::pair<StringRef, ArrayRef<uint64_t>>
430*0b57cec5SDimitry Andric   readNameFromStrtab(ArrayRef<uint64_t> Record);
431*0b57cec5SDimitry Andric 
432*0b57cec5SDimitry Andric   bool readBlockInfo();
433*0b57cec5SDimitry Andric 
434*0b57cec5SDimitry Andric   // Contains an arbitrary and optional string identifying the bitcode producer
435*0b57cec5SDimitry Andric   std::string ProducerIdentification;
436*0b57cec5SDimitry Andric 
437*0b57cec5SDimitry Andric   Error error(const Twine &Message);
438*0b57cec5SDimitry Andric };
439*0b57cec5SDimitry Andric 
440*0b57cec5SDimitry Andric } // end anonymous namespace
441*0b57cec5SDimitry Andric 
442*0b57cec5SDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) {
443*0b57cec5SDimitry Andric   std::string FullMsg = Message.str();
444*0b57cec5SDimitry Andric   if (!ProducerIdentification.empty())
445*0b57cec5SDimitry Andric     FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
446*0b57cec5SDimitry Andric                LLVM_VERSION_STRING "')";
447*0b57cec5SDimitry Andric   return ::error(FullMsg);
448*0b57cec5SDimitry Andric }
449*0b57cec5SDimitry Andric 
450*0b57cec5SDimitry Andric Expected<unsigned>
451*0b57cec5SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
452*0b57cec5SDimitry Andric   if (Record.empty())
453*0b57cec5SDimitry Andric     return error("Invalid record");
454*0b57cec5SDimitry Andric   unsigned ModuleVersion = Record[0];
455*0b57cec5SDimitry Andric   if (ModuleVersion > 2)
456*0b57cec5SDimitry Andric     return error("Invalid value");
457*0b57cec5SDimitry Andric   UseStrtab = ModuleVersion >= 2;
458*0b57cec5SDimitry Andric   return ModuleVersion;
459*0b57cec5SDimitry Andric }
460*0b57cec5SDimitry Andric 
461*0b57cec5SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>>
462*0b57cec5SDimitry Andric BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
463*0b57cec5SDimitry Andric   if (!UseStrtab)
464*0b57cec5SDimitry Andric     return {"", Record};
465*0b57cec5SDimitry Andric   // Invalid reference. Let the caller complain about the record being empty.
466*0b57cec5SDimitry Andric   if (Record[0] + Record[1] > Strtab.size())
467*0b57cec5SDimitry Andric     return {"", {}};
468*0b57cec5SDimitry Andric   return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
469*0b57cec5SDimitry Andric }
470*0b57cec5SDimitry Andric 
471*0b57cec5SDimitry Andric namespace {
472*0b57cec5SDimitry Andric 
473*0b57cec5SDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
474*0b57cec5SDimitry Andric   LLVMContext &Context;
475*0b57cec5SDimitry Andric   Module *TheModule = nullptr;
476*0b57cec5SDimitry Andric   // Next offset to start scanning for lazy parsing of function bodies.
477*0b57cec5SDimitry Andric   uint64_t NextUnreadBit = 0;
478*0b57cec5SDimitry Andric   // Last function offset found in the VST.
479*0b57cec5SDimitry Andric   uint64_t LastFunctionBlockBit = 0;
480*0b57cec5SDimitry Andric   bool SeenValueSymbolTable = false;
481*0b57cec5SDimitry Andric   uint64_t VSTOffset = 0;
482*0b57cec5SDimitry Andric 
483*0b57cec5SDimitry Andric   std::vector<std::string> SectionTable;
484*0b57cec5SDimitry Andric   std::vector<std::string> GCTable;
485*0b57cec5SDimitry Andric 
486*0b57cec5SDimitry Andric   std::vector<Type*> TypeList;
487*0b57cec5SDimitry Andric   DenseMap<Function *, FunctionType *> FunctionTypes;
488*0b57cec5SDimitry Andric   BitcodeReaderValueList ValueList;
489*0b57cec5SDimitry Andric   Optional<MetadataLoader> MDLoader;
490*0b57cec5SDimitry Andric   std::vector<Comdat *> ComdatList;
4910eae32dcSDimitry Andric   DenseSet<GlobalObject *> ImplicitComdatObjects;
492*0b57cec5SDimitry Andric   SmallVector<Instruction *, 64> InstructionList;
493*0b57cec5SDimitry Andric 
494*0b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
495349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
496349cc55cSDimitry Andric 
497349cc55cSDimitry Andric   struct FunctionOperandInfo {
498349cc55cSDimitry Andric     Function *F;
499349cc55cSDimitry Andric     unsigned PersonalityFn;
500349cc55cSDimitry Andric     unsigned Prefix;
501349cc55cSDimitry Andric     unsigned Prologue;
502349cc55cSDimitry Andric   };
503349cc55cSDimitry Andric   std::vector<FunctionOperandInfo> FunctionOperands;
504*0b57cec5SDimitry Andric 
505*0b57cec5SDimitry Andric   /// The set of attributes by index.  Index zero in the file is for null, and
506*0b57cec5SDimitry Andric   /// is thus not represented here.  As such all indices are off by one.
507*0b57cec5SDimitry Andric   std::vector<AttributeList> MAttributes;
508*0b57cec5SDimitry Andric 
509*0b57cec5SDimitry Andric   /// The set of attribute groups.
510*0b57cec5SDimitry Andric   std::map<unsigned, AttributeList> MAttributeGroups;
511*0b57cec5SDimitry Andric 
512*0b57cec5SDimitry Andric   /// While parsing a function body, this is a list of the basic blocks for the
513*0b57cec5SDimitry Andric   /// function.
514*0b57cec5SDimitry Andric   std::vector<BasicBlock*> FunctionBBs;
515*0b57cec5SDimitry Andric 
516*0b57cec5SDimitry Andric   // When reading the module header, this list is populated with functions that
517*0b57cec5SDimitry Andric   // have bodies later in the file.
518*0b57cec5SDimitry Andric   std::vector<Function*> FunctionsWithBodies;
519*0b57cec5SDimitry Andric 
520*0b57cec5SDimitry Andric   // When intrinsic functions are encountered which require upgrading they are
521*0b57cec5SDimitry Andric   // stored here with their replacement function.
522*0b57cec5SDimitry Andric   using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
523*0b57cec5SDimitry Andric   UpdatedIntrinsicMap UpgradedIntrinsics;
524*0b57cec5SDimitry Andric   // Intrinsics which were remangled because of types rename
525*0b57cec5SDimitry Andric   UpdatedIntrinsicMap RemangledIntrinsics;
526*0b57cec5SDimitry Andric 
527*0b57cec5SDimitry Andric   // Several operations happen after the module header has been read, but
528*0b57cec5SDimitry Andric   // before function bodies are processed. This keeps track of whether
529*0b57cec5SDimitry Andric   // we've done this yet.
530*0b57cec5SDimitry Andric   bool SeenFirstFunctionBody = false;
531*0b57cec5SDimitry Andric 
532*0b57cec5SDimitry Andric   /// When function bodies are initially scanned, this map contains info about
533*0b57cec5SDimitry Andric   /// where to find deferred function body in the stream.
534*0b57cec5SDimitry Andric   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
535*0b57cec5SDimitry Andric 
536*0b57cec5SDimitry Andric   /// When Metadata block is initially scanned when parsing the module, we may
537*0b57cec5SDimitry Andric   /// choose to defer parsing of the metadata. This vector contains info about
538*0b57cec5SDimitry Andric   /// which Metadata blocks are deferred.
539*0b57cec5SDimitry Andric   std::vector<uint64_t> DeferredMetadataInfo;
540*0b57cec5SDimitry Andric 
541*0b57cec5SDimitry Andric   /// These are basic blocks forward-referenced by block addresses.  They are
542*0b57cec5SDimitry Andric   /// inserted lazily into functions when they're loaded.  The basic block ID is
543*0b57cec5SDimitry Andric   /// its index into the vector.
544*0b57cec5SDimitry Andric   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
545*0b57cec5SDimitry Andric   std::deque<Function *> BasicBlockFwdRefQueue;
546*0b57cec5SDimitry Andric 
547*0b57cec5SDimitry Andric   /// Indicates that we are using a new encoding for instruction operands where
548*0b57cec5SDimitry Andric   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
549*0b57cec5SDimitry Andric   /// instruction number, for a more compact encoding.  Some instruction
550*0b57cec5SDimitry Andric   /// operands are not relative to the instruction ID: basic block numbers, and
551*0b57cec5SDimitry Andric   /// types. Once the old style function blocks have been phased out, we would
552*0b57cec5SDimitry Andric   /// not need this flag.
553*0b57cec5SDimitry Andric   bool UseRelativeIDs = false;
554*0b57cec5SDimitry Andric 
555*0b57cec5SDimitry Andric   /// True if all functions will be materialized, negating the need to process
556*0b57cec5SDimitry Andric   /// (e.g.) blockaddress forward references.
557*0b57cec5SDimitry Andric   bool WillMaterializeAllForwardRefs = false;
558*0b57cec5SDimitry Andric 
559*0b57cec5SDimitry Andric   bool StripDebugInfo = false;
560*0b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
561*0b57cec5SDimitry Andric 
562*0b57cec5SDimitry Andric   std::vector<std::string> BundleTags;
563*0b57cec5SDimitry Andric   SmallVector<SyncScope::ID, 8> SSIDs;
564*0b57cec5SDimitry Andric 
565*0b57cec5SDimitry Andric public:
566*0b57cec5SDimitry Andric   BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
567*0b57cec5SDimitry Andric                 StringRef ProducerIdentification, LLVMContext &Context);
568*0b57cec5SDimitry Andric 
569*0b57cec5SDimitry Andric   Error materializeForwardReferencedFunctions();
570*0b57cec5SDimitry Andric 
571*0b57cec5SDimitry Andric   Error materialize(GlobalValue *GV) override;
572*0b57cec5SDimitry Andric   Error materializeModule() override;
573*0b57cec5SDimitry Andric   std::vector<StructType *> getIdentifiedStructTypes() const override;
574*0b57cec5SDimitry Andric 
575*0b57cec5SDimitry Andric   /// Main interface to parsing a bitcode buffer.
576*0b57cec5SDimitry Andric   /// \returns true if an error occurred.
5775ffd83dbSDimitry Andric   Error parseBitcodeInto(
5785ffd83dbSDimitry Andric       Module *M, bool ShouldLazyLoadMetadata = false, bool IsImporting = false,
579e8d8bef9SDimitry Andric       DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });
580*0b57cec5SDimitry Andric 
581*0b57cec5SDimitry Andric   static uint64_t decodeSignRotatedValue(uint64_t V);
582*0b57cec5SDimitry Andric 
583*0b57cec5SDimitry Andric   /// Materialize any deferred Metadata block.
584*0b57cec5SDimitry Andric   Error materializeMetadata() override;
585*0b57cec5SDimitry Andric 
586*0b57cec5SDimitry Andric   void setStripDebugInfo() override;
587*0b57cec5SDimitry Andric 
588*0b57cec5SDimitry Andric private:
589*0b57cec5SDimitry Andric   std::vector<StructType *> IdentifiedStructTypes;
590*0b57cec5SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
591*0b57cec5SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context);
592*0b57cec5SDimitry Andric 
593fe6060f1SDimitry Andric   Type *getTypeByID(unsigned ID);
594*0b57cec5SDimitry Andric 
595fe6060f1SDimitry Andric   Value *getFnValueByID(unsigned ID, Type *Ty) {
596*0b57cec5SDimitry Andric     if (Ty && Ty->isMetadataTy())
597*0b57cec5SDimitry Andric       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
598fe6060f1SDimitry Andric     return ValueList.getValueFwdRef(ID, Ty);
599*0b57cec5SDimitry Andric   }
600*0b57cec5SDimitry Andric 
601*0b57cec5SDimitry Andric   Metadata *getFnMetadataByID(unsigned ID) {
602*0b57cec5SDimitry Andric     return MDLoader->getMetadataFwdRefOrLoad(ID);
603*0b57cec5SDimitry Andric   }
604*0b57cec5SDimitry Andric 
605*0b57cec5SDimitry Andric   BasicBlock *getBasicBlock(unsigned ID) const {
606*0b57cec5SDimitry Andric     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
607*0b57cec5SDimitry Andric     return FunctionBBs[ID];
608*0b57cec5SDimitry Andric   }
609*0b57cec5SDimitry Andric 
610*0b57cec5SDimitry Andric   AttributeList getAttributes(unsigned i) const {
611*0b57cec5SDimitry Andric     if (i-1 < MAttributes.size())
612*0b57cec5SDimitry Andric       return MAttributes[i-1];
613*0b57cec5SDimitry Andric     return AttributeList();
614*0b57cec5SDimitry Andric   }
615*0b57cec5SDimitry Andric 
616*0b57cec5SDimitry Andric   /// Read a value/type pair out of the specified record from slot 'Slot'.
617*0b57cec5SDimitry Andric   /// Increment Slot past the number of slots used in the record. Return true on
618*0b57cec5SDimitry Andric   /// failure.
619e8d8bef9SDimitry Andric   bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
620fe6060f1SDimitry Andric                         unsigned InstNum, Value *&ResVal) {
621*0b57cec5SDimitry Andric     if (Slot == Record.size()) return true;
622*0b57cec5SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot++];
623*0b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
624*0b57cec5SDimitry Andric     if (UseRelativeIDs)
625*0b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
626*0b57cec5SDimitry Andric     if (ValNo < InstNum) {
627*0b57cec5SDimitry Andric       // If this is not a forward reference, just return the value we already
628*0b57cec5SDimitry Andric       // have.
629fe6060f1SDimitry Andric       ResVal = getFnValueByID(ValNo, nullptr);
630*0b57cec5SDimitry Andric       return ResVal == nullptr;
631*0b57cec5SDimitry Andric     }
632*0b57cec5SDimitry Andric     if (Slot == Record.size())
633*0b57cec5SDimitry Andric       return true;
634*0b57cec5SDimitry Andric 
635*0b57cec5SDimitry Andric     unsigned TypeNo = (unsigned)Record[Slot++];
636*0b57cec5SDimitry Andric     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
637*0b57cec5SDimitry Andric     return ResVal == nullptr;
638*0b57cec5SDimitry Andric   }
639*0b57cec5SDimitry Andric 
640*0b57cec5SDimitry Andric   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
641*0b57cec5SDimitry Andric   /// past the number of slots used by the value in the record. Return true if
642*0b57cec5SDimitry Andric   /// there is an error.
643e8d8bef9SDimitry Andric   bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
644*0b57cec5SDimitry Andric                 unsigned InstNum, Type *Ty, Value *&ResVal) {
645*0b57cec5SDimitry Andric     if (getValue(Record, Slot, InstNum, Ty, ResVal))
646*0b57cec5SDimitry Andric       return true;
647*0b57cec5SDimitry Andric     // All values currently take a single record slot.
648*0b57cec5SDimitry Andric     ++Slot;
649*0b57cec5SDimitry Andric     return false;
650*0b57cec5SDimitry Andric   }
651*0b57cec5SDimitry Andric 
652*0b57cec5SDimitry Andric   /// Like popValue, but does not increment the Slot number.
653e8d8bef9SDimitry Andric   bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
654*0b57cec5SDimitry Andric                 unsigned InstNum, Type *Ty, Value *&ResVal) {
655*0b57cec5SDimitry Andric     ResVal = getValue(Record, Slot, InstNum, Ty);
656*0b57cec5SDimitry Andric     return ResVal == nullptr;
657*0b57cec5SDimitry Andric   }
658*0b57cec5SDimitry Andric 
659*0b57cec5SDimitry Andric   /// Version of getValue that returns ResVal directly, or 0 if there is an
660*0b57cec5SDimitry Andric   /// error.
661e8d8bef9SDimitry Andric   Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
662*0b57cec5SDimitry Andric                   unsigned InstNum, Type *Ty) {
663*0b57cec5SDimitry Andric     if (Slot == Record.size()) return nullptr;
664*0b57cec5SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot];
665*0b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
666*0b57cec5SDimitry Andric     if (UseRelativeIDs)
667*0b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
668*0b57cec5SDimitry Andric     return getFnValueByID(ValNo, Ty);
669*0b57cec5SDimitry Andric   }
670*0b57cec5SDimitry Andric 
671*0b57cec5SDimitry Andric   /// Like getValue, but decodes signed VBRs.
672e8d8bef9SDimitry Andric   Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
673*0b57cec5SDimitry Andric                         unsigned InstNum, Type *Ty) {
674*0b57cec5SDimitry Andric     if (Slot == Record.size()) return nullptr;
675*0b57cec5SDimitry Andric     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
676*0b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
677*0b57cec5SDimitry Andric     if (UseRelativeIDs)
678*0b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
679*0b57cec5SDimitry Andric     return getFnValueByID(ValNo, Ty);
680*0b57cec5SDimitry Andric   }
681*0b57cec5SDimitry Andric 
682fe6060f1SDimitry Andric   /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
683fe6060f1SDimitry Andric   /// corresponding argument's pointee type. Also upgrades intrinsics that now
684fe6060f1SDimitry Andric   /// require an elementtype attribute.
685fe6060f1SDimitry Andric   void propagateAttributeTypes(CallBase *CB, ArrayRef<Type *> ArgsTys);
686*0b57cec5SDimitry Andric 
687*0b57cec5SDimitry Andric   /// Converts alignment exponent (i.e. power of two (or zero)) to the
688*0b57cec5SDimitry Andric   /// corresponding alignment to use. If alignment is too large, returns
689*0b57cec5SDimitry Andric   /// a corresponding error code.
6908bcb0991SDimitry Andric   Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
691*0b57cec5SDimitry Andric   Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
6925ffd83dbSDimitry Andric   Error parseModule(
6935ffd83dbSDimitry Andric       uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
6945ffd83dbSDimitry Andric       DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });
695*0b57cec5SDimitry Andric 
696*0b57cec5SDimitry Andric   Error parseComdatRecord(ArrayRef<uint64_t> Record);
697*0b57cec5SDimitry Andric   Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
698*0b57cec5SDimitry Andric   Error parseFunctionRecord(ArrayRef<uint64_t> Record);
699*0b57cec5SDimitry Andric   Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
700*0b57cec5SDimitry Andric                                         ArrayRef<uint64_t> Record);
701*0b57cec5SDimitry Andric 
702*0b57cec5SDimitry Andric   Error parseAttributeBlock();
703*0b57cec5SDimitry Andric   Error parseAttributeGroupBlock();
704*0b57cec5SDimitry Andric   Error parseTypeTable();
705*0b57cec5SDimitry Andric   Error parseTypeTableBody();
706*0b57cec5SDimitry Andric   Error parseOperandBundleTags();
707*0b57cec5SDimitry Andric   Error parseSyncScopeNames();
708*0b57cec5SDimitry Andric 
709*0b57cec5SDimitry Andric   Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
710*0b57cec5SDimitry Andric                                 unsigned NameIndex, Triple &TT);
711*0b57cec5SDimitry Andric   void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
712*0b57cec5SDimitry Andric                                ArrayRef<uint64_t> Record);
713*0b57cec5SDimitry Andric   Error parseValueSymbolTable(uint64_t Offset = 0);
714*0b57cec5SDimitry Andric   Error parseGlobalValueSymbolTable();
715*0b57cec5SDimitry Andric   Error parseConstants();
716*0b57cec5SDimitry Andric   Error rememberAndSkipFunctionBodies();
717*0b57cec5SDimitry Andric   Error rememberAndSkipFunctionBody();
718*0b57cec5SDimitry Andric   /// Save the positions of the Metadata blocks and skip parsing the blocks.
719*0b57cec5SDimitry Andric   Error rememberAndSkipMetadata();
720*0b57cec5SDimitry Andric   Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
721*0b57cec5SDimitry Andric   Error parseFunctionBody(Function *F);
722*0b57cec5SDimitry Andric   Error globalCleanup();
723*0b57cec5SDimitry Andric   Error resolveGlobalAndIndirectSymbolInits();
724*0b57cec5SDimitry Andric   Error parseUseLists();
725*0b57cec5SDimitry Andric   Error findFunctionInStream(
726*0b57cec5SDimitry Andric       Function *F,
727*0b57cec5SDimitry Andric       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
728*0b57cec5SDimitry Andric 
729*0b57cec5SDimitry Andric   SyncScope::ID getDecodedSyncScopeID(unsigned Val);
730*0b57cec5SDimitry Andric };
731*0b57cec5SDimitry Andric 
732*0b57cec5SDimitry Andric /// Class to manage reading and parsing function summary index bitcode
733*0b57cec5SDimitry Andric /// files/sections.
734*0b57cec5SDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
735*0b57cec5SDimitry Andric   /// The module index built during parsing.
736*0b57cec5SDimitry Andric   ModuleSummaryIndex &TheIndex;
737*0b57cec5SDimitry Andric 
738*0b57cec5SDimitry Andric   /// Indicates whether we have encountered a global value summary section
739*0b57cec5SDimitry Andric   /// yet during parsing.
740*0b57cec5SDimitry Andric   bool SeenGlobalValSummary = false;
741*0b57cec5SDimitry Andric 
742*0b57cec5SDimitry Andric   /// Indicates whether we have already parsed the VST, used for error checking.
743*0b57cec5SDimitry Andric   bool SeenValueSymbolTable = false;
744*0b57cec5SDimitry Andric 
745*0b57cec5SDimitry Andric   /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
746*0b57cec5SDimitry Andric   /// Used to enable on-demand parsing of the VST.
747*0b57cec5SDimitry Andric   uint64_t VSTOffset = 0;
748*0b57cec5SDimitry Andric 
749*0b57cec5SDimitry Andric   // Map to save ValueId to ValueInfo association that was recorded in the
750*0b57cec5SDimitry Andric   // ValueSymbolTable. It is used after the VST is parsed to convert
751*0b57cec5SDimitry Andric   // call graph edges read from the function summary from referencing
752*0b57cec5SDimitry Andric   // callees by their ValueId to using the ValueInfo instead, which is how
753*0b57cec5SDimitry Andric   // they are recorded in the summary index being built.
754*0b57cec5SDimitry Andric   // We save a GUID which refers to the same global as the ValueInfo, but
755*0b57cec5SDimitry Andric   // ignoring the linkage, i.e. for values other than local linkage they are
756*0b57cec5SDimitry Andric   // identical.
757*0b57cec5SDimitry Andric   DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
758*0b57cec5SDimitry Andric       ValueIdToValueInfoMap;
759*0b57cec5SDimitry Andric 
760*0b57cec5SDimitry Andric   /// Map populated during module path string table parsing, from the
761*0b57cec5SDimitry Andric   /// module ID to a string reference owned by the index's module
762*0b57cec5SDimitry Andric   /// path string table, used to correlate with combined index
763*0b57cec5SDimitry Andric   /// summary records.
764*0b57cec5SDimitry Andric   DenseMap<uint64_t, StringRef> ModuleIdMap;
765*0b57cec5SDimitry Andric 
766*0b57cec5SDimitry Andric   /// Original source file name recorded in a bitcode record.
767*0b57cec5SDimitry Andric   std::string SourceFileName;
768*0b57cec5SDimitry Andric 
769*0b57cec5SDimitry Andric   /// The string identifier given to this module by the client, normally the
770*0b57cec5SDimitry Andric   /// path to the bitcode file.
771*0b57cec5SDimitry Andric   StringRef ModulePath;
772*0b57cec5SDimitry Andric 
773*0b57cec5SDimitry Andric   /// For per-module summary indexes, the unique numerical identifier given to
774*0b57cec5SDimitry Andric   /// this module by the client.
775*0b57cec5SDimitry Andric   unsigned ModuleId;
776*0b57cec5SDimitry Andric 
777*0b57cec5SDimitry Andric public:
778*0b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
779*0b57cec5SDimitry Andric                                   ModuleSummaryIndex &TheIndex,
780*0b57cec5SDimitry Andric                                   StringRef ModulePath, unsigned ModuleId);
781*0b57cec5SDimitry Andric 
782*0b57cec5SDimitry Andric   Error parseModule();
783*0b57cec5SDimitry Andric 
784*0b57cec5SDimitry Andric private:
785*0b57cec5SDimitry Andric   void setValueGUID(uint64_t ValueID, StringRef ValueName,
786*0b57cec5SDimitry Andric                     GlobalValue::LinkageTypes Linkage,
787*0b57cec5SDimitry Andric                     StringRef SourceFileName);
788*0b57cec5SDimitry Andric   Error parseValueSymbolTable(
789*0b57cec5SDimitry Andric       uint64_t Offset,
790*0b57cec5SDimitry Andric       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
791*0b57cec5SDimitry Andric   std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
792*0b57cec5SDimitry Andric   std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
793*0b57cec5SDimitry Andric                                                     bool IsOldProfileFormat,
794*0b57cec5SDimitry Andric                                                     bool HasProfile,
795*0b57cec5SDimitry Andric                                                     bool HasRelBF);
796*0b57cec5SDimitry Andric   Error parseEntireSummary(unsigned ID);
797*0b57cec5SDimitry Andric   Error parseModuleStringTable();
798*0b57cec5SDimitry Andric   void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
799*0b57cec5SDimitry Andric   void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
800*0b57cec5SDimitry Andric                                        TypeIdCompatibleVtableInfo &TypeId);
801e8d8bef9SDimitry Andric   std::vector<FunctionSummary::ParamAccess>
802e8d8bef9SDimitry Andric   parseParamAccesses(ArrayRef<uint64_t> Record);
803*0b57cec5SDimitry Andric 
804*0b57cec5SDimitry Andric   std::pair<ValueInfo, GlobalValue::GUID>
805*0b57cec5SDimitry Andric   getValueInfoFromValueId(unsigned ValueId);
806*0b57cec5SDimitry Andric 
807*0b57cec5SDimitry Andric   void addThisModule();
808*0b57cec5SDimitry Andric   ModuleSummaryIndex::ModuleInfo *getThisModule();
809*0b57cec5SDimitry Andric };
810*0b57cec5SDimitry Andric 
811*0b57cec5SDimitry Andric } // end anonymous namespace
812*0b57cec5SDimitry Andric 
813*0b57cec5SDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
814*0b57cec5SDimitry Andric                                                     Error Err) {
815*0b57cec5SDimitry Andric   if (Err) {
816*0b57cec5SDimitry Andric     std::error_code EC;
817*0b57cec5SDimitry Andric     handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
818*0b57cec5SDimitry Andric       EC = EIB.convertToErrorCode();
819*0b57cec5SDimitry Andric       Ctx.emitError(EIB.message());
820*0b57cec5SDimitry Andric     });
821*0b57cec5SDimitry Andric     return EC;
822*0b57cec5SDimitry Andric   }
823*0b57cec5SDimitry Andric   return std::error_code();
824*0b57cec5SDimitry Andric }
825*0b57cec5SDimitry Andric 
826*0b57cec5SDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
827*0b57cec5SDimitry Andric                              StringRef ProducerIdentification,
828*0b57cec5SDimitry Andric                              LLVMContext &Context)
829*0b57cec5SDimitry Andric     : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
830*0b57cec5SDimitry Andric       ValueList(Context, Stream.SizeInBytes()) {
8315ffd83dbSDimitry Andric   this->ProducerIdentification = std::string(ProducerIdentification);
832*0b57cec5SDimitry Andric }
833*0b57cec5SDimitry Andric 
834*0b57cec5SDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() {
835*0b57cec5SDimitry Andric   if (WillMaterializeAllForwardRefs)
836*0b57cec5SDimitry Andric     return Error::success();
837*0b57cec5SDimitry Andric 
838*0b57cec5SDimitry Andric   // Prevent recursion.
839*0b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = true;
840*0b57cec5SDimitry Andric 
841*0b57cec5SDimitry Andric   while (!BasicBlockFwdRefQueue.empty()) {
842*0b57cec5SDimitry Andric     Function *F = BasicBlockFwdRefQueue.front();
843*0b57cec5SDimitry Andric     BasicBlockFwdRefQueue.pop_front();
844*0b57cec5SDimitry Andric     assert(F && "Expected valid function");
845*0b57cec5SDimitry Andric     if (!BasicBlockFwdRefs.count(F))
846*0b57cec5SDimitry Andric       // Already materialized.
847*0b57cec5SDimitry Andric       continue;
848*0b57cec5SDimitry Andric 
849*0b57cec5SDimitry Andric     // Check for a function that isn't materializable to prevent an infinite
850*0b57cec5SDimitry Andric     // loop.  When parsing a blockaddress stored in a global variable, there
851*0b57cec5SDimitry Andric     // isn't a trivial way to check if a function will have a body without a
852*0b57cec5SDimitry Andric     // linear search through FunctionsWithBodies, so just check it here.
853*0b57cec5SDimitry Andric     if (!F->isMaterializable())
854*0b57cec5SDimitry Andric       return error("Never resolved function from blockaddress");
855*0b57cec5SDimitry Andric 
856*0b57cec5SDimitry Andric     // Try to materialize F.
857*0b57cec5SDimitry Andric     if (Error Err = materialize(F))
858*0b57cec5SDimitry Andric       return Err;
859*0b57cec5SDimitry Andric   }
860*0b57cec5SDimitry Andric   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
861*0b57cec5SDimitry Andric 
862*0b57cec5SDimitry Andric   // Reset state.
863*0b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = false;
864*0b57cec5SDimitry Andric   return Error::success();
865*0b57cec5SDimitry Andric }
866*0b57cec5SDimitry Andric 
867*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
868*0b57cec5SDimitry Andric //  Helper functions to implement forward reference resolution, etc.
869*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
870*0b57cec5SDimitry Andric 
871*0b57cec5SDimitry Andric static bool hasImplicitComdat(size_t Val) {
872*0b57cec5SDimitry Andric   switch (Val) {
873*0b57cec5SDimitry Andric   default:
874*0b57cec5SDimitry Andric     return false;
875*0b57cec5SDimitry Andric   case 1:  // Old WeakAnyLinkage
876*0b57cec5SDimitry Andric   case 4:  // Old LinkOnceAnyLinkage
877*0b57cec5SDimitry Andric   case 10: // Old WeakODRLinkage
878*0b57cec5SDimitry Andric   case 11: // Old LinkOnceODRLinkage
879*0b57cec5SDimitry Andric     return true;
880*0b57cec5SDimitry Andric   }
881*0b57cec5SDimitry Andric }
882*0b57cec5SDimitry Andric 
883*0b57cec5SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
884*0b57cec5SDimitry Andric   switch (Val) {
885*0b57cec5SDimitry Andric   default: // Map unknown/new linkages to external
886*0b57cec5SDimitry Andric   case 0:
887*0b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage;
888*0b57cec5SDimitry Andric   case 2:
889*0b57cec5SDimitry Andric     return GlobalValue::AppendingLinkage;
890*0b57cec5SDimitry Andric   case 3:
891*0b57cec5SDimitry Andric     return GlobalValue::InternalLinkage;
892*0b57cec5SDimitry Andric   case 5:
893*0b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
894*0b57cec5SDimitry Andric   case 6:
895*0b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
896*0b57cec5SDimitry Andric   case 7:
897*0b57cec5SDimitry Andric     return GlobalValue::ExternalWeakLinkage;
898*0b57cec5SDimitry Andric   case 8:
899*0b57cec5SDimitry Andric     return GlobalValue::CommonLinkage;
900*0b57cec5SDimitry Andric   case 9:
901*0b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage;
902*0b57cec5SDimitry Andric   case 12:
903*0b57cec5SDimitry Andric     return GlobalValue::AvailableExternallyLinkage;
904*0b57cec5SDimitry Andric   case 13:
905*0b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
906*0b57cec5SDimitry Andric   case 14:
907*0b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
908*0b57cec5SDimitry Andric   case 15:
909*0b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
910*0b57cec5SDimitry Andric   case 1: // Old value with implicit comdat.
911*0b57cec5SDimitry Andric   case 16:
912*0b57cec5SDimitry Andric     return GlobalValue::WeakAnyLinkage;
913*0b57cec5SDimitry Andric   case 10: // Old value with implicit comdat.
914*0b57cec5SDimitry Andric   case 17:
915*0b57cec5SDimitry Andric     return GlobalValue::WeakODRLinkage;
916*0b57cec5SDimitry Andric   case 4: // Old value with implicit comdat.
917*0b57cec5SDimitry Andric   case 18:
918*0b57cec5SDimitry Andric     return GlobalValue::LinkOnceAnyLinkage;
919*0b57cec5SDimitry Andric   case 11: // Old value with implicit comdat.
920*0b57cec5SDimitry Andric   case 19:
921*0b57cec5SDimitry Andric     return GlobalValue::LinkOnceODRLinkage;
922*0b57cec5SDimitry Andric   }
923*0b57cec5SDimitry Andric }
924*0b57cec5SDimitry Andric 
925*0b57cec5SDimitry Andric static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
926*0b57cec5SDimitry Andric   FunctionSummary::FFlags Flags;
927*0b57cec5SDimitry Andric   Flags.ReadNone = RawFlags & 0x1;
928*0b57cec5SDimitry Andric   Flags.ReadOnly = (RawFlags >> 1) & 0x1;
929*0b57cec5SDimitry Andric   Flags.NoRecurse = (RawFlags >> 2) & 0x1;
930*0b57cec5SDimitry Andric   Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
931*0b57cec5SDimitry Andric   Flags.NoInline = (RawFlags >> 4) & 0x1;
932480093f4SDimitry Andric   Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
933349cc55cSDimitry Andric   Flags.NoUnwind = (RawFlags >> 6) & 0x1;
934349cc55cSDimitry Andric   Flags.MayThrow = (RawFlags >> 7) & 0x1;
935349cc55cSDimitry Andric   Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
9360eae32dcSDimitry Andric   Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
937*0b57cec5SDimitry Andric   return Flags;
938*0b57cec5SDimitry Andric }
939*0b57cec5SDimitry Andric 
940fe6060f1SDimitry Andric // Decode the flags for GlobalValue in the summary. The bits for each attribute:
941fe6060f1SDimitry Andric //
942fe6060f1SDimitry Andric // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
943fe6060f1SDimitry Andric // visibility: [8, 10).
944*0b57cec5SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
945*0b57cec5SDimitry Andric                                                             uint64_t Version) {
946*0b57cec5SDimitry Andric   // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
947*0b57cec5SDimitry Andric   // like getDecodedLinkage() above. Any future change to the linkage enum and
948*0b57cec5SDimitry Andric   // to getDecodedLinkage() will need to be taken into account here as above.
949*0b57cec5SDimitry Andric   auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
950fe6060f1SDimitry Andric   auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
951*0b57cec5SDimitry Andric   RawFlags = RawFlags >> 4;
952*0b57cec5SDimitry Andric   bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
953*0b57cec5SDimitry Andric   // The Live flag wasn't introduced until version 3. For dead stripping
954*0b57cec5SDimitry Andric   // to work correctly on earlier versions, we must conservatively treat all
955*0b57cec5SDimitry Andric   // values as live.
956*0b57cec5SDimitry Andric   bool Live = (RawFlags & 0x2) || Version < 3;
957*0b57cec5SDimitry Andric   bool Local = (RawFlags & 0x4);
958*0b57cec5SDimitry Andric   bool AutoHide = (RawFlags & 0x8);
959*0b57cec5SDimitry Andric 
960fe6060f1SDimitry Andric   return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
961fe6060f1SDimitry Andric                                      Live, Local, AutoHide);
962*0b57cec5SDimitry Andric }
963*0b57cec5SDimitry Andric 
964*0b57cec5SDimitry Andric // Decode the flags for GlobalVariable in the summary
965*0b57cec5SDimitry Andric static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
9665ffd83dbSDimitry Andric   return GlobalVarSummary::GVarFlags(
9675ffd83dbSDimitry Andric       (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
9685ffd83dbSDimitry Andric       (RawFlags & 0x4) ? true : false,
9695ffd83dbSDimitry Andric       (GlobalObject::VCallVisibility)(RawFlags >> 3));
970*0b57cec5SDimitry Andric }
971*0b57cec5SDimitry Andric 
972*0b57cec5SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
973*0b57cec5SDimitry Andric   switch (Val) {
974*0b57cec5SDimitry Andric   default: // Map unknown visibilities to default.
975*0b57cec5SDimitry Andric   case 0: return GlobalValue::DefaultVisibility;
976*0b57cec5SDimitry Andric   case 1: return GlobalValue::HiddenVisibility;
977*0b57cec5SDimitry Andric   case 2: return GlobalValue::ProtectedVisibility;
978*0b57cec5SDimitry Andric   }
979*0b57cec5SDimitry Andric }
980*0b57cec5SDimitry Andric 
981*0b57cec5SDimitry Andric static GlobalValue::DLLStorageClassTypes
982*0b57cec5SDimitry Andric getDecodedDLLStorageClass(unsigned Val) {
983*0b57cec5SDimitry Andric   switch (Val) {
984*0b57cec5SDimitry Andric   default: // Map unknown values to default.
985*0b57cec5SDimitry Andric   case 0: return GlobalValue::DefaultStorageClass;
986*0b57cec5SDimitry Andric   case 1: return GlobalValue::DLLImportStorageClass;
987*0b57cec5SDimitry Andric   case 2: return GlobalValue::DLLExportStorageClass;
988*0b57cec5SDimitry Andric   }
989*0b57cec5SDimitry Andric }
990*0b57cec5SDimitry Andric 
991*0b57cec5SDimitry Andric static bool getDecodedDSOLocal(unsigned Val) {
992*0b57cec5SDimitry Andric   switch(Val) {
993*0b57cec5SDimitry Andric   default: // Map unknown values to preemptable.
994*0b57cec5SDimitry Andric   case 0:  return false;
995*0b57cec5SDimitry Andric   case 1:  return true;
996*0b57cec5SDimitry Andric   }
997*0b57cec5SDimitry Andric }
998*0b57cec5SDimitry Andric 
999*0b57cec5SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
1000*0b57cec5SDimitry Andric   switch (Val) {
1001*0b57cec5SDimitry Andric     case 0: return GlobalVariable::NotThreadLocal;
1002*0b57cec5SDimitry Andric     default: // Map unknown non-zero value to general dynamic.
1003*0b57cec5SDimitry Andric     case 1: return GlobalVariable::GeneralDynamicTLSModel;
1004*0b57cec5SDimitry Andric     case 2: return GlobalVariable::LocalDynamicTLSModel;
1005*0b57cec5SDimitry Andric     case 3: return GlobalVariable::InitialExecTLSModel;
1006*0b57cec5SDimitry Andric     case 4: return GlobalVariable::LocalExecTLSModel;
1007*0b57cec5SDimitry Andric   }
1008*0b57cec5SDimitry Andric }
1009*0b57cec5SDimitry Andric 
1010*0b57cec5SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
1011*0b57cec5SDimitry Andric   switch (Val) {
1012*0b57cec5SDimitry Andric     default: // Map unknown to UnnamedAddr::None.
1013*0b57cec5SDimitry Andric     case 0: return GlobalVariable::UnnamedAddr::None;
1014*0b57cec5SDimitry Andric     case 1: return GlobalVariable::UnnamedAddr::Global;
1015*0b57cec5SDimitry Andric     case 2: return GlobalVariable::UnnamedAddr::Local;
1016*0b57cec5SDimitry Andric   }
1017*0b57cec5SDimitry Andric }
1018*0b57cec5SDimitry Andric 
1019*0b57cec5SDimitry Andric static int getDecodedCastOpcode(unsigned Val) {
1020*0b57cec5SDimitry Andric   switch (Val) {
1021*0b57cec5SDimitry Andric   default: return -1;
1022*0b57cec5SDimitry Andric   case bitc::CAST_TRUNC   : return Instruction::Trunc;
1023*0b57cec5SDimitry Andric   case bitc::CAST_ZEXT    : return Instruction::ZExt;
1024*0b57cec5SDimitry Andric   case bitc::CAST_SEXT    : return Instruction::SExt;
1025*0b57cec5SDimitry Andric   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
1026*0b57cec5SDimitry Andric   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
1027*0b57cec5SDimitry Andric   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
1028*0b57cec5SDimitry Andric   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
1029*0b57cec5SDimitry Andric   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
1030*0b57cec5SDimitry Andric   case bitc::CAST_FPEXT   : return Instruction::FPExt;
1031*0b57cec5SDimitry Andric   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
1032*0b57cec5SDimitry Andric   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
1033*0b57cec5SDimitry Andric   case bitc::CAST_BITCAST : return Instruction::BitCast;
1034*0b57cec5SDimitry Andric   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
1035*0b57cec5SDimitry Andric   }
1036*0b57cec5SDimitry Andric }
1037*0b57cec5SDimitry Andric 
1038*0b57cec5SDimitry Andric static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
1039*0b57cec5SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
1040*0b57cec5SDimitry Andric   // UnOps are only valid for int/fp or vector of int/fp types
1041*0b57cec5SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
1042*0b57cec5SDimitry Andric     return -1;
1043*0b57cec5SDimitry Andric 
1044*0b57cec5SDimitry Andric   switch (Val) {
1045*0b57cec5SDimitry Andric   default:
1046*0b57cec5SDimitry Andric     return -1;
10478bcb0991SDimitry Andric   case bitc::UNOP_FNEG:
1048*0b57cec5SDimitry Andric     return IsFP ? Instruction::FNeg : -1;
1049*0b57cec5SDimitry Andric   }
1050*0b57cec5SDimitry Andric }
1051*0b57cec5SDimitry Andric 
1052*0b57cec5SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
1053*0b57cec5SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
1054*0b57cec5SDimitry Andric   // BinOps are only valid for int/fp or vector of int/fp types
1055*0b57cec5SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
1056*0b57cec5SDimitry Andric     return -1;
1057*0b57cec5SDimitry Andric 
1058*0b57cec5SDimitry Andric   switch (Val) {
1059*0b57cec5SDimitry Andric   default:
1060*0b57cec5SDimitry Andric     return -1;
1061*0b57cec5SDimitry Andric   case bitc::BINOP_ADD:
1062*0b57cec5SDimitry Andric     return IsFP ? Instruction::FAdd : Instruction::Add;
1063*0b57cec5SDimitry Andric   case bitc::BINOP_SUB:
1064*0b57cec5SDimitry Andric     return IsFP ? Instruction::FSub : Instruction::Sub;
1065*0b57cec5SDimitry Andric   case bitc::BINOP_MUL:
1066*0b57cec5SDimitry Andric     return IsFP ? Instruction::FMul : Instruction::Mul;
1067*0b57cec5SDimitry Andric   case bitc::BINOP_UDIV:
1068*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::UDiv;
1069*0b57cec5SDimitry Andric   case bitc::BINOP_SDIV:
1070*0b57cec5SDimitry Andric     return IsFP ? Instruction::FDiv : Instruction::SDiv;
1071*0b57cec5SDimitry Andric   case bitc::BINOP_UREM:
1072*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::URem;
1073*0b57cec5SDimitry Andric   case bitc::BINOP_SREM:
1074*0b57cec5SDimitry Andric     return IsFP ? Instruction::FRem : Instruction::SRem;
1075*0b57cec5SDimitry Andric   case bitc::BINOP_SHL:
1076*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Shl;
1077*0b57cec5SDimitry Andric   case bitc::BINOP_LSHR:
1078*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::LShr;
1079*0b57cec5SDimitry Andric   case bitc::BINOP_ASHR:
1080*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::AShr;
1081*0b57cec5SDimitry Andric   case bitc::BINOP_AND:
1082*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::And;
1083*0b57cec5SDimitry Andric   case bitc::BINOP_OR:
1084*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Or;
1085*0b57cec5SDimitry Andric   case bitc::BINOP_XOR:
1086*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Xor;
1087*0b57cec5SDimitry Andric   }
1088*0b57cec5SDimitry Andric }
1089*0b57cec5SDimitry Andric 
1090*0b57cec5SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
1091*0b57cec5SDimitry Andric   switch (Val) {
1092*0b57cec5SDimitry Andric   default: return AtomicRMWInst::BAD_BINOP;
1093*0b57cec5SDimitry Andric   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1094*0b57cec5SDimitry Andric   case bitc::RMW_ADD: return AtomicRMWInst::Add;
1095*0b57cec5SDimitry Andric   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1096*0b57cec5SDimitry Andric   case bitc::RMW_AND: return AtomicRMWInst::And;
1097*0b57cec5SDimitry Andric   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1098*0b57cec5SDimitry Andric   case bitc::RMW_OR: return AtomicRMWInst::Or;
1099*0b57cec5SDimitry Andric   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1100*0b57cec5SDimitry Andric   case bitc::RMW_MAX: return AtomicRMWInst::Max;
1101*0b57cec5SDimitry Andric   case bitc::RMW_MIN: return AtomicRMWInst::Min;
1102*0b57cec5SDimitry Andric   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1103*0b57cec5SDimitry Andric   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1104*0b57cec5SDimitry Andric   case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
1105*0b57cec5SDimitry Andric   case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1106*0b57cec5SDimitry Andric   }
1107*0b57cec5SDimitry Andric }
1108*0b57cec5SDimitry Andric 
1109*0b57cec5SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) {
1110*0b57cec5SDimitry Andric   switch (Val) {
1111*0b57cec5SDimitry Andric   case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1112*0b57cec5SDimitry Andric   case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1113*0b57cec5SDimitry Andric   case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1114*0b57cec5SDimitry Andric   case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1115*0b57cec5SDimitry Andric   case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1116*0b57cec5SDimitry Andric   case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
1117*0b57cec5SDimitry Andric   default: // Map unknown orderings to sequentially-consistent.
1118*0b57cec5SDimitry Andric   case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
1119*0b57cec5SDimitry Andric   }
1120*0b57cec5SDimitry Andric }
1121*0b57cec5SDimitry Andric 
1122*0b57cec5SDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1123*0b57cec5SDimitry Andric   switch (Val) {
1124*0b57cec5SDimitry Andric   default: // Map unknown selection kinds to any.
1125*0b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_ANY:
1126*0b57cec5SDimitry Andric     return Comdat::Any;
1127*0b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1128*0b57cec5SDimitry Andric     return Comdat::ExactMatch;
1129*0b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_LARGEST:
1130*0b57cec5SDimitry Andric     return Comdat::Largest;
1131*0b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1132fe6060f1SDimitry Andric     return Comdat::NoDeduplicate;
1133*0b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1134*0b57cec5SDimitry Andric     return Comdat::SameSize;
1135*0b57cec5SDimitry Andric   }
1136*0b57cec5SDimitry Andric }
1137*0b57cec5SDimitry Andric 
1138*0b57cec5SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1139*0b57cec5SDimitry Andric   FastMathFlags FMF;
1140*0b57cec5SDimitry Andric   if (0 != (Val & bitc::UnsafeAlgebra))
1141*0b57cec5SDimitry Andric     FMF.setFast();
1142*0b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowReassoc))
1143*0b57cec5SDimitry Andric     FMF.setAllowReassoc();
1144*0b57cec5SDimitry Andric   if (0 != (Val & bitc::NoNaNs))
1145*0b57cec5SDimitry Andric     FMF.setNoNaNs();
1146*0b57cec5SDimitry Andric   if (0 != (Val & bitc::NoInfs))
1147*0b57cec5SDimitry Andric     FMF.setNoInfs();
1148*0b57cec5SDimitry Andric   if (0 != (Val & bitc::NoSignedZeros))
1149*0b57cec5SDimitry Andric     FMF.setNoSignedZeros();
1150*0b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowReciprocal))
1151*0b57cec5SDimitry Andric     FMF.setAllowReciprocal();
1152*0b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowContract))
1153*0b57cec5SDimitry Andric     FMF.setAllowContract(true);
1154*0b57cec5SDimitry Andric   if (0 != (Val & bitc::ApproxFunc))
1155*0b57cec5SDimitry Andric     FMF.setApproxFunc();
1156*0b57cec5SDimitry Andric   return FMF;
1157*0b57cec5SDimitry Andric }
1158*0b57cec5SDimitry Andric 
1159*0b57cec5SDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1160*0b57cec5SDimitry Andric   switch (Val) {
1161*0b57cec5SDimitry Andric   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1162*0b57cec5SDimitry Andric   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1163*0b57cec5SDimitry Andric   }
1164*0b57cec5SDimitry Andric }
1165*0b57cec5SDimitry Andric 
1166fe6060f1SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) {
1167*0b57cec5SDimitry Andric   // The type table size is always specified correctly.
1168*0b57cec5SDimitry Andric   if (ID >= TypeList.size())
1169*0b57cec5SDimitry Andric     return nullptr;
1170*0b57cec5SDimitry Andric 
1171*0b57cec5SDimitry Andric   if (Type *Ty = TypeList[ID])
1172*0b57cec5SDimitry Andric     return Ty;
1173*0b57cec5SDimitry Andric 
1174*0b57cec5SDimitry Andric   // If we have a forward reference, the only possible case is when it is to a
1175*0b57cec5SDimitry Andric   // named struct.  Just create a placeholder for now.
1176*0b57cec5SDimitry Andric   return TypeList[ID] = createIdentifiedStructType(Context);
1177*0b57cec5SDimitry Andric }
1178*0b57cec5SDimitry Andric 
1179*0b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1180*0b57cec5SDimitry Andric                                                       StringRef Name) {
1181*0b57cec5SDimitry Andric   auto *Ret = StructType::create(Context, Name);
1182*0b57cec5SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
1183*0b57cec5SDimitry Andric   return Ret;
1184*0b57cec5SDimitry Andric }
1185*0b57cec5SDimitry Andric 
1186*0b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1187*0b57cec5SDimitry Andric   auto *Ret = StructType::create(Context);
1188*0b57cec5SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
1189*0b57cec5SDimitry Andric   return Ret;
1190*0b57cec5SDimitry Andric }
1191*0b57cec5SDimitry Andric 
1192*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1193*0b57cec5SDimitry Andric //  Functions for parsing blocks from the bitcode file
1194*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1195*0b57cec5SDimitry Andric 
1196*0b57cec5SDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1197*0b57cec5SDimitry Andric   switch (Val) {
1198*0b57cec5SDimitry Andric   case Attribute::EndAttrKinds:
11995ffd83dbSDimitry Andric   case Attribute::EmptyKey:
12005ffd83dbSDimitry Andric   case Attribute::TombstoneKey:
1201*0b57cec5SDimitry Andric     llvm_unreachable("Synthetic enumerators which should never get here");
1202*0b57cec5SDimitry Andric 
1203*0b57cec5SDimitry Andric   case Attribute::None:            return 0;
1204*0b57cec5SDimitry Andric   case Attribute::ZExt:            return 1 << 0;
1205*0b57cec5SDimitry Andric   case Attribute::SExt:            return 1 << 1;
1206*0b57cec5SDimitry Andric   case Attribute::NoReturn:        return 1 << 2;
1207*0b57cec5SDimitry Andric   case Attribute::InReg:           return 1 << 3;
1208*0b57cec5SDimitry Andric   case Attribute::StructRet:       return 1 << 4;
1209*0b57cec5SDimitry Andric   case Attribute::NoUnwind:        return 1 << 5;
1210*0b57cec5SDimitry Andric   case Attribute::NoAlias:         return 1 << 6;
1211*0b57cec5SDimitry Andric   case Attribute::ByVal:           return 1 << 7;
1212*0b57cec5SDimitry Andric   case Attribute::Nest:            return 1 << 8;
1213*0b57cec5SDimitry Andric   case Attribute::ReadNone:        return 1 << 9;
1214*0b57cec5SDimitry Andric   case Attribute::ReadOnly:        return 1 << 10;
1215*0b57cec5SDimitry Andric   case Attribute::NoInline:        return 1 << 11;
1216*0b57cec5SDimitry Andric   case Attribute::AlwaysInline:    return 1 << 12;
1217*0b57cec5SDimitry Andric   case Attribute::OptimizeForSize: return 1 << 13;
1218*0b57cec5SDimitry Andric   case Attribute::StackProtect:    return 1 << 14;
1219*0b57cec5SDimitry Andric   case Attribute::StackProtectReq: return 1 << 15;
1220*0b57cec5SDimitry Andric   case Attribute::Alignment:       return 31 << 16;
1221*0b57cec5SDimitry Andric   case Attribute::NoCapture:       return 1 << 21;
1222*0b57cec5SDimitry Andric   case Attribute::NoRedZone:       return 1 << 22;
1223*0b57cec5SDimitry Andric   case Attribute::NoImplicitFloat: return 1 << 23;
1224*0b57cec5SDimitry Andric   case Attribute::Naked:           return 1 << 24;
1225*0b57cec5SDimitry Andric   case Attribute::InlineHint:      return 1 << 25;
1226*0b57cec5SDimitry Andric   case Attribute::StackAlignment:  return 7 << 26;
1227*0b57cec5SDimitry Andric   case Attribute::ReturnsTwice:    return 1 << 29;
1228*0b57cec5SDimitry Andric   case Attribute::UWTable:         return 1 << 30;
1229*0b57cec5SDimitry Andric   case Attribute::NonLazyBind:     return 1U << 31;
1230*0b57cec5SDimitry Andric   case Attribute::SanitizeAddress: return 1ULL << 32;
1231*0b57cec5SDimitry Andric   case Attribute::MinSize:         return 1ULL << 33;
1232*0b57cec5SDimitry Andric   case Attribute::NoDuplicate:     return 1ULL << 34;
1233*0b57cec5SDimitry Andric   case Attribute::StackProtectStrong: return 1ULL << 35;
1234*0b57cec5SDimitry Andric   case Attribute::SanitizeThread:  return 1ULL << 36;
1235*0b57cec5SDimitry Andric   case Attribute::SanitizeMemory:  return 1ULL << 37;
1236*0b57cec5SDimitry Andric   case Attribute::NoBuiltin:       return 1ULL << 38;
1237*0b57cec5SDimitry Andric   case Attribute::Returned:        return 1ULL << 39;
1238*0b57cec5SDimitry Andric   case Attribute::Cold:            return 1ULL << 40;
1239*0b57cec5SDimitry Andric   case Attribute::Builtin:         return 1ULL << 41;
1240*0b57cec5SDimitry Andric   case Attribute::OptimizeNone:    return 1ULL << 42;
1241*0b57cec5SDimitry Andric   case Attribute::InAlloca:        return 1ULL << 43;
1242*0b57cec5SDimitry Andric   case Attribute::NonNull:         return 1ULL << 44;
1243*0b57cec5SDimitry Andric   case Attribute::JumpTable:       return 1ULL << 45;
1244*0b57cec5SDimitry Andric   case Attribute::Convergent:      return 1ULL << 46;
1245*0b57cec5SDimitry Andric   case Attribute::SafeStack:       return 1ULL << 47;
1246*0b57cec5SDimitry Andric   case Attribute::NoRecurse:       return 1ULL << 48;
1247*0b57cec5SDimitry Andric   case Attribute::InaccessibleMemOnly:         return 1ULL << 49;
1248*0b57cec5SDimitry Andric   case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1249*0b57cec5SDimitry Andric   case Attribute::SwiftSelf:       return 1ULL << 51;
1250*0b57cec5SDimitry Andric   case Attribute::SwiftError:      return 1ULL << 52;
1251*0b57cec5SDimitry Andric   case Attribute::WriteOnly:       return 1ULL << 53;
1252*0b57cec5SDimitry Andric   case Attribute::Speculatable:    return 1ULL << 54;
1253*0b57cec5SDimitry Andric   case Attribute::StrictFP:        return 1ULL << 55;
1254*0b57cec5SDimitry Andric   case Attribute::SanitizeHWAddress: return 1ULL << 56;
1255*0b57cec5SDimitry Andric   case Attribute::NoCfCheck:       return 1ULL << 57;
1256*0b57cec5SDimitry Andric   case Attribute::OptForFuzzing:   return 1ULL << 58;
1257*0b57cec5SDimitry Andric   case Attribute::ShadowCallStack: return 1ULL << 59;
1258*0b57cec5SDimitry Andric   case Attribute::SpeculativeLoadHardening:
1259*0b57cec5SDimitry Andric     return 1ULL << 60;
1260*0b57cec5SDimitry Andric   case Attribute::ImmArg:
1261*0b57cec5SDimitry Andric     return 1ULL << 61;
1262*0b57cec5SDimitry Andric   case Attribute::WillReturn:
1263*0b57cec5SDimitry Andric     return 1ULL << 62;
1264*0b57cec5SDimitry Andric   case Attribute::NoFree:
1265*0b57cec5SDimitry Andric     return 1ULL << 63;
12665ffd83dbSDimitry Andric   default:
12675ffd83dbSDimitry Andric     // Other attributes are not supported in the raw format,
12685ffd83dbSDimitry Andric     // as we ran out of space.
12695ffd83dbSDimitry Andric     return 0;
1270*0b57cec5SDimitry Andric   }
1271*0b57cec5SDimitry Andric   llvm_unreachable("Unsupported attribute type");
1272*0b57cec5SDimitry Andric }
1273*0b57cec5SDimitry Andric 
1274*0b57cec5SDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1275*0b57cec5SDimitry Andric   if (!Val) return;
1276*0b57cec5SDimitry Andric 
1277*0b57cec5SDimitry Andric   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1278*0b57cec5SDimitry Andric        I = Attribute::AttrKind(I + 1)) {
1279*0b57cec5SDimitry Andric     if (uint64_t A = (Val & getRawAttributeMask(I))) {
1280*0b57cec5SDimitry Andric       if (I == Attribute::Alignment)
1281*0b57cec5SDimitry Andric         B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1282*0b57cec5SDimitry Andric       else if (I == Attribute::StackAlignment)
1283*0b57cec5SDimitry Andric         B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1284fe6060f1SDimitry Andric       else if (Attribute::isTypeAttrKind(I))
1285fe6060f1SDimitry Andric         B.addTypeAttr(I, nullptr); // Type will be auto-upgraded.
1286*0b57cec5SDimitry Andric       else
1287*0b57cec5SDimitry Andric         B.addAttribute(I);
1288*0b57cec5SDimitry Andric     }
1289*0b57cec5SDimitry Andric   }
1290*0b57cec5SDimitry Andric }
1291*0b57cec5SDimitry Andric 
1292*0b57cec5SDimitry Andric /// This fills an AttrBuilder object with the LLVM attributes that have
1293*0b57cec5SDimitry Andric /// been decoded from the given integer. This function must stay in sync with
1294*0b57cec5SDimitry Andric /// 'encodeLLVMAttributesForBitcode'.
1295*0b57cec5SDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1296*0b57cec5SDimitry Andric                                            uint64_t EncodedAttrs) {
1297*0b57cec5SDimitry Andric   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
1298*0b57cec5SDimitry Andric   // the bits above 31 down by 11 bits.
1299*0b57cec5SDimitry Andric   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1300*0b57cec5SDimitry Andric   assert((!Alignment || isPowerOf2_32(Alignment)) &&
1301*0b57cec5SDimitry Andric          "Alignment must be a power of two.");
1302*0b57cec5SDimitry Andric 
1303*0b57cec5SDimitry Andric   if (Alignment)
1304*0b57cec5SDimitry Andric     B.addAlignmentAttr(Alignment);
1305*0b57cec5SDimitry Andric   addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1306*0b57cec5SDimitry Andric                           (EncodedAttrs & 0xffff));
1307*0b57cec5SDimitry Andric }
1308*0b57cec5SDimitry Andric 
1309*0b57cec5SDimitry Andric Error BitcodeReader::parseAttributeBlock() {
1310*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1311*0b57cec5SDimitry Andric     return Err;
1312*0b57cec5SDimitry Andric 
1313*0b57cec5SDimitry Andric   if (!MAttributes.empty())
1314*0b57cec5SDimitry Andric     return error("Invalid multiple blocks");
1315*0b57cec5SDimitry Andric 
1316*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
1317*0b57cec5SDimitry Andric 
1318*0b57cec5SDimitry Andric   SmallVector<AttributeList, 8> Attrs;
1319*0b57cec5SDimitry Andric 
1320*0b57cec5SDimitry Andric   // Read all the records.
1321*0b57cec5SDimitry Andric   while (true) {
1322*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1323*0b57cec5SDimitry Andric     if (!MaybeEntry)
1324*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
1325*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
1326*0b57cec5SDimitry Andric 
1327*0b57cec5SDimitry Andric     switch (Entry.Kind) {
1328*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1329*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
1330*0b57cec5SDimitry Andric       return error("Malformed block");
1331*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
1332*0b57cec5SDimitry Andric       return Error::success();
1333*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
1334*0b57cec5SDimitry Andric       // The interesting case.
1335*0b57cec5SDimitry Andric       break;
1336*0b57cec5SDimitry Andric     }
1337*0b57cec5SDimitry Andric 
1338*0b57cec5SDimitry Andric     // Read a record.
1339*0b57cec5SDimitry Andric     Record.clear();
1340*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1341*0b57cec5SDimitry Andric     if (!MaybeRecord)
1342*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
1343*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
1344*0b57cec5SDimitry Andric     default:  // Default behavior: ignore.
1345*0b57cec5SDimitry Andric       break;
1346*0b57cec5SDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
13475ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
1348*0b57cec5SDimitry Andric       if (Record.size() & 1)
1349*0b57cec5SDimitry Andric         return error("Invalid record");
1350*0b57cec5SDimitry Andric 
1351*0b57cec5SDimitry Andric       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
135204eeddc0SDimitry Andric         AttrBuilder B(Context);
1353*0b57cec5SDimitry Andric         decodeLLVMAttributesForBitcode(B, Record[i+1]);
1354*0b57cec5SDimitry Andric         Attrs.push_back(AttributeList::get(Context, Record[i], B));
1355*0b57cec5SDimitry Andric       }
1356*0b57cec5SDimitry Andric 
1357*0b57cec5SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
1358*0b57cec5SDimitry Andric       Attrs.clear();
1359*0b57cec5SDimitry Andric       break;
1360*0b57cec5SDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1361*0b57cec5SDimitry Andric       for (unsigned i = 0, e = Record.size(); i != e; ++i)
1362*0b57cec5SDimitry Andric         Attrs.push_back(MAttributeGroups[Record[i]]);
1363*0b57cec5SDimitry Andric 
1364*0b57cec5SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
1365*0b57cec5SDimitry Andric       Attrs.clear();
1366*0b57cec5SDimitry Andric       break;
1367*0b57cec5SDimitry Andric     }
1368*0b57cec5SDimitry Andric   }
1369*0b57cec5SDimitry Andric }
1370*0b57cec5SDimitry Andric 
1371*0b57cec5SDimitry Andric // Returns Attribute::None on unrecognized codes.
1372*0b57cec5SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1373*0b57cec5SDimitry Andric   switch (Code) {
1374*0b57cec5SDimitry Andric   default:
1375*0b57cec5SDimitry Andric     return Attribute::None;
1376*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALIGNMENT:
1377*0b57cec5SDimitry Andric     return Attribute::Alignment;
1378*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALWAYS_INLINE:
1379*0b57cec5SDimitry Andric     return Attribute::AlwaysInline;
1380*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_ARGMEMONLY:
1381*0b57cec5SDimitry Andric     return Attribute::ArgMemOnly;
1382*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_BUILTIN:
1383*0b57cec5SDimitry Andric     return Attribute::Builtin;
1384*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_BY_VAL:
1385*0b57cec5SDimitry Andric     return Attribute::ByVal;
1386*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_IN_ALLOCA:
1387*0b57cec5SDimitry Andric     return Attribute::InAlloca;
1388*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_COLD:
1389*0b57cec5SDimitry Andric     return Attribute::Cold;
1390*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_CONVERGENT:
1391*0b57cec5SDimitry Andric     return Attribute::Convergent;
1392349cc55cSDimitry Andric   case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION:
1393349cc55cSDimitry Andric     return Attribute::DisableSanitizerInstrumentation;
1394fe6060f1SDimitry Andric   case bitc::ATTR_KIND_ELEMENTTYPE:
1395fe6060f1SDimitry Andric     return Attribute::ElementType;
1396*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1397*0b57cec5SDimitry Andric     return Attribute::InaccessibleMemOnly;
1398*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1399*0b57cec5SDimitry Andric     return Attribute::InaccessibleMemOrArgMemOnly;
1400*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_INLINE_HINT:
1401*0b57cec5SDimitry Andric     return Attribute::InlineHint;
1402*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_IN_REG:
1403*0b57cec5SDimitry Andric     return Attribute::InReg;
1404*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_JUMP_TABLE:
1405*0b57cec5SDimitry Andric     return Attribute::JumpTable;
1406*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_MIN_SIZE:
1407*0b57cec5SDimitry Andric     return Attribute::MinSize;
1408*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NAKED:
1409*0b57cec5SDimitry Andric     return Attribute::Naked;
1410*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NEST:
1411*0b57cec5SDimitry Andric     return Attribute::Nest;
1412*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_ALIAS:
1413*0b57cec5SDimitry Andric     return Attribute::NoAlias;
1414*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_BUILTIN:
1415*0b57cec5SDimitry Andric     return Attribute::NoBuiltin;
1416e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_NO_CALLBACK:
1417e8d8bef9SDimitry Andric     return Attribute::NoCallback;
1418*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_CAPTURE:
1419*0b57cec5SDimitry Andric     return Attribute::NoCapture;
1420*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_DUPLICATE:
1421*0b57cec5SDimitry Andric     return Attribute::NoDuplicate;
1422*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOFREE:
1423*0b57cec5SDimitry Andric     return Attribute::NoFree;
1424*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1425*0b57cec5SDimitry Andric     return Attribute::NoImplicitFloat;
1426*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_INLINE:
1427*0b57cec5SDimitry Andric     return Attribute::NoInline;
1428*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RECURSE:
1429*0b57cec5SDimitry Andric     return Attribute::NoRecurse;
14305ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NO_MERGE:
14315ffd83dbSDimitry Andric     return Attribute::NoMerge;
1432*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NON_LAZY_BIND:
1433*0b57cec5SDimitry Andric     return Attribute::NonLazyBind;
1434*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NON_NULL:
1435*0b57cec5SDimitry Andric     return Attribute::NonNull;
1436*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE:
1437*0b57cec5SDimitry Andric     return Attribute::Dereferenceable;
1438*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1439*0b57cec5SDimitry Andric     return Attribute::DereferenceableOrNull;
1440*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALLOC_SIZE:
1441*0b57cec5SDimitry Andric     return Attribute::AllocSize;
1442*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RED_ZONE:
1443*0b57cec5SDimitry Andric     return Attribute::NoRedZone;
1444*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RETURN:
1445*0b57cec5SDimitry Andric     return Attribute::NoReturn;
1446*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOSYNC:
1447*0b57cec5SDimitry Andric     return Attribute::NoSync;
1448*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOCF_CHECK:
1449*0b57cec5SDimitry Andric     return Attribute::NoCfCheck;
1450fe6060f1SDimitry Andric   case bitc::ATTR_KIND_NO_PROFILE:
1451fe6060f1SDimitry Andric     return Attribute::NoProfile;
1452*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_UNWIND:
1453*0b57cec5SDimitry Andric     return Attribute::NoUnwind;
1454fe6060f1SDimitry Andric   case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
1455fe6060f1SDimitry Andric     return Attribute::NoSanitizeCoverage;
14565ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
14575ffd83dbSDimitry Andric     return Attribute::NullPointerIsValid;
1458*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPT_FOR_FUZZING:
1459*0b57cec5SDimitry Andric     return Attribute::OptForFuzzing;
1460*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1461*0b57cec5SDimitry Andric     return Attribute::OptimizeForSize;
1462*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_NONE:
1463*0b57cec5SDimitry Andric     return Attribute::OptimizeNone;
1464*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_READ_NONE:
1465*0b57cec5SDimitry Andric     return Attribute::ReadNone;
1466*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_READ_ONLY:
1467*0b57cec5SDimitry Andric     return Attribute::ReadOnly;
1468*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_RETURNED:
1469*0b57cec5SDimitry Andric     return Attribute::Returned;
1470*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_RETURNS_TWICE:
1471*0b57cec5SDimitry Andric     return Attribute::ReturnsTwice;
1472*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_S_EXT:
1473*0b57cec5SDimitry Andric     return Attribute::SExt;
1474*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SPECULATABLE:
1475*0b57cec5SDimitry Andric     return Attribute::Speculatable;
1476*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_ALIGNMENT:
1477*0b57cec5SDimitry Andric     return Attribute::StackAlignment;
1478*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT:
1479*0b57cec5SDimitry Andric     return Attribute::StackProtect;
1480*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1481*0b57cec5SDimitry Andric     return Attribute::StackProtectReq;
1482*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1483*0b57cec5SDimitry Andric     return Attribute::StackProtectStrong;
1484*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SAFESTACK:
1485*0b57cec5SDimitry Andric     return Attribute::SafeStack;
1486*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SHADOWCALLSTACK:
1487*0b57cec5SDimitry Andric     return Attribute::ShadowCallStack;
1488*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STRICT_FP:
1489*0b57cec5SDimitry Andric     return Attribute::StrictFP;
1490*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STRUCT_RET:
1491*0b57cec5SDimitry Andric     return Attribute::StructRet;
1492*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1493*0b57cec5SDimitry Andric     return Attribute::SanitizeAddress;
1494*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
1495*0b57cec5SDimitry Andric     return Attribute::SanitizeHWAddress;
1496*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_THREAD:
1497*0b57cec5SDimitry Andric     return Attribute::SanitizeThread;
1498*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMORY:
1499*0b57cec5SDimitry Andric     return Attribute::SanitizeMemory;
1500*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
1501*0b57cec5SDimitry Andric     return Attribute::SpeculativeLoadHardening;
1502*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ERROR:
1503*0b57cec5SDimitry Andric     return Attribute::SwiftError;
1504*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SWIFT_SELF:
1505*0b57cec5SDimitry Andric     return Attribute::SwiftSelf;
1506fe6060f1SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ASYNC:
1507fe6060f1SDimitry Andric     return Attribute::SwiftAsync;
1508*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_UW_TABLE:
1509*0b57cec5SDimitry Andric     return Attribute::UWTable;
1510fe6060f1SDimitry Andric   case bitc::ATTR_KIND_VSCALE_RANGE:
1511fe6060f1SDimitry Andric     return Attribute::VScaleRange;
1512*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_WILLRETURN:
1513*0b57cec5SDimitry Andric     return Attribute::WillReturn;
1514*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_WRITEONLY:
1515*0b57cec5SDimitry Andric     return Attribute::WriteOnly;
1516*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_Z_EXT:
1517*0b57cec5SDimitry Andric     return Attribute::ZExt;
1518*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_IMMARG:
1519*0b57cec5SDimitry Andric     return Attribute::ImmArg;
1520*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMTAG:
1521*0b57cec5SDimitry Andric     return Attribute::SanitizeMemTag;
15225ffd83dbSDimitry Andric   case bitc::ATTR_KIND_PREALLOCATED:
15235ffd83dbSDimitry Andric     return Attribute::Preallocated;
15245ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NOUNDEF:
15255ffd83dbSDimitry Andric     return Attribute::NoUndef;
1526e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_BYREF:
1527e8d8bef9SDimitry Andric     return Attribute::ByRef;
1528e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_MUSTPROGRESS:
1529e8d8bef9SDimitry Andric     return Attribute::MustProgress;
1530e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_HOT:
1531e8d8bef9SDimitry Andric     return Attribute::Hot;
1532*0b57cec5SDimitry Andric   }
1533*0b57cec5SDimitry Andric }
1534*0b57cec5SDimitry Andric 
1535*0b57cec5SDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
15368bcb0991SDimitry Andric                                          MaybeAlign &Alignment) {
1537*0b57cec5SDimitry Andric   // Note: Alignment in bitcode files is incremented by 1, so that zero
1538*0b57cec5SDimitry Andric   // can be used for default alignment.
1539*0b57cec5SDimitry Andric   if (Exponent > Value::MaxAlignmentExponent + 1)
1540*0b57cec5SDimitry Andric     return error("Invalid alignment value");
15418bcb0991SDimitry Andric   Alignment = decodeMaybeAlign(Exponent);
1542*0b57cec5SDimitry Andric   return Error::success();
1543*0b57cec5SDimitry Andric }
1544*0b57cec5SDimitry Andric 
1545*0b57cec5SDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
1546*0b57cec5SDimitry Andric   *Kind = getAttrFromCode(Code);
1547*0b57cec5SDimitry Andric   if (*Kind == Attribute::None)
1548*0b57cec5SDimitry Andric     return error("Unknown attribute kind (" + Twine(Code) + ")");
1549*0b57cec5SDimitry Andric   return Error::success();
1550*0b57cec5SDimitry Andric }
1551*0b57cec5SDimitry Andric 
1552*0b57cec5SDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() {
1553*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
1554*0b57cec5SDimitry Andric     return Err;
1555*0b57cec5SDimitry Andric 
1556*0b57cec5SDimitry Andric   if (!MAttributeGroups.empty())
1557*0b57cec5SDimitry Andric     return error("Invalid multiple blocks");
1558*0b57cec5SDimitry Andric 
1559*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
1560*0b57cec5SDimitry Andric 
1561*0b57cec5SDimitry Andric   // Read all the records.
1562*0b57cec5SDimitry Andric   while (true) {
1563*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1564*0b57cec5SDimitry Andric     if (!MaybeEntry)
1565*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
1566*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
1567*0b57cec5SDimitry Andric 
1568*0b57cec5SDimitry Andric     switch (Entry.Kind) {
1569*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1570*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
1571*0b57cec5SDimitry Andric       return error("Malformed block");
1572*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
1573*0b57cec5SDimitry Andric       return Error::success();
1574*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
1575*0b57cec5SDimitry Andric       // The interesting case.
1576*0b57cec5SDimitry Andric       break;
1577*0b57cec5SDimitry Andric     }
1578*0b57cec5SDimitry Andric 
1579*0b57cec5SDimitry Andric     // Read a record.
1580*0b57cec5SDimitry Andric     Record.clear();
1581*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1582*0b57cec5SDimitry Andric     if (!MaybeRecord)
1583*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
1584*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
1585*0b57cec5SDimitry Andric     default:  // Default behavior: ignore.
1586*0b57cec5SDimitry Andric       break;
1587*0b57cec5SDimitry Andric     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1588*0b57cec5SDimitry Andric       if (Record.size() < 3)
1589*0b57cec5SDimitry Andric         return error("Invalid record");
1590*0b57cec5SDimitry Andric 
1591*0b57cec5SDimitry Andric       uint64_t GrpID = Record[0];
1592*0b57cec5SDimitry Andric       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1593*0b57cec5SDimitry Andric 
159404eeddc0SDimitry Andric       AttrBuilder B(Context);
1595*0b57cec5SDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1596*0b57cec5SDimitry Andric         if (Record[i] == 0) {        // Enum attribute
1597*0b57cec5SDimitry Andric           Attribute::AttrKind Kind;
1598*0b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
1599*0b57cec5SDimitry Andric             return Err;
1600*0b57cec5SDimitry Andric 
1601*0b57cec5SDimitry Andric           // Upgrade old-style byval attribute to one with a type, even if it's
1602*0b57cec5SDimitry Andric           // nullptr. We will have to insert the real type when we associate
1603*0b57cec5SDimitry Andric           // this AttributeList with a function.
1604*0b57cec5SDimitry Andric           if (Kind == Attribute::ByVal)
1605*0b57cec5SDimitry Andric             B.addByValAttr(nullptr);
1606e8d8bef9SDimitry Andric           else if (Kind == Attribute::StructRet)
1607e8d8bef9SDimitry Andric             B.addStructRetAttr(nullptr);
1608fe6060f1SDimitry Andric           else if (Kind == Attribute::InAlloca)
1609fe6060f1SDimitry Andric             B.addInAllocaAttr(nullptr);
1610fe6060f1SDimitry Andric           else if (Attribute::isEnumAttrKind(Kind))
1611*0b57cec5SDimitry Andric             B.addAttribute(Kind);
1612fe6060f1SDimitry Andric           else
1613fe6060f1SDimitry Andric             return error("Not an enum attribute");
1614*0b57cec5SDimitry Andric         } else if (Record[i] == 1) { // Integer attribute
1615*0b57cec5SDimitry Andric           Attribute::AttrKind Kind;
1616*0b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
1617*0b57cec5SDimitry Andric             return Err;
1618fe6060f1SDimitry Andric           if (!Attribute::isIntAttrKind(Kind))
1619fe6060f1SDimitry Andric             return error("Not an int attribute");
1620*0b57cec5SDimitry Andric           if (Kind == Attribute::Alignment)
1621*0b57cec5SDimitry Andric             B.addAlignmentAttr(Record[++i]);
1622*0b57cec5SDimitry Andric           else if (Kind == Attribute::StackAlignment)
1623*0b57cec5SDimitry Andric             B.addStackAlignmentAttr(Record[++i]);
1624*0b57cec5SDimitry Andric           else if (Kind == Attribute::Dereferenceable)
1625*0b57cec5SDimitry Andric             B.addDereferenceableAttr(Record[++i]);
1626*0b57cec5SDimitry Andric           else if (Kind == Attribute::DereferenceableOrNull)
1627*0b57cec5SDimitry Andric             B.addDereferenceableOrNullAttr(Record[++i]);
1628*0b57cec5SDimitry Andric           else if (Kind == Attribute::AllocSize)
1629*0b57cec5SDimitry Andric             B.addAllocSizeAttrFromRawRepr(Record[++i]);
1630fe6060f1SDimitry Andric           else if (Kind == Attribute::VScaleRange)
1631fe6060f1SDimitry Andric             B.addVScaleRangeAttrFromRawRepr(Record[++i]);
1632*0b57cec5SDimitry Andric         } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
1633*0b57cec5SDimitry Andric           bool HasValue = (Record[i++] == 4);
1634*0b57cec5SDimitry Andric           SmallString<64> KindStr;
1635*0b57cec5SDimitry Andric           SmallString<64> ValStr;
1636*0b57cec5SDimitry Andric 
1637*0b57cec5SDimitry Andric           while (Record[i] != 0 && i != e)
1638*0b57cec5SDimitry Andric             KindStr += Record[i++];
1639*0b57cec5SDimitry Andric           assert(Record[i] == 0 && "Kind string not null terminated");
1640*0b57cec5SDimitry Andric 
1641*0b57cec5SDimitry Andric           if (HasValue) {
1642*0b57cec5SDimitry Andric             // Has a value associated with it.
1643*0b57cec5SDimitry Andric             ++i; // Skip the '0' that terminates the "kind" string.
1644*0b57cec5SDimitry Andric             while (Record[i] != 0 && i != e)
1645*0b57cec5SDimitry Andric               ValStr += Record[i++];
1646*0b57cec5SDimitry Andric             assert(Record[i] == 0 && "Value string not null terminated");
1647*0b57cec5SDimitry Andric           }
1648*0b57cec5SDimitry Andric 
1649*0b57cec5SDimitry Andric           B.addAttribute(KindStr.str(), ValStr.str());
1650*0b57cec5SDimitry Andric         } else {
1651*0b57cec5SDimitry Andric           assert((Record[i] == 5 || Record[i] == 6) &&
1652*0b57cec5SDimitry Andric                  "Invalid attribute group entry");
1653*0b57cec5SDimitry Andric           bool HasType = Record[i] == 6;
1654*0b57cec5SDimitry Andric           Attribute::AttrKind Kind;
1655*0b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
1656*0b57cec5SDimitry Andric             return Err;
1657fe6060f1SDimitry Andric           if (!Attribute::isTypeAttrKind(Kind))
1658fe6060f1SDimitry Andric             return error("Not a type attribute");
1659fe6060f1SDimitry Andric 
1660fe6060f1SDimitry Andric           B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
1661*0b57cec5SDimitry Andric         }
1662*0b57cec5SDimitry Andric       }
1663*0b57cec5SDimitry Andric 
16645ffd83dbSDimitry Andric       UpgradeAttributes(B);
1665*0b57cec5SDimitry Andric       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1666*0b57cec5SDimitry Andric       break;
1667*0b57cec5SDimitry Andric     }
1668*0b57cec5SDimitry Andric     }
1669*0b57cec5SDimitry Andric   }
1670*0b57cec5SDimitry Andric }
1671*0b57cec5SDimitry Andric 
1672*0b57cec5SDimitry Andric Error BitcodeReader::parseTypeTable() {
1673*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
1674*0b57cec5SDimitry Andric     return Err;
1675*0b57cec5SDimitry Andric 
1676*0b57cec5SDimitry Andric   return parseTypeTableBody();
1677*0b57cec5SDimitry Andric }
1678*0b57cec5SDimitry Andric 
1679*0b57cec5SDimitry Andric Error BitcodeReader::parseTypeTableBody() {
1680*0b57cec5SDimitry Andric   if (!TypeList.empty())
1681*0b57cec5SDimitry Andric     return error("Invalid multiple blocks");
1682*0b57cec5SDimitry Andric 
1683*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
1684*0b57cec5SDimitry Andric   unsigned NumRecords = 0;
1685*0b57cec5SDimitry Andric 
1686*0b57cec5SDimitry Andric   SmallString<64> TypeName;
1687*0b57cec5SDimitry Andric 
1688*0b57cec5SDimitry Andric   // Read all the records for this type table.
1689*0b57cec5SDimitry Andric   while (true) {
1690*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1691*0b57cec5SDimitry Andric     if (!MaybeEntry)
1692*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
1693*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
1694*0b57cec5SDimitry Andric 
1695*0b57cec5SDimitry Andric     switch (Entry.Kind) {
1696*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1697*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
1698*0b57cec5SDimitry Andric       return error("Malformed block");
1699*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
1700*0b57cec5SDimitry Andric       if (NumRecords != TypeList.size())
1701*0b57cec5SDimitry Andric         return error("Malformed block");
1702*0b57cec5SDimitry Andric       return Error::success();
1703*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
1704*0b57cec5SDimitry Andric       // The interesting case.
1705*0b57cec5SDimitry Andric       break;
1706*0b57cec5SDimitry Andric     }
1707*0b57cec5SDimitry Andric 
1708*0b57cec5SDimitry Andric     // Read a record.
1709*0b57cec5SDimitry Andric     Record.clear();
1710*0b57cec5SDimitry Andric     Type *ResultTy = nullptr;
1711*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1712*0b57cec5SDimitry Andric     if (!MaybeRecord)
1713*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
1714*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
1715*0b57cec5SDimitry Andric     default:
1716*0b57cec5SDimitry Andric       return error("Invalid value");
1717*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1718*0b57cec5SDimitry Andric       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1719*0b57cec5SDimitry Andric       // type list.  This allows us to reserve space.
1720e8d8bef9SDimitry Andric       if (Record.empty())
1721*0b57cec5SDimitry Andric         return error("Invalid record");
1722*0b57cec5SDimitry Andric       TypeList.resize(Record[0]);
1723*0b57cec5SDimitry Andric       continue;
1724*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_VOID:      // VOID
1725*0b57cec5SDimitry Andric       ResultTy = Type::getVoidTy(Context);
1726*0b57cec5SDimitry Andric       break;
1727*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_HALF:     // HALF
1728*0b57cec5SDimitry Andric       ResultTy = Type::getHalfTy(Context);
1729*0b57cec5SDimitry Andric       break;
17305ffd83dbSDimitry Andric     case bitc::TYPE_CODE_BFLOAT:    // BFLOAT
17315ffd83dbSDimitry Andric       ResultTy = Type::getBFloatTy(Context);
17325ffd83dbSDimitry Andric       break;
1733*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_FLOAT:     // FLOAT
1734*0b57cec5SDimitry Andric       ResultTy = Type::getFloatTy(Context);
1735*0b57cec5SDimitry Andric       break;
1736*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
1737*0b57cec5SDimitry Andric       ResultTy = Type::getDoubleTy(Context);
1738*0b57cec5SDimitry Andric       break;
1739*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
1740*0b57cec5SDimitry Andric       ResultTy = Type::getX86_FP80Ty(Context);
1741*0b57cec5SDimitry Andric       break;
1742*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_FP128:     // FP128
1743*0b57cec5SDimitry Andric       ResultTy = Type::getFP128Ty(Context);
1744*0b57cec5SDimitry Andric       break;
1745*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1746*0b57cec5SDimitry Andric       ResultTy = Type::getPPC_FP128Ty(Context);
1747*0b57cec5SDimitry Andric       break;
1748*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_LABEL:     // LABEL
1749*0b57cec5SDimitry Andric       ResultTy = Type::getLabelTy(Context);
1750*0b57cec5SDimitry Andric       break;
1751*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_METADATA:  // METADATA
1752*0b57cec5SDimitry Andric       ResultTy = Type::getMetadataTy(Context);
1753*0b57cec5SDimitry Andric       break;
1754*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
1755*0b57cec5SDimitry Andric       ResultTy = Type::getX86_MMXTy(Context);
1756*0b57cec5SDimitry Andric       break;
1757e8d8bef9SDimitry Andric     case bitc::TYPE_CODE_X86_AMX:   // X86_AMX
1758e8d8bef9SDimitry Andric       ResultTy = Type::getX86_AMXTy(Context);
1759e8d8bef9SDimitry Andric       break;
1760*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_TOKEN:     // TOKEN
1761*0b57cec5SDimitry Andric       ResultTy = Type::getTokenTy(Context);
1762*0b57cec5SDimitry Andric       break;
1763*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1764e8d8bef9SDimitry Andric       if (Record.empty())
1765*0b57cec5SDimitry Andric         return error("Invalid record");
1766*0b57cec5SDimitry Andric 
1767*0b57cec5SDimitry Andric       uint64_t NumBits = Record[0];
1768*0b57cec5SDimitry Andric       if (NumBits < IntegerType::MIN_INT_BITS ||
1769*0b57cec5SDimitry Andric           NumBits > IntegerType::MAX_INT_BITS)
1770*0b57cec5SDimitry Andric         return error("Bitwidth for integer type out of range");
1771*0b57cec5SDimitry Andric       ResultTy = IntegerType::get(Context, NumBits);
1772*0b57cec5SDimitry Andric       break;
1773*0b57cec5SDimitry Andric     }
1774*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1775*0b57cec5SDimitry Andric                                     //          [pointee type, address space]
1776e8d8bef9SDimitry Andric       if (Record.empty())
1777*0b57cec5SDimitry Andric         return error("Invalid record");
1778*0b57cec5SDimitry Andric       unsigned AddressSpace = 0;
1779*0b57cec5SDimitry Andric       if (Record.size() == 2)
1780*0b57cec5SDimitry Andric         AddressSpace = Record[1];
1781*0b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[0]);
1782*0b57cec5SDimitry Andric       if (!ResultTy ||
1783*0b57cec5SDimitry Andric           !PointerType::isValidElementType(ResultTy))
1784*0b57cec5SDimitry Andric         return error("Invalid type");
1785*0b57cec5SDimitry Andric       ResultTy = PointerType::get(ResultTy, AddressSpace);
1786*0b57cec5SDimitry Andric       break;
1787*0b57cec5SDimitry Andric     }
1788fe6060f1SDimitry Andric     case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
1789fe6060f1SDimitry Andric       if (Record.size() != 1)
1790fe6060f1SDimitry Andric         return error("Invalid record");
1791349cc55cSDimitry Andric       if (Context.supportsTypedPointers())
1792349cc55cSDimitry Andric         return error(
1793349cc55cSDimitry Andric             "Opaque pointers are only supported in -opaque-pointers mode");
1794fe6060f1SDimitry Andric       unsigned AddressSpace = Record[0];
1795fe6060f1SDimitry Andric       ResultTy = PointerType::get(Context, AddressSpace);
1796fe6060f1SDimitry Andric       break;
1797fe6060f1SDimitry Andric     }
1798*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_FUNCTION_OLD: {
17995ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
1800*0b57cec5SDimitry Andric       // FUNCTION: [vararg, attrid, retty, paramty x N]
1801*0b57cec5SDimitry Andric       if (Record.size() < 3)
1802*0b57cec5SDimitry Andric         return error("Invalid record");
1803*0b57cec5SDimitry Andric       SmallVector<Type*, 8> ArgTys;
1804*0b57cec5SDimitry Andric       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1805*0b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
1806*0b57cec5SDimitry Andric           ArgTys.push_back(T);
1807*0b57cec5SDimitry Andric         else
1808*0b57cec5SDimitry Andric           break;
1809*0b57cec5SDimitry Andric       }
1810*0b57cec5SDimitry Andric 
1811*0b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[2]);
1812*0b57cec5SDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-3)
1813*0b57cec5SDimitry Andric         return error("Invalid type");
1814*0b57cec5SDimitry Andric 
1815*0b57cec5SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1816*0b57cec5SDimitry Andric       break;
1817*0b57cec5SDimitry Andric     }
1818*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_FUNCTION: {
1819*0b57cec5SDimitry Andric       // FUNCTION: [vararg, retty, paramty x N]
1820*0b57cec5SDimitry Andric       if (Record.size() < 2)
1821*0b57cec5SDimitry Andric         return error("Invalid record");
1822*0b57cec5SDimitry Andric       SmallVector<Type*, 8> ArgTys;
1823*0b57cec5SDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1824*0b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i])) {
1825*0b57cec5SDimitry Andric           if (!FunctionType::isValidArgumentType(T))
1826*0b57cec5SDimitry Andric             return error("Invalid function argument type");
1827*0b57cec5SDimitry Andric           ArgTys.push_back(T);
1828*0b57cec5SDimitry Andric         }
1829*0b57cec5SDimitry Andric         else
1830*0b57cec5SDimitry Andric           break;
1831*0b57cec5SDimitry Andric       }
1832*0b57cec5SDimitry Andric 
1833*0b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
1834*0b57cec5SDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-2)
1835*0b57cec5SDimitry Andric         return error("Invalid type");
1836*0b57cec5SDimitry Andric 
1837*0b57cec5SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1838*0b57cec5SDimitry Andric       break;
1839*0b57cec5SDimitry Andric     }
1840*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1841e8d8bef9SDimitry Andric       if (Record.empty())
1842*0b57cec5SDimitry Andric         return error("Invalid record");
1843*0b57cec5SDimitry Andric       SmallVector<Type*, 8> EltTys;
1844*0b57cec5SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1845*0b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
1846*0b57cec5SDimitry Andric           EltTys.push_back(T);
1847*0b57cec5SDimitry Andric         else
1848*0b57cec5SDimitry Andric           break;
1849*0b57cec5SDimitry Andric       }
1850*0b57cec5SDimitry Andric       if (EltTys.size() != Record.size()-1)
1851*0b57cec5SDimitry Andric         return error("Invalid type");
1852*0b57cec5SDimitry Andric       ResultTy = StructType::get(Context, EltTys, Record[0]);
1853*0b57cec5SDimitry Andric       break;
1854*0b57cec5SDimitry Andric     }
1855*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
1856*0b57cec5SDimitry Andric       if (convertToString(Record, 0, TypeName))
1857*0b57cec5SDimitry Andric         return error("Invalid record");
1858*0b57cec5SDimitry Andric       continue;
1859*0b57cec5SDimitry Andric 
1860*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1861e8d8bef9SDimitry Andric       if (Record.empty())
1862*0b57cec5SDimitry Andric         return error("Invalid record");
1863*0b57cec5SDimitry Andric 
1864*0b57cec5SDimitry Andric       if (NumRecords >= TypeList.size())
1865*0b57cec5SDimitry Andric         return error("Invalid TYPE table");
1866*0b57cec5SDimitry Andric 
1867*0b57cec5SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
1868*0b57cec5SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1869*0b57cec5SDimitry Andric       if (Res) {
1870*0b57cec5SDimitry Andric         Res->setName(TypeName);
1871*0b57cec5SDimitry Andric         TypeList[NumRecords] = nullptr;
1872*0b57cec5SDimitry Andric       } else  // Otherwise, create a new struct.
1873*0b57cec5SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
1874*0b57cec5SDimitry Andric       TypeName.clear();
1875*0b57cec5SDimitry Andric 
1876*0b57cec5SDimitry Andric       SmallVector<Type*, 8> EltTys;
1877*0b57cec5SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1878*0b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
1879*0b57cec5SDimitry Andric           EltTys.push_back(T);
1880*0b57cec5SDimitry Andric         else
1881*0b57cec5SDimitry Andric           break;
1882*0b57cec5SDimitry Andric       }
1883*0b57cec5SDimitry Andric       if (EltTys.size() != Record.size()-1)
1884*0b57cec5SDimitry Andric         return error("Invalid record");
1885*0b57cec5SDimitry Andric       Res->setBody(EltTys, Record[0]);
1886*0b57cec5SDimitry Andric       ResultTy = Res;
1887*0b57cec5SDimitry Andric       break;
1888*0b57cec5SDimitry Andric     }
1889*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
1890*0b57cec5SDimitry Andric       if (Record.size() != 1)
1891*0b57cec5SDimitry Andric         return error("Invalid record");
1892*0b57cec5SDimitry Andric 
1893*0b57cec5SDimitry Andric       if (NumRecords >= TypeList.size())
1894*0b57cec5SDimitry Andric         return error("Invalid TYPE table");
1895*0b57cec5SDimitry Andric 
1896*0b57cec5SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
1897*0b57cec5SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1898*0b57cec5SDimitry Andric       if (Res) {
1899*0b57cec5SDimitry Andric         Res->setName(TypeName);
1900*0b57cec5SDimitry Andric         TypeList[NumRecords] = nullptr;
1901*0b57cec5SDimitry Andric       } else  // Otherwise, create a new struct with no body.
1902*0b57cec5SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
1903*0b57cec5SDimitry Andric       TypeName.clear();
1904*0b57cec5SDimitry Andric       ResultTy = Res;
1905*0b57cec5SDimitry Andric       break;
1906*0b57cec5SDimitry Andric     }
1907*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1908*0b57cec5SDimitry Andric       if (Record.size() < 2)
1909*0b57cec5SDimitry Andric         return error("Invalid record");
1910*0b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
1911*0b57cec5SDimitry Andric       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1912*0b57cec5SDimitry Andric         return error("Invalid type");
1913*0b57cec5SDimitry Andric       ResultTy = ArrayType::get(ResultTy, Record[0]);
1914*0b57cec5SDimitry Andric       break;
1915*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty] or
1916*0b57cec5SDimitry Andric                                     //         [numelts, eltty, scalable]
1917*0b57cec5SDimitry Andric       if (Record.size() < 2)
1918*0b57cec5SDimitry Andric         return error("Invalid record");
1919*0b57cec5SDimitry Andric       if (Record[0] == 0)
1920*0b57cec5SDimitry Andric         return error("Invalid vector length");
1921*0b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
1922349cc55cSDimitry Andric       if (!ResultTy || !VectorType::isValidElementType(ResultTy))
1923*0b57cec5SDimitry Andric         return error("Invalid type");
1924*0b57cec5SDimitry Andric       bool Scalable = Record.size() > 2 ? Record[2] : false;
1925*0b57cec5SDimitry Andric       ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
1926*0b57cec5SDimitry Andric       break;
1927*0b57cec5SDimitry Andric     }
1928*0b57cec5SDimitry Andric 
1929*0b57cec5SDimitry Andric     if (NumRecords >= TypeList.size())
1930*0b57cec5SDimitry Andric       return error("Invalid TYPE table");
1931*0b57cec5SDimitry Andric     if (TypeList[NumRecords])
1932*0b57cec5SDimitry Andric       return error(
1933*0b57cec5SDimitry Andric           "Invalid TYPE table: Only named structs can be forward referenced");
1934*0b57cec5SDimitry Andric     assert(ResultTy && "Didn't read a type?");
1935*0b57cec5SDimitry Andric     TypeList[NumRecords++] = ResultTy;
1936*0b57cec5SDimitry Andric   }
1937*0b57cec5SDimitry Andric }
1938*0b57cec5SDimitry Andric 
1939*0b57cec5SDimitry Andric Error BitcodeReader::parseOperandBundleTags() {
1940*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1941*0b57cec5SDimitry Andric     return Err;
1942*0b57cec5SDimitry Andric 
1943*0b57cec5SDimitry Andric   if (!BundleTags.empty())
1944*0b57cec5SDimitry Andric     return error("Invalid multiple blocks");
1945*0b57cec5SDimitry Andric 
1946*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
1947*0b57cec5SDimitry Andric 
1948*0b57cec5SDimitry Andric   while (true) {
1949*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1950*0b57cec5SDimitry Andric     if (!MaybeEntry)
1951*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
1952*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
1953*0b57cec5SDimitry Andric 
1954*0b57cec5SDimitry Andric     switch (Entry.Kind) {
1955*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1956*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
1957*0b57cec5SDimitry Andric       return error("Malformed block");
1958*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
1959*0b57cec5SDimitry Andric       return Error::success();
1960*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
1961*0b57cec5SDimitry Andric       // The interesting case.
1962*0b57cec5SDimitry Andric       break;
1963*0b57cec5SDimitry Andric     }
1964*0b57cec5SDimitry Andric 
1965*0b57cec5SDimitry Andric     // Tags are implicitly mapped to integers by their order.
1966*0b57cec5SDimitry Andric 
1967*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1968*0b57cec5SDimitry Andric     if (!MaybeRecord)
1969*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
1970*0b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
1971*0b57cec5SDimitry Andric       return error("Invalid record");
1972*0b57cec5SDimitry Andric 
1973*0b57cec5SDimitry Andric     // OPERAND_BUNDLE_TAG: [strchr x N]
1974*0b57cec5SDimitry Andric     BundleTags.emplace_back();
1975*0b57cec5SDimitry Andric     if (convertToString(Record, 0, BundleTags.back()))
1976*0b57cec5SDimitry Andric       return error("Invalid record");
1977*0b57cec5SDimitry Andric     Record.clear();
1978*0b57cec5SDimitry Andric   }
1979*0b57cec5SDimitry Andric }
1980*0b57cec5SDimitry Andric 
1981*0b57cec5SDimitry Andric Error BitcodeReader::parseSyncScopeNames() {
1982*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
1983*0b57cec5SDimitry Andric     return Err;
1984*0b57cec5SDimitry Andric 
1985*0b57cec5SDimitry Andric   if (!SSIDs.empty())
1986*0b57cec5SDimitry Andric     return error("Invalid multiple synchronization scope names blocks");
1987*0b57cec5SDimitry Andric 
1988*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
1989*0b57cec5SDimitry Andric   while (true) {
1990*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1991*0b57cec5SDimitry Andric     if (!MaybeEntry)
1992*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
1993*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
1994*0b57cec5SDimitry Andric 
1995*0b57cec5SDimitry Andric     switch (Entry.Kind) {
1996*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1997*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
1998*0b57cec5SDimitry Andric       return error("Malformed block");
1999*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2000*0b57cec5SDimitry Andric       if (SSIDs.empty())
2001*0b57cec5SDimitry Andric         return error("Invalid empty synchronization scope names block");
2002*0b57cec5SDimitry Andric       return Error::success();
2003*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
2004*0b57cec5SDimitry Andric       // The interesting case.
2005*0b57cec5SDimitry Andric       break;
2006*0b57cec5SDimitry Andric     }
2007*0b57cec5SDimitry Andric 
2008*0b57cec5SDimitry Andric     // Synchronization scope names are implicitly mapped to synchronization
2009*0b57cec5SDimitry Andric     // scope IDs by their order.
2010*0b57cec5SDimitry Andric 
2011*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2012*0b57cec5SDimitry Andric     if (!MaybeRecord)
2013*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
2014*0b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2015*0b57cec5SDimitry Andric       return error("Invalid record");
2016*0b57cec5SDimitry Andric 
2017*0b57cec5SDimitry Andric     SmallString<16> SSN;
2018*0b57cec5SDimitry Andric     if (convertToString(Record, 0, SSN))
2019*0b57cec5SDimitry Andric       return error("Invalid record");
2020*0b57cec5SDimitry Andric 
2021*0b57cec5SDimitry Andric     SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2022*0b57cec5SDimitry Andric     Record.clear();
2023*0b57cec5SDimitry Andric   }
2024*0b57cec5SDimitry Andric }
2025*0b57cec5SDimitry Andric 
2026*0b57cec5SDimitry Andric /// Associate a value with its name from the given index in the provided record.
2027*0b57cec5SDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2028*0b57cec5SDimitry Andric                                              unsigned NameIndex, Triple &TT) {
2029*0b57cec5SDimitry Andric   SmallString<128> ValueName;
2030*0b57cec5SDimitry Andric   if (convertToString(Record, NameIndex, ValueName))
2031*0b57cec5SDimitry Andric     return error("Invalid record");
2032*0b57cec5SDimitry Andric   unsigned ValueID = Record[0];
2033*0b57cec5SDimitry Andric   if (ValueID >= ValueList.size() || !ValueList[ValueID])
2034*0b57cec5SDimitry Andric     return error("Invalid record");
2035*0b57cec5SDimitry Andric   Value *V = ValueList[ValueID];
2036*0b57cec5SDimitry Andric 
2037*0b57cec5SDimitry Andric   StringRef NameStr(ValueName.data(), ValueName.size());
2038*0b57cec5SDimitry Andric   if (NameStr.find_first_of(0) != StringRef::npos)
2039*0b57cec5SDimitry Andric     return error("Invalid value name");
2040*0b57cec5SDimitry Andric   V->setName(NameStr);
2041*0b57cec5SDimitry Andric   auto *GO = dyn_cast<GlobalObject>(V);
20420eae32dcSDimitry Andric   if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
2043*0b57cec5SDimitry Andric     GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2044*0b57cec5SDimitry Andric   return V;
2045*0b57cec5SDimitry Andric }
2046*0b57cec5SDimitry Andric 
2047*0b57cec5SDimitry Andric /// Helper to note and return the current location, and jump to the given
2048*0b57cec5SDimitry Andric /// offset.
2049*0b57cec5SDimitry Andric static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
2050*0b57cec5SDimitry Andric                                                  BitstreamCursor &Stream) {
2051*0b57cec5SDimitry Andric   // Save the current parsing location so we can jump back at the end
2052*0b57cec5SDimitry Andric   // of the VST read.
2053*0b57cec5SDimitry Andric   uint64_t CurrentBit = Stream.GetCurrentBitNo();
2054*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2055*0b57cec5SDimitry Andric     return std::move(JumpFailed);
2056*0b57cec5SDimitry Andric   Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2057*0b57cec5SDimitry Andric   if (!MaybeEntry)
2058*0b57cec5SDimitry Andric     return MaybeEntry.takeError();
2059*0b57cec5SDimitry Andric   assert(MaybeEntry.get().Kind == BitstreamEntry::SubBlock);
2060*0b57cec5SDimitry Andric   assert(MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID);
2061*0b57cec5SDimitry Andric   return CurrentBit;
2062*0b57cec5SDimitry Andric }
2063*0b57cec5SDimitry Andric 
2064*0b57cec5SDimitry Andric void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2065*0b57cec5SDimitry Andric                                             Function *F,
2066*0b57cec5SDimitry Andric                                             ArrayRef<uint64_t> Record) {
2067*0b57cec5SDimitry Andric   // Note that we subtract 1 here because the offset is relative to one word
2068*0b57cec5SDimitry Andric   // before the start of the identification or module block, which was
2069*0b57cec5SDimitry Andric   // historically always the start of the regular bitcode header.
2070*0b57cec5SDimitry Andric   uint64_t FuncWordOffset = Record[1] - 1;
2071*0b57cec5SDimitry Andric   uint64_t FuncBitOffset = FuncWordOffset * 32;
2072*0b57cec5SDimitry Andric   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2073*0b57cec5SDimitry Andric   // Set the LastFunctionBlockBit to point to the last function block.
2074*0b57cec5SDimitry Andric   // Later when parsing is resumed after function materialization,
2075*0b57cec5SDimitry Andric   // we can simply skip that last function block.
2076*0b57cec5SDimitry Andric   if (FuncBitOffset > LastFunctionBlockBit)
2077*0b57cec5SDimitry Andric     LastFunctionBlockBit = FuncBitOffset;
2078*0b57cec5SDimitry Andric }
2079*0b57cec5SDimitry Andric 
2080*0b57cec5SDimitry Andric /// Read a new-style GlobalValue symbol table.
2081*0b57cec5SDimitry Andric Error BitcodeReader::parseGlobalValueSymbolTable() {
2082*0b57cec5SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
2083*0b57cec5SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2084*0b57cec5SDimitry Andric 
2085*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2086*0b57cec5SDimitry Andric     return Err;
2087*0b57cec5SDimitry Andric 
2088*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2089*0b57cec5SDimitry Andric   while (true) {
2090*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2091*0b57cec5SDimitry Andric     if (!MaybeEntry)
2092*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
2093*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2094*0b57cec5SDimitry Andric 
2095*0b57cec5SDimitry Andric     switch (Entry.Kind) {
2096*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
2097*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
2098*0b57cec5SDimitry Andric       return error("Malformed block");
2099*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2100*0b57cec5SDimitry Andric       return Error::success();
2101*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
2102*0b57cec5SDimitry Andric       break;
2103*0b57cec5SDimitry Andric     }
2104*0b57cec5SDimitry Andric 
2105*0b57cec5SDimitry Andric     Record.clear();
2106*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2107*0b57cec5SDimitry Andric     if (!MaybeRecord)
2108*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
2109*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
2110*0b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: // [valueid, offset]
2111*0b57cec5SDimitry Andric       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2112*0b57cec5SDimitry Andric                               cast<Function>(ValueList[Record[0]]), Record);
2113*0b57cec5SDimitry Andric       break;
2114*0b57cec5SDimitry Andric     }
2115*0b57cec5SDimitry Andric   }
2116*0b57cec5SDimitry Andric }
2117*0b57cec5SDimitry Andric 
2118*0b57cec5SDimitry Andric /// Parse the value symbol table at either the current parsing location or
2119*0b57cec5SDimitry Andric /// at the given bit offset if provided.
2120*0b57cec5SDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
2121*0b57cec5SDimitry Andric   uint64_t CurrentBit;
2122*0b57cec5SDimitry Andric   // Pass in the Offset to distinguish between calling for the module-level
2123*0b57cec5SDimitry Andric   // VST (where we want to jump to the VST offset) and the function-level
2124*0b57cec5SDimitry Andric   // VST (where we don't).
2125*0b57cec5SDimitry Andric   if (Offset > 0) {
2126*0b57cec5SDimitry Andric     Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2127*0b57cec5SDimitry Andric     if (!MaybeCurrentBit)
2128*0b57cec5SDimitry Andric       return MaybeCurrentBit.takeError();
2129*0b57cec5SDimitry Andric     CurrentBit = MaybeCurrentBit.get();
2130*0b57cec5SDimitry Andric     // If this module uses a string table, read this as a module-level VST.
2131*0b57cec5SDimitry Andric     if (UseStrtab) {
2132*0b57cec5SDimitry Andric       if (Error Err = parseGlobalValueSymbolTable())
2133*0b57cec5SDimitry Andric         return Err;
2134*0b57cec5SDimitry Andric       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2135*0b57cec5SDimitry Andric         return JumpFailed;
2136*0b57cec5SDimitry Andric       return Error::success();
2137*0b57cec5SDimitry Andric     }
2138*0b57cec5SDimitry Andric     // Otherwise, the VST will be in a similar format to a function-level VST,
2139*0b57cec5SDimitry Andric     // and will contain symbol names.
2140*0b57cec5SDimitry Andric   }
2141*0b57cec5SDimitry Andric 
2142*0b57cec5SDimitry Andric   // Compute the delta between the bitcode indices in the VST (the word offset
2143*0b57cec5SDimitry Andric   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2144*0b57cec5SDimitry Andric   // expected by the lazy reader. The reader's EnterSubBlock expects to have
2145*0b57cec5SDimitry Andric   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2146*0b57cec5SDimitry Andric   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2147*0b57cec5SDimitry Andric   // just before entering the VST subblock because: 1) the EnterSubBlock
2148*0b57cec5SDimitry Andric   // changes the AbbrevID width; 2) the VST block is nested within the same
2149*0b57cec5SDimitry Andric   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2150*0b57cec5SDimitry Andric   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2151*0b57cec5SDimitry Andric   // jump to the FUNCTION_BLOCK using this offset later, we don't want
2152*0b57cec5SDimitry Andric   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2153*0b57cec5SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
2154*0b57cec5SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2155*0b57cec5SDimitry Andric 
2156*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2157*0b57cec5SDimitry Andric     return Err;
2158*0b57cec5SDimitry Andric 
2159*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2160*0b57cec5SDimitry Andric 
2161*0b57cec5SDimitry Andric   Triple TT(TheModule->getTargetTriple());
2162*0b57cec5SDimitry Andric 
2163*0b57cec5SDimitry Andric   // Read all the records for this value table.
2164*0b57cec5SDimitry Andric   SmallString<128> ValueName;
2165*0b57cec5SDimitry Andric 
2166*0b57cec5SDimitry Andric   while (true) {
2167*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2168*0b57cec5SDimitry Andric     if (!MaybeEntry)
2169*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
2170*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2171*0b57cec5SDimitry Andric 
2172*0b57cec5SDimitry Andric     switch (Entry.Kind) {
2173*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2174*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
2175*0b57cec5SDimitry Andric       return error("Malformed block");
2176*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2177*0b57cec5SDimitry Andric       if (Offset > 0)
2178*0b57cec5SDimitry Andric         if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2179*0b57cec5SDimitry Andric           return JumpFailed;
2180*0b57cec5SDimitry Andric       return Error::success();
2181*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
2182*0b57cec5SDimitry Andric       // The interesting case.
2183*0b57cec5SDimitry Andric       break;
2184*0b57cec5SDimitry Andric     }
2185*0b57cec5SDimitry Andric 
2186*0b57cec5SDimitry Andric     // Read a record.
2187*0b57cec5SDimitry Andric     Record.clear();
2188*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2189*0b57cec5SDimitry Andric     if (!MaybeRecord)
2190*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
2191*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
2192*0b57cec5SDimitry Andric     default:  // Default behavior: unknown type.
2193*0b57cec5SDimitry Andric       break;
2194*0b57cec5SDimitry Andric     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
2195*0b57cec5SDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2196*0b57cec5SDimitry Andric       if (Error Err = ValOrErr.takeError())
2197*0b57cec5SDimitry Andric         return Err;
2198*0b57cec5SDimitry Andric       ValOrErr.get();
2199*0b57cec5SDimitry Andric       break;
2200*0b57cec5SDimitry Andric     }
2201*0b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
2202*0b57cec5SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2203*0b57cec5SDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2204*0b57cec5SDimitry Andric       if (Error Err = ValOrErr.takeError())
2205*0b57cec5SDimitry Andric         return Err;
2206*0b57cec5SDimitry Andric       Value *V = ValOrErr.get();
2207*0b57cec5SDimitry Andric 
2208*0b57cec5SDimitry Andric       // Ignore function offsets emitted for aliases of functions in older
2209*0b57cec5SDimitry Andric       // versions of LLVM.
2210*0b57cec5SDimitry Andric       if (auto *F = dyn_cast<Function>(V))
2211*0b57cec5SDimitry Andric         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2212*0b57cec5SDimitry Andric       break;
2213*0b57cec5SDimitry Andric     }
2214*0b57cec5SDimitry Andric     case bitc::VST_CODE_BBENTRY: {
2215*0b57cec5SDimitry Andric       if (convertToString(Record, 1, ValueName))
2216*0b57cec5SDimitry Andric         return error("Invalid record");
2217*0b57cec5SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[0]);
2218*0b57cec5SDimitry Andric       if (!BB)
2219*0b57cec5SDimitry Andric         return error("Invalid record");
2220*0b57cec5SDimitry Andric 
2221*0b57cec5SDimitry Andric       BB->setName(StringRef(ValueName.data(), ValueName.size()));
2222*0b57cec5SDimitry Andric       ValueName.clear();
2223*0b57cec5SDimitry Andric       break;
2224*0b57cec5SDimitry Andric     }
2225*0b57cec5SDimitry Andric     }
2226*0b57cec5SDimitry Andric   }
2227*0b57cec5SDimitry Andric }
2228*0b57cec5SDimitry Andric 
2229*0b57cec5SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2230*0b57cec5SDimitry Andric /// encoding.
2231*0b57cec5SDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2232*0b57cec5SDimitry Andric   if ((V & 1) == 0)
2233*0b57cec5SDimitry Andric     return V >> 1;
2234*0b57cec5SDimitry Andric   if (V != 1)
2235*0b57cec5SDimitry Andric     return -(V >> 1);
2236*0b57cec5SDimitry Andric   // There is no such thing as -0 with integers.  "-0" really means MININT.
2237*0b57cec5SDimitry Andric   return 1ULL << 63;
2238*0b57cec5SDimitry Andric }
2239*0b57cec5SDimitry Andric 
2240*0b57cec5SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can.
2241*0b57cec5SDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2242*0b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2243349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
2244349cc55cSDimitry Andric   std::vector<FunctionOperandInfo> FunctionOperandWorklist;
2245*0b57cec5SDimitry Andric 
2246*0b57cec5SDimitry Andric   GlobalInitWorklist.swap(GlobalInits);
2247*0b57cec5SDimitry Andric   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2248349cc55cSDimitry Andric   FunctionOperandWorklist.swap(FunctionOperands);
2249*0b57cec5SDimitry Andric 
2250*0b57cec5SDimitry Andric   while (!GlobalInitWorklist.empty()) {
2251*0b57cec5SDimitry Andric     unsigned ValID = GlobalInitWorklist.back().second;
2252*0b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
2253*0b57cec5SDimitry Andric       // Not ready to resolve this yet, it requires something later in the file.
2254*0b57cec5SDimitry Andric       GlobalInits.push_back(GlobalInitWorklist.back());
2255*0b57cec5SDimitry Andric     } else {
2256*0b57cec5SDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2257*0b57cec5SDimitry Andric         GlobalInitWorklist.back().first->setInitializer(C);
2258*0b57cec5SDimitry Andric       else
2259*0b57cec5SDimitry Andric         return error("Expected a constant");
2260*0b57cec5SDimitry Andric     }
2261*0b57cec5SDimitry Andric     GlobalInitWorklist.pop_back();
2262*0b57cec5SDimitry Andric   }
2263*0b57cec5SDimitry Andric 
2264*0b57cec5SDimitry Andric   while (!IndirectSymbolInitWorklist.empty()) {
2265*0b57cec5SDimitry Andric     unsigned ValID = IndirectSymbolInitWorklist.back().second;
2266*0b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
2267*0b57cec5SDimitry Andric       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2268*0b57cec5SDimitry Andric     } else {
2269*0b57cec5SDimitry Andric       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2270*0b57cec5SDimitry Andric       if (!C)
2271*0b57cec5SDimitry Andric         return error("Expected a constant");
2272349cc55cSDimitry Andric       GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
2273349cc55cSDimitry Andric       if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
2274349cc55cSDimitry Andric         if (C->getType() != GV->getType())
2275*0b57cec5SDimitry Andric           return error("Alias and aliasee types don't match");
2276349cc55cSDimitry Andric         GA->setAliasee(C);
2277349cc55cSDimitry Andric       } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
2278349cc55cSDimitry Andric         Type *ResolverFTy =
2279349cc55cSDimitry Andric             GlobalIFunc::getResolverFunctionType(GI->getValueType());
2280349cc55cSDimitry Andric         // Transparently fix up the type for compatiblity with older bitcode
2281349cc55cSDimitry Andric         GI->setResolver(
2282349cc55cSDimitry Andric             ConstantExpr::getBitCast(C, ResolverFTy->getPointerTo()));
2283349cc55cSDimitry Andric       } else {
2284349cc55cSDimitry Andric         return error("Expected an alias or an ifunc");
2285349cc55cSDimitry Andric       }
2286*0b57cec5SDimitry Andric     }
2287*0b57cec5SDimitry Andric     IndirectSymbolInitWorklist.pop_back();
2288*0b57cec5SDimitry Andric   }
2289*0b57cec5SDimitry Andric 
2290349cc55cSDimitry Andric   while (!FunctionOperandWorklist.empty()) {
2291349cc55cSDimitry Andric     FunctionOperandInfo &Info = FunctionOperandWorklist.back();
2292349cc55cSDimitry Andric     if (Info.PersonalityFn) {
2293349cc55cSDimitry Andric       unsigned ValID = Info.PersonalityFn - 1;
2294349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
2295*0b57cec5SDimitry Andric         if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2296349cc55cSDimitry Andric           Info.F->setPersonalityFn(C);
2297*0b57cec5SDimitry Andric         else
2298*0b57cec5SDimitry Andric           return error("Expected a constant");
2299349cc55cSDimitry Andric         Info.PersonalityFn = 0;
2300*0b57cec5SDimitry Andric       }
2301*0b57cec5SDimitry Andric     }
2302349cc55cSDimitry Andric     if (Info.Prefix) {
2303349cc55cSDimitry Andric       unsigned ValID = Info.Prefix - 1;
2304349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
2305*0b57cec5SDimitry Andric         if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2306349cc55cSDimitry Andric           Info.F->setPrefixData(C);
2307*0b57cec5SDimitry Andric         else
2308*0b57cec5SDimitry Andric           return error("Expected a constant");
2309349cc55cSDimitry Andric         Info.Prefix = 0;
2310*0b57cec5SDimitry Andric       }
2311*0b57cec5SDimitry Andric     }
2312349cc55cSDimitry Andric     if (Info.Prologue) {
2313349cc55cSDimitry Andric       unsigned ValID = Info.Prologue - 1;
2314349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
2315*0b57cec5SDimitry Andric         if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2316349cc55cSDimitry Andric           Info.F->setPrologueData(C);
2317*0b57cec5SDimitry Andric         else
2318*0b57cec5SDimitry Andric           return error("Expected a constant");
2319349cc55cSDimitry Andric         Info.Prologue = 0;
2320*0b57cec5SDimitry Andric       }
2321349cc55cSDimitry Andric     }
2322349cc55cSDimitry Andric     if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
2323349cc55cSDimitry Andric       FunctionOperands.push_back(Info);
2324349cc55cSDimitry Andric     FunctionOperandWorklist.pop_back();
2325*0b57cec5SDimitry Andric   }
2326*0b57cec5SDimitry Andric 
2327*0b57cec5SDimitry Andric   return Error::success();
2328*0b57cec5SDimitry Andric }
2329*0b57cec5SDimitry Andric 
23305ffd83dbSDimitry Andric APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2331*0b57cec5SDimitry Andric   SmallVector<uint64_t, 8> Words(Vals.size());
2332*0b57cec5SDimitry Andric   transform(Vals, Words.begin(),
2333*0b57cec5SDimitry Andric                  BitcodeReader::decodeSignRotatedValue);
2334*0b57cec5SDimitry Andric 
2335*0b57cec5SDimitry Andric   return APInt(TypeBits, Words);
2336*0b57cec5SDimitry Andric }
2337*0b57cec5SDimitry Andric 
2338*0b57cec5SDimitry Andric Error BitcodeReader::parseConstants() {
2339*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2340*0b57cec5SDimitry Andric     return Err;
2341*0b57cec5SDimitry Andric 
2342*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2343*0b57cec5SDimitry Andric 
2344*0b57cec5SDimitry Andric   // Read all the records for this value table.
2345*0b57cec5SDimitry Andric   Type *CurTy = Type::getInt32Ty(Context);
2346*0b57cec5SDimitry Andric   unsigned NextCstNo = ValueList.size();
2347*0b57cec5SDimitry Andric 
23485ffd83dbSDimitry Andric   struct DelayedShufTy {
23495ffd83dbSDimitry Andric     VectorType *OpTy;
23505ffd83dbSDimitry Andric     VectorType *RTy;
23515ffd83dbSDimitry Andric     uint64_t Op0Idx;
23525ffd83dbSDimitry Andric     uint64_t Op1Idx;
23535ffd83dbSDimitry Andric     uint64_t Op2Idx;
23545ffd83dbSDimitry Andric     unsigned CstNo;
23555ffd83dbSDimitry Andric   };
23565ffd83dbSDimitry Andric   std::vector<DelayedShufTy> DelayedShuffles;
2357349cc55cSDimitry Andric   struct DelayedSelTy {
2358349cc55cSDimitry Andric     Type *OpTy;
2359349cc55cSDimitry Andric     uint64_t Op0Idx;
2360349cc55cSDimitry Andric     uint64_t Op1Idx;
2361349cc55cSDimitry Andric     uint64_t Op2Idx;
2362349cc55cSDimitry Andric     unsigned CstNo;
2363349cc55cSDimitry Andric   };
2364349cc55cSDimitry Andric   std::vector<DelayedSelTy> DelayedSelectors;
2365349cc55cSDimitry Andric 
2366*0b57cec5SDimitry Andric   while (true) {
2367*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2368*0b57cec5SDimitry Andric     if (!MaybeEntry)
2369*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
2370*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2371*0b57cec5SDimitry Andric 
2372*0b57cec5SDimitry Andric     switch (Entry.Kind) {
2373*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2374*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
2375*0b57cec5SDimitry Andric       return error("Malformed block");
2376*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
23775ffd83dbSDimitry Andric       // Once all the constants have been read, go through and resolve forward
23785ffd83dbSDimitry Andric       // references.
23795ffd83dbSDimitry Andric       //
23805ffd83dbSDimitry Andric       // We have to treat shuffles specially because they don't have three
23815ffd83dbSDimitry Andric       // operands anymore.  We need to convert the shuffle mask into an array,
23825ffd83dbSDimitry Andric       // and we can't convert a forward reference.
23835ffd83dbSDimitry Andric       for (auto &DelayedShuffle : DelayedShuffles) {
23845ffd83dbSDimitry Andric         VectorType *OpTy = DelayedShuffle.OpTy;
23855ffd83dbSDimitry Andric         VectorType *RTy = DelayedShuffle.RTy;
23865ffd83dbSDimitry Andric         uint64_t Op0Idx = DelayedShuffle.Op0Idx;
23875ffd83dbSDimitry Andric         uint64_t Op1Idx = DelayedShuffle.Op1Idx;
23885ffd83dbSDimitry Andric         uint64_t Op2Idx = DelayedShuffle.Op2Idx;
23895ffd83dbSDimitry Andric         uint64_t CstNo = DelayedShuffle.CstNo;
23905ffd83dbSDimitry Andric         Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, OpTy);
23915ffd83dbSDimitry Andric         Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy);
23925ffd83dbSDimitry Andric         Type *ShufTy =
23935ffd83dbSDimitry Andric             VectorType::get(Type::getInt32Ty(Context), RTy->getElementCount());
23945ffd83dbSDimitry Andric         Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, ShufTy);
23955ffd83dbSDimitry Andric         if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
23965ffd83dbSDimitry Andric           return error("Invalid shufflevector operands");
23975ffd83dbSDimitry Andric         SmallVector<int, 16> Mask;
23985ffd83dbSDimitry Andric         ShuffleVectorInst::getShuffleMask(Op2, Mask);
23995ffd83dbSDimitry Andric         Value *V = ConstantExpr::getShuffleVector(Op0, Op1, Mask);
2400fe6060f1SDimitry Andric         ValueList.assignValue(V, CstNo);
24015ffd83dbSDimitry Andric       }
2402349cc55cSDimitry Andric       for (auto &DelayedSelector : DelayedSelectors) {
2403349cc55cSDimitry Andric         Type *OpTy = DelayedSelector.OpTy;
2404349cc55cSDimitry Andric         Type *SelectorTy = Type::getInt1Ty(Context);
2405349cc55cSDimitry Andric         uint64_t Op0Idx = DelayedSelector.Op0Idx;
2406349cc55cSDimitry Andric         uint64_t Op1Idx = DelayedSelector.Op1Idx;
2407349cc55cSDimitry Andric         uint64_t Op2Idx = DelayedSelector.Op2Idx;
2408349cc55cSDimitry Andric         uint64_t CstNo = DelayedSelector.CstNo;
2409349cc55cSDimitry Andric         Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy);
2410349cc55cSDimitry Andric         Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, OpTy);
2411349cc55cSDimitry Andric         // The selector might be an i1 or an <n x i1>
2412349cc55cSDimitry Andric         // Get the type from the ValueList before getting a forward ref.
2413349cc55cSDimitry Andric         if (VectorType *VTy = dyn_cast<VectorType>(OpTy)) {
2414349cc55cSDimitry Andric           Value *V = ValueList[Op0Idx];
2415349cc55cSDimitry Andric           assert(V);
2416349cc55cSDimitry Andric           if (SelectorTy != V->getType())
2417349cc55cSDimitry Andric             SelectorTy = VectorType::get(SelectorTy, VTy->getElementCount());
2418349cc55cSDimitry Andric         }
2419349cc55cSDimitry Andric         Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, SelectorTy);
2420349cc55cSDimitry Andric         Value *V = ConstantExpr::getSelect(Op0, Op1, Op2);
2421349cc55cSDimitry Andric         ValueList.assignValue(V, CstNo);
2422349cc55cSDimitry Andric       }
24235ffd83dbSDimitry Andric 
2424*0b57cec5SDimitry Andric       if (NextCstNo != ValueList.size())
2425*0b57cec5SDimitry Andric         return error("Invalid constant reference");
2426*0b57cec5SDimitry Andric 
2427*0b57cec5SDimitry Andric       ValueList.resolveConstantForwardRefs();
2428*0b57cec5SDimitry Andric       return Error::success();
2429*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
2430*0b57cec5SDimitry Andric       // The interesting case.
2431*0b57cec5SDimitry Andric       break;
2432*0b57cec5SDimitry Andric     }
2433*0b57cec5SDimitry Andric 
2434*0b57cec5SDimitry Andric     // Read a record.
2435*0b57cec5SDimitry Andric     Record.clear();
2436*0b57cec5SDimitry Andric     Type *VoidType = Type::getVoidTy(Context);
2437*0b57cec5SDimitry Andric     Value *V = nullptr;
2438*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2439*0b57cec5SDimitry Andric     if (!MaybeBitCode)
2440*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
2441*0b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
2442*0b57cec5SDimitry Andric     default:  // Default behavior: unknown constant
2443*0b57cec5SDimitry Andric     case bitc::CST_CODE_UNDEF:     // UNDEF
2444*0b57cec5SDimitry Andric       V = UndefValue::get(CurTy);
2445*0b57cec5SDimitry Andric       break;
2446e8d8bef9SDimitry Andric     case bitc::CST_CODE_POISON:    // POISON
2447e8d8bef9SDimitry Andric       V = PoisonValue::get(CurTy);
2448e8d8bef9SDimitry Andric       break;
2449*0b57cec5SDimitry Andric     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2450*0b57cec5SDimitry Andric       if (Record.empty())
2451*0b57cec5SDimitry Andric         return error("Invalid record");
2452*0b57cec5SDimitry Andric       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2453*0b57cec5SDimitry Andric         return error("Invalid record");
2454*0b57cec5SDimitry Andric       if (TypeList[Record[0]] == VoidType)
2455*0b57cec5SDimitry Andric         return error("Invalid constant type");
2456fe6060f1SDimitry Andric       CurTy = TypeList[Record[0]];
2457*0b57cec5SDimitry Andric       continue;  // Skip the ValueList manipulation.
2458*0b57cec5SDimitry Andric     case bitc::CST_CODE_NULL:      // NULL
24598bcb0991SDimitry Andric       if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
24608bcb0991SDimitry Andric         return error("Invalid type for a constant null value");
2461*0b57cec5SDimitry Andric       V = Constant::getNullValue(CurTy);
2462*0b57cec5SDimitry Andric       break;
2463*0b57cec5SDimitry Andric     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2464*0b57cec5SDimitry Andric       if (!CurTy->isIntegerTy() || Record.empty())
2465*0b57cec5SDimitry Andric         return error("Invalid record");
2466*0b57cec5SDimitry Andric       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2467*0b57cec5SDimitry Andric       break;
2468*0b57cec5SDimitry Andric     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2469*0b57cec5SDimitry Andric       if (!CurTy->isIntegerTy() || Record.empty())
2470*0b57cec5SDimitry Andric         return error("Invalid record");
2471*0b57cec5SDimitry Andric 
2472*0b57cec5SDimitry Andric       APInt VInt =
2473*0b57cec5SDimitry Andric           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2474*0b57cec5SDimitry Andric       V = ConstantInt::get(Context, VInt);
2475*0b57cec5SDimitry Andric 
2476*0b57cec5SDimitry Andric       break;
2477*0b57cec5SDimitry Andric     }
2478*0b57cec5SDimitry Andric     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2479*0b57cec5SDimitry Andric       if (Record.empty())
2480*0b57cec5SDimitry Andric         return error("Invalid record");
2481*0b57cec5SDimitry Andric       if (CurTy->isHalfTy())
2482*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2483*0b57cec5SDimitry Andric                                              APInt(16, (uint16_t)Record[0])));
24845ffd83dbSDimitry Andric       else if (CurTy->isBFloatTy())
24855ffd83dbSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
24865ffd83dbSDimitry Andric                                              APInt(16, (uint32_t)Record[0])));
2487*0b57cec5SDimitry Andric       else if (CurTy->isFloatTy())
2488*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2489*0b57cec5SDimitry Andric                                              APInt(32, (uint32_t)Record[0])));
2490*0b57cec5SDimitry Andric       else if (CurTy->isDoubleTy())
2491*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2492*0b57cec5SDimitry Andric                                              APInt(64, Record[0])));
2493*0b57cec5SDimitry Andric       else if (CurTy->isX86_FP80Ty()) {
2494*0b57cec5SDimitry Andric         // Bits are not stored the same way as a normal i80 APInt, compensate.
2495*0b57cec5SDimitry Andric         uint64_t Rearrange[2];
2496*0b57cec5SDimitry Andric         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2497*0b57cec5SDimitry Andric         Rearrange[1] = Record[0] >> 48;
2498*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2499*0b57cec5SDimitry Andric                                              APInt(80, Rearrange)));
2500*0b57cec5SDimitry Andric       } else if (CurTy->isFP128Ty())
2501*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2502*0b57cec5SDimitry Andric                                              APInt(128, Record)));
2503*0b57cec5SDimitry Andric       else if (CurTy->isPPC_FP128Ty())
2504*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2505*0b57cec5SDimitry Andric                                              APInt(128, Record)));
2506*0b57cec5SDimitry Andric       else
2507*0b57cec5SDimitry Andric         V = UndefValue::get(CurTy);
2508*0b57cec5SDimitry Andric       break;
2509*0b57cec5SDimitry Andric     }
2510*0b57cec5SDimitry Andric 
2511*0b57cec5SDimitry Andric     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2512*0b57cec5SDimitry Andric       if (Record.empty())
2513*0b57cec5SDimitry Andric         return error("Invalid record");
2514*0b57cec5SDimitry Andric 
2515*0b57cec5SDimitry Andric       unsigned Size = Record.size();
2516*0b57cec5SDimitry Andric       SmallVector<Constant*, 16> Elts;
2517*0b57cec5SDimitry Andric 
2518*0b57cec5SDimitry Andric       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2519*0b57cec5SDimitry Andric         for (unsigned i = 0; i != Size; ++i)
2520*0b57cec5SDimitry Andric           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2521*0b57cec5SDimitry Andric                                                      STy->getElementType(i)));
2522*0b57cec5SDimitry Andric         V = ConstantStruct::get(STy, Elts);
2523*0b57cec5SDimitry Andric       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2524*0b57cec5SDimitry Andric         Type *EltTy = ATy->getElementType();
2525*0b57cec5SDimitry Andric         for (unsigned i = 0; i != Size; ++i)
2526*0b57cec5SDimitry Andric           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2527*0b57cec5SDimitry Andric         V = ConstantArray::get(ATy, Elts);
2528*0b57cec5SDimitry Andric       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2529*0b57cec5SDimitry Andric         Type *EltTy = VTy->getElementType();
2530*0b57cec5SDimitry Andric         for (unsigned i = 0; i != Size; ++i)
2531*0b57cec5SDimitry Andric           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2532*0b57cec5SDimitry Andric         V = ConstantVector::get(Elts);
2533*0b57cec5SDimitry Andric       } else {
2534*0b57cec5SDimitry Andric         V = UndefValue::get(CurTy);
2535*0b57cec5SDimitry Andric       }
2536*0b57cec5SDimitry Andric       break;
2537*0b57cec5SDimitry Andric     }
2538*0b57cec5SDimitry Andric     case bitc::CST_CODE_STRING:    // STRING: [values]
2539*0b57cec5SDimitry Andric     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2540*0b57cec5SDimitry Andric       if (Record.empty())
2541*0b57cec5SDimitry Andric         return error("Invalid record");
2542*0b57cec5SDimitry Andric 
2543*0b57cec5SDimitry Andric       SmallString<16> Elts(Record.begin(), Record.end());
2544*0b57cec5SDimitry Andric       V = ConstantDataArray::getString(Context, Elts,
2545*0b57cec5SDimitry Andric                                        BitCode == bitc::CST_CODE_CSTRING);
2546*0b57cec5SDimitry Andric       break;
2547*0b57cec5SDimitry Andric     }
2548*0b57cec5SDimitry Andric     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2549*0b57cec5SDimitry Andric       if (Record.empty())
2550*0b57cec5SDimitry Andric         return error("Invalid record");
2551*0b57cec5SDimitry Andric 
25525ffd83dbSDimitry Andric       Type *EltTy;
25535ffd83dbSDimitry Andric       if (auto *Array = dyn_cast<ArrayType>(CurTy))
25545ffd83dbSDimitry Andric         EltTy = Array->getElementType();
25555ffd83dbSDimitry Andric       else
25565ffd83dbSDimitry Andric         EltTy = cast<VectorType>(CurTy)->getElementType();
2557*0b57cec5SDimitry Andric       if (EltTy->isIntegerTy(8)) {
2558*0b57cec5SDimitry Andric         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2559*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
2560*0b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
2561*0b57cec5SDimitry Andric         else
2562*0b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
2563*0b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(16)) {
2564*0b57cec5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2565*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
2566*0b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
2567*0b57cec5SDimitry Andric         else
2568*0b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
2569*0b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(32)) {
2570*0b57cec5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2571*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
2572*0b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
2573*0b57cec5SDimitry Andric         else
2574*0b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
2575*0b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(64)) {
2576*0b57cec5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2577*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
2578*0b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
2579*0b57cec5SDimitry Andric         else
2580*0b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
2581*0b57cec5SDimitry Andric       } else if (EltTy->isHalfTy()) {
2582*0b57cec5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2583*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
25845ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
2585*0b57cec5SDimitry Andric         else
25865ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
25875ffd83dbSDimitry Andric       } else if (EltTy->isBFloatTy()) {
25885ffd83dbSDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
25895ffd83dbSDimitry Andric         if (isa<VectorType>(CurTy))
25905ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
25915ffd83dbSDimitry Andric         else
25925ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
2593*0b57cec5SDimitry Andric       } else if (EltTy->isFloatTy()) {
2594*0b57cec5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2595*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
25965ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
2597*0b57cec5SDimitry Andric         else
25985ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
2599*0b57cec5SDimitry Andric       } else if (EltTy->isDoubleTy()) {
2600*0b57cec5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2601*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
26025ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
2603*0b57cec5SDimitry Andric         else
26045ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
2605*0b57cec5SDimitry Andric       } else {
2606*0b57cec5SDimitry Andric         return error("Invalid type for value");
2607*0b57cec5SDimitry Andric       }
2608*0b57cec5SDimitry Andric       break;
2609*0b57cec5SDimitry Andric     }
2610*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_UNOP: {  // CE_UNOP: [opcode, opval]
2611*0b57cec5SDimitry Andric       if (Record.size() < 2)
2612*0b57cec5SDimitry Andric         return error("Invalid record");
2613*0b57cec5SDimitry Andric       int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
2614*0b57cec5SDimitry Andric       if (Opc < 0) {
2615*0b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown unop.
2616*0b57cec5SDimitry Andric       } else {
2617*0b57cec5SDimitry Andric         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2618*0b57cec5SDimitry Andric         unsigned Flags = 0;
2619*0b57cec5SDimitry Andric         V = ConstantExpr::get(Opc, LHS, Flags);
2620*0b57cec5SDimitry Andric       }
2621*0b57cec5SDimitry Andric       break;
2622*0b57cec5SDimitry Andric     }
2623*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2624*0b57cec5SDimitry Andric       if (Record.size() < 3)
2625*0b57cec5SDimitry Andric         return error("Invalid record");
2626*0b57cec5SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2627*0b57cec5SDimitry Andric       if (Opc < 0) {
2628*0b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown binop.
2629*0b57cec5SDimitry Andric       } else {
2630*0b57cec5SDimitry Andric         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2631*0b57cec5SDimitry Andric         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2632*0b57cec5SDimitry Andric         unsigned Flags = 0;
2633*0b57cec5SDimitry Andric         if (Record.size() >= 4) {
2634*0b57cec5SDimitry Andric           if (Opc == Instruction::Add ||
2635*0b57cec5SDimitry Andric               Opc == Instruction::Sub ||
2636*0b57cec5SDimitry Andric               Opc == Instruction::Mul ||
2637*0b57cec5SDimitry Andric               Opc == Instruction::Shl) {
2638*0b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2639*0b57cec5SDimitry Andric               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2640*0b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2641*0b57cec5SDimitry Andric               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2642*0b57cec5SDimitry Andric           } else if (Opc == Instruction::SDiv ||
2643*0b57cec5SDimitry Andric                      Opc == Instruction::UDiv ||
2644*0b57cec5SDimitry Andric                      Opc == Instruction::LShr ||
2645*0b57cec5SDimitry Andric                      Opc == Instruction::AShr) {
2646*0b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::PEO_EXACT))
2647*0b57cec5SDimitry Andric               Flags |= SDivOperator::IsExact;
2648*0b57cec5SDimitry Andric           }
2649*0b57cec5SDimitry Andric         }
2650*0b57cec5SDimitry Andric         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2651*0b57cec5SDimitry Andric       }
2652*0b57cec5SDimitry Andric       break;
2653*0b57cec5SDimitry Andric     }
2654*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2655*0b57cec5SDimitry Andric       if (Record.size() < 3)
2656*0b57cec5SDimitry Andric         return error("Invalid record");
2657*0b57cec5SDimitry Andric       int Opc = getDecodedCastOpcode(Record[0]);
2658*0b57cec5SDimitry Andric       if (Opc < 0) {
2659*0b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown cast.
2660*0b57cec5SDimitry Andric       } else {
2661*0b57cec5SDimitry Andric         Type *OpTy = getTypeByID(Record[1]);
2662*0b57cec5SDimitry Andric         if (!OpTy)
2663*0b57cec5SDimitry Andric           return error("Invalid record");
2664*0b57cec5SDimitry Andric         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2665*0b57cec5SDimitry Andric         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2666*0b57cec5SDimitry Andric         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2667*0b57cec5SDimitry Andric       }
2668*0b57cec5SDimitry Andric       break;
2669*0b57cec5SDimitry Andric     }
2670*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2671*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2672*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2673*0b57cec5SDimitry Andric                                                      // operands]
2674*0b57cec5SDimitry Andric       unsigned OpNum = 0;
2675*0b57cec5SDimitry Andric       Type *PointeeType = nullptr;
2676*0b57cec5SDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2677*0b57cec5SDimitry Andric           Record.size() % 2)
2678*0b57cec5SDimitry Andric         PointeeType = getTypeByID(Record[OpNum++]);
2679*0b57cec5SDimitry Andric 
2680*0b57cec5SDimitry Andric       bool InBounds = false;
2681*0b57cec5SDimitry Andric       Optional<unsigned> InRangeIndex;
2682*0b57cec5SDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2683*0b57cec5SDimitry Andric         uint64_t Op = Record[OpNum++];
2684*0b57cec5SDimitry Andric         InBounds = Op & 1;
2685*0b57cec5SDimitry Andric         InRangeIndex = Op >> 1;
2686*0b57cec5SDimitry Andric       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2687*0b57cec5SDimitry Andric         InBounds = true;
2688*0b57cec5SDimitry Andric 
2689*0b57cec5SDimitry Andric       SmallVector<Constant*, 16> Elts;
2690*0b57cec5SDimitry Andric       Type *Elt0FullTy = nullptr;
2691*0b57cec5SDimitry Andric       while (OpNum != Record.size()) {
2692*0b57cec5SDimitry Andric         if (!Elt0FullTy)
2693fe6060f1SDimitry Andric           Elt0FullTy = getTypeByID(Record[OpNum]);
2694*0b57cec5SDimitry Andric         Type *ElTy = getTypeByID(Record[OpNum++]);
2695*0b57cec5SDimitry Andric         if (!ElTy)
2696*0b57cec5SDimitry Andric           return error("Invalid record");
2697*0b57cec5SDimitry Andric         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2698*0b57cec5SDimitry Andric       }
2699*0b57cec5SDimitry Andric 
2700*0b57cec5SDimitry Andric       if (Elts.size() < 1)
2701*0b57cec5SDimitry Andric         return error("Invalid gep with no operands");
2702*0b57cec5SDimitry Andric 
2703fe6060f1SDimitry Andric       PointerType *OrigPtrTy = cast<PointerType>(Elt0FullTy->getScalarType());
2704*0b57cec5SDimitry Andric       if (!PointeeType)
270504eeddc0SDimitry Andric         PointeeType = OrigPtrTy->getPointerElementType();
2706fe6060f1SDimitry Andric       else if (!OrigPtrTy->isOpaqueOrPointeeTypeMatches(PointeeType))
2707*0b57cec5SDimitry Andric         return error("Explicit gep operator type does not match pointee type "
2708*0b57cec5SDimitry Andric                      "of pointer operand");
2709*0b57cec5SDimitry Andric 
2710*0b57cec5SDimitry Andric       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2711*0b57cec5SDimitry Andric       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2712*0b57cec5SDimitry Andric                                          InBounds, InRangeIndex);
2713*0b57cec5SDimitry Andric       break;
2714*0b57cec5SDimitry Andric     }
2715*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2716*0b57cec5SDimitry Andric       if (Record.size() < 3)
2717*0b57cec5SDimitry Andric         return error("Invalid record");
2718*0b57cec5SDimitry Andric 
2719349cc55cSDimitry Andric       DelayedSelectors.push_back(
2720349cc55cSDimitry Andric           {CurTy, Record[0], Record[1], Record[2], NextCstNo});
2721349cc55cSDimitry Andric       (void)ValueList.getConstantFwdRef(NextCstNo, CurTy);
2722349cc55cSDimitry Andric       ++NextCstNo;
2723349cc55cSDimitry Andric       continue;
2724*0b57cec5SDimitry Andric     }
2725*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_EXTRACTELT
2726*0b57cec5SDimitry Andric         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2727*0b57cec5SDimitry Andric       if (Record.size() < 3)
2728*0b57cec5SDimitry Andric         return error("Invalid record");
2729*0b57cec5SDimitry Andric       VectorType *OpTy =
2730*0b57cec5SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2731*0b57cec5SDimitry Andric       if (!OpTy)
2732*0b57cec5SDimitry Andric         return error("Invalid record");
2733*0b57cec5SDimitry Andric       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2734*0b57cec5SDimitry Andric       Constant *Op1 = nullptr;
2735*0b57cec5SDimitry Andric       if (Record.size() == 4) {
2736*0b57cec5SDimitry Andric         Type *IdxTy = getTypeByID(Record[2]);
2737*0b57cec5SDimitry Andric         if (!IdxTy)
2738*0b57cec5SDimitry Andric           return error("Invalid record");
2739*0b57cec5SDimitry Andric         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
27405ffd83dbSDimitry Andric       } else {
27415ffd83dbSDimitry Andric         // Deprecated, but still needed to read old bitcode files.
2742*0b57cec5SDimitry Andric         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
27435ffd83dbSDimitry Andric       }
2744*0b57cec5SDimitry Andric       if (!Op1)
2745*0b57cec5SDimitry Andric         return error("Invalid record");
2746*0b57cec5SDimitry Andric       V = ConstantExpr::getExtractElement(Op0, Op1);
2747*0b57cec5SDimitry Andric       break;
2748*0b57cec5SDimitry Andric     }
2749*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_INSERTELT
2750*0b57cec5SDimitry Andric         : { // CE_INSERTELT: [opval, opval, opty, opval]
2751*0b57cec5SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2752*0b57cec5SDimitry Andric       if (Record.size() < 3 || !OpTy)
2753*0b57cec5SDimitry Andric         return error("Invalid record");
2754*0b57cec5SDimitry Andric       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2755*0b57cec5SDimitry Andric       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2756*0b57cec5SDimitry Andric                                                   OpTy->getElementType());
2757*0b57cec5SDimitry Andric       Constant *Op2 = nullptr;
2758*0b57cec5SDimitry Andric       if (Record.size() == 4) {
2759*0b57cec5SDimitry Andric         Type *IdxTy = getTypeByID(Record[2]);
2760*0b57cec5SDimitry Andric         if (!IdxTy)
2761*0b57cec5SDimitry Andric           return error("Invalid record");
2762*0b57cec5SDimitry Andric         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
27635ffd83dbSDimitry Andric       } else {
27645ffd83dbSDimitry Andric         // Deprecated, but still needed to read old bitcode files.
2765*0b57cec5SDimitry Andric         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
27665ffd83dbSDimitry Andric       }
2767*0b57cec5SDimitry Andric       if (!Op2)
2768*0b57cec5SDimitry Andric         return error("Invalid record");
2769*0b57cec5SDimitry Andric       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2770*0b57cec5SDimitry Andric       break;
2771*0b57cec5SDimitry Andric     }
2772*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2773*0b57cec5SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2774*0b57cec5SDimitry Andric       if (Record.size() < 3 || !OpTy)
2775*0b57cec5SDimitry Andric         return error("Invalid record");
27765ffd83dbSDimitry Andric       DelayedShuffles.push_back(
2777fe6060f1SDimitry Andric           {OpTy, OpTy, Record[0], Record[1], Record[2], NextCstNo});
27785ffd83dbSDimitry Andric       ++NextCstNo;
27795ffd83dbSDimitry Andric       continue;
2780*0b57cec5SDimitry Andric     }
2781*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2782*0b57cec5SDimitry Andric       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2783*0b57cec5SDimitry Andric       VectorType *OpTy =
2784*0b57cec5SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2785*0b57cec5SDimitry Andric       if (Record.size() < 4 || !RTy || !OpTy)
2786*0b57cec5SDimitry Andric         return error("Invalid record");
27875ffd83dbSDimitry Andric       DelayedShuffles.push_back(
2788fe6060f1SDimitry Andric           {OpTy, RTy, Record[1], Record[2], Record[3], NextCstNo});
27895ffd83dbSDimitry Andric       ++NextCstNo;
27905ffd83dbSDimitry Andric       continue;
2791*0b57cec5SDimitry Andric     }
2792*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2793*0b57cec5SDimitry Andric       if (Record.size() < 4)
2794*0b57cec5SDimitry Andric         return error("Invalid record");
2795*0b57cec5SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
2796*0b57cec5SDimitry Andric       if (!OpTy)
2797*0b57cec5SDimitry Andric         return error("Invalid record");
2798*0b57cec5SDimitry Andric       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2799*0b57cec5SDimitry Andric       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2800*0b57cec5SDimitry Andric 
2801*0b57cec5SDimitry Andric       if (OpTy->isFPOrFPVectorTy())
2802*0b57cec5SDimitry Andric         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2803*0b57cec5SDimitry Andric       else
2804*0b57cec5SDimitry Andric         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2805*0b57cec5SDimitry Andric       break;
2806*0b57cec5SDimitry Andric     }
2807*0b57cec5SDimitry Andric     // This maintains backward compatibility, pre-asm dialect keywords.
28085ffd83dbSDimitry Andric     // Deprecated, but still needed to read old bitcode files.
2809*0b57cec5SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD: {
2810*0b57cec5SDimitry Andric       if (Record.size() < 2)
2811*0b57cec5SDimitry Andric         return error("Invalid record");
2812*0b57cec5SDimitry Andric       std::string AsmStr, ConstrStr;
2813*0b57cec5SDimitry Andric       bool HasSideEffects = Record[0] & 1;
2814*0b57cec5SDimitry Andric       bool IsAlignStack = Record[0] >> 1;
2815*0b57cec5SDimitry Andric       unsigned AsmStrSize = Record[1];
2816*0b57cec5SDimitry Andric       if (2+AsmStrSize >= Record.size())
2817*0b57cec5SDimitry Andric         return error("Invalid record");
2818*0b57cec5SDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
2819*0b57cec5SDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
2820*0b57cec5SDimitry Andric         return error("Invalid record");
2821*0b57cec5SDimitry Andric 
2822*0b57cec5SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
2823*0b57cec5SDimitry Andric         AsmStr += (char)Record[2+i];
2824*0b57cec5SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
2825*0b57cec5SDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
2826*0b57cec5SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
282704eeddc0SDimitry Andric       // FIXME: support upgrading in opaque pointers mode.
282804eeddc0SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurTy->getPointerElementType()),
2829fe6060f1SDimitry Andric                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2830*0b57cec5SDimitry Andric       break;
2831*0b57cec5SDimitry Andric     }
2832*0b57cec5SDimitry Andric     // This version adds support for the asm dialect keywords (e.g.,
2833*0b57cec5SDimitry Andric     // inteldialect).
2834fe6060f1SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD2: {
2835*0b57cec5SDimitry Andric       if (Record.size() < 2)
2836*0b57cec5SDimitry Andric         return error("Invalid record");
2837*0b57cec5SDimitry Andric       std::string AsmStr, ConstrStr;
2838*0b57cec5SDimitry Andric       bool HasSideEffects = Record[0] & 1;
2839*0b57cec5SDimitry Andric       bool IsAlignStack = (Record[0] >> 1) & 1;
2840*0b57cec5SDimitry Andric       unsigned AsmDialect = Record[0] >> 2;
2841*0b57cec5SDimitry Andric       unsigned AsmStrSize = Record[1];
2842*0b57cec5SDimitry Andric       if (2+AsmStrSize >= Record.size())
2843*0b57cec5SDimitry Andric         return error("Invalid record");
2844*0b57cec5SDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
2845*0b57cec5SDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
2846*0b57cec5SDimitry Andric         return error("Invalid record");
2847*0b57cec5SDimitry Andric 
2848*0b57cec5SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
2849*0b57cec5SDimitry Andric         AsmStr += (char)Record[2+i];
2850*0b57cec5SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
2851*0b57cec5SDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
2852*0b57cec5SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
285304eeddc0SDimitry Andric       // FIXME: support upgrading in opaque pointers mode.
285404eeddc0SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurTy->getPointerElementType()),
2855fe6060f1SDimitry Andric                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2856*0b57cec5SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect));
2857*0b57cec5SDimitry Andric       break;
2858*0b57cec5SDimitry Andric     }
2859fe6060f1SDimitry Andric     // This version adds support for the unwind keyword.
286004eeddc0SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD3: {
2861fe6060f1SDimitry Andric       if (Record.size() < 2)
2862fe6060f1SDimitry Andric         return error("Invalid record");
286304eeddc0SDimitry Andric       unsigned OpNum = 0;
2864fe6060f1SDimitry Andric       std::string AsmStr, ConstrStr;
286504eeddc0SDimitry Andric       bool HasSideEffects = Record[OpNum] & 1;
286604eeddc0SDimitry Andric       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
286704eeddc0SDimitry Andric       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
286804eeddc0SDimitry Andric       bool CanThrow = (Record[OpNum] >> 3) & 1;
286904eeddc0SDimitry Andric       ++OpNum;
287004eeddc0SDimitry Andric       unsigned AsmStrSize = Record[OpNum];
287104eeddc0SDimitry Andric       ++OpNum;
287204eeddc0SDimitry Andric       if (OpNum + AsmStrSize >= Record.size())
2873fe6060f1SDimitry Andric         return error("Invalid record");
287404eeddc0SDimitry Andric       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
287504eeddc0SDimitry Andric       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
2876fe6060f1SDimitry Andric         return error("Invalid record");
2877fe6060f1SDimitry Andric 
2878fe6060f1SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
287904eeddc0SDimitry Andric         AsmStr += (char)Record[OpNum + i];
288004eeddc0SDimitry Andric       ++OpNum;
2881fe6060f1SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
288204eeddc0SDimitry Andric         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
2883fe6060f1SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
288404eeddc0SDimitry Andric       // FIXME: support upgrading in opaque pointers mode.
288504eeddc0SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurTy->getPointerElementType()),
2886fe6060f1SDimitry Andric                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2887fe6060f1SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
2888fe6060f1SDimitry Andric       break;
2889fe6060f1SDimitry Andric     }
289004eeddc0SDimitry Andric     // This version adds explicit function type.
289104eeddc0SDimitry Andric     case bitc::CST_CODE_INLINEASM: {
289204eeddc0SDimitry Andric       if (Record.size() < 3)
289304eeddc0SDimitry Andric         return error("Invalid record");
289404eeddc0SDimitry Andric       unsigned OpNum = 0;
289504eeddc0SDimitry Andric       auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
289604eeddc0SDimitry Andric       ++OpNum;
289704eeddc0SDimitry Andric       if (!FnTy)
289804eeddc0SDimitry Andric         return error("Invalid record");
289904eeddc0SDimitry Andric       std::string AsmStr, ConstrStr;
290004eeddc0SDimitry Andric       bool HasSideEffects = Record[OpNum] & 1;
290104eeddc0SDimitry Andric       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
290204eeddc0SDimitry Andric       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
290304eeddc0SDimitry Andric       bool CanThrow = (Record[OpNum] >> 3) & 1;
290404eeddc0SDimitry Andric       ++OpNum;
290504eeddc0SDimitry Andric       unsigned AsmStrSize = Record[OpNum];
290604eeddc0SDimitry Andric       ++OpNum;
290704eeddc0SDimitry Andric       if (OpNum + AsmStrSize >= Record.size())
290804eeddc0SDimitry Andric         return error("Invalid record");
290904eeddc0SDimitry Andric       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
291004eeddc0SDimitry Andric       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
291104eeddc0SDimitry Andric         return error("Invalid record");
291204eeddc0SDimitry Andric 
291304eeddc0SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
291404eeddc0SDimitry Andric         AsmStr += (char)Record[OpNum + i];
291504eeddc0SDimitry Andric       ++OpNum;
291604eeddc0SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
291704eeddc0SDimitry Andric         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
291804eeddc0SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
291904eeddc0SDimitry Andric       V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
292004eeddc0SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
292104eeddc0SDimitry Andric       break;
292204eeddc0SDimitry Andric     }
2923*0b57cec5SDimitry Andric     case bitc::CST_CODE_BLOCKADDRESS:{
2924*0b57cec5SDimitry Andric       if (Record.size() < 3)
2925*0b57cec5SDimitry Andric         return error("Invalid record");
2926*0b57cec5SDimitry Andric       Type *FnTy = getTypeByID(Record[0]);
2927*0b57cec5SDimitry Andric       if (!FnTy)
2928*0b57cec5SDimitry Andric         return error("Invalid record");
2929*0b57cec5SDimitry Andric       Function *Fn =
2930*0b57cec5SDimitry Andric         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2931*0b57cec5SDimitry Andric       if (!Fn)
2932*0b57cec5SDimitry Andric         return error("Invalid record");
2933*0b57cec5SDimitry Andric 
2934*0b57cec5SDimitry Andric       // If the function is already parsed we can insert the block address right
2935*0b57cec5SDimitry Andric       // away.
2936*0b57cec5SDimitry Andric       BasicBlock *BB;
2937*0b57cec5SDimitry Andric       unsigned BBID = Record[2];
2938*0b57cec5SDimitry Andric       if (!BBID)
2939*0b57cec5SDimitry Andric         // Invalid reference to entry block.
2940*0b57cec5SDimitry Andric         return error("Invalid ID");
2941*0b57cec5SDimitry Andric       if (!Fn->empty()) {
2942*0b57cec5SDimitry Andric         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2943*0b57cec5SDimitry Andric         for (size_t I = 0, E = BBID; I != E; ++I) {
2944*0b57cec5SDimitry Andric           if (BBI == BBE)
2945*0b57cec5SDimitry Andric             return error("Invalid ID");
2946*0b57cec5SDimitry Andric           ++BBI;
2947*0b57cec5SDimitry Andric         }
2948*0b57cec5SDimitry Andric         BB = &*BBI;
2949*0b57cec5SDimitry Andric       } else {
2950*0b57cec5SDimitry Andric         // Otherwise insert a placeholder and remember it so it can be inserted
2951*0b57cec5SDimitry Andric         // when the function is parsed.
2952*0b57cec5SDimitry Andric         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2953*0b57cec5SDimitry Andric         if (FwdBBs.empty())
2954*0b57cec5SDimitry Andric           BasicBlockFwdRefQueue.push_back(Fn);
2955*0b57cec5SDimitry Andric         if (FwdBBs.size() < BBID + 1)
2956*0b57cec5SDimitry Andric           FwdBBs.resize(BBID + 1);
2957*0b57cec5SDimitry Andric         if (!FwdBBs[BBID])
2958*0b57cec5SDimitry Andric           FwdBBs[BBID] = BasicBlock::Create(Context);
2959*0b57cec5SDimitry Andric         BB = FwdBBs[BBID];
2960*0b57cec5SDimitry Andric       }
2961*0b57cec5SDimitry Andric       V = BlockAddress::get(Fn, BB);
2962*0b57cec5SDimitry Andric       break;
2963*0b57cec5SDimitry Andric     }
2964fe6060f1SDimitry Andric     case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
2965fe6060f1SDimitry Andric       if (Record.size() < 2)
2966fe6060f1SDimitry Andric         return error("Invalid record");
2967fe6060f1SDimitry Andric       Type *GVTy = getTypeByID(Record[0]);
2968fe6060f1SDimitry Andric       if (!GVTy)
2969fe6060f1SDimitry Andric         return error("Invalid record");
2970fe6060f1SDimitry Andric       GlobalValue *GV = dyn_cast_or_null<GlobalValue>(
2971fe6060f1SDimitry Andric           ValueList.getConstantFwdRef(Record[1], GVTy));
2972fe6060f1SDimitry Andric       if (!GV)
2973fe6060f1SDimitry Andric         return error("Invalid record");
2974fe6060f1SDimitry Andric 
2975fe6060f1SDimitry Andric       V = DSOLocalEquivalent::get(GV);
2976fe6060f1SDimitry Andric       break;
2977fe6060f1SDimitry Andric     }
29780eae32dcSDimitry Andric     case bitc::CST_CODE_NO_CFI_VALUE: {
29790eae32dcSDimitry Andric       if (Record.size() < 2)
29800eae32dcSDimitry Andric         return error("Invalid record");
29810eae32dcSDimitry Andric       Type *GVTy = getTypeByID(Record[0]);
29820eae32dcSDimitry Andric       if (!GVTy)
29830eae32dcSDimitry Andric         return error("Invalid record");
29840eae32dcSDimitry Andric       GlobalValue *GV = dyn_cast_or_null<GlobalValue>(
29850eae32dcSDimitry Andric           ValueList.getConstantFwdRef(Record[1], GVTy));
29860eae32dcSDimitry Andric       if (!GV)
29870eae32dcSDimitry Andric         return error("Invalid record");
29880eae32dcSDimitry Andric       V = NoCFIValue::get(GV);
29890eae32dcSDimitry Andric       break;
29900eae32dcSDimitry Andric     }
2991*0b57cec5SDimitry Andric     }
2992*0b57cec5SDimitry Andric 
2993fe6060f1SDimitry Andric     ValueList.assignValue(V, NextCstNo);
2994*0b57cec5SDimitry Andric     ++NextCstNo;
2995*0b57cec5SDimitry Andric   }
2996*0b57cec5SDimitry Andric }
2997*0b57cec5SDimitry Andric 
2998*0b57cec5SDimitry Andric Error BitcodeReader::parseUseLists() {
2999*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3000*0b57cec5SDimitry Andric     return Err;
3001*0b57cec5SDimitry Andric 
3002*0b57cec5SDimitry Andric   // Read all the records.
3003*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
3004*0b57cec5SDimitry Andric 
3005*0b57cec5SDimitry Andric   while (true) {
3006*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3007*0b57cec5SDimitry Andric     if (!MaybeEntry)
3008*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
3009*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
3010*0b57cec5SDimitry Andric 
3011*0b57cec5SDimitry Andric     switch (Entry.Kind) {
3012*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
3013*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
3014*0b57cec5SDimitry Andric       return error("Malformed block");
3015*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
3016*0b57cec5SDimitry Andric       return Error::success();
3017*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
3018*0b57cec5SDimitry Andric       // The interesting case.
3019*0b57cec5SDimitry Andric       break;
3020*0b57cec5SDimitry Andric     }
3021*0b57cec5SDimitry Andric 
3022*0b57cec5SDimitry Andric     // Read a use list record.
3023*0b57cec5SDimitry Andric     Record.clear();
3024*0b57cec5SDimitry Andric     bool IsBB = false;
3025*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3026*0b57cec5SDimitry Andric     if (!MaybeRecord)
3027*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
3028*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
3029*0b57cec5SDimitry Andric     default:  // Default behavior: unknown type.
3030*0b57cec5SDimitry Andric       break;
3031*0b57cec5SDimitry Andric     case bitc::USELIST_CODE_BB:
3032*0b57cec5SDimitry Andric       IsBB = true;
3033*0b57cec5SDimitry Andric       LLVM_FALLTHROUGH;
3034*0b57cec5SDimitry Andric     case bitc::USELIST_CODE_DEFAULT: {
3035*0b57cec5SDimitry Andric       unsigned RecordLength = Record.size();
3036*0b57cec5SDimitry Andric       if (RecordLength < 3)
3037*0b57cec5SDimitry Andric         // Records should have at least an ID and two indexes.
3038*0b57cec5SDimitry Andric         return error("Invalid record");
3039e8d8bef9SDimitry Andric       unsigned ID = Record.pop_back_val();
3040*0b57cec5SDimitry Andric 
3041*0b57cec5SDimitry Andric       Value *V;
3042*0b57cec5SDimitry Andric       if (IsBB) {
3043*0b57cec5SDimitry Andric         assert(ID < FunctionBBs.size() && "Basic block not found");
3044*0b57cec5SDimitry Andric         V = FunctionBBs[ID];
3045*0b57cec5SDimitry Andric       } else
3046*0b57cec5SDimitry Andric         V = ValueList[ID];
3047*0b57cec5SDimitry Andric       unsigned NumUses = 0;
3048*0b57cec5SDimitry Andric       SmallDenseMap<const Use *, unsigned, 16> Order;
3049*0b57cec5SDimitry Andric       for (const Use &U : V->materialized_uses()) {
3050*0b57cec5SDimitry Andric         if (++NumUses > Record.size())
3051*0b57cec5SDimitry Andric           break;
3052*0b57cec5SDimitry Andric         Order[&U] = Record[NumUses - 1];
3053*0b57cec5SDimitry Andric       }
3054*0b57cec5SDimitry Andric       if (Order.size() != Record.size() || NumUses > Record.size())
3055*0b57cec5SDimitry Andric         // Mismatches can happen if the functions are being materialized lazily
3056*0b57cec5SDimitry Andric         // (out-of-order), or a value has been upgraded.
3057*0b57cec5SDimitry Andric         break;
3058*0b57cec5SDimitry Andric 
3059*0b57cec5SDimitry Andric       V->sortUseList([&](const Use &L, const Use &R) {
3060*0b57cec5SDimitry Andric         return Order.lookup(&L) < Order.lookup(&R);
3061*0b57cec5SDimitry Andric       });
3062*0b57cec5SDimitry Andric       break;
3063*0b57cec5SDimitry Andric     }
3064*0b57cec5SDimitry Andric     }
3065*0b57cec5SDimitry Andric   }
3066*0b57cec5SDimitry Andric }
3067*0b57cec5SDimitry Andric 
3068*0b57cec5SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it.
3069*0b57cec5SDimitry Andric /// This lets us lazily deserialize the metadata.
3070*0b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() {
3071*0b57cec5SDimitry Andric   // Save the current stream state.
3072*0b57cec5SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
3073*0b57cec5SDimitry Andric   DeferredMetadataInfo.push_back(CurBit);
3074*0b57cec5SDimitry Andric 
3075*0b57cec5SDimitry Andric   // Skip over the block for now.
3076*0b57cec5SDimitry Andric   if (Error Err = Stream.SkipBlock())
3077*0b57cec5SDimitry Andric     return Err;
3078*0b57cec5SDimitry Andric   return Error::success();
3079*0b57cec5SDimitry Andric }
3080*0b57cec5SDimitry Andric 
3081*0b57cec5SDimitry Andric Error BitcodeReader::materializeMetadata() {
3082*0b57cec5SDimitry Andric   for (uint64_t BitPos : DeferredMetadataInfo) {
3083*0b57cec5SDimitry Andric     // Move the bit stream to the saved position.
3084*0b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(BitPos))
3085*0b57cec5SDimitry Andric       return JumpFailed;
3086*0b57cec5SDimitry Andric     if (Error Err = MDLoader->parseModuleMetadata())
3087*0b57cec5SDimitry Andric       return Err;
3088*0b57cec5SDimitry Andric   }
3089*0b57cec5SDimitry Andric 
3090*0b57cec5SDimitry Andric   // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3091e8d8bef9SDimitry Andric   // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3092e8d8bef9SDimitry Andric   // multiple times.
3093e8d8bef9SDimitry Andric   if (!TheModule->getNamedMetadata("llvm.linker.options")) {
3094*0b57cec5SDimitry Andric     if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
3095*0b57cec5SDimitry Andric       NamedMDNode *LinkerOpts =
3096*0b57cec5SDimitry Andric           TheModule->getOrInsertNamedMetadata("llvm.linker.options");
3097*0b57cec5SDimitry Andric       for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3098*0b57cec5SDimitry Andric         LinkerOpts->addOperand(cast<MDNode>(MDOptions));
3099*0b57cec5SDimitry Andric     }
3100e8d8bef9SDimitry Andric   }
3101*0b57cec5SDimitry Andric 
3102*0b57cec5SDimitry Andric   DeferredMetadataInfo.clear();
3103*0b57cec5SDimitry Andric   return Error::success();
3104*0b57cec5SDimitry Andric }
3105*0b57cec5SDimitry Andric 
3106*0b57cec5SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3107*0b57cec5SDimitry Andric 
3108*0b57cec5SDimitry Andric /// When we see the block for a function body, remember where it is and then
3109*0b57cec5SDimitry Andric /// skip it.  This lets us lazily deserialize the functions.
3110*0b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() {
3111*0b57cec5SDimitry Andric   // Get the function we are talking about.
3112*0b57cec5SDimitry Andric   if (FunctionsWithBodies.empty())
3113*0b57cec5SDimitry Andric     return error("Insufficient function protos");
3114*0b57cec5SDimitry Andric 
3115*0b57cec5SDimitry Andric   Function *Fn = FunctionsWithBodies.back();
3116*0b57cec5SDimitry Andric   FunctionsWithBodies.pop_back();
3117*0b57cec5SDimitry Andric 
3118*0b57cec5SDimitry Andric   // Save the current stream state.
3119*0b57cec5SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
3120*0b57cec5SDimitry Andric   assert(
3121*0b57cec5SDimitry Andric       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3122*0b57cec5SDimitry Andric       "Mismatch between VST and scanned function offsets");
3123*0b57cec5SDimitry Andric   DeferredFunctionInfo[Fn] = CurBit;
3124*0b57cec5SDimitry Andric 
3125*0b57cec5SDimitry Andric   // Skip over the function block for now.
3126*0b57cec5SDimitry Andric   if (Error Err = Stream.SkipBlock())
3127*0b57cec5SDimitry Andric     return Err;
3128*0b57cec5SDimitry Andric   return Error::success();
3129*0b57cec5SDimitry Andric }
3130*0b57cec5SDimitry Andric 
3131*0b57cec5SDimitry Andric Error BitcodeReader::globalCleanup() {
3132*0b57cec5SDimitry Andric   // Patch the initializers for globals and aliases up.
3133*0b57cec5SDimitry Andric   if (Error Err = resolveGlobalAndIndirectSymbolInits())
3134*0b57cec5SDimitry Andric     return Err;
3135*0b57cec5SDimitry Andric   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3136*0b57cec5SDimitry Andric     return error("Malformed global initializer set");
3137*0b57cec5SDimitry Andric 
3138*0b57cec5SDimitry Andric   // Look for intrinsic functions which need to be upgraded at some point
31395ffd83dbSDimitry Andric   // and functions that need to have their function attributes upgraded.
3140*0b57cec5SDimitry Andric   for (Function &F : *TheModule) {
3141*0b57cec5SDimitry Andric     MDLoader->upgradeDebugIntrinsics(F);
3142*0b57cec5SDimitry Andric     Function *NewFn;
3143*0b57cec5SDimitry Andric     if (UpgradeIntrinsicFunction(&F, NewFn))
3144*0b57cec5SDimitry Andric       UpgradedIntrinsics[&F] = NewFn;
3145*0b57cec5SDimitry Andric     else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3146*0b57cec5SDimitry Andric       // Some types could be renamed during loading if several modules are
3147*0b57cec5SDimitry Andric       // loaded in the same LLVMContext (LTO scenario). In this case we should
3148*0b57cec5SDimitry Andric       // remangle intrinsics names as well.
3149*0b57cec5SDimitry Andric       RemangledIntrinsics[&F] = Remangled.getValue();
31505ffd83dbSDimitry Andric     // Look for functions that rely on old function attribute behavior.
31515ffd83dbSDimitry Andric     UpgradeFunctionAttributes(F);
3152*0b57cec5SDimitry Andric   }
3153*0b57cec5SDimitry Andric 
3154*0b57cec5SDimitry Andric   // Look for global variables which need to be renamed.
3155*0b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3156*0b57cec5SDimitry Andric   for (GlobalVariable &GV : TheModule->globals())
3157*0b57cec5SDimitry Andric     if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
3158*0b57cec5SDimitry Andric       UpgradedVariables.emplace_back(&GV, Upgraded);
3159*0b57cec5SDimitry Andric   for (auto &Pair : UpgradedVariables) {
3160*0b57cec5SDimitry Andric     Pair.first->eraseFromParent();
3161*0b57cec5SDimitry Andric     TheModule->getGlobalList().push_back(Pair.second);
3162*0b57cec5SDimitry Andric   }
3163*0b57cec5SDimitry Andric 
3164*0b57cec5SDimitry Andric   // Force deallocation of memory for these vectors to favor the client that
3165*0b57cec5SDimitry Andric   // want lazy deserialization.
3166*0b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3167349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
3168*0b57cec5SDimitry Andric   return Error::success();
3169*0b57cec5SDimitry Andric }
3170*0b57cec5SDimitry Andric 
3171*0b57cec5SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we
3172*0b57cec5SDimitry Andric /// either have an old bitcode file without a VST forward declaration record,
3173*0b57cec5SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous
3174*0b57cec5SDimitry Andric /// functions do not have a name and are therefore not in the VST.
3175*0b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() {
3176*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3177*0b57cec5SDimitry Andric     return JumpFailed;
3178*0b57cec5SDimitry Andric 
3179*0b57cec5SDimitry Andric   if (Stream.AtEndOfStream())
3180*0b57cec5SDimitry Andric     return error("Could not find function in stream");
3181*0b57cec5SDimitry Andric 
3182*0b57cec5SDimitry Andric   if (!SeenFirstFunctionBody)
3183*0b57cec5SDimitry Andric     return error("Trying to materialize functions before seeing function blocks");
3184*0b57cec5SDimitry Andric 
3185*0b57cec5SDimitry Andric   // An old bitcode file with the symbol table at the end would have
3186*0b57cec5SDimitry Andric   // finished the parse greedily.
3187*0b57cec5SDimitry Andric   assert(SeenValueSymbolTable);
3188*0b57cec5SDimitry Andric 
3189*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
3190*0b57cec5SDimitry Andric 
3191*0b57cec5SDimitry Andric   while (true) {
3192*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3193*0b57cec5SDimitry Andric     if (!MaybeEntry)
3194*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
3195*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
3196*0b57cec5SDimitry Andric 
3197*0b57cec5SDimitry Andric     switch (Entry.Kind) {
3198*0b57cec5SDimitry Andric     default:
3199*0b57cec5SDimitry Andric       return error("Expect SubBlock");
3200*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
3201*0b57cec5SDimitry Andric       switch (Entry.ID) {
3202*0b57cec5SDimitry Andric       default:
3203*0b57cec5SDimitry Andric         return error("Expect function block");
3204*0b57cec5SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
3205*0b57cec5SDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
3206*0b57cec5SDimitry Andric           return Err;
3207*0b57cec5SDimitry Andric         NextUnreadBit = Stream.GetCurrentBitNo();
3208*0b57cec5SDimitry Andric         return Error::success();
3209*0b57cec5SDimitry Andric       }
3210*0b57cec5SDimitry Andric     }
3211*0b57cec5SDimitry Andric   }
3212*0b57cec5SDimitry Andric }
3213*0b57cec5SDimitry Andric 
3214*0b57cec5SDimitry Andric bool BitcodeReaderBase::readBlockInfo() {
3215*0b57cec5SDimitry Andric   Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
3216*0b57cec5SDimitry Andric       Stream.ReadBlockInfoBlock();
3217*0b57cec5SDimitry Andric   if (!MaybeNewBlockInfo)
3218*0b57cec5SDimitry Andric     return true; // FIXME Handle the error.
3219*0b57cec5SDimitry Andric   Optional<BitstreamBlockInfo> NewBlockInfo =
3220*0b57cec5SDimitry Andric       std::move(MaybeNewBlockInfo.get());
3221*0b57cec5SDimitry Andric   if (!NewBlockInfo)
3222*0b57cec5SDimitry Andric     return true;
3223*0b57cec5SDimitry Andric   BlockInfo = std::move(*NewBlockInfo);
3224*0b57cec5SDimitry Andric   return false;
3225*0b57cec5SDimitry Andric }
3226*0b57cec5SDimitry Andric 
3227*0b57cec5SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
3228*0b57cec5SDimitry Andric   // v1: [selection_kind, name]
3229*0b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, selection_kind]
3230*0b57cec5SDimitry Andric   StringRef Name;
3231*0b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
3232*0b57cec5SDimitry Andric 
3233*0b57cec5SDimitry Andric   if (Record.empty())
3234*0b57cec5SDimitry Andric     return error("Invalid record");
3235*0b57cec5SDimitry Andric   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3236*0b57cec5SDimitry Andric   std::string OldFormatName;
3237*0b57cec5SDimitry Andric   if (!UseStrtab) {
3238*0b57cec5SDimitry Andric     if (Record.size() < 2)
3239*0b57cec5SDimitry Andric       return error("Invalid record");
3240*0b57cec5SDimitry Andric     unsigned ComdatNameSize = Record[1];
3241*0b57cec5SDimitry Andric     OldFormatName.reserve(ComdatNameSize);
3242*0b57cec5SDimitry Andric     for (unsigned i = 0; i != ComdatNameSize; ++i)
3243*0b57cec5SDimitry Andric       OldFormatName += (char)Record[2 + i];
3244*0b57cec5SDimitry Andric     Name = OldFormatName;
3245*0b57cec5SDimitry Andric   }
3246*0b57cec5SDimitry Andric   Comdat *C = TheModule->getOrInsertComdat(Name);
3247*0b57cec5SDimitry Andric   C->setSelectionKind(SK);
3248*0b57cec5SDimitry Andric   ComdatList.push_back(C);
3249*0b57cec5SDimitry Andric   return Error::success();
3250*0b57cec5SDimitry Andric }
3251*0b57cec5SDimitry Andric 
3252*0b57cec5SDimitry Andric static void inferDSOLocal(GlobalValue *GV) {
3253*0b57cec5SDimitry Andric   // infer dso_local from linkage and visibility if it is not encoded.
3254*0b57cec5SDimitry Andric   if (GV->hasLocalLinkage() ||
3255*0b57cec5SDimitry Andric       (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
3256*0b57cec5SDimitry Andric     GV->setDSOLocal(true);
3257*0b57cec5SDimitry Andric }
3258*0b57cec5SDimitry Andric 
3259*0b57cec5SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
3260*0b57cec5SDimitry Andric   // v1: [pointer type, isconst, initid, linkage, alignment, section,
3261*0b57cec5SDimitry Andric   // visibility, threadlocal, unnamed_addr, externally_initialized,
3262*0b57cec5SDimitry Andric   // dllstorageclass, comdat, attributes, preemption specifier,
3263*0b57cec5SDimitry Andric   // partition strtab offset, partition strtab size] (name in VST)
3264*0b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
3265*0b57cec5SDimitry Andric   StringRef Name;
3266*0b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
3267*0b57cec5SDimitry Andric 
3268*0b57cec5SDimitry Andric   if (Record.size() < 6)
3269*0b57cec5SDimitry Andric     return error("Invalid record");
3270fe6060f1SDimitry Andric   Type *Ty = getTypeByID(Record[0]);
3271*0b57cec5SDimitry Andric   if (!Ty)
3272*0b57cec5SDimitry Andric     return error("Invalid record");
3273*0b57cec5SDimitry Andric   bool isConstant = Record[1] & 1;
3274*0b57cec5SDimitry Andric   bool explicitType = Record[1] & 2;
3275*0b57cec5SDimitry Andric   unsigned AddressSpace;
3276*0b57cec5SDimitry Andric   if (explicitType) {
3277*0b57cec5SDimitry Andric     AddressSpace = Record[1] >> 2;
3278*0b57cec5SDimitry Andric   } else {
3279*0b57cec5SDimitry Andric     if (!Ty->isPointerTy())
3280*0b57cec5SDimitry Andric       return error("Invalid type for value");
3281*0b57cec5SDimitry Andric     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
328204eeddc0SDimitry Andric     Ty = Ty->getPointerElementType();
3283*0b57cec5SDimitry Andric   }
3284*0b57cec5SDimitry Andric 
3285*0b57cec5SDimitry Andric   uint64_t RawLinkage = Record[3];
3286*0b57cec5SDimitry Andric   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
32878bcb0991SDimitry Andric   MaybeAlign Alignment;
3288*0b57cec5SDimitry Andric   if (Error Err = parseAlignmentValue(Record[4], Alignment))
3289*0b57cec5SDimitry Andric     return Err;
3290*0b57cec5SDimitry Andric   std::string Section;
3291*0b57cec5SDimitry Andric   if (Record[5]) {
3292*0b57cec5SDimitry Andric     if (Record[5] - 1 >= SectionTable.size())
3293*0b57cec5SDimitry Andric       return error("Invalid ID");
3294*0b57cec5SDimitry Andric     Section = SectionTable[Record[5] - 1];
3295*0b57cec5SDimitry Andric   }
3296*0b57cec5SDimitry Andric   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3297*0b57cec5SDimitry Andric   // Local linkage must have default visibility.
32985ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
3299*0b57cec5SDimitry Andric   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3300*0b57cec5SDimitry Andric     Visibility = getDecodedVisibility(Record[6]);
3301*0b57cec5SDimitry Andric 
3302*0b57cec5SDimitry Andric   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3303*0b57cec5SDimitry Andric   if (Record.size() > 7)
3304*0b57cec5SDimitry Andric     TLM = getDecodedThreadLocalMode(Record[7]);
3305*0b57cec5SDimitry Andric 
3306*0b57cec5SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3307*0b57cec5SDimitry Andric   if (Record.size() > 8)
3308*0b57cec5SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3309*0b57cec5SDimitry Andric 
3310*0b57cec5SDimitry Andric   bool ExternallyInitialized = false;
3311*0b57cec5SDimitry Andric   if (Record.size() > 9)
3312*0b57cec5SDimitry Andric     ExternallyInitialized = Record[9];
3313*0b57cec5SDimitry Andric 
3314*0b57cec5SDimitry Andric   GlobalVariable *NewGV =
3315*0b57cec5SDimitry Andric       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
3316*0b57cec5SDimitry Andric                          nullptr, TLM, AddressSpace, ExternallyInitialized);
3317*0b57cec5SDimitry Andric   NewGV->setAlignment(Alignment);
3318*0b57cec5SDimitry Andric   if (!Section.empty())
3319*0b57cec5SDimitry Andric     NewGV->setSection(Section);
3320*0b57cec5SDimitry Andric   NewGV->setVisibility(Visibility);
3321*0b57cec5SDimitry Andric   NewGV->setUnnamedAddr(UnnamedAddr);
3322*0b57cec5SDimitry Andric 
3323*0b57cec5SDimitry Andric   if (Record.size() > 10)
3324*0b57cec5SDimitry Andric     NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3325*0b57cec5SDimitry Andric   else
3326*0b57cec5SDimitry Andric     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3327*0b57cec5SDimitry Andric 
3328fe6060f1SDimitry Andric   ValueList.push_back(NewGV);
3329*0b57cec5SDimitry Andric 
3330*0b57cec5SDimitry Andric   // Remember which value to use for the global initializer.
3331*0b57cec5SDimitry Andric   if (unsigned InitID = Record[2])
3332*0b57cec5SDimitry Andric     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
3333*0b57cec5SDimitry Andric 
3334*0b57cec5SDimitry Andric   if (Record.size() > 11) {
3335*0b57cec5SDimitry Andric     if (unsigned ComdatID = Record[11]) {
3336*0b57cec5SDimitry Andric       if (ComdatID > ComdatList.size())
3337*0b57cec5SDimitry Andric         return error("Invalid global variable comdat ID");
3338*0b57cec5SDimitry Andric       NewGV->setComdat(ComdatList[ComdatID - 1]);
3339*0b57cec5SDimitry Andric     }
3340*0b57cec5SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
33410eae32dcSDimitry Andric     ImplicitComdatObjects.insert(NewGV);
3342*0b57cec5SDimitry Andric   }
3343*0b57cec5SDimitry Andric 
3344*0b57cec5SDimitry Andric   if (Record.size() > 12) {
3345349cc55cSDimitry Andric     auto AS = getAttributes(Record[12]).getFnAttrs();
3346*0b57cec5SDimitry Andric     NewGV->setAttributes(AS);
3347*0b57cec5SDimitry Andric   }
3348*0b57cec5SDimitry Andric 
3349*0b57cec5SDimitry Andric   if (Record.size() > 13) {
3350*0b57cec5SDimitry Andric     NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
3351*0b57cec5SDimitry Andric   }
3352*0b57cec5SDimitry Andric   inferDSOLocal(NewGV);
3353*0b57cec5SDimitry Andric 
3354*0b57cec5SDimitry Andric   // Check whether we have enough values to read a partition name.
3355*0b57cec5SDimitry Andric   if (Record.size() > 15)
3356*0b57cec5SDimitry Andric     NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
3357*0b57cec5SDimitry Andric 
3358*0b57cec5SDimitry Andric   return Error::success();
3359*0b57cec5SDimitry Andric }
3360*0b57cec5SDimitry Andric 
3361*0b57cec5SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
3362*0b57cec5SDimitry Andric   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3363*0b57cec5SDimitry Andric   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3364*0b57cec5SDimitry Andric   // prefixdata,  personalityfn, preemption specifier, addrspace] (name in VST)
3365*0b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
3366*0b57cec5SDimitry Andric   StringRef Name;
3367*0b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
3368*0b57cec5SDimitry Andric 
3369*0b57cec5SDimitry Andric   if (Record.size() < 8)
3370*0b57cec5SDimitry Andric     return error("Invalid record");
3371fe6060f1SDimitry Andric   Type *FTy = getTypeByID(Record[0]);
3372*0b57cec5SDimitry Andric   if (!FTy)
3373*0b57cec5SDimitry Andric     return error("Invalid record");
3374fe6060f1SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(FTy))
337504eeddc0SDimitry Andric     FTy = PTy->getPointerElementType();
3376*0b57cec5SDimitry Andric 
3377*0b57cec5SDimitry Andric   if (!isa<FunctionType>(FTy))
3378*0b57cec5SDimitry Andric     return error("Invalid type for value");
3379*0b57cec5SDimitry Andric   auto CC = static_cast<CallingConv::ID>(Record[1]);
3380*0b57cec5SDimitry Andric   if (CC & ~CallingConv::MaxID)
3381*0b57cec5SDimitry Andric     return error("Invalid calling convention ID");
3382*0b57cec5SDimitry Andric 
3383*0b57cec5SDimitry Andric   unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3384*0b57cec5SDimitry Andric   if (Record.size() > 16)
3385*0b57cec5SDimitry Andric     AddrSpace = Record[16];
3386*0b57cec5SDimitry Andric 
3387*0b57cec5SDimitry Andric   Function *Func =
3388*0b57cec5SDimitry Andric       Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
3389*0b57cec5SDimitry Andric                        AddrSpace, Name, TheModule);
3390*0b57cec5SDimitry Andric 
3391fe6060f1SDimitry Andric   assert(Func->getFunctionType() == FTy &&
3392*0b57cec5SDimitry Andric          "Incorrect fully specified type provided for function");
3393fe6060f1SDimitry Andric   FunctionTypes[Func] = cast<FunctionType>(FTy);
3394*0b57cec5SDimitry Andric 
3395*0b57cec5SDimitry Andric   Func->setCallingConv(CC);
3396*0b57cec5SDimitry Andric   bool isProto = Record[2];
3397*0b57cec5SDimitry Andric   uint64_t RawLinkage = Record[3];
3398*0b57cec5SDimitry Andric   Func->setLinkage(getDecodedLinkage(RawLinkage));
3399*0b57cec5SDimitry Andric   Func->setAttributes(getAttributes(Record[4]));
3400*0b57cec5SDimitry Andric 
3401e8d8bef9SDimitry Andric   // Upgrade any old-style byval or sret without a type by propagating the
3402e8d8bef9SDimitry Andric   // argument's pointee type. There should be no opaque pointers where the byval
3403e8d8bef9SDimitry Andric   // type is implicit.
3404*0b57cec5SDimitry Andric   for (unsigned i = 0; i != Func->arg_size(); ++i) {
3405fe6060f1SDimitry Andric     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3406fe6060f1SDimitry Andric                                      Attribute::InAlloca}) {
3407e8d8bef9SDimitry Andric       if (!Func->hasParamAttribute(i, Kind))
3408*0b57cec5SDimitry Andric         continue;
3409*0b57cec5SDimitry Andric 
3410fe6060f1SDimitry Andric       if (Func->getParamAttribute(i, Kind).getValueAsType())
3411fe6060f1SDimitry Andric         continue;
3412fe6060f1SDimitry Andric 
3413e8d8bef9SDimitry Andric       Func->removeParamAttr(i, Kind);
3414e8d8bef9SDimitry Andric 
3415fe6060f1SDimitry Andric       Type *PTy = cast<FunctionType>(FTy)->getParamType(i);
341604eeddc0SDimitry Andric       Type *PtrEltTy = PTy->getPointerElementType();
3417fe6060f1SDimitry Andric       Attribute NewAttr;
3418fe6060f1SDimitry Andric       switch (Kind) {
3419fe6060f1SDimitry Andric       case Attribute::ByVal:
3420fe6060f1SDimitry Andric         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3421fe6060f1SDimitry Andric         break;
3422fe6060f1SDimitry Andric       case Attribute::StructRet:
3423fe6060f1SDimitry Andric         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3424fe6060f1SDimitry Andric         break;
3425fe6060f1SDimitry Andric       case Attribute::InAlloca:
3426fe6060f1SDimitry Andric         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3427fe6060f1SDimitry Andric         break;
3428fe6060f1SDimitry Andric       default:
3429fe6060f1SDimitry Andric         llvm_unreachable("not an upgraded type attribute");
3430fe6060f1SDimitry Andric       }
3431fe6060f1SDimitry Andric 
3432e8d8bef9SDimitry Andric       Func->addParamAttr(i, NewAttr);
3433e8d8bef9SDimitry Andric     }
3434*0b57cec5SDimitry Andric   }
3435*0b57cec5SDimitry Andric 
34368bcb0991SDimitry Andric   MaybeAlign Alignment;
3437*0b57cec5SDimitry Andric   if (Error Err = parseAlignmentValue(Record[5], Alignment))
3438*0b57cec5SDimitry Andric     return Err;
3439*0b57cec5SDimitry Andric   Func->setAlignment(Alignment);
3440*0b57cec5SDimitry Andric   if (Record[6]) {
3441*0b57cec5SDimitry Andric     if (Record[6] - 1 >= SectionTable.size())
3442*0b57cec5SDimitry Andric       return error("Invalid ID");
3443*0b57cec5SDimitry Andric     Func->setSection(SectionTable[Record[6] - 1]);
3444*0b57cec5SDimitry Andric   }
3445*0b57cec5SDimitry Andric   // Local linkage must have default visibility.
34465ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
3447*0b57cec5SDimitry Andric   if (!Func->hasLocalLinkage())
3448*0b57cec5SDimitry Andric     Func->setVisibility(getDecodedVisibility(Record[7]));
3449*0b57cec5SDimitry Andric   if (Record.size() > 8 && Record[8]) {
3450*0b57cec5SDimitry Andric     if (Record[8] - 1 >= GCTable.size())
3451*0b57cec5SDimitry Andric       return error("Invalid ID");
3452*0b57cec5SDimitry Andric     Func->setGC(GCTable[Record[8] - 1]);
3453*0b57cec5SDimitry Andric   }
3454*0b57cec5SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3455*0b57cec5SDimitry Andric   if (Record.size() > 9)
3456*0b57cec5SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3457*0b57cec5SDimitry Andric   Func->setUnnamedAddr(UnnamedAddr);
3458349cc55cSDimitry Andric 
3459349cc55cSDimitry Andric   FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
3460349cc55cSDimitry Andric   if (Record.size() > 10)
3461349cc55cSDimitry Andric     OperandInfo.Prologue = Record[10];
3462*0b57cec5SDimitry Andric 
3463*0b57cec5SDimitry Andric   if (Record.size() > 11)
3464*0b57cec5SDimitry Andric     Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3465*0b57cec5SDimitry Andric   else
3466*0b57cec5SDimitry Andric     upgradeDLLImportExportLinkage(Func, RawLinkage);
3467*0b57cec5SDimitry Andric 
3468*0b57cec5SDimitry Andric   if (Record.size() > 12) {
3469*0b57cec5SDimitry Andric     if (unsigned ComdatID = Record[12]) {
3470*0b57cec5SDimitry Andric       if (ComdatID > ComdatList.size())
3471*0b57cec5SDimitry Andric         return error("Invalid function comdat ID");
3472*0b57cec5SDimitry Andric       Func->setComdat(ComdatList[ComdatID - 1]);
3473*0b57cec5SDimitry Andric     }
3474*0b57cec5SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
34750eae32dcSDimitry Andric     ImplicitComdatObjects.insert(Func);
3476*0b57cec5SDimitry Andric   }
3477*0b57cec5SDimitry Andric 
3478349cc55cSDimitry Andric   if (Record.size() > 13)
3479349cc55cSDimitry Andric     OperandInfo.Prefix = Record[13];
3480*0b57cec5SDimitry Andric 
3481349cc55cSDimitry Andric   if (Record.size() > 14)
3482349cc55cSDimitry Andric     OperandInfo.PersonalityFn = Record[14];
3483*0b57cec5SDimitry Andric 
3484*0b57cec5SDimitry Andric   if (Record.size() > 15) {
3485*0b57cec5SDimitry Andric     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3486*0b57cec5SDimitry Andric   }
3487*0b57cec5SDimitry Andric   inferDSOLocal(Func);
3488*0b57cec5SDimitry Andric 
3489*0b57cec5SDimitry Andric   // Record[16] is the address space number.
3490*0b57cec5SDimitry Andric 
3491fe6060f1SDimitry Andric   // Check whether we have enough values to read a partition name. Also make
3492fe6060f1SDimitry Andric   // sure Strtab has enough values.
3493fe6060f1SDimitry Andric   if (Record.size() > 18 && Strtab.data() &&
3494fe6060f1SDimitry Andric       Record[17] + Record[18] <= Strtab.size()) {
3495*0b57cec5SDimitry Andric     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
3496fe6060f1SDimitry Andric   }
3497*0b57cec5SDimitry Andric 
3498fe6060f1SDimitry Andric   ValueList.push_back(Func);
3499*0b57cec5SDimitry Andric 
3500349cc55cSDimitry Andric   if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
3501349cc55cSDimitry Andric     FunctionOperands.push_back(OperandInfo);
3502349cc55cSDimitry Andric 
3503*0b57cec5SDimitry Andric   // If this is a function with a body, remember the prototype we are
3504*0b57cec5SDimitry Andric   // creating now, so that we can match up the body with them later.
3505*0b57cec5SDimitry Andric   if (!isProto) {
3506*0b57cec5SDimitry Andric     Func->setIsMaterializable(true);
3507*0b57cec5SDimitry Andric     FunctionsWithBodies.push_back(Func);
3508*0b57cec5SDimitry Andric     DeferredFunctionInfo[Func] = 0;
3509*0b57cec5SDimitry Andric   }
3510*0b57cec5SDimitry Andric   return Error::success();
3511*0b57cec5SDimitry Andric }
3512*0b57cec5SDimitry Andric 
3513*0b57cec5SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3514*0b57cec5SDimitry Andric     unsigned BitCode, ArrayRef<uint64_t> Record) {
3515*0b57cec5SDimitry Andric   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3516*0b57cec5SDimitry Andric   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3517*0b57cec5SDimitry Andric   // dllstorageclass, threadlocal, unnamed_addr,
3518*0b57cec5SDimitry Andric   // preemption specifier] (name in VST)
3519*0b57cec5SDimitry Andric   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3520*0b57cec5SDimitry Andric   // visibility, dllstorageclass, threadlocal, unnamed_addr,
3521*0b57cec5SDimitry Andric   // preemption specifier] (name in VST)
3522*0b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
3523*0b57cec5SDimitry Andric   StringRef Name;
3524*0b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
3525*0b57cec5SDimitry Andric 
3526*0b57cec5SDimitry Andric   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3527*0b57cec5SDimitry Andric   if (Record.size() < (3 + (unsigned)NewRecord))
3528*0b57cec5SDimitry Andric     return error("Invalid record");
3529*0b57cec5SDimitry Andric   unsigned OpNum = 0;
3530fe6060f1SDimitry Andric   Type *Ty = getTypeByID(Record[OpNum++]);
3531*0b57cec5SDimitry Andric   if (!Ty)
3532*0b57cec5SDimitry Andric     return error("Invalid record");
3533*0b57cec5SDimitry Andric 
3534*0b57cec5SDimitry Andric   unsigned AddrSpace;
3535*0b57cec5SDimitry Andric   if (!NewRecord) {
3536*0b57cec5SDimitry Andric     auto *PTy = dyn_cast<PointerType>(Ty);
3537*0b57cec5SDimitry Andric     if (!PTy)
3538*0b57cec5SDimitry Andric       return error("Invalid type for value");
353904eeddc0SDimitry Andric     Ty = PTy->getPointerElementType();
3540*0b57cec5SDimitry Andric     AddrSpace = PTy->getAddressSpace();
3541*0b57cec5SDimitry Andric   } else {
3542*0b57cec5SDimitry Andric     AddrSpace = Record[OpNum++];
3543*0b57cec5SDimitry Andric   }
3544*0b57cec5SDimitry Andric 
3545*0b57cec5SDimitry Andric   auto Val = Record[OpNum++];
3546*0b57cec5SDimitry Andric   auto Linkage = Record[OpNum++];
3547349cc55cSDimitry Andric   GlobalValue *NewGA;
3548*0b57cec5SDimitry Andric   if (BitCode == bitc::MODULE_CODE_ALIAS ||
3549*0b57cec5SDimitry Andric       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3550*0b57cec5SDimitry Andric     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3551*0b57cec5SDimitry Andric                                 TheModule);
3552*0b57cec5SDimitry Andric   else
3553*0b57cec5SDimitry Andric     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3554*0b57cec5SDimitry Andric                                 nullptr, TheModule);
3555*0b57cec5SDimitry Andric 
3556*0b57cec5SDimitry Andric   // Local linkage must have default visibility.
35575ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
3558*0b57cec5SDimitry Andric   if (OpNum != Record.size()) {
3559*0b57cec5SDimitry Andric     auto VisInd = OpNum++;
3560*0b57cec5SDimitry Andric     if (!NewGA->hasLocalLinkage())
3561*0b57cec5SDimitry Andric       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3562*0b57cec5SDimitry Andric   }
3563*0b57cec5SDimitry Andric   if (BitCode == bitc::MODULE_CODE_ALIAS ||
3564*0b57cec5SDimitry Andric       BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
3565*0b57cec5SDimitry Andric     if (OpNum != Record.size())
3566*0b57cec5SDimitry Andric       NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3567*0b57cec5SDimitry Andric     else
3568*0b57cec5SDimitry Andric       upgradeDLLImportExportLinkage(NewGA, Linkage);
3569*0b57cec5SDimitry Andric     if (OpNum != Record.size())
3570*0b57cec5SDimitry Andric       NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3571*0b57cec5SDimitry Andric     if (OpNum != Record.size())
3572*0b57cec5SDimitry Andric       NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3573*0b57cec5SDimitry Andric   }
3574*0b57cec5SDimitry Andric   if (OpNum != Record.size())
3575*0b57cec5SDimitry Andric     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3576*0b57cec5SDimitry Andric   inferDSOLocal(NewGA);
3577*0b57cec5SDimitry Andric 
3578*0b57cec5SDimitry Andric   // Check whether we have enough values to read a partition name.
3579*0b57cec5SDimitry Andric   if (OpNum + 1 < Record.size()) {
3580*0b57cec5SDimitry Andric     NewGA->setPartition(
3581*0b57cec5SDimitry Andric         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
3582*0b57cec5SDimitry Andric     OpNum += 2;
3583*0b57cec5SDimitry Andric   }
3584*0b57cec5SDimitry Andric 
3585fe6060f1SDimitry Andric   ValueList.push_back(NewGA);
3586*0b57cec5SDimitry Andric   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3587*0b57cec5SDimitry Andric   return Error::success();
3588*0b57cec5SDimitry Andric }
3589*0b57cec5SDimitry Andric 
3590*0b57cec5SDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit,
35915ffd83dbSDimitry Andric                                  bool ShouldLazyLoadMetadata,
35925ffd83dbSDimitry Andric                                  DataLayoutCallbackTy DataLayoutCallback) {
3593*0b57cec5SDimitry Andric   if (ResumeBit) {
3594*0b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
3595*0b57cec5SDimitry Andric       return JumpFailed;
3596*0b57cec5SDimitry Andric   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3597*0b57cec5SDimitry Andric     return Err;
3598*0b57cec5SDimitry Andric 
3599*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
3600*0b57cec5SDimitry Andric 
36015ffd83dbSDimitry Andric   // Parts of bitcode parsing depend on the datalayout.  Make sure we
36025ffd83dbSDimitry Andric   // finalize the datalayout before we run any of that code.
36035ffd83dbSDimitry Andric   bool ResolvedDataLayout = false;
36045ffd83dbSDimitry Andric   auto ResolveDataLayout = [&] {
36055ffd83dbSDimitry Andric     if (ResolvedDataLayout)
36065ffd83dbSDimitry Andric       return;
36075ffd83dbSDimitry Andric 
36085ffd83dbSDimitry Andric     // datalayout and triple can't be parsed after this point.
36095ffd83dbSDimitry Andric     ResolvedDataLayout = true;
36105ffd83dbSDimitry Andric 
36115ffd83dbSDimitry Andric     // Upgrade data layout string.
36125ffd83dbSDimitry Andric     std::string DL = llvm::UpgradeDataLayoutString(
36135ffd83dbSDimitry Andric         TheModule->getDataLayoutStr(), TheModule->getTargetTriple());
36145ffd83dbSDimitry Andric     TheModule->setDataLayout(DL);
36155ffd83dbSDimitry Andric 
36165ffd83dbSDimitry Andric     if (auto LayoutOverride =
36175ffd83dbSDimitry Andric             DataLayoutCallback(TheModule->getTargetTriple()))
36185ffd83dbSDimitry Andric       TheModule->setDataLayout(*LayoutOverride);
36195ffd83dbSDimitry Andric   };
36205ffd83dbSDimitry Andric 
3621*0b57cec5SDimitry Andric   // Read all the records for this module.
3622*0b57cec5SDimitry Andric   while (true) {
3623*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3624*0b57cec5SDimitry Andric     if (!MaybeEntry)
3625*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
3626*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
3627*0b57cec5SDimitry Andric 
3628*0b57cec5SDimitry Andric     switch (Entry.Kind) {
3629*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
3630*0b57cec5SDimitry Andric       return error("Malformed block");
3631*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
36325ffd83dbSDimitry Andric       ResolveDataLayout();
3633*0b57cec5SDimitry Andric       return globalCleanup();
3634*0b57cec5SDimitry Andric 
3635*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
3636*0b57cec5SDimitry Andric       switch (Entry.ID) {
3637*0b57cec5SDimitry Andric       default:  // Skip unknown content.
3638*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
3639*0b57cec5SDimitry Andric           return Err;
3640*0b57cec5SDimitry Andric         break;
3641*0b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
3642*0b57cec5SDimitry Andric         if (readBlockInfo())
3643*0b57cec5SDimitry Andric           return error("Malformed block");
3644*0b57cec5SDimitry Andric         break;
3645*0b57cec5SDimitry Andric       case bitc::PARAMATTR_BLOCK_ID:
3646*0b57cec5SDimitry Andric         if (Error Err = parseAttributeBlock())
3647*0b57cec5SDimitry Andric           return Err;
3648*0b57cec5SDimitry Andric         break;
3649*0b57cec5SDimitry Andric       case bitc::PARAMATTR_GROUP_BLOCK_ID:
3650*0b57cec5SDimitry Andric         if (Error Err = parseAttributeGroupBlock())
3651*0b57cec5SDimitry Andric           return Err;
3652*0b57cec5SDimitry Andric         break;
3653*0b57cec5SDimitry Andric       case bitc::TYPE_BLOCK_ID_NEW:
3654*0b57cec5SDimitry Andric         if (Error Err = parseTypeTable())
3655*0b57cec5SDimitry Andric           return Err;
3656*0b57cec5SDimitry Andric         break;
3657*0b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
3658*0b57cec5SDimitry Andric         if (!SeenValueSymbolTable) {
3659*0b57cec5SDimitry Andric           // Either this is an old form VST without function index and an
3660*0b57cec5SDimitry Andric           // associated VST forward declaration record (which would have caused
3661*0b57cec5SDimitry Andric           // the VST to be jumped to and parsed before it was encountered
3662*0b57cec5SDimitry Andric           // normally in the stream), or there were no function blocks to
3663*0b57cec5SDimitry Andric           // trigger an earlier parsing of the VST.
3664*0b57cec5SDimitry Andric           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3665*0b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable())
3666*0b57cec5SDimitry Andric             return Err;
3667*0b57cec5SDimitry Andric           SeenValueSymbolTable = true;
3668*0b57cec5SDimitry Andric         } else {
3669*0b57cec5SDimitry Andric           // We must have had a VST forward declaration record, which caused
3670*0b57cec5SDimitry Andric           // the parser to jump to and parse the VST earlier.
3671*0b57cec5SDimitry Andric           assert(VSTOffset > 0);
3672*0b57cec5SDimitry Andric           if (Error Err = Stream.SkipBlock())
3673*0b57cec5SDimitry Andric             return Err;
3674*0b57cec5SDimitry Andric         }
3675*0b57cec5SDimitry Andric         break;
3676*0b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
3677*0b57cec5SDimitry Andric         if (Error Err = parseConstants())
3678*0b57cec5SDimitry Andric           return Err;
3679*0b57cec5SDimitry Andric         if (Error Err = resolveGlobalAndIndirectSymbolInits())
3680*0b57cec5SDimitry Andric           return Err;
3681*0b57cec5SDimitry Andric         break;
3682*0b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
3683*0b57cec5SDimitry Andric         if (ShouldLazyLoadMetadata) {
3684*0b57cec5SDimitry Andric           if (Error Err = rememberAndSkipMetadata())
3685*0b57cec5SDimitry Andric             return Err;
3686*0b57cec5SDimitry Andric           break;
3687*0b57cec5SDimitry Andric         }
3688*0b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3689*0b57cec5SDimitry Andric         if (Error Err = MDLoader->parseModuleMetadata())
3690*0b57cec5SDimitry Andric           return Err;
3691*0b57cec5SDimitry Andric         break;
3692*0b57cec5SDimitry Andric       case bitc::METADATA_KIND_BLOCK_ID:
3693*0b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataKinds())
3694*0b57cec5SDimitry Andric           return Err;
3695*0b57cec5SDimitry Andric         break;
3696*0b57cec5SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
36975ffd83dbSDimitry Andric         ResolveDataLayout();
36985ffd83dbSDimitry Andric 
3699*0b57cec5SDimitry Andric         // If this is the first function body we've seen, reverse the
3700*0b57cec5SDimitry Andric         // FunctionsWithBodies list.
3701*0b57cec5SDimitry Andric         if (!SeenFirstFunctionBody) {
3702*0b57cec5SDimitry Andric           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3703*0b57cec5SDimitry Andric           if (Error Err = globalCleanup())
3704*0b57cec5SDimitry Andric             return Err;
3705*0b57cec5SDimitry Andric           SeenFirstFunctionBody = true;
3706*0b57cec5SDimitry Andric         }
3707*0b57cec5SDimitry Andric 
3708*0b57cec5SDimitry Andric         if (VSTOffset > 0) {
3709*0b57cec5SDimitry Andric           // If we have a VST forward declaration record, make sure we
3710*0b57cec5SDimitry Andric           // parse the VST now if we haven't already. It is needed to
3711*0b57cec5SDimitry Andric           // set up the DeferredFunctionInfo vector for lazy reading.
3712*0b57cec5SDimitry Andric           if (!SeenValueSymbolTable) {
3713*0b57cec5SDimitry Andric             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3714*0b57cec5SDimitry Andric               return Err;
3715*0b57cec5SDimitry Andric             SeenValueSymbolTable = true;
3716*0b57cec5SDimitry Andric             // Fall through so that we record the NextUnreadBit below.
3717*0b57cec5SDimitry Andric             // This is necessary in case we have an anonymous function that
3718*0b57cec5SDimitry Andric             // is later materialized. Since it will not have a VST entry we
3719*0b57cec5SDimitry Andric             // need to fall back to the lazy parse to find its offset.
3720*0b57cec5SDimitry Andric           } else {
3721*0b57cec5SDimitry Andric             // If we have a VST forward declaration record, but have already
3722*0b57cec5SDimitry Andric             // parsed the VST (just above, when the first function body was
3723*0b57cec5SDimitry Andric             // encountered here), then we are resuming the parse after
3724*0b57cec5SDimitry Andric             // materializing functions. The ResumeBit points to the
3725*0b57cec5SDimitry Andric             // start of the last function block recorded in the
3726*0b57cec5SDimitry Andric             // DeferredFunctionInfo map. Skip it.
3727*0b57cec5SDimitry Andric             if (Error Err = Stream.SkipBlock())
3728*0b57cec5SDimitry Andric               return Err;
3729*0b57cec5SDimitry Andric             continue;
3730*0b57cec5SDimitry Andric           }
3731*0b57cec5SDimitry Andric         }
3732*0b57cec5SDimitry Andric 
3733*0b57cec5SDimitry Andric         // Support older bitcode files that did not have the function
3734*0b57cec5SDimitry Andric         // index in the VST, nor a VST forward declaration record, as
3735*0b57cec5SDimitry Andric         // well as anonymous functions that do not have VST entries.
3736*0b57cec5SDimitry Andric         // Build the DeferredFunctionInfo vector on the fly.
3737*0b57cec5SDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
3738*0b57cec5SDimitry Andric           return Err;
3739*0b57cec5SDimitry Andric 
3740*0b57cec5SDimitry Andric         // Suspend parsing when we reach the function bodies. Subsequent
3741*0b57cec5SDimitry Andric         // materialization calls will resume it when necessary. If the bitcode
3742*0b57cec5SDimitry Andric         // file is old, the symbol table will be at the end instead and will not
3743*0b57cec5SDimitry Andric         // have been seen yet. In this case, just finish the parse now.
3744*0b57cec5SDimitry Andric         if (SeenValueSymbolTable) {
3745*0b57cec5SDimitry Andric           NextUnreadBit = Stream.GetCurrentBitNo();
3746*0b57cec5SDimitry Andric           // After the VST has been parsed, we need to make sure intrinsic name
3747*0b57cec5SDimitry Andric           // are auto-upgraded.
3748*0b57cec5SDimitry Andric           return globalCleanup();
3749*0b57cec5SDimitry Andric         }
3750*0b57cec5SDimitry Andric         break;
3751*0b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
3752*0b57cec5SDimitry Andric         if (Error Err = parseUseLists())
3753*0b57cec5SDimitry Andric           return Err;
3754*0b57cec5SDimitry Andric         break;
3755*0b57cec5SDimitry Andric       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3756*0b57cec5SDimitry Andric         if (Error Err = parseOperandBundleTags())
3757*0b57cec5SDimitry Andric           return Err;
3758*0b57cec5SDimitry Andric         break;
3759*0b57cec5SDimitry Andric       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3760*0b57cec5SDimitry Andric         if (Error Err = parseSyncScopeNames())
3761*0b57cec5SDimitry Andric           return Err;
3762*0b57cec5SDimitry Andric         break;
3763*0b57cec5SDimitry Andric       }
3764*0b57cec5SDimitry Andric       continue;
3765*0b57cec5SDimitry Andric 
3766*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
3767*0b57cec5SDimitry Andric       // The interesting case.
3768*0b57cec5SDimitry Andric       break;
3769*0b57cec5SDimitry Andric     }
3770*0b57cec5SDimitry Andric 
3771*0b57cec5SDimitry Andric     // Read a record.
3772*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3773*0b57cec5SDimitry Andric     if (!MaybeBitCode)
3774*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
3775*0b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
3776*0b57cec5SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
3777*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_VERSION: {
3778*0b57cec5SDimitry Andric       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3779*0b57cec5SDimitry Andric       if (!VersionOrErr)
3780*0b57cec5SDimitry Andric         return VersionOrErr.takeError();
3781*0b57cec5SDimitry Andric       UseRelativeIDs = *VersionOrErr >= 1;
3782*0b57cec5SDimitry Andric       break;
3783*0b57cec5SDimitry Andric     }
3784*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
37855ffd83dbSDimitry Andric       if (ResolvedDataLayout)
37865ffd83dbSDimitry Andric         return error("target triple too late in module");
3787*0b57cec5SDimitry Andric       std::string S;
3788*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
3789*0b57cec5SDimitry Andric         return error("Invalid record");
3790*0b57cec5SDimitry Andric       TheModule->setTargetTriple(S);
3791*0b57cec5SDimitry Andric       break;
3792*0b57cec5SDimitry Andric     }
3793*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
37945ffd83dbSDimitry Andric       if (ResolvedDataLayout)
37955ffd83dbSDimitry Andric         return error("datalayout too late in module");
3796*0b57cec5SDimitry Andric       std::string S;
3797*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
3798*0b57cec5SDimitry Andric         return error("Invalid record");
3799*0b57cec5SDimitry Andric       TheModule->setDataLayout(S);
3800*0b57cec5SDimitry Andric       break;
3801*0b57cec5SDimitry Andric     }
3802*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3803*0b57cec5SDimitry Andric       std::string S;
3804*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
3805*0b57cec5SDimitry Andric         return error("Invalid record");
3806*0b57cec5SDimitry Andric       TheModule->setModuleInlineAsm(S);
3807*0b57cec5SDimitry Andric       break;
3808*0b57cec5SDimitry Andric     }
3809*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
38105ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
3811*0b57cec5SDimitry Andric       std::string S;
3812*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
3813*0b57cec5SDimitry Andric         return error("Invalid record");
3814*0b57cec5SDimitry Andric       // Ignore value.
3815*0b57cec5SDimitry Andric       break;
3816*0b57cec5SDimitry Andric     }
3817*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3818*0b57cec5SDimitry Andric       std::string S;
3819*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
3820*0b57cec5SDimitry Andric         return error("Invalid record");
3821*0b57cec5SDimitry Andric       SectionTable.push_back(S);
3822*0b57cec5SDimitry Andric       break;
3823*0b57cec5SDimitry Andric     }
3824*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3825*0b57cec5SDimitry Andric       std::string S;
3826*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
3827*0b57cec5SDimitry Andric         return error("Invalid record");
3828*0b57cec5SDimitry Andric       GCTable.push_back(S);
3829*0b57cec5SDimitry Andric       break;
3830*0b57cec5SDimitry Andric     }
3831*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_COMDAT:
3832*0b57cec5SDimitry Andric       if (Error Err = parseComdatRecord(Record))
3833*0b57cec5SDimitry Andric         return Err;
3834*0b57cec5SDimitry Andric       break;
383504eeddc0SDimitry Andric     // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
383604eeddc0SDimitry Andric     // written by ThinLinkBitcodeWriter. See
383704eeddc0SDimitry Andric     // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
383804eeddc0SDimitry Andric     // record
383904eeddc0SDimitry Andric     // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
3840*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_GLOBALVAR:
3841*0b57cec5SDimitry Andric       if (Error Err = parseGlobalVarRecord(Record))
3842*0b57cec5SDimitry Andric         return Err;
3843*0b57cec5SDimitry Andric       break;
3844*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_FUNCTION:
38455ffd83dbSDimitry Andric       ResolveDataLayout();
3846*0b57cec5SDimitry Andric       if (Error Err = parseFunctionRecord(Record))
3847*0b57cec5SDimitry Andric         return Err;
3848*0b57cec5SDimitry Andric       break;
3849*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_IFUNC:
3850*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS:
3851*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS_OLD:
3852*0b57cec5SDimitry Andric       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3853*0b57cec5SDimitry Andric         return Err;
3854*0b57cec5SDimitry Andric       break;
3855*0b57cec5SDimitry Andric     /// MODULE_CODE_VSTOFFSET: [offset]
3856*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_VSTOFFSET:
3857e8d8bef9SDimitry Andric       if (Record.empty())
3858*0b57cec5SDimitry Andric         return error("Invalid record");
3859*0b57cec5SDimitry Andric       // Note that we subtract 1 here because the offset is relative to one word
3860*0b57cec5SDimitry Andric       // before the start of the identification or module block, which was
3861*0b57cec5SDimitry Andric       // historically always the start of the regular bitcode header.
3862*0b57cec5SDimitry Andric       VSTOffset = Record[0] - 1;
3863*0b57cec5SDimitry Andric       break;
3864*0b57cec5SDimitry Andric     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3865*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_SOURCE_FILENAME:
3866*0b57cec5SDimitry Andric       SmallString<128> ValueName;
3867*0b57cec5SDimitry Andric       if (convertToString(Record, 0, ValueName))
3868*0b57cec5SDimitry Andric         return error("Invalid record");
3869*0b57cec5SDimitry Andric       TheModule->setSourceFileName(ValueName);
3870*0b57cec5SDimitry Andric       break;
3871*0b57cec5SDimitry Andric     }
3872*0b57cec5SDimitry Andric     Record.clear();
3873*0b57cec5SDimitry Andric   }
3874*0b57cec5SDimitry Andric }
3875*0b57cec5SDimitry Andric 
3876*0b57cec5SDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
38775ffd83dbSDimitry Andric                                       bool IsImporting,
38785ffd83dbSDimitry Andric                                       DataLayoutCallbackTy DataLayoutCallback) {
3879*0b57cec5SDimitry Andric   TheModule = M;
3880*0b57cec5SDimitry Andric   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3881*0b57cec5SDimitry Andric                             [&](unsigned ID) { return getTypeByID(ID); });
38825ffd83dbSDimitry Andric   return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback);
3883*0b57cec5SDimitry Andric }
3884*0b57cec5SDimitry Andric 
3885*0b57cec5SDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3886*0b57cec5SDimitry Andric   if (!isa<PointerType>(PtrType))
3887*0b57cec5SDimitry Andric     return error("Load/Store operand is not a pointer type");
3888*0b57cec5SDimitry Andric 
3889fe6060f1SDimitry Andric   if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType))
3890*0b57cec5SDimitry Andric     return error("Explicit load/store type does not match pointee "
3891*0b57cec5SDimitry Andric                  "type of pointer operand");
3892fe6060f1SDimitry Andric   if (!PointerType::isLoadableOrStorableType(ValType))
3893*0b57cec5SDimitry Andric     return error("Cannot load/store from pointer");
3894*0b57cec5SDimitry Andric   return Error::success();
3895*0b57cec5SDimitry Andric }
3896*0b57cec5SDimitry Andric 
3897fe6060f1SDimitry Andric void BitcodeReader::propagateAttributeTypes(CallBase *CB,
3898fe6060f1SDimitry Andric                                             ArrayRef<Type *> ArgsTys) {
3899*0b57cec5SDimitry Andric   for (unsigned i = 0; i != CB->arg_size(); ++i) {
3900fe6060f1SDimitry Andric     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3901fe6060f1SDimitry Andric                                      Attribute::InAlloca}) {
390204eeddc0SDimitry Andric       if (!CB->paramHasAttr(i, Kind) ||
390304eeddc0SDimitry Andric           CB->getParamAttr(i, Kind).getValueAsType())
3904*0b57cec5SDimitry Andric         continue;
3905*0b57cec5SDimitry Andric 
3906e8d8bef9SDimitry Andric       CB->removeParamAttr(i, Kind);
3907e8d8bef9SDimitry Andric 
390804eeddc0SDimitry Andric       Type *PtrEltTy = ArgsTys[i]->getPointerElementType();
3909fe6060f1SDimitry Andric       Attribute NewAttr;
3910fe6060f1SDimitry Andric       switch (Kind) {
3911fe6060f1SDimitry Andric       case Attribute::ByVal:
3912fe6060f1SDimitry Andric         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3913fe6060f1SDimitry Andric         break;
3914fe6060f1SDimitry Andric       case Attribute::StructRet:
3915fe6060f1SDimitry Andric         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3916fe6060f1SDimitry Andric         break;
3917fe6060f1SDimitry Andric       case Attribute::InAlloca:
3918fe6060f1SDimitry Andric         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3919fe6060f1SDimitry Andric         break;
3920fe6060f1SDimitry Andric       default:
3921fe6060f1SDimitry Andric         llvm_unreachable("not an upgraded type attribute");
3922fe6060f1SDimitry Andric       }
3923fe6060f1SDimitry Andric 
3924e8d8bef9SDimitry Andric       CB->addParamAttr(i, NewAttr);
3925e8d8bef9SDimitry Andric     }
3926*0b57cec5SDimitry Andric   }
3927fe6060f1SDimitry Andric 
392804eeddc0SDimitry Andric   if (CB->isInlineAsm()) {
392904eeddc0SDimitry Andric     const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
393004eeddc0SDimitry Andric     unsigned ArgNo = 0;
393104eeddc0SDimitry Andric     for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
393204eeddc0SDimitry Andric       if (!CI.hasArg())
393304eeddc0SDimitry Andric         continue;
393404eeddc0SDimitry Andric 
393504eeddc0SDimitry Andric       if (CI.isIndirect && !CB->getAttributes().getParamElementType(ArgNo)) {
393604eeddc0SDimitry Andric         Type *ElemTy = ArgsTys[ArgNo]->getPointerElementType();
393704eeddc0SDimitry Andric         CB->addParamAttr(
393804eeddc0SDimitry Andric             ArgNo, Attribute::get(Context, Attribute::ElementType, ElemTy));
393904eeddc0SDimitry Andric       }
394004eeddc0SDimitry Andric 
394104eeddc0SDimitry Andric       ArgNo++;
394204eeddc0SDimitry Andric     }
394304eeddc0SDimitry Andric   }
394404eeddc0SDimitry Andric 
3945fe6060f1SDimitry Andric   switch (CB->getIntrinsicID()) {
3946fe6060f1SDimitry Andric   case Intrinsic::preserve_array_access_index:
3947fe6060f1SDimitry Andric   case Intrinsic::preserve_struct_access_index:
3948fe6060f1SDimitry Andric     if (!CB->getAttributes().getParamElementType(0)) {
394904eeddc0SDimitry Andric       Type *ElTy = ArgsTys[0]->getPointerElementType();
3950fe6060f1SDimitry Andric       Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
3951fe6060f1SDimitry Andric       CB->addParamAttr(0, NewAttr);
3952fe6060f1SDimitry Andric     }
3953fe6060f1SDimitry Andric     break;
3954fe6060f1SDimitry Andric   default:
3955fe6060f1SDimitry Andric     break;
3956fe6060f1SDimitry Andric   }
3957*0b57cec5SDimitry Andric }
3958*0b57cec5SDimitry Andric 
3959*0b57cec5SDimitry Andric /// Lazily parse the specified function body block.
3960*0b57cec5SDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) {
3961*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3962*0b57cec5SDimitry Andric     return Err;
3963*0b57cec5SDimitry Andric 
3964*0b57cec5SDimitry Andric   // Unexpected unresolved metadata when parsing function.
3965*0b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
3966*0b57cec5SDimitry Andric     return error("Invalid function metadata: incoming forward references");
3967*0b57cec5SDimitry Andric 
3968*0b57cec5SDimitry Andric   InstructionList.clear();
3969*0b57cec5SDimitry Andric   unsigned ModuleValueListSize = ValueList.size();
3970*0b57cec5SDimitry Andric   unsigned ModuleMDLoaderSize = MDLoader->size();
3971*0b57cec5SDimitry Andric 
3972*0b57cec5SDimitry Andric   // Add all the function arguments to the value table.
3973fe6060f1SDimitry Andric #ifndef NDEBUG
3974*0b57cec5SDimitry Andric   unsigned ArgNo = 0;
3975fe6060f1SDimitry Andric   FunctionType *FTy = FunctionTypes[F];
3976fe6060f1SDimitry Andric #endif
3977*0b57cec5SDimitry Andric   for (Argument &I : F->args()) {
3978fe6060f1SDimitry Andric     assert(I.getType() == FTy->getParamType(ArgNo++) &&
3979*0b57cec5SDimitry Andric            "Incorrect fully specified type for Function Argument");
3980fe6060f1SDimitry Andric     ValueList.push_back(&I);
3981*0b57cec5SDimitry Andric   }
3982*0b57cec5SDimitry Andric   unsigned NextValueNo = ValueList.size();
3983*0b57cec5SDimitry Andric   BasicBlock *CurBB = nullptr;
3984*0b57cec5SDimitry Andric   unsigned CurBBNo = 0;
3985*0b57cec5SDimitry Andric 
3986*0b57cec5SDimitry Andric   DebugLoc LastLoc;
3987*0b57cec5SDimitry Andric   auto getLastInstruction = [&]() -> Instruction * {
3988*0b57cec5SDimitry Andric     if (CurBB && !CurBB->empty())
3989*0b57cec5SDimitry Andric       return &CurBB->back();
3990*0b57cec5SDimitry Andric     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3991*0b57cec5SDimitry Andric              !FunctionBBs[CurBBNo - 1]->empty())
3992*0b57cec5SDimitry Andric       return &FunctionBBs[CurBBNo - 1]->back();
3993*0b57cec5SDimitry Andric     return nullptr;
3994*0b57cec5SDimitry Andric   };
3995*0b57cec5SDimitry Andric 
3996*0b57cec5SDimitry Andric   std::vector<OperandBundleDef> OperandBundles;
3997*0b57cec5SDimitry Andric 
3998*0b57cec5SDimitry Andric   // Read all the records.
3999*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
4000*0b57cec5SDimitry Andric 
4001*0b57cec5SDimitry Andric   while (true) {
4002*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4003*0b57cec5SDimitry Andric     if (!MaybeEntry)
4004*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
4005*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
4006*0b57cec5SDimitry Andric 
4007*0b57cec5SDimitry Andric     switch (Entry.Kind) {
4008*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
4009*0b57cec5SDimitry Andric       return error("Malformed block");
4010*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
4011*0b57cec5SDimitry Andric       goto OutOfRecordLoop;
4012*0b57cec5SDimitry Andric 
4013*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
4014*0b57cec5SDimitry Andric       switch (Entry.ID) {
4015*0b57cec5SDimitry Andric       default:  // Skip unknown content.
4016*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
4017*0b57cec5SDimitry Andric           return Err;
4018*0b57cec5SDimitry Andric         break;
4019*0b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
4020*0b57cec5SDimitry Andric         if (Error Err = parseConstants())
4021*0b57cec5SDimitry Andric           return Err;
4022*0b57cec5SDimitry Andric         NextValueNo = ValueList.size();
4023*0b57cec5SDimitry Andric         break;
4024*0b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
4025*0b57cec5SDimitry Andric         if (Error Err = parseValueSymbolTable())
4026*0b57cec5SDimitry Andric           return Err;
4027*0b57cec5SDimitry Andric         break;
4028*0b57cec5SDimitry Andric       case bitc::METADATA_ATTACHMENT_ID:
4029*0b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
4030*0b57cec5SDimitry Andric           return Err;
4031*0b57cec5SDimitry Andric         break;
4032*0b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
4033*0b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() &&
4034*0b57cec5SDimitry Andric                "Must read all module-level metadata before function-level");
4035*0b57cec5SDimitry Andric         if (Error Err = MDLoader->parseFunctionMetadata())
4036*0b57cec5SDimitry Andric           return Err;
4037*0b57cec5SDimitry Andric         break;
4038*0b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
4039*0b57cec5SDimitry Andric         if (Error Err = parseUseLists())
4040*0b57cec5SDimitry Andric           return Err;
4041*0b57cec5SDimitry Andric         break;
4042*0b57cec5SDimitry Andric       }
4043*0b57cec5SDimitry Andric       continue;
4044*0b57cec5SDimitry Andric 
4045*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
4046*0b57cec5SDimitry Andric       // The interesting case.
4047*0b57cec5SDimitry Andric       break;
4048*0b57cec5SDimitry Andric     }
4049*0b57cec5SDimitry Andric 
4050*0b57cec5SDimitry Andric     // Read a record.
4051*0b57cec5SDimitry Andric     Record.clear();
4052*0b57cec5SDimitry Andric     Instruction *I = nullptr;
4053*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4054*0b57cec5SDimitry Andric     if (!MaybeBitCode)
4055*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
4056*0b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
4057*0b57cec5SDimitry Andric     default: // Default behavior: reject
4058*0b57cec5SDimitry Andric       return error("Invalid value");
4059*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4060e8d8bef9SDimitry Andric       if (Record.empty() || Record[0] == 0)
4061*0b57cec5SDimitry Andric         return error("Invalid record");
4062*0b57cec5SDimitry Andric       // Create all the basic blocks for the function.
4063*0b57cec5SDimitry Andric       FunctionBBs.resize(Record[0]);
4064*0b57cec5SDimitry Andric 
4065*0b57cec5SDimitry Andric       // See if anything took the address of blocks in this function.
4066*0b57cec5SDimitry Andric       auto BBFRI = BasicBlockFwdRefs.find(F);
4067*0b57cec5SDimitry Andric       if (BBFRI == BasicBlockFwdRefs.end()) {
40684824e7fdSDimitry Andric         for (BasicBlock *&BB : FunctionBBs)
40694824e7fdSDimitry Andric           BB = BasicBlock::Create(Context, "", F);
4070*0b57cec5SDimitry Andric       } else {
4071*0b57cec5SDimitry Andric         auto &BBRefs = BBFRI->second;
4072*0b57cec5SDimitry Andric         // Check for invalid basic block references.
4073*0b57cec5SDimitry Andric         if (BBRefs.size() > FunctionBBs.size())
4074*0b57cec5SDimitry Andric           return error("Invalid ID");
4075*0b57cec5SDimitry Andric         assert(!BBRefs.empty() && "Unexpected empty array");
4076*0b57cec5SDimitry Andric         assert(!BBRefs.front() && "Invalid reference to entry block");
4077*0b57cec5SDimitry Andric         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4078*0b57cec5SDimitry Andric              ++I)
4079*0b57cec5SDimitry Andric           if (I < RE && BBRefs[I]) {
4080*0b57cec5SDimitry Andric             BBRefs[I]->insertInto(F);
4081*0b57cec5SDimitry Andric             FunctionBBs[I] = BBRefs[I];
4082*0b57cec5SDimitry Andric           } else {
4083*0b57cec5SDimitry Andric             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4084*0b57cec5SDimitry Andric           }
4085*0b57cec5SDimitry Andric 
4086*0b57cec5SDimitry Andric         // Erase from the table.
4087*0b57cec5SDimitry Andric         BasicBlockFwdRefs.erase(BBFRI);
4088*0b57cec5SDimitry Andric       }
4089*0b57cec5SDimitry Andric 
4090*0b57cec5SDimitry Andric       CurBB = FunctionBBs[0];
4091*0b57cec5SDimitry Andric       continue;
4092*0b57cec5SDimitry Andric     }
4093*0b57cec5SDimitry Andric 
4094*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4095*0b57cec5SDimitry Andric       // This record indicates that the last instruction is at the same
4096*0b57cec5SDimitry Andric       // location as the previous instruction with a location.
4097*0b57cec5SDimitry Andric       I = getLastInstruction();
4098*0b57cec5SDimitry Andric 
4099*0b57cec5SDimitry Andric       if (!I)
4100*0b57cec5SDimitry Andric         return error("Invalid record");
4101*0b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
4102*0b57cec5SDimitry Andric       I = nullptr;
4103*0b57cec5SDimitry Andric       continue;
4104*0b57cec5SDimitry Andric 
4105*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
4106*0b57cec5SDimitry Andric       I = getLastInstruction();
4107*0b57cec5SDimitry Andric       if (!I || Record.size() < 4)
4108*0b57cec5SDimitry Andric         return error("Invalid record");
4109*0b57cec5SDimitry Andric 
4110*0b57cec5SDimitry Andric       unsigned Line = Record[0], Col = Record[1];
4111*0b57cec5SDimitry Andric       unsigned ScopeID = Record[2], IAID = Record[3];
4112*0b57cec5SDimitry Andric       bool isImplicitCode = Record.size() == 5 && Record[4];
4113*0b57cec5SDimitry Andric 
4114*0b57cec5SDimitry Andric       MDNode *Scope = nullptr, *IA = nullptr;
4115*0b57cec5SDimitry Andric       if (ScopeID) {
4116*0b57cec5SDimitry Andric         Scope = dyn_cast_or_null<MDNode>(
4117*0b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
4118*0b57cec5SDimitry Andric         if (!Scope)
4119*0b57cec5SDimitry Andric           return error("Invalid record");
4120*0b57cec5SDimitry Andric       }
4121*0b57cec5SDimitry Andric       if (IAID) {
4122*0b57cec5SDimitry Andric         IA = dyn_cast_or_null<MDNode>(
4123*0b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
4124*0b57cec5SDimitry Andric         if (!IA)
4125*0b57cec5SDimitry Andric           return error("Invalid record");
4126*0b57cec5SDimitry Andric       }
4127e8d8bef9SDimitry Andric       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4128e8d8bef9SDimitry Andric                                 isImplicitCode);
4129*0b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
4130*0b57cec5SDimitry Andric       I = nullptr;
4131*0b57cec5SDimitry Andric       continue;
4132*0b57cec5SDimitry Andric     }
4133*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
4134*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4135*0b57cec5SDimitry Andric       Value *LHS;
4136*0b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4137*0b57cec5SDimitry Andric           OpNum+1 > Record.size())
4138*0b57cec5SDimitry Andric         return error("Invalid record");
4139*0b57cec5SDimitry Andric 
4140*0b57cec5SDimitry Andric       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
4141*0b57cec5SDimitry Andric       if (Opc == -1)
4142*0b57cec5SDimitry Andric         return error("Invalid record");
4143*0b57cec5SDimitry Andric       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
4144*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4145*0b57cec5SDimitry Andric       if (OpNum < Record.size()) {
4146*0b57cec5SDimitry Andric         if (isa<FPMathOperator>(I)) {
4147*0b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4148*0b57cec5SDimitry Andric           if (FMF.any())
4149*0b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
4150*0b57cec5SDimitry Andric         }
4151*0b57cec5SDimitry Andric       }
4152*0b57cec5SDimitry Andric       break;
4153*0b57cec5SDimitry Andric     }
4154*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4155*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4156*0b57cec5SDimitry Andric       Value *LHS, *RHS;
4157*0b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4158*0b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4159*0b57cec5SDimitry Andric           OpNum+1 > Record.size())
4160*0b57cec5SDimitry Andric         return error("Invalid record");
4161*0b57cec5SDimitry Andric 
4162*0b57cec5SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4163*0b57cec5SDimitry Andric       if (Opc == -1)
4164*0b57cec5SDimitry Andric         return error("Invalid record");
4165*0b57cec5SDimitry Andric       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4166*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4167*0b57cec5SDimitry Andric       if (OpNum < Record.size()) {
4168*0b57cec5SDimitry Andric         if (Opc == Instruction::Add ||
4169*0b57cec5SDimitry Andric             Opc == Instruction::Sub ||
4170*0b57cec5SDimitry Andric             Opc == Instruction::Mul ||
4171*0b57cec5SDimitry Andric             Opc == Instruction::Shl) {
4172*0b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4173*0b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4174*0b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4175*0b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4176*0b57cec5SDimitry Andric         } else if (Opc == Instruction::SDiv ||
4177*0b57cec5SDimitry Andric                    Opc == Instruction::UDiv ||
4178*0b57cec5SDimitry Andric                    Opc == Instruction::LShr ||
4179*0b57cec5SDimitry Andric                    Opc == Instruction::AShr) {
4180*0b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4181*0b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setIsExact(true);
4182*0b57cec5SDimitry Andric         } else if (isa<FPMathOperator>(I)) {
4183*0b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4184*0b57cec5SDimitry Andric           if (FMF.any())
4185*0b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
4186*0b57cec5SDimitry Andric         }
4187*0b57cec5SDimitry Andric 
4188*0b57cec5SDimitry Andric       }
4189*0b57cec5SDimitry Andric       break;
4190*0b57cec5SDimitry Andric     }
4191*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4192*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4193*0b57cec5SDimitry Andric       Value *Op;
4194*0b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4195*0b57cec5SDimitry Andric           OpNum+2 != Record.size())
4196*0b57cec5SDimitry Andric         return error("Invalid record");
4197*0b57cec5SDimitry Andric 
4198fe6060f1SDimitry Andric       Type *ResTy = getTypeByID(Record[OpNum]);
4199*0b57cec5SDimitry Andric       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4200*0b57cec5SDimitry Andric       if (Opc == -1 || !ResTy)
4201*0b57cec5SDimitry Andric         return error("Invalid record");
4202*0b57cec5SDimitry Andric       Instruction *Temp = nullptr;
4203*0b57cec5SDimitry Andric       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4204*0b57cec5SDimitry Andric         if (Temp) {
4205*0b57cec5SDimitry Andric           InstructionList.push_back(Temp);
4206480093f4SDimitry Andric           assert(CurBB && "No current BB?");
4207*0b57cec5SDimitry Andric           CurBB->getInstList().push_back(Temp);
4208*0b57cec5SDimitry Andric         }
4209*0b57cec5SDimitry Andric       } else {
4210*0b57cec5SDimitry Andric         auto CastOp = (Instruction::CastOps)Opc;
4211*0b57cec5SDimitry Andric         if (!CastInst::castIsValid(CastOp, Op, ResTy))
4212*0b57cec5SDimitry Andric           return error("Invalid cast");
4213*0b57cec5SDimitry Andric         I = CastInst::Create(CastOp, Op, ResTy);
4214*0b57cec5SDimitry Andric       }
4215*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4216*0b57cec5SDimitry Andric       break;
4217*0b57cec5SDimitry Andric     }
4218*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4219*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP_OLD:
4220*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4221*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4222*0b57cec5SDimitry Andric 
4223*0b57cec5SDimitry Andric       Type *Ty;
4224*0b57cec5SDimitry Andric       bool InBounds;
4225*0b57cec5SDimitry Andric 
4226*0b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4227*0b57cec5SDimitry Andric         InBounds = Record[OpNum++];
4228fe6060f1SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
4229*0b57cec5SDimitry Andric       } else {
4230*0b57cec5SDimitry Andric         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4231*0b57cec5SDimitry Andric         Ty = nullptr;
4232*0b57cec5SDimitry Andric       }
4233*0b57cec5SDimitry Andric 
4234*0b57cec5SDimitry Andric       Value *BasePtr;
4235fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4236*0b57cec5SDimitry Andric         return error("Invalid record");
4237*0b57cec5SDimitry Andric 
4238*0b57cec5SDimitry Andric       if (!Ty) {
423904eeddc0SDimitry Andric         Ty = BasePtr->getType()->getScalarType()->getPointerElementType();
4240fe6060f1SDimitry Andric       } else if (!cast<PointerType>(BasePtr->getType()->getScalarType())
4241fe6060f1SDimitry Andric                       ->isOpaqueOrPointeeTypeMatches(Ty)) {
4242*0b57cec5SDimitry Andric         return error(
4243*0b57cec5SDimitry Andric             "Explicit gep type does not match pointee type of pointer operand");
4244fe6060f1SDimitry Andric       }
4245*0b57cec5SDimitry Andric 
4246*0b57cec5SDimitry Andric       SmallVector<Value*, 16> GEPIdx;
4247*0b57cec5SDimitry Andric       while (OpNum != Record.size()) {
4248*0b57cec5SDimitry Andric         Value *Op;
4249*0b57cec5SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4250*0b57cec5SDimitry Andric           return error("Invalid record");
4251*0b57cec5SDimitry Andric         GEPIdx.push_back(Op);
4252*0b57cec5SDimitry Andric       }
4253*0b57cec5SDimitry Andric 
4254*0b57cec5SDimitry Andric       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4255*0b57cec5SDimitry Andric 
4256*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4257*0b57cec5SDimitry Andric       if (InBounds)
4258*0b57cec5SDimitry Andric         cast<GetElementPtrInst>(I)->setIsInBounds(true);
4259*0b57cec5SDimitry Andric       break;
4260*0b57cec5SDimitry Andric     }
4261*0b57cec5SDimitry Andric 
4262*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4263*0b57cec5SDimitry Andric                                        // EXTRACTVAL: [opty, opval, n x indices]
4264*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4265*0b57cec5SDimitry Andric       Value *Agg;
4266fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4267*0b57cec5SDimitry Andric         return error("Invalid record");
4268fe6060f1SDimitry Andric       Type *Ty = Agg->getType();
4269*0b57cec5SDimitry Andric 
4270*0b57cec5SDimitry Andric       unsigned RecSize = Record.size();
4271*0b57cec5SDimitry Andric       if (OpNum == RecSize)
4272*0b57cec5SDimitry Andric         return error("EXTRACTVAL: Invalid instruction with 0 indices");
4273*0b57cec5SDimitry Andric 
4274*0b57cec5SDimitry Andric       SmallVector<unsigned, 4> EXTRACTVALIdx;
4275*0b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
4276fe6060f1SDimitry Andric         bool IsArray = Ty->isArrayTy();
4277fe6060f1SDimitry Andric         bool IsStruct = Ty->isStructTy();
4278*0b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
4279*0b57cec5SDimitry Andric 
4280*0b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
4281*0b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid type");
4282*0b57cec5SDimitry Andric         if ((unsigned)Index != Index)
4283*0b57cec5SDimitry Andric           return error("Invalid value");
4284fe6060f1SDimitry Andric         if (IsStruct && Index >= Ty->getStructNumElements())
4285*0b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid struct index");
4286fe6060f1SDimitry Andric         if (IsArray && Index >= Ty->getArrayNumElements())
4287*0b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid array index");
4288*0b57cec5SDimitry Andric         EXTRACTVALIdx.push_back((unsigned)Index);
4289*0b57cec5SDimitry Andric 
4290*0b57cec5SDimitry Andric         if (IsStruct)
4291fe6060f1SDimitry Andric           Ty = Ty->getStructElementType(Index);
4292*0b57cec5SDimitry Andric         else
4293fe6060f1SDimitry Andric           Ty = Ty->getArrayElementType();
4294*0b57cec5SDimitry Andric       }
4295*0b57cec5SDimitry Andric 
4296*0b57cec5SDimitry Andric       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4297*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4298*0b57cec5SDimitry Andric       break;
4299*0b57cec5SDimitry Andric     }
4300*0b57cec5SDimitry Andric 
4301*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTVAL: {
4302*0b57cec5SDimitry Andric                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
4303*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4304*0b57cec5SDimitry Andric       Value *Agg;
4305fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4306*0b57cec5SDimitry Andric         return error("Invalid record");
4307*0b57cec5SDimitry Andric       Value *Val;
4308*0b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4309*0b57cec5SDimitry Andric         return error("Invalid record");
4310*0b57cec5SDimitry Andric 
4311*0b57cec5SDimitry Andric       unsigned RecSize = Record.size();
4312*0b57cec5SDimitry Andric       if (OpNum == RecSize)
4313*0b57cec5SDimitry Andric         return error("INSERTVAL: Invalid instruction with 0 indices");
4314*0b57cec5SDimitry Andric 
4315*0b57cec5SDimitry Andric       SmallVector<unsigned, 4> INSERTVALIdx;
4316*0b57cec5SDimitry Andric       Type *CurTy = Agg->getType();
4317*0b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
4318*0b57cec5SDimitry Andric         bool IsArray = CurTy->isArrayTy();
4319*0b57cec5SDimitry Andric         bool IsStruct = CurTy->isStructTy();
4320*0b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
4321*0b57cec5SDimitry Andric 
4322*0b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
4323*0b57cec5SDimitry Andric           return error("INSERTVAL: Invalid type");
4324*0b57cec5SDimitry Andric         if ((unsigned)Index != Index)
4325*0b57cec5SDimitry Andric           return error("Invalid value");
4326*0b57cec5SDimitry Andric         if (IsStruct && Index >= CurTy->getStructNumElements())
4327*0b57cec5SDimitry Andric           return error("INSERTVAL: Invalid struct index");
4328*0b57cec5SDimitry Andric         if (IsArray && Index >= CurTy->getArrayNumElements())
4329*0b57cec5SDimitry Andric           return error("INSERTVAL: Invalid array index");
4330*0b57cec5SDimitry Andric 
4331*0b57cec5SDimitry Andric         INSERTVALIdx.push_back((unsigned)Index);
4332*0b57cec5SDimitry Andric         if (IsStruct)
4333*0b57cec5SDimitry Andric           CurTy = CurTy->getStructElementType(Index);
4334*0b57cec5SDimitry Andric         else
4335*0b57cec5SDimitry Andric           CurTy = CurTy->getArrayElementType();
4336*0b57cec5SDimitry Andric       }
4337*0b57cec5SDimitry Andric 
4338*0b57cec5SDimitry Andric       if (CurTy != Val->getType())
4339*0b57cec5SDimitry Andric         return error("Inserted value type doesn't match aggregate type");
4340*0b57cec5SDimitry Andric 
4341*0b57cec5SDimitry Andric       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4342*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4343*0b57cec5SDimitry Andric       break;
4344*0b57cec5SDimitry Andric     }
4345*0b57cec5SDimitry Andric 
4346*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4347*0b57cec5SDimitry Andric       // obsolete form of select
4348*0b57cec5SDimitry Andric       // handles select i1 ... in old bitcode
4349*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4350*0b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
4351fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4352*0b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4353*0b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4354*0b57cec5SDimitry Andric         return error("Invalid record");
4355*0b57cec5SDimitry Andric 
4356*0b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4357*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4358*0b57cec5SDimitry Andric       break;
4359*0b57cec5SDimitry Andric     }
4360*0b57cec5SDimitry Andric 
4361*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4362*0b57cec5SDimitry Andric       // new form of select
4363*0b57cec5SDimitry Andric       // handles select i1 or select [N x i1]
4364*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4365*0b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
4366fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4367*0b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4368*0b57cec5SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Cond))
4369*0b57cec5SDimitry Andric         return error("Invalid record");
4370*0b57cec5SDimitry Andric 
4371*0b57cec5SDimitry Andric       // select condition can be either i1 or [N x i1]
4372*0b57cec5SDimitry Andric       if (VectorType* vector_type =
4373*0b57cec5SDimitry Andric           dyn_cast<VectorType>(Cond->getType())) {
4374*0b57cec5SDimitry Andric         // expect <n x i1>
4375*0b57cec5SDimitry Andric         if (vector_type->getElementType() != Type::getInt1Ty(Context))
4376*0b57cec5SDimitry Andric           return error("Invalid type for value");
4377*0b57cec5SDimitry Andric       } else {
4378*0b57cec5SDimitry Andric         // expect i1
4379*0b57cec5SDimitry Andric         if (Cond->getType() != Type::getInt1Ty(Context))
4380*0b57cec5SDimitry Andric           return error("Invalid type for value");
4381*0b57cec5SDimitry Andric       }
4382*0b57cec5SDimitry Andric 
4383*0b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4384*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4385*0b57cec5SDimitry Andric       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
4386*0b57cec5SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4387*0b57cec5SDimitry Andric         if (FMF.any())
4388*0b57cec5SDimitry Andric           I->setFastMathFlags(FMF);
4389*0b57cec5SDimitry Andric       }
4390*0b57cec5SDimitry Andric       break;
4391*0b57cec5SDimitry Andric     }
4392*0b57cec5SDimitry Andric 
4393*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4394*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4395*0b57cec5SDimitry Andric       Value *Vec, *Idx;
4396fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4397*0b57cec5SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4398*0b57cec5SDimitry Andric         return error("Invalid record");
4399*0b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
4400*0b57cec5SDimitry Andric         return error("Invalid type for value");
4401*0b57cec5SDimitry Andric       I = ExtractElementInst::Create(Vec, Idx);
4402*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4403*0b57cec5SDimitry Andric       break;
4404*0b57cec5SDimitry Andric     }
4405*0b57cec5SDimitry Andric 
4406*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4407*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4408*0b57cec5SDimitry Andric       Value *Vec, *Elt, *Idx;
4409fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4410*0b57cec5SDimitry Andric         return error("Invalid record");
4411*0b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
4412*0b57cec5SDimitry Andric         return error("Invalid type for value");
4413*0b57cec5SDimitry Andric       if (popValue(Record, OpNum, NextValueNo,
4414*0b57cec5SDimitry Andric                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4415*0b57cec5SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4416*0b57cec5SDimitry Andric         return error("Invalid record");
4417*0b57cec5SDimitry Andric       I = InsertElementInst::Create(Vec, Elt, Idx);
4418*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4419*0b57cec5SDimitry Andric       break;
4420*0b57cec5SDimitry Andric     }
4421*0b57cec5SDimitry Andric 
4422*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4423*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4424*0b57cec5SDimitry Andric       Value *Vec1, *Vec2, *Mask;
4425fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4426*0b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4427*0b57cec5SDimitry Andric         return error("Invalid record");
4428*0b57cec5SDimitry Andric 
4429*0b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4430*0b57cec5SDimitry Andric         return error("Invalid record");
4431*0b57cec5SDimitry Andric       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4432*0b57cec5SDimitry Andric         return error("Invalid type for value");
44335ffd83dbSDimitry Andric 
4434*0b57cec5SDimitry Andric       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4435*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4436*0b57cec5SDimitry Andric       break;
4437*0b57cec5SDimitry Andric     }
4438*0b57cec5SDimitry Andric 
4439*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
4440*0b57cec5SDimitry Andric       // Old form of ICmp/FCmp returning bool
4441*0b57cec5SDimitry Andric       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4442*0b57cec5SDimitry Andric       // both legal on vectors but had different behaviour.
4443*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4444*0b57cec5SDimitry Andric       // FCmp/ICmp returning bool or vector of bool
4445*0b57cec5SDimitry Andric 
4446*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4447*0b57cec5SDimitry Andric       Value *LHS, *RHS;
4448*0b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4449*0b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4450*0b57cec5SDimitry Andric         return error("Invalid record");
4451*0b57cec5SDimitry Andric 
4452*0b57cec5SDimitry Andric       if (OpNum >= Record.size())
4453*0b57cec5SDimitry Andric         return error(
4454*0b57cec5SDimitry Andric             "Invalid record: operand number exceeded available operands");
4455*0b57cec5SDimitry Andric 
4456*0b57cec5SDimitry Andric       unsigned PredVal = Record[OpNum];
4457*0b57cec5SDimitry Andric       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4458*0b57cec5SDimitry Andric       FastMathFlags FMF;
4459*0b57cec5SDimitry Andric       if (IsFP && Record.size() > OpNum+1)
4460*0b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[++OpNum]);
4461*0b57cec5SDimitry Andric 
4462*0b57cec5SDimitry Andric       if (OpNum+1 != Record.size())
4463*0b57cec5SDimitry Andric         return error("Invalid record");
4464*0b57cec5SDimitry Andric 
4465*0b57cec5SDimitry Andric       if (LHS->getType()->isFPOrFPVectorTy())
4466*0b57cec5SDimitry Andric         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4467*0b57cec5SDimitry Andric       else
4468*0b57cec5SDimitry Andric         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4469*0b57cec5SDimitry Andric 
4470*0b57cec5SDimitry Andric       if (FMF.any())
4471*0b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
4472*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4473*0b57cec5SDimitry Andric       break;
4474*0b57cec5SDimitry Andric     }
4475*0b57cec5SDimitry Andric 
4476*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4477*0b57cec5SDimitry Andric       {
4478*0b57cec5SDimitry Andric         unsigned Size = Record.size();
4479*0b57cec5SDimitry Andric         if (Size == 0) {
4480*0b57cec5SDimitry Andric           I = ReturnInst::Create(Context);
4481*0b57cec5SDimitry Andric           InstructionList.push_back(I);
4482*0b57cec5SDimitry Andric           break;
4483*0b57cec5SDimitry Andric         }
4484*0b57cec5SDimitry Andric 
4485*0b57cec5SDimitry Andric         unsigned OpNum = 0;
4486*0b57cec5SDimitry Andric         Value *Op = nullptr;
4487*0b57cec5SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4488*0b57cec5SDimitry Andric           return error("Invalid record");
4489*0b57cec5SDimitry Andric         if (OpNum != Record.size())
4490*0b57cec5SDimitry Andric           return error("Invalid record");
4491*0b57cec5SDimitry Andric 
4492*0b57cec5SDimitry Andric         I = ReturnInst::Create(Context, Op);
4493*0b57cec5SDimitry Andric         InstructionList.push_back(I);
4494*0b57cec5SDimitry Andric         break;
4495*0b57cec5SDimitry Andric       }
4496*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4497*0b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 3)
4498*0b57cec5SDimitry Andric         return error("Invalid record");
4499*0b57cec5SDimitry Andric       BasicBlock *TrueDest = getBasicBlock(Record[0]);
4500*0b57cec5SDimitry Andric       if (!TrueDest)
4501*0b57cec5SDimitry Andric         return error("Invalid record");
4502*0b57cec5SDimitry Andric 
4503*0b57cec5SDimitry Andric       if (Record.size() == 1) {
4504*0b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest);
4505*0b57cec5SDimitry Andric         InstructionList.push_back(I);
4506*0b57cec5SDimitry Andric       }
4507*0b57cec5SDimitry Andric       else {
4508*0b57cec5SDimitry Andric         BasicBlock *FalseDest = getBasicBlock(Record[1]);
4509*0b57cec5SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo,
4510*0b57cec5SDimitry Andric                                Type::getInt1Ty(Context));
4511*0b57cec5SDimitry Andric         if (!FalseDest || !Cond)
4512*0b57cec5SDimitry Andric           return error("Invalid record");
4513*0b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest, FalseDest, Cond);
4514*0b57cec5SDimitry Andric         InstructionList.push_back(I);
4515*0b57cec5SDimitry Andric       }
4516*0b57cec5SDimitry Andric       break;
4517*0b57cec5SDimitry Andric     }
4518*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4519*0b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 2)
4520*0b57cec5SDimitry Andric         return error("Invalid record");
4521*0b57cec5SDimitry Andric       unsigned Idx = 0;
4522*0b57cec5SDimitry Andric       Value *CleanupPad =
4523*0b57cec5SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4524*0b57cec5SDimitry Andric       if (!CleanupPad)
4525*0b57cec5SDimitry Andric         return error("Invalid record");
4526*0b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
4527*0b57cec5SDimitry Andric       if (Record.size() == 2) {
4528*0b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
4529*0b57cec5SDimitry Andric         if (!UnwindDest)
4530*0b57cec5SDimitry Andric           return error("Invalid record");
4531*0b57cec5SDimitry Andric       }
4532*0b57cec5SDimitry Andric 
4533*0b57cec5SDimitry Andric       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4534*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4535*0b57cec5SDimitry Andric       break;
4536*0b57cec5SDimitry Andric     }
4537*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4538*0b57cec5SDimitry Andric       if (Record.size() != 2)
4539*0b57cec5SDimitry Andric         return error("Invalid record");
4540*0b57cec5SDimitry Andric       unsigned Idx = 0;
4541*0b57cec5SDimitry Andric       Value *CatchPad =
4542*0b57cec5SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4543*0b57cec5SDimitry Andric       if (!CatchPad)
4544*0b57cec5SDimitry Andric         return error("Invalid record");
4545*0b57cec5SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[Idx++]);
4546*0b57cec5SDimitry Andric       if (!BB)
4547*0b57cec5SDimitry Andric         return error("Invalid record");
4548*0b57cec5SDimitry Andric 
4549*0b57cec5SDimitry Andric       I = CatchReturnInst::Create(CatchPad, BB);
4550*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4551*0b57cec5SDimitry Andric       break;
4552*0b57cec5SDimitry Andric     }
4553*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4554*0b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
4555*0b57cec5SDimitry Andric       if (Record.size() < 2)
4556*0b57cec5SDimitry Andric         return error("Invalid record");
4557*0b57cec5SDimitry Andric 
4558*0b57cec5SDimitry Andric       unsigned Idx = 0;
4559*0b57cec5SDimitry Andric 
4560*0b57cec5SDimitry Andric       Value *ParentPad =
4561*0b57cec5SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4562*0b57cec5SDimitry Andric 
4563*0b57cec5SDimitry Andric       unsigned NumHandlers = Record[Idx++];
4564*0b57cec5SDimitry Andric 
4565*0b57cec5SDimitry Andric       SmallVector<BasicBlock *, 2> Handlers;
4566*0b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4567*0b57cec5SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[Idx++]);
4568*0b57cec5SDimitry Andric         if (!BB)
4569*0b57cec5SDimitry Andric           return error("Invalid record");
4570*0b57cec5SDimitry Andric         Handlers.push_back(BB);
4571*0b57cec5SDimitry Andric       }
4572*0b57cec5SDimitry Andric 
4573*0b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
4574*0b57cec5SDimitry Andric       if (Idx + 1 == Record.size()) {
4575*0b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
4576*0b57cec5SDimitry Andric         if (!UnwindDest)
4577*0b57cec5SDimitry Andric           return error("Invalid record");
4578*0b57cec5SDimitry Andric       }
4579*0b57cec5SDimitry Andric 
4580*0b57cec5SDimitry Andric       if (Record.size() != Idx)
4581*0b57cec5SDimitry Andric         return error("Invalid record");
4582*0b57cec5SDimitry Andric 
4583*0b57cec5SDimitry Andric       auto *CatchSwitch =
4584*0b57cec5SDimitry Andric           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4585*0b57cec5SDimitry Andric       for (BasicBlock *Handler : Handlers)
4586*0b57cec5SDimitry Andric         CatchSwitch->addHandler(Handler);
4587*0b57cec5SDimitry Andric       I = CatchSwitch;
4588*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4589*0b57cec5SDimitry Andric       break;
4590*0b57cec5SDimitry Andric     }
4591*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHPAD:
4592*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4593*0b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
4594*0b57cec5SDimitry Andric       if (Record.size() < 2)
4595*0b57cec5SDimitry Andric         return error("Invalid record");
4596*0b57cec5SDimitry Andric 
4597*0b57cec5SDimitry Andric       unsigned Idx = 0;
4598*0b57cec5SDimitry Andric 
4599*0b57cec5SDimitry Andric       Value *ParentPad =
4600*0b57cec5SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4601*0b57cec5SDimitry Andric 
4602*0b57cec5SDimitry Andric       unsigned NumArgOperands = Record[Idx++];
4603*0b57cec5SDimitry Andric 
4604*0b57cec5SDimitry Andric       SmallVector<Value *, 2> Args;
4605*0b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4606*0b57cec5SDimitry Andric         Value *Val;
4607*0b57cec5SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val))
4608*0b57cec5SDimitry Andric           return error("Invalid record");
4609*0b57cec5SDimitry Andric         Args.push_back(Val);
4610*0b57cec5SDimitry Andric       }
4611*0b57cec5SDimitry Andric 
4612*0b57cec5SDimitry Andric       if (Record.size() != Idx)
4613*0b57cec5SDimitry Andric         return error("Invalid record");
4614*0b57cec5SDimitry Andric 
4615*0b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4616*0b57cec5SDimitry Andric         I = CleanupPadInst::Create(ParentPad, Args);
4617*0b57cec5SDimitry Andric       else
4618*0b57cec5SDimitry Andric         I = CatchPadInst::Create(ParentPad, Args);
4619*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4620*0b57cec5SDimitry Andric       break;
4621*0b57cec5SDimitry Andric     }
4622*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4623*0b57cec5SDimitry Andric       // Check magic
4624*0b57cec5SDimitry Andric       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4625*0b57cec5SDimitry Andric         // "New" SwitchInst format with case ranges. The changes to write this
4626*0b57cec5SDimitry Andric         // format were reverted but we still recognize bitcode that uses it.
4627*0b57cec5SDimitry Andric         // Hopefully someday we will have support for case ranges and can use
4628*0b57cec5SDimitry Andric         // this format again.
4629*0b57cec5SDimitry Andric 
4630*0b57cec5SDimitry Andric         Type *OpTy = getTypeByID(Record[1]);
4631*0b57cec5SDimitry Andric         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4632*0b57cec5SDimitry Andric 
4633*0b57cec5SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4634*0b57cec5SDimitry Andric         BasicBlock *Default = getBasicBlock(Record[3]);
4635*0b57cec5SDimitry Andric         if (!OpTy || !Cond || !Default)
4636*0b57cec5SDimitry Andric           return error("Invalid record");
4637*0b57cec5SDimitry Andric 
4638*0b57cec5SDimitry Andric         unsigned NumCases = Record[4];
4639*0b57cec5SDimitry Andric 
4640*0b57cec5SDimitry Andric         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4641*0b57cec5SDimitry Andric         InstructionList.push_back(SI);
4642*0b57cec5SDimitry Andric 
4643*0b57cec5SDimitry Andric         unsigned CurIdx = 5;
4644*0b57cec5SDimitry Andric         for (unsigned i = 0; i != NumCases; ++i) {
4645*0b57cec5SDimitry Andric           SmallVector<ConstantInt*, 1> CaseVals;
4646*0b57cec5SDimitry Andric           unsigned NumItems = Record[CurIdx++];
4647*0b57cec5SDimitry Andric           for (unsigned ci = 0; ci != NumItems; ++ci) {
4648*0b57cec5SDimitry Andric             bool isSingleNumber = Record[CurIdx++];
4649*0b57cec5SDimitry Andric 
4650*0b57cec5SDimitry Andric             APInt Low;
4651*0b57cec5SDimitry Andric             unsigned ActiveWords = 1;
4652*0b57cec5SDimitry Andric             if (ValueBitWidth > 64)
4653*0b57cec5SDimitry Andric               ActiveWords = Record[CurIdx++];
4654*0b57cec5SDimitry Andric             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4655*0b57cec5SDimitry Andric                                 ValueBitWidth);
4656*0b57cec5SDimitry Andric             CurIdx += ActiveWords;
4657*0b57cec5SDimitry Andric 
4658*0b57cec5SDimitry Andric             if (!isSingleNumber) {
4659*0b57cec5SDimitry Andric               ActiveWords = 1;
4660*0b57cec5SDimitry Andric               if (ValueBitWidth > 64)
4661*0b57cec5SDimitry Andric                 ActiveWords = Record[CurIdx++];
4662*0b57cec5SDimitry Andric               APInt High = readWideAPInt(
4663*0b57cec5SDimitry Andric                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4664*0b57cec5SDimitry Andric               CurIdx += ActiveWords;
4665*0b57cec5SDimitry Andric 
4666*0b57cec5SDimitry Andric               // FIXME: It is not clear whether values in the range should be
4667*0b57cec5SDimitry Andric               // compared as signed or unsigned values. The partially
4668*0b57cec5SDimitry Andric               // implemented changes that used this format in the past used
4669*0b57cec5SDimitry Andric               // unsigned comparisons.
4670*0b57cec5SDimitry Andric               for ( ; Low.ule(High); ++Low)
4671*0b57cec5SDimitry Andric                 CaseVals.push_back(ConstantInt::get(Context, Low));
4672*0b57cec5SDimitry Andric             } else
4673*0b57cec5SDimitry Andric               CaseVals.push_back(ConstantInt::get(Context, Low));
4674*0b57cec5SDimitry Andric           }
4675*0b57cec5SDimitry Andric           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
46764824e7fdSDimitry Andric           for (ConstantInt *Cst : CaseVals)
46774824e7fdSDimitry Andric             SI->addCase(Cst, DestBB);
4678*0b57cec5SDimitry Andric         }
4679*0b57cec5SDimitry Andric         I = SI;
4680*0b57cec5SDimitry Andric         break;
4681*0b57cec5SDimitry Andric       }
4682*0b57cec5SDimitry Andric 
4683*0b57cec5SDimitry Andric       // Old SwitchInst format without case ranges.
4684*0b57cec5SDimitry Andric 
4685*0b57cec5SDimitry Andric       if (Record.size() < 3 || (Record.size() & 1) == 0)
4686*0b57cec5SDimitry Andric         return error("Invalid record");
4687*0b57cec5SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
4688*0b57cec5SDimitry Andric       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4689*0b57cec5SDimitry Andric       BasicBlock *Default = getBasicBlock(Record[2]);
4690*0b57cec5SDimitry Andric       if (!OpTy || !Cond || !Default)
4691*0b57cec5SDimitry Andric         return error("Invalid record");
4692*0b57cec5SDimitry Andric       unsigned NumCases = (Record.size()-3)/2;
4693*0b57cec5SDimitry Andric       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4694*0b57cec5SDimitry Andric       InstructionList.push_back(SI);
4695*0b57cec5SDimitry Andric       for (unsigned i = 0, e = NumCases; i != e; ++i) {
4696*0b57cec5SDimitry Andric         ConstantInt *CaseVal =
4697*0b57cec5SDimitry Andric           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4698*0b57cec5SDimitry Andric         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4699*0b57cec5SDimitry Andric         if (!CaseVal || !DestBB) {
4700*0b57cec5SDimitry Andric           delete SI;
4701*0b57cec5SDimitry Andric           return error("Invalid record");
4702*0b57cec5SDimitry Andric         }
4703*0b57cec5SDimitry Andric         SI->addCase(CaseVal, DestBB);
4704*0b57cec5SDimitry Andric       }
4705*0b57cec5SDimitry Andric       I = SI;
4706*0b57cec5SDimitry Andric       break;
4707*0b57cec5SDimitry Andric     }
4708*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4709*0b57cec5SDimitry Andric       if (Record.size() < 2)
4710*0b57cec5SDimitry Andric         return error("Invalid record");
4711*0b57cec5SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
4712*0b57cec5SDimitry Andric       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4713*0b57cec5SDimitry Andric       if (!OpTy || !Address)
4714*0b57cec5SDimitry Andric         return error("Invalid record");
4715*0b57cec5SDimitry Andric       unsigned NumDests = Record.size()-2;
4716*0b57cec5SDimitry Andric       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4717*0b57cec5SDimitry Andric       InstructionList.push_back(IBI);
4718*0b57cec5SDimitry Andric       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4719*0b57cec5SDimitry Andric         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4720*0b57cec5SDimitry Andric           IBI->addDestination(DestBB);
4721*0b57cec5SDimitry Andric         } else {
4722*0b57cec5SDimitry Andric           delete IBI;
4723*0b57cec5SDimitry Andric           return error("Invalid record");
4724*0b57cec5SDimitry Andric         }
4725*0b57cec5SDimitry Andric       }
4726*0b57cec5SDimitry Andric       I = IBI;
4727*0b57cec5SDimitry Andric       break;
4728*0b57cec5SDimitry Andric     }
4729*0b57cec5SDimitry Andric 
4730*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INVOKE: {
4731*0b57cec5SDimitry Andric       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4732*0b57cec5SDimitry Andric       if (Record.size() < 4)
4733*0b57cec5SDimitry Andric         return error("Invalid record");
4734*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4735*0b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
4736*0b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
4737*0b57cec5SDimitry Andric       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4738*0b57cec5SDimitry Andric       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4739*0b57cec5SDimitry Andric 
4740*0b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
4741*0b57cec5SDimitry Andric       if ((CCInfo >> 13) & 1) {
4742fe6060f1SDimitry Andric         FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]));
4743fe6060f1SDimitry Andric         if (!FTy)
4744*0b57cec5SDimitry Andric           return error("Explicit invoke type is not a function type");
4745*0b57cec5SDimitry Andric       }
4746*0b57cec5SDimitry Andric 
4747*0b57cec5SDimitry Andric       Value *Callee;
4748fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4749*0b57cec5SDimitry Andric         return error("Invalid record");
4750*0b57cec5SDimitry Andric 
4751*0b57cec5SDimitry Andric       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4752*0b57cec5SDimitry Andric       if (!CalleeTy)
4753*0b57cec5SDimitry Andric         return error("Callee is not a pointer");
4754*0b57cec5SDimitry Andric       if (!FTy) {
475504eeddc0SDimitry Andric         FTy =
475604eeddc0SDimitry Andric             dyn_cast<FunctionType>(Callee->getType()->getPointerElementType());
4757fe6060f1SDimitry Andric         if (!FTy)
4758*0b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
4759fe6060f1SDimitry Andric       } else if (!CalleeTy->isOpaqueOrPointeeTypeMatches(FTy))
4760*0b57cec5SDimitry Andric         return error("Explicit invoke type does not match pointee type of "
4761*0b57cec5SDimitry Andric                      "callee operand");
4762*0b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
4763*0b57cec5SDimitry Andric         return error("Insufficient operands to call");
4764*0b57cec5SDimitry Andric 
4765*0b57cec5SDimitry Andric       SmallVector<Value*, 16> Ops;
4766fe6060f1SDimitry Andric       SmallVector<Type *, 16> ArgsTys;
4767*0b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4768*0b57cec5SDimitry Andric         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4769*0b57cec5SDimitry Andric                                FTy->getParamType(i)));
4770fe6060f1SDimitry Andric         ArgsTys.push_back(FTy->getParamType(i));
4771*0b57cec5SDimitry Andric         if (!Ops.back())
4772*0b57cec5SDimitry Andric           return error("Invalid record");
4773*0b57cec5SDimitry Andric       }
4774*0b57cec5SDimitry Andric 
4775*0b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
4776*0b57cec5SDimitry Andric         if (Record.size() != OpNum)
4777*0b57cec5SDimitry Andric           return error("Invalid record");
4778*0b57cec5SDimitry Andric       } else {
4779*0b57cec5SDimitry Andric         // Read type/value pairs for varargs params.
4780*0b57cec5SDimitry Andric         while (OpNum != Record.size()) {
4781*0b57cec5SDimitry Andric           Value *Op;
4782fe6060f1SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4783*0b57cec5SDimitry Andric             return error("Invalid record");
4784*0b57cec5SDimitry Andric           Ops.push_back(Op);
4785fe6060f1SDimitry Andric           ArgsTys.push_back(Op->getType());
4786*0b57cec5SDimitry Andric         }
4787*0b57cec5SDimitry Andric       }
4788*0b57cec5SDimitry Andric 
4789*0b57cec5SDimitry Andric       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
4790*0b57cec5SDimitry Andric                              OperandBundles);
4791*0b57cec5SDimitry Andric       OperandBundles.clear();
4792*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4793*0b57cec5SDimitry Andric       cast<InvokeInst>(I)->setCallingConv(
4794*0b57cec5SDimitry Andric           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4795*0b57cec5SDimitry Andric       cast<InvokeInst>(I)->setAttributes(PAL);
4796fe6060f1SDimitry Andric       propagateAttributeTypes(cast<CallBase>(I), ArgsTys);
4797*0b57cec5SDimitry Andric 
4798*0b57cec5SDimitry Andric       break;
4799*0b57cec5SDimitry Andric     }
4800*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4801*0b57cec5SDimitry Andric       unsigned Idx = 0;
4802*0b57cec5SDimitry Andric       Value *Val = nullptr;
4803*0b57cec5SDimitry Andric       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4804*0b57cec5SDimitry Andric         return error("Invalid record");
4805*0b57cec5SDimitry Andric       I = ResumeInst::Create(Val);
4806*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4807*0b57cec5SDimitry Andric       break;
4808*0b57cec5SDimitry Andric     }
4809*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALLBR: {
4810*0b57cec5SDimitry Andric       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
4811*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4812*0b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
4813*0b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
4814*0b57cec5SDimitry Andric 
4815*0b57cec5SDimitry Andric       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
4816*0b57cec5SDimitry Andric       unsigned NumIndirectDests = Record[OpNum++];
4817*0b57cec5SDimitry Andric       SmallVector<BasicBlock *, 16> IndirectDests;
4818*0b57cec5SDimitry Andric       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
4819*0b57cec5SDimitry Andric         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
4820*0b57cec5SDimitry Andric 
4821*0b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
4822*0b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
4823fe6060f1SDimitry Andric         FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]));
4824fe6060f1SDimitry Andric         if (!FTy)
4825*0b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
4826*0b57cec5SDimitry Andric       }
4827*0b57cec5SDimitry Andric 
4828*0b57cec5SDimitry Andric       Value *Callee;
4829fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4830*0b57cec5SDimitry Andric         return error("Invalid record");
4831*0b57cec5SDimitry Andric 
4832*0b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4833*0b57cec5SDimitry Andric       if (!OpTy)
4834*0b57cec5SDimitry Andric         return error("Callee is not a pointer type");
4835*0b57cec5SDimitry Andric       if (!FTy) {
483604eeddc0SDimitry Andric         FTy =
483704eeddc0SDimitry Andric             dyn_cast<FunctionType>(Callee->getType()->getPointerElementType());
4838fe6060f1SDimitry Andric         if (!FTy)
4839*0b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
484004eeddc0SDimitry Andric       } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
4841*0b57cec5SDimitry Andric         return error("Explicit call type does not match pointee type of "
4842*0b57cec5SDimitry Andric                      "callee operand");
4843*0b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
4844*0b57cec5SDimitry Andric         return error("Insufficient operands to call");
4845*0b57cec5SDimitry Andric 
4846*0b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
484704eeddc0SDimitry Andric       SmallVector<Type *, 16> ArgsTys;
4848*0b57cec5SDimitry Andric       // Read the fixed params.
4849*0b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
485004eeddc0SDimitry Andric         Value *Arg;
4851*0b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
485204eeddc0SDimitry Andric           Arg = getBasicBlock(Record[OpNum]);
4853*0b57cec5SDimitry Andric         else
485404eeddc0SDimitry Andric           Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i));
485504eeddc0SDimitry Andric         if (!Arg)
4856*0b57cec5SDimitry Andric           return error("Invalid record");
485704eeddc0SDimitry Andric         Args.push_back(Arg);
485804eeddc0SDimitry Andric         ArgsTys.push_back(Arg->getType());
4859*0b57cec5SDimitry Andric       }
4860*0b57cec5SDimitry Andric 
4861*0b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
4862*0b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
4863*0b57cec5SDimitry Andric         if (OpNum != Record.size())
4864*0b57cec5SDimitry Andric           return error("Invalid record");
4865*0b57cec5SDimitry Andric       } else {
4866*0b57cec5SDimitry Andric         while (OpNum != Record.size()) {
4867*0b57cec5SDimitry Andric           Value *Op;
4868*0b57cec5SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4869*0b57cec5SDimitry Andric             return error("Invalid record");
4870*0b57cec5SDimitry Andric           Args.push_back(Op);
487104eeddc0SDimitry Andric           ArgsTys.push_back(Op->getType());
4872*0b57cec5SDimitry Andric         }
4873*0b57cec5SDimitry Andric       }
4874*0b57cec5SDimitry Andric 
4875*0b57cec5SDimitry Andric       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
4876*0b57cec5SDimitry Andric                              OperandBundles);
4877*0b57cec5SDimitry Andric       OperandBundles.clear();
4878*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4879*0b57cec5SDimitry Andric       cast<CallBrInst>(I)->setCallingConv(
4880*0b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4881*0b57cec5SDimitry Andric       cast<CallBrInst>(I)->setAttributes(PAL);
488204eeddc0SDimitry Andric       propagateAttributeTypes(cast<CallBase>(I), ArgsTys);
4883*0b57cec5SDimitry Andric       break;
4884*0b57cec5SDimitry Andric     }
4885*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4886*0b57cec5SDimitry Andric       I = new UnreachableInst(Context);
4887*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4888*0b57cec5SDimitry Andric       break;
4889*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4890e8d8bef9SDimitry Andric       if (Record.empty())
4891*0b57cec5SDimitry Andric         return error("Invalid record");
48928bcb0991SDimitry Andric       // The first record specifies the type.
4893fe6060f1SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
4894*0b57cec5SDimitry Andric       if (!Ty)
4895*0b57cec5SDimitry Andric         return error("Invalid record");
4896*0b57cec5SDimitry Andric 
48978bcb0991SDimitry Andric       // Phi arguments are pairs of records of [value, basic block].
48988bcb0991SDimitry Andric       // There is an optional final record for fast-math-flags if this phi has a
48998bcb0991SDimitry Andric       // floating-point type.
49008bcb0991SDimitry Andric       size_t NumArgs = (Record.size() - 1) / 2;
49018bcb0991SDimitry Andric       PHINode *PN = PHINode::Create(Ty, NumArgs);
4902480093f4SDimitry Andric       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN))
4903480093f4SDimitry Andric         return error("Invalid record");
4904*0b57cec5SDimitry Andric       InstructionList.push_back(PN);
4905*0b57cec5SDimitry Andric 
49068bcb0991SDimitry Andric       for (unsigned i = 0; i != NumArgs; i++) {
4907*0b57cec5SDimitry Andric         Value *V;
4908*0b57cec5SDimitry Andric         // With the new function encoding, it is possible that operands have
4909*0b57cec5SDimitry Andric         // negative IDs (for forward references).  Use a signed VBR
4910*0b57cec5SDimitry Andric         // representation to keep the encoding small.
4911*0b57cec5SDimitry Andric         if (UseRelativeIDs)
49128bcb0991SDimitry Andric           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty);
4913*0b57cec5SDimitry Andric         else
49148bcb0991SDimitry Andric           V = getValue(Record, i * 2 + 1, NextValueNo, Ty);
49158bcb0991SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
4916*0b57cec5SDimitry Andric         if (!V || !BB)
4917*0b57cec5SDimitry Andric           return error("Invalid record");
4918*0b57cec5SDimitry Andric         PN->addIncoming(V, BB);
4919*0b57cec5SDimitry Andric       }
4920*0b57cec5SDimitry Andric       I = PN;
49218bcb0991SDimitry Andric 
49228bcb0991SDimitry Andric       // If there are an even number of records, the final record must be FMF.
49238bcb0991SDimitry Andric       if (Record.size() % 2 == 0) {
49248bcb0991SDimitry Andric         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
49258bcb0991SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
49268bcb0991SDimitry Andric         if (FMF.any())
49278bcb0991SDimitry Andric           I->setFastMathFlags(FMF);
49288bcb0991SDimitry Andric       }
49298bcb0991SDimitry Andric 
4930*0b57cec5SDimitry Andric       break;
4931*0b57cec5SDimitry Andric     }
4932*0b57cec5SDimitry Andric 
4933*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD:
4934*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4935*0b57cec5SDimitry Andric       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4936*0b57cec5SDimitry Andric       unsigned Idx = 0;
4937*0b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4938*0b57cec5SDimitry Andric         if (Record.size() < 3)
4939*0b57cec5SDimitry Andric           return error("Invalid record");
4940*0b57cec5SDimitry Andric       } else {
4941*0b57cec5SDimitry Andric         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4942*0b57cec5SDimitry Andric         if (Record.size() < 4)
4943*0b57cec5SDimitry Andric           return error("Invalid record");
4944*0b57cec5SDimitry Andric       }
4945fe6060f1SDimitry Andric       Type *Ty = getTypeByID(Record[Idx++]);
4946*0b57cec5SDimitry Andric       if (!Ty)
4947*0b57cec5SDimitry Andric         return error("Invalid record");
4948*0b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4949*0b57cec5SDimitry Andric         Value *PersFn = nullptr;
4950*0b57cec5SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4951*0b57cec5SDimitry Andric           return error("Invalid record");
4952*0b57cec5SDimitry Andric 
4953*0b57cec5SDimitry Andric         if (!F->hasPersonalityFn())
4954*0b57cec5SDimitry Andric           F->setPersonalityFn(cast<Constant>(PersFn));
4955*0b57cec5SDimitry Andric         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4956*0b57cec5SDimitry Andric           return error("Personality function mismatch");
4957*0b57cec5SDimitry Andric       }
4958*0b57cec5SDimitry Andric 
4959*0b57cec5SDimitry Andric       bool IsCleanup = !!Record[Idx++];
4960*0b57cec5SDimitry Andric       unsigned NumClauses = Record[Idx++];
4961*0b57cec5SDimitry Andric       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4962*0b57cec5SDimitry Andric       LP->setCleanup(IsCleanup);
4963*0b57cec5SDimitry Andric       for (unsigned J = 0; J != NumClauses; ++J) {
4964*0b57cec5SDimitry Andric         LandingPadInst::ClauseType CT =
4965*0b57cec5SDimitry Andric           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4966*0b57cec5SDimitry Andric         Value *Val;
4967*0b57cec5SDimitry Andric 
4968*0b57cec5SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4969*0b57cec5SDimitry Andric           delete LP;
4970*0b57cec5SDimitry Andric           return error("Invalid record");
4971*0b57cec5SDimitry Andric         }
4972*0b57cec5SDimitry Andric 
4973*0b57cec5SDimitry Andric         assert((CT != LandingPadInst::Catch ||
4974*0b57cec5SDimitry Andric                 !isa<ArrayType>(Val->getType())) &&
4975*0b57cec5SDimitry Andric                "Catch clause has a invalid type!");
4976*0b57cec5SDimitry Andric         assert((CT != LandingPadInst::Filter ||
4977*0b57cec5SDimitry Andric                 isa<ArrayType>(Val->getType())) &&
4978*0b57cec5SDimitry Andric                "Filter clause has invalid type!");
4979*0b57cec5SDimitry Andric         LP->addClause(cast<Constant>(Val));
4980*0b57cec5SDimitry Andric       }
4981*0b57cec5SDimitry Andric 
4982*0b57cec5SDimitry Andric       I = LP;
4983*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4984*0b57cec5SDimitry Andric       break;
4985*0b57cec5SDimitry Andric     }
4986*0b57cec5SDimitry Andric 
4987*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4988*0b57cec5SDimitry Andric       if (Record.size() != 4)
4989*0b57cec5SDimitry Andric         return error("Invalid record");
4990e8d8bef9SDimitry Andric       using APV = AllocaPackedValues;
4991e8d8bef9SDimitry Andric       const uint64_t Rec = Record[3];
4992e8d8bef9SDimitry Andric       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
4993e8d8bef9SDimitry Andric       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
4994fe6060f1SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
4995e8d8bef9SDimitry Andric       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
4996*0b57cec5SDimitry Andric         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4997*0b57cec5SDimitry Andric         if (!PTy)
4998*0b57cec5SDimitry Andric           return error("Old-style alloca with a non-pointer type");
499904eeddc0SDimitry Andric         Ty = PTy->getPointerElementType();
5000*0b57cec5SDimitry Andric       }
5001*0b57cec5SDimitry Andric       Type *OpTy = getTypeByID(Record[1]);
5002*0b57cec5SDimitry Andric       Value *Size = getFnValueByID(Record[2], OpTy);
50038bcb0991SDimitry Andric       MaybeAlign Align;
5004349cc55cSDimitry Andric       uint64_t AlignExp =
5005349cc55cSDimitry Andric           Bitfield::get<APV::AlignLower>(Rec) |
5006349cc55cSDimitry Andric           (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
5007349cc55cSDimitry Andric       if (Error Err = parseAlignmentValue(AlignExp, Align)) {
5008*0b57cec5SDimitry Andric         return Err;
5009*0b57cec5SDimitry Andric       }
5010*0b57cec5SDimitry Andric       if (!Ty || !Size)
5011*0b57cec5SDimitry Andric         return error("Invalid record");
5012*0b57cec5SDimitry Andric 
5013*0b57cec5SDimitry Andric       // FIXME: Make this an optional field.
5014*0b57cec5SDimitry Andric       const DataLayout &DL = TheModule->getDataLayout();
5015*0b57cec5SDimitry Andric       unsigned AS = DL.getAllocaAddrSpace();
5016*0b57cec5SDimitry Andric 
50175ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
50185ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
50195ffd83dbSDimitry Andric         return error("alloca of unsized type");
50205ffd83dbSDimitry Andric       if (!Align)
50215ffd83dbSDimitry Andric         Align = DL.getPrefTypeAlign(Ty);
50225ffd83dbSDimitry Andric 
50235ffd83dbSDimitry Andric       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
5024*0b57cec5SDimitry Andric       AI->setUsedWithInAlloca(InAlloca);
5025*0b57cec5SDimitry Andric       AI->setSwiftError(SwiftError);
5026*0b57cec5SDimitry Andric       I = AI;
5027*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5028*0b57cec5SDimitry Andric       break;
5029*0b57cec5SDimitry Andric     }
5030*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
5031*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5032*0b57cec5SDimitry Andric       Value *Op;
5033fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5034*0b57cec5SDimitry Andric           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
5035*0b57cec5SDimitry Andric         return error("Invalid record");
5036*0b57cec5SDimitry Andric 
5037*0b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
5038*0b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
5039*0b57cec5SDimitry Andric 
5040*0b57cec5SDimitry Andric       Type *Ty = nullptr;
5041*0b57cec5SDimitry Andric       if (OpNum + 3 == Record.size()) {
5042fe6060f1SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
5043fe6060f1SDimitry Andric       } else {
504404eeddc0SDimitry Andric         Ty = Op->getType()->getPointerElementType();
5045fe6060f1SDimitry Andric       }
5046*0b57cec5SDimitry Andric 
5047*0b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5048*0b57cec5SDimitry Andric         return Err;
5049*0b57cec5SDimitry Andric 
50508bcb0991SDimitry Andric       MaybeAlign Align;
5051*0b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5052*0b57cec5SDimitry Andric         return Err;
50535ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
50545ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
50555ffd83dbSDimitry Andric         return error("load of unsized type");
50565ffd83dbSDimitry Andric       if (!Align)
50575ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
50585ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
5059*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5060*0b57cec5SDimitry Andric       break;
5061*0b57cec5SDimitry Andric     }
5062*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOADATOMIC: {
5063*0b57cec5SDimitry Andric        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
5064*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5065*0b57cec5SDimitry Andric       Value *Op;
5066fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
5067*0b57cec5SDimitry Andric           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
5068*0b57cec5SDimitry Andric         return error("Invalid record");
5069*0b57cec5SDimitry Andric 
5070*0b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
5071*0b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
5072*0b57cec5SDimitry Andric 
5073*0b57cec5SDimitry Andric       Type *Ty = nullptr;
5074*0b57cec5SDimitry Andric       if (OpNum + 5 == Record.size()) {
5075fe6060f1SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
5076fe6060f1SDimitry Andric       } else {
507704eeddc0SDimitry Andric         Ty = Op->getType()->getPointerElementType();
5078fe6060f1SDimitry Andric       }
5079*0b57cec5SDimitry Andric 
5080*0b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5081*0b57cec5SDimitry Andric         return Err;
5082*0b57cec5SDimitry Andric 
5083*0b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5084*0b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
5085*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::Release ||
5086*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
5087*0b57cec5SDimitry Andric         return error("Invalid record");
5088*0b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5089*0b57cec5SDimitry Andric         return error("Invalid record");
5090*0b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5091*0b57cec5SDimitry Andric 
50928bcb0991SDimitry Andric       MaybeAlign Align;
5093*0b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5094*0b57cec5SDimitry Andric         return Err;
50955ffd83dbSDimitry Andric       if (!Align)
50965ffd83dbSDimitry Andric         return error("Alignment missing from atomic load");
50975ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
5098*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5099*0b57cec5SDimitry Andric       break;
5100*0b57cec5SDimitry Andric     }
5101*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE:
5102*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5103*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5104*0b57cec5SDimitry Andric       Value *Val, *Ptr;
5105fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5106*0b57cec5SDimitry Andric           (BitCode == bitc::FUNC_CODE_INST_STORE
5107*0b57cec5SDimitry Andric                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5108*0b57cec5SDimitry Andric                : popValue(Record, OpNum, NextValueNo,
510904eeddc0SDimitry Andric                           Ptr->getType()->getPointerElementType(), Val)) ||
5110*0b57cec5SDimitry Andric           OpNum + 2 != Record.size())
5111*0b57cec5SDimitry Andric         return error("Invalid record");
5112*0b57cec5SDimitry Andric 
5113*0b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5114*0b57cec5SDimitry Andric         return Err;
51158bcb0991SDimitry Andric       MaybeAlign Align;
5116*0b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5117*0b57cec5SDimitry Andric         return Err;
51185ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
51195ffd83dbSDimitry Andric       if (!Align && !Val->getType()->isSized(&Visited))
51205ffd83dbSDimitry Andric         return error("store of unsized type");
51215ffd83dbSDimitry Andric       if (!Align)
51225ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
51235ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
5124*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5125*0b57cec5SDimitry Andric       break;
5126*0b57cec5SDimitry Andric     }
5127*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC:
5128*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5129*0b57cec5SDimitry Andric       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
5130*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5131*0b57cec5SDimitry Andric       Value *Val, *Ptr;
5132fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5133*0b57cec5SDimitry Andric           !isa<PointerType>(Ptr->getType()) ||
5134*0b57cec5SDimitry Andric           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5135*0b57cec5SDimitry Andric                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5136*0b57cec5SDimitry Andric                : popValue(Record, OpNum, NextValueNo,
513704eeddc0SDimitry Andric                           Ptr->getType()->getPointerElementType(), Val)) ||
5138*0b57cec5SDimitry Andric           OpNum + 4 != Record.size())
5139*0b57cec5SDimitry Andric         return error("Invalid record");
5140*0b57cec5SDimitry Andric 
5141*0b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5142*0b57cec5SDimitry Andric         return Err;
5143*0b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5144*0b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
5145*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::Acquire ||
5146*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
5147*0b57cec5SDimitry Andric         return error("Invalid record");
5148*0b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5149*0b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5150*0b57cec5SDimitry Andric         return error("Invalid record");
5151*0b57cec5SDimitry Andric 
51528bcb0991SDimitry Andric       MaybeAlign Align;
5153*0b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5154*0b57cec5SDimitry Andric         return Err;
51555ffd83dbSDimitry Andric       if (!Align)
51565ffd83dbSDimitry Andric         return error("Alignment missing from atomic store");
51575ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
5158*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5159*0b57cec5SDimitry Andric       break;
5160*0b57cec5SDimitry Andric     }
5161e8d8bef9SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
5162e8d8bef9SDimitry Andric       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
5163e8d8bef9SDimitry Andric       // failure_ordering?, weak?]
5164e8d8bef9SDimitry Andric       const size_t NumRecords = Record.size();
5165*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5166e8d8bef9SDimitry Andric       Value *Ptr = nullptr;
5167fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr))
5168*0b57cec5SDimitry Andric         return error("Invalid record");
5169*0b57cec5SDimitry Andric 
5170*0b57cec5SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
5171*0b57cec5SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
5172*0b57cec5SDimitry Andric 
5173e8d8bef9SDimitry Andric       Value *Cmp = nullptr;
5174e8d8bef9SDimitry Andric       if (popValue(Record, OpNum, NextValueNo,
5175fe6060f1SDimitry Andric                    cast<PointerType>(Ptr->getType())->getPointerElementType(),
5176fe6060f1SDimitry Andric                    Cmp))
5177*0b57cec5SDimitry Andric         return error("Invalid record");
5178e8d8bef9SDimitry Andric 
5179e8d8bef9SDimitry Andric       Value *New = nullptr;
5180*0b57cec5SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5181e8d8bef9SDimitry Andric           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
5182*0b57cec5SDimitry Andric         return error("Invalid record");
5183*0b57cec5SDimitry Andric 
5184e8d8bef9SDimitry Andric       const AtomicOrdering SuccessOrdering =
5185e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
5186*0b57cec5SDimitry Andric       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5187*0b57cec5SDimitry Andric           SuccessOrdering == AtomicOrdering::Unordered)
5188*0b57cec5SDimitry Andric         return error("Invalid record");
5189e8d8bef9SDimitry Andric 
5190e8d8bef9SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5191*0b57cec5SDimitry Andric 
5192*0b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5193*0b57cec5SDimitry Andric         return Err;
5194*0b57cec5SDimitry Andric 
5195e8d8bef9SDimitry Andric       const AtomicOrdering FailureOrdering =
5196e8d8bef9SDimitry Andric           NumRecords < 7
5197e8d8bef9SDimitry Andric               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
5198e8d8bef9SDimitry Andric               : getDecodedOrdering(Record[OpNum + 3]);
5199e8d8bef9SDimitry Andric 
5200fe6060f1SDimitry Andric       if (FailureOrdering == AtomicOrdering::NotAtomic ||
5201fe6060f1SDimitry Andric           FailureOrdering == AtomicOrdering::Unordered)
5202fe6060f1SDimitry Andric         return error("Invalid record");
5203fe6060f1SDimitry Andric 
5204e8d8bef9SDimitry Andric       const Align Alignment(
52055ffd83dbSDimitry Andric           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5206e8d8bef9SDimitry Andric 
52075ffd83dbSDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
52085ffd83dbSDimitry Andric                                 FailureOrdering, SSID);
5209*0b57cec5SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5210*0b57cec5SDimitry Andric 
5211e8d8bef9SDimitry Andric       if (NumRecords < 8) {
5212*0b57cec5SDimitry Andric         // Before weak cmpxchgs existed, the instruction simply returned the
5213*0b57cec5SDimitry Andric         // value loaded from memory, so bitcode files from that era will be
5214*0b57cec5SDimitry Andric         // expecting the first component of a modern cmpxchg.
5215*0b57cec5SDimitry Andric         CurBB->getInstList().push_back(I);
5216*0b57cec5SDimitry Andric         I = ExtractValueInst::Create(I, 0);
5217*0b57cec5SDimitry Andric       } else {
5218*0b57cec5SDimitry Andric         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
5219*0b57cec5SDimitry Andric       }
5220*0b57cec5SDimitry Andric 
5221*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5222*0b57cec5SDimitry Andric       break;
5223*0b57cec5SDimitry Andric     }
5224e8d8bef9SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG: {
5225e8d8bef9SDimitry Andric       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
5226fe6060f1SDimitry Andric       // failure_ordering, weak, align?]
5227e8d8bef9SDimitry Andric       const size_t NumRecords = Record.size();
5228e8d8bef9SDimitry Andric       unsigned OpNum = 0;
5229e8d8bef9SDimitry Andric       Value *Ptr = nullptr;
5230fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr))
5231e8d8bef9SDimitry Andric         return error("Invalid record");
5232e8d8bef9SDimitry Andric 
5233e8d8bef9SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
5234e8d8bef9SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
5235e8d8bef9SDimitry Andric 
5236e8d8bef9SDimitry Andric       Value *Cmp = nullptr;
5237fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp))
5238e8d8bef9SDimitry Andric         return error("Invalid record");
5239e8d8bef9SDimitry Andric 
5240e8d8bef9SDimitry Andric       Value *Val = nullptr;
5241fe6060f1SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), Val))
5242e8d8bef9SDimitry Andric         return error("Invalid record");
5243e8d8bef9SDimitry Andric 
5244fe6060f1SDimitry Andric       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
5245fe6060f1SDimitry Andric         return error("Invalid record");
5246fe6060f1SDimitry Andric 
5247fe6060f1SDimitry Andric       const bool IsVol = Record[OpNum];
5248fe6060f1SDimitry Andric 
5249e8d8bef9SDimitry Andric       const AtomicOrdering SuccessOrdering =
5250e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
5251fe6060f1SDimitry Andric       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
5252fe6060f1SDimitry Andric         return error("Invalid cmpxchg success ordering");
5253e8d8bef9SDimitry Andric 
5254e8d8bef9SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5255e8d8bef9SDimitry Andric 
5256e8d8bef9SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5257e8d8bef9SDimitry Andric         return Err;
5258e8d8bef9SDimitry Andric 
5259e8d8bef9SDimitry Andric       const AtomicOrdering FailureOrdering =
5260e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 3]);
5261fe6060f1SDimitry Andric       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
5262fe6060f1SDimitry Andric         return error("Invalid cmpxchg failure ordering");
5263e8d8bef9SDimitry Andric 
5264fe6060f1SDimitry Andric       const bool IsWeak = Record[OpNum + 4];
5265e8d8bef9SDimitry Andric 
5266fe6060f1SDimitry Andric       MaybeAlign Alignment;
5267fe6060f1SDimitry Andric 
5268fe6060f1SDimitry Andric       if (NumRecords == (OpNum + 6)) {
5269fe6060f1SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
5270fe6060f1SDimitry Andric           return Err;
5271fe6060f1SDimitry Andric       }
5272fe6060f1SDimitry Andric       if (!Alignment)
5273fe6060f1SDimitry Andric         Alignment =
5274fe6060f1SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5275fe6060f1SDimitry Andric 
5276fe6060f1SDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
5277e8d8bef9SDimitry Andric                                 FailureOrdering, SSID);
5278fe6060f1SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
5279fe6060f1SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
5280e8d8bef9SDimitry Andric 
5281e8d8bef9SDimitry Andric       InstructionList.push_back(I);
5282e8d8bef9SDimitry Andric       break;
5283e8d8bef9SDimitry Andric     }
5284fe6060f1SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
5285*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW: {
5286fe6060f1SDimitry Andric       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
5287fe6060f1SDimitry Andric       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
5288fe6060f1SDimitry Andric       const size_t NumRecords = Record.size();
5289*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5290fe6060f1SDimitry Andric 
5291fe6060f1SDimitry Andric       Value *Ptr = nullptr;
5292fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr))
5293*0b57cec5SDimitry Andric         return error("Invalid record");
5294fe6060f1SDimitry Andric 
5295fe6060f1SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
5296fe6060f1SDimitry Andric         return error("Invalid record");
5297fe6060f1SDimitry Andric 
5298fe6060f1SDimitry Andric       Value *Val = nullptr;
5299fe6060f1SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
5300fe6060f1SDimitry Andric         if (popValue(Record, OpNum, NextValueNo,
5301fe6060f1SDimitry Andric                      cast<PointerType>(Ptr->getType())->getPointerElementType(),
5302fe6060f1SDimitry Andric                      Val))
5303fe6060f1SDimitry Andric           return error("Invalid record");
5304fe6060f1SDimitry Andric       } else {
5305fe6060f1SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val))
5306fe6060f1SDimitry Andric           return error("Invalid record");
5307fe6060f1SDimitry Andric       }
5308fe6060f1SDimitry Andric 
5309fe6060f1SDimitry Andric       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
5310fe6060f1SDimitry Andric         return error("Invalid record");
5311fe6060f1SDimitry Andric 
5312fe6060f1SDimitry Andric       const AtomicRMWInst::BinOp Operation =
5313fe6060f1SDimitry Andric           getDecodedRMWOperation(Record[OpNum]);
5314*0b57cec5SDimitry Andric       if (Operation < AtomicRMWInst::FIRST_BINOP ||
5315*0b57cec5SDimitry Andric           Operation > AtomicRMWInst::LAST_BINOP)
5316*0b57cec5SDimitry Andric         return error("Invalid record");
5317fe6060f1SDimitry Andric 
5318fe6060f1SDimitry Andric       const bool IsVol = Record[OpNum + 1];
5319fe6060f1SDimitry Andric 
5320fe6060f1SDimitry Andric       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5321*0b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
5322*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered)
5323*0b57cec5SDimitry Andric         return error("Invalid record");
5324fe6060f1SDimitry Andric 
5325fe6060f1SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5326fe6060f1SDimitry Andric 
5327fe6060f1SDimitry Andric       MaybeAlign Alignment;
5328fe6060f1SDimitry Andric 
5329fe6060f1SDimitry Andric       if (NumRecords == (OpNum + 5)) {
5330fe6060f1SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
5331fe6060f1SDimitry Andric           return Err;
5332fe6060f1SDimitry Andric       }
5333fe6060f1SDimitry Andric 
5334fe6060f1SDimitry Andric       if (!Alignment)
5335fe6060f1SDimitry Andric         Alignment =
5336fe6060f1SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
5337fe6060f1SDimitry Andric 
5338fe6060f1SDimitry Andric       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
5339fe6060f1SDimitry Andric       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
5340fe6060f1SDimitry Andric 
5341*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5342*0b57cec5SDimitry Andric       break;
5343*0b57cec5SDimitry Andric     }
5344*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
5345*0b57cec5SDimitry Andric       if (2 != Record.size())
5346*0b57cec5SDimitry Andric         return error("Invalid record");
5347*0b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5348*0b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
5349*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered ||
5350*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::Monotonic)
5351*0b57cec5SDimitry Andric         return error("Invalid record");
5352*0b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
5353*0b57cec5SDimitry Andric       I = new FenceInst(Context, Ordering, SSID);
5354*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5355*0b57cec5SDimitry Andric       break;
5356*0b57cec5SDimitry Andric     }
5357*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALL: {
5358*0b57cec5SDimitry Andric       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5359*0b57cec5SDimitry Andric       if (Record.size() < 3)
5360*0b57cec5SDimitry Andric         return error("Invalid record");
5361*0b57cec5SDimitry Andric 
5362*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5363*0b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
5364*0b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
5365*0b57cec5SDimitry Andric 
5366*0b57cec5SDimitry Andric       FastMathFlags FMF;
5367*0b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_FMF) & 1) {
5368*0b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[OpNum++]);
5369*0b57cec5SDimitry Andric         if (!FMF.any())
5370*0b57cec5SDimitry Andric           return error("Fast math flags indicator set for call with no FMF");
5371*0b57cec5SDimitry Andric       }
5372*0b57cec5SDimitry Andric 
5373*0b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
5374*0b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5375fe6060f1SDimitry Andric         FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]));
5376fe6060f1SDimitry Andric         if (!FTy)
5377*0b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
5378*0b57cec5SDimitry Andric       }
5379*0b57cec5SDimitry Andric 
5380*0b57cec5SDimitry Andric       Value *Callee;
5381fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5382*0b57cec5SDimitry Andric         return error("Invalid record");
5383*0b57cec5SDimitry Andric 
5384*0b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5385*0b57cec5SDimitry Andric       if (!OpTy)
5386*0b57cec5SDimitry Andric         return error("Callee is not a pointer type");
5387*0b57cec5SDimitry Andric       if (!FTy) {
538804eeddc0SDimitry Andric         FTy =
538904eeddc0SDimitry Andric             dyn_cast<FunctionType>(Callee->getType()->getPointerElementType());
5390fe6060f1SDimitry Andric         if (!FTy)
5391*0b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
5392fe6060f1SDimitry Andric       } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
5393*0b57cec5SDimitry Andric         return error("Explicit call type does not match pointee type of "
5394*0b57cec5SDimitry Andric                      "callee operand");
5395*0b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
5396*0b57cec5SDimitry Andric         return error("Insufficient operands to call");
5397*0b57cec5SDimitry Andric 
5398*0b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
5399fe6060f1SDimitry Andric       SmallVector<Type *, 16> ArgsTys;
5400*0b57cec5SDimitry Andric       // Read the fixed params.
5401*0b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5402*0b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
5403*0b57cec5SDimitry Andric           Args.push_back(getBasicBlock(Record[OpNum]));
5404*0b57cec5SDimitry Andric         else
5405*0b57cec5SDimitry Andric           Args.push_back(getValue(Record, OpNum, NextValueNo,
5406*0b57cec5SDimitry Andric                                   FTy->getParamType(i)));
5407fe6060f1SDimitry Andric         ArgsTys.push_back(FTy->getParamType(i));
5408*0b57cec5SDimitry Andric         if (!Args.back())
5409*0b57cec5SDimitry Andric           return error("Invalid record");
5410*0b57cec5SDimitry Andric       }
5411*0b57cec5SDimitry Andric 
5412*0b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
5413*0b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
5414*0b57cec5SDimitry Andric         if (OpNum != Record.size())
5415*0b57cec5SDimitry Andric           return error("Invalid record");
5416*0b57cec5SDimitry Andric       } else {
5417*0b57cec5SDimitry Andric         while (OpNum != Record.size()) {
5418*0b57cec5SDimitry Andric           Value *Op;
5419fe6060f1SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5420*0b57cec5SDimitry Andric             return error("Invalid record");
5421*0b57cec5SDimitry Andric           Args.push_back(Op);
5422fe6060f1SDimitry Andric           ArgsTys.push_back(Op->getType());
5423*0b57cec5SDimitry Andric         }
5424*0b57cec5SDimitry Andric       }
5425*0b57cec5SDimitry Andric 
5426*0b57cec5SDimitry Andric       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5427*0b57cec5SDimitry Andric       OperandBundles.clear();
5428*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5429*0b57cec5SDimitry Andric       cast<CallInst>(I)->setCallingConv(
5430*0b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5431*0b57cec5SDimitry Andric       CallInst::TailCallKind TCK = CallInst::TCK_None;
5432*0b57cec5SDimitry Andric       if (CCInfo & 1 << bitc::CALL_TAIL)
5433*0b57cec5SDimitry Andric         TCK = CallInst::TCK_Tail;
5434*0b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5435*0b57cec5SDimitry Andric         TCK = CallInst::TCK_MustTail;
5436*0b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_NOTAIL))
5437*0b57cec5SDimitry Andric         TCK = CallInst::TCK_NoTail;
5438*0b57cec5SDimitry Andric       cast<CallInst>(I)->setTailCallKind(TCK);
5439*0b57cec5SDimitry Andric       cast<CallInst>(I)->setAttributes(PAL);
5440fe6060f1SDimitry Andric       propagateAttributeTypes(cast<CallBase>(I), ArgsTys);
5441*0b57cec5SDimitry Andric       if (FMF.any()) {
5442*0b57cec5SDimitry Andric         if (!isa<FPMathOperator>(I))
5443*0b57cec5SDimitry Andric           return error("Fast-math-flags specified for call without "
5444*0b57cec5SDimitry Andric                        "floating-point scalar or vector return type");
5445*0b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
5446*0b57cec5SDimitry Andric       }
5447*0b57cec5SDimitry Andric       break;
5448*0b57cec5SDimitry Andric     }
5449*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5450*0b57cec5SDimitry Andric       if (Record.size() < 3)
5451*0b57cec5SDimitry Andric         return error("Invalid record");
5452*0b57cec5SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
5453*0b57cec5SDimitry Andric       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5454fe6060f1SDimitry Andric       Type *ResTy = getTypeByID(Record[2]);
5455*0b57cec5SDimitry Andric       if (!OpTy || !Op || !ResTy)
5456*0b57cec5SDimitry Andric         return error("Invalid record");
5457*0b57cec5SDimitry Andric       I = new VAArgInst(Op, ResTy);
5458*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5459*0b57cec5SDimitry Andric       break;
5460*0b57cec5SDimitry Andric     }
5461*0b57cec5SDimitry Andric 
5462*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5463*0b57cec5SDimitry Andric       // A call or an invoke can be optionally prefixed with some variable
5464*0b57cec5SDimitry Andric       // number of operand bundle blocks.  These blocks are read into
5465*0b57cec5SDimitry Andric       // OperandBundles and consumed at the next call or invoke instruction.
5466*0b57cec5SDimitry Andric 
5467e8d8bef9SDimitry Andric       if (Record.empty() || Record[0] >= BundleTags.size())
5468*0b57cec5SDimitry Andric         return error("Invalid record");
5469*0b57cec5SDimitry Andric 
5470*0b57cec5SDimitry Andric       std::vector<Value *> Inputs;
5471*0b57cec5SDimitry Andric 
5472*0b57cec5SDimitry Andric       unsigned OpNum = 1;
5473*0b57cec5SDimitry Andric       while (OpNum != Record.size()) {
5474*0b57cec5SDimitry Andric         Value *Op;
5475*0b57cec5SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5476*0b57cec5SDimitry Andric           return error("Invalid record");
5477*0b57cec5SDimitry Andric         Inputs.push_back(Op);
5478*0b57cec5SDimitry Andric       }
5479*0b57cec5SDimitry Andric 
5480*0b57cec5SDimitry Andric       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5481*0b57cec5SDimitry Andric       continue;
5482*0b57cec5SDimitry Andric     }
5483480093f4SDimitry Andric 
5484480093f4SDimitry Andric     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
5485480093f4SDimitry Andric       unsigned OpNum = 0;
5486480093f4SDimitry Andric       Value *Op = nullptr;
5487fe6060f1SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5488480093f4SDimitry Andric         return error("Invalid record");
5489480093f4SDimitry Andric       if (OpNum != Record.size())
5490480093f4SDimitry Andric         return error("Invalid record");
5491480093f4SDimitry Andric 
5492480093f4SDimitry Andric       I = new FreezeInst(Op);
5493480093f4SDimitry Andric       InstructionList.push_back(I);
5494480093f4SDimitry Andric       break;
5495480093f4SDimitry Andric     }
5496*0b57cec5SDimitry Andric     }
5497*0b57cec5SDimitry Andric 
5498*0b57cec5SDimitry Andric     // Add instruction to end of current BB.  If there is no current BB, reject
5499*0b57cec5SDimitry Andric     // this file.
5500*0b57cec5SDimitry Andric     if (!CurBB) {
5501*0b57cec5SDimitry Andric       I->deleteValue();
5502*0b57cec5SDimitry Andric       return error("Invalid instruction with no BB");
5503*0b57cec5SDimitry Andric     }
5504*0b57cec5SDimitry Andric     if (!OperandBundles.empty()) {
5505*0b57cec5SDimitry Andric       I->deleteValue();
5506*0b57cec5SDimitry Andric       return error("Operand bundles found with no consumer");
5507*0b57cec5SDimitry Andric     }
5508*0b57cec5SDimitry Andric     CurBB->getInstList().push_back(I);
5509*0b57cec5SDimitry Andric 
5510*0b57cec5SDimitry Andric     // If this was a terminator instruction, move to the next block.
5511*0b57cec5SDimitry Andric     if (I->isTerminator()) {
5512*0b57cec5SDimitry Andric       ++CurBBNo;
5513*0b57cec5SDimitry Andric       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5514*0b57cec5SDimitry Andric     }
5515*0b57cec5SDimitry Andric 
5516*0b57cec5SDimitry Andric     // Non-void values get registered in the value table for future use.
5517fe6060f1SDimitry Andric     if (!I->getType()->isVoidTy())
5518fe6060f1SDimitry Andric       ValueList.assignValue(I, NextValueNo++);
5519*0b57cec5SDimitry Andric   }
5520*0b57cec5SDimitry Andric 
5521*0b57cec5SDimitry Andric OutOfRecordLoop:
5522*0b57cec5SDimitry Andric 
5523*0b57cec5SDimitry Andric   if (!OperandBundles.empty())
5524*0b57cec5SDimitry Andric     return error("Operand bundles found with no consumer");
5525*0b57cec5SDimitry Andric 
5526*0b57cec5SDimitry Andric   // Check the function list for unresolved values.
5527*0b57cec5SDimitry Andric   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5528*0b57cec5SDimitry Andric     if (!A->getParent()) {
5529*0b57cec5SDimitry Andric       // We found at least one unresolved value.  Nuke them all to avoid leaks.
5530*0b57cec5SDimitry Andric       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5531*0b57cec5SDimitry Andric         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5532*0b57cec5SDimitry Andric           A->replaceAllUsesWith(UndefValue::get(A->getType()));
5533*0b57cec5SDimitry Andric           delete A;
5534*0b57cec5SDimitry Andric         }
5535*0b57cec5SDimitry Andric       }
5536*0b57cec5SDimitry Andric       return error("Never resolved value found in function");
5537*0b57cec5SDimitry Andric     }
5538*0b57cec5SDimitry Andric   }
5539*0b57cec5SDimitry Andric 
5540*0b57cec5SDimitry Andric   // Unexpected unresolved metadata about to be dropped.
5541*0b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
5542*0b57cec5SDimitry Andric     return error("Invalid function metadata: outgoing forward refs");
5543*0b57cec5SDimitry Andric 
5544*0b57cec5SDimitry Andric   // Trim the value list down to the size it was before we parsed this function.
5545*0b57cec5SDimitry Andric   ValueList.shrinkTo(ModuleValueListSize);
5546*0b57cec5SDimitry Andric   MDLoader->shrinkTo(ModuleMDLoaderSize);
5547*0b57cec5SDimitry Andric   std::vector<BasicBlock*>().swap(FunctionBBs);
5548*0b57cec5SDimitry Andric   return Error::success();
5549*0b57cec5SDimitry Andric }
5550*0b57cec5SDimitry Andric 
5551*0b57cec5SDimitry Andric /// Find the function body in the bitcode stream
5552*0b57cec5SDimitry Andric Error BitcodeReader::findFunctionInStream(
5553*0b57cec5SDimitry Andric     Function *F,
5554*0b57cec5SDimitry Andric     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5555*0b57cec5SDimitry Andric   while (DeferredFunctionInfoIterator->second == 0) {
5556*0b57cec5SDimitry Andric     // This is the fallback handling for the old format bitcode that
5557*0b57cec5SDimitry Andric     // didn't contain the function index in the VST, or when we have
5558*0b57cec5SDimitry Andric     // an anonymous function which would not have a VST entry.
5559*0b57cec5SDimitry Andric     // Assert that we have one of those two cases.
5560*0b57cec5SDimitry Andric     assert(VSTOffset == 0 || !F->hasName());
5561*0b57cec5SDimitry Andric     // Parse the next body in the stream and set its position in the
5562*0b57cec5SDimitry Andric     // DeferredFunctionInfo map.
5563*0b57cec5SDimitry Andric     if (Error Err = rememberAndSkipFunctionBodies())
5564*0b57cec5SDimitry Andric       return Err;
5565*0b57cec5SDimitry Andric   }
5566*0b57cec5SDimitry Andric   return Error::success();
5567*0b57cec5SDimitry Andric }
5568*0b57cec5SDimitry Andric 
5569*0b57cec5SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
5570*0b57cec5SDimitry Andric   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
5571*0b57cec5SDimitry Andric     return SyncScope::ID(Val);
5572*0b57cec5SDimitry Andric   if (Val >= SSIDs.size())
5573*0b57cec5SDimitry Andric     return SyncScope::System; // Map unknown synchronization scopes to system.
5574*0b57cec5SDimitry Andric   return SSIDs[Val];
5575*0b57cec5SDimitry Andric }
5576*0b57cec5SDimitry Andric 
5577*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5578*0b57cec5SDimitry Andric // GVMaterializer implementation
5579*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
5580*0b57cec5SDimitry Andric 
5581*0b57cec5SDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) {
5582*0b57cec5SDimitry Andric   Function *F = dyn_cast<Function>(GV);
5583*0b57cec5SDimitry Andric   // If it's not a function or is already material, ignore the request.
5584*0b57cec5SDimitry Andric   if (!F || !F->isMaterializable())
5585*0b57cec5SDimitry Andric     return Error::success();
5586*0b57cec5SDimitry Andric 
5587*0b57cec5SDimitry Andric   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5588*0b57cec5SDimitry Andric   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5589*0b57cec5SDimitry Andric   // If its position is recorded as 0, its body is somewhere in the stream
5590*0b57cec5SDimitry Andric   // but we haven't seen it yet.
5591*0b57cec5SDimitry Andric   if (DFII->second == 0)
5592*0b57cec5SDimitry Andric     if (Error Err = findFunctionInStream(F, DFII))
5593*0b57cec5SDimitry Andric       return Err;
5594*0b57cec5SDimitry Andric 
5595*0b57cec5SDimitry Andric   // Materialize metadata before parsing any function bodies.
5596*0b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
5597*0b57cec5SDimitry Andric     return Err;
5598*0b57cec5SDimitry Andric 
5599*0b57cec5SDimitry Andric   // Move the bit stream to the saved position of the deferred function body.
5600*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
5601*0b57cec5SDimitry Andric     return JumpFailed;
5602*0b57cec5SDimitry Andric   if (Error Err = parseFunctionBody(F))
5603*0b57cec5SDimitry Andric     return Err;
5604*0b57cec5SDimitry Andric   F->setIsMaterializable(false);
5605*0b57cec5SDimitry Andric 
5606*0b57cec5SDimitry Andric   if (StripDebugInfo)
5607*0b57cec5SDimitry Andric     stripDebugInfo(*F);
5608*0b57cec5SDimitry Andric 
5609*0b57cec5SDimitry Andric   // Upgrade any old intrinsic calls in the function.
5610*0b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
5611349cc55cSDimitry Andric     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
5612*0b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
5613*0b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
5614*0b57cec5SDimitry Andric   }
5615*0b57cec5SDimitry Andric 
5616*0b57cec5SDimitry Andric   // Update calls to the remangled intrinsics
5617*0b57cec5SDimitry Andric   for (auto &I : RemangledIntrinsics)
5618349cc55cSDimitry Andric     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
5619*0b57cec5SDimitry Andric       // Don't expect any other users than call sites
5620349cc55cSDimitry Andric       cast<CallBase>(U)->setCalledFunction(I.second);
5621*0b57cec5SDimitry Andric 
5622*0b57cec5SDimitry Andric   // Finish fn->subprogram upgrade for materialized functions.
5623*0b57cec5SDimitry Andric   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
5624*0b57cec5SDimitry Andric     F->setSubprogram(SP);
5625*0b57cec5SDimitry Andric 
5626*0b57cec5SDimitry Andric   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
5627*0b57cec5SDimitry Andric   if (!MDLoader->isStrippingTBAA()) {
5628*0b57cec5SDimitry Andric     for (auto &I : instructions(F)) {
5629*0b57cec5SDimitry Andric       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
5630*0b57cec5SDimitry Andric       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
5631*0b57cec5SDimitry Andric         continue;
5632*0b57cec5SDimitry Andric       MDLoader->setStripTBAA(true);
5633*0b57cec5SDimitry Andric       stripTBAA(F->getParent());
5634*0b57cec5SDimitry Andric     }
5635*0b57cec5SDimitry Andric   }
5636*0b57cec5SDimitry Andric 
5637e8d8bef9SDimitry Andric   for (auto &I : instructions(F)) {
5638fe6060f1SDimitry Andric     // "Upgrade" older incorrect branch weights by dropping them.
5639e8d8bef9SDimitry Andric     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
5640e8d8bef9SDimitry Andric       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
5641e8d8bef9SDimitry Andric         MDString *MDS = cast<MDString>(MD->getOperand(0));
5642e8d8bef9SDimitry Andric         StringRef ProfName = MDS->getString();
5643e8d8bef9SDimitry Andric         // Check consistency of !prof branch_weights metadata.
5644e8d8bef9SDimitry Andric         if (!ProfName.equals("branch_weights"))
5645e8d8bef9SDimitry Andric           continue;
5646e8d8bef9SDimitry Andric         unsigned ExpectedNumOperands = 0;
5647e8d8bef9SDimitry Andric         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
5648e8d8bef9SDimitry Andric           ExpectedNumOperands = BI->getNumSuccessors();
5649e8d8bef9SDimitry Andric         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
5650e8d8bef9SDimitry Andric           ExpectedNumOperands = SI->getNumSuccessors();
5651e8d8bef9SDimitry Andric         else if (isa<CallInst>(&I))
5652e8d8bef9SDimitry Andric           ExpectedNumOperands = 1;
5653e8d8bef9SDimitry Andric         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
5654e8d8bef9SDimitry Andric           ExpectedNumOperands = IBI->getNumDestinations();
5655e8d8bef9SDimitry Andric         else if (isa<SelectInst>(&I))
5656e8d8bef9SDimitry Andric           ExpectedNumOperands = 2;
5657e8d8bef9SDimitry Andric         else
5658e8d8bef9SDimitry Andric           continue; // ignore and continue.
5659e8d8bef9SDimitry Andric 
5660e8d8bef9SDimitry Andric         // If branch weight doesn't match, just strip branch weight.
5661e8d8bef9SDimitry Andric         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
5662e8d8bef9SDimitry Andric           I.setMetadata(LLVMContext::MD_prof, nullptr);
5663e8d8bef9SDimitry Andric       }
5664e8d8bef9SDimitry Andric     }
5665fe6060f1SDimitry Andric 
5666fe6060f1SDimitry Andric     // Remove incompatible attributes on function calls.
5667fe6060f1SDimitry Andric     if (auto *CI = dyn_cast<CallBase>(&I)) {
5668349cc55cSDimitry Andric       CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
5669fe6060f1SDimitry Andric           CI->getFunctionType()->getReturnType()));
5670fe6060f1SDimitry Andric 
5671fe6060f1SDimitry Andric       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
5672fe6060f1SDimitry Andric         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
5673fe6060f1SDimitry Andric                                         CI->getArgOperand(ArgNo)->getType()));
5674fe6060f1SDimitry Andric     }
5675e8d8bef9SDimitry Andric   }
5676e8d8bef9SDimitry Andric 
56775ffd83dbSDimitry Andric   // Look for functions that rely on old function attribute behavior.
56785ffd83dbSDimitry Andric   UpgradeFunctionAttributes(*F);
56795ffd83dbSDimitry Andric 
5680*0b57cec5SDimitry Andric   // Bring in any functions that this function forward-referenced via
5681*0b57cec5SDimitry Andric   // blockaddresses.
5682*0b57cec5SDimitry Andric   return materializeForwardReferencedFunctions();
5683*0b57cec5SDimitry Andric }
5684*0b57cec5SDimitry Andric 
5685*0b57cec5SDimitry Andric Error BitcodeReader::materializeModule() {
5686*0b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
5687*0b57cec5SDimitry Andric     return Err;
5688*0b57cec5SDimitry Andric 
5689*0b57cec5SDimitry Andric   // Promise to materialize all forward references.
5690*0b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = true;
5691*0b57cec5SDimitry Andric 
5692*0b57cec5SDimitry Andric   // Iterate over the module, deserializing any functions that are still on
5693*0b57cec5SDimitry Andric   // disk.
5694*0b57cec5SDimitry Andric   for (Function &F : *TheModule) {
5695*0b57cec5SDimitry Andric     if (Error Err = materialize(&F))
5696*0b57cec5SDimitry Andric       return Err;
5697*0b57cec5SDimitry Andric   }
5698*0b57cec5SDimitry Andric   // At this point, if there are any function bodies, parse the rest of
5699*0b57cec5SDimitry Andric   // the bits in the module past the last function block we have recorded
5700*0b57cec5SDimitry Andric   // through either lazy scanning or the VST.
5701*0b57cec5SDimitry Andric   if (LastFunctionBlockBit || NextUnreadBit)
5702*0b57cec5SDimitry Andric     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
5703*0b57cec5SDimitry Andric                                     ? LastFunctionBlockBit
5704*0b57cec5SDimitry Andric                                     : NextUnreadBit))
5705*0b57cec5SDimitry Andric       return Err;
5706*0b57cec5SDimitry Andric 
5707*0b57cec5SDimitry Andric   // Check that all block address forward references got resolved (as we
5708*0b57cec5SDimitry Andric   // promised above).
5709*0b57cec5SDimitry Andric   if (!BasicBlockFwdRefs.empty())
5710*0b57cec5SDimitry Andric     return error("Never resolved function from blockaddress");
5711*0b57cec5SDimitry Andric 
5712*0b57cec5SDimitry Andric   // Upgrade any intrinsic calls that slipped through (should not happen!) and
5713*0b57cec5SDimitry Andric   // delete the old functions to clean up. We can't do this unless the entire
5714*0b57cec5SDimitry Andric   // module is materialized because there could always be another function body
5715*0b57cec5SDimitry Andric   // with calls to the old function.
5716*0b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
5717*0b57cec5SDimitry Andric     for (auto *U : I.first->users()) {
5718*0b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
5719*0b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
5720*0b57cec5SDimitry Andric     }
5721*0b57cec5SDimitry Andric     if (!I.first->use_empty())
5722*0b57cec5SDimitry Andric       I.first->replaceAllUsesWith(I.second);
5723*0b57cec5SDimitry Andric     I.first->eraseFromParent();
5724*0b57cec5SDimitry Andric   }
5725*0b57cec5SDimitry Andric   UpgradedIntrinsics.clear();
5726*0b57cec5SDimitry Andric   // Do the same for remangled intrinsics
5727*0b57cec5SDimitry Andric   for (auto &I : RemangledIntrinsics) {
5728*0b57cec5SDimitry Andric     I.first->replaceAllUsesWith(I.second);
5729*0b57cec5SDimitry Andric     I.first->eraseFromParent();
5730*0b57cec5SDimitry Andric   }
5731*0b57cec5SDimitry Andric   RemangledIntrinsics.clear();
5732*0b57cec5SDimitry Andric 
5733*0b57cec5SDimitry Andric   UpgradeDebugInfo(*TheModule);
5734*0b57cec5SDimitry Andric 
5735*0b57cec5SDimitry Andric   UpgradeModuleFlags(*TheModule);
5736*0b57cec5SDimitry Andric 
57378bcb0991SDimitry Andric   UpgradeARCRuntime(*TheModule);
5738*0b57cec5SDimitry Andric 
5739*0b57cec5SDimitry Andric   return Error::success();
5740*0b57cec5SDimitry Andric }
5741*0b57cec5SDimitry Andric 
5742*0b57cec5SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5743*0b57cec5SDimitry Andric   return IdentifiedStructTypes;
5744*0b57cec5SDimitry Andric }
5745*0b57cec5SDimitry Andric 
5746*0b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5747*0b57cec5SDimitry Andric     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
5748*0b57cec5SDimitry Andric     StringRef ModulePath, unsigned ModuleId)
5749*0b57cec5SDimitry Andric     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
5750*0b57cec5SDimitry Andric       ModulePath(ModulePath), ModuleId(ModuleId) {}
5751*0b57cec5SDimitry Andric 
5752*0b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::addThisModule() {
5753*0b57cec5SDimitry Andric   TheIndex.addModule(ModulePath, ModuleId);
5754*0b57cec5SDimitry Andric }
5755*0b57cec5SDimitry Andric 
5756*0b57cec5SDimitry Andric ModuleSummaryIndex::ModuleInfo *
5757*0b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getThisModule() {
5758*0b57cec5SDimitry Andric   return TheIndex.getModule(ModulePath);
5759*0b57cec5SDimitry Andric }
5760*0b57cec5SDimitry Andric 
5761*0b57cec5SDimitry Andric std::pair<ValueInfo, GlobalValue::GUID>
5762*0b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
5763*0b57cec5SDimitry Andric   auto VGI = ValueIdToValueInfoMap[ValueId];
5764*0b57cec5SDimitry Andric   assert(VGI.first);
5765*0b57cec5SDimitry Andric   return VGI;
5766*0b57cec5SDimitry Andric }
5767*0b57cec5SDimitry Andric 
5768*0b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID(
5769*0b57cec5SDimitry Andric     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
5770*0b57cec5SDimitry Andric     StringRef SourceFileName) {
5771*0b57cec5SDimitry Andric   std::string GlobalId =
5772*0b57cec5SDimitry Andric       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
5773*0b57cec5SDimitry Andric   auto ValueGUID = GlobalValue::getGUID(GlobalId);
5774*0b57cec5SDimitry Andric   auto OriginalNameID = ValueGUID;
5775*0b57cec5SDimitry Andric   if (GlobalValue::isLocalLinkage(Linkage))
5776*0b57cec5SDimitry Andric     OriginalNameID = GlobalValue::getGUID(ValueName);
5777*0b57cec5SDimitry Andric   if (PrintSummaryGUIDs)
5778*0b57cec5SDimitry Andric     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5779*0b57cec5SDimitry Andric            << ValueName << "\n";
5780*0b57cec5SDimitry Andric 
5781*0b57cec5SDimitry Andric   // UseStrtab is false for legacy summary formats and value names are
5782*0b57cec5SDimitry Andric   // created on stack. In that case we save the name in a string saver in
5783*0b57cec5SDimitry Andric   // the index so that the value name can be recorded.
5784*0b57cec5SDimitry Andric   ValueIdToValueInfoMap[ValueID] = std::make_pair(
5785*0b57cec5SDimitry Andric       TheIndex.getOrInsertValueInfo(
5786*0b57cec5SDimitry Andric           ValueGUID,
5787*0b57cec5SDimitry Andric           UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
5788*0b57cec5SDimitry Andric       OriginalNameID);
5789*0b57cec5SDimitry Andric }
5790*0b57cec5SDimitry Andric 
5791*0b57cec5SDimitry Andric // Specialized value symbol table parser used when reading module index
5792*0b57cec5SDimitry Andric // blocks where we don't actually create global values. The parsed information
5793*0b57cec5SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries.
5794*0b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5795*0b57cec5SDimitry Andric     uint64_t Offset,
5796*0b57cec5SDimitry Andric     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5797*0b57cec5SDimitry Andric   // With a strtab the VST is not required to parse the summary.
5798*0b57cec5SDimitry Andric   if (UseStrtab)
5799*0b57cec5SDimitry Andric     return Error::success();
5800*0b57cec5SDimitry Andric 
5801*0b57cec5SDimitry Andric   assert(Offset > 0 && "Expected non-zero VST offset");
5802*0b57cec5SDimitry Andric   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
5803*0b57cec5SDimitry Andric   if (!MaybeCurrentBit)
5804*0b57cec5SDimitry Andric     return MaybeCurrentBit.takeError();
5805*0b57cec5SDimitry Andric   uint64_t CurrentBit = MaybeCurrentBit.get();
5806*0b57cec5SDimitry Andric 
5807*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5808*0b57cec5SDimitry Andric     return Err;
5809*0b57cec5SDimitry Andric 
5810*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
5811*0b57cec5SDimitry Andric 
5812*0b57cec5SDimitry Andric   // Read all the records for this value table.
5813*0b57cec5SDimitry Andric   SmallString<128> ValueName;
5814*0b57cec5SDimitry Andric 
5815*0b57cec5SDimitry Andric   while (true) {
5816*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
5817*0b57cec5SDimitry Andric     if (!MaybeEntry)
5818*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
5819*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
5820*0b57cec5SDimitry Andric 
5821*0b57cec5SDimitry Andric     switch (Entry.Kind) {
5822*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
5823*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
5824*0b57cec5SDimitry Andric       return error("Malformed block");
5825*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
5826*0b57cec5SDimitry Andric       // Done parsing VST, jump back to wherever we came from.
5827*0b57cec5SDimitry Andric       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
5828*0b57cec5SDimitry Andric         return JumpFailed;
5829*0b57cec5SDimitry Andric       return Error::success();
5830*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
5831*0b57cec5SDimitry Andric       // The interesting case.
5832*0b57cec5SDimitry Andric       break;
5833*0b57cec5SDimitry Andric     }
5834*0b57cec5SDimitry Andric 
5835*0b57cec5SDimitry Andric     // Read a record.
5836*0b57cec5SDimitry Andric     Record.clear();
5837*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
5838*0b57cec5SDimitry Andric     if (!MaybeRecord)
5839*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
5840*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
5841*0b57cec5SDimitry Andric     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5842*0b57cec5SDimitry Andric       break;
5843*0b57cec5SDimitry Andric     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5844*0b57cec5SDimitry Andric       if (convertToString(Record, 1, ValueName))
5845*0b57cec5SDimitry Andric         return error("Invalid record");
5846*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
5847*0b57cec5SDimitry Andric       assert(!SourceFileName.empty());
5848*0b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
5849*0b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
5850*0b57cec5SDimitry Andric              "No linkage found for VST entry?");
5851*0b57cec5SDimitry Andric       auto Linkage = VLI->second;
5852*0b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5853*0b57cec5SDimitry Andric       ValueName.clear();
5854*0b57cec5SDimitry Andric       break;
5855*0b57cec5SDimitry Andric     }
5856*0b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
5857*0b57cec5SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5858*0b57cec5SDimitry Andric       if (convertToString(Record, 2, ValueName))
5859*0b57cec5SDimitry Andric         return error("Invalid record");
5860*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
5861*0b57cec5SDimitry Andric       assert(!SourceFileName.empty());
5862*0b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
5863*0b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
5864*0b57cec5SDimitry Andric              "No linkage found for VST entry?");
5865*0b57cec5SDimitry Andric       auto Linkage = VLI->second;
5866*0b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5867*0b57cec5SDimitry Andric       ValueName.clear();
5868*0b57cec5SDimitry Andric       break;
5869*0b57cec5SDimitry Andric     }
5870*0b57cec5SDimitry Andric     case bitc::VST_CODE_COMBINED_ENTRY: {
5871*0b57cec5SDimitry Andric       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5872*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
5873*0b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
5874*0b57cec5SDimitry Andric       // The "original name", which is the second value of the pair will be
5875*0b57cec5SDimitry Andric       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5876*0b57cec5SDimitry Andric       ValueIdToValueInfoMap[ValueID] =
5877*0b57cec5SDimitry Andric           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5878*0b57cec5SDimitry Andric       break;
5879*0b57cec5SDimitry Andric     }
5880*0b57cec5SDimitry Andric     }
5881*0b57cec5SDimitry Andric   }
5882*0b57cec5SDimitry Andric }
5883*0b57cec5SDimitry Andric 
5884*0b57cec5SDimitry Andric // Parse just the blocks needed for building the index out of the module.
5885*0b57cec5SDimitry Andric // At the end of this routine the module Index is populated with a map
5886*0b57cec5SDimitry Andric // from global value id to GlobalValueSummary objects.
5887*0b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() {
5888*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5889*0b57cec5SDimitry Andric     return Err;
5890*0b57cec5SDimitry Andric 
5891*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
5892*0b57cec5SDimitry Andric   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5893*0b57cec5SDimitry Andric   unsigned ValueId = 0;
5894*0b57cec5SDimitry Andric 
5895*0b57cec5SDimitry Andric   // Read the index for this module.
5896*0b57cec5SDimitry Andric   while (true) {
5897*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5898*0b57cec5SDimitry Andric     if (!MaybeEntry)
5899*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
5900*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
5901*0b57cec5SDimitry Andric 
5902*0b57cec5SDimitry Andric     switch (Entry.Kind) {
5903*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
5904*0b57cec5SDimitry Andric       return error("Malformed block");
5905*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
5906*0b57cec5SDimitry Andric       return Error::success();
5907*0b57cec5SDimitry Andric 
5908*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
5909*0b57cec5SDimitry Andric       switch (Entry.ID) {
5910*0b57cec5SDimitry Andric       default: // Skip unknown content.
5911*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
5912*0b57cec5SDimitry Andric           return Err;
5913*0b57cec5SDimitry Andric         break;
5914*0b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
5915*0b57cec5SDimitry Andric         // Need to parse these to get abbrev ids (e.g. for VST)
5916*0b57cec5SDimitry Andric         if (readBlockInfo())
5917*0b57cec5SDimitry Andric           return error("Malformed block");
5918*0b57cec5SDimitry Andric         break;
5919*0b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
5920*0b57cec5SDimitry Andric         // Should have been parsed earlier via VSTOffset, unless there
5921*0b57cec5SDimitry Andric         // is no summary section.
5922*0b57cec5SDimitry Andric         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5923*0b57cec5SDimitry Andric                 !SeenGlobalValSummary) &&
5924*0b57cec5SDimitry Andric                "Expected early VST parse via VSTOffset record");
5925*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
5926*0b57cec5SDimitry Andric           return Err;
5927*0b57cec5SDimitry Andric         break;
5928*0b57cec5SDimitry Andric       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5929*0b57cec5SDimitry Andric       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
5930*0b57cec5SDimitry Andric         // Add the module if it is a per-module index (has a source file name).
5931*0b57cec5SDimitry Andric         if (!SourceFileName.empty())
5932*0b57cec5SDimitry Andric           addThisModule();
5933*0b57cec5SDimitry Andric         assert(!SeenValueSymbolTable &&
5934*0b57cec5SDimitry Andric                "Already read VST when parsing summary block?");
5935*0b57cec5SDimitry Andric         // We might not have a VST if there were no values in the
5936*0b57cec5SDimitry Andric         // summary. An empty summary block generated when we are
5937*0b57cec5SDimitry Andric         // performing ThinLTO compiles so we don't later invoke
5938*0b57cec5SDimitry Andric         // the regular LTO process on them.
5939*0b57cec5SDimitry Andric         if (VSTOffset > 0) {
5940*0b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5941*0b57cec5SDimitry Andric             return Err;
5942*0b57cec5SDimitry Andric           SeenValueSymbolTable = true;
5943*0b57cec5SDimitry Andric         }
5944*0b57cec5SDimitry Andric         SeenGlobalValSummary = true;
5945*0b57cec5SDimitry Andric         if (Error Err = parseEntireSummary(Entry.ID))
5946*0b57cec5SDimitry Andric           return Err;
5947*0b57cec5SDimitry Andric         break;
5948*0b57cec5SDimitry Andric       case bitc::MODULE_STRTAB_BLOCK_ID:
5949*0b57cec5SDimitry Andric         if (Error Err = parseModuleStringTable())
5950*0b57cec5SDimitry Andric           return Err;
5951*0b57cec5SDimitry Andric         break;
5952*0b57cec5SDimitry Andric       }
5953*0b57cec5SDimitry Andric       continue;
5954*0b57cec5SDimitry Andric 
5955*0b57cec5SDimitry Andric     case BitstreamEntry::Record: {
5956*0b57cec5SDimitry Andric         Record.clear();
5957*0b57cec5SDimitry Andric         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
5958*0b57cec5SDimitry Andric         if (!MaybeBitCode)
5959*0b57cec5SDimitry Andric           return MaybeBitCode.takeError();
5960*0b57cec5SDimitry Andric         switch (MaybeBitCode.get()) {
5961*0b57cec5SDimitry Andric         default:
5962*0b57cec5SDimitry Andric           break; // Default behavior, ignore unknown content.
5963*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_VERSION: {
5964*0b57cec5SDimitry Andric           if (Error Err = parseVersionRecord(Record).takeError())
5965*0b57cec5SDimitry Andric             return Err;
5966*0b57cec5SDimitry Andric           break;
5967*0b57cec5SDimitry Andric         }
5968*0b57cec5SDimitry Andric         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5969*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_SOURCE_FILENAME: {
5970*0b57cec5SDimitry Andric           SmallString<128> ValueName;
5971*0b57cec5SDimitry Andric           if (convertToString(Record, 0, ValueName))
5972*0b57cec5SDimitry Andric             return error("Invalid record");
5973*0b57cec5SDimitry Andric           SourceFileName = ValueName.c_str();
5974*0b57cec5SDimitry Andric           break;
5975*0b57cec5SDimitry Andric         }
5976*0b57cec5SDimitry Andric         /// MODULE_CODE_HASH: [5*i32]
5977*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_HASH: {
5978*0b57cec5SDimitry Andric           if (Record.size() != 5)
5979*0b57cec5SDimitry Andric             return error("Invalid hash length " + Twine(Record.size()).str());
5980*0b57cec5SDimitry Andric           auto &Hash = getThisModule()->second.second;
5981*0b57cec5SDimitry Andric           int Pos = 0;
5982*0b57cec5SDimitry Andric           for (auto &Val : Record) {
5983*0b57cec5SDimitry Andric             assert(!(Val >> 32) && "Unexpected high bits set");
5984*0b57cec5SDimitry Andric             Hash[Pos++] = Val;
5985*0b57cec5SDimitry Andric           }
5986*0b57cec5SDimitry Andric           break;
5987*0b57cec5SDimitry Andric         }
5988*0b57cec5SDimitry Andric         /// MODULE_CODE_VSTOFFSET: [offset]
5989*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_VSTOFFSET:
5990e8d8bef9SDimitry Andric           if (Record.empty())
5991*0b57cec5SDimitry Andric             return error("Invalid record");
5992*0b57cec5SDimitry Andric           // Note that we subtract 1 here because the offset is relative to one
5993*0b57cec5SDimitry Andric           // word before the start of the identification or module block, which
5994*0b57cec5SDimitry Andric           // was historically always the start of the regular bitcode header.
5995*0b57cec5SDimitry Andric           VSTOffset = Record[0] - 1;
5996*0b57cec5SDimitry Andric           break;
5997*0b57cec5SDimitry Andric         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
5998*0b57cec5SDimitry Andric         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
5999*0b57cec5SDimitry Andric         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
6000*0b57cec5SDimitry Andric         // v2: [strtab offset, strtab size, v1]
6001*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_GLOBALVAR:
6002*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_FUNCTION:
6003*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_ALIAS: {
6004*0b57cec5SDimitry Andric           StringRef Name;
6005*0b57cec5SDimitry Andric           ArrayRef<uint64_t> GVRecord;
6006*0b57cec5SDimitry Andric           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
6007*0b57cec5SDimitry Andric           if (GVRecord.size() <= 3)
6008*0b57cec5SDimitry Andric             return error("Invalid record");
6009*0b57cec5SDimitry Andric           uint64_t RawLinkage = GVRecord[3];
6010*0b57cec5SDimitry Andric           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6011*0b57cec5SDimitry Andric           if (!UseStrtab) {
6012*0b57cec5SDimitry Andric             ValueIdToLinkageMap[ValueId++] = Linkage;
6013*0b57cec5SDimitry Andric             break;
6014*0b57cec5SDimitry Andric           }
6015*0b57cec5SDimitry Andric 
6016*0b57cec5SDimitry Andric           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
6017*0b57cec5SDimitry Andric           break;
6018*0b57cec5SDimitry Andric         }
6019*0b57cec5SDimitry Andric         }
6020*0b57cec5SDimitry Andric       }
6021*0b57cec5SDimitry Andric       continue;
6022*0b57cec5SDimitry Andric     }
6023*0b57cec5SDimitry Andric   }
6024*0b57cec5SDimitry Andric }
6025*0b57cec5SDimitry Andric 
6026*0b57cec5SDimitry Andric std::vector<ValueInfo>
6027*0b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
6028*0b57cec5SDimitry Andric   std::vector<ValueInfo> Ret;
6029*0b57cec5SDimitry Andric   Ret.reserve(Record.size());
6030*0b57cec5SDimitry Andric   for (uint64_t RefValueId : Record)
6031*0b57cec5SDimitry Andric     Ret.push_back(getValueInfoFromValueId(RefValueId).first);
6032*0b57cec5SDimitry Andric   return Ret;
6033*0b57cec5SDimitry Andric }
6034*0b57cec5SDimitry Andric 
6035*0b57cec5SDimitry Andric std::vector<FunctionSummary::EdgeTy>
6036*0b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
6037*0b57cec5SDimitry Andric                                               bool IsOldProfileFormat,
6038*0b57cec5SDimitry Andric                                               bool HasProfile, bool HasRelBF) {
6039*0b57cec5SDimitry Andric   std::vector<FunctionSummary::EdgeTy> Ret;
6040*0b57cec5SDimitry Andric   Ret.reserve(Record.size());
6041*0b57cec5SDimitry Andric   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
6042*0b57cec5SDimitry Andric     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
6043*0b57cec5SDimitry Andric     uint64_t RelBF = 0;
6044*0b57cec5SDimitry Andric     ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6045*0b57cec5SDimitry Andric     if (IsOldProfileFormat) {
6046*0b57cec5SDimitry Andric       I += 1; // Skip old callsitecount field
6047*0b57cec5SDimitry Andric       if (HasProfile)
6048*0b57cec5SDimitry Andric         I += 1; // Skip old profilecount field
6049*0b57cec5SDimitry Andric     } else if (HasProfile)
6050*0b57cec5SDimitry Andric       Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
6051*0b57cec5SDimitry Andric     else if (HasRelBF)
6052*0b57cec5SDimitry Andric       RelBF = Record[++I];
6053*0b57cec5SDimitry Andric     Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
6054*0b57cec5SDimitry Andric   }
6055*0b57cec5SDimitry Andric   return Ret;
6056*0b57cec5SDimitry Andric }
6057*0b57cec5SDimitry Andric 
6058*0b57cec5SDimitry Andric static void
6059*0b57cec5SDimitry Andric parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
6060*0b57cec5SDimitry Andric                                        WholeProgramDevirtResolution &Wpd) {
6061*0b57cec5SDimitry Andric   uint64_t ArgNum = Record[Slot++];
6062*0b57cec5SDimitry Andric   WholeProgramDevirtResolution::ByArg &B =
6063*0b57cec5SDimitry Andric       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
6064*0b57cec5SDimitry Andric   Slot += ArgNum;
6065*0b57cec5SDimitry Andric 
6066*0b57cec5SDimitry Andric   B.TheKind =
6067*0b57cec5SDimitry Andric       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
6068*0b57cec5SDimitry Andric   B.Info = Record[Slot++];
6069*0b57cec5SDimitry Andric   B.Byte = Record[Slot++];
6070*0b57cec5SDimitry Andric   B.Bit = Record[Slot++];
6071*0b57cec5SDimitry Andric }
6072*0b57cec5SDimitry Andric 
6073*0b57cec5SDimitry Andric static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
6074*0b57cec5SDimitry Andric                                               StringRef Strtab, size_t &Slot,
6075*0b57cec5SDimitry Andric                                               TypeIdSummary &TypeId) {
6076*0b57cec5SDimitry Andric   uint64_t Id = Record[Slot++];
6077*0b57cec5SDimitry Andric   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
6078*0b57cec5SDimitry Andric 
6079*0b57cec5SDimitry Andric   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
6080*0b57cec5SDimitry Andric   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
6081*0b57cec5SDimitry Andric                         static_cast<size_t>(Record[Slot + 1])};
6082*0b57cec5SDimitry Andric   Slot += 2;
6083*0b57cec5SDimitry Andric 
6084*0b57cec5SDimitry Andric   uint64_t ResByArgNum = Record[Slot++];
6085*0b57cec5SDimitry Andric   for (uint64_t I = 0; I != ResByArgNum; ++I)
6086*0b57cec5SDimitry Andric     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
6087*0b57cec5SDimitry Andric }
6088*0b57cec5SDimitry Andric 
6089*0b57cec5SDimitry Andric static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
6090*0b57cec5SDimitry Andric                                      StringRef Strtab,
6091*0b57cec5SDimitry Andric                                      ModuleSummaryIndex &TheIndex) {
6092*0b57cec5SDimitry Andric   size_t Slot = 0;
6093*0b57cec5SDimitry Andric   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
6094*0b57cec5SDimitry Andric       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
6095*0b57cec5SDimitry Andric   Slot += 2;
6096*0b57cec5SDimitry Andric 
6097*0b57cec5SDimitry Andric   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
6098*0b57cec5SDimitry Andric   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
6099*0b57cec5SDimitry Andric   TypeId.TTRes.AlignLog2 = Record[Slot++];
6100*0b57cec5SDimitry Andric   TypeId.TTRes.SizeM1 = Record[Slot++];
6101*0b57cec5SDimitry Andric   TypeId.TTRes.BitMask = Record[Slot++];
6102*0b57cec5SDimitry Andric   TypeId.TTRes.InlineBits = Record[Slot++];
6103*0b57cec5SDimitry Andric 
6104*0b57cec5SDimitry Andric   while (Slot < Record.size())
6105*0b57cec5SDimitry Andric     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
6106*0b57cec5SDimitry Andric }
6107*0b57cec5SDimitry Andric 
6108e8d8bef9SDimitry Andric std::vector<FunctionSummary::ParamAccess>
6109e8d8bef9SDimitry Andric ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
61105ffd83dbSDimitry Andric   auto ReadRange = [&]() {
61115ffd83dbSDimitry Andric     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
61125ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
61135ffd83dbSDimitry Andric     Record = Record.drop_front();
61145ffd83dbSDimitry Andric     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
61155ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
61165ffd83dbSDimitry Andric     Record = Record.drop_front();
61175ffd83dbSDimitry Andric     ConstantRange Range{Lower, Upper};
61185ffd83dbSDimitry Andric     assert(!Range.isFullSet());
61195ffd83dbSDimitry Andric     assert(!Range.isUpperSignWrapped());
61205ffd83dbSDimitry Andric     return Range;
61215ffd83dbSDimitry Andric   };
61225ffd83dbSDimitry Andric 
61235ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
61245ffd83dbSDimitry Andric   while (!Record.empty()) {
61255ffd83dbSDimitry Andric     PendingParamAccesses.emplace_back();
61265ffd83dbSDimitry Andric     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
61275ffd83dbSDimitry Andric     ParamAccess.ParamNo = Record.front();
61285ffd83dbSDimitry Andric     Record = Record.drop_front();
61295ffd83dbSDimitry Andric     ParamAccess.Use = ReadRange();
61305ffd83dbSDimitry Andric     ParamAccess.Calls.resize(Record.front());
61315ffd83dbSDimitry Andric     Record = Record.drop_front();
61325ffd83dbSDimitry Andric     for (auto &Call : ParamAccess.Calls) {
61335ffd83dbSDimitry Andric       Call.ParamNo = Record.front();
61345ffd83dbSDimitry Andric       Record = Record.drop_front();
6135e8d8bef9SDimitry Andric       Call.Callee = getValueInfoFromValueId(Record.front()).first;
61365ffd83dbSDimitry Andric       Record = Record.drop_front();
61375ffd83dbSDimitry Andric       Call.Offsets = ReadRange();
61385ffd83dbSDimitry Andric     }
61395ffd83dbSDimitry Andric   }
61405ffd83dbSDimitry Andric   return PendingParamAccesses;
61415ffd83dbSDimitry Andric }
61425ffd83dbSDimitry Andric 
6143*0b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
6144*0b57cec5SDimitry Andric     ArrayRef<uint64_t> Record, size_t &Slot,
6145*0b57cec5SDimitry Andric     TypeIdCompatibleVtableInfo &TypeId) {
6146*0b57cec5SDimitry Andric   uint64_t Offset = Record[Slot++];
6147*0b57cec5SDimitry Andric   ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first;
6148*0b57cec5SDimitry Andric   TypeId.push_back({Offset, Callee});
6149*0b57cec5SDimitry Andric }
6150*0b57cec5SDimitry Andric 
6151*0b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
6152*0b57cec5SDimitry Andric     ArrayRef<uint64_t> Record) {
6153*0b57cec5SDimitry Andric   size_t Slot = 0;
6154*0b57cec5SDimitry Andric   TypeIdCompatibleVtableInfo &TypeId =
6155*0b57cec5SDimitry Andric       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
6156*0b57cec5SDimitry Andric           {Strtab.data() + Record[Slot],
6157*0b57cec5SDimitry Andric            static_cast<size_t>(Record[Slot + 1])});
6158*0b57cec5SDimitry Andric   Slot += 2;
6159*0b57cec5SDimitry Andric 
6160*0b57cec5SDimitry Andric   while (Slot < Record.size())
6161*0b57cec5SDimitry Andric     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
6162*0b57cec5SDimitry Andric }
6163*0b57cec5SDimitry Andric 
6164*0b57cec5SDimitry Andric static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
6165*0b57cec5SDimitry Andric                            unsigned WOCnt) {
6166*0b57cec5SDimitry Andric   // Readonly and writeonly refs are in the end of the refs list.
6167*0b57cec5SDimitry Andric   assert(ROCnt + WOCnt <= Refs.size());
6168*0b57cec5SDimitry Andric   unsigned FirstWORef = Refs.size() - WOCnt;
6169*0b57cec5SDimitry Andric   unsigned RefNo = FirstWORef - ROCnt;
6170*0b57cec5SDimitry Andric   for (; RefNo < FirstWORef; ++RefNo)
6171*0b57cec5SDimitry Andric     Refs[RefNo].setReadOnly();
6172*0b57cec5SDimitry Andric   for (; RefNo < Refs.size(); ++RefNo)
6173*0b57cec5SDimitry Andric     Refs[RefNo].setWriteOnly();
6174*0b57cec5SDimitry Andric }
6175*0b57cec5SDimitry Andric 
6176*0b57cec5SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary
6177*0b57cec5SDimitry Andric // objects in the index.
6178*0b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
6179*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
6180*0b57cec5SDimitry Andric     return Err;
6181*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
6182*0b57cec5SDimitry Andric 
6183*0b57cec5SDimitry Andric   // Parse version
6184*0b57cec5SDimitry Andric   {
6185*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6186*0b57cec5SDimitry Andric     if (!MaybeEntry)
6187*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
6188*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
6189*0b57cec5SDimitry Andric 
6190*0b57cec5SDimitry Andric     if (Entry.Kind != BitstreamEntry::Record)
6191*0b57cec5SDimitry Andric       return error("Invalid Summary Block: record for version expected");
6192*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6193*0b57cec5SDimitry Andric     if (!MaybeRecord)
6194*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
6195*0b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::FS_VERSION)
6196*0b57cec5SDimitry Andric       return error("Invalid Summary Block: version expected");
6197*0b57cec5SDimitry Andric   }
6198*0b57cec5SDimitry Andric   const uint64_t Version = Record[0];
6199*0b57cec5SDimitry Andric   const bool IsOldProfileFormat = Version == 1;
6200480093f4SDimitry Andric   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
6201*0b57cec5SDimitry Andric     return error("Invalid summary version " + Twine(Version) +
6202480093f4SDimitry Andric                  ". Version should be in the range [1-" +
6203480093f4SDimitry Andric                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
6204480093f4SDimitry Andric                  "].");
6205*0b57cec5SDimitry Andric   Record.clear();
6206*0b57cec5SDimitry Andric 
6207*0b57cec5SDimitry Andric   // Keep around the last seen summary to be used when we see an optional
6208*0b57cec5SDimitry Andric   // "OriginalName" attachement.
6209*0b57cec5SDimitry Andric   GlobalValueSummary *LastSeenSummary = nullptr;
6210*0b57cec5SDimitry Andric   GlobalValue::GUID LastSeenGUID = 0;
6211*0b57cec5SDimitry Andric 
6212*0b57cec5SDimitry Andric   // We can expect to see any number of type ID information records before
6213*0b57cec5SDimitry Andric   // each function summary records; these variables store the information
6214*0b57cec5SDimitry Andric   // collected so far so that it can be used to create the summary object.
6215*0b57cec5SDimitry Andric   std::vector<GlobalValue::GUID> PendingTypeTests;
6216*0b57cec5SDimitry Andric   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
6217*0b57cec5SDimitry Andric       PendingTypeCheckedLoadVCalls;
6218*0b57cec5SDimitry Andric   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
6219*0b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls;
62205ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6221*0b57cec5SDimitry Andric 
6222*0b57cec5SDimitry Andric   while (true) {
6223*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6224*0b57cec5SDimitry Andric     if (!MaybeEntry)
6225*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
6226*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
6227*0b57cec5SDimitry Andric 
6228*0b57cec5SDimitry Andric     switch (Entry.Kind) {
6229*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
6230*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
6231*0b57cec5SDimitry Andric       return error("Malformed block");
6232*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
6233*0b57cec5SDimitry Andric       return Error::success();
6234*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
6235*0b57cec5SDimitry Andric       // The interesting case.
6236*0b57cec5SDimitry Andric       break;
6237*0b57cec5SDimitry Andric     }
6238*0b57cec5SDimitry Andric 
6239*0b57cec5SDimitry Andric     // Read a record. The record format depends on whether this
6240*0b57cec5SDimitry Andric     // is a per-module index or a combined index file. In the per-module
6241*0b57cec5SDimitry Andric     // case the records contain the associated value's ID for correlation
6242*0b57cec5SDimitry Andric     // with VST entries. In the combined index the correlation is done
6243*0b57cec5SDimitry Andric     // via the bitcode offset of the summary records (which were saved
6244*0b57cec5SDimitry Andric     // in the combined index VST entries). The records also contain
6245*0b57cec5SDimitry Andric     // information used for ThinLTO renaming and importing.
6246*0b57cec5SDimitry Andric     Record.clear();
6247*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6248*0b57cec5SDimitry Andric     if (!MaybeBitCode)
6249*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
6250*0b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
6251*0b57cec5SDimitry Andric     default: // Default behavior: ignore.
6252*0b57cec5SDimitry Andric       break;
6253*0b57cec5SDimitry Andric     case bitc::FS_FLAGS: {  // [flags]
62545ffd83dbSDimitry Andric       TheIndex.setFlags(Record[0]);
6255*0b57cec5SDimitry Andric       break;
6256*0b57cec5SDimitry Andric     }
6257*0b57cec5SDimitry Andric     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
6258*0b57cec5SDimitry Andric       uint64_t ValueID = Record[0];
6259*0b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
6260*0b57cec5SDimitry Andric       ValueIdToValueInfoMap[ValueID] =
6261*0b57cec5SDimitry Andric           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
6262*0b57cec5SDimitry Andric       break;
6263*0b57cec5SDimitry Andric     }
6264*0b57cec5SDimitry Andric     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
6265*0b57cec5SDimitry Andric     //                numrefs x valueid, n x (valueid)]
6266*0b57cec5SDimitry Andric     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
6267*0b57cec5SDimitry Andric     //                        numrefs x valueid,
6268*0b57cec5SDimitry Andric     //                        n x (valueid, hotness)]
6269*0b57cec5SDimitry Andric     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
6270*0b57cec5SDimitry Andric     //                      numrefs x valueid,
6271*0b57cec5SDimitry Andric     //                      n x (valueid, relblockfreq)]
6272*0b57cec5SDimitry Andric     case bitc::FS_PERMODULE:
6273*0b57cec5SDimitry Andric     case bitc::FS_PERMODULE_RELBF:
6274*0b57cec5SDimitry Andric     case bitc::FS_PERMODULE_PROFILE: {
6275*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
6276*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
6277*0b57cec5SDimitry Andric       unsigned InstCount = Record[2];
6278*0b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
6279*0b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
6280*0b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
6281*0b57cec5SDimitry Andric       int RefListStartIndex = 4;
6282*0b57cec5SDimitry Andric       if (Version >= 4) {
6283*0b57cec5SDimitry Andric         RawFunFlags = Record[3];
6284*0b57cec5SDimitry Andric         NumRefs = Record[4];
6285*0b57cec5SDimitry Andric         RefListStartIndex = 5;
6286*0b57cec5SDimitry Andric         if (Version >= 5) {
6287*0b57cec5SDimitry Andric           NumRORefs = Record[5];
6288*0b57cec5SDimitry Andric           RefListStartIndex = 6;
6289*0b57cec5SDimitry Andric           if (Version >= 7) {
6290*0b57cec5SDimitry Andric             NumWORefs = Record[6];
6291*0b57cec5SDimitry Andric             RefListStartIndex = 7;
6292*0b57cec5SDimitry Andric           }
6293*0b57cec5SDimitry Andric         }
6294*0b57cec5SDimitry Andric       }
6295*0b57cec5SDimitry Andric 
6296*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6297*0b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
6298*0b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
6299*0b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
6300*0b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
6301*0b57cec5SDimitry Andric       // ownership.
6302*0b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6303*0b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
6304*0b57cec5SDimitry Andric              "Record size inconsistent with number of references");
6305*0b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
6306*0b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6307*0b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6308*0b57cec5SDimitry Andric       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
6309*0b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
6310*0b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6311*0b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, HasRelBF);
6312*0b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
63138bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
6314*0b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
6315*0b57cec5SDimitry Andric           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
6316*0b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
6317*0b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
6318*0b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
63195ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
63205ffd83dbSDimitry Andric           std::move(PendingParamAccesses));
6321*0b57cec5SDimitry Andric       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
6322*0b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
6323*0b57cec5SDimitry Andric       FS->setOriginalName(VIAndOriginalGUID.second);
6324*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
6325*0b57cec5SDimitry Andric       break;
6326*0b57cec5SDimitry Andric     }
6327*0b57cec5SDimitry Andric     // FS_ALIAS: [valueid, flags, valueid]
6328*0b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6329*0b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
6330*0b57cec5SDimitry Andric     case bitc::FS_ALIAS: {
6331*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
6332*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
6333*0b57cec5SDimitry Andric       unsigned AliaseeID = Record[2];
6334*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
63358bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
6336*0b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
6337*0b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
6338*0b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
6339*0b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
6340*0b57cec5SDimitry Andric       // ownership.
6341*0b57cec5SDimitry Andric       AS->setModulePath(getThisModule()->first());
6342*0b57cec5SDimitry Andric 
6343*0b57cec5SDimitry Andric       auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
6344*0b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
6345*0b57cec5SDimitry Andric       if (!AliaseeInModule)
6346*0b57cec5SDimitry Andric         return error("Alias expects aliasee summary to be parsed");
6347*0b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
6348*0b57cec5SDimitry Andric 
6349*0b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
6350*0b57cec5SDimitry Andric       AS->setOriginalName(GUID.second);
6351*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
6352*0b57cec5SDimitry Andric       break;
6353*0b57cec5SDimitry Andric     }
6354*0b57cec5SDimitry Andric     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
6355*0b57cec5SDimitry Andric     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6356*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
6357*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
6358*0b57cec5SDimitry Andric       unsigned RefArrayStart = 2;
6359*0b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
63605ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
63615ffd83dbSDimitry Andric                                       /* Constant */ false,
63625ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
6363*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6364*0b57cec5SDimitry Andric       if (Version >= 5) {
6365*0b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[2]);
6366*0b57cec5SDimitry Andric         RefArrayStart = 3;
6367*0b57cec5SDimitry Andric       }
6368*0b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
6369*0b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6370*0b57cec5SDimitry Andric       auto FS =
63718bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6372*0b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
6373*0b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
6374*0b57cec5SDimitry Andric       FS->setOriginalName(GUID.second);
6375*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
6376*0b57cec5SDimitry Andric       break;
6377*0b57cec5SDimitry Andric     }
6378*0b57cec5SDimitry Andric     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
6379*0b57cec5SDimitry Andric     //                        numrefs, numrefs x valueid,
6380*0b57cec5SDimitry Andric     //                        n x (valueid, offset)]
6381*0b57cec5SDimitry Andric     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
6382*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
6383*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
6384*0b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
6385*0b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
6386*0b57cec5SDimitry Andric       unsigned RefListStartIndex = 4;
6387*0b57cec5SDimitry Andric       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
6388*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6389*0b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
6390*0b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6391*0b57cec5SDimitry Andric       VTableFuncList VTableFuncs;
6392*0b57cec5SDimitry Andric       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
6393*0b57cec5SDimitry Andric         ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6394*0b57cec5SDimitry Andric         uint64_t Offset = Record[++I];
6395*0b57cec5SDimitry Andric         VTableFuncs.push_back({Callee, Offset});
6396*0b57cec5SDimitry Andric       }
6397*0b57cec5SDimitry Andric       auto VS =
63988bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6399*0b57cec5SDimitry Andric       VS->setModulePath(getThisModule()->first());
6400*0b57cec5SDimitry Andric       VS->setVTableFuncs(VTableFuncs);
6401*0b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
6402*0b57cec5SDimitry Andric       VS->setOriginalName(GUID.second);
6403*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(VS));
6404*0b57cec5SDimitry Andric       break;
6405*0b57cec5SDimitry Andric     }
6406*0b57cec5SDimitry Andric     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
6407*0b57cec5SDimitry Andric     //               numrefs x valueid, n x (valueid)]
6408*0b57cec5SDimitry Andric     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
6409*0b57cec5SDimitry Andric     //                       numrefs x valueid, n x (valueid, hotness)]
6410*0b57cec5SDimitry Andric     case bitc::FS_COMBINED:
6411*0b57cec5SDimitry Andric     case bitc::FS_COMBINED_PROFILE: {
6412*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
6413*0b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
6414*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
6415*0b57cec5SDimitry Andric       unsigned InstCount = Record[3];
6416*0b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
6417*0b57cec5SDimitry Andric       uint64_t EntryCount = 0;
6418*0b57cec5SDimitry Andric       unsigned NumRefs = Record[4];
6419*0b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
6420*0b57cec5SDimitry Andric       int RefListStartIndex = 5;
6421*0b57cec5SDimitry Andric 
6422*0b57cec5SDimitry Andric       if (Version >= 4) {
6423*0b57cec5SDimitry Andric         RawFunFlags = Record[4];
6424*0b57cec5SDimitry Andric         RefListStartIndex = 6;
6425*0b57cec5SDimitry Andric         size_t NumRefsIndex = 5;
6426*0b57cec5SDimitry Andric         if (Version >= 5) {
6427*0b57cec5SDimitry Andric           unsigned NumRORefsOffset = 1;
6428*0b57cec5SDimitry Andric           RefListStartIndex = 7;
6429*0b57cec5SDimitry Andric           if (Version >= 6) {
6430*0b57cec5SDimitry Andric             NumRefsIndex = 6;
6431*0b57cec5SDimitry Andric             EntryCount = Record[5];
6432*0b57cec5SDimitry Andric             RefListStartIndex = 8;
6433*0b57cec5SDimitry Andric             if (Version >= 7) {
6434*0b57cec5SDimitry Andric               RefListStartIndex = 9;
6435*0b57cec5SDimitry Andric               NumWORefs = Record[8];
6436*0b57cec5SDimitry Andric               NumRORefsOffset = 2;
6437*0b57cec5SDimitry Andric             }
6438*0b57cec5SDimitry Andric           }
6439*0b57cec5SDimitry Andric           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
6440*0b57cec5SDimitry Andric         }
6441*0b57cec5SDimitry Andric         NumRefs = Record[NumRefsIndex];
6442*0b57cec5SDimitry Andric       }
6443*0b57cec5SDimitry Andric 
6444*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6445*0b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6446*0b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
6447*0b57cec5SDimitry Andric              "Record size inconsistent with number of references");
6448*0b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
6449*0b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6450*0b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6451*0b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
6452*0b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6453*0b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, false);
6454*0b57cec5SDimitry Andric       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6455*0b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
64568bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
6457*0b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
6458*0b57cec5SDimitry Andric           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
6459*0b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
6460*0b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
6461*0b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
64625ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
64635ffd83dbSDimitry Andric           std::move(PendingParamAccesses));
6464*0b57cec5SDimitry Andric       LastSeenSummary = FS.get();
6465*0b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
6466*0b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
6467*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6468*0b57cec5SDimitry Andric       break;
6469*0b57cec5SDimitry Andric     }
6470*0b57cec5SDimitry Andric     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6471*0b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6472*0b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
6473*0b57cec5SDimitry Andric     case bitc::FS_COMBINED_ALIAS: {
6474*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
6475*0b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
6476*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
6477*0b57cec5SDimitry Andric       unsigned AliaseeValueId = Record[3];
6478*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
64798bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
6480*0b57cec5SDimitry Andric       LastSeenSummary = AS.get();
6481*0b57cec5SDimitry Andric       AS->setModulePath(ModuleIdMap[ModuleId]);
6482*0b57cec5SDimitry Andric 
6483*0b57cec5SDimitry Andric       auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
6484*0b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
6485*0b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
6486*0b57cec5SDimitry Andric 
6487*0b57cec5SDimitry Andric       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6488*0b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
6489*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(AS));
6490*0b57cec5SDimitry Andric       break;
6491*0b57cec5SDimitry Andric     }
6492*0b57cec5SDimitry Andric     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6493*0b57cec5SDimitry Andric     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6494*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
6495*0b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
6496*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
6497*0b57cec5SDimitry Andric       unsigned RefArrayStart = 3;
6498*0b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
64995ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
65005ffd83dbSDimitry Andric                                       /* Constant */ false,
65015ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
6502*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6503*0b57cec5SDimitry Andric       if (Version >= 5) {
6504*0b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[3]);
6505*0b57cec5SDimitry Andric         RefArrayStart = 4;
6506*0b57cec5SDimitry Andric       }
6507*0b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
6508*0b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6509*0b57cec5SDimitry Andric       auto FS =
65108bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6511*0b57cec5SDimitry Andric       LastSeenSummary = FS.get();
6512*0b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
6513*0b57cec5SDimitry Andric       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6514*0b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
6515*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6516*0b57cec5SDimitry Andric       break;
6517*0b57cec5SDimitry Andric     }
6518*0b57cec5SDimitry Andric     // FS_COMBINED_ORIGINAL_NAME: [original_name]
6519*0b57cec5SDimitry Andric     case bitc::FS_COMBINED_ORIGINAL_NAME: {
6520*0b57cec5SDimitry Andric       uint64_t OriginalName = Record[0];
6521*0b57cec5SDimitry Andric       if (!LastSeenSummary)
6522*0b57cec5SDimitry Andric         return error("Name attachment that does not follow a combined record");
6523*0b57cec5SDimitry Andric       LastSeenSummary->setOriginalName(OriginalName);
6524*0b57cec5SDimitry Andric       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
6525*0b57cec5SDimitry Andric       // Reset the LastSeenSummary
6526*0b57cec5SDimitry Andric       LastSeenSummary = nullptr;
6527*0b57cec5SDimitry Andric       LastSeenGUID = 0;
6528*0b57cec5SDimitry Andric       break;
6529*0b57cec5SDimitry Andric     }
6530*0b57cec5SDimitry Andric     case bitc::FS_TYPE_TESTS:
6531*0b57cec5SDimitry Andric       assert(PendingTypeTests.empty());
6532e8d8bef9SDimitry Andric       llvm::append_range(PendingTypeTests, Record);
6533*0b57cec5SDimitry Andric       break;
6534*0b57cec5SDimitry Andric 
6535*0b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
6536*0b57cec5SDimitry Andric       assert(PendingTypeTestAssumeVCalls.empty());
6537*0b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
6538*0b57cec5SDimitry Andric         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
6539*0b57cec5SDimitry Andric       break;
6540*0b57cec5SDimitry Andric 
6541*0b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
6542*0b57cec5SDimitry Andric       assert(PendingTypeCheckedLoadVCalls.empty());
6543*0b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
6544*0b57cec5SDimitry Andric         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
6545*0b57cec5SDimitry Andric       break;
6546*0b57cec5SDimitry Andric 
6547*0b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
6548*0b57cec5SDimitry Andric       PendingTypeTestAssumeConstVCalls.push_back(
6549*0b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6550*0b57cec5SDimitry Andric       break;
6551*0b57cec5SDimitry Andric 
6552*0b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
6553*0b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls.push_back(
6554*0b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6555*0b57cec5SDimitry Andric       break;
6556*0b57cec5SDimitry Andric 
6557*0b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DEFS: {
6558*0b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
6559*0b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
6560*0b57cec5SDimitry Andric         CfiFunctionDefs.insert(
6561*0b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6562*0b57cec5SDimitry Andric       break;
6563*0b57cec5SDimitry Andric     }
6564*0b57cec5SDimitry Andric 
6565*0b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DECLS: {
6566*0b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
6567*0b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
6568*0b57cec5SDimitry Andric         CfiFunctionDecls.insert(
6569*0b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6570*0b57cec5SDimitry Andric       break;
6571*0b57cec5SDimitry Andric     }
6572*0b57cec5SDimitry Andric 
6573*0b57cec5SDimitry Andric     case bitc::FS_TYPE_ID:
6574*0b57cec5SDimitry Andric       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
6575*0b57cec5SDimitry Andric       break;
6576*0b57cec5SDimitry Andric 
6577*0b57cec5SDimitry Andric     case bitc::FS_TYPE_ID_METADATA:
6578*0b57cec5SDimitry Andric       parseTypeIdCompatibleVtableSummaryRecord(Record);
6579*0b57cec5SDimitry Andric       break;
65805ffd83dbSDimitry Andric 
65815ffd83dbSDimitry Andric     case bitc::FS_BLOCK_COUNT:
65825ffd83dbSDimitry Andric       TheIndex.addBlockCount(Record[0]);
65835ffd83dbSDimitry Andric       break;
65845ffd83dbSDimitry Andric 
65855ffd83dbSDimitry Andric     case bitc::FS_PARAM_ACCESS: {
65865ffd83dbSDimitry Andric       PendingParamAccesses = parseParamAccesses(Record);
65875ffd83dbSDimitry Andric       break;
65885ffd83dbSDimitry Andric     }
6589*0b57cec5SDimitry Andric     }
6590*0b57cec5SDimitry Andric   }
6591*0b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
6592*0b57cec5SDimitry Andric }
6593*0b57cec5SDimitry Andric 
6594*0b57cec5SDimitry Andric // Parse the  module string table block into the Index.
6595*0b57cec5SDimitry Andric // This populates the ModulePathStringTable map in the index.
6596*0b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6597*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6598*0b57cec5SDimitry Andric     return Err;
6599*0b57cec5SDimitry Andric 
6600*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
6601*0b57cec5SDimitry Andric 
6602*0b57cec5SDimitry Andric   SmallString<128> ModulePath;
6603*0b57cec5SDimitry Andric   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
6604*0b57cec5SDimitry Andric 
6605*0b57cec5SDimitry Andric   while (true) {
6606*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6607*0b57cec5SDimitry Andric     if (!MaybeEntry)
6608*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
6609*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
6610*0b57cec5SDimitry Andric 
6611*0b57cec5SDimitry Andric     switch (Entry.Kind) {
6612*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
6613*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
6614*0b57cec5SDimitry Andric       return error("Malformed block");
6615*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
6616*0b57cec5SDimitry Andric       return Error::success();
6617*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
6618*0b57cec5SDimitry Andric       // The interesting case.
6619*0b57cec5SDimitry Andric       break;
6620*0b57cec5SDimitry Andric     }
6621*0b57cec5SDimitry Andric 
6622*0b57cec5SDimitry Andric     Record.clear();
6623*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6624*0b57cec5SDimitry Andric     if (!MaybeRecord)
6625*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
6626*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
6627*0b57cec5SDimitry Andric     default: // Default behavior: ignore.
6628*0b57cec5SDimitry Andric       break;
6629*0b57cec5SDimitry Andric     case bitc::MST_CODE_ENTRY: {
6630*0b57cec5SDimitry Andric       // MST_ENTRY: [modid, namechar x N]
6631*0b57cec5SDimitry Andric       uint64_t ModuleId = Record[0];
6632*0b57cec5SDimitry Andric 
6633*0b57cec5SDimitry Andric       if (convertToString(Record, 1, ModulePath))
6634*0b57cec5SDimitry Andric         return error("Invalid record");
6635*0b57cec5SDimitry Andric 
6636*0b57cec5SDimitry Andric       LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
6637*0b57cec5SDimitry Andric       ModuleIdMap[ModuleId] = LastSeenModule->first();
6638*0b57cec5SDimitry Andric 
6639*0b57cec5SDimitry Andric       ModulePath.clear();
6640*0b57cec5SDimitry Andric       break;
6641*0b57cec5SDimitry Andric     }
6642*0b57cec5SDimitry Andric     /// MST_CODE_HASH: [5*i32]
6643*0b57cec5SDimitry Andric     case bitc::MST_CODE_HASH: {
6644*0b57cec5SDimitry Andric       if (Record.size() != 5)
6645*0b57cec5SDimitry Andric         return error("Invalid hash length " + Twine(Record.size()).str());
6646*0b57cec5SDimitry Andric       if (!LastSeenModule)
6647*0b57cec5SDimitry Andric         return error("Invalid hash that does not follow a module path");
6648*0b57cec5SDimitry Andric       int Pos = 0;
6649*0b57cec5SDimitry Andric       for (auto &Val : Record) {
6650*0b57cec5SDimitry Andric         assert(!(Val >> 32) && "Unexpected high bits set");
6651*0b57cec5SDimitry Andric         LastSeenModule->second.second[Pos++] = Val;
6652*0b57cec5SDimitry Andric       }
6653*0b57cec5SDimitry Andric       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
6654*0b57cec5SDimitry Andric       LastSeenModule = nullptr;
6655*0b57cec5SDimitry Andric       break;
6656*0b57cec5SDimitry Andric     }
6657*0b57cec5SDimitry Andric     }
6658*0b57cec5SDimitry Andric   }
6659*0b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
6660*0b57cec5SDimitry Andric }
6661*0b57cec5SDimitry Andric 
6662*0b57cec5SDimitry Andric namespace {
6663*0b57cec5SDimitry Andric 
6664*0b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
6665*0b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
6666*0b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
6667*0b57cec5SDimitry Andric class BitcodeErrorCategoryType : public std::error_category {
6668*0b57cec5SDimitry Andric   const char *name() const noexcept override {
6669*0b57cec5SDimitry Andric     return "llvm.bitcode";
6670*0b57cec5SDimitry Andric   }
6671*0b57cec5SDimitry Andric 
6672*0b57cec5SDimitry Andric   std::string message(int IE) const override {
6673*0b57cec5SDimitry Andric     BitcodeError E = static_cast<BitcodeError>(IE);
6674*0b57cec5SDimitry Andric     switch (E) {
6675*0b57cec5SDimitry Andric     case BitcodeError::CorruptedBitcode:
6676*0b57cec5SDimitry Andric       return "Corrupted bitcode";
6677*0b57cec5SDimitry Andric     }
6678*0b57cec5SDimitry Andric     llvm_unreachable("Unknown error type!");
6679*0b57cec5SDimitry Andric   }
6680*0b57cec5SDimitry Andric };
6681*0b57cec5SDimitry Andric 
6682*0b57cec5SDimitry Andric } // end anonymous namespace
6683*0b57cec5SDimitry Andric 
6684*0b57cec5SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6685*0b57cec5SDimitry Andric 
6686*0b57cec5SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() {
6687*0b57cec5SDimitry Andric   return *ErrorCategory;
6688*0b57cec5SDimitry Andric }
6689*0b57cec5SDimitry Andric 
6690*0b57cec5SDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
6691*0b57cec5SDimitry Andric                                             unsigned Block, unsigned RecordID) {
6692*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(Block))
6693*0b57cec5SDimitry Andric     return std::move(Err);
6694*0b57cec5SDimitry Andric 
6695*0b57cec5SDimitry Andric   StringRef Strtab;
6696*0b57cec5SDimitry Andric   while (true) {
6697*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6698*0b57cec5SDimitry Andric     if (!MaybeEntry)
6699*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
6700*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
6701*0b57cec5SDimitry Andric 
6702*0b57cec5SDimitry Andric     switch (Entry.Kind) {
6703*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
6704*0b57cec5SDimitry Andric       return Strtab;
6705*0b57cec5SDimitry Andric 
6706*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
6707*0b57cec5SDimitry Andric       return error("Malformed block");
6708*0b57cec5SDimitry Andric 
6709*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
6710*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
6711*0b57cec5SDimitry Andric         return std::move(Err);
6712*0b57cec5SDimitry Andric       break;
6713*0b57cec5SDimitry Andric 
6714*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
6715*0b57cec5SDimitry Andric       StringRef Blob;
6716*0b57cec5SDimitry Andric       SmallVector<uint64_t, 1> Record;
6717*0b57cec5SDimitry Andric       Expected<unsigned> MaybeRecord =
6718*0b57cec5SDimitry Andric           Stream.readRecord(Entry.ID, Record, &Blob);
6719*0b57cec5SDimitry Andric       if (!MaybeRecord)
6720*0b57cec5SDimitry Andric         return MaybeRecord.takeError();
6721*0b57cec5SDimitry Andric       if (MaybeRecord.get() == RecordID)
6722*0b57cec5SDimitry Andric         Strtab = Blob;
6723*0b57cec5SDimitry Andric       break;
6724*0b57cec5SDimitry Andric     }
6725*0b57cec5SDimitry Andric   }
6726*0b57cec5SDimitry Andric }
6727*0b57cec5SDimitry Andric 
6728*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6729*0b57cec5SDimitry Andric // External interface
6730*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6731*0b57cec5SDimitry Andric 
6732*0b57cec5SDimitry Andric Expected<std::vector<BitcodeModule>>
6733*0b57cec5SDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
6734*0b57cec5SDimitry Andric   auto FOrErr = getBitcodeFileContents(Buffer);
6735*0b57cec5SDimitry Andric   if (!FOrErr)
6736*0b57cec5SDimitry Andric     return FOrErr.takeError();
6737*0b57cec5SDimitry Andric   return std::move(FOrErr->Mods);
6738*0b57cec5SDimitry Andric }
6739*0b57cec5SDimitry Andric 
6740*0b57cec5SDimitry Andric Expected<BitcodeFileContents>
6741*0b57cec5SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
6742*0b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6743*0b57cec5SDimitry Andric   if (!StreamOrErr)
6744*0b57cec5SDimitry Andric     return StreamOrErr.takeError();
6745*0b57cec5SDimitry Andric   BitstreamCursor &Stream = *StreamOrErr;
6746*0b57cec5SDimitry Andric 
6747*0b57cec5SDimitry Andric   BitcodeFileContents F;
6748*0b57cec5SDimitry Andric   while (true) {
6749*0b57cec5SDimitry Andric     uint64_t BCBegin = Stream.getCurrentByteNo();
6750*0b57cec5SDimitry Andric 
6751*0b57cec5SDimitry Andric     // We may be consuming bitcode from a client that leaves garbage at the end
6752*0b57cec5SDimitry Andric     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
6753*0b57cec5SDimitry Andric     // the end that there cannot possibly be another module, stop looking.
6754*0b57cec5SDimitry Andric     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
6755*0b57cec5SDimitry Andric       return F;
6756*0b57cec5SDimitry Andric 
6757*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6758*0b57cec5SDimitry Andric     if (!MaybeEntry)
6759*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
6760*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
6761*0b57cec5SDimitry Andric 
6762*0b57cec5SDimitry Andric     switch (Entry.Kind) {
6763*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
6764*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
6765*0b57cec5SDimitry Andric       return error("Malformed block");
6766*0b57cec5SDimitry Andric 
6767*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: {
6768*0b57cec5SDimitry Andric       uint64_t IdentificationBit = -1ull;
6769*0b57cec5SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
6770*0b57cec5SDimitry Andric         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6771*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
6772*0b57cec5SDimitry Andric           return std::move(Err);
6773*0b57cec5SDimitry Andric 
6774*0b57cec5SDimitry Andric         {
6775*0b57cec5SDimitry Andric           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6776*0b57cec5SDimitry Andric           if (!MaybeEntry)
6777*0b57cec5SDimitry Andric             return MaybeEntry.takeError();
6778*0b57cec5SDimitry Andric           Entry = MaybeEntry.get();
6779*0b57cec5SDimitry Andric         }
6780*0b57cec5SDimitry Andric 
6781*0b57cec5SDimitry Andric         if (Entry.Kind != BitstreamEntry::SubBlock ||
6782*0b57cec5SDimitry Andric             Entry.ID != bitc::MODULE_BLOCK_ID)
6783*0b57cec5SDimitry Andric           return error("Malformed block");
6784*0b57cec5SDimitry Andric       }
6785*0b57cec5SDimitry Andric 
6786*0b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
6787*0b57cec5SDimitry Andric         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6788*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
6789*0b57cec5SDimitry Andric           return std::move(Err);
6790*0b57cec5SDimitry Andric 
6791*0b57cec5SDimitry Andric         F.Mods.push_back({Stream.getBitcodeBytes().slice(
6792*0b57cec5SDimitry Andric                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
6793*0b57cec5SDimitry Andric                           Buffer.getBufferIdentifier(), IdentificationBit,
6794*0b57cec5SDimitry Andric                           ModuleBit});
6795*0b57cec5SDimitry Andric         continue;
6796*0b57cec5SDimitry Andric       }
6797*0b57cec5SDimitry Andric 
6798*0b57cec5SDimitry Andric       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
6799*0b57cec5SDimitry Andric         Expected<StringRef> Strtab =
6800*0b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
6801*0b57cec5SDimitry Andric         if (!Strtab)
6802*0b57cec5SDimitry Andric           return Strtab.takeError();
6803*0b57cec5SDimitry Andric         // This string table is used by every preceding bitcode module that does
6804*0b57cec5SDimitry Andric         // not have its own string table. A bitcode file may have multiple
6805*0b57cec5SDimitry Andric         // string tables if it was created by binary concatenation, for example
6806*0b57cec5SDimitry Andric         // with "llvm-cat -b".
68070eae32dcSDimitry Andric         for (BitcodeModule &I : llvm::reverse(F.Mods)) {
68080eae32dcSDimitry Andric           if (!I.Strtab.empty())
6809*0b57cec5SDimitry Andric             break;
68100eae32dcSDimitry Andric           I.Strtab = *Strtab;
6811*0b57cec5SDimitry Andric         }
6812*0b57cec5SDimitry Andric         // Similarly, the string table is used by every preceding symbol table;
6813*0b57cec5SDimitry Andric         // normally there will be just one unless the bitcode file was created
6814*0b57cec5SDimitry Andric         // by binary concatenation.
6815*0b57cec5SDimitry Andric         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
6816*0b57cec5SDimitry Andric           F.StrtabForSymtab = *Strtab;
6817*0b57cec5SDimitry Andric         continue;
6818*0b57cec5SDimitry Andric       }
6819*0b57cec5SDimitry Andric 
6820*0b57cec5SDimitry Andric       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
6821*0b57cec5SDimitry Andric         Expected<StringRef> SymtabOrErr =
6822*0b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
6823*0b57cec5SDimitry Andric         if (!SymtabOrErr)
6824*0b57cec5SDimitry Andric           return SymtabOrErr.takeError();
6825*0b57cec5SDimitry Andric 
6826*0b57cec5SDimitry Andric         // We can expect the bitcode file to have multiple symbol tables if it
6827*0b57cec5SDimitry Andric         // was created by binary concatenation. In that case we silently
6828*0b57cec5SDimitry Andric         // ignore any subsequent symbol tables, which is fine because this is a
6829*0b57cec5SDimitry Andric         // low level function. The client is expected to notice that the number
6830*0b57cec5SDimitry Andric         // of modules in the symbol table does not match the number of modules
6831*0b57cec5SDimitry Andric         // in the input file and regenerate the symbol table.
6832*0b57cec5SDimitry Andric         if (F.Symtab.empty())
6833*0b57cec5SDimitry Andric           F.Symtab = *SymtabOrErr;
6834*0b57cec5SDimitry Andric         continue;
6835*0b57cec5SDimitry Andric       }
6836*0b57cec5SDimitry Andric 
6837*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
6838*0b57cec5SDimitry Andric         return std::move(Err);
6839*0b57cec5SDimitry Andric       continue;
6840*0b57cec5SDimitry Andric     }
6841*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
6842349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
6843349cc55cSDimitry Andric         return std::move(E);
6844*0b57cec5SDimitry Andric       continue;
6845*0b57cec5SDimitry Andric     }
6846*0b57cec5SDimitry Andric   }
6847*0b57cec5SDimitry Andric }
6848*0b57cec5SDimitry Andric 
6849*0b57cec5SDimitry Andric /// Get a lazy one-at-time loading module from bitcode.
6850*0b57cec5SDimitry Andric ///
6851*0b57cec5SDimitry Andric /// This isn't always used in a lazy context.  In particular, it's also used by
6852*0b57cec5SDimitry Andric /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
6853*0b57cec5SDimitry Andric /// in forward-referenced functions from block address references.
6854*0b57cec5SDimitry Andric ///
6855*0b57cec5SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize
6856*0b57cec5SDimitry Andric /// everything.
6857*0b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
6858*0b57cec5SDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
68595ffd83dbSDimitry Andric                              bool ShouldLazyLoadMetadata, bool IsImporting,
68605ffd83dbSDimitry Andric                              DataLayoutCallbackTy DataLayoutCallback) {
6861*0b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
6862*0b57cec5SDimitry Andric 
6863*0b57cec5SDimitry Andric   std::string ProducerIdentification;
6864*0b57cec5SDimitry Andric   if (IdentificationBit != -1ull) {
6865*0b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
6866*0b57cec5SDimitry Andric       return std::move(JumpFailed);
6867349cc55cSDimitry Andric     if (Error E =
6868349cc55cSDimitry Andric             readIdentificationBlock(Stream).moveInto(ProducerIdentification))
6869349cc55cSDimitry Andric       return std::move(E);
6870*0b57cec5SDimitry Andric   }
6871*0b57cec5SDimitry Andric 
6872*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6873*0b57cec5SDimitry Andric     return std::move(JumpFailed);
6874*0b57cec5SDimitry Andric   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
6875*0b57cec5SDimitry Andric                               Context);
6876*0b57cec5SDimitry Andric 
6877*0b57cec5SDimitry Andric   std::unique_ptr<Module> M =
68788bcb0991SDimitry Andric       std::make_unique<Module>(ModuleIdentifier, Context);
6879*0b57cec5SDimitry Andric   M->setMaterializer(R);
6880*0b57cec5SDimitry Andric 
6881*0b57cec5SDimitry Andric   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
68825ffd83dbSDimitry Andric   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
68835ffd83dbSDimitry Andric                                       IsImporting, DataLayoutCallback))
6884*0b57cec5SDimitry Andric     return std::move(Err);
6885*0b57cec5SDimitry Andric 
6886*0b57cec5SDimitry Andric   if (MaterializeAll) {
6887*0b57cec5SDimitry Andric     // Read in the entire module, and destroy the BitcodeReader.
6888*0b57cec5SDimitry Andric     if (Error Err = M->materializeAll())
6889*0b57cec5SDimitry Andric       return std::move(Err);
6890*0b57cec5SDimitry Andric   } else {
6891*0b57cec5SDimitry Andric     // Resolve forward references from blockaddresses.
6892*0b57cec5SDimitry Andric     if (Error Err = R->materializeForwardReferencedFunctions())
6893*0b57cec5SDimitry Andric       return std::move(Err);
6894*0b57cec5SDimitry Andric   }
6895*0b57cec5SDimitry Andric   return std::move(M);
6896*0b57cec5SDimitry Andric }
6897*0b57cec5SDimitry Andric 
6898*0b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
6899*0b57cec5SDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
6900*0b57cec5SDimitry Andric                              bool IsImporting) {
69015ffd83dbSDimitry Andric   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
69025ffd83dbSDimitry Andric                        [](StringRef) { return None; });
6903*0b57cec5SDimitry Andric }
6904*0b57cec5SDimitry Andric 
6905*0b57cec5SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex.
6906*0b57cec5SDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the
6907*0b57cec5SDimitry Andric // module path used in the combined summary (e.g. when reading summaries for
6908*0b57cec5SDimitry Andric // regular LTO modules).
6909*0b57cec5SDimitry Andric Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
6910*0b57cec5SDimitry Andric                                  StringRef ModulePath, uint64_t ModuleId) {
6911*0b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
6912*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6913*0b57cec5SDimitry Andric     return JumpFailed;
6914*0b57cec5SDimitry Andric 
6915*0b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
6916*0b57cec5SDimitry Andric                                     ModulePath, ModuleId);
6917*0b57cec5SDimitry Andric   return R.parseModule();
6918*0b57cec5SDimitry Andric }
6919*0b57cec5SDimitry Andric 
6920*0b57cec5SDimitry Andric // Parse the specified bitcode buffer, returning the function info index.
6921*0b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
6922*0b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
6923*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6924*0b57cec5SDimitry Andric     return std::move(JumpFailed);
6925*0b57cec5SDimitry Andric 
69268bcb0991SDimitry Andric   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
6927*0b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
6928*0b57cec5SDimitry Andric                                     ModuleIdentifier, 0);
6929*0b57cec5SDimitry Andric 
6930*0b57cec5SDimitry Andric   if (Error Err = R.parseModule())
6931*0b57cec5SDimitry Andric     return std::move(Err);
6932*0b57cec5SDimitry Andric 
6933*0b57cec5SDimitry Andric   return std::move(Index);
6934*0b57cec5SDimitry Andric }
6935*0b57cec5SDimitry Andric 
6936*0b57cec5SDimitry Andric static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
6937*0b57cec5SDimitry Andric                                                 unsigned ID) {
6938*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
6939*0b57cec5SDimitry Andric     return std::move(Err);
6940*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
6941*0b57cec5SDimitry Andric 
6942*0b57cec5SDimitry Andric   while (true) {
6943349cc55cSDimitry Andric     BitstreamEntry Entry;
6944349cc55cSDimitry Andric     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
6945349cc55cSDimitry Andric       return std::move(E);
6946*0b57cec5SDimitry Andric 
6947*0b57cec5SDimitry Andric     switch (Entry.Kind) {
6948*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
6949*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
6950*0b57cec5SDimitry Andric       return error("Malformed block");
6951*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
6952*0b57cec5SDimitry Andric       // If no flags record found, conservatively return true to mimic
6953*0b57cec5SDimitry Andric       // behavior before this flag was added.
6954*0b57cec5SDimitry Andric       return true;
6955*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
6956*0b57cec5SDimitry Andric       // The interesting case.
6957*0b57cec5SDimitry Andric       break;
6958*0b57cec5SDimitry Andric     }
6959*0b57cec5SDimitry Andric 
6960*0b57cec5SDimitry Andric     // Look for the FS_FLAGS record.
6961*0b57cec5SDimitry Andric     Record.clear();
6962*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6963*0b57cec5SDimitry Andric     if (!MaybeBitCode)
6964*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
6965*0b57cec5SDimitry Andric     switch (MaybeBitCode.get()) {
6966*0b57cec5SDimitry Andric     default: // Default behavior: ignore.
6967*0b57cec5SDimitry Andric       break;
6968*0b57cec5SDimitry Andric     case bitc::FS_FLAGS: { // [flags]
6969*0b57cec5SDimitry Andric       uint64_t Flags = Record[0];
6970*0b57cec5SDimitry Andric       // Scan flags.
6971fe6060f1SDimitry Andric       assert(Flags <= 0x7f && "Unexpected bits in flag");
6972*0b57cec5SDimitry Andric 
6973*0b57cec5SDimitry Andric       return Flags & 0x8;
6974*0b57cec5SDimitry Andric     }
6975*0b57cec5SDimitry Andric     }
6976*0b57cec5SDimitry Andric   }
6977*0b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
6978*0b57cec5SDimitry Andric }
6979*0b57cec5SDimitry Andric 
6980*0b57cec5SDimitry Andric // Check if the given bitcode buffer contains a global value summary block.
6981*0b57cec5SDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
6982*0b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
6983*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6984*0b57cec5SDimitry Andric     return std::move(JumpFailed);
6985*0b57cec5SDimitry Andric 
6986*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6987*0b57cec5SDimitry Andric     return std::move(Err);
6988*0b57cec5SDimitry Andric 
6989*0b57cec5SDimitry Andric   while (true) {
6990349cc55cSDimitry Andric     llvm::BitstreamEntry Entry;
6991349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
6992349cc55cSDimitry Andric       return std::move(E);
6993*0b57cec5SDimitry Andric 
6994*0b57cec5SDimitry Andric     switch (Entry.Kind) {
6995*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
6996*0b57cec5SDimitry Andric       return error("Malformed block");
6997*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
6998*0b57cec5SDimitry Andric       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
6999*0b57cec5SDimitry Andric                             /*EnableSplitLTOUnit=*/false};
7000*0b57cec5SDimitry Andric 
7001*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
7002*0b57cec5SDimitry Andric       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
7003*0b57cec5SDimitry Andric         Expected<bool> EnableSplitLTOUnit =
7004*0b57cec5SDimitry Andric             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
7005*0b57cec5SDimitry Andric         if (!EnableSplitLTOUnit)
7006*0b57cec5SDimitry Andric           return EnableSplitLTOUnit.takeError();
7007*0b57cec5SDimitry Andric         return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
7008*0b57cec5SDimitry Andric                               *EnableSplitLTOUnit};
7009*0b57cec5SDimitry Andric       }
7010*0b57cec5SDimitry Andric 
7011*0b57cec5SDimitry Andric       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
7012*0b57cec5SDimitry Andric         Expected<bool> EnableSplitLTOUnit =
7013*0b57cec5SDimitry Andric             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
7014*0b57cec5SDimitry Andric         if (!EnableSplitLTOUnit)
7015*0b57cec5SDimitry Andric           return EnableSplitLTOUnit.takeError();
7016*0b57cec5SDimitry Andric         return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
7017*0b57cec5SDimitry Andric                               *EnableSplitLTOUnit};
7018*0b57cec5SDimitry Andric       }
7019*0b57cec5SDimitry Andric 
7020*0b57cec5SDimitry Andric       // Ignore other sub-blocks.
7021*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
7022*0b57cec5SDimitry Andric         return std::move(Err);
7023*0b57cec5SDimitry Andric       continue;
7024*0b57cec5SDimitry Andric 
7025*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
7026*0b57cec5SDimitry Andric       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
7027*0b57cec5SDimitry Andric         continue;
7028*0b57cec5SDimitry Andric       else
7029*0b57cec5SDimitry Andric         return StreamFailed.takeError();
7030*0b57cec5SDimitry Andric     }
7031*0b57cec5SDimitry Andric   }
7032*0b57cec5SDimitry Andric }
7033*0b57cec5SDimitry Andric 
7034*0b57cec5SDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
7035*0b57cec5SDimitry Andric   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
7036*0b57cec5SDimitry Andric   if (!MsOrErr)
7037*0b57cec5SDimitry Andric     return MsOrErr.takeError();
7038*0b57cec5SDimitry Andric 
7039*0b57cec5SDimitry Andric   if (MsOrErr->size() != 1)
7040*0b57cec5SDimitry Andric     return error("Expected a single module");
7041*0b57cec5SDimitry Andric 
7042*0b57cec5SDimitry Andric   return (*MsOrErr)[0];
7043*0b57cec5SDimitry Andric }
7044*0b57cec5SDimitry Andric 
7045*0b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
7046*0b57cec5SDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
7047*0b57cec5SDimitry Andric                            bool ShouldLazyLoadMetadata, bool IsImporting) {
7048*0b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7049*0b57cec5SDimitry Andric   if (!BM)
7050*0b57cec5SDimitry Andric     return BM.takeError();
7051*0b57cec5SDimitry Andric 
7052*0b57cec5SDimitry Andric   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
7053*0b57cec5SDimitry Andric }
7054*0b57cec5SDimitry Andric 
7055*0b57cec5SDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
7056*0b57cec5SDimitry Andric     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
7057*0b57cec5SDimitry Andric     bool ShouldLazyLoadMetadata, bool IsImporting) {
7058*0b57cec5SDimitry Andric   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
7059*0b57cec5SDimitry Andric                                      IsImporting);
7060*0b57cec5SDimitry Andric   if (MOrErr)
7061*0b57cec5SDimitry Andric     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
7062*0b57cec5SDimitry Andric   return MOrErr;
7063*0b57cec5SDimitry Andric }
7064*0b57cec5SDimitry Andric 
7065*0b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
70665ffd83dbSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context,
70675ffd83dbSDimitry Andric                            DataLayoutCallbackTy DataLayoutCallback) {
70685ffd83dbSDimitry Andric   return getModuleImpl(Context, true, false, false, DataLayoutCallback);
7069*0b57cec5SDimitry Andric   // TODO: Restore the use-lists to the in-memory state when the bitcode was
7070*0b57cec5SDimitry Andric   // written.  We must defer until the Module has been fully materialized.
7071*0b57cec5SDimitry Andric }
7072*0b57cec5SDimitry Andric 
70735ffd83dbSDimitry Andric Expected<std::unique_ptr<Module>>
70745ffd83dbSDimitry Andric llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
70755ffd83dbSDimitry Andric                        DataLayoutCallbackTy DataLayoutCallback) {
7076*0b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7077*0b57cec5SDimitry Andric   if (!BM)
7078*0b57cec5SDimitry Andric     return BM.takeError();
7079*0b57cec5SDimitry Andric 
70805ffd83dbSDimitry Andric   return BM->parseModule(Context, DataLayoutCallback);
7081*0b57cec5SDimitry Andric }
7082*0b57cec5SDimitry Andric 
7083*0b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
7084*0b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7085*0b57cec5SDimitry Andric   if (!StreamOrErr)
7086*0b57cec5SDimitry Andric     return StreamOrErr.takeError();
7087*0b57cec5SDimitry Andric 
7088*0b57cec5SDimitry Andric   return readTriple(*StreamOrErr);
7089*0b57cec5SDimitry Andric }
7090*0b57cec5SDimitry Andric 
7091*0b57cec5SDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
7092*0b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7093*0b57cec5SDimitry Andric   if (!StreamOrErr)
7094*0b57cec5SDimitry Andric     return StreamOrErr.takeError();
7095*0b57cec5SDimitry Andric 
7096*0b57cec5SDimitry Andric   return hasObjCCategory(*StreamOrErr);
7097*0b57cec5SDimitry Andric }
7098*0b57cec5SDimitry Andric 
7099*0b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
7100*0b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7101*0b57cec5SDimitry Andric   if (!StreamOrErr)
7102*0b57cec5SDimitry Andric     return StreamOrErr.takeError();
7103*0b57cec5SDimitry Andric 
7104*0b57cec5SDimitry Andric   return readIdentificationCode(*StreamOrErr);
7105*0b57cec5SDimitry Andric }
7106*0b57cec5SDimitry Andric 
7107*0b57cec5SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
7108*0b57cec5SDimitry Andric                                    ModuleSummaryIndex &CombinedIndex,
7109*0b57cec5SDimitry Andric                                    uint64_t ModuleId) {
7110*0b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7111*0b57cec5SDimitry Andric   if (!BM)
7112*0b57cec5SDimitry Andric     return BM.takeError();
7113*0b57cec5SDimitry Andric 
7114*0b57cec5SDimitry Andric   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
7115*0b57cec5SDimitry Andric }
7116*0b57cec5SDimitry Andric 
7117*0b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
7118*0b57cec5SDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
7119*0b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7120*0b57cec5SDimitry Andric   if (!BM)
7121*0b57cec5SDimitry Andric     return BM.takeError();
7122*0b57cec5SDimitry Andric 
7123*0b57cec5SDimitry Andric   return BM->getSummary();
7124*0b57cec5SDimitry Andric }
7125*0b57cec5SDimitry Andric 
7126*0b57cec5SDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
7127*0b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7128*0b57cec5SDimitry Andric   if (!BM)
7129*0b57cec5SDimitry Andric     return BM.takeError();
7130*0b57cec5SDimitry Andric 
7131*0b57cec5SDimitry Andric   return BM->getLTOInfo();
7132*0b57cec5SDimitry Andric }
7133*0b57cec5SDimitry Andric 
7134*0b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
7135*0b57cec5SDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path,
7136*0b57cec5SDimitry Andric                                    bool IgnoreEmptyThinLTOIndexFile) {
7137*0b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
7138*0b57cec5SDimitry Andric       MemoryBuffer::getFileOrSTDIN(Path);
7139*0b57cec5SDimitry Andric   if (!FileOrErr)
7140*0b57cec5SDimitry Andric     return errorCodeToError(FileOrErr.getError());
7141*0b57cec5SDimitry Andric   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
7142*0b57cec5SDimitry Andric     return nullptr;
7143*0b57cec5SDimitry Andric   return getModuleSummaryIndex(**FileOrErr);
7144*0b57cec5SDimitry Andric }
7145