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"
4281ad6265SDimitry Andric #include "llvm/IR/GetElementPtrTypeIterator.h"
43*0b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
44*0b57cec5SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
45*0b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
46*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
47*0b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
48*0b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
49*0b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
50*0b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
51*0b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
52*0b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
53*0b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
5481ad6265SDimitry Andric #include "llvm/IR/IntrinsicsAArch64.h"
5581ad6265SDimitry Andric #include "llvm/IR/IntrinsicsARM.h"
56*0b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
57*0b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
58*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
59*0b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
60*0b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
61*0b57cec5SDimitry Andric #include "llvm/IR/Type.h"
62*0b57cec5SDimitry Andric #include "llvm/IR/Value.h"
63*0b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
64*0b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
65*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
66*0b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
67*0b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
68*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
69*0b57cec5SDimitry Andric #include "llvm/Support/Error.h"
70*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
71*0b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
72*0b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
73*0b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
74*0b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
75*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
76*0b57cec5SDimitry Andric #include <algorithm>
77*0b57cec5SDimitry Andric #include <cassert>
78*0b57cec5SDimitry Andric #include <cstddef>
79*0b57cec5SDimitry Andric #include <cstdint>
80*0b57cec5SDimitry Andric #include <deque>
81*0b57cec5SDimitry Andric #include <map>
82*0b57cec5SDimitry Andric #include <memory>
83*0b57cec5SDimitry Andric #include <set>
84*0b57cec5SDimitry Andric #include <string>
85*0b57cec5SDimitry Andric #include <system_error>
86*0b57cec5SDimitry Andric #include <tuple>
87*0b57cec5SDimitry Andric #include <utility>
88*0b57cec5SDimitry Andric #include <vector>
89*0b57cec5SDimitry Andric 
90*0b57cec5SDimitry Andric using namespace llvm;
91*0b57cec5SDimitry Andric 
92*0b57cec5SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs(
93*0b57cec5SDimitry Andric     "print-summary-global-ids", cl::init(false), cl::Hidden,
94*0b57cec5SDimitry Andric     cl::desc(
95*0b57cec5SDimitry Andric         "Print the global id for each value when reading the module summary"));
96*0b57cec5SDimitry Andric 
9781ad6265SDimitry Andric static cl::opt<bool> ExpandConstantExprs(
9881ad6265SDimitry Andric     "expand-constant-exprs", cl::Hidden,
9981ad6265SDimitry Andric     cl::desc(
10081ad6265SDimitry Andric         "Expand constant expressions to instructions for testing purposes"));
10181ad6265SDimitry Andric 
102*0b57cec5SDimitry Andric namespace {
103*0b57cec5SDimitry Andric 
104*0b57cec5SDimitry Andric enum {
105*0b57cec5SDimitry Andric   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
106*0b57cec5SDimitry Andric };
107*0b57cec5SDimitry Andric 
108*0b57cec5SDimitry Andric } // end anonymous namespace
109*0b57cec5SDimitry Andric 
110*0b57cec5SDimitry Andric static Error error(const Twine &Message) {
111*0b57cec5SDimitry Andric   return make_error<StringError>(
112*0b57cec5SDimitry Andric       Message, make_error_code(BitcodeError::CorruptedBitcode));
113*0b57cec5SDimitry Andric }
114*0b57cec5SDimitry Andric 
115*0b57cec5SDimitry Andric static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
116*0b57cec5SDimitry Andric   if (!Stream.canSkipToPos(4))
117*0b57cec5SDimitry Andric     return createStringError(std::errc::illegal_byte_sequence,
118*0b57cec5SDimitry Andric                              "file too small to contain bitcode header");
119*0b57cec5SDimitry Andric   for (unsigned C : {'B', 'C'})
120*0b57cec5SDimitry Andric     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
121*0b57cec5SDimitry Andric       if (Res.get() != C)
122*0b57cec5SDimitry Andric         return createStringError(std::errc::illegal_byte_sequence,
123*0b57cec5SDimitry Andric                                  "file doesn't start with bitcode header");
124*0b57cec5SDimitry Andric     } else
125*0b57cec5SDimitry Andric       return Res.takeError();
126*0b57cec5SDimitry Andric   for (unsigned C : {0x0, 0xC, 0xE, 0xD})
127*0b57cec5SDimitry Andric     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
128*0b57cec5SDimitry Andric       if (Res.get() != C)
129*0b57cec5SDimitry Andric         return createStringError(std::errc::illegal_byte_sequence,
130*0b57cec5SDimitry Andric                                  "file doesn't start with bitcode header");
131*0b57cec5SDimitry Andric     } else
132*0b57cec5SDimitry Andric       return Res.takeError();
133*0b57cec5SDimitry Andric   return Error::success();
134*0b57cec5SDimitry Andric }
135*0b57cec5SDimitry Andric 
136*0b57cec5SDimitry Andric static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
137*0b57cec5SDimitry Andric   const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
138*0b57cec5SDimitry Andric   const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
139*0b57cec5SDimitry Andric 
140*0b57cec5SDimitry Andric   if (Buffer.getBufferSize() & 3)
141*0b57cec5SDimitry Andric     return error("Invalid bitcode signature");
142*0b57cec5SDimitry Andric 
143*0b57cec5SDimitry Andric   // If we have a wrapper header, parse it and ignore the non-bc file contents.
144*0b57cec5SDimitry Andric   // The magic number is 0x0B17C0DE stored in little endian.
145*0b57cec5SDimitry Andric   if (isBitcodeWrapper(BufPtr, BufEnd))
146*0b57cec5SDimitry Andric     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
147*0b57cec5SDimitry Andric       return error("Invalid bitcode wrapper header");
148*0b57cec5SDimitry Andric 
149*0b57cec5SDimitry Andric   BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
150*0b57cec5SDimitry Andric   if (Error Err = hasInvalidBitcodeHeader(Stream))
151*0b57cec5SDimitry Andric     return std::move(Err);
152*0b57cec5SDimitry Andric 
153*0b57cec5SDimitry Andric   return std::move(Stream);
154*0b57cec5SDimitry Andric }
155*0b57cec5SDimitry Andric 
156*0b57cec5SDimitry Andric /// Convert a string from a record into an std::string, return true on failure.
157*0b57cec5SDimitry Andric template <typename StrTy>
158*0b57cec5SDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
159*0b57cec5SDimitry Andric                             StrTy &Result) {
160*0b57cec5SDimitry Andric   if (Idx > Record.size())
161*0b57cec5SDimitry Andric     return true;
162*0b57cec5SDimitry Andric 
1635ffd83dbSDimitry Andric   Result.append(Record.begin() + Idx, Record.end());
164*0b57cec5SDimitry Andric   return false;
165*0b57cec5SDimitry Andric }
166*0b57cec5SDimitry Andric 
167*0b57cec5SDimitry Andric // Strip all the TBAA attachment for the module.
168*0b57cec5SDimitry Andric static void stripTBAA(Module *M) {
169*0b57cec5SDimitry Andric   for (auto &F : *M) {
170*0b57cec5SDimitry Andric     if (F.isMaterializable())
171*0b57cec5SDimitry Andric       continue;
172*0b57cec5SDimitry Andric     for (auto &I : instructions(F))
173*0b57cec5SDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, nullptr);
174*0b57cec5SDimitry Andric   }
175*0b57cec5SDimitry Andric }
176*0b57cec5SDimitry Andric 
177*0b57cec5SDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
178*0b57cec5SDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any.
179*0b57cec5SDimitry Andric static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
180*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
181*0b57cec5SDimitry Andric     return std::move(Err);
182*0b57cec5SDimitry Andric 
183*0b57cec5SDimitry Andric   // Read all the records.
184*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
185*0b57cec5SDimitry Andric 
186*0b57cec5SDimitry Andric   std::string ProducerIdentification;
187*0b57cec5SDimitry Andric 
188*0b57cec5SDimitry Andric   while (true) {
189*0b57cec5SDimitry Andric     BitstreamEntry Entry;
190349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
191349cc55cSDimitry Andric       return std::move(E);
192*0b57cec5SDimitry Andric 
193*0b57cec5SDimitry Andric     switch (Entry.Kind) {
194*0b57cec5SDimitry Andric     default:
195*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
196*0b57cec5SDimitry Andric       return error("Malformed block");
197*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
198*0b57cec5SDimitry Andric       return ProducerIdentification;
199*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
200*0b57cec5SDimitry Andric       // The interesting case.
201*0b57cec5SDimitry Andric       break;
202*0b57cec5SDimitry Andric     }
203*0b57cec5SDimitry Andric 
204*0b57cec5SDimitry Andric     // Read a record.
205*0b57cec5SDimitry Andric     Record.clear();
206*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
207*0b57cec5SDimitry Andric     if (!MaybeBitCode)
208*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
209*0b57cec5SDimitry Andric     switch (MaybeBitCode.get()) {
210*0b57cec5SDimitry Andric     default: // Default behavior: reject
211*0b57cec5SDimitry Andric       return error("Invalid value");
212*0b57cec5SDimitry Andric     case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
213*0b57cec5SDimitry Andric       convertToString(Record, 0, ProducerIdentification);
214*0b57cec5SDimitry Andric       break;
215*0b57cec5SDimitry Andric     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
216*0b57cec5SDimitry Andric       unsigned epoch = (unsigned)Record[0];
217*0b57cec5SDimitry Andric       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
218*0b57cec5SDimitry Andric         return error(
219*0b57cec5SDimitry Andric           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
220*0b57cec5SDimitry Andric           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
221*0b57cec5SDimitry Andric       }
222*0b57cec5SDimitry Andric     }
223*0b57cec5SDimitry Andric     }
224*0b57cec5SDimitry Andric   }
225*0b57cec5SDimitry Andric }
226*0b57cec5SDimitry Andric 
227*0b57cec5SDimitry Andric static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
228*0b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
229*0b57cec5SDimitry Andric   // need to understand them all.
230*0b57cec5SDimitry Andric   while (true) {
231*0b57cec5SDimitry Andric     if (Stream.AtEndOfStream())
232*0b57cec5SDimitry Andric       return "";
233*0b57cec5SDimitry Andric 
234*0b57cec5SDimitry Andric     BitstreamEntry Entry;
235349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
236349cc55cSDimitry Andric       return std::move(E);
237*0b57cec5SDimitry Andric 
238*0b57cec5SDimitry Andric     switch (Entry.Kind) {
239*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
240*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
241*0b57cec5SDimitry Andric       return error("Malformed block");
242*0b57cec5SDimitry Andric 
243*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
244*0b57cec5SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
245*0b57cec5SDimitry Andric         return readIdentificationBlock(Stream);
246*0b57cec5SDimitry Andric 
247*0b57cec5SDimitry Andric       // Ignore other sub-blocks.
248*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
249*0b57cec5SDimitry Andric         return std::move(Err);
250*0b57cec5SDimitry Andric       continue;
251*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
252349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
253349cc55cSDimitry Andric         return std::move(E);
254*0b57cec5SDimitry Andric       continue;
255*0b57cec5SDimitry Andric     }
256*0b57cec5SDimitry Andric   }
257*0b57cec5SDimitry Andric }
258*0b57cec5SDimitry Andric 
259*0b57cec5SDimitry Andric static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
260*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
261*0b57cec5SDimitry Andric     return std::move(Err);
262*0b57cec5SDimitry Andric 
263*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
264*0b57cec5SDimitry Andric   // Read all the records for this module.
265*0b57cec5SDimitry Andric 
266*0b57cec5SDimitry Andric   while (true) {
267*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
268*0b57cec5SDimitry Andric     if (!MaybeEntry)
269*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
270*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
271*0b57cec5SDimitry Andric 
272*0b57cec5SDimitry Andric     switch (Entry.Kind) {
273*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
274*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
275*0b57cec5SDimitry Andric       return error("Malformed block");
276*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
277*0b57cec5SDimitry Andric       return false;
278*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
279*0b57cec5SDimitry Andric       // The interesting case.
280*0b57cec5SDimitry Andric       break;
281*0b57cec5SDimitry Andric     }
282*0b57cec5SDimitry Andric 
283*0b57cec5SDimitry Andric     // Read a record.
284*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
285*0b57cec5SDimitry Andric     if (!MaybeRecord)
286*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
287*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
288*0b57cec5SDimitry Andric     default:
289*0b57cec5SDimitry Andric       break; // Default behavior, ignore unknown content.
290*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
291*0b57cec5SDimitry Andric       std::string S;
292*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
29381ad6265SDimitry Andric         return error("Invalid section name record");
294*0b57cec5SDimitry Andric       // Check for the i386 and other (x86_64, ARM) conventions
295*0b57cec5SDimitry Andric       if (S.find("__DATA,__objc_catlist") != std::string::npos ||
296*0b57cec5SDimitry Andric           S.find("__OBJC,__category") != std::string::npos)
297*0b57cec5SDimitry Andric         return true;
298*0b57cec5SDimitry Andric       break;
299*0b57cec5SDimitry Andric     }
300*0b57cec5SDimitry Andric     }
301*0b57cec5SDimitry Andric     Record.clear();
302*0b57cec5SDimitry Andric   }
303*0b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
304*0b57cec5SDimitry Andric }
305*0b57cec5SDimitry Andric 
306*0b57cec5SDimitry Andric static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
307*0b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
308*0b57cec5SDimitry Andric   // need to understand them all.
309*0b57cec5SDimitry Andric   while (true) {
310*0b57cec5SDimitry Andric     BitstreamEntry Entry;
311349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
312349cc55cSDimitry Andric       return std::move(E);
313*0b57cec5SDimitry Andric 
314*0b57cec5SDimitry Andric     switch (Entry.Kind) {
315*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
316*0b57cec5SDimitry Andric       return error("Malformed block");
317*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
318*0b57cec5SDimitry Andric       return false;
319*0b57cec5SDimitry Andric 
320*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
321*0b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
322*0b57cec5SDimitry Andric         return hasObjCCategoryInModule(Stream);
323*0b57cec5SDimitry Andric 
324*0b57cec5SDimitry Andric       // Ignore other sub-blocks.
325*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
326*0b57cec5SDimitry Andric         return std::move(Err);
327*0b57cec5SDimitry Andric       continue;
328*0b57cec5SDimitry Andric 
329*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
330349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
331349cc55cSDimitry Andric         return std::move(E);
332*0b57cec5SDimitry Andric       continue;
333*0b57cec5SDimitry Andric     }
334*0b57cec5SDimitry Andric   }
335*0b57cec5SDimitry Andric }
336*0b57cec5SDimitry Andric 
337*0b57cec5SDimitry Andric static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
338*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
339*0b57cec5SDimitry Andric     return std::move(Err);
340*0b57cec5SDimitry Andric 
341*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
342*0b57cec5SDimitry Andric 
343*0b57cec5SDimitry Andric   std::string Triple;
344*0b57cec5SDimitry Andric 
345*0b57cec5SDimitry Andric   // Read all the records for this module.
346*0b57cec5SDimitry Andric   while (true) {
347*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
348*0b57cec5SDimitry Andric     if (!MaybeEntry)
349*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
350*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
351*0b57cec5SDimitry Andric 
352*0b57cec5SDimitry Andric     switch (Entry.Kind) {
353*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
354*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
355*0b57cec5SDimitry Andric       return error("Malformed block");
356*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
357*0b57cec5SDimitry Andric       return Triple;
358*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
359*0b57cec5SDimitry Andric       // The interesting case.
360*0b57cec5SDimitry Andric       break;
361*0b57cec5SDimitry Andric     }
362*0b57cec5SDimitry Andric 
363*0b57cec5SDimitry Andric     // Read a record.
364*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
365*0b57cec5SDimitry Andric     if (!MaybeRecord)
366*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
367*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
368*0b57cec5SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
369*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
370*0b57cec5SDimitry Andric       std::string S;
371*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
37281ad6265SDimitry Andric         return error("Invalid triple record");
373*0b57cec5SDimitry Andric       Triple = S;
374*0b57cec5SDimitry Andric       break;
375*0b57cec5SDimitry Andric     }
376*0b57cec5SDimitry Andric     }
377*0b57cec5SDimitry Andric     Record.clear();
378*0b57cec5SDimitry Andric   }
379*0b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
380*0b57cec5SDimitry Andric }
381*0b57cec5SDimitry Andric 
382*0b57cec5SDimitry Andric static Expected<std::string> readTriple(BitstreamCursor &Stream) {
383*0b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
384*0b57cec5SDimitry Andric   // need to understand them all.
385*0b57cec5SDimitry Andric   while (true) {
386*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advance();
387*0b57cec5SDimitry Andric     if (!MaybeEntry)
388*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
389*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
390*0b57cec5SDimitry Andric 
391*0b57cec5SDimitry Andric     switch (Entry.Kind) {
392*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
393*0b57cec5SDimitry Andric       return error("Malformed block");
394*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
395*0b57cec5SDimitry Andric       return "";
396*0b57cec5SDimitry Andric 
397*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
398*0b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
399*0b57cec5SDimitry Andric         return readModuleTriple(Stream);
400*0b57cec5SDimitry Andric 
401*0b57cec5SDimitry Andric       // Ignore other sub-blocks.
402*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
403*0b57cec5SDimitry Andric         return std::move(Err);
404*0b57cec5SDimitry Andric       continue;
405*0b57cec5SDimitry Andric 
406*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
407*0b57cec5SDimitry Andric       if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
408*0b57cec5SDimitry Andric         continue;
409*0b57cec5SDimitry Andric       else
410*0b57cec5SDimitry Andric         return Skipped.takeError();
411*0b57cec5SDimitry Andric     }
412*0b57cec5SDimitry Andric   }
413*0b57cec5SDimitry Andric }
414*0b57cec5SDimitry Andric 
415*0b57cec5SDimitry Andric namespace {
416*0b57cec5SDimitry Andric 
417*0b57cec5SDimitry Andric class BitcodeReaderBase {
418*0b57cec5SDimitry Andric protected:
419*0b57cec5SDimitry Andric   BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
420*0b57cec5SDimitry Andric       : Stream(std::move(Stream)), Strtab(Strtab) {
421*0b57cec5SDimitry Andric     this->Stream.setBlockInfo(&BlockInfo);
422*0b57cec5SDimitry Andric   }
423*0b57cec5SDimitry Andric 
424*0b57cec5SDimitry Andric   BitstreamBlockInfo BlockInfo;
425*0b57cec5SDimitry Andric   BitstreamCursor Stream;
426*0b57cec5SDimitry Andric   StringRef Strtab;
427*0b57cec5SDimitry Andric 
428*0b57cec5SDimitry Andric   /// In version 2 of the bitcode we store names of global values and comdats in
429*0b57cec5SDimitry Andric   /// a string table rather than in the VST.
430*0b57cec5SDimitry Andric   bool UseStrtab = false;
431*0b57cec5SDimitry Andric 
432*0b57cec5SDimitry Andric   Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
433*0b57cec5SDimitry Andric 
434*0b57cec5SDimitry Andric   /// If this module uses a string table, pop the reference to the string table
435*0b57cec5SDimitry Andric   /// and return the referenced string and the rest of the record. Otherwise
436*0b57cec5SDimitry Andric   /// just return the record itself.
437*0b57cec5SDimitry Andric   std::pair<StringRef, ArrayRef<uint64_t>>
438*0b57cec5SDimitry Andric   readNameFromStrtab(ArrayRef<uint64_t> Record);
439*0b57cec5SDimitry Andric 
44081ad6265SDimitry Andric   Error readBlockInfo();
441*0b57cec5SDimitry Andric 
442*0b57cec5SDimitry Andric   // Contains an arbitrary and optional string identifying the bitcode producer
443*0b57cec5SDimitry Andric   std::string ProducerIdentification;
444*0b57cec5SDimitry Andric 
445*0b57cec5SDimitry Andric   Error error(const Twine &Message);
446*0b57cec5SDimitry Andric };
447*0b57cec5SDimitry Andric 
448*0b57cec5SDimitry Andric } // end anonymous namespace
449*0b57cec5SDimitry Andric 
450*0b57cec5SDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) {
451*0b57cec5SDimitry Andric   std::string FullMsg = Message.str();
452*0b57cec5SDimitry Andric   if (!ProducerIdentification.empty())
453*0b57cec5SDimitry Andric     FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
454*0b57cec5SDimitry Andric                LLVM_VERSION_STRING "')";
455*0b57cec5SDimitry Andric   return ::error(FullMsg);
456*0b57cec5SDimitry Andric }
457*0b57cec5SDimitry Andric 
458*0b57cec5SDimitry Andric Expected<unsigned>
459*0b57cec5SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
460*0b57cec5SDimitry Andric   if (Record.empty())
46181ad6265SDimitry Andric     return error("Invalid version record");
462*0b57cec5SDimitry Andric   unsigned ModuleVersion = Record[0];
463*0b57cec5SDimitry Andric   if (ModuleVersion > 2)
464*0b57cec5SDimitry Andric     return error("Invalid value");
465*0b57cec5SDimitry Andric   UseStrtab = ModuleVersion >= 2;
466*0b57cec5SDimitry Andric   return ModuleVersion;
467*0b57cec5SDimitry Andric }
468*0b57cec5SDimitry Andric 
469*0b57cec5SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>>
470*0b57cec5SDimitry Andric BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
471*0b57cec5SDimitry Andric   if (!UseStrtab)
472*0b57cec5SDimitry Andric     return {"", Record};
473*0b57cec5SDimitry Andric   // Invalid reference. Let the caller complain about the record being empty.
474*0b57cec5SDimitry Andric   if (Record[0] + Record[1] > Strtab.size())
475*0b57cec5SDimitry Andric     return {"", {}};
476*0b57cec5SDimitry Andric   return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
477*0b57cec5SDimitry Andric }
478*0b57cec5SDimitry Andric 
479*0b57cec5SDimitry Andric namespace {
480*0b57cec5SDimitry Andric 
48181ad6265SDimitry Andric /// This represents a constant expression or constant aggregate using a custom
48281ad6265SDimitry Andric /// structure internal to the bitcode reader. Later, this structure will be
48381ad6265SDimitry Andric /// expanded by materializeValue() either into a constant expression/aggregate,
48481ad6265SDimitry Andric /// or into an instruction sequence at the point of use. This allows us to
48581ad6265SDimitry Andric /// upgrade bitcode using constant expressions even if this kind of constant
48681ad6265SDimitry Andric /// expression is no longer supported.
48781ad6265SDimitry Andric class BitcodeConstant final : public Value,
48881ad6265SDimitry Andric                               TrailingObjects<BitcodeConstant, unsigned> {
48981ad6265SDimitry Andric   friend TrailingObjects;
49081ad6265SDimitry Andric 
49181ad6265SDimitry Andric   // Value subclass ID: Pick largest possible value to avoid any clashes.
49281ad6265SDimitry Andric   static constexpr uint8_t SubclassID = 255;
49381ad6265SDimitry Andric 
49481ad6265SDimitry Andric public:
49581ad6265SDimitry Andric   // Opcodes used for non-expressions. This includes constant aggregates
49681ad6265SDimitry Andric   // (struct, array, vector) that might need expansion, as well as non-leaf
49781ad6265SDimitry Andric   // constants that don't need expansion (no_cfi, dso_local, blockaddress),
49881ad6265SDimitry Andric   // but still go through BitcodeConstant to avoid different uselist orders
49981ad6265SDimitry Andric   // between the two cases.
50081ad6265SDimitry Andric   static constexpr uint8_t ConstantStructOpcode = 255;
50181ad6265SDimitry Andric   static constexpr uint8_t ConstantArrayOpcode = 254;
50281ad6265SDimitry Andric   static constexpr uint8_t ConstantVectorOpcode = 253;
50381ad6265SDimitry Andric   static constexpr uint8_t NoCFIOpcode = 252;
50481ad6265SDimitry Andric   static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
50581ad6265SDimitry Andric   static constexpr uint8_t BlockAddressOpcode = 250;
50681ad6265SDimitry Andric   static constexpr uint8_t FirstSpecialOpcode = BlockAddressOpcode;
50781ad6265SDimitry Andric 
50881ad6265SDimitry Andric   // Separate struct to make passing different number of parameters to
50981ad6265SDimitry Andric   // BitcodeConstant::create() more convenient.
51081ad6265SDimitry Andric   struct ExtraInfo {
51181ad6265SDimitry Andric     uint8_t Opcode;
51281ad6265SDimitry Andric     uint8_t Flags;
51381ad6265SDimitry Andric     unsigned Extra;
51481ad6265SDimitry Andric     Type *SrcElemTy;
51581ad6265SDimitry Andric 
51681ad6265SDimitry Andric     ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, unsigned Extra = 0,
51781ad6265SDimitry Andric               Type *SrcElemTy = nullptr)
51881ad6265SDimitry Andric         : Opcode(Opcode), Flags(Flags), Extra(Extra), SrcElemTy(SrcElemTy) {}
51981ad6265SDimitry Andric   };
52081ad6265SDimitry Andric 
52181ad6265SDimitry Andric   uint8_t Opcode;
52281ad6265SDimitry Andric   uint8_t Flags;
52381ad6265SDimitry Andric   unsigned NumOperands;
52481ad6265SDimitry Andric   unsigned Extra;  // GEP inrange index or blockaddress BB id.
52581ad6265SDimitry Andric   Type *SrcElemTy; // GEP source element type.
52681ad6265SDimitry Andric 
52781ad6265SDimitry Andric private:
52881ad6265SDimitry Andric   BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
52981ad6265SDimitry Andric       : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags),
53081ad6265SDimitry Andric         NumOperands(OpIDs.size()), Extra(Info.Extra),
53181ad6265SDimitry Andric         SrcElemTy(Info.SrcElemTy) {
53281ad6265SDimitry Andric     std::uninitialized_copy(OpIDs.begin(), OpIDs.end(),
53381ad6265SDimitry Andric                             getTrailingObjects<unsigned>());
53481ad6265SDimitry Andric   }
53581ad6265SDimitry Andric 
53681ad6265SDimitry Andric   BitcodeConstant &operator=(const BitcodeConstant &) = delete;
53781ad6265SDimitry Andric 
53881ad6265SDimitry Andric public:
53981ad6265SDimitry Andric   static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty,
54081ad6265SDimitry Andric                                  const ExtraInfo &Info,
54181ad6265SDimitry Andric                                  ArrayRef<unsigned> OpIDs) {
54281ad6265SDimitry Andric     void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()),
54381ad6265SDimitry Andric                            alignof(BitcodeConstant));
54481ad6265SDimitry Andric     return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
54581ad6265SDimitry Andric   }
54681ad6265SDimitry Andric 
54781ad6265SDimitry Andric   static bool classof(const Value *V) { return V->getValueID() == SubclassID; }
54881ad6265SDimitry Andric 
54981ad6265SDimitry Andric   ArrayRef<unsigned> getOperandIDs() const {
55081ad6265SDimitry Andric     return makeArrayRef(getTrailingObjects<unsigned>(), NumOperands);
55181ad6265SDimitry Andric   }
55281ad6265SDimitry Andric 
55381ad6265SDimitry Andric   Optional<unsigned> getInRangeIndex() const {
55481ad6265SDimitry Andric     assert(Opcode == Instruction::GetElementPtr);
55581ad6265SDimitry Andric     if (Extra == (unsigned)-1)
55681ad6265SDimitry Andric       return None;
55781ad6265SDimitry Andric     return Extra;
55881ad6265SDimitry Andric   }
55981ad6265SDimitry Andric 
56081ad6265SDimitry Andric   const char *getOpcodeName() const {
56181ad6265SDimitry Andric     return Instruction::getOpcodeName(Opcode);
56281ad6265SDimitry Andric   }
56381ad6265SDimitry Andric };
56481ad6265SDimitry Andric 
565*0b57cec5SDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
566*0b57cec5SDimitry Andric   LLVMContext &Context;
567*0b57cec5SDimitry Andric   Module *TheModule = nullptr;
568*0b57cec5SDimitry Andric   // Next offset to start scanning for lazy parsing of function bodies.
569*0b57cec5SDimitry Andric   uint64_t NextUnreadBit = 0;
570*0b57cec5SDimitry Andric   // Last function offset found in the VST.
571*0b57cec5SDimitry Andric   uint64_t LastFunctionBlockBit = 0;
572*0b57cec5SDimitry Andric   bool SeenValueSymbolTable = false;
573*0b57cec5SDimitry Andric   uint64_t VSTOffset = 0;
574*0b57cec5SDimitry Andric 
575*0b57cec5SDimitry Andric   std::vector<std::string> SectionTable;
576*0b57cec5SDimitry Andric   std::vector<std::string> GCTable;
577*0b57cec5SDimitry Andric 
578*0b57cec5SDimitry Andric   std::vector<Type *> TypeList;
57981ad6265SDimitry Andric   /// Track type IDs of contained types. Order is the same as the contained
58081ad6265SDimitry Andric   /// types of a Type*. This is used during upgrades of typed pointer IR in
58181ad6265SDimitry Andric   /// opaque pointer mode.
58281ad6265SDimitry Andric   DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
58381ad6265SDimitry Andric   /// In some cases, we need to create a type ID for a type that was not
58481ad6265SDimitry Andric   /// explicitly encoded in the bitcode, or we don't know about at the current
58581ad6265SDimitry Andric   /// point. For example, a global may explicitly encode the value type ID, but
58681ad6265SDimitry Andric   /// not have a type ID for the pointer to value type, for which we create a
58781ad6265SDimitry Andric   /// virtual type ID instead. This map stores the new type ID that was created
58881ad6265SDimitry Andric   /// for the given pair of Type and contained type ID.
58981ad6265SDimitry Andric   DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs;
59081ad6265SDimitry Andric   DenseMap<Function *, unsigned> FunctionTypeIDs;
59181ad6265SDimitry Andric   /// Allocator for BitcodeConstants. This should come before ValueList,
59281ad6265SDimitry Andric   /// because the ValueList might hold ValueHandles to these constants, so
59381ad6265SDimitry Andric   /// ValueList must be destroyed before Alloc.
59481ad6265SDimitry Andric   BumpPtrAllocator Alloc;
595*0b57cec5SDimitry Andric   BitcodeReaderValueList ValueList;
596*0b57cec5SDimitry Andric   Optional<MetadataLoader> MDLoader;
597*0b57cec5SDimitry Andric   std::vector<Comdat *> ComdatList;
5980eae32dcSDimitry Andric   DenseSet<GlobalObject *> ImplicitComdatObjects;
599*0b57cec5SDimitry Andric   SmallVector<Instruction *, 64> InstructionList;
600*0b57cec5SDimitry Andric 
601*0b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
602349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
603349cc55cSDimitry Andric 
604349cc55cSDimitry Andric   struct FunctionOperandInfo {
605349cc55cSDimitry Andric     Function *F;
606349cc55cSDimitry Andric     unsigned PersonalityFn;
607349cc55cSDimitry Andric     unsigned Prefix;
608349cc55cSDimitry Andric     unsigned Prologue;
609349cc55cSDimitry Andric   };
610349cc55cSDimitry Andric   std::vector<FunctionOperandInfo> FunctionOperands;
611*0b57cec5SDimitry Andric 
612*0b57cec5SDimitry Andric   /// The set of attributes by index.  Index zero in the file is for null, and
613*0b57cec5SDimitry Andric   /// is thus not represented here.  As such all indices are off by one.
614*0b57cec5SDimitry Andric   std::vector<AttributeList> MAttributes;
615*0b57cec5SDimitry Andric 
616*0b57cec5SDimitry Andric   /// The set of attribute groups.
617*0b57cec5SDimitry Andric   std::map<unsigned, AttributeList> MAttributeGroups;
618*0b57cec5SDimitry Andric 
619*0b57cec5SDimitry Andric   /// While parsing a function body, this is a list of the basic blocks for the
620*0b57cec5SDimitry Andric   /// function.
621*0b57cec5SDimitry Andric   std::vector<BasicBlock*> FunctionBBs;
622*0b57cec5SDimitry Andric 
623*0b57cec5SDimitry Andric   // When reading the module header, this list is populated with functions that
624*0b57cec5SDimitry Andric   // have bodies later in the file.
625*0b57cec5SDimitry Andric   std::vector<Function*> FunctionsWithBodies;
626*0b57cec5SDimitry Andric 
627*0b57cec5SDimitry Andric   // When intrinsic functions are encountered which require upgrading they are
628*0b57cec5SDimitry Andric   // stored here with their replacement function.
629*0b57cec5SDimitry Andric   using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
630*0b57cec5SDimitry Andric   UpdatedIntrinsicMap UpgradedIntrinsics;
631*0b57cec5SDimitry Andric   // Intrinsics which were remangled because of types rename
632*0b57cec5SDimitry Andric   UpdatedIntrinsicMap RemangledIntrinsics;
633*0b57cec5SDimitry Andric 
634*0b57cec5SDimitry Andric   // Several operations happen after the module header has been read, but
635*0b57cec5SDimitry Andric   // before function bodies are processed. This keeps track of whether
636*0b57cec5SDimitry Andric   // we've done this yet.
637*0b57cec5SDimitry Andric   bool SeenFirstFunctionBody = false;
638*0b57cec5SDimitry Andric 
639*0b57cec5SDimitry Andric   /// When function bodies are initially scanned, this map contains info about
640*0b57cec5SDimitry Andric   /// where to find deferred function body in the stream.
641*0b57cec5SDimitry Andric   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
642*0b57cec5SDimitry Andric 
643*0b57cec5SDimitry Andric   /// When Metadata block is initially scanned when parsing the module, we may
644*0b57cec5SDimitry Andric   /// choose to defer parsing of the metadata. This vector contains info about
645*0b57cec5SDimitry Andric   /// which Metadata blocks are deferred.
646*0b57cec5SDimitry Andric   std::vector<uint64_t> DeferredMetadataInfo;
647*0b57cec5SDimitry Andric 
648*0b57cec5SDimitry Andric   /// These are basic blocks forward-referenced by block addresses.  They are
649*0b57cec5SDimitry Andric   /// inserted lazily into functions when they're loaded.  The basic block ID is
650*0b57cec5SDimitry Andric   /// its index into the vector.
651*0b57cec5SDimitry Andric   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
652*0b57cec5SDimitry Andric   std::deque<Function *> BasicBlockFwdRefQueue;
653*0b57cec5SDimitry Andric 
65481ad6265SDimitry Andric   /// These are Functions that contain BlockAddresses which refer a different
65581ad6265SDimitry Andric   /// Function. When parsing the different Function, queue Functions that refer
65681ad6265SDimitry Andric   /// to the different Function. Those Functions must be materialized in order
65781ad6265SDimitry Andric   /// to resolve their BlockAddress constants before the different Function
65881ad6265SDimitry Andric   /// gets moved into another Module.
65981ad6265SDimitry Andric   std::vector<Function *> BackwardRefFunctions;
66081ad6265SDimitry Andric 
661*0b57cec5SDimitry Andric   /// Indicates that we are using a new encoding for instruction operands where
662*0b57cec5SDimitry Andric   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
663*0b57cec5SDimitry Andric   /// instruction number, for a more compact encoding.  Some instruction
664*0b57cec5SDimitry Andric   /// operands are not relative to the instruction ID: basic block numbers, and
665*0b57cec5SDimitry Andric   /// types. Once the old style function blocks have been phased out, we would
666*0b57cec5SDimitry Andric   /// not need this flag.
667*0b57cec5SDimitry Andric   bool UseRelativeIDs = false;
668*0b57cec5SDimitry Andric 
669*0b57cec5SDimitry Andric   /// True if all functions will be materialized, negating the need to process
670*0b57cec5SDimitry Andric   /// (e.g.) blockaddress forward references.
671*0b57cec5SDimitry Andric   bool WillMaterializeAllForwardRefs = false;
672*0b57cec5SDimitry Andric 
673*0b57cec5SDimitry Andric   bool StripDebugInfo = false;
674*0b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
675*0b57cec5SDimitry Andric 
676*0b57cec5SDimitry Andric   std::vector<std::string> BundleTags;
677*0b57cec5SDimitry Andric   SmallVector<SyncScope::ID, 8> SSIDs;
678*0b57cec5SDimitry Andric 
679*0b57cec5SDimitry Andric public:
680*0b57cec5SDimitry Andric   BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
681*0b57cec5SDimitry Andric                 StringRef ProducerIdentification, LLVMContext &Context);
682*0b57cec5SDimitry Andric 
683*0b57cec5SDimitry Andric   Error materializeForwardReferencedFunctions();
684*0b57cec5SDimitry Andric 
685*0b57cec5SDimitry Andric   Error materialize(GlobalValue *GV) override;
686*0b57cec5SDimitry Andric   Error materializeModule() override;
687*0b57cec5SDimitry Andric   std::vector<StructType *> getIdentifiedStructTypes() const override;
688*0b57cec5SDimitry Andric 
689*0b57cec5SDimitry Andric   /// Main interface to parsing a bitcode buffer.
690*0b57cec5SDimitry Andric   /// \returns true if an error occurred.
6915ffd83dbSDimitry Andric   Error parseBitcodeInto(
69281ad6265SDimitry Andric       Module *M, bool ShouldLazyLoadMetadata, bool IsImporting,
69381ad6265SDimitry Andric       DataLayoutCallbackTy DataLayoutCallback);
694*0b57cec5SDimitry Andric 
695*0b57cec5SDimitry Andric   static uint64_t decodeSignRotatedValue(uint64_t V);
696*0b57cec5SDimitry Andric 
697*0b57cec5SDimitry Andric   /// Materialize any deferred Metadata block.
698*0b57cec5SDimitry Andric   Error materializeMetadata() override;
699*0b57cec5SDimitry Andric 
700*0b57cec5SDimitry Andric   void setStripDebugInfo() override;
701*0b57cec5SDimitry Andric 
702*0b57cec5SDimitry Andric private:
703*0b57cec5SDimitry Andric   std::vector<StructType *> IdentifiedStructTypes;
704*0b57cec5SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
705*0b57cec5SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context);
706*0b57cec5SDimitry Andric 
70781ad6265SDimitry Andric   static constexpr unsigned InvalidTypeID = ~0u;
708*0b57cec5SDimitry Andric 
70981ad6265SDimitry Andric   Type *getTypeByID(unsigned ID);
71081ad6265SDimitry Andric   Type *getPtrElementTypeByID(unsigned ID);
71181ad6265SDimitry Andric   unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0);
71281ad6265SDimitry Andric   unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
71381ad6265SDimitry Andric 
71481ad6265SDimitry Andric   Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB);
71581ad6265SDimitry Andric   Expected<Constant *> getValueForInitializer(unsigned ID);
71681ad6265SDimitry Andric 
71781ad6265SDimitry Andric   Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID,
71881ad6265SDimitry Andric                         BasicBlock *ConstExprInsertBB) {
719*0b57cec5SDimitry Andric     if (Ty && Ty->isMetadataTy())
720*0b57cec5SDimitry Andric       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
72181ad6265SDimitry Andric     return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB);
722*0b57cec5SDimitry Andric   }
723*0b57cec5SDimitry Andric 
724*0b57cec5SDimitry Andric   Metadata *getFnMetadataByID(unsigned ID) {
725*0b57cec5SDimitry Andric     return MDLoader->getMetadataFwdRefOrLoad(ID);
726*0b57cec5SDimitry Andric   }
727*0b57cec5SDimitry Andric 
728*0b57cec5SDimitry Andric   BasicBlock *getBasicBlock(unsigned ID) const {
729*0b57cec5SDimitry Andric     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
730*0b57cec5SDimitry Andric     return FunctionBBs[ID];
731*0b57cec5SDimitry Andric   }
732*0b57cec5SDimitry Andric 
733*0b57cec5SDimitry Andric   AttributeList getAttributes(unsigned i) const {
734*0b57cec5SDimitry Andric     if (i-1 < MAttributes.size())
735*0b57cec5SDimitry Andric       return MAttributes[i-1];
736*0b57cec5SDimitry Andric     return AttributeList();
737*0b57cec5SDimitry Andric   }
738*0b57cec5SDimitry Andric 
739*0b57cec5SDimitry Andric   /// Read a value/type pair out of the specified record from slot 'Slot'.
740*0b57cec5SDimitry Andric   /// Increment Slot past the number of slots used in the record. Return true on
741*0b57cec5SDimitry Andric   /// failure.
742e8d8bef9SDimitry Andric   bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
74381ad6265SDimitry Andric                         unsigned InstNum, Value *&ResVal, unsigned &TypeID,
74481ad6265SDimitry Andric                         BasicBlock *ConstExprInsertBB) {
745*0b57cec5SDimitry Andric     if (Slot == Record.size()) return true;
746*0b57cec5SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot++];
747*0b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
748*0b57cec5SDimitry Andric     if (UseRelativeIDs)
749*0b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
750*0b57cec5SDimitry Andric     if (ValNo < InstNum) {
751*0b57cec5SDimitry Andric       // If this is not a forward reference, just return the value we already
752*0b57cec5SDimitry Andric       // have.
75381ad6265SDimitry Andric       TypeID = ValueList.getTypeID(ValNo);
75481ad6265SDimitry Andric       ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB);
75581ad6265SDimitry Andric       assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) &&
75681ad6265SDimitry Andric              "Incorrect type ID stored for value");
757*0b57cec5SDimitry Andric       return ResVal == nullptr;
758*0b57cec5SDimitry Andric     }
759*0b57cec5SDimitry Andric     if (Slot == Record.size())
760*0b57cec5SDimitry Andric       return true;
761*0b57cec5SDimitry Andric 
76281ad6265SDimitry Andric     TypeID = (unsigned)Record[Slot++];
76381ad6265SDimitry Andric     ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID,
76481ad6265SDimitry Andric                             ConstExprInsertBB);
765*0b57cec5SDimitry Andric     return ResVal == nullptr;
766*0b57cec5SDimitry Andric   }
767*0b57cec5SDimitry Andric 
768*0b57cec5SDimitry Andric   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
769*0b57cec5SDimitry Andric   /// past the number of slots used by the value in the record. Return true if
770*0b57cec5SDimitry Andric   /// there is an error.
771e8d8bef9SDimitry Andric   bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
77281ad6265SDimitry Andric                 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
77381ad6265SDimitry Andric                 BasicBlock *ConstExprInsertBB) {
77481ad6265SDimitry Andric     if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
775*0b57cec5SDimitry Andric       return true;
776*0b57cec5SDimitry Andric     // All values currently take a single record slot.
777*0b57cec5SDimitry Andric     ++Slot;
778*0b57cec5SDimitry Andric     return false;
779*0b57cec5SDimitry Andric   }
780*0b57cec5SDimitry Andric 
781*0b57cec5SDimitry Andric   /// Like popValue, but does not increment the Slot number.
782e8d8bef9SDimitry Andric   bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
78381ad6265SDimitry Andric                 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
78481ad6265SDimitry Andric                 BasicBlock *ConstExprInsertBB) {
78581ad6265SDimitry Andric     ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
786*0b57cec5SDimitry Andric     return ResVal == nullptr;
787*0b57cec5SDimitry Andric   }
788*0b57cec5SDimitry Andric 
789*0b57cec5SDimitry Andric   /// Version of getValue that returns ResVal directly, or 0 if there is an
790*0b57cec5SDimitry Andric   /// error.
791e8d8bef9SDimitry Andric   Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
79281ad6265SDimitry Andric                   unsigned InstNum, Type *Ty, unsigned TyID,
79381ad6265SDimitry Andric                   BasicBlock *ConstExprInsertBB) {
794*0b57cec5SDimitry Andric     if (Slot == Record.size()) return nullptr;
795*0b57cec5SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot];
796*0b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
797*0b57cec5SDimitry Andric     if (UseRelativeIDs)
798*0b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
79981ad6265SDimitry Andric     return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
800*0b57cec5SDimitry Andric   }
801*0b57cec5SDimitry Andric 
802*0b57cec5SDimitry Andric   /// Like getValue, but decodes signed VBRs.
803e8d8bef9SDimitry Andric   Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
80481ad6265SDimitry Andric                         unsigned InstNum, Type *Ty, unsigned TyID,
80581ad6265SDimitry Andric                         BasicBlock *ConstExprInsertBB) {
806*0b57cec5SDimitry Andric     if (Slot == Record.size()) return nullptr;
807*0b57cec5SDimitry Andric     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
808*0b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
809*0b57cec5SDimitry Andric     if (UseRelativeIDs)
810*0b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
81181ad6265SDimitry Andric     return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
812*0b57cec5SDimitry Andric   }
813*0b57cec5SDimitry Andric 
814fe6060f1SDimitry Andric   /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
815fe6060f1SDimitry Andric   /// corresponding argument's pointee type. Also upgrades intrinsics that now
816fe6060f1SDimitry Andric   /// require an elementtype attribute.
81781ad6265SDimitry Andric   Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
818*0b57cec5SDimitry Andric 
819*0b57cec5SDimitry Andric   /// Converts alignment exponent (i.e. power of two (or zero)) to the
820*0b57cec5SDimitry Andric   /// corresponding alignment to use. If alignment is too large, returns
821*0b57cec5SDimitry Andric   /// a corresponding error code.
8228bcb0991SDimitry Andric   Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
823*0b57cec5SDimitry Andric   Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
8245ffd83dbSDimitry Andric   Error parseModule(
8255ffd83dbSDimitry Andric       uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
8265ffd83dbSDimitry Andric       DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });
827*0b57cec5SDimitry Andric 
828*0b57cec5SDimitry Andric   Error parseComdatRecord(ArrayRef<uint64_t> Record);
829*0b57cec5SDimitry Andric   Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
830*0b57cec5SDimitry Andric   Error parseFunctionRecord(ArrayRef<uint64_t> Record);
831*0b57cec5SDimitry Andric   Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
832*0b57cec5SDimitry Andric                                         ArrayRef<uint64_t> Record);
833*0b57cec5SDimitry Andric 
834*0b57cec5SDimitry Andric   Error parseAttributeBlock();
835*0b57cec5SDimitry Andric   Error parseAttributeGroupBlock();
836*0b57cec5SDimitry Andric   Error parseTypeTable();
837*0b57cec5SDimitry Andric   Error parseTypeTableBody();
838*0b57cec5SDimitry Andric   Error parseOperandBundleTags();
839*0b57cec5SDimitry Andric   Error parseSyncScopeNames();
840*0b57cec5SDimitry Andric 
841*0b57cec5SDimitry Andric   Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
842*0b57cec5SDimitry Andric                                 unsigned NameIndex, Triple &TT);
843*0b57cec5SDimitry Andric   void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
844*0b57cec5SDimitry Andric                                ArrayRef<uint64_t> Record);
845*0b57cec5SDimitry Andric   Error parseValueSymbolTable(uint64_t Offset = 0);
846*0b57cec5SDimitry Andric   Error parseGlobalValueSymbolTable();
847*0b57cec5SDimitry Andric   Error parseConstants();
848*0b57cec5SDimitry Andric   Error rememberAndSkipFunctionBodies();
849*0b57cec5SDimitry Andric   Error rememberAndSkipFunctionBody();
850*0b57cec5SDimitry Andric   /// Save the positions of the Metadata blocks and skip parsing the blocks.
851*0b57cec5SDimitry Andric   Error rememberAndSkipMetadata();
852*0b57cec5SDimitry Andric   Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
853*0b57cec5SDimitry Andric   Error parseFunctionBody(Function *F);
854*0b57cec5SDimitry Andric   Error globalCleanup();
855*0b57cec5SDimitry Andric   Error resolveGlobalAndIndirectSymbolInits();
856*0b57cec5SDimitry Andric   Error parseUseLists();
857*0b57cec5SDimitry Andric   Error findFunctionInStream(
858*0b57cec5SDimitry Andric       Function *F,
859*0b57cec5SDimitry Andric       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
860*0b57cec5SDimitry Andric 
861*0b57cec5SDimitry Andric   SyncScope::ID getDecodedSyncScopeID(unsigned Val);
862*0b57cec5SDimitry Andric };
863*0b57cec5SDimitry Andric 
864*0b57cec5SDimitry Andric /// Class to manage reading and parsing function summary index bitcode
865*0b57cec5SDimitry Andric /// files/sections.
866*0b57cec5SDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
867*0b57cec5SDimitry Andric   /// The module index built during parsing.
868*0b57cec5SDimitry Andric   ModuleSummaryIndex &TheIndex;
869*0b57cec5SDimitry Andric 
870*0b57cec5SDimitry Andric   /// Indicates whether we have encountered a global value summary section
871*0b57cec5SDimitry Andric   /// yet during parsing.
872*0b57cec5SDimitry Andric   bool SeenGlobalValSummary = false;
873*0b57cec5SDimitry Andric 
874*0b57cec5SDimitry Andric   /// Indicates whether we have already parsed the VST, used for error checking.
875*0b57cec5SDimitry Andric   bool SeenValueSymbolTable = false;
876*0b57cec5SDimitry Andric 
877*0b57cec5SDimitry Andric   /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
878*0b57cec5SDimitry Andric   /// Used to enable on-demand parsing of the VST.
879*0b57cec5SDimitry Andric   uint64_t VSTOffset = 0;
880*0b57cec5SDimitry Andric 
881*0b57cec5SDimitry Andric   // Map to save ValueId to ValueInfo association that was recorded in the
882*0b57cec5SDimitry Andric   // ValueSymbolTable. It is used after the VST is parsed to convert
883*0b57cec5SDimitry Andric   // call graph edges read from the function summary from referencing
884*0b57cec5SDimitry Andric   // callees by their ValueId to using the ValueInfo instead, which is how
885*0b57cec5SDimitry Andric   // they are recorded in the summary index being built.
886*0b57cec5SDimitry Andric   // We save a GUID which refers to the same global as the ValueInfo, but
887*0b57cec5SDimitry Andric   // ignoring the linkage, i.e. for values other than local linkage they are
888*0b57cec5SDimitry Andric   // identical.
889*0b57cec5SDimitry Andric   DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
890*0b57cec5SDimitry Andric       ValueIdToValueInfoMap;
891*0b57cec5SDimitry Andric 
892*0b57cec5SDimitry Andric   /// Map populated during module path string table parsing, from the
893*0b57cec5SDimitry Andric   /// module ID to a string reference owned by the index's module
894*0b57cec5SDimitry Andric   /// path string table, used to correlate with combined index
895*0b57cec5SDimitry Andric   /// summary records.
896*0b57cec5SDimitry Andric   DenseMap<uint64_t, StringRef> ModuleIdMap;
897*0b57cec5SDimitry Andric 
898*0b57cec5SDimitry Andric   /// Original source file name recorded in a bitcode record.
899*0b57cec5SDimitry Andric   std::string SourceFileName;
900*0b57cec5SDimitry Andric 
901*0b57cec5SDimitry Andric   /// The string identifier given to this module by the client, normally the
902*0b57cec5SDimitry Andric   /// path to the bitcode file.
903*0b57cec5SDimitry Andric   StringRef ModulePath;
904*0b57cec5SDimitry Andric 
905*0b57cec5SDimitry Andric   /// For per-module summary indexes, the unique numerical identifier given to
906*0b57cec5SDimitry Andric   /// this module by the client.
907*0b57cec5SDimitry Andric   unsigned ModuleId;
908*0b57cec5SDimitry Andric 
909*0b57cec5SDimitry Andric public:
910*0b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
911*0b57cec5SDimitry Andric                                   ModuleSummaryIndex &TheIndex,
912*0b57cec5SDimitry Andric                                   StringRef ModulePath, unsigned ModuleId);
913*0b57cec5SDimitry Andric 
914*0b57cec5SDimitry Andric   Error parseModule();
915*0b57cec5SDimitry Andric 
916*0b57cec5SDimitry Andric private:
917*0b57cec5SDimitry Andric   void setValueGUID(uint64_t ValueID, StringRef ValueName,
918*0b57cec5SDimitry Andric                     GlobalValue::LinkageTypes Linkage,
919*0b57cec5SDimitry Andric                     StringRef SourceFileName);
920*0b57cec5SDimitry Andric   Error parseValueSymbolTable(
921*0b57cec5SDimitry Andric       uint64_t Offset,
922*0b57cec5SDimitry Andric       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
923*0b57cec5SDimitry Andric   std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
924*0b57cec5SDimitry Andric   std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
925*0b57cec5SDimitry Andric                                                     bool IsOldProfileFormat,
926*0b57cec5SDimitry Andric                                                     bool HasProfile,
927*0b57cec5SDimitry Andric                                                     bool HasRelBF);
928*0b57cec5SDimitry Andric   Error parseEntireSummary(unsigned ID);
929*0b57cec5SDimitry Andric   Error parseModuleStringTable();
930*0b57cec5SDimitry Andric   void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
931*0b57cec5SDimitry Andric   void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
932*0b57cec5SDimitry Andric                                        TypeIdCompatibleVtableInfo &TypeId);
933e8d8bef9SDimitry Andric   std::vector<FunctionSummary::ParamAccess>
934e8d8bef9SDimitry Andric   parseParamAccesses(ArrayRef<uint64_t> Record);
935*0b57cec5SDimitry Andric 
936*0b57cec5SDimitry Andric   std::pair<ValueInfo, GlobalValue::GUID>
937*0b57cec5SDimitry Andric   getValueInfoFromValueId(unsigned ValueId);
938*0b57cec5SDimitry Andric 
939*0b57cec5SDimitry Andric   void addThisModule();
940*0b57cec5SDimitry Andric   ModuleSummaryIndex::ModuleInfo *getThisModule();
941*0b57cec5SDimitry Andric };
942*0b57cec5SDimitry Andric 
943*0b57cec5SDimitry Andric } // end anonymous namespace
944*0b57cec5SDimitry Andric 
945*0b57cec5SDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
946*0b57cec5SDimitry Andric                                                     Error Err) {
947*0b57cec5SDimitry Andric   if (Err) {
948*0b57cec5SDimitry Andric     std::error_code EC;
949*0b57cec5SDimitry Andric     handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
950*0b57cec5SDimitry Andric       EC = EIB.convertToErrorCode();
951*0b57cec5SDimitry Andric       Ctx.emitError(EIB.message());
952*0b57cec5SDimitry Andric     });
953*0b57cec5SDimitry Andric     return EC;
954*0b57cec5SDimitry Andric   }
955*0b57cec5SDimitry Andric   return std::error_code();
956*0b57cec5SDimitry Andric }
957*0b57cec5SDimitry Andric 
958*0b57cec5SDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
959*0b57cec5SDimitry Andric                              StringRef ProducerIdentification,
960*0b57cec5SDimitry Andric                              LLVMContext &Context)
961*0b57cec5SDimitry Andric     : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
96281ad6265SDimitry Andric       ValueList(this->Stream.SizeInBytes(),
96381ad6265SDimitry Andric                 [this](unsigned ValID, BasicBlock *InsertBB) {
96481ad6265SDimitry Andric                   return materializeValue(ValID, InsertBB);
96581ad6265SDimitry Andric                 }) {
9665ffd83dbSDimitry Andric   this->ProducerIdentification = std::string(ProducerIdentification);
967*0b57cec5SDimitry Andric }
968*0b57cec5SDimitry Andric 
969*0b57cec5SDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() {
970*0b57cec5SDimitry Andric   if (WillMaterializeAllForwardRefs)
971*0b57cec5SDimitry Andric     return Error::success();
972*0b57cec5SDimitry Andric 
973*0b57cec5SDimitry Andric   // Prevent recursion.
974*0b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = true;
975*0b57cec5SDimitry Andric 
976*0b57cec5SDimitry Andric   while (!BasicBlockFwdRefQueue.empty()) {
977*0b57cec5SDimitry Andric     Function *F = BasicBlockFwdRefQueue.front();
978*0b57cec5SDimitry Andric     BasicBlockFwdRefQueue.pop_front();
979*0b57cec5SDimitry Andric     assert(F && "Expected valid function");
980*0b57cec5SDimitry Andric     if (!BasicBlockFwdRefs.count(F))
981*0b57cec5SDimitry Andric       // Already materialized.
982*0b57cec5SDimitry Andric       continue;
983*0b57cec5SDimitry Andric 
984*0b57cec5SDimitry Andric     // Check for a function that isn't materializable to prevent an infinite
985*0b57cec5SDimitry Andric     // loop.  When parsing a blockaddress stored in a global variable, there
986*0b57cec5SDimitry Andric     // isn't a trivial way to check if a function will have a body without a
987*0b57cec5SDimitry Andric     // linear search through FunctionsWithBodies, so just check it here.
988*0b57cec5SDimitry Andric     if (!F->isMaterializable())
989*0b57cec5SDimitry Andric       return error("Never resolved function from blockaddress");
990*0b57cec5SDimitry Andric 
991*0b57cec5SDimitry Andric     // Try to materialize F.
992*0b57cec5SDimitry Andric     if (Error Err = materialize(F))
993*0b57cec5SDimitry Andric       return Err;
994*0b57cec5SDimitry Andric   }
995*0b57cec5SDimitry Andric   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
996*0b57cec5SDimitry Andric 
99781ad6265SDimitry Andric   for (Function *F : BackwardRefFunctions)
99881ad6265SDimitry Andric     if (Error Err = materialize(F))
99981ad6265SDimitry Andric       return Err;
100081ad6265SDimitry Andric   BackwardRefFunctions.clear();
100181ad6265SDimitry Andric 
1002*0b57cec5SDimitry Andric   // Reset state.
1003*0b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = false;
1004*0b57cec5SDimitry Andric   return Error::success();
1005*0b57cec5SDimitry Andric }
1006*0b57cec5SDimitry Andric 
1007*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1008*0b57cec5SDimitry Andric //  Helper functions to implement forward reference resolution, etc.
1009*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1010*0b57cec5SDimitry Andric 
1011*0b57cec5SDimitry Andric static bool hasImplicitComdat(size_t Val) {
1012*0b57cec5SDimitry Andric   switch (Val) {
1013*0b57cec5SDimitry Andric   default:
1014*0b57cec5SDimitry Andric     return false;
1015*0b57cec5SDimitry Andric   case 1:  // Old WeakAnyLinkage
1016*0b57cec5SDimitry Andric   case 4:  // Old LinkOnceAnyLinkage
1017*0b57cec5SDimitry Andric   case 10: // Old WeakODRLinkage
1018*0b57cec5SDimitry Andric   case 11: // Old LinkOnceODRLinkage
1019*0b57cec5SDimitry Andric     return true;
1020*0b57cec5SDimitry Andric   }
1021*0b57cec5SDimitry Andric }
1022*0b57cec5SDimitry Andric 
1023*0b57cec5SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
1024*0b57cec5SDimitry Andric   switch (Val) {
1025*0b57cec5SDimitry Andric   default: // Map unknown/new linkages to external
1026*0b57cec5SDimitry Andric   case 0:
1027*0b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage;
1028*0b57cec5SDimitry Andric   case 2:
1029*0b57cec5SDimitry Andric     return GlobalValue::AppendingLinkage;
1030*0b57cec5SDimitry Andric   case 3:
1031*0b57cec5SDimitry Andric     return GlobalValue::InternalLinkage;
1032*0b57cec5SDimitry Andric   case 5:
1033*0b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
1034*0b57cec5SDimitry Andric   case 6:
1035*0b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
1036*0b57cec5SDimitry Andric   case 7:
1037*0b57cec5SDimitry Andric     return GlobalValue::ExternalWeakLinkage;
1038*0b57cec5SDimitry Andric   case 8:
1039*0b57cec5SDimitry Andric     return GlobalValue::CommonLinkage;
1040*0b57cec5SDimitry Andric   case 9:
1041*0b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage;
1042*0b57cec5SDimitry Andric   case 12:
1043*0b57cec5SDimitry Andric     return GlobalValue::AvailableExternallyLinkage;
1044*0b57cec5SDimitry Andric   case 13:
1045*0b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
1046*0b57cec5SDimitry Andric   case 14:
1047*0b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
1048*0b57cec5SDimitry Andric   case 15:
1049*0b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
1050*0b57cec5SDimitry Andric   case 1: // Old value with implicit comdat.
1051*0b57cec5SDimitry Andric   case 16:
1052*0b57cec5SDimitry Andric     return GlobalValue::WeakAnyLinkage;
1053*0b57cec5SDimitry Andric   case 10: // Old value with implicit comdat.
1054*0b57cec5SDimitry Andric   case 17:
1055*0b57cec5SDimitry Andric     return GlobalValue::WeakODRLinkage;
1056*0b57cec5SDimitry Andric   case 4: // Old value with implicit comdat.
1057*0b57cec5SDimitry Andric   case 18:
1058*0b57cec5SDimitry Andric     return GlobalValue::LinkOnceAnyLinkage;
1059*0b57cec5SDimitry Andric   case 11: // Old value with implicit comdat.
1060*0b57cec5SDimitry Andric   case 19:
1061*0b57cec5SDimitry Andric     return GlobalValue::LinkOnceODRLinkage;
1062*0b57cec5SDimitry Andric   }
1063*0b57cec5SDimitry Andric }
1064*0b57cec5SDimitry Andric 
1065*0b57cec5SDimitry Andric static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
1066*0b57cec5SDimitry Andric   FunctionSummary::FFlags Flags;
1067*0b57cec5SDimitry Andric   Flags.ReadNone = RawFlags & 0x1;
1068*0b57cec5SDimitry Andric   Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1069*0b57cec5SDimitry Andric   Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1070*0b57cec5SDimitry Andric   Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1071*0b57cec5SDimitry Andric   Flags.NoInline = (RawFlags >> 4) & 0x1;
1072480093f4SDimitry Andric   Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1073349cc55cSDimitry Andric   Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1074349cc55cSDimitry Andric   Flags.MayThrow = (RawFlags >> 7) & 0x1;
1075349cc55cSDimitry Andric   Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
10760eae32dcSDimitry Andric   Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1077*0b57cec5SDimitry Andric   return Flags;
1078*0b57cec5SDimitry Andric }
1079*0b57cec5SDimitry Andric 
1080fe6060f1SDimitry Andric // Decode the flags for GlobalValue in the summary. The bits for each attribute:
1081fe6060f1SDimitry Andric //
1082fe6060f1SDimitry Andric // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
1083fe6060f1SDimitry Andric // visibility: [8, 10).
1084*0b57cec5SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
1085*0b57cec5SDimitry Andric                                                             uint64_t Version) {
1086*0b57cec5SDimitry Andric   // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
1087*0b57cec5SDimitry Andric   // like getDecodedLinkage() above. Any future change to the linkage enum and
1088*0b57cec5SDimitry Andric   // to getDecodedLinkage() will need to be taken into account here as above.
1089*0b57cec5SDimitry Andric   auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
1090fe6060f1SDimitry Andric   auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
1091*0b57cec5SDimitry Andric   RawFlags = RawFlags >> 4;
1092*0b57cec5SDimitry Andric   bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1093*0b57cec5SDimitry Andric   // The Live flag wasn't introduced until version 3. For dead stripping
1094*0b57cec5SDimitry Andric   // to work correctly on earlier versions, we must conservatively treat all
1095*0b57cec5SDimitry Andric   // values as live.
1096*0b57cec5SDimitry Andric   bool Live = (RawFlags & 0x2) || Version < 3;
1097*0b57cec5SDimitry Andric   bool Local = (RawFlags & 0x4);
1098*0b57cec5SDimitry Andric   bool AutoHide = (RawFlags & 0x8);
1099*0b57cec5SDimitry Andric 
1100fe6060f1SDimitry Andric   return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
1101fe6060f1SDimitry Andric                                      Live, Local, AutoHide);
1102*0b57cec5SDimitry Andric }
1103*0b57cec5SDimitry Andric 
1104*0b57cec5SDimitry Andric // Decode the flags for GlobalVariable in the summary
1105*0b57cec5SDimitry Andric static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
11065ffd83dbSDimitry Andric   return GlobalVarSummary::GVarFlags(
11075ffd83dbSDimitry Andric       (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
11085ffd83dbSDimitry Andric       (RawFlags & 0x4) ? true : false,
11095ffd83dbSDimitry Andric       (GlobalObject::VCallVisibility)(RawFlags >> 3));
1110*0b57cec5SDimitry Andric }
1111*0b57cec5SDimitry Andric 
1112*0b57cec5SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
1113*0b57cec5SDimitry Andric   switch (Val) {
1114*0b57cec5SDimitry Andric   default: // Map unknown visibilities to default.
1115*0b57cec5SDimitry Andric   case 0: return GlobalValue::DefaultVisibility;
1116*0b57cec5SDimitry Andric   case 1: return GlobalValue::HiddenVisibility;
1117*0b57cec5SDimitry Andric   case 2: return GlobalValue::ProtectedVisibility;
1118*0b57cec5SDimitry Andric   }
1119*0b57cec5SDimitry Andric }
1120*0b57cec5SDimitry Andric 
1121*0b57cec5SDimitry Andric static GlobalValue::DLLStorageClassTypes
1122*0b57cec5SDimitry Andric getDecodedDLLStorageClass(unsigned Val) {
1123*0b57cec5SDimitry Andric   switch (Val) {
1124*0b57cec5SDimitry Andric   default: // Map unknown values to default.
1125*0b57cec5SDimitry Andric   case 0: return GlobalValue::DefaultStorageClass;
1126*0b57cec5SDimitry Andric   case 1: return GlobalValue::DLLImportStorageClass;
1127*0b57cec5SDimitry Andric   case 2: return GlobalValue::DLLExportStorageClass;
1128*0b57cec5SDimitry Andric   }
1129*0b57cec5SDimitry Andric }
1130*0b57cec5SDimitry Andric 
1131*0b57cec5SDimitry Andric static bool getDecodedDSOLocal(unsigned Val) {
1132*0b57cec5SDimitry Andric   switch(Val) {
1133*0b57cec5SDimitry Andric   default: // Map unknown values to preemptable.
1134*0b57cec5SDimitry Andric   case 0:  return false;
1135*0b57cec5SDimitry Andric   case 1:  return true;
1136*0b57cec5SDimitry Andric   }
1137*0b57cec5SDimitry Andric }
1138*0b57cec5SDimitry Andric 
1139*0b57cec5SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
1140*0b57cec5SDimitry Andric   switch (Val) {
1141*0b57cec5SDimitry Andric     case 0: return GlobalVariable::NotThreadLocal;
1142*0b57cec5SDimitry Andric     default: // Map unknown non-zero value to general dynamic.
1143*0b57cec5SDimitry Andric     case 1: return GlobalVariable::GeneralDynamicTLSModel;
1144*0b57cec5SDimitry Andric     case 2: return GlobalVariable::LocalDynamicTLSModel;
1145*0b57cec5SDimitry Andric     case 3: return GlobalVariable::InitialExecTLSModel;
1146*0b57cec5SDimitry Andric     case 4: return GlobalVariable::LocalExecTLSModel;
1147*0b57cec5SDimitry Andric   }
1148*0b57cec5SDimitry Andric }
1149*0b57cec5SDimitry Andric 
1150*0b57cec5SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
1151*0b57cec5SDimitry Andric   switch (Val) {
1152*0b57cec5SDimitry Andric     default: // Map unknown to UnnamedAddr::None.
1153*0b57cec5SDimitry Andric     case 0: return GlobalVariable::UnnamedAddr::None;
1154*0b57cec5SDimitry Andric     case 1: return GlobalVariable::UnnamedAddr::Global;
1155*0b57cec5SDimitry Andric     case 2: return GlobalVariable::UnnamedAddr::Local;
1156*0b57cec5SDimitry Andric   }
1157*0b57cec5SDimitry Andric }
1158*0b57cec5SDimitry Andric 
1159*0b57cec5SDimitry Andric static int getDecodedCastOpcode(unsigned Val) {
1160*0b57cec5SDimitry Andric   switch (Val) {
1161*0b57cec5SDimitry Andric   default: return -1;
1162*0b57cec5SDimitry Andric   case bitc::CAST_TRUNC   : return Instruction::Trunc;
1163*0b57cec5SDimitry Andric   case bitc::CAST_ZEXT    : return Instruction::ZExt;
1164*0b57cec5SDimitry Andric   case bitc::CAST_SEXT    : return Instruction::SExt;
1165*0b57cec5SDimitry Andric   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
1166*0b57cec5SDimitry Andric   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
1167*0b57cec5SDimitry Andric   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
1168*0b57cec5SDimitry Andric   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
1169*0b57cec5SDimitry Andric   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
1170*0b57cec5SDimitry Andric   case bitc::CAST_FPEXT   : return Instruction::FPExt;
1171*0b57cec5SDimitry Andric   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
1172*0b57cec5SDimitry Andric   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
1173*0b57cec5SDimitry Andric   case bitc::CAST_BITCAST : return Instruction::BitCast;
1174*0b57cec5SDimitry Andric   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
1175*0b57cec5SDimitry Andric   }
1176*0b57cec5SDimitry Andric }
1177*0b57cec5SDimitry Andric 
1178*0b57cec5SDimitry Andric static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
1179*0b57cec5SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
1180*0b57cec5SDimitry Andric   // UnOps are only valid for int/fp or vector of int/fp types
1181*0b57cec5SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
1182*0b57cec5SDimitry Andric     return -1;
1183*0b57cec5SDimitry Andric 
1184*0b57cec5SDimitry Andric   switch (Val) {
1185*0b57cec5SDimitry Andric   default:
1186*0b57cec5SDimitry Andric     return -1;
11878bcb0991SDimitry Andric   case bitc::UNOP_FNEG:
1188*0b57cec5SDimitry Andric     return IsFP ? Instruction::FNeg : -1;
1189*0b57cec5SDimitry Andric   }
1190*0b57cec5SDimitry Andric }
1191*0b57cec5SDimitry Andric 
1192*0b57cec5SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
1193*0b57cec5SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
1194*0b57cec5SDimitry Andric   // BinOps are only valid for int/fp or vector of int/fp types
1195*0b57cec5SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
1196*0b57cec5SDimitry Andric     return -1;
1197*0b57cec5SDimitry Andric 
1198*0b57cec5SDimitry Andric   switch (Val) {
1199*0b57cec5SDimitry Andric   default:
1200*0b57cec5SDimitry Andric     return -1;
1201*0b57cec5SDimitry Andric   case bitc::BINOP_ADD:
1202*0b57cec5SDimitry Andric     return IsFP ? Instruction::FAdd : Instruction::Add;
1203*0b57cec5SDimitry Andric   case bitc::BINOP_SUB:
1204*0b57cec5SDimitry Andric     return IsFP ? Instruction::FSub : Instruction::Sub;
1205*0b57cec5SDimitry Andric   case bitc::BINOP_MUL:
1206*0b57cec5SDimitry Andric     return IsFP ? Instruction::FMul : Instruction::Mul;
1207*0b57cec5SDimitry Andric   case bitc::BINOP_UDIV:
1208*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::UDiv;
1209*0b57cec5SDimitry Andric   case bitc::BINOP_SDIV:
1210*0b57cec5SDimitry Andric     return IsFP ? Instruction::FDiv : Instruction::SDiv;
1211*0b57cec5SDimitry Andric   case bitc::BINOP_UREM:
1212*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::URem;
1213*0b57cec5SDimitry Andric   case bitc::BINOP_SREM:
1214*0b57cec5SDimitry Andric     return IsFP ? Instruction::FRem : Instruction::SRem;
1215*0b57cec5SDimitry Andric   case bitc::BINOP_SHL:
1216*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Shl;
1217*0b57cec5SDimitry Andric   case bitc::BINOP_LSHR:
1218*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::LShr;
1219*0b57cec5SDimitry Andric   case bitc::BINOP_ASHR:
1220*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::AShr;
1221*0b57cec5SDimitry Andric   case bitc::BINOP_AND:
1222*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::And;
1223*0b57cec5SDimitry Andric   case bitc::BINOP_OR:
1224*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Or;
1225*0b57cec5SDimitry Andric   case bitc::BINOP_XOR:
1226*0b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Xor;
1227*0b57cec5SDimitry Andric   }
1228*0b57cec5SDimitry Andric }
1229*0b57cec5SDimitry Andric 
1230*0b57cec5SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
1231*0b57cec5SDimitry Andric   switch (Val) {
1232*0b57cec5SDimitry Andric   default: return AtomicRMWInst::BAD_BINOP;
1233*0b57cec5SDimitry Andric   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1234*0b57cec5SDimitry Andric   case bitc::RMW_ADD: return AtomicRMWInst::Add;
1235*0b57cec5SDimitry Andric   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1236*0b57cec5SDimitry Andric   case bitc::RMW_AND: return AtomicRMWInst::And;
1237*0b57cec5SDimitry Andric   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1238*0b57cec5SDimitry Andric   case bitc::RMW_OR: return AtomicRMWInst::Or;
1239*0b57cec5SDimitry Andric   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1240*0b57cec5SDimitry Andric   case bitc::RMW_MAX: return AtomicRMWInst::Max;
1241*0b57cec5SDimitry Andric   case bitc::RMW_MIN: return AtomicRMWInst::Min;
1242*0b57cec5SDimitry Andric   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1243*0b57cec5SDimitry Andric   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1244*0b57cec5SDimitry Andric   case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
1245*0b57cec5SDimitry Andric   case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1246*0b57cec5SDimitry Andric   }
1247*0b57cec5SDimitry Andric }
1248*0b57cec5SDimitry Andric 
1249*0b57cec5SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) {
1250*0b57cec5SDimitry Andric   switch (Val) {
1251*0b57cec5SDimitry Andric   case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1252*0b57cec5SDimitry Andric   case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1253*0b57cec5SDimitry Andric   case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1254*0b57cec5SDimitry Andric   case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1255*0b57cec5SDimitry Andric   case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1256*0b57cec5SDimitry Andric   case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
1257*0b57cec5SDimitry Andric   default: // Map unknown orderings to sequentially-consistent.
1258*0b57cec5SDimitry Andric   case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
1259*0b57cec5SDimitry Andric   }
1260*0b57cec5SDimitry Andric }
1261*0b57cec5SDimitry Andric 
1262*0b57cec5SDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1263*0b57cec5SDimitry Andric   switch (Val) {
1264*0b57cec5SDimitry Andric   default: // Map unknown selection kinds to any.
1265*0b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_ANY:
1266*0b57cec5SDimitry Andric     return Comdat::Any;
1267*0b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1268*0b57cec5SDimitry Andric     return Comdat::ExactMatch;
1269*0b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_LARGEST:
1270*0b57cec5SDimitry Andric     return Comdat::Largest;
1271*0b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1272fe6060f1SDimitry Andric     return Comdat::NoDeduplicate;
1273*0b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1274*0b57cec5SDimitry Andric     return Comdat::SameSize;
1275*0b57cec5SDimitry Andric   }
1276*0b57cec5SDimitry Andric }
1277*0b57cec5SDimitry Andric 
1278*0b57cec5SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1279*0b57cec5SDimitry Andric   FastMathFlags FMF;
1280*0b57cec5SDimitry Andric   if (0 != (Val & bitc::UnsafeAlgebra))
1281*0b57cec5SDimitry Andric     FMF.setFast();
1282*0b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowReassoc))
1283*0b57cec5SDimitry Andric     FMF.setAllowReassoc();
1284*0b57cec5SDimitry Andric   if (0 != (Val & bitc::NoNaNs))
1285*0b57cec5SDimitry Andric     FMF.setNoNaNs();
1286*0b57cec5SDimitry Andric   if (0 != (Val & bitc::NoInfs))
1287*0b57cec5SDimitry Andric     FMF.setNoInfs();
1288*0b57cec5SDimitry Andric   if (0 != (Val & bitc::NoSignedZeros))
1289*0b57cec5SDimitry Andric     FMF.setNoSignedZeros();
1290*0b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowReciprocal))
1291*0b57cec5SDimitry Andric     FMF.setAllowReciprocal();
1292*0b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowContract))
1293*0b57cec5SDimitry Andric     FMF.setAllowContract(true);
1294*0b57cec5SDimitry Andric   if (0 != (Val & bitc::ApproxFunc))
1295*0b57cec5SDimitry Andric     FMF.setApproxFunc();
1296*0b57cec5SDimitry Andric   return FMF;
1297*0b57cec5SDimitry Andric }
1298*0b57cec5SDimitry Andric 
1299*0b57cec5SDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1300*0b57cec5SDimitry Andric   switch (Val) {
1301*0b57cec5SDimitry Andric   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1302*0b57cec5SDimitry Andric   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1303*0b57cec5SDimitry Andric   }
1304*0b57cec5SDimitry Andric }
1305*0b57cec5SDimitry Andric 
1306fe6060f1SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) {
1307*0b57cec5SDimitry Andric   // The type table size is always specified correctly.
1308*0b57cec5SDimitry Andric   if (ID >= TypeList.size())
1309*0b57cec5SDimitry Andric     return nullptr;
1310*0b57cec5SDimitry Andric 
1311*0b57cec5SDimitry Andric   if (Type *Ty = TypeList[ID])
1312*0b57cec5SDimitry Andric     return Ty;
1313*0b57cec5SDimitry Andric 
1314*0b57cec5SDimitry Andric   // If we have a forward reference, the only possible case is when it is to a
1315*0b57cec5SDimitry Andric   // named struct.  Just create a placeholder for now.
1316*0b57cec5SDimitry Andric   return TypeList[ID] = createIdentifiedStructType(Context);
1317*0b57cec5SDimitry Andric }
1318*0b57cec5SDimitry Andric 
131981ad6265SDimitry Andric unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) {
132081ad6265SDimitry Andric   auto It = ContainedTypeIDs.find(ID);
132181ad6265SDimitry Andric   if (It == ContainedTypeIDs.end())
132281ad6265SDimitry Andric     return InvalidTypeID;
132381ad6265SDimitry Andric 
132481ad6265SDimitry Andric   if (Idx >= It->second.size())
132581ad6265SDimitry Andric     return InvalidTypeID;
132681ad6265SDimitry Andric 
132781ad6265SDimitry Andric   return It->second[Idx];
132881ad6265SDimitry Andric }
132981ad6265SDimitry Andric 
133081ad6265SDimitry Andric Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) {
133181ad6265SDimitry Andric   if (ID >= TypeList.size())
133281ad6265SDimitry Andric     return nullptr;
133381ad6265SDimitry Andric 
133481ad6265SDimitry Andric   Type *Ty = TypeList[ID];
133581ad6265SDimitry Andric   if (!Ty->isPointerTy())
133681ad6265SDimitry Andric     return nullptr;
133781ad6265SDimitry Andric 
133881ad6265SDimitry Andric   Type *ElemTy = getTypeByID(getContainedTypeID(ID, 0));
133981ad6265SDimitry Andric   if (!ElemTy)
134081ad6265SDimitry Andric     return nullptr;
134181ad6265SDimitry Andric 
134281ad6265SDimitry Andric   assert(cast<PointerType>(Ty)->isOpaqueOrPointeeTypeMatches(ElemTy) &&
134381ad6265SDimitry Andric          "Incorrect element type");
134481ad6265SDimitry Andric   return ElemTy;
134581ad6265SDimitry Andric }
134681ad6265SDimitry Andric 
134781ad6265SDimitry Andric unsigned BitcodeReader::getVirtualTypeID(Type *Ty,
134881ad6265SDimitry Andric                                          ArrayRef<unsigned> ChildTypeIDs) {
134981ad6265SDimitry Andric   unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0];
135081ad6265SDimitry Andric   auto CacheKey = std::make_pair(Ty, ChildTypeID);
135181ad6265SDimitry Andric   auto It = VirtualTypeIDs.find(CacheKey);
135281ad6265SDimitry Andric   if (It != VirtualTypeIDs.end()) {
135381ad6265SDimitry Andric     // The cmpxchg return value is the only place we need more than one
135481ad6265SDimitry Andric     // contained type ID, however the second one will always be the same (i1),
135581ad6265SDimitry Andric     // so we don't need to include it in the cache key. This asserts that the
135681ad6265SDimitry Andric     // contained types are indeed as expected and there are no collisions.
135781ad6265SDimitry Andric     assert((ChildTypeIDs.empty() ||
135881ad6265SDimitry Andric             ContainedTypeIDs[It->second] == ChildTypeIDs) &&
135981ad6265SDimitry Andric            "Incorrect cached contained type IDs");
136081ad6265SDimitry Andric     return It->second;
136181ad6265SDimitry Andric   }
136281ad6265SDimitry Andric 
136381ad6265SDimitry Andric #ifndef NDEBUG
136481ad6265SDimitry Andric   if (!Ty->isOpaquePointerTy()) {
136581ad6265SDimitry Andric     assert(Ty->getNumContainedTypes() == ChildTypeIDs.size() &&
136681ad6265SDimitry Andric            "Wrong number of contained types");
136781ad6265SDimitry Andric     for (auto Pair : zip(Ty->subtypes(), ChildTypeIDs)) {
136881ad6265SDimitry Andric       assert(std::get<0>(Pair) == getTypeByID(std::get<1>(Pair)) &&
136981ad6265SDimitry Andric              "Incorrect contained type ID");
137081ad6265SDimitry Andric     }
137181ad6265SDimitry Andric   }
137281ad6265SDimitry Andric #endif
137381ad6265SDimitry Andric 
137481ad6265SDimitry Andric   unsigned TypeID = TypeList.size();
137581ad6265SDimitry Andric   TypeList.push_back(Ty);
137681ad6265SDimitry Andric   if (!ChildTypeIDs.empty())
137781ad6265SDimitry Andric     append_range(ContainedTypeIDs[TypeID], ChildTypeIDs);
137881ad6265SDimitry Andric   VirtualTypeIDs.insert({CacheKey, TypeID});
137981ad6265SDimitry Andric   return TypeID;
138081ad6265SDimitry Andric }
138181ad6265SDimitry Andric 
138281ad6265SDimitry Andric static bool isConstExprSupported(uint8_t Opcode) {
138381ad6265SDimitry Andric   // These are not real constant expressions, always consider them supported.
138481ad6265SDimitry Andric   if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
138581ad6265SDimitry Andric     return true;
138681ad6265SDimitry Andric 
138781ad6265SDimitry Andric   return !ExpandConstantExprs;
138881ad6265SDimitry Andric }
138981ad6265SDimitry Andric 
139081ad6265SDimitry Andric Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID,
139181ad6265SDimitry Andric                                                   BasicBlock *InsertBB) {
139281ad6265SDimitry Andric   // Quickly handle the case where there is no BitcodeConstant to resolve.
139381ad6265SDimitry Andric   if (StartValID < ValueList.size() && ValueList[StartValID] &&
139481ad6265SDimitry Andric       !isa<BitcodeConstant>(ValueList[StartValID]))
139581ad6265SDimitry Andric     return ValueList[StartValID];
139681ad6265SDimitry Andric 
139781ad6265SDimitry Andric   SmallDenseMap<unsigned, Value *> MaterializedValues;
139881ad6265SDimitry Andric   SmallVector<unsigned> Worklist;
139981ad6265SDimitry Andric   Worklist.push_back(StartValID);
140081ad6265SDimitry Andric   while (!Worklist.empty()) {
140181ad6265SDimitry Andric     unsigned ValID = Worklist.back();
140281ad6265SDimitry Andric     if (MaterializedValues.count(ValID)) {
140381ad6265SDimitry Andric       // Duplicate expression that was already handled.
140481ad6265SDimitry Andric       Worklist.pop_back();
140581ad6265SDimitry Andric       continue;
140681ad6265SDimitry Andric     }
140781ad6265SDimitry Andric 
140881ad6265SDimitry Andric     if (ValID >= ValueList.size() || !ValueList[ValID])
140981ad6265SDimitry Andric       return error("Invalid value ID");
141081ad6265SDimitry Andric 
141181ad6265SDimitry Andric     Value *V = ValueList[ValID];
141281ad6265SDimitry Andric     auto *BC = dyn_cast<BitcodeConstant>(V);
141381ad6265SDimitry Andric     if (!BC) {
141481ad6265SDimitry Andric       MaterializedValues.insert({ValID, V});
141581ad6265SDimitry Andric       Worklist.pop_back();
141681ad6265SDimitry Andric       continue;
141781ad6265SDimitry Andric     }
141881ad6265SDimitry Andric 
141981ad6265SDimitry Andric     // Iterate in reverse, so values will get popped from the worklist in
142081ad6265SDimitry Andric     // expected order.
142181ad6265SDimitry Andric     SmallVector<Value *> Ops;
142281ad6265SDimitry Andric     for (unsigned OpID : reverse(BC->getOperandIDs())) {
142381ad6265SDimitry Andric       auto It = MaterializedValues.find(OpID);
142481ad6265SDimitry Andric       if (It != MaterializedValues.end())
142581ad6265SDimitry Andric         Ops.push_back(It->second);
142681ad6265SDimitry Andric       else
142781ad6265SDimitry Andric         Worklist.push_back(OpID);
142881ad6265SDimitry Andric     }
142981ad6265SDimitry Andric 
143081ad6265SDimitry Andric     // Some expressions have not been resolved yet, handle them first and then
143181ad6265SDimitry Andric     // revisit this one.
143281ad6265SDimitry Andric     if (Ops.size() != BC->getOperandIDs().size())
143381ad6265SDimitry Andric       continue;
143481ad6265SDimitry Andric     std::reverse(Ops.begin(), Ops.end());
143581ad6265SDimitry Andric 
143681ad6265SDimitry Andric     SmallVector<Constant *> ConstOps;
143781ad6265SDimitry Andric     for (Value *Op : Ops)
143881ad6265SDimitry Andric       if (auto *C = dyn_cast<Constant>(Op))
143981ad6265SDimitry Andric         ConstOps.push_back(C);
144081ad6265SDimitry Andric 
144181ad6265SDimitry Andric     // Materialize as constant expression if possible.
144281ad6265SDimitry Andric     if (isConstExprSupported(BC->Opcode) && ConstOps.size() == Ops.size()) {
144381ad6265SDimitry Andric       Constant *C;
144481ad6265SDimitry Andric       if (Instruction::isCast(BC->Opcode)) {
144581ad6265SDimitry Andric         C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType());
144681ad6265SDimitry Andric         if (!C)
144781ad6265SDimitry Andric           C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType());
144881ad6265SDimitry Andric       } else if (Instruction::isUnaryOp(BC->Opcode)) {
144981ad6265SDimitry Andric         C = ConstantExpr::get(BC->Opcode, ConstOps[0], BC->Flags);
145081ad6265SDimitry Andric       } else if (Instruction::isBinaryOp(BC->Opcode)) {
145181ad6265SDimitry Andric         C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags);
145281ad6265SDimitry Andric       } else {
145381ad6265SDimitry Andric         switch (BC->Opcode) {
145481ad6265SDimitry Andric         case BitcodeConstant::NoCFIOpcode: {
145581ad6265SDimitry Andric           auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
145681ad6265SDimitry Andric           if (!GV)
145781ad6265SDimitry Andric             return error("no_cfi operand must be GlobalValue");
145881ad6265SDimitry Andric           C = NoCFIValue::get(GV);
145981ad6265SDimitry Andric           break;
146081ad6265SDimitry Andric         }
146181ad6265SDimitry Andric         case BitcodeConstant::DSOLocalEquivalentOpcode: {
146281ad6265SDimitry Andric           auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
146381ad6265SDimitry Andric           if (!GV)
146481ad6265SDimitry Andric             return error("dso_local operand must be GlobalValue");
146581ad6265SDimitry Andric           C = DSOLocalEquivalent::get(GV);
146681ad6265SDimitry Andric           break;
146781ad6265SDimitry Andric         }
146881ad6265SDimitry Andric         case BitcodeConstant::BlockAddressOpcode: {
146981ad6265SDimitry Andric           Function *Fn = dyn_cast<Function>(ConstOps[0]);
147081ad6265SDimitry Andric           if (!Fn)
147181ad6265SDimitry Andric             return error("blockaddress operand must be a function");
147281ad6265SDimitry Andric 
147381ad6265SDimitry Andric           // If the function is already parsed we can insert the block address
147481ad6265SDimitry Andric           // right away.
147581ad6265SDimitry Andric           BasicBlock *BB;
147681ad6265SDimitry Andric           unsigned BBID = BC->Extra;
147781ad6265SDimitry Andric           if (!BBID)
147881ad6265SDimitry Andric             // Invalid reference to entry block.
147981ad6265SDimitry Andric             return error("Invalid ID");
148081ad6265SDimitry Andric           if (!Fn->empty()) {
148181ad6265SDimitry Andric             Function::iterator BBI = Fn->begin(), BBE = Fn->end();
148281ad6265SDimitry Andric             for (size_t I = 0, E = BBID; I != E; ++I) {
148381ad6265SDimitry Andric               if (BBI == BBE)
148481ad6265SDimitry Andric                 return error("Invalid ID");
148581ad6265SDimitry Andric               ++BBI;
148681ad6265SDimitry Andric             }
148781ad6265SDimitry Andric             BB = &*BBI;
148881ad6265SDimitry Andric           } else {
148981ad6265SDimitry Andric             // Otherwise insert a placeholder and remember it so it can be
149081ad6265SDimitry Andric             // inserted when the function is parsed.
149181ad6265SDimitry Andric             auto &FwdBBs = BasicBlockFwdRefs[Fn];
149281ad6265SDimitry Andric             if (FwdBBs.empty())
149381ad6265SDimitry Andric               BasicBlockFwdRefQueue.push_back(Fn);
149481ad6265SDimitry Andric             if (FwdBBs.size() < BBID + 1)
149581ad6265SDimitry Andric               FwdBBs.resize(BBID + 1);
149681ad6265SDimitry Andric             if (!FwdBBs[BBID])
149781ad6265SDimitry Andric               FwdBBs[BBID] = BasicBlock::Create(Context);
149881ad6265SDimitry Andric             BB = FwdBBs[BBID];
149981ad6265SDimitry Andric           }
150081ad6265SDimitry Andric           C = BlockAddress::get(Fn, BB);
150181ad6265SDimitry Andric           break;
150281ad6265SDimitry Andric         }
150381ad6265SDimitry Andric         case BitcodeConstant::ConstantStructOpcode:
150481ad6265SDimitry Andric           C = ConstantStruct::get(cast<StructType>(BC->getType()), ConstOps);
150581ad6265SDimitry Andric           break;
150681ad6265SDimitry Andric         case BitcodeConstant::ConstantArrayOpcode:
150781ad6265SDimitry Andric           C = ConstantArray::get(cast<ArrayType>(BC->getType()), ConstOps);
150881ad6265SDimitry Andric           break;
150981ad6265SDimitry Andric         case BitcodeConstant::ConstantVectorOpcode:
151081ad6265SDimitry Andric           C = ConstantVector::get(ConstOps);
151181ad6265SDimitry Andric           break;
151281ad6265SDimitry Andric         case Instruction::ICmp:
151381ad6265SDimitry Andric         case Instruction::FCmp:
151481ad6265SDimitry Andric           C = ConstantExpr::getCompare(BC->Flags, ConstOps[0], ConstOps[1]);
151581ad6265SDimitry Andric           break;
151681ad6265SDimitry Andric         case Instruction::GetElementPtr:
151781ad6265SDimitry Andric           C = ConstantExpr::getGetElementPtr(
151881ad6265SDimitry Andric               BC->SrcElemTy, ConstOps[0], makeArrayRef(ConstOps).drop_front(),
151981ad6265SDimitry Andric               BC->Flags, BC->getInRangeIndex());
152081ad6265SDimitry Andric           break;
152181ad6265SDimitry Andric         case Instruction::Select:
152281ad6265SDimitry Andric           C = ConstantExpr::getSelect(ConstOps[0], ConstOps[1], ConstOps[2]);
152381ad6265SDimitry Andric           break;
152481ad6265SDimitry Andric         case Instruction::ExtractElement:
152581ad6265SDimitry Andric           C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]);
152681ad6265SDimitry Andric           break;
152781ad6265SDimitry Andric         case Instruction::InsertElement:
152881ad6265SDimitry Andric           C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1],
152981ad6265SDimitry Andric                                              ConstOps[2]);
153081ad6265SDimitry Andric           break;
153181ad6265SDimitry Andric         case Instruction::ShuffleVector: {
153281ad6265SDimitry Andric           SmallVector<int, 16> Mask;
153381ad6265SDimitry Andric           ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask);
153481ad6265SDimitry Andric           C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask);
153581ad6265SDimitry Andric           break;
153681ad6265SDimitry Andric         }
153781ad6265SDimitry Andric         default:
153881ad6265SDimitry Andric           llvm_unreachable("Unhandled bitcode constant");
153981ad6265SDimitry Andric         }
154081ad6265SDimitry Andric       }
154181ad6265SDimitry Andric 
154281ad6265SDimitry Andric       // Cache resolved constant.
154381ad6265SDimitry Andric       ValueList.replaceValueWithoutRAUW(ValID, C);
154481ad6265SDimitry Andric       MaterializedValues.insert({ValID, C});
154581ad6265SDimitry Andric       Worklist.pop_back();
154681ad6265SDimitry Andric       continue;
154781ad6265SDimitry Andric     }
154881ad6265SDimitry Andric 
154981ad6265SDimitry Andric     if (!InsertBB)
155081ad6265SDimitry Andric       return error(Twine("Value referenced by initializer is an unsupported "
155181ad6265SDimitry Andric                          "constant expression of type ") +
155281ad6265SDimitry Andric                    BC->getOpcodeName());
155381ad6265SDimitry Andric 
155481ad6265SDimitry Andric     // Materialize as instructions if necessary.
155581ad6265SDimitry Andric     Instruction *I;
155681ad6265SDimitry Andric     if (Instruction::isCast(BC->Opcode)) {
155781ad6265SDimitry Andric       I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0],
155881ad6265SDimitry Andric                            BC->getType(), "constexpr", InsertBB);
155981ad6265SDimitry Andric     } else if (Instruction::isUnaryOp(BC->Opcode)) {
156081ad6265SDimitry Andric       I = UnaryOperator::Create((Instruction::UnaryOps)BC->Opcode, Ops[0],
156181ad6265SDimitry Andric                                 "constexpr", InsertBB);
156281ad6265SDimitry Andric     } else if (Instruction::isBinaryOp(BC->Opcode)) {
156381ad6265SDimitry Andric       I = BinaryOperator::Create((Instruction::BinaryOps)BC->Opcode, Ops[0],
156481ad6265SDimitry Andric                                  Ops[1], "constexpr", InsertBB);
156581ad6265SDimitry Andric       if (isa<OverflowingBinaryOperator>(I)) {
156681ad6265SDimitry Andric         if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap)
156781ad6265SDimitry Andric           I->setHasNoSignedWrap();
156881ad6265SDimitry Andric         if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap)
156981ad6265SDimitry Andric           I->setHasNoUnsignedWrap();
157081ad6265SDimitry Andric       }
157181ad6265SDimitry Andric       if (isa<PossiblyExactOperator>(I) &&
157281ad6265SDimitry Andric           (BC->Flags & PossiblyExactOperator::IsExact))
157381ad6265SDimitry Andric         I->setIsExact();
157481ad6265SDimitry Andric     } else {
157581ad6265SDimitry Andric       switch (BC->Opcode) {
157681ad6265SDimitry Andric       case BitcodeConstant::ConstantStructOpcode:
157781ad6265SDimitry Andric       case BitcodeConstant::ConstantArrayOpcode:
157881ad6265SDimitry Andric       case BitcodeConstant::ConstantVectorOpcode: {
157981ad6265SDimitry Andric         Type *IdxTy = Type::getInt32Ty(BC->getContext());
158081ad6265SDimitry Andric         Value *V = PoisonValue::get(BC->getType());
158181ad6265SDimitry Andric         for (auto Pair : enumerate(Ops)) {
158281ad6265SDimitry Andric           Value *Idx = ConstantInt::get(IdxTy, Pair.index());
158381ad6265SDimitry Andric           V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins",
158481ad6265SDimitry Andric                                         InsertBB);
158581ad6265SDimitry Andric         }
158681ad6265SDimitry Andric         I = cast<Instruction>(V);
158781ad6265SDimitry Andric         break;
158881ad6265SDimitry Andric       }
158981ad6265SDimitry Andric       case Instruction::ICmp:
159081ad6265SDimitry Andric       case Instruction::FCmp:
159181ad6265SDimitry Andric         I = CmpInst::Create((Instruction::OtherOps)BC->Opcode,
159281ad6265SDimitry Andric                             (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1],
159381ad6265SDimitry Andric                             "constexpr", InsertBB);
159481ad6265SDimitry Andric         break;
159581ad6265SDimitry Andric       case Instruction::GetElementPtr:
159681ad6265SDimitry Andric         I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0],
159781ad6265SDimitry Andric                                       makeArrayRef(Ops).drop_front(),
159881ad6265SDimitry Andric                                       "constexpr", InsertBB);
159981ad6265SDimitry Andric         if (BC->Flags)
160081ad6265SDimitry Andric           cast<GetElementPtrInst>(I)->setIsInBounds();
160181ad6265SDimitry Andric         break;
160281ad6265SDimitry Andric       case Instruction::Select:
160381ad6265SDimitry Andric         I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB);
160481ad6265SDimitry Andric         break;
160581ad6265SDimitry Andric       case Instruction::ExtractElement:
160681ad6265SDimitry Andric         I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB);
160781ad6265SDimitry Andric         break;
160881ad6265SDimitry Andric       case Instruction::InsertElement:
160981ad6265SDimitry Andric         I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr",
161081ad6265SDimitry Andric                                       InsertBB);
161181ad6265SDimitry Andric         break;
161281ad6265SDimitry Andric       case Instruction::ShuffleVector:
161381ad6265SDimitry Andric         I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr",
161481ad6265SDimitry Andric                                   InsertBB);
161581ad6265SDimitry Andric         break;
161681ad6265SDimitry Andric       default:
161781ad6265SDimitry Andric         llvm_unreachable("Unhandled bitcode constant");
161881ad6265SDimitry Andric       }
161981ad6265SDimitry Andric     }
162081ad6265SDimitry Andric 
162181ad6265SDimitry Andric     MaterializedValues.insert({ValID, I});
162281ad6265SDimitry Andric     Worklist.pop_back();
162381ad6265SDimitry Andric   }
162481ad6265SDimitry Andric 
162581ad6265SDimitry Andric   return MaterializedValues[StartValID];
162681ad6265SDimitry Andric }
162781ad6265SDimitry Andric 
162881ad6265SDimitry Andric Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) {
162981ad6265SDimitry Andric   Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr);
163081ad6265SDimitry Andric   if (!MaybeV)
163181ad6265SDimitry Andric     return MaybeV.takeError();
163281ad6265SDimitry Andric 
163381ad6265SDimitry Andric   // Result must be Constant if InsertBB is nullptr.
163481ad6265SDimitry Andric   return cast<Constant>(MaybeV.get());
163581ad6265SDimitry Andric }
163681ad6265SDimitry Andric 
1637*0b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1638*0b57cec5SDimitry Andric                                                       StringRef Name) {
1639*0b57cec5SDimitry Andric   auto *Ret = StructType::create(Context, Name);
1640*0b57cec5SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
1641*0b57cec5SDimitry Andric   return Ret;
1642*0b57cec5SDimitry Andric }
1643*0b57cec5SDimitry Andric 
1644*0b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1645*0b57cec5SDimitry Andric   auto *Ret = StructType::create(Context);
1646*0b57cec5SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
1647*0b57cec5SDimitry Andric   return Ret;
1648*0b57cec5SDimitry Andric }
1649*0b57cec5SDimitry Andric 
1650*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1651*0b57cec5SDimitry Andric //  Functions for parsing blocks from the bitcode file
1652*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1653*0b57cec5SDimitry Andric 
1654*0b57cec5SDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1655*0b57cec5SDimitry Andric   switch (Val) {
1656*0b57cec5SDimitry Andric   case Attribute::EndAttrKinds:
16575ffd83dbSDimitry Andric   case Attribute::EmptyKey:
16585ffd83dbSDimitry Andric   case Attribute::TombstoneKey:
1659*0b57cec5SDimitry Andric     llvm_unreachable("Synthetic enumerators which should never get here");
1660*0b57cec5SDimitry Andric 
1661*0b57cec5SDimitry Andric   case Attribute::None:            return 0;
1662*0b57cec5SDimitry Andric   case Attribute::ZExt:            return 1 << 0;
1663*0b57cec5SDimitry Andric   case Attribute::SExt:            return 1 << 1;
1664*0b57cec5SDimitry Andric   case Attribute::NoReturn:        return 1 << 2;
1665*0b57cec5SDimitry Andric   case Attribute::InReg:           return 1 << 3;
1666*0b57cec5SDimitry Andric   case Attribute::StructRet:       return 1 << 4;
1667*0b57cec5SDimitry Andric   case Attribute::NoUnwind:        return 1 << 5;
1668*0b57cec5SDimitry Andric   case Attribute::NoAlias:         return 1 << 6;
1669*0b57cec5SDimitry Andric   case Attribute::ByVal:           return 1 << 7;
1670*0b57cec5SDimitry Andric   case Attribute::Nest:            return 1 << 8;
1671*0b57cec5SDimitry Andric   case Attribute::ReadNone:        return 1 << 9;
1672*0b57cec5SDimitry Andric   case Attribute::ReadOnly:        return 1 << 10;
1673*0b57cec5SDimitry Andric   case Attribute::NoInline:        return 1 << 11;
1674*0b57cec5SDimitry Andric   case Attribute::AlwaysInline:    return 1 << 12;
1675*0b57cec5SDimitry Andric   case Attribute::OptimizeForSize: return 1 << 13;
1676*0b57cec5SDimitry Andric   case Attribute::StackProtect:    return 1 << 14;
1677*0b57cec5SDimitry Andric   case Attribute::StackProtectReq: return 1 << 15;
1678*0b57cec5SDimitry Andric   case Attribute::Alignment:       return 31 << 16;
1679*0b57cec5SDimitry Andric   case Attribute::NoCapture:       return 1 << 21;
1680*0b57cec5SDimitry Andric   case Attribute::NoRedZone:       return 1 << 22;
1681*0b57cec5SDimitry Andric   case Attribute::NoImplicitFloat: return 1 << 23;
1682*0b57cec5SDimitry Andric   case Attribute::Naked:           return 1 << 24;
1683*0b57cec5SDimitry Andric   case Attribute::InlineHint:      return 1 << 25;
1684*0b57cec5SDimitry Andric   case Attribute::StackAlignment:  return 7 << 26;
1685*0b57cec5SDimitry Andric   case Attribute::ReturnsTwice:    return 1 << 29;
1686*0b57cec5SDimitry Andric   case Attribute::UWTable:         return 1 << 30;
1687*0b57cec5SDimitry Andric   case Attribute::NonLazyBind:     return 1U << 31;
1688*0b57cec5SDimitry Andric   case Attribute::SanitizeAddress: return 1ULL << 32;
1689*0b57cec5SDimitry Andric   case Attribute::MinSize:         return 1ULL << 33;
1690*0b57cec5SDimitry Andric   case Attribute::NoDuplicate:     return 1ULL << 34;
1691*0b57cec5SDimitry Andric   case Attribute::StackProtectStrong: return 1ULL << 35;
1692*0b57cec5SDimitry Andric   case Attribute::SanitizeThread:  return 1ULL << 36;
1693*0b57cec5SDimitry Andric   case Attribute::SanitizeMemory:  return 1ULL << 37;
1694*0b57cec5SDimitry Andric   case Attribute::NoBuiltin:       return 1ULL << 38;
1695*0b57cec5SDimitry Andric   case Attribute::Returned:        return 1ULL << 39;
1696*0b57cec5SDimitry Andric   case Attribute::Cold:            return 1ULL << 40;
1697*0b57cec5SDimitry Andric   case Attribute::Builtin:         return 1ULL << 41;
1698*0b57cec5SDimitry Andric   case Attribute::OptimizeNone:    return 1ULL << 42;
1699*0b57cec5SDimitry Andric   case Attribute::InAlloca:        return 1ULL << 43;
1700*0b57cec5SDimitry Andric   case Attribute::NonNull:         return 1ULL << 44;
1701*0b57cec5SDimitry Andric   case Attribute::JumpTable:       return 1ULL << 45;
1702*0b57cec5SDimitry Andric   case Attribute::Convergent:      return 1ULL << 46;
1703*0b57cec5SDimitry Andric   case Attribute::SafeStack:       return 1ULL << 47;
1704*0b57cec5SDimitry Andric   case Attribute::NoRecurse:       return 1ULL << 48;
1705*0b57cec5SDimitry Andric   case Attribute::InaccessibleMemOnly:         return 1ULL << 49;
1706*0b57cec5SDimitry Andric   case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1707*0b57cec5SDimitry Andric   case Attribute::SwiftSelf:       return 1ULL << 51;
1708*0b57cec5SDimitry Andric   case Attribute::SwiftError:      return 1ULL << 52;
1709*0b57cec5SDimitry Andric   case Attribute::WriteOnly:       return 1ULL << 53;
1710*0b57cec5SDimitry Andric   case Attribute::Speculatable:    return 1ULL << 54;
1711*0b57cec5SDimitry Andric   case Attribute::StrictFP:        return 1ULL << 55;
1712*0b57cec5SDimitry Andric   case Attribute::SanitizeHWAddress: return 1ULL << 56;
1713*0b57cec5SDimitry Andric   case Attribute::NoCfCheck:       return 1ULL << 57;
1714*0b57cec5SDimitry Andric   case Attribute::OptForFuzzing:   return 1ULL << 58;
1715*0b57cec5SDimitry Andric   case Attribute::ShadowCallStack: return 1ULL << 59;
1716*0b57cec5SDimitry Andric   case Attribute::SpeculativeLoadHardening:
1717*0b57cec5SDimitry Andric     return 1ULL << 60;
1718*0b57cec5SDimitry Andric   case Attribute::ImmArg:
1719*0b57cec5SDimitry Andric     return 1ULL << 61;
1720*0b57cec5SDimitry Andric   case Attribute::WillReturn:
1721*0b57cec5SDimitry Andric     return 1ULL << 62;
1722*0b57cec5SDimitry Andric   case Attribute::NoFree:
1723*0b57cec5SDimitry Andric     return 1ULL << 63;
17245ffd83dbSDimitry Andric   default:
17255ffd83dbSDimitry Andric     // Other attributes are not supported in the raw format,
17265ffd83dbSDimitry Andric     // as we ran out of space.
17275ffd83dbSDimitry Andric     return 0;
1728*0b57cec5SDimitry Andric   }
1729*0b57cec5SDimitry Andric   llvm_unreachable("Unsupported attribute type");
1730*0b57cec5SDimitry Andric }
1731*0b57cec5SDimitry Andric 
1732*0b57cec5SDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1733*0b57cec5SDimitry Andric   if (!Val) return;
1734*0b57cec5SDimitry Andric 
1735*0b57cec5SDimitry Andric   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1736*0b57cec5SDimitry Andric        I = Attribute::AttrKind(I + 1)) {
1737*0b57cec5SDimitry Andric     if (uint64_t A = (Val & getRawAttributeMask(I))) {
1738*0b57cec5SDimitry Andric       if (I == Attribute::Alignment)
1739*0b57cec5SDimitry Andric         B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1740*0b57cec5SDimitry Andric       else if (I == Attribute::StackAlignment)
1741*0b57cec5SDimitry Andric         B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1742fe6060f1SDimitry Andric       else if (Attribute::isTypeAttrKind(I))
1743fe6060f1SDimitry Andric         B.addTypeAttr(I, nullptr); // Type will be auto-upgraded.
1744*0b57cec5SDimitry Andric       else
1745*0b57cec5SDimitry Andric         B.addAttribute(I);
1746*0b57cec5SDimitry Andric     }
1747*0b57cec5SDimitry Andric   }
1748*0b57cec5SDimitry Andric }
1749*0b57cec5SDimitry Andric 
1750*0b57cec5SDimitry Andric /// This fills an AttrBuilder object with the LLVM attributes that have
1751*0b57cec5SDimitry Andric /// been decoded from the given integer. This function must stay in sync with
1752*0b57cec5SDimitry Andric /// 'encodeLLVMAttributesForBitcode'.
1753*0b57cec5SDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1754*0b57cec5SDimitry Andric                                            uint64_t EncodedAttrs) {
1755*0b57cec5SDimitry Andric   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
1756*0b57cec5SDimitry Andric   // the bits above 31 down by 11 bits.
1757*0b57cec5SDimitry Andric   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1758*0b57cec5SDimitry Andric   assert((!Alignment || isPowerOf2_32(Alignment)) &&
1759*0b57cec5SDimitry Andric          "Alignment must be a power of two.");
1760*0b57cec5SDimitry Andric 
1761*0b57cec5SDimitry Andric   if (Alignment)
1762*0b57cec5SDimitry Andric     B.addAlignmentAttr(Alignment);
1763*0b57cec5SDimitry Andric   addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1764*0b57cec5SDimitry Andric                           (EncodedAttrs & 0xffff));
1765*0b57cec5SDimitry Andric }
1766*0b57cec5SDimitry Andric 
1767*0b57cec5SDimitry Andric Error BitcodeReader::parseAttributeBlock() {
1768*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1769*0b57cec5SDimitry Andric     return Err;
1770*0b57cec5SDimitry Andric 
1771*0b57cec5SDimitry Andric   if (!MAttributes.empty())
1772*0b57cec5SDimitry Andric     return error("Invalid multiple blocks");
1773*0b57cec5SDimitry Andric 
1774*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
1775*0b57cec5SDimitry Andric 
1776*0b57cec5SDimitry Andric   SmallVector<AttributeList, 8> Attrs;
1777*0b57cec5SDimitry Andric 
1778*0b57cec5SDimitry Andric   // Read all the records.
1779*0b57cec5SDimitry Andric   while (true) {
1780*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1781*0b57cec5SDimitry Andric     if (!MaybeEntry)
1782*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
1783*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
1784*0b57cec5SDimitry Andric 
1785*0b57cec5SDimitry Andric     switch (Entry.Kind) {
1786*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1787*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
1788*0b57cec5SDimitry Andric       return error("Malformed block");
1789*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
1790*0b57cec5SDimitry Andric       return Error::success();
1791*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
1792*0b57cec5SDimitry Andric       // The interesting case.
1793*0b57cec5SDimitry Andric       break;
1794*0b57cec5SDimitry Andric     }
1795*0b57cec5SDimitry Andric 
1796*0b57cec5SDimitry Andric     // Read a record.
1797*0b57cec5SDimitry Andric     Record.clear();
1798*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1799*0b57cec5SDimitry Andric     if (!MaybeRecord)
1800*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
1801*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
1802*0b57cec5SDimitry Andric     default:  // Default behavior: ignore.
1803*0b57cec5SDimitry Andric       break;
1804*0b57cec5SDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
18055ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
1806*0b57cec5SDimitry Andric       if (Record.size() & 1)
180781ad6265SDimitry Andric         return error("Invalid parameter attribute record");
1808*0b57cec5SDimitry Andric 
1809*0b57cec5SDimitry Andric       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
181004eeddc0SDimitry Andric         AttrBuilder B(Context);
1811*0b57cec5SDimitry Andric         decodeLLVMAttributesForBitcode(B, Record[i+1]);
1812*0b57cec5SDimitry Andric         Attrs.push_back(AttributeList::get(Context, Record[i], B));
1813*0b57cec5SDimitry Andric       }
1814*0b57cec5SDimitry Andric 
1815*0b57cec5SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
1816*0b57cec5SDimitry Andric       Attrs.clear();
1817*0b57cec5SDimitry Andric       break;
1818*0b57cec5SDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1819*0b57cec5SDimitry Andric       for (unsigned i = 0, e = Record.size(); i != e; ++i)
1820*0b57cec5SDimitry Andric         Attrs.push_back(MAttributeGroups[Record[i]]);
1821*0b57cec5SDimitry Andric 
1822*0b57cec5SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
1823*0b57cec5SDimitry Andric       Attrs.clear();
1824*0b57cec5SDimitry Andric       break;
1825*0b57cec5SDimitry Andric     }
1826*0b57cec5SDimitry Andric   }
1827*0b57cec5SDimitry Andric }
1828*0b57cec5SDimitry Andric 
1829*0b57cec5SDimitry Andric // Returns Attribute::None on unrecognized codes.
1830*0b57cec5SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1831*0b57cec5SDimitry Andric   switch (Code) {
1832*0b57cec5SDimitry Andric   default:
1833*0b57cec5SDimitry Andric     return Attribute::None;
1834*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALIGNMENT:
1835*0b57cec5SDimitry Andric     return Attribute::Alignment;
1836*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALWAYS_INLINE:
1837*0b57cec5SDimitry Andric     return Attribute::AlwaysInline;
1838*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_ARGMEMONLY:
1839*0b57cec5SDimitry Andric     return Attribute::ArgMemOnly;
1840*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_BUILTIN:
1841*0b57cec5SDimitry Andric     return Attribute::Builtin;
1842*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_BY_VAL:
1843*0b57cec5SDimitry Andric     return Attribute::ByVal;
1844*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_IN_ALLOCA:
1845*0b57cec5SDimitry Andric     return Attribute::InAlloca;
1846*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_COLD:
1847*0b57cec5SDimitry Andric     return Attribute::Cold;
1848*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_CONVERGENT:
1849*0b57cec5SDimitry Andric     return Attribute::Convergent;
1850349cc55cSDimitry Andric   case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION:
1851349cc55cSDimitry Andric     return Attribute::DisableSanitizerInstrumentation;
1852fe6060f1SDimitry Andric   case bitc::ATTR_KIND_ELEMENTTYPE:
1853fe6060f1SDimitry Andric     return Attribute::ElementType;
1854*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1855*0b57cec5SDimitry Andric     return Attribute::InaccessibleMemOnly;
1856*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1857*0b57cec5SDimitry Andric     return Attribute::InaccessibleMemOrArgMemOnly;
1858*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_INLINE_HINT:
1859*0b57cec5SDimitry Andric     return Attribute::InlineHint;
1860*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_IN_REG:
1861*0b57cec5SDimitry Andric     return Attribute::InReg;
1862*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_JUMP_TABLE:
1863*0b57cec5SDimitry Andric     return Attribute::JumpTable;
1864*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_MIN_SIZE:
1865*0b57cec5SDimitry Andric     return Attribute::MinSize;
1866*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NAKED:
1867*0b57cec5SDimitry Andric     return Attribute::Naked;
1868*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NEST:
1869*0b57cec5SDimitry Andric     return Attribute::Nest;
1870*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_ALIAS:
1871*0b57cec5SDimitry Andric     return Attribute::NoAlias;
1872*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_BUILTIN:
1873*0b57cec5SDimitry Andric     return Attribute::NoBuiltin;
1874e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_NO_CALLBACK:
1875e8d8bef9SDimitry Andric     return Attribute::NoCallback;
1876*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_CAPTURE:
1877*0b57cec5SDimitry Andric     return Attribute::NoCapture;
1878*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_DUPLICATE:
1879*0b57cec5SDimitry Andric     return Attribute::NoDuplicate;
1880*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOFREE:
1881*0b57cec5SDimitry Andric     return Attribute::NoFree;
1882*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1883*0b57cec5SDimitry Andric     return Attribute::NoImplicitFloat;
1884*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_INLINE:
1885*0b57cec5SDimitry Andric     return Attribute::NoInline;
1886*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RECURSE:
1887*0b57cec5SDimitry Andric     return Attribute::NoRecurse;
18885ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NO_MERGE:
18895ffd83dbSDimitry Andric     return Attribute::NoMerge;
1890*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NON_LAZY_BIND:
1891*0b57cec5SDimitry Andric     return Attribute::NonLazyBind;
1892*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NON_NULL:
1893*0b57cec5SDimitry Andric     return Attribute::NonNull;
1894*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE:
1895*0b57cec5SDimitry Andric     return Attribute::Dereferenceable;
1896*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1897*0b57cec5SDimitry Andric     return Attribute::DereferenceableOrNull;
189881ad6265SDimitry Andric   case bitc::ATTR_KIND_ALLOC_ALIGN:
189981ad6265SDimitry Andric     return Attribute::AllocAlign;
190081ad6265SDimitry Andric   case bitc::ATTR_KIND_ALLOC_KIND:
190181ad6265SDimitry Andric     return Attribute::AllocKind;
1902*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALLOC_SIZE:
1903*0b57cec5SDimitry Andric     return Attribute::AllocSize;
190481ad6265SDimitry Andric   case bitc::ATTR_KIND_ALLOCATED_POINTER:
190581ad6265SDimitry Andric     return Attribute::AllocatedPointer;
1906*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RED_ZONE:
1907*0b57cec5SDimitry Andric     return Attribute::NoRedZone;
1908*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RETURN:
1909*0b57cec5SDimitry Andric     return Attribute::NoReturn;
1910*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOSYNC:
1911*0b57cec5SDimitry Andric     return Attribute::NoSync;
1912*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOCF_CHECK:
1913*0b57cec5SDimitry Andric     return Attribute::NoCfCheck;
1914fe6060f1SDimitry Andric   case bitc::ATTR_KIND_NO_PROFILE:
1915fe6060f1SDimitry Andric     return Attribute::NoProfile;
1916*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_UNWIND:
1917*0b57cec5SDimitry Andric     return Attribute::NoUnwind;
191881ad6265SDimitry Andric   case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS:
191981ad6265SDimitry Andric     return Attribute::NoSanitizeBounds;
1920fe6060f1SDimitry Andric   case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
1921fe6060f1SDimitry Andric     return Attribute::NoSanitizeCoverage;
19225ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
19235ffd83dbSDimitry Andric     return Attribute::NullPointerIsValid;
1924*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPT_FOR_FUZZING:
1925*0b57cec5SDimitry Andric     return Attribute::OptForFuzzing;
1926*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1927*0b57cec5SDimitry Andric     return Attribute::OptimizeForSize;
1928*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_NONE:
1929*0b57cec5SDimitry Andric     return Attribute::OptimizeNone;
1930*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_READ_NONE:
1931*0b57cec5SDimitry Andric     return Attribute::ReadNone;
1932*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_READ_ONLY:
1933*0b57cec5SDimitry Andric     return Attribute::ReadOnly;
1934*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_RETURNED:
1935*0b57cec5SDimitry Andric     return Attribute::Returned;
1936*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_RETURNS_TWICE:
1937*0b57cec5SDimitry Andric     return Attribute::ReturnsTwice;
1938*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_S_EXT:
1939*0b57cec5SDimitry Andric     return Attribute::SExt;
1940*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SPECULATABLE:
1941*0b57cec5SDimitry Andric     return Attribute::Speculatable;
1942*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_ALIGNMENT:
1943*0b57cec5SDimitry Andric     return Attribute::StackAlignment;
1944*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT:
1945*0b57cec5SDimitry Andric     return Attribute::StackProtect;
1946*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1947*0b57cec5SDimitry Andric     return Attribute::StackProtectReq;
1948*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1949*0b57cec5SDimitry Andric     return Attribute::StackProtectStrong;
1950*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SAFESTACK:
1951*0b57cec5SDimitry Andric     return Attribute::SafeStack;
1952*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SHADOWCALLSTACK:
1953*0b57cec5SDimitry Andric     return Attribute::ShadowCallStack;
1954*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STRICT_FP:
1955*0b57cec5SDimitry Andric     return Attribute::StrictFP;
1956*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_STRUCT_RET:
1957*0b57cec5SDimitry Andric     return Attribute::StructRet;
1958*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1959*0b57cec5SDimitry Andric     return Attribute::SanitizeAddress;
1960*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
1961*0b57cec5SDimitry Andric     return Attribute::SanitizeHWAddress;
1962*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_THREAD:
1963*0b57cec5SDimitry Andric     return Attribute::SanitizeThread;
1964*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMORY:
1965*0b57cec5SDimitry Andric     return Attribute::SanitizeMemory;
1966*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
1967*0b57cec5SDimitry Andric     return Attribute::SpeculativeLoadHardening;
1968*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ERROR:
1969*0b57cec5SDimitry Andric     return Attribute::SwiftError;
1970*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SWIFT_SELF:
1971*0b57cec5SDimitry Andric     return Attribute::SwiftSelf;
1972fe6060f1SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ASYNC:
1973fe6060f1SDimitry Andric     return Attribute::SwiftAsync;
1974*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_UW_TABLE:
1975*0b57cec5SDimitry Andric     return Attribute::UWTable;
1976fe6060f1SDimitry Andric   case bitc::ATTR_KIND_VSCALE_RANGE:
1977fe6060f1SDimitry Andric     return Attribute::VScaleRange;
1978*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_WILLRETURN:
1979*0b57cec5SDimitry Andric     return Attribute::WillReturn;
1980*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_WRITEONLY:
1981*0b57cec5SDimitry Andric     return Attribute::WriteOnly;
1982*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_Z_EXT:
1983*0b57cec5SDimitry Andric     return Attribute::ZExt;
1984*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_IMMARG:
1985*0b57cec5SDimitry Andric     return Attribute::ImmArg;
1986*0b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMTAG:
1987*0b57cec5SDimitry Andric     return Attribute::SanitizeMemTag;
19885ffd83dbSDimitry Andric   case bitc::ATTR_KIND_PREALLOCATED:
19895ffd83dbSDimitry Andric     return Attribute::Preallocated;
19905ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NOUNDEF:
19915ffd83dbSDimitry Andric     return Attribute::NoUndef;
1992e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_BYREF:
1993e8d8bef9SDimitry Andric     return Attribute::ByRef;
1994e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_MUSTPROGRESS:
1995e8d8bef9SDimitry Andric     return Attribute::MustProgress;
1996e8d8bef9SDimitry Andric   case bitc::ATTR_KIND_HOT:
1997e8d8bef9SDimitry Andric     return Attribute::Hot;
199881ad6265SDimitry Andric   case bitc::ATTR_KIND_PRESPLIT_COROUTINE:
199981ad6265SDimitry Andric     return Attribute::PresplitCoroutine;
2000*0b57cec5SDimitry Andric   }
2001*0b57cec5SDimitry Andric }
2002*0b57cec5SDimitry Andric 
2003*0b57cec5SDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
20048bcb0991SDimitry Andric                                          MaybeAlign &Alignment) {
2005*0b57cec5SDimitry Andric   // Note: Alignment in bitcode files is incremented by 1, so that zero
2006*0b57cec5SDimitry Andric   // can be used for default alignment.
2007*0b57cec5SDimitry Andric   if (Exponent > Value::MaxAlignmentExponent + 1)
2008*0b57cec5SDimitry Andric     return error("Invalid alignment value");
20098bcb0991SDimitry Andric   Alignment = decodeMaybeAlign(Exponent);
2010*0b57cec5SDimitry Andric   return Error::success();
2011*0b57cec5SDimitry Andric }
2012*0b57cec5SDimitry Andric 
2013*0b57cec5SDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2014*0b57cec5SDimitry Andric   *Kind = getAttrFromCode(Code);
2015*0b57cec5SDimitry Andric   if (*Kind == Attribute::None)
2016*0b57cec5SDimitry Andric     return error("Unknown attribute kind (" + Twine(Code) + ")");
2017*0b57cec5SDimitry Andric   return Error::success();
2018*0b57cec5SDimitry Andric }
2019*0b57cec5SDimitry Andric 
2020*0b57cec5SDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() {
2021*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
2022*0b57cec5SDimitry Andric     return Err;
2023*0b57cec5SDimitry Andric 
2024*0b57cec5SDimitry Andric   if (!MAttributeGroups.empty())
2025*0b57cec5SDimitry Andric     return error("Invalid multiple blocks");
2026*0b57cec5SDimitry Andric 
2027*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2028*0b57cec5SDimitry Andric 
2029*0b57cec5SDimitry Andric   // Read all the records.
2030*0b57cec5SDimitry Andric   while (true) {
2031*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2032*0b57cec5SDimitry Andric     if (!MaybeEntry)
2033*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
2034*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2035*0b57cec5SDimitry Andric 
2036*0b57cec5SDimitry Andric     switch (Entry.Kind) {
2037*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2038*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
2039*0b57cec5SDimitry Andric       return error("Malformed block");
2040*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2041*0b57cec5SDimitry Andric       return Error::success();
2042*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
2043*0b57cec5SDimitry Andric       // The interesting case.
2044*0b57cec5SDimitry Andric       break;
2045*0b57cec5SDimitry Andric     }
2046*0b57cec5SDimitry Andric 
2047*0b57cec5SDimitry Andric     // Read a record.
2048*0b57cec5SDimitry Andric     Record.clear();
2049*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2050*0b57cec5SDimitry Andric     if (!MaybeRecord)
2051*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
2052*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
2053*0b57cec5SDimitry Andric     default:  // Default behavior: ignore.
2054*0b57cec5SDimitry Andric       break;
2055*0b57cec5SDimitry Andric     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
2056*0b57cec5SDimitry Andric       if (Record.size() < 3)
205781ad6265SDimitry Andric         return error("Invalid grp record");
2058*0b57cec5SDimitry Andric 
2059*0b57cec5SDimitry Andric       uint64_t GrpID = Record[0];
2060*0b57cec5SDimitry Andric       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
2061*0b57cec5SDimitry Andric 
206204eeddc0SDimitry Andric       AttrBuilder B(Context);
2063*0b57cec5SDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2064*0b57cec5SDimitry Andric         if (Record[i] == 0) {        // Enum attribute
2065*0b57cec5SDimitry Andric           Attribute::AttrKind Kind;
2066*0b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
2067*0b57cec5SDimitry Andric             return Err;
2068*0b57cec5SDimitry Andric 
2069*0b57cec5SDimitry Andric           // Upgrade old-style byval attribute to one with a type, even if it's
2070*0b57cec5SDimitry Andric           // nullptr. We will have to insert the real type when we associate
2071*0b57cec5SDimitry Andric           // this AttributeList with a function.
2072*0b57cec5SDimitry Andric           if (Kind == Attribute::ByVal)
2073*0b57cec5SDimitry Andric             B.addByValAttr(nullptr);
2074e8d8bef9SDimitry Andric           else if (Kind == Attribute::StructRet)
2075e8d8bef9SDimitry Andric             B.addStructRetAttr(nullptr);
2076fe6060f1SDimitry Andric           else if (Kind == Attribute::InAlloca)
2077fe6060f1SDimitry Andric             B.addInAllocaAttr(nullptr);
207881ad6265SDimitry Andric           else if (Kind == Attribute::UWTable)
207981ad6265SDimitry Andric             B.addUWTableAttr(UWTableKind::Default);
2080fe6060f1SDimitry Andric           else if (Attribute::isEnumAttrKind(Kind))
2081*0b57cec5SDimitry Andric             B.addAttribute(Kind);
2082fe6060f1SDimitry Andric           else
2083fe6060f1SDimitry Andric             return error("Not an enum attribute");
2084*0b57cec5SDimitry Andric         } else if (Record[i] == 1) { // Integer attribute
2085*0b57cec5SDimitry Andric           Attribute::AttrKind Kind;
2086*0b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
2087*0b57cec5SDimitry Andric             return Err;
2088fe6060f1SDimitry Andric           if (!Attribute::isIntAttrKind(Kind))
2089fe6060f1SDimitry Andric             return error("Not an int attribute");
2090*0b57cec5SDimitry Andric           if (Kind == Attribute::Alignment)
2091*0b57cec5SDimitry Andric             B.addAlignmentAttr(Record[++i]);
2092*0b57cec5SDimitry Andric           else if (Kind == Attribute::StackAlignment)
2093*0b57cec5SDimitry Andric             B.addStackAlignmentAttr(Record[++i]);
2094*0b57cec5SDimitry Andric           else if (Kind == Attribute::Dereferenceable)
2095*0b57cec5SDimitry Andric             B.addDereferenceableAttr(Record[++i]);
2096*0b57cec5SDimitry Andric           else if (Kind == Attribute::DereferenceableOrNull)
2097*0b57cec5SDimitry Andric             B.addDereferenceableOrNullAttr(Record[++i]);
2098*0b57cec5SDimitry Andric           else if (Kind == Attribute::AllocSize)
2099*0b57cec5SDimitry Andric             B.addAllocSizeAttrFromRawRepr(Record[++i]);
2100fe6060f1SDimitry Andric           else if (Kind == Attribute::VScaleRange)
2101fe6060f1SDimitry Andric             B.addVScaleRangeAttrFromRawRepr(Record[++i]);
210281ad6265SDimitry Andric           else if (Kind == Attribute::UWTable)
210381ad6265SDimitry Andric             B.addUWTableAttr(UWTableKind(Record[++i]));
210481ad6265SDimitry Andric           else if (Kind == Attribute::AllocKind)
210581ad6265SDimitry Andric             B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i]));
2106*0b57cec5SDimitry Andric         } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
2107*0b57cec5SDimitry Andric           bool HasValue = (Record[i++] == 4);
2108*0b57cec5SDimitry Andric           SmallString<64> KindStr;
2109*0b57cec5SDimitry Andric           SmallString<64> ValStr;
2110*0b57cec5SDimitry Andric 
2111*0b57cec5SDimitry Andric           while (Record[i] != 0 && i != e)
2112*0b57cec5SDimitry Andric             KindStr += Record[i++];
2113*0b57cec5SDimitry Andric           assert(Record[i] == 0 && "Kind string not null terminated");
2114*0b57cec5SDimitry Andric 
2115*0b57cec5SDimitry Andric           if (HasValue) {
2116*0b57cec5SDimitry Andric             // Has a value associated with it.
2117*0b57cec5SDimitry Andric             ++i; // Skip the '0' that terminates the "kind" string.
2118*0b57cec5SDimitry Andric             while (Record[i] != 0 && i != e)
2119*0b57cec5SDimitry Andric               ValStr += Record[i++];
2120*0b57cec5SDimitry Andric             assert(Record[i] == 0 && "Value string not null terminated");
2121*0b57cec5SDimitry Andric           }
2122*0b57cec5SDimitry Andric 
2123*0b57cec5SDimitry Andric           B.addAttribute(KindStr.str(), ValStr.str());
212481ad6265SDimitry Andric         } else if (Record[i] == 5 || Record[i] == 6) {
2125*0b57cec5SDimitry Andric           bool HasType = Record[i] == 6;
2126*0b57cec5SDimitry Andric           Attribute::AttrKind Kind;
2127*0b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
2128*0b57cec5SDimitry Andric             return Err;
2129fe6060f1SDimitry Andric           if (!Attribute::isTypeAttrKind(Kind))
2130fe6060f1SDimitry Andric             return error("Not a type attribute");
2131fe6060f1SDimitry Andric 
2132fe6060f1SDimitry Andric           B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
213381ad6265SDimitry Andric         } else {
213481ad6265SDimitry Andric           return error("Invalid attribute group entry");
2135*0b57cec5SDimitry Andric         }
2136*0b57cec5SDimitry Andric       }
2137*0b57cec5SDimitry Andric 
21385ffd83dbSDimitry Andric       UpgradeAttributes(B);
2139*0b57cec5SDimitry Andric       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
2140*0b57cec5SDimitry Andric       break;
2141*0b57cec5SDimitry Andric     }
2142*0b57cec5SDimitry Andric     }
2143*0b57cec5SDimitry Andric   }
2144*0b57cec5SDimitry Andric }
2145*0b57cec5SDimitry Andric 
2146*0b57cec5SDimitry Andric Error BitcodeReader::parseTypeTable() {
2147*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
2148*0b57cec5SDimitry Andric     return Err;
2149*0b57cec5SDimitry Andric 
2150*0b57cec5SDimitry Andric   return parseTypeTableBody();
2151*0b57cec5SDimitry Andric }
2152*0b57cec5SDimitry Andric 
2153*0b57cec5SDimitry Andric Error BitcodeReader::parseTypeTableBody() {
2154*0b57cec5SDimitry Andric   if (!TypeList.empty())
2155*0b57cec5SDimitry Andric     return error("Invalid multiple blocks");
2156*0b57cec5SDimitry Andric 
2157*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2158*0b57cec5SDimitry Andric   unsigned NumRecords = 0;
2159*0b57cec5SDimitry Andric 
2160*0b57cec5SDimitry Andric   SmallString<64> TypeName;
2161*0b57cec5SDimitry Andric 
2162*0b57cec5SDimitry Andric   // Read all the records for this type table.
2163*0b57cec5SDimitry Andric   while (true) {
2164*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2165*0b57cec5SDimitry Andric     if (!MaybeEntry)
2166*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
2167*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2168*0b57cec5SDimitry Andric 
2169*0b57cec5SDimitry Andric     switch (Entry.Kind) {
2170*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2171*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
2172*0b57cec5SDimitry Andric       return error("Malformed block");
2173*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2174*0b57cec5SDimitry Andric       if (NumRecords != TypeList.size())
2175*0b57cec5SDimitry Andric         return error("Malformed block");
2176*0b57cec5SDimitry Andric       return Error::success();
2177*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
2178*0b57cec5SDimitry Andric       // The interesting case.
2179*0b57cec5SDimitry Andric       break;
2180*0b57cec5SDimitry Andric     }
2181*0b57cec5SDimitry Andric 
2182*0b57cec5SDimitry Andric     // Read a record.
2183*0b57cec5SDimitry Andric     Record.clear();
2184*0b57cec5SDimitry Andric     Type *ResultTy = nullptr;
218581ad6265SDimitry Andric     SmallVector<unsigned> ContainedIDs;
2186*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2187*0b57cec5SDimitry Andric     if (!MaybeRecord)
2188*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
2189*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
2190*0b57cec5SDimitry Andric     default:
2191*0b57cec5SDimitry Andric       return error("Invalid value");
2192*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
2193*0b57cec5SDimitry Andric       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
2194*0b57cec5SDimitry Andric       // type list.  This allows us to reserve space.
2195e8d8bef9SDimitry Andric       if (Record.empty())
219681ad6265SDimitry Andric         return error("Invalid numentry record");
2197*0b57cec5SDimitry Andric       TypeList.resize(Record[0]);
2198*0b57cec5SDimitry Andric       continue;
2199*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_VOID:      // VOID
2200*0b57cec5SDimitry Andric       ResultTy = Type::getVoidTy(Context);
2201*0b57cec5SDimitry Andric       break;
2202*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_HALF:     // HALF
2203*0b57cec5SDimitry Andric       ResultTy = Type::getHalfTy(Context);
2204*0b57cec5SDimitry Andric       break;
22055ffd83dbSDimitry Andric     case bitc::TYPE_CODE_BFLOAT:    // BFLOAT
22065ffd83dbSDimitry Andric       ResultTy = Type::getBFloatTy(Context);
22075ffd83dbSDimitry Andric       break;
2208*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_FLOAT:     // FLOAT
2209*0b57cec5SDimitry Andric       ResultTy = Type::getFloatTy(Context);
2210*0b57cec5SDimitry Andric       break;
2211*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
2212*0b57cec5SDimitry Andric       ResultTy = Type::getDoubleTy(Context);
2213*0b57cec5SDimitry Andric       break;
2214*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
2215*0b57cec5SDimitry Andric       ResultTy = Type::getX86_FP80Ty(Context);
2216*0b57cec5SDimitry Andric       break;
2217*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_FP128:     // FP128
2218*0b57cec5SDimitry Andric       ResultTy = Type::getFP128Ty(Context);
2219*0b57cec5SDimitry Andric       break;
2220*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
2221*0b57cec5SDimitry Andric       ResultTy = Type::getPPC_FP128Ty(Context);
2222*0b57cec5SDimitry Andric       break;
2223*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_LABEL:     // LABEL
2224*0b57cec5SDimitry Andric       ResultTy = Type::getLabelTy(Context);
2225*0b57cec5SDimitry Andric       break;
2226*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_METADATA:  // METADATA
2227*0b57cec5SDimitry Andric       ResultTy = Type::getMetadataTy(Context);
2228*0b57cec5SDimitry Andric       break;
2229*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
2230*0b57cec5SDimitry Andric       ResultTy = Type::getX86_MMXTy(Context);
2231*0b57cec5SDimitry Andric       break;
2232e8d8bef9SDimitry Andric     case bitc::TYPE_CODE_X86_AMX:   // X86_AMX
2233e8d8bef9SDimitry Andric       ResultTy = Type::getX86_AMXTy(Context);
2234e8d8bef9SDimitry Andric       break;
2235*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_TOKEN:     // TOKEN
2236*0b57cec5SDimitry Andric       ResultTy = Type::getTokenTy(Context);
2237*0b57cec5SDimitry Andric       break;
2238*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
2239e8d8bef9SDimitry Andric       if (Record.empty())
224081ad6265SDimitry Andric         return error("Invalid integer record");
2241*0b57cec5SDimitry Andric 
2242*0b57cec5SDimitry Andric       uint64_t NumBits = Record[0];
2243*0b57cec5SDimitry Andric       if (NumBits < IntegerType::MIN_INT_BITS ||
2244*0b57cec5SDimitry Andric           NumBits > IntegerType::MAX_INT_BITS)
2245*0b57cec5SDimitry Andric         return error("Bitwidth for integer type out of range");
2246*0b57cec5SDimitry Andric       ResultTy = IntegerType::get(Context, NumBits);
2247*0b57cec5SDimitry Andric       break;
2248*0b57cec5SDimitry Andric     }
2249*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
2250*0b57cec5SDimitry Andric                                     //          [pointee type, address space]
2251e8d8bef9SDimitry Andric       if (Record.empty())
225281ad6265SDimitry Andric         return error("Invalid pointer record");
2253*0b57cec5SDimitry Andric       unsigned AddressSpace = 0;
2254*0b57cec5SDimitry Andric       if (Record.size() == 2)
2255*0b57cec5SDimitry Andric         AddressSpace = Record[1];
2256*0b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[0]);
2257*0b57cec5SDimitry Andric       if (!ResultTy ||
2258*0b57cec5SDimitry Andric           !PointerType::isValidElementType(ResultTy))
2259*0b57cec5SDimitry Andric         return error("Invalid type");
226081ad6265SDimitry Andric       if (LLVM_UNLIKELY(!Context.hasSetOpaquePointersValue()))
226181ad6265SDimitry Andric         Context.setOpaquePointers(false);
226281ad6265SDimitry Andric       ContainedIDs.push_back(Record[0]);
2263*0b57cec5SDimitry Andric       ResultTy = PointerType::get(ResultTy, AddressSpace);
2264*0b57cec5SDimitry Andric       break;
2265*0b57cec5SDimitry Andric     }
2266fe6060f1SDimitry Andric     case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
2267fe6060f1SDimitry Andric       if (Record.size() != 1)
226881ad6265SDimitry Andric         return error("Invalid opaque pointer record");
226981ad6265SDimitry Andric       if (LLVM_UNLIKELY(!Context.hasSetOpaquePointersValue())) {
227081ad6265SDimitry Andric         Context.setOpaquePointers(true);
227181ad6265SDimitry Andric       } else if (Context.supportsTypedPointers())
2272349cc55cSDimitry Andric         return error(
2273349cc55cSDimitry Andric             "Opaque pointers are only supported in -opaque-pointers mode");
2274fe6060f1SDimitry Andric       unsigned AddressSpace = Record[0];
2275fe6060f1SDimitry Andric       ResultTy = PointerType::get(Context, AddressSpace);
2276fe6060f1SDimitry Andric       break;
2277fe6060f1SDimitry Andric     }
2278*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_FUNCTION_OLD: {
22795ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
2280*0b57cec5SDimitry Andric       // FUNCTION: [vararg, attrid, retty, paramty x N]
2281*0b57cec5SDimitry Andric       if (Record.size() < 3)
228281ad6265SDimitry Andric         return error("Invalid function record");
2283*0b57cec5SDimitry Andric       SmallVector<Type*, 8> ArgTys;
2284*0b57cec5SDimitry Andric       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
2285*0b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
2286*0b57cec5SDimitry Andric           ArgTys.push_back(T);
2287*0b57cec5SDimitry Andric         else
2288*0b57cec5SDimitry Andric           break;
2289*0b57cec5SDimitry Andric       }
2290*0b57cec5SDimitry Andric 
2291*0b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[2]);
2292*0b57cec5SDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-3)
2293*0b57cec5SDimitry Andric         return error("Invalid type");
2294*0b57cec5SDimitry Andric 
229581ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 2, Record.end());
2296*0b57cec5SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2297*0b57cec5SDimitry Andric       break;
2298*0b57cec5SDimitry Andric     }
2299*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_FUNCTION: {
2300*0b57cec5SDimitry Andric       // FUNCTION: [vararg, retty, paramty x N]
2301*0b57cec5SDimitry Andric       if (Record.size() < 2)
230281ad6265SDimitry Andric         return error("Invalid function record");
2303*0b57cec5SDimitry Andric       SmallVector<Type*, 8> ArgTys;
2304*0b57cec5SDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2305*0b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i])) {
2306*0b57cec5SDimitry Andric           if (!FunctionType::isValidArgumentType(T))
2307*0b57cec5SDimitry Andric             return error("Invalid function argument type");
2308*0b57cec5SDimitry Andric           ArgTys.push_back(T);
2309*0b57cec5SDimitry Andric         }
2310*0b57cec5SDimitry Andric         else
2311*0b57cec5SDimitry Andric           break;
2312*0b57cec5SDimitry Andric       }
2313*0b57cec5SDimitry Andric 
2314*0b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
2315*0b57cec5SDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-2)
2316*0b57cec5SDimitry Andric         return error("Invalid type");
2317*0b57cec5SDimitry Andric 
231881ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 1, Record.end());
2319*0b57cec5SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2320*0b57cec5SDimitry Andric       break;
2321*0b57cec5SDimitry Andric     }
2322*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
2323e8d8bef9SDimitry Andric       if (Record.empty())
232481ad6265SDimitry Andric         return error("Invalid anon struct record");
2325*0b57cec5SDimitry Andric       SmallVector<Type*, 8> EltTys;
2326*0b57cec5SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2327*0b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
2328*0b57cec5SDimitry Andric           EltTys.push_back(T);
2329*0b57cec5SDimitry Andric         else
2330*0b57cec5SDimitry Andric           break;
2331*0b57cec5SDimitry Andric       }
2332*0b57cec5SDimitry Andric       if (EltTys.size() != Record.size()-1)
2333*0b57cec5SDimitry Andric         return error("Invalid type");
233481ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 1, Record.end());
2335*0b57cec5SDimitry Andric       ResultTy = StructType::get(Context, EltTys, Record[0]);
2336*0b57cec5SDimitry Andric       break;
2337*0b57cec5SDimitry Andric     }
2338*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
2339*0b57cec5SDimitry Andric       if (convertToString(Record, 0, TypeName))
234081ad6265SDimitry Andric         return error("Invalid struct name record");
2341*0b57cec5SDimitry Andric       continue;
2342*0b57cec5SDimitry Andric 
2343*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
2344e8d8bef9SDimitry Andric       if (Record.empty())
234581ad6265SDimitry Andric         return error("Invalid named struct record");
2346*0b57cec5SDimitry Andric 
2347*0b57cec5SDimitry Andric       if (NumRecords >= TypeList.size())
2348*0b57cec5SDimitry Andric         return error("Invalid TYPE table");
2349*0b57cec5SDimitry Andric 
2350*0b57cec5SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
2351*0b57cec5SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2352*0b57cec5SDimitry Andric       if (Res) {
2353*0b57cec5SDimitry Andric         Res->setName(TypeName);
2354*0b57cec5SDimitry Andric         TypeList[NumRecords] = nullptr;
2355*0b57cec5SDimitry Andric       } else  // Otherwise, create a new struct.
2356*0b57cec5SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
2357*0b57cec5SDimitry Andric       TypeName.clear();
2358*0b57cec5SDimitry Andric 
2359*0b57cec5SDimitry Andric       SmallVector<Type*, 8> EltTys;
2360*0b57cec5SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2361*0b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
2362*0b57cec5SDimitry Andric           EltTys.push_back(T);
2363*0b57cec5SDimitry Andric         else
2364*0b57cec5SDimitry Andric           break;
2365*0b57cec5SDimitry Andric       }
2366*0b57cec5SDimitry Andric       if (EltTys.size() != Record.size()-1)
236781ad6265SDimitry Andric         return error("Invalid named struct record");
2368*0b57cec5SDimitry Andric       Res->setBody(EltTys, Record[0]);
236981ad6265SDimitry Andric       ContainedIDs.append(Record.begin() + 1, Record.end());
2370*0b57cec5SDimitry Andric       ResultTy = Res;
2371*0b57cec5SDimitry Andric       break;
2372*0b57cec5SDimitry Andric     }
2373*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
2374*0b57cec5SDimitry Andric       if (Record.size() != 1)
237581ad6265SDimitry Andric         return error("Invalid opaque type record");
2376*0b57cec5SDimitry Andric 
2377*0b57cec5SDimitry Andric       if (NumRecords >= TypeList.size())
2378*0b57cec5SDimitry Andric         return error("Invalid TYPE table");
2379*0b57cec5SDimitry Andric 
2380*0b57cec5SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
2381*0b57cec5SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2382*0b57cec5SDimitry Andric       if (Res) {
2383*0b57cec5SDimitry Andric         Res->setName(TypeName);
2384*0b57cec5SDimitry Andric         TypeList[NumRecords] = nullptr;
2385*0b57cec5SDimitry Andric       } else  // Otherwise, create a new struct with no body.
2386*0b57cec5SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
2387*0b57cec5SDimitry Andric       TypeName.clear();
2388*0b57cec5SDimitry Andric       ResultTy = Res;
2389*0b57cec5SDimitry Andric       break;
2390*0b57cec5SDimitry Andric     }
2391*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
2392*0b57cec5SDimitry Andric       if (Record.size() < 2)
239381ad6265SDimitry Andric         return error("Invalid array type record");
2394*0b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
2395*0b57cec5SDimitry Andric       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2396*0b57cec5SDimitry Andric         return error("Invalid type");
239781ad6265SDimitry Andric       ContainedIDs.push_back(Record[1]);
2398*0b57cec5SDimitry Andric       ResultTy = ArrayType::get(ResultTy, Record[0]);
2399*0b57cec5SDimitry Andric       break;
2400*0b57cec5SDimitry Andric     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty] or
2401*0b57cec5SDimitry Andric                                     //         [numelts, eltty, scalable]
2402*0b57cec5SDimitry Andric       if (Record.size() < 2)
240381ad6265SDimitry Andric         return error("Invalid vector type record");
2404*0b57cec5SDimitry Andric       if (Record[0] == 0)
2405*0b57cec5SDimitry Andric         return error("Invalid vector length");
2406*0b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
2407349cc55cSDimitry Andric       if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2408*0b57cec5SDimitry Andric         return error("Invalid type");
2409*0b57cec5SDimitry Andric       bool Scalable = Record.size() > 2 ? Record[2] : false;
241081ad6265SDimitry Andric       ContainedIDs.push_back(Record[1]);
2411*0b57cec5SDimitry Andric       ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2412*0b57cec5SDimitry Andric       break;
2413*0b57cec5SDimitry Andric     }
2414*0b57cec5SDimitry Andric 
2415*0b57cec5SDimitry Andric     if (NumRecords >= TypeList.size())
2416*0b57cec5SDimitry Andric       return error("Invalid TYPE table");
2417*0b57cec5SDimitry Andric     if (TypeList[NumRecords])
2418*0b57cec5SDimitry Andric       return error(
2419*0b57cec5SDimitry Andric           "Invalid TYPE table: Only named structs can be forward referenced");
2420*0b57cec5SDimitry Andric     assert(ResultTy && "Didn't read a type?");
242181ad6265SDimitry Andric     TypeList[NumRecords] = ResultTy;
242281ad6265SDimitry Andric     if (!ContainedIDs.empty())
242381ad6265SDimitry Andric       ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
242481ad6265SDimitry Andric     ++NumRecords;
2425*0b57cec5SDimitry Andric   }
2426*0b57cec5SDimitry Andric }
2427*0b57cec5SDimitry Andric 
2428*0b57cec5SDimitry Andric Error BitcodeReader::parseOperandBundleTags() {
2429*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
2430*0b57cec5SDimitry Andric     return Err;
2431*0b57cec5SDimitry Andric 
2432*0b57cec5SDimitry Andric   if (!BundleTags.empty())
2433*0b57cec5SDimitry Andric     return error("Invalid multiple blocks");
2434*0b57cec5SDimitry Andric 
2435*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2436*0b57cec5SDimitry Andric 
2437*0b57cec5SDimitry Andric   while (true) {
2438*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2439*0b57cec5SDimitry Andric     if (!MaybeEntry)
2440*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
2441*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2442*0b57cec5SDimitry Andric 
2443*0b57cec5SDimitry Andric     switch (Entry.Kind) {
2444*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2445*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
2446*0b57cec5SDimitry Andric       return error("Malformed block");
2447*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2448*0b57cec5SDimitry Andric       return Error::success();
2449*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
2450*0b57cec5SDimitry Andric       // The interesting case.
2451*0b57cec5SDimitry Andric       break;
2452*0b57cec5SDimitry Andric     }
2453*0b57cec5SDimitry Andric 
2454*0b57cec5SDimitry Andric     // Tags are implicitly mapped to integers by their order.
2455*0b57cec5SDimitry Andric 
2456*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2457*0b57cec5SDimitry Andric     if (!MaybeRecord)
2458*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
2459*0b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
246081ad6265SDimitry Andric       return error("Invalid operand bundle record");
2461*0b57cec5SDimitry Andric 
2462*0b57cec5SDimitry Andric     // OPERAND_BUNDLE_TAG: [strchr x N]
2463*0b57cec5SDimitry Andric     BundleTags.emplace_back();
2464*0b57cec5SDimitry Andric     if (convertToString(Record, 0, BundleTags.back()))
246581ad6265SDimitry Andric       return error("Invalid operand bundle record");
2466*0b57cec5SDimitry Andric     Record.clear();
2467*0b57cec5SDimitry Andric   }
2468*0b57cec5SDimitry Andric }
2469*0b57cec5SDimitry Andric 
2470*0b57cec5SDimitry Andric Error BitcodeReader::parseSyncScopeNames() {
2471*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2472*0b57cec5SDimitry Andric     return Err;
2473*0b57cec5SDimitry Andric 
2474*0b57cec5SDimitry Andric   if (!SSIDs.empty())
2475*0b57cec5SDimitry Andric     return error("Invalid multiple synchronization scope names blocks");
2476*0b57cec5SDimitry Andric 
2477*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2478*0b57cec5SDimitry Andric   while (true) {
2479*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2480*0b57cec5SDimitry Andric     if (!MaybeEntry)
2481*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
2482*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2483*0b57cec5SDimitry Andric 
2484*0b57cec5SDimitry Andric     switch (Entry.Kind) {
2485*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2486*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
2487*0b57cec5SDimitry Andric       return error("Malformed block");
2488*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2489*0b57cec5SDimitry Andric       if (SSIDs.empty())
2490*0b57cec5SDimitry Andric         return error("Invalid empty synchronization scope names block");
2491*0b57cec5SDimitry Andric       return Error::success();
2492*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
2493*0b57cec5SDimitry Andric       // The interesting case.
2494*0b57cec5SDimitry Andric       break;
2495*0b57cec5SDimitry Andric     }
2496*0b57cec5SDimitry Andric 
2497*0b57cec5SDimitry Andric     // Synchronization scope names are implicitly mapped to synchronization
2498*0b57cec5SDimitry Andric     // scope IDs by their order.
2499*0b57cec5SDimitry Andric 
2500*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2501*0b57cec5SDimitry Andric     if (!MaybeRecord)
2502*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
2503*0b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
250481ad6265SDimitry Andric       return error("Invalid sync scope record");
2505*0b57cec5SDimitry Andric 
2506*0b57cec5SDimitry Andric     SmallString<16> SSN;
2507*0b57cec5SDimitry Andric     if (convertToString(Record, 0, SSN))
250881ad6265SDimitry Andric       return error("Invalid sync scope record");
2509*0b57cec5SDimitry Andric 
2510*0b57cec5SDimitry Andric     SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2511*0b57cec5SDimitry Andric     Record.clear();
2512*0b57cec5SDimitry Andric   }
2513*0b57cec5SDimitry Andric }
2514*0b57cec5SDimitry Andric 
2515*0b57cec5SDimitry Andric /// Associate a value with its name from the given index in the provided record.
2516*0b57cec5SDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2517*0b57cec5SDimitry Andric                                              unsigned NameIndex, Triple &TT) {
2518*0b57cec5SDimitry Andric   SmallString<128> ValueName;
2519*0b57cec5SDimitry Andric   if (convertToString(Record, NameIndex, ValueName))
2520*0b57cec5SDimitry Andric     return error("Invalid record");
2521*0b57cec5SDimitry Andric   unsigned ValueID = Record[0];
2522*0b57cec5SDimitry Andric   if (ValueID >= ValueList.size() || !ValueList[ValueID])
2523*0b57cec5SDimitry Andric     return error("Invalid record");
2524*0b57cec5SDimitry Andric   Value *V = ValueList[ValueID];
2525*0b57cec5SDimitry Andric 
2526*0b57cec5SDimitry Andric   StringRef NameStr(ValueName.data(), ValueName.size());
2527*0b57cec5SDimitry Andric   if (NameStr.find_first_of(0) != StringRef::npos)
2528*0b57cec5SDimitry Andric     return error("Invalid value name");
2529*0b57cec5SDimitry Andric   V->setName(NameStr);
2530*0b57cec5SDimitry Andric   auto *GO = dyn_cast<GlobalObject>(V);
25310eae32dcSDimitry Andric   if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
2532*0b57cec5SDimitry Andric     GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2533*0b57cec5SDimitry Andric   return V;
2534*0b57cec5SDimitry Andric }
2535*0b57cec5SDimitry Andric 
2536*0b57cec5SDimitry Andric /// Helper to note and return the current location, and jump to the given
2537*0b57cec5SDimitry Andric /// offset.
2538*0b57cec5SDimitry Andric static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
2539*0b57cec5SDimitry Andric                                                  BitstreamCursor &Stream) {
2540*0b57cec5SDimitry Andric   // Save the current parsing location so we can jump back at the end
2541*0b57cec5SDimitry Andric   // of the VST read.
2542*0b57cec5SDimitry Andric   uint64_t CurrentBit = Stream.GetCurrentBitNo();
2543*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2544*0b57cec5SDimitry Andric     return std::move(JumpFailed);
2545*0b57cec5SDimitry Andric   Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2546*0b57cec5SDimitry Andric   if (!MaybeEntry)
2547*0b57cec5SDimitry Andric     return MaybeEntry.takeError();
254881ad6265SDimitry Andric   if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
254981ad6265SDimitry Andric       MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
255081ad6265SDimitry Andric     return error("Expected value symbol table subblock");
2551*0b57cec5SDimitry Andric   return CurrentBit;
2552*0b57cec5SDimitry Andric }
2553*0b57cec5SDimitry Andric 
2554*0b57cec5SDimitry Andric void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2555*0b57cec5SDimitry Andric                                             Function *F,
2556*0b57cec5SDimitry Andric                                             ArrayRef<uint64_t> Record) {
2557*0b57cec5SDimitry Andric   // Note that we subtract 1 here because the offset is relative to one word
2558*0b57cec5SDimitry Andric   // before the start of the identification or module block, which was
2559*0b57cec5SDimitry Andric   // historically always the start of the regular bitcode header.
2560*0b57cec5SDimitry Andric   uint64_t FuncWordOffset = Record[1] - 1;
2561*0b57cec5SDimitry Andric   uint64_t FuncBitOffset = FuncWordOffset * 32;
2562*0b57cec5SDimitry Andric   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2563*0b57cec5SDimitry Andric   // Set the LastFunctionBlockBit to point to the last function block.
2564*0b57cec5SDimitry Andric   // Later when parsing is resumed after function materialization,
2565*0b57cec5SDimitry Andric   // we can simply skip that last function block.
2566*0b57cec5SDimitry Andric   if (FuncBitOffset > LastFunctionBlockBit)
2567*0b57cec5SDimitry Andric     LastFunctionBlockBit = FuncBitOffset;
2568*0b57cec5SDimitry Andric }
2569*0b57cec5SDimitry Andric 
2570*0b57cec5SDimitry Andric /// Read a new-style GlobalValue symbol table.
2571*0b57cec5SDimitry Andric Error BitcodeReader::parseGlobalValueSymbolTable() {
2572*0b57cec5SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
2573*0b57cec5SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2574*0b57cec5SDimitry Andric 
2575*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2576*0b57cec5SDimitry Andric     return Err;
2577*0b57cec5SDimitry Andric 
2578*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2579*0b57cec5SDimitry Andric   while (true) {
2580*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2581*0b57cec5SDimitry Andric     if (!MaybeEntry)
2582*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
2583*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2584*0b57cec5SDimitry Andric 
2585*0b57cec5SDimitry Andric     switch (Entry.Kind) {
2586*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
2587*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
2588*0b57cec5SDimitry Andric       return error("Malformed block");
2589*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2590*0b57cec5SDimitry Andric       return Error::success();
2591*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
2592*0b57cec5SDimitry Andric       break;
2593*0b57cec5SDimitry Andric     }
2594*0b57cec5SDimitry Andric 
2595*0b57cec5SDimitry Andric     Record.clear();
2596*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2597*0b57cec5SDimitry Andric     if (!MaybeRecord)
2598*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
2599*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
260081ad6265SDimitry Andric     case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
260181ad6265SDimitry Andric       unsigned ValueID = Record[0];
260281ad6265SDimitry Andric       if (ValueID >= ValueList.size() || !ValueList[ValueID])
260381ad6265SDimitry Andric         return error("Invalid value reference in symbol table");
2604*0b57cec5SDimitry Andric       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
260581ad6265SDimitry Andric                               cast<Function>(ValueList[ValueID]), Record);
2606*0b57cec5SDimitry Andric       break;
2607*0b57cec5SDimitry Andric     }
2608*0b57cec5SDimitry Andric     }
2609*0b57cec5SDimitry Andric   }
261081ad6265SDimitry Andric }
2611*0b57cec5SDimitry Andric 
2612*0b57cec5SDimitry Andric /// Parse the value symbol table at either the current parsing location or
2613*0b57cec5SDimitry Andric /// at the given bit offset if provided.
2614*0b57cec5SDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
2615*0b57cec5SDimitry Andric   uint64_t CurrentBit;
2616*0b57cec5SDimitry Andric   // Pass in the Offset to distinguish between calling for the module-level
2617*0b57cec5SDimitry Andric   // VST (where we want to jump to the VST offset) and the function-level
2618*0b57cec5SDimitry Andric   // VST (where we don't).
2619*0b57cec5SDimitry Andric   if (Offset > 0) {
2620*0b57cec5SDimitry Andric     Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2621*0b57cec5SDimitry Andric     if (!MaybeCurrentBit)
2622*0b57cec5SDimitry Andric       return MaybeCurrentBit.takeError();
2623*0b57cec5SDimitry Andric     CurrentBit = MaybeCurrentBit.get();
2624*0b57cec5SDimitry Andric     // If this module uses a string table, read this as a module-level VST.
2625*0b57cec5SDimitry Andric     if (UseStrtab) {
2626*0b57cec5SDimitry Andric       if (Error Err = parseGlobalValueSymbolTable())
2627*0b57cec5SDimitry Andric         return Err;
2628*0b57cec5SDimitry Andric       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2629*0b57cec5SDimitry Andric         return JumpFailed;
2630*0b57cec5SDimitry Andric       return Error::success();
2631*0b57cec5SDimitry Andric     }
2632*0b57cec5SDimitry Andric     // Otherwise, the VST will be in a similar format to a function-level VST,
2633*0b57cec5SDimitry Andric     // and will contain symbol names.
2634*0b57cec5SDimitry Andric   }
2635*0b57cec5SDimitry Andric 
2636*0b57cec5SDimitry Andric   // Compute the delta between the bitcode indices in the VST (the word offset
2637*0b57cec5SDimitry Andric   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2638*0b57cec5SDimitry Andric   // expected by the lazy reader. The reader's EnterSubBlock expects to have
2639*0b57cec5SDimitry Andric   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2640*0b57cec5SDimitry Andric   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2641*0b57cec5SDimitry Andric   // just before entering the VST subblock because: 1) the EnterSubBlock
2642*0b57cec5SDimitry Andric   // changes the AbbrevID width; 2) the VST block is nested within the same
2643*0b57cec5SDimitry Andric   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2644*0b57cec5SDimitry Andric   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2645*0b57cec5SDimitry Andric   // jump to the FUNCTION_BLOCK using this offset later, we don't want
2646*0b57cec5SDimitry Andric   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2647*0b57cec5SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
2648*0b57cec5SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2649*0b57cec5SDimitry Andric 
2650*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2651*0b57cec5SDimitry Andric     return Err;
2652*0b57cec5SDimitry Andric 
2653*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2654*0b57cec5SDimitry Andric 
2655*0b57cec5SDimitry Andric   Triple TT(TheModule->getTargetTriple());
2656*0b57cec5SDimitry Andric 
2657*0b57cec5SDimitry Andric   // Read all the records for this value table.
2658*0b57cec5SDimitry Andric   SmallString<128> ValueName;
2659*0b57cec5SDimitry Andric 
2660*0b57cec5SDimitry Andric   while (true) {
2661*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2662*0b57cec5SDimitry Andric     if (!MaybeEntry)
2663*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
2664*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2665*0b57cec5SDimitry Andric 
2666*0b57cec5SDimitry Andric     switch (Entry.Kind) {
2667*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2668*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
2669*0b57cec5SDimitry Andric       return error("Malformed block");
2670*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2671*0b57cec5SDimitry Andric       if (Offset > 0)
2672*0b57cec5SDimitry Andric         if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2673*0b57cec5SDimitry Andric           return JumpFailed;
2674*0b57cec5SDimitry Andric       return Error::success();
2675*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
2676*0b57cec5SDimitry Andric       // The interesting case.
2677*0b57cec5SDimitry Andric       break;
2678*0b57cec5SDimitry Andric     }
2679*0b57cec5SDimitry Andric 
2680*0b57cec5SDimitry Andric     // Read a record.
2681*0b57cec5SDimitry Andric     Record.clear();
2682*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2683*0b57cec5SDimitry Andric     if (!MaybeRecord)
2684*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
2685*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
2686*0b57cec5SDimitry Andric     default:  // Default behavior: unknown type.
2687*0b57cec5SDimitry Andric       break;
2688*0b57cec5SDimitry Andric     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
2689*0b57cec5SDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2690*0b57cec5SDimitry Andric       if (Error Err = ValOrErr.takeError())
2691*0b57cec5SDimitry Andric         return Err;
2692*0b57cec5SDimitry Andric       ValOrErr.get();
2693*0b57cec5SDimitry Andric       break;
2694*0b57cec5SDimitry Andric     }
2695*0b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
2696*0b57cec5SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2697*0b57cec5SDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2698*0b57cec5SDimitry Andric       if (Error Err = ValOrErr.takeError())
2699*0b57cec5SDimitry Andric         return Err;
2700*0b57cec5SDimitry Andric       Value *V = ValOrErr.get();
2701*0b57cec5SDimitry Andric 
2702*0b57cec5SDimitry Andric       // Ignore function offsets emitted for aliases of functions in older
2703*0b57cec5SDimitry Andric       // versions of LLVM.
2704*0b57cec5SDimitry Andric       if (auto *F = dyn_cast<Function>(V))
2705*0b57cec5SDimitry Andric         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2706*0b57cec5SDimitry Andric       break;
2707*0b57cec5SDimitry Andric     }
2708*0b57cec5SDimitry Andric     case bitc::VST_CODE_BBENTRY: {
2709*0b57cec5SDimitry Andric       if (convertToString(Record, 1, ValueName))
271081ad6265SDimitry Andric         return error("Invalid bbentry record");
2711*0b57cec5SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[0]);
2712*0b57cec5SDimitry Andric       if (!BB)
271381ad6265SDimitry Andric         return error("Invalid bbentry record");
2714*0b57cec5SDimitry Andric 
2715*0b57cec5SDimitry Andric       BB->setName(StringRef(ValueName.data(), ValueName.size()));
2716*0b57cec5SDimitry Andric       ValueName.clear();
2717*0b57cec5SDimitry Andric       break;
2718*0b57cec5SDimitry Andric     }
2719*0b57cec5SDimitry Andric     }
2720*0b57cec5SDimitry Andric   }
2721*0b57cec5SDimitry Andric }
2722*0b57cec5SDimitry Andric 
2723*0b57cec5SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2724*0b57cec5SDimitry Andric /// encoding.
2725*0b57cec5SDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2726*0b57cec5SDimitry Andric   if ((V & 1) == 0)
2727*0b57cec5SDimitry Andric     return V >> 1;
2728*0b57cec5SDimitry Andric   if (V != 1)
2729*0b57cec5SDimitry Andric     return -(V >> 1);
2730*0b57cec5SDimitry Andric   // There is no such thing as -0 with integers.  "-0" really means MININT.
2731*0b57cec5SDimitry Andric   return 1ULL << 63;
2732*0b57cec5SDimitry Andric }
2733*0b57cec5SDimitry Andric 
2734*0b57cec5SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can.
2735*0b57cec5SDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2736*0b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2737349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
2738349cc55cSDimitry Andric   std::vector<FunctionOperandInfo> FunctionOperandWorklist;
2739*0b57cec5SDimitry Andric 
2740*0b57cec5SDimitry Andric   GlobalInitWorklist.swap(GlobalInits);
2741*0b57cec5SDimitry Andric   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2742349cc55cSDimitry Andric   FunctionOperandWorklist.swap(FunctionOperands);
2743*0b57cec5SDimitry Andric 
2744*0b57cec5SDimitry Andric   while (!GlobalInitWorklist.empty()) {
2745*0b57cec5SDimitry Andric     unsigned ValID = GlobalInitWorklist.back().second;
2746*0b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
2747*0b57cec5SDimitry Andric       // Not ready to resolve this yet, it requires something later in the file.
2748*0b57cec5SDimitry Andric       GlobalInits.push_back(GlobalInitWorklist.back());
2749*0b57cec5SDimitry Andric     } else {
275081ad6265SDimitry Andric       Expected<Constant *> MaybeC = getValueForInitializer(ValID);
275181ad6265SDimitry Andric       if (!MaybeC)
275281ad6265SDimitry Andric         return MaybeC.takeError();
275381ad6265SDimitry Andric       GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
2754*0b57cec5SDimitry Andric     }
2755*0b57cec5SDimitry Andric     GlobalInitWorklist.pop_back();
2756*0b57cec5SDimitry Andric   }
2757*0b57cec5SDimitry Andric 
2758*0b57cec5SDimitry Andric   while (!IndirectSymbolInitWorklist.empty()) {
2759*0b57cec5SDimitry Andric     unsigned ValID = IndirectSymbolInitWorklist.back().second;
2760*0b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
2761*0b57cec5SDimitry Andric       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2762*0b57cec5SDimitry Andric     } else {
276381ad6265SDimitry Andric       Expected<Constant *> MaybeC = getValueForInitializer(ValID);
276481ad6265SDimitry Andric       if (!MaybeC)
276581ad6265SDimitry Andric         return MaybeC.takeError();
276681ad6265SDimitry Andric       Constant *C = MaybeC.get();
2767349cc55cSDimitry Andric       GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
2768349cc55cSDimitry Andric       if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
2769349cc55cSDimitry Andric         if (C->getType() != GV->getType())
2770*0b57cec5SDimitry Andric           return error("Alias and aliasee types don't match");
2771349cc55cSDimitry Andric         GA->setAliasee(C);
2772349cc55cSDimitry Andric       } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
2773349cc55cSDimitry Andric         Type *ResolverFTy =
2774349cc55cSDimitry Andric             GlobalIFunc::getResolverFunctionType(GI->getValueType());
2775349cc55cSDimitry Andric         // Transparently fix up the type for compatiblity with older bitcode
2776349cc55cSDimitry Andric         GI->setResolver(
2777349cc55cSDimitry Andric             ConstantExpr::getBitCast(C, ResolverFTy->getPointerTo()));
2778349cc55cSDimitry Andric       } else {
2779349cc55cSDimitry Andric         return error("Expected an alias or an ifunc");
2780349cc55cSDimitry Andric       }
2781*0b57cec5SDimitry Andric     }
2782*0b57cec5SDimitry Andric     IndirectSymbolInitWorklist.pop_back();
2783*0b57cec5SDimitry Andric   }
2784*0b57cec5SDimitry Andric 
2785349cc55cSDimitry Andric   while (!FunctionOperandWorklist.empty()) {
2786349cc55cSDimitry Andric     FunctionOperandInfo &Info = FunctionOperandWorklist.back();
2787349cc55cSDimitry Andric     if (Info.PersonalityFn) {
2788349cc55cSDimitry Andric       unsigned ValID = Info.PersonalityFn - 1;
2789349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
279081ad6265SDimitry Andric         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
279181ad6265SDimitry Andric         if (!MaybeC)
279281ad6265SDimitry Andric           return MaybeC.takeError();
279381ad6265SDimitry Andric         Info.F->setPersonalityFn(MaybeC.get());
2794349cc55cSDimitry Andric         Info.PersonalityFn = 0;
2795*0b57cec5SDimitry Andric       }
2796*0b57cec5SDimitry Andric     }
2797349cc55cSDimitry Andric     if (Info.Prefix) {
2798349cc55cSDimitry Andric       unsigned ValID = Info.Prefix - 1;
2799349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
280081ad6265SDimitry Andric         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
280181ad6265SDimitry Andric         if (!MaybeC)
280281ad6265SDimitry Andric           return MaybeC.takeError();
280381ad6265SDimitry Andric         Info.F->setPrefixData(MaybeC.get());
2804349cc55cSDimitry Andric         Info.Prefix = 0;
2805*0b57cec5SDimitry Andric       }
2806*0b57cec5SDimitry Andric     }
2807349cc55cSDimitry Andric     if (Info.Prologue) {
2808349cc55cSDimitry Andric       unsigned ValID = Info.Prologue - 1;
2809349cc55cSDimitry Andric       if (ValID < ValueList.size()) {
281081ad6265SDimitry Andric         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
281181ad6265SDimitry Andric         if (!MaybeC)
281281ad6265SDimitry Andric           return MaybeC.takeError();
281381ad6265SDimitry Andric         Info.F->setPrologueData(MaybeC.get());
2814349cc55cSDimitry Andric         Info.Prologue = 0;
2815*0b57cec5SDimitry Andric       }
2816349cc55cSDimitry Andric     }
2817349cc55cSDimitry Andric     if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
2818349cc55cSDimitry Andric       FunctionOperands.push_back(Info);
2819349cc55cSDimitry Andric     FunctionOperandWorklist.pop_back();
2820*0b57cec5SDimitry Andric   }
2821*0b57cec5SDimitry Andric 
2822*0b57cec5SDimitry Andric   return Error::success();
2823*0b57cec5SDimitry Andric }
2824*0b57cec5SDimitry Andric 
28255ffd83dbSDimitry Andric APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2826*0b57cec5SDimitry Andric   SmallVector<uint64_t, 8> Words(Vals.size());
2827*0b57cec5SDimitry Andric   transform(Vals, Words.begin(),
2828*0b57cec5SDimitry Andric                  BitcodeReader::decodeSignRotatedValue);
2829*0b57cec5SDimitry Andric 
2830*0b57cec5SDimitry Andric   return APInt(TypeBits, Words);
2831*0b57cec5SDimitry Andric }
2832*0b57cec5SDimitry Andric 
2833*0b57cec5SDimitry Andric Error BitcodeReader::parseConstants() {
2834*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2835*0b57cec5SDimitry Andric     return Err;
2836*0b57cec5SDimitry Andric 
2837*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2838*0b57cec5SDimitry Andric 
2839*0b57cec5SDimitry Andric   // Read all the records for this value table.
2840*0b57cec5SDimitry Andric   Type *CurTy = Type::getInt32Ty(Context);
284181ad6265SDimitry Andric   unsigned Int32TyID = getVirtualTypeID(CurTy);
284281ad6265SDimitry Andric   unsigned CurTyID = Int32TyID;
284381ad6265SDimitry Andric   Type *CurElemTy = nullptr;
2844*0b57cec5SDimitry Andric   unsigned NextCstNo = ValueList.size();
2845*0b57cec5SDimitry Andric 
2846*0b57cec5SDimitry Andric   while (true) {
2847*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2848*0b57cec5SDimitry Andric     if (!MaybeEntry)
2849*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
2850*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2851*0b57cec5SDimitry Andric 
2852*0b57cec5SDimitry Andric     switch (Entry.Kind) {
2853*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2854*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
2855*0b57cec5SDimitry Andric       return error("Malformed block");
2856*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2857*0b57cec5SDimitry Andric       if (NextCstNo != ValueList.size())
2858*0b57cec5SDimitry Andric         return error("Invalid constant reference");
2859*0b57cec5SDimitry Andric       return Error::success();
2860*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
2861*0b57cec5SDimitry Andric       // The interesting case.
2862*0b57cec5SDimitry Andric       break;
2863*0b57cec5SDimitry Andric     }
2864*0b57cec5SDimitry Andric 
2865*0b57cec5SDimitry Andric     // Read a record.
2866*0b57cec5SDimitry Andric     Record.clear();
2867*0b57cec5SDimitry Andric     Type *VoidType = Type::getVoidTy(Context);
2868*0b57cec5SDimitry Andric     Value *V = nullptr;
2869*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2870*0b57cec5SDimitry Andric     if (!MaybeBitCode)
2871*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
2872*0b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
2873*0b57cec5SDimitry Andric     default:  // Default behavior: unknown constant
2874*0b57cec5SDimitry Andric     case bitc::CST_CODE_UNDEF:     // UNDEF
2875*0b57cec5SDimitry Andric       V = UndefValue::get(CurTy);
2876*0b57cec5SDimitry Andric       break;
2877e8d8bef9SDimitry Andric     case bitc::CST_CODE_POISON:    // POISON
2878e8d8bef9SDimitry Andric       V = PoisonValue::get(CurTy);
2879e8d8bef9SDimitry Andric       break;
2880*0b57cec5SDimitry Andric     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2881*0b57cec5SDimitry Andric       if (Record.empty())
288281ad6265SDimitry Andric         return error("Invalid settype record");
2883*0b57cec5SDimitry Andric       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
288481ad6265SDimitry Andric         return error("Invalid settype record");
2885*0b57cec5SDimitry Andric       if (TypeList[Record[0]] == VoidType)
2886*0b57cec5SDimitry Andric         return error("Invalid constant type");
288781ad6265SDimitry Andric       CurTyID = Record[0];
288881ad6265SDimitry Andric       CurTy = TypeList[CurTyID];
288981ad6265SDimitry Andric       CurElemTy = getPtrElementTypeByID(CurTyID);
2890*0b57cec5SDimitry Andric       continue;  // Skip the ValueList manipulation.
2891*0b57cec5SDimitry Andric     case bitc::CST_CODE_NULL:      // NULL
28928bcb0991SDimitry Andric       if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
28938bcb0991SDimitry Andric         return error("Invalid type for a constant null value");
2894*0b57cec5SDimitry Andric       V = Constant::getNullValue(CurTy);
2895*0b57cec5SDimitry Andric       break;
2896*0b57cec5SDimitry Andric     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2897*0b57cec5SDimitry Andric       if (!CurTy->isIntegerTy() || Record.empty())
289881ad6265SDimitry Andric         return error("Invalid integer const record");
2899*0b57cec5SDimitry Andric       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2900*0b57cec5SDimitry Andric       break;
2901*0b57cec5SDimitry Andric     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2902*0b57cec5SDimitry Andric       if (!CurTy->isIntegerTy() || Record.empty())
290381ad6265SDimitry Andric         return error("Invalid wide integer const record");
2904*0b57cec5SDimitry Andric 
2905*0b57cec5SDimitry Andric       APInt VInt =
2906*0b57cec5SDimitry Andric           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2907*0b57cec5SDimitry Andric       V = ConstantInt::get(Context, VInt);
2908*0b57cec5SDimitry Andric 
2909*0b57cec5SDimitry Andric       break;
2910*0b57cec5SDimitry Andric     }
2911*0b57cec5SDimitry Andric     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2912*0b57cec5SDimitry Andric       if (Record.empty())
291381ad6265SDimitry Andric         return error("Invalid float const record");
2914*0b57cec5SDimitry Andric       if (CurTy->isHalfTy())
2915*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2916*0b57cec5SDimitry Andric                                              APInt(16, (uint16_t)Record[0])));
29175ffd83dbSDimitry Andric       else if (CurTy->isBFloatTy())
29185ffd83dbSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
29195ffd83dbSDimitry Andric                                              APInt(16, (uint32_t)Record[0])));
2920*0b57cec5SDimitry Andric       else if (CurTy->isFloatTy())
2921*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2922*0b57cec5SDimitry Andric                                              APInt(32, (uint32_t)Record[0])));
2923*0b57cec5SDimitry Andric       else if (CurTy->isDoubleTy())
2924*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2925*0b57cec5SDimitry Andric                                              APInt(64, Record[0])));
2926*0b57cec5SDimitry Andric       else if (CurTy->isX86_FP80Ty()) {
2927*0b57cec5SDimitry Andric         // Bits are not stored the same way as a normal i80 APInt, compensate.
2928*0b57cec5SDimitry Andric         uint64_t Rearrange[2];
2929*0b57cec5SDimitry Andric         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2930*0b57cec5SDimitry Andric         Rearrange[1] = Record[0] >> 48;
2931*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2932*0b57cec5SDimitry Andric                                              APInt(80, Rearrange)));
2933*0b57cec5SDimitry Andric       } else if (CurTy->isFP128Ty())
2934*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2935*0b57cec5SDimitry Andric                                              APInt(128, Record)));
2936*0b57cec5SDimitry Andric       else if (CurTy->isPPC_FP128Ty())
2937*0b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2938*0b57cec5SDimitry Andric                                              APInt(128, Record)));
2939*0b57cec5SDimitry Andric       else
2940*0b57cec5SDimitry Andric         V = UndefValue::get(CurTy);
2941*0b57cec5SDimitry Andric       break;
2942*0b57cec5SDimitry Andric     }
2943*0b57cec5SDimitry Andric 
2944*0b57cec5SDimitry Andric     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2945*0b57cec5SDimitry Andric       if (Record.empty())
294681ad6265SDimitry Andric         return error("Invalid aggregate record");
2947*0b57cec5SDimitry Andric 
2948*0b57cec5SDimitry Andric       unsigned Size = Record.size();
294981ad6265SDimitry Andric       SmallVector<unsigned, 16> Elts;
295081ad6265SDimitry Andric       for (unsigned i = 0; i != Size; ++i)
295181ad6265SDimitry Andric         Elts.push_back(Record[i]);
2952*0b57cec5SDimitry Andric 
295381ad6265SDimitry Andric       if (isa<StructType>(CurTy)) {
295481ad6265SDimitry Andric         V = BitcodeConstant::create(
295581ad6265SDimitry Andric             Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
295681ad6265SDimitry Andric       } else if (isa<ArrayType>(CurTy)) {
295781ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy,
295881ad6265SDimitry Andric                                     BitcodeConstant::ConstantArrayOpcode, Elts);
295981ad6265SDimitry Andric       } else if (isa<VectorType>(CurTy)) {
296081ad6265SDimitry Andric         V = BitcodeConstant::create(
296181ad6265SDimitry Andric             Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
2962*0b57cec5SDimitry Andric       } else {
2963*0b57cec5SDimitry Andric         V = UndefValue::get(CurTy);
2964*0b57cec5SDimitry Andric       }
2965*0b57cec5SDimitry Andric       break;
2966*0b57cec5SDimitry Andric     }
2967*0b57cec5SDimitry Andric     case bitc::CST_CODE_STRING:    // STRING: [values]
2968*0b57cec5SDimitry Andric     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2969*0b57cec5SDimitry Andric       if (Record.empty())
297081ad6265SDimitry Andric         return error("Invalid string record");
2971*0b57cec5SDimitry Andric 
2972*0b57cec5SDimitry Andric       SmallString<16> Elts(Record.begin(), Record.end());
2973*0b57cec5SDimitry Andric       V = ConstantDataArray::getString(Context, Elts,
2974*0b57cec5SDimitry Andric                                        BitCode == bitc::CST_CODE_CSTRING);
2975*0b57cec5SDimitry Andric       break;
2976*0b57cec5SDimitry Andric     }
2977*0b57cec5SDimitry Andric     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2978*0b57cec5SDimitry Andric       if (Record.empty())
297981ad6265SDimitry Andric         return error("Invalid data record");
2980*0b57cec5SDimitry Andric 
29815ffd83dbSDimitry Andric       Type *EltTy;
29825ffd83dbSDimitry Andric       if (auto *Array = dyn_cast<ArrayType>(CurTy))
29835ffd83dbSDimitry Andric         EltTy = Array->getElementType();
29845ffd83dbSDimitry Andric       else
29855ffd83dbSDimitry Andric         EltTy = cast<VectorType>(CurTy)->getElementType();
2986*0b57cec5SDimitry Andric       if (EltTy->isIntegerTy(8)) {
2987*0b57cec5SDimitry Andric         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2988*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
2989*0b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
2990*0b57cec5SDimitry Andric         else
2991*0b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
2992*0b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(16)) {
2993*0b57cec5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2994*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
2995*0b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
2996*0b57cec5SDimitry Andric         else
2997*0b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
2998*0b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(32)) {
2999*0b57cec5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3000*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
3001*0b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
3002*0b57cec5SDimitry Andric         else
3003*0b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
3004*0b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(64)) {
3005*0b57cec5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3006*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
3007*0b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
3008*0b57cec5SDimitry Andric         else
3009*0b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
3010*0b57cec5SDimitry Andric       } else if (EltTy->isHalfTy()) {
3011*0b57cec5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3012*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
30135ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
3014*0b57cec5SDimitry Andric         else
30155ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
30165ffd83dbSDimitry Andric       } else if (EltTy->isBFloatTy()) {
30175ffd83dbSDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
30185ffd83dbSDimitry Andric         if (isa<VectorType>(CurTy))
30195ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
30205ffd83dbSDimitry Andric         else
30215ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
3022*0b57cec5SDimitry Andric       } else if (EltTy->isFloatTy()) {
3023*0b57cec5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3024*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
30255ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
3026*0b57cec5SDimitry Andric         else
30275ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
3028*0b57cec5SDimitry Andric       } else if (EltTy->isDoubleTy()) {
3029*0b57cec5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3030*0b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
30315ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
3032*0b57cec5SDimitry Andric         else
30335ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
3034*0b57cec5SDimitry Andric       } else {
3035*0b57cec5SDimitry Andric         return error("Invalid type for value");
3036*0b57cec5SDimitry Andric       }
3037*0b57cec5SDimitry Andric       break;
3038*0b57cec5SDimitry Andric     }
3039*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_UNOP: {  // CE_UNOP: [opcode, opval]
3040*0b57cec5SDimitry Andric       if (Record.size() < 2)
304181ad6265SDimitry Andric         return error("Invalid unary op constexpr record");
3042*0b57cec5SDimitry Andric       int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
3043*0b57cec5SDimitry Andric       if (Opc < 0) {
3044*0b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown unop.
3045*0b57cec5SDimitry Andric       } else {
304681ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]);
3047*0b57cec5SDimitry Andric       }
3048*0b57cec5SDimitry Andric       break;
3049*0b57cec5SDimitry Andric     }
3050*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
3051*0b57cec5SDimitry Andric       if (Record.size() < 3)
305281ad6265SDimitry Andric         return error("Invalid binary op constexpr record");
3053*0b57cec5SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
3054*0b57cec5SDimitry Andric       if (Opc < 0) {
3055*0b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown binop.
3056*0b57cec5SDimitry Andric       } else {
305781ad6265SDimitry Andric         uint8_t Flags = 0;
3058*0b57cec5SDimitry Andric         if (Record.size() >= 4) {
3059*0b57cec5SDimitry Andric           if (Opc == Instruction::Add ||
3060*0b57cec5SDimitry Andric               Opc == Instruction::Sub ||
3061*0b57cec5SDimitry Andric               Opc == Instruction::Mul ||
3062*0b57cec5SDimitry Andric               Opc == Instruction::Shl) {
3063*0b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3064*0b57cec5SDimitry Andric               Flags |= OverflowingBinaryOperator::NoSignedWrap;
3065*0b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3066*0b57cec5SDimitry Andric               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3067*0b57cec5SDimitry Andric           } else if (Opc == Instruction::SDiv ||
3068*0b57cec5SDimitry Andric                      Opc == Instruction::UDiv ||
3069*0b57cec5SDimitry Andric                      Opc == Instruction::LShr ||
3070*0b57cec5SDimitry Andric                      Opc == Instruction::AShr) {
3071*0b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::PEO_EXACT))
3072*0b57cec5SDimitry Andric               Flags |= SDivOperator::IsExact;
3073*0b57cec5SDimitry Andric           }
3074*0b57cec5SDimitry Andric         }
307581ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags},
307681ad6265SDimitry Andric                                     {(unsigned)Record[1], (unsigned)Record[2]});
3077*0b57cec5SDimitry Andric       }
3078*0b57cec5SDimitry Andric       break;
3079*0b57cec5SDimitry Andric     }
3080*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
3081*0b57cec5SDimitry Andric       if (Record.size() < 3)
308281ad6265SDimitry Andric         return error("Invalid cast constexpr record");
3083*0b57cec5SDimitry Andric       int Opc = getDecodedCastOpcode(Record[0]);
3084*0b57cec5SDimitry Andric       if (Opc < 0) {
3085*0b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown cast.
3086*0b57cec5SDimitry Andric       } else {
308781ad6265SDimitry Andric         unsigned OpTyID = Record[1];
308881ad6265SDimitry Andric         Type *OpTy = getTypeByID(OpTyID);
3089*0b57cec5SDimitry Andric         if (!OpTy)
309081ad6265SDimitry Andric           return error("Invalid cast constexpr record");
309181ad6265SDimitry Andric         V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]);
3092*0b57cec5SDimitry Andric       }
3093*0b57cec5SDimitry Andric       break;
3094*0b57cec5SDimitry Andric     }
3095*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
3096*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
3097*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
3098*0b57cec5SDimitry Andric                                                      // operands]
309981ad6265SDimitry Andric       if (Record.size() < 2)
310081ad6265SDimitry Andric         return error("Constant GEP record must have at least two elements");
3101*0b57cec5SDimitry Andric       unsigned OpNum = 0;
3102*0b57cec5SDimitry Andric       Type *PointeeType = nullptr;
3103*0b57cec5SDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
3104*0b57cec5SDimitry Andric           Record.size() % 2)
3105*0b57cec5SDimitry Andric         PointeeType = getTypeByID(Record[OpNum++]);
3106*0b57cec5SDimitry Andric 
3107*0b57cec5SDimitry Andric       bool InBounds = false;
3108*0b57cec5SDimitry Andric       Optional<unsigned> InRangeIndex;
3109*0b57cec5SDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
3110*0b57cec5SDimitry Andric         uint64_t Op = Record[OpNum++];
3111*0b57cec5SDimitry Andric         InBounds = Op & 1;
3112*0b57cec5SDimitry Andric         InRangeIndex = Op >> 1;
3113*0b57cec5SDimitry Andric       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
3114*0b57cec5SDimitry Andric         InBounds = true;
3115*0b57cec5SDimitry Andric 
311681ad6265SDimitry Andric       SmallVector<unsigned, 16> Elts;
311781ad6265SDimitry Andric       unsigned BaseTypeID = Record[OpNum];
3118*0b57cec5SDimitry Andric       while (OpNum != Record.size()) {
311981ad6265SDimitry Andric         unsigned ElTyID = Record[OpNum++];
312081ad6265SDimitry Andric         Type *ElTy = getTypeByID(ElTyID);
3121*0b57cec5SDimitry Andric         if (!ElTy)
312281ad6265SDimitry Andric           return error("Invalid getelementptr constexpr record");
312381ad6265SDimitry Andric         Elts.push_back(Record[OpNum++]);
3124*0b57cec5SDimitry Andric       }
3125*0b57cec5SDimitry Andric 
3126*0b57cec5SDimitry Andric       if (Elts.size() < 1)
3127*0b57cec5SDimitry Andric         return error("Invalid gep with no operands");
3128*0b57cec5SDimitry Andric 
312981ad6265SDimitry Andric       Type *BaseType = getTypeByID(BaseTypeID);
313081ad6265SDimitry Andric       if (isa<VectorType>(BaseType)) {
313181ad6265SDimitry Andric         BaseTypeID = getContainedTypeID(BaseTypeID, 0);
313281ad6265SDimitry Andric         BaseType = getTypeByID(BaseTypeID);
313381ad6265SDimitry Andric       }
313481ad6265SDimitry Andric 
313581ad6265SDimitry Andric       PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType);
313681ad6265SDimitry Andric       if (!OrigPtrTy)
313781ad6265SDimitry Andric         return error("GEP base operand must be pointer or vector of pointer");
313881ad6265SDimitry Andric 
313981ad6265SDimitry Andric       if (!PointeeType) {
314081ad6265SDimitry Andric         PointeeType = getPtrElementTypeByID(BaseTypeID);
3141*0b57cec5SDimitry Andric         if (!PointeeType)
314281ad6265SDimitry Andric           return error("Missing element type for old-style constant GEP");
314381ad6265SDimitry Andric       } else if (!OrigPtrTy->isOpaqueOrPointeeTypeMatches(PointeeType))
3144*0b57cec5SDimitry Andric         return error("Explicit gep operator type does not match pointee type "
3145*0b57cec5SDimitry Andric                      "of pointer operand");
3146*0b57cec5SDimitry Andric 
314781ad6265SDimitry Andric       V = BitcodeConstant::create(Alloc, CurTy,
314881ad6265SDimitry Andric                                   {Instruction::GetElementPtr, InBounds,
314981ad6265SDimitry Andric                                    InRangeIndex.value_or(-1), PointeeType},
315081ad6265SDimitry Andric                                   Elts);
3151*0b57cec5SDimitry Andric       break;
3152*0b57cec5SDimitry Andric     }
3153*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
3154*0b57cec5SDimitry Andric       if (Record.size() < 3)
315581ad6265SDimitry Andric         return error("Invalid select constexpr record");
3156*0b57cec5SDimitry Andric 
315781ad6265SDimitry Andric       V = BitcodeConstant::create(
315881ad6265SDimitry Andric           Alloc, CurTy, Instruction::Select,
315981ad6265SDimitry Andric           {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
316081ad6265SDimitry Andric       break;
3161*0b57cec5SDimitry Andric     }
3162*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_EXTRACTELT
3163*0b57cec5SDimitry Andric         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3164*0b57cec5SDimitry Andric       if (Record.size() < 3)
316581ad6265SDimitry Andric         return error("Invalid extractelement constexpr record");
316681ad6265SDimitry Andric       unsigned OpTyID = Record[0];
3167*0b57cec5SDimitry Andric       VectorType *OpTy =
316881ad6265SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
3169*0b57cec5SDimitry Andric       if (!OpTy)
317081ad6265SDimitry Andric         return error("Invalid extractelement constexpr record");
317181ad6265SDimitry Andric       unsigned IdxRecord;
3172*0b57cec5SDimitry Andric       if (Record.size() == 4) {
317381ad6265SDimitry Andric         unsigned IdxTyID = Record[2];
317481ad6265SDimitry Andric         Type *IdxTy = getTypeByID(IdxTyID);
3175*0b57cec5SDimitry Andric         if (!IdxTy)
317681ad6265SDimitry Andric           return error("Invalid extractelement constexpr record");
317781ad6265SDimitry Andric         IdxRecord = Record[3];
31785ffd83dbSDimitry Andric       } else {
31795ffd83dbSDimitry Andric         // Deprecated, but still needed to read old bitcode files.
318081ad6265SDimitry Andric         IdxRecord = Record[2];
31815ffd83dbSDimitry Andric       }
318281ad6265SDimitry Andric       V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
318381ad6265SDimitry Andric                                   {(unsigned)Record[1], IdxRecord});
3184*0b57cec5SDimitry Andric       break;
3185*0b57cec5SDimitry Andric     }
3186*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_INSERTELT
3187*0b57cec5SDimitry Andric         : { // CE_INSERTELT: [opval, opval, opty, opval]
3188*0b57cec5SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3189*0b57cec5SDimitry Andric       if (Record.size() < 3 || !OpTy)
319081ad6265SDimitry Andric         return error("Invalid insertelement constexpr record");
319181ad6265SDimitry Andric       unsigned IdxRecord;
3192*0b57cec5SDimitry Andric       if (Record.size() == 4) {
319381ad6265SDimitry Andric         unsigned IdxTyID = Record[2];
319481ad6265SDimitry Andric         Type *IdxTy = getTypeByID(IdxTyID);
3195*0b57cec5SDimitry Andric         if (!IdxTy)
319681ad6265SDimitry Andric           return error("Invalid insertelement constexpr record");
319781ad6265SDimitry Andric         IdxRecord = Record[3];
31985ffd83dbSDimitry Andric       } else {
31995ffd83dbSDimitry Andric         // Deprecated, but still needed to read old bitcode files.
320081ad6265SDimitry Andric         IdxRecord = Record[2];
32015ffd83dbSDimitry Andric       }
320281ad6265SDimitry Andric       V = BitcodeConstant::create(
320381ad6265SDimitry Andric           Alloc, CurTy, Instruction::InsertElement,
320481ad6265SDimitry Andric           {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
3205*0b57cec5SDimitry Andric       break;
3206*0b57cec5SDimitry Andric     }
3207*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
3208*0b57cec5SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3209*0b57cec5SDimitry Andric       if (Record.size() < 3 || !OpTy)
321081ad6265SDimitry Andric         return error("Invalid shufflevector constexpr record");
321181ad6265SDimitry Andric       V = BitcodeConstant::create(
321281ad6265SDimitry Andric           Alloc, CurTy, Instruction::ShuffleVector,
321381ad6265SDimitry Andric           {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
321481ad6265SDimitry Andric       break;
3215*0b57cec5SDimitry Andric     }
3216*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
3217*0b57cec5SDimitry Andric       VectorType *RTy = dyn_cast<VectorType>(CurTy);
3218*0b57cec5SDimitry Andric       VectorType *OpTy =
3219*0b57cec5SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3220*0b57cec5SDimitry Andric       if (Record.size() < 4 || !RTy || !OpTy)
322181ad6265SDimitry Andric         return error("Invalid shufflevector constexpr record");
322281ad6265SDimitry Andric       V = BitcodeConstant::create(
322381ad6265SDimitry Andric           Alloc, CurTy, Instruction::ShuffleVector,
322481ad6265SDimitry Andric           {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]});
322581ad6265SDimitry Andric       break;
3226*0b57cec5SDimitry Andric     }
3227*0b57cec5SDimitry Andric     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
3228*0b57cec5SDimitry Andric       if (Record.size() < 4)
322981ad6265SDimitry Andric         return error("Invalid cmp constexpt record");
323081ad6265SDimitry Andric       unsigned OpTyID = Record[0];
323181ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
3232*0b57cec5SDimitry Andric       if (!OpTy)
323381ad6265SDimitry Andric         return error("Invalid cmp constexpr record");
323481ad6265SDimitry Andric       V = BitcodeConstant::create(
323581ad6265SDimitry Andric           Alloc, CurTy,
323681ad6265SDimitry Andric           {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
323781ad6265SDimitry Andric                                               : Instruction::ICmp),
323881ad6265SDimitry Andric            (uint8_t)Record[3]},
323981ad6265SDimitry Andric           {(unsigned)Record[1], (unsigned)Record[2]});
3240*0b57cec5SDimitry Andric       break;
3241*0b57cec5SDimitry Andric     }
3242*0b57cec5SDimitry Andric     // This maintains backward compatibility, pre-asm dialect keywords.
32435ffd83dbSDimitry Andric     // Deprecated, but still needed to read old bitcode files.
3244*0b57cec5SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD: {
3245*0b57cec5SDimitry Andric       if (Record.size() < 2)
324681ad6265SDimitry Andric         return error("Invalid inlineasm record");
3247*0b57cec5SDimitry Andric       std::string AsmStr, ConstrStr;
3248*0b57cec5SDimitry Andric       bool HasSideEffects = Record[0] & 1;
3249*0b57cec5SDimitry Andric       bool IsAlignStack = Record[0] >> 1;
3250*0b57cec5SDimitry Andric       unsigned AsmStrSize = Record[1];
3251*0b57cec5SDimitry Andric       if (2+AsmStrSize >= Record.size())
325281ad6265SDimitry Andric         return error("Invalid inlineasm record");
3253*0b57cec5SDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
3254*0b57cec5SDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
325581ad6265SDimitry Andric         return error("Invalid inlineasm record");
3256*0b57cec5SDimitry Andric 
3257*0b57cec5SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
3258*0b57cec5SDimitry Andric         AsmStr += (char)Record[2+i];
3259*0b57cec5SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
3260*0b57cec5SDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
3261*0b57cec5SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
326281ad6265SDimitry Andric       if (!CurElemTy)
326381ad6265SDimitry Andric         return error("Missing element type for old-style inlineasm");
326481ad6265SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
326581ad6265SDimitry Andric                          HasSideEffects, IsAlignStack);
3266*0b57cec5SDimitry Andric       break;
3267*0b57cec5SDimitry Andric     }
3268*0b57cec5SDimitry Andric     // This version adds support for the asm dialect keywords (e.g.,
3269*0b57cec5SDimitry Andric     // inteldialect).
3270fe6060f1SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD2: {
3271*0b57cec5SDimitry Andric       if (Record.size() < 2)
327281ad6265SDimitry Andric         return error("Invalid inlineasm record");
3273*0b57cec5SDimitry Andric       std::string AsmStr, ConstrStr;
3274*0b57cec5SDimitry Andric       bool HasSideEffects = Record[0] & 1;
3275*0b57cec5SDimitry Andric       bool IsAlignStack = (Record[0] >> 1) & 1;
3276*0b57cec5SDimitry Andric       unsigned AsmDialect = Record[0] >> 2;
3277*0b57cec5SDimitry Andric       unsigned AsmStrSize = Record[1];
3278*0b57cec5SDimitry Andric       if (2+AsmStrSize >= Record.size())
327981ad6265SDimitry Andric         return error("Invalid inlineasm record");
3280*0b57cec5SDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
3281*0b57cec5SDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
328281ad6265SDimitry Andric         return error("Invalid inlineasm record");
3283*0b57cec5SDimitry Andric 
3284*0b57cec5SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
3285*0b57cec5SDimitry Andric         AsmStr += (char)Record[2+i];
3286*0b57cec5SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
3287*0b57cec5SDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
3288*0b57cec5SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
328981ad6265SDimitry Andric       if (!CurElemTy)
329081ad6265SDimitry Andric         return error("Missing element type for old-style inlineasm");
329181ad6265SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
329281ad6265SDimitry Andric                          HasSideEffects, IsAlignStack,
3293*0b57cec5SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect));
3294*0b57cec5SDimitry Andric       break;
3295*0b57cec5SDimitry Andric     }
3296fe6060f1SDimitry Andric     // This version adds support for the unwind keyword.
329704eeddc0SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD3: {
3298fe6060f1SDimitry Andric       if (Record.size() < 2)
329981ad6265SDimitry Andric         return error("Invalid inlineasm record");
330004eeddc0SDimitry Andric       unsigned OpNum = 0;
3301fe6060f1SDimitry Andric       std::string AsmStr, ConstrStr;
330204eeddc0SDimitry Andric       bool HasSideEffects = Record[OpNum] & 1;
330304eeddc0SDimitry Andric       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
330404eeddc0SDimitry Andric       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
330504eeddc0SDimitry Andric       bool CanThrow = (Record[OpNum] >> 3) & 1;
330604eeddc0SDimitry Andric       ++OpNum;
330704eeddc0SDimitry Andric       unsigned AsmStrSize = Record[OpNum];
330804eeddc0SDimitry Andric       ++OpNum;
330904eeddc0SDimitry Andric       if (OpNum + AsmStrSize >= Record.size())
331081ad6265SDimitry Andric         return error("Invalid inlineasm record");
331104eeddc0SDimitry Andric       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
331204eeddc0SDimitry Andric       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
331381ad6265SDimitry Andric         return error("Invalid inlineasm record");
3314fe6060f1SDimitry Andric 
3315fe6060f1SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
331604eeddc0SDimitry Andric         AsmStr += (char)Record[OpNum + i];
331704eeddc0SDimitry Andric       ++OpNum;
3318fe6060f1SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
331904eeddc0SDimitry Andric         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3320fe6060f1SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
332181ad6265SDimitry Andric       if (!CurElemTy)
332281ad6265SDimitry Andric         return error("Missing element type for old-style inlineasm");
332381ad6265SDimitry Andric       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
332481ad6265SDimitry Andric                          HasSideEffects, IsAlignStack,
3325fe6060f1SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
3326fe6060f1SDimitry Andric       break;
3327fe6060f1SDimitry Andric     }
332804eeddc0SDimitry Andric     // This version adds explicit function type.
332904eeddc0SDimitry Andric     case bitc::CST_CODE_INLINEASM: {
333004eeddc0SDimitry Andric       if (Record.size() < 3)
333181ad6265SDimitry Andric         return error("Invalid inlineasm record");
333204eeddc0SDimitry Andric       unsigned OpNum = 0;
333304eeddc0SDimitry Andric       auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
333404eeddc0SDimitry Andric       ++OpNum;
333504eeddc0SDimitry Andric       if (!FnTy)
333681ad6265SDimitry Andric         return error("Invalid inlineasm record");
333704eeddc0SDimitry Andric       std::string AsmStr, ConstrStr;
333804eeddc0SDimitry Andric       bool HasSideEffects = Record[OpNum] & 1;
333904eeddc0SDimitry Andric       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
334004eeddc0SDimitry Andric       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
334104eeddc0SDimitry Andric       bool CanThrow = (Record[OpNum] >> 3) & 1;
334204eeddc0SDimitry Andric       ++OpNum;
334304eeddc0SDimitry Andric       unsigned AsmStrSize = Record[OpNum];
334404eeddc0SDimitry Andric       ++OpNum;
334504eeddc0SDimitry Andric       if (OpNum + AsmStrSize >= Record.size())
334681ad6265SDimitry Andric         return error("Invalid inlineasm record");
334704eeddc0SDimitry Andric       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
334804eeddc0SDimitry Andric       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
334981ad6265SDimitry Andric         return error("Invalid inlineasm record");
335004eeddc0SDimitry Andric 
335104eeddc0SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
335204eeddc0SDimitry Andric         AsmStr += (char)Record[OpNum + i];
335304eeddc0SDimitry Andric       ++OpNum;
335404eeddc0SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
335504eeddc0SDimitry Andric         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
335604eeddc0SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
335704eeddc0SDimitry Andric       V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
335804eeddc0SDimitry Andric                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
335904eeddc0SDimitry Andric       break;
336004eeddc0SDimitry Andric     }
3361*0b57cec5SDimitry Andric     case bitc::CST_CODE_BLOCKADDRESS:{
3362*0b57cec5SDimitry Andric       if (Record.size() < 3)
336381ad6265SDimitry Andric         return error("Invalid blockaddress record");
336481ad6265SDimitry Andric       unsigned FnTyID = Record[0];
336581ad6265SDimitry Andric       Type *FnTy = getTypeByID(FnTyID);
3366*0b57cec5SDimitry Andric       if (!FnTy)
336781ad6265SDimitry Andric         return error("Invalid blockaddress record");
336881ad6265SDimitry Andric       V = BitcodeConstant::create(
336981ad6265SDimitry Andric           Alloc, CurTy,
337081ad6265SDimitry Andric           {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
337181ad6265SDimitry Andric           Record[1]);
3372*0b57cec5SDimitry Andric       break;
3373*0b57cec5SDimitry Andric     }
3374fe6060f1SDimitry Andric     case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
3375fe6060f1SDimitry Andric       if (Record.size() < 2)
337681ad6265SDimitry Andric         return error("Invalid dso_local record");
337781ad6265SDimitry Andric       unsigned GVTyID = Record[0];
337881ad6265SDimitry Andric       Type *GVTy = getTypeByID(GVTyID);
3379fe6060f1SDimitry Andric       if (!GVTy)
338081ad6265SDimitry Andric         return error("Invalid dso_local record");
338181ad6265SDimitry Andric       V = BitcodeConstant::create(
338281ad6265SDimitry Andric           Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3383fe6060f1SDimitry Andric       break;
3384fe6060f1SDimitry Andric     }
33850eae32dcSDimitry Andric     case bitc::CST_CODE_NO_CFI_VALUE: {
33860eae32dcSDimitry Andric       if (Record.size() < 2)
338781ad6265SDimitry Andric         return error("Invalid no_cfi record");
338881ad6265SDimitry Andric       unsigned GVTyID = Record[0];
338981ad6265SDimitry Andric       Type *GVTy = getTypeByID(GVTyID);
33900eae32dcSDimitry Andric       if (!GVTy)
339181ad6265SDimitry Andric         return error("Invalid no_cfi record");
339281ad6265SDimitry Andric       V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
339381ad6265SDimitry Andric                                   Record[1]);
33940eae32dcSDimitry Andric       break;
33950eae32dcSDimitry Andric     }
3396*0b57cec5SDimitry Andric     }
3397*0b57cec5SDimitry Andric 
339881ad6265SDimitry Andric     assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
339981ad6265SDimitry Andric     if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))
340081ad6265SDimitry Andric       return Err;
3401*0b57cec5SDimitry Andric     ++NextCstNo;
3402*0b57cec5SDimitry Andric   }
3403*0b57cec5SDimitry Andric }
3404*0b57cec5SDimitry Andric 
3405*0b57cec5SDimitry Andric Error BitcodeReader::parseUseLists() {
3406*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3407*0b57cec5SDimitry Andric     return Err;
3408*0b57cec5SDimitry Andric 
3409*0b57cec5SDimitry Andric   // Read all the records.
3410*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
3411*0b57cec5SDimitry Andric 
3412*0b57cec5SDimitry Andric   while (true) {
3413*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3414*0b57cec5SDimitry Andric     if (!MaybeEntry)
3415*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
3416*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
3417*0b57cec5SDimitry Andric 
3418*0b57cec5SDimitry Andric     switch (Entry.Kind) {
3419*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
3420*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
3421*0b57cec5SDimitry Andric       return error("Malformed block");
3422*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
3423*0b57cec5SDimitry Andric       return Error::success();
3424*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
3425*0b57cec5SDimitry Andric       // The interesting case.
3426*0b57cec5SDimitry Andric       break;
3427*0b57cec5SDimitry Andric     }
3428*0b57cec5SDimitry Andric 
3429*0b57cec5SDimitry Andric     // Read a use list record.
3430*0b57cec5SDimitry Andric     Record.clear();
3431*0b57cec5SDimitry Andric     bool IsBB = false;
3432*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3433*0b57cec5SDimitry Andric     if (!MaybeRecord)
3434*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
3435*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
3436*0b57cec5SDimitry Andric     default:  // Default behavior: unknown type.
3437*0b57cec5SDimitry Andric       break;
3438*0b57cec5SDimitry Andric     case bitc::USELIST_CODE_BB:
3439*0b57cec5SDimitry Andric       IsBB = true;
3440*0b57cec5SDimitry Andric       LLVM_FALLTHROUGH;
3441*0b57cec5SDimitry Andric     case bitc::USELIST_CODE_DEFAULT: {
3442*0b57cec5SDimitry Andric       unsigned RecordLength = Record.size();
3443*0b57cec5SDimitry Andric       if (RecordLength < 3)
3444*0b57cec5SDimitry Andric         // Records should have at least an ID and two indexes.
3445*0b57cec5SDimitry Andric         return error("Invalid record");
3446e8d8bef9SDimitry Andric       unsigned ID = Record.pop_back_val();
3447*0b57cec5SDimitry Andric 
3448*0b57cec5SDimitry Andric       Value *V;
3449*0b57cec5SDimitry Andric       if (IsBB) {
3450*0b57cec5SDimitry Andric         assert(ID < FunctionBBs.size() && "Basic block not found");
3451*0b57cec5SDimitry Andric         V = FunctionBBs[ID];
3452*0b57cec5SDimitry Andric       } else
3453*0b57cec5SDimitry Andric         V = ValueList[ID];
3454*0b57cec5SDimitry Andric       unsigned NumUses = 0;
3455*0b57cec5SDimitry Andric       SmallDenseMap<const Use *, unsigned, 16> Order;
3456*0b57cec5SDimitry Andric       for (const Use &U : V->materialized_uses()) {
3457*0b57cec5SDimitry Andric         if (++NumUses > Record.size())
3458*0b57cec5SDimitry Andric           break;
3459*0b57cec5SDimitry Andric         Order[&U] = Record[NumUses - 1];
3460*0b57cec5SDimitry Andric       }
3461*0b57cec5SDimitry Andric       if (Order.size() != Record.size() || NumUses > Record.size())
3462*0b57cec5SDimitry Andric         // Mismatches can happen if the functions are being materialized lazily
3463*0b57cec5SDimitry Andric         // (out-of-order), or a value has been upgraded.
3464*0b57cec5SDimitry Andric         break;
3465*0b57cec5SDimitry Andric 
3466*0b57cec5SDimitry Andric       V->sortUseList([&](const Use &L, const Use &R) {
3467*0b57cec5SDimitry Andric         return Order.lookup(&L) < Order.lookup(&R);
3468*0b57cec5SDimitry Andric       });
3469*0b57cec5SDimitry Andric       break;
3470*0b57cec5SDimitry Andric     }
3471*0b57cec5SDimitry Andric     }
3472*0b57cec5SDimitry Andric   }
3473*0b57cec5SDimitry Andric }
3474*0b57cec5SDimitry Andric 
3475*0b57cec5SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it.
3476*0b57cec5SDimitry Andric /// This lets us lazily deserialize the metadata.
3477*0b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() {
3478*0b57cec5SDimitry Andric   // Save the current stream state.
3479*0b57cec5SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
3480*0b57cec5SDimitry Andric   DeferredMetadataInfo.push_back(CurBit);
3481*0b57cec5SDimitry Andric 
3482*0b57cec5SDimitry Andric   // Skip over the block for now.
3483*0b57cec5SDimitry Andric   if (Error Err = Stream.SkipBlock())
3484*0b57cec5SDimitry Andric     return Err;
3485*0b57cec5SDimitry Andric   return Error::success();
3486*0b57cec5SDimitry Andric }
3487*0b57cec5SDimitry Andric 
3488*0b57cec5SDimitry Andric Error BitcodeReader::materializeMetadata() {
3489*0b57cec5SDimitry Andric   for (uint64_t BitPos : DeferredMetadataInfo) {
3490*0b57cec5SDimitry Andric     // Move the bit stream to the saved position.
3491*0b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(BitPos))
3492*0b57cec5SDimitry Andric       return JumpFailed;
3493*0b57cec5SDimitry Andric     if (Error Err = MDLoader->parseModuleMetadata())
3494*0b57cec5SDimitry Andric       return Err;
3495*0b57cec5SDimitry Andric   }
3496*0b57cec5SDimitry Andric 
3497*0b57cec5SDimitry Andric   // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3498e8d8bef9SDimitry Andric   // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3499e8d8bef9SDimitry Andric   // multiple times.
3500e8d8bef9SDimitry Andric   if (!TheModule->getNamedMetadata("llvm.linker.options")) {
3501*0b57cec5SDimitry Andric     if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
3502*0b57cec5SDimitry Andric       NamedMDNode *LinkerOpts =
3503*0b57cec5SDimitry Andric           TheModule->getOrInsertNamedMetadata("llvm.linker.options");
3504*0b57cec5SDimitry Andric       for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3505*0b57cec5SDimitry Andric         LinkerOpts->addOperand(cast<MDNode>(MDOptions));
3506*0b57cec5SDimitry Andric     }
3507e8d8bef9SDimitry Andric   }
3508*0b57cec5SDimitry Andric 
3509*0b57cec5SDimitry Andric   DeferredMetadataInfo.clear();
3510*0b57cec5SDimitry Andric   return Error::success();
3511*0b57cec5SDimitry Andric }
3512*0b57cec5SDimitry Andric 
3513*0b57cec5SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3514*0b57cec5SDimitry Andric 
3515*0b57cec5SDimitry Andric /// When we see the block for a function body, remember where it is and then
3516*0b57cec5SDimitry Andric /// skip it.  This lets us lazily deserialize the functions.
3517*0b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() {
3518*0b57cec5SDimitry Andric   // Get the function we are talking about.
3519*0b57cec5SDimitry Andric   if (FunctionsWithBodies.empty())
3520*0b57cec5SDimitry Andric     return error("Insufficient function protos");
3521*0b57cec5SDimitry Andric 
3522*0b57cec5SDimitry Andric   Function *Fn = FunctionsWithBodies.back();
3523*0b57cec5SDimitry Andric   FunctionsWithBodies.pop_back();
3524*0b57cec5SDimitry Andric 
3525*0b57cec5SDimitry Andric   // Save the current stream state.
3526*0b57cec5SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
3527*0b57cec5SDimitry Andric   assert(
3528*0b57cec5SDimitry Andric       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3529*0b57cec5SDimitry Andric       "Mismatch between VST and scanned function offsets");
3530*0b57cec5SDimitry Andric   DeferredFunctionInfo[Fn] = CurBit;
3531*0b57cec5SDimitry Andric 
3532*0b57cec5SDimitry Andric   // Skip over the function block for now.
3533*0b57cec5SDimitry Andric   if (Error Err = Stream.SkipBlock())
3534*0b57cec5SDimitry Andric     return Err;
3535*0b57cec5SDimitry Andric   return Error::success();
3536*0b57cec5SDimitry Andric }
3537*0b57cec5SDimitry Andric 
3538*0b57cec5SDimitry Andric Error BitcodeReader::globalCleanup() {
3539*0b57cec5SDimitry Andric   // Patch the initializers for globals and aliases up.
3540*0b57cec5SDimitry Andric   if (Error Err = resolveGlobalAndIndirectSymbolInits())
3541*0b57cec5SDimitry Andric     return Err;
3542*0b57cec5SDimitry Andric   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3543*0b57cec5SDimitry Andric     return error("Malformed global initializer set");
3544*0b57cec5SDimitry Andric 
3545*0b57cec5SDimitry Andric   // Look for intrinsic functions which need to be upgraded at some point
35465ffd83dbSDimitry Andric   // and functions that need to have their function attributes upgraded.
3547*0b57cec5SDimitry Andric   for (Function &F : *TheModule) {
3548*0b57cec5SDimitry Andric     MDLoader->upgradeDebugIntrinsics(F);
3549*0b57cec5SDimitry Andric     Function *NewFn;
3550*0b57cec5SDimitry Andric     if (UpgradeIntrinsicFunction(&F, NewFn))
3551*0b57cec5SDimitry Andric       UpgradedIntrinsics[&F] = NewFn;
3552*0b57cec5SDimitry Andric     else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3553*0b57cec5SDimitry Andric       // Some types could be renamed during loading if several modules are
3554*0b57cec5SDimitry Andric       // loaded in the same LLVMContext (LTO scenario). In this case we should
3555*0b57cec5SDimitry Andric       // remangle intrinsics names as well.
355681ad6265SDimitry Andric       RemangledIntrinsics[&F] = *Remangled;
35575ffd83dbSDimitry Andric     // Look for functions that rely on old function attribute behavior.
35585ffd83dbSDimitry Andric     UpgradeFunctionAttributes(F);
3559*0b57cec5SDimitry Andric   }
3560*0b57cec5SDimitry Andric 
3561*0b57cec5SDimitry Andric   // Look for global variables which need to be renamed.
3562*0b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3563*0b57cec5SDimitry Andric   for (GlobalVariable &GV : TheModule->globals())
3564*0b57cec5SDimitry Andric     if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
3565*0b57cec5SDimitry Andric       UpgradedVariables.emplace_back(&GV, Upgraded);
3566*0b57cec5SDimitry Andric   for (auto &Pair : UpgradedVariables) {
3567*0b57cec5SDimitry Andric     Pair.first->eraseFromParent();
3568*0b57cec5SDimitry Andric     TheModule->getGlobalList().push_back(Pair.second);
3569*0b57cec5SDimitry Andric   }
3570*0b57cec5SDimitry Andric 
3571*0b57cec5SDimitry Andric   // Force deallocation of memory for these vectors to favor the client that
3572*0b57cec5SDimitry Andric   // want lazy deserialization.
3573*0b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3574349cc55cSDimitry Andric   std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
3575*0b57cec5SDimitry Andric   return Error::success();
3576*0b57cec5SDimitry Andric }
3577*0b57cec5SDimitry Andric 
3578*0b57cec5SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we
3579*0b57cec5SDimitry Andric /// either have an old bitcode file without a VST forward declaration record,
3580*0b57cec5SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous
3581*0b57cec5SDimitry Andric /// functions do not have a name and are therefore not in the VST.
3582*0b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() {
3583*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3584*0b57cec5SDimitry Andric     return JumpFailed;
3585*0b57cec5SDimitry Andric 
3586*0b57cec5SDimitry Andric   if (Stream.AtEndOfStream())
3587*0b57cec5SDimitry Andric     return error("Could not find function in stream");
3588*0b57cec5SDimitry Andric 
3589*0b57cec5SDimitry Andric   if (!SeenFirstFunctionBody)
3590*0b57cec5SDimitry Andric     return error("Trying to materialize functions before seeing function blocks");
3591*0b57cec5SDimitry Andric 
3592*0b57cec5SDimitry Andric   // An old bitcode file with the symbol table at the end would have
3593*0b57cec5SDimitry Andric   // finished the parse greedily.
3594*0b57cec5SDimitry Andric   assert(SeenValueSymbolTable);
3595*0b57cec5SDimitry Andric 
3596*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
3597*0b57cec5SDimitry Andric 
3598*0b57cec5SDimitry Andric   while (true) {
3599*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3600*0b57cec5SDimitry Andric     if (!MaybeEntry)
3601*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
3602*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
3603*0b57cec5SDimitry Andric 
3604*0b57cec5SDimitry Andric     switch (Entry.Kind) {
3605*0b57cec5SDimitry Andric     default:
3606*0b57cec5SDimitry Andric       return error("Expect SubBlock");
3607*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
3608*0b57cec5SDimitry Andric       switch (Entry.ID) {
3609*0b57cec5SDimitry Andric       default:
3610*0b57cec5SDimitry Andric         return error("Expect function block");
3611*0b57cec5SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
3612*0b57cec5SDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
3613*0b57cec5SDimitry Andric           return Err;
3614*0b57cec5SDimitry Andric         NextUnreadBit = Stream.GetCurrentBitNo();
3615*0b57cec5SDimitry Andric         return Error::success();
3616*0b57cec5SDimitry Andric       }
3617*0b57cec5SDimitry Andric     }
3618*0b57cec5SDimitry Andric   }
3619*0b57cec5SDimitry Andric }
3620*0b57cec5SDimitry Andric 
362181ad6265SDimitry Andric Error BitcodeReaderBase::readBlockInfo() {
3622*0b57cec5SDimitry Andric   Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
3623*0b57cec5SDimitry Andric       Stream.ReadBlockInfoBlock();
3624*0b57cec5SDimitry Andric   if (!MaybeNewBlockInfo)
362581ad6265SDimitry Andric     return MaybeNewBlockInfo.takeError();
3626*0b57cec5SDimitry Andric   Optional<BitstreamBlockInfo> NewBlockInfo =
3627*0b57cec5SDimitry Andric       std::move(MaybeNewBlockInfo.get());
3628*0b57cec5SDimitry Andric   if (!NewBlockInfo)
362981ad6265SDimitry Andric     return error("Malformed block");
3630*0b57cec5SDimitry Andric   BlockInfo = std::move(*NewBlockInfo);
363181ad6265SDimitry Andric   return Error::success();
3632*0b57cec5SDimitry Andric }
3633*0b57cec5SDimitry Andric 
3634*0b57cec5SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
3635*0b57cec5SDimitry Andric   // v1: [selection_kind, name]
3636*0b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, selection_kind]
3637*0b57cec5SDimitry Andric   StringRef Name;
3638*0b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
3639*0b57cec5SDimitry Andric 
3640*0b57cec5SDimitry Andric   if (Record.empty())
3641*0b57cec5SDimitry Andric     return error("Invalid record");
3642*0b57cec5SDimitry Andric   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3643*0b57cec5SDimitry Andric   std::string OldFormatName;
3644*0b57cec5SDimitry Andric   if (!UseStrtab) {
3645*0b57cec5SDimitry Andric     if (Record.size() < 2)
3646*0b57cec5SDimitry Andric       return error("Invalid record");
3647*0b57cec5SDimitry Andric     unsigned ComdatNameSize = Record[1];
364881ad6265SDimitry Andric     if (ComdatNameSize > Record.size() - 2)
364981ad6265SDimitry Andric       return error("Comdat name size too large");
3650*0b57cec5SDimitry Andric     OldFormatName.reserve(ComdatNameSize);
3651*0b57cec5SDimitry Andric     for (unsigned i = 0; i != ComdatNameSize; ++i)
3652*0b57cec5SDimitry Andric       OldFormatName += (char)Record[2 + i];
3653*0b57cec5SDimitry Andric     Name = OldFormatName;
3654*0b57cec5SDimitry Andric   }
3655*0b57cec5SDimitry Andric   Comdat *C = TheModule->getOrInsertComdat(Name);
3656*0b57cec5SDimitry Andric   C->setSelectionKind(SK);
3657*0b57cec5SDimitry Andric   ComdatList.push_back(C);
3658*0b57cec5SDimitry Andric   return Error::success();
3659*0b57cec5SDimitry Andric }
3660*0b57cec5SDimitry Andric 
3661*0b57cec5SDimitry Andric static void inferDSOLocal(GlobalValue *GV) {
3662*0b57cec5SDimitry Andric   // infer dso_local from linkage and visibility if it is not encoded.
3663*0b57cec5SDimitry Andric   if (GV->hasLocalLinkage() ||
3664*0b57cec5SDimitry Andric       (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
3665*0b57cec5SDimitry Andric     GV->setDSOLocal(true);
3666*0b57cec5SDimitry Andric }
3667*0b57cec5SDimitry Andric 
366881ad6265SDimitry Andric GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) {
366981ad6265SDimitry Andric   GlobalValue::SanitizerMetadata Meta;
367081ad6265SDimitry Andric   if (V & (1 << 0))
367181ad6265SDimitry Andric     Meta.NoAddress = true;
367281ad6265SDimitry Andric   if (V & (1 << 1))
367381ad6265SDimitry Andric     Meta.NoHWAddress = true;
367481ad6265SDimitry Andric   if (V & (1 << 2))
367581ad6265SDimitry Andric     Meta.NoMemtag = true;
367681ad6265SDimitry Andric   if (V & (1 << 3))
367781ad6265SDimitry Andric     Meta.IsDynInit = true;
367881ad6265SDimitry Andric   return Meta;
367981ad6265SDimitry Andric }
368081ad6265SDimitry Andric 
3681*0b57cec5SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
3682*0b57cec5SDimitry Andric   // v1: [pointer type, isconst, initid, linkage, alignment, section,
3683*0b57cec5SDimitry Andric   // visibility, threadlocal, unnamed_addr, externally_initialized,
3684*0b57cec5SDimitry Andric   // dllstorageclass, comdat, attributes, preemption specifier,
3685*0b57cec5SDimitry Andric   // partition strtab offset, partition strtab size] (name in VST)
3686*0b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
3687*0b57cec5SDimitry Andric   StringRef Name;
3688*0b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
3689*0b57cec5SDimitry Andric 
3690*0b57cec5SDimitry Andric   if (Record.size() < 6)
3691*0b57cec5SDimitry Andric     return error("Invalid record");
369281ad6265SDimitry Andric   unsigned TyID = Record[0];
369381ad6265SDimitry Andric   Type *Ty = getTypeByID(TyID);
3694*0b57cec5SDimitry Andric   if (!Ty)
3695*0b57cec5SDimitry Andric     return error("Invalid record");
3696*0b57cec5SDimitry Andric   bool isConstant = Record[1] & 1;
3697*0b57cec5SDimitry Andric   bool explicitType = Record[1] & 2;
3698*0b57cec5SDimitry Andric   unsigned AddressSpace;
3699*0b57cec5SDimitry Andric   if (explicitType) {
3700*0b57cec5SDimitry Andric     AddressSpace = Record[1] >> 2;
3701*0b57cec5SDimitry Andric   } else {
3702*0b57cec5SDimitry Andric     if (!Ty->isPointerTy())
3703*0b57cec5SDimitry Andric       return error("Invalid type for value");
3704*0b57cec5SDimitry Andric     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
370581ad6265SDimitry Andric     TyID = getContainedTypeID(TyID);
370681ad6265SDimitry Andric     Ty = getTypeByID(TyID);
370781ad6265SDimitry Andric     if (!Ty)
370881ad6265SDimitry Andric       return error("Missing element type for old-style global");
3709*0b57cec5SDimitry Andric   }
3710*0b57cec5SDimitry Andric 
3711*0b57cec5SDimitry Andric   uint64_t RawLinkage = Record[3];
3712*0b57cec5SDimitry Andric   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
37138bcb0991SDimitry Andric   MaybeAlign Alignment;
3714*0b57cec5SDimitry Andric   if (Error Err = parseAlignmentValue(Record[4], Alignment))
3715*0b57cec5SDimitry Andric     return Err;
3716*0b57cec5SDimitry Andric   std::string Section;
3717*0b57cec5SDimitry Andric   if (Record[5]) {
3718*0b57cec5SDimitry Andric     if (Record[5] - 1 >= SectionTable.size())
3719*0b57cec5SDimitry Andric       return error("Invalid ID");
3720*0b57cec5SDimitry Andric     Section = SectionTable[Record[5] - 1];
3721*0b57cec5SDimitry Andric   }
3722*0b57cec5SDimitry Andric   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3723*0b57cec5SDimitry Andric   // Local linkage must have default visibility.
37245ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
3725*0b57cec5SDimitry Andric   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3726*0b57cec5SDimitry Andric     Visibility = getDecodedVisibility(Record[6]);
3727*0b57cec5SDimitry Andric 
3728*0b57cec5SDimitry Andric   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3729*0b57cec5SDimitry Andric   if (Record.size() > 7)
3730*0b57cec5SDimitry Andric     TLM = getDecodedThreadLocalMode(Record[7]);
3731*0b57cec5SDimitry Andric 
3732*0b57cec5SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3733*0b57cec5SDimitry Andric   if (Record.size() > 8)
3734*0b57cec5SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3735*0b57cec5SDimitry Andric 
3736*0b57cec5SDimitry Andric   bool ExternallyInitialized = false;
3737*0b57cec5SDimitry Andric   if (Record.size() > 9)
3738*0b57cec5SDimitry Andric     ExternallyInitialized = Record[9];
3739*0b57cec5SDimitry Andric 
3740*0b57cec5SDimitry Andric   GlobalVariable *NewGV =
3741*0b57cec5SDimitry Andric       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
3742*0b57cec5SDimitry Andric                          nullptr, TLM, AddressSpace, ExternallyInitialized);
3743*0b57cec5SDimitry Andric   NewGV->setAlignment(Alignment);
3744*0b57cec5SDimitry Andric   if (!Section.empty())
3745*0b57cec5SDimitry Andric     NewGV->setSection(Section);
3746*0b57cec5SDimitry Andric   NewGV->setVisibility(Visibility);
3747*0b57cec5SDimitry Andric   NewGV->setUnnamedAddr(UnnamedAddr);
3748*0b57cec5SDimitry Andric 
3749*0b57cec5SDimitry Andric   if (Record.size() > 10)
3750*0b57cec5SDimitry Andric     NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3751*0b57cec5SDimitry Andric   else
3752*0b57cec5SDimitry Andric     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3753*0b57cec5SDimitry Andric 
375481ad6265SDimitry Andric   ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));
3755*0b57cec5SDimitry Andric 
3756*0b57cec5SDimitry Andric   // Remember which value to use for the global initializer.
3757*0b57cec5SDimitry Andric   if (unsigned InitID = Record[2])
3758*0b57cec5SDimitry Andric     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
3759*0b57cec5SDimitry Andric 
3760*0b57cec5SDimitry Andric   if (Record.size() > 11) {
3761*0b57cec5SDimitry Andric     if (unsigned ComdatID = Record[11]) {
3762*0b57cec5SDimitry Andric       if (ComdatID > ComdatList.size())
3763*0b57cec5SDimitry Andric         return error("Invalid global variable comdat ID");
3764*0b57cec5SDimitry Andric       NewGV->setComdat(ComdatList[ComdatID - 1]);
3765*0b57cec5SDimitry Andric     }
3766*0b57cec5SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
37670eae32dcSDimitry Andric     ImplicitComdatObjects.insert(NewGV);
3768*0b57cec5SDimitry Andric   }
3769*0b57cec5SDimitry Andric 
3770*0b57cec5SDimitry Andric   if (Record.size() > 12) {
3771349cc55cSDimitry Andric     auto AS = getAttributes(Record[12]).getFnAttrs();
3772*0b57cec5SDimitry Andric     NewGV->setAttributes(AS);
3773*0b57cec5SDimitry Andric   }
3774*0b57cec5SDimitry Andric 
3775*0b57cec5SDimitry Andric   if (Record.size() > 13) {
3776*0b57cec5SDimitry Andric     NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
3777*0b57cec5SDimitry Andric   }
3778*0b57cec5SDimitry Andric   inferDSOLocal(NewGV);
3779*0b57cec5SDimitry Andric 
3780*0b57cec5SDimitry Andric   // Check whether we have enough values to read a partition name.
3781*0b57cec5SDimitry Andric   if (Record.size() > 15)
3782*0b57cec5SDimitry Andric     NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
3783*0b57cec5SDimitry Andric 
378481ad6265SDimitry Andric   if (Record.size() > 16 && Record[16]) {
378581ad6265SDimitry Andric     llvm::GlobalValue::SanitizerMetadata Meta =
378681ad6265SDimitry Andric         deserializeSanitizerMetadata(Record[16]);
378781ad6265SDimitry Andric     NewGV->setSanitizerMetadata(Meta);
378881ad6265SDimitry Andric   }
378981ad6265SDimitry Andric 
3790*0b57cec5SDimitry Andric   return Error::success();
3791*0b57cec5SDimitry Andric }
3792*0b57cec5SDimitry Andric 
3793*0b57cec5SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
3794*0b57cec5SDimitry Andric   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3795*0b57cec5SDimitry Andric   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3796*0b57cec5SDimitry Andric   // prefixdata,  personalityfn, preemption specifier, addrspace] (name in VST)
3797*0b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
3798*0b57cec5SDimitry Andric   StringRef Name;
3799*0b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
3800*0b57cec5SDimitry Andric 
3801*0b57cec5SDimitry Andric   if (Record.size() < 8)
3802*0b57cec5SDimitry Andric     return error("Invalid record");
380381ad6265SDimitry Andric   unsigned FTyID = Record[0];
380481ad6265SDimitry Andric   Type *FTy = getTypeByID(FTyID);
3805*0b57cec5SDimitry Andric   if (!FTy)
3806*0b57cec5SDimitry Andric     return error("Invalid record");
380781ad6265SDimitry Andric   if (isa<PointerType>(FTy)) {
380881ad6265SDimitry Andric     FTyID = getContainedTypeID(FTyID, 0);
380981ad6265SDimitry Andric     FTy = getTypeByID(FTyID);
381081ad6265SDimitry Andric     if (!FTy)
381181ad6265SDimitry Andric       return error("Missing element type for old-style function");
381281ad6265SDimitry Andric   }
3813*0b57cec5SDimitry Andric 
3814*0b57cec5SDimitry Andric   if (!isa<FunctionType>(FTy))
3815*0b57cec5SDimitry Andric     return error("Invalid type for value");
3816*0b57cec5SDimitry Andric   auto CC = static_cast<CallingConv::ID>(Record[1]);
3817*0b57cec5SDimitry Andric   if (CC & ~CallingConv::MaxID)
3818*0b57cec5SDimitry Andric     return error("Invalid calling convention ID");
3819*0b57cec5SDimitry Andric 
3820*0b57cec5SDimitry Andric   unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3821*0b57cec5SDimitry Andric   if (Record.size() > 16)
3822*0b57cec5SDimitry Andric     AddrSpace = Record[16];
3823*0b57cec5SDimitry Andric 
3824*0b57cec5SDimitry Andric   Function *Func =
3825*0b57cec5SDimitry Andric       Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
3826*0b57cec5SDimitry Andric                        AddrSpace, Name, TheModule);
3827*0b57cec5SDimitry Andric 
3828fe6060f1SDimitry Andric   assert(Func->getFunctionType() == FTy &&
3829*0b57cec5SDimitry Andric          "Incorrect fully specified type provided for function");
383081ad6265SDimitry Andric   FunctionTypeIDs[Func] = FTyID;
3831*0b57cec5SDimitry Andric 
3832*0b57cec5SDimitry Andric   Func->setCallingConv(CC);
3833*0b57cec5SDimitry Andric   bool isProto = Record[2];
3834*0b57cec5SDimitry Andric   uint64_t RawLinkage = Record[3];
3835*0b57cec5SDimitry Andric   Func->setLinkage(getDecodedLinkage(RawLinkage));
3836*0b57cec5SDimitry Andric   Func->setAttributes(getAttributes(Record[4]));
3837*0b57cec5SDimitry Andric 
3838e8d8bef9SDimitry Andric   // Upgrade any old-style byval or sret without a type by propagating the
3839e8d8bef9SDimitry Andric   // argument's pointee type. There should be no opaque pointers where the byval
3840e8d8bef9SDimitry Andric   // type is implicit.
3841*0b57cec5SDimitry Andric   for (unsigned i = 0; i != Func->arg_size(); ++i) {
3842fe6060f1SDimitry Andric     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3843fe6060f1SDimitry Andric                                      Attribute::InAlloca}) {
3844e8d8bef9SDimitry Andric       if (!Func->hasParamAttribute(i, Kind))
3845*0b57cec5SDimitry Andric         continue;
3846*0b57cec5SDimitry Andric 
3847fe6060f1SDimitry Andric       if (Func->getParamAttribute(i, Kind).getValueAsType())
3848fe6060f1SDimitry Andric         continue;
3849fe6060f1SDimitry Andric 
3850e8d8bef9SDimitry Andric       Func->removeParamAttr(i, Kind);
3851e8d8bef9SDimitry Andric 
385281ad6265SDimitry Andric       unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
385381ad6265SDimitry Andric       Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
385481ad6265SDimitry Andric       if (!PtrEltTy)
385581ad6265SDimitry Andric         return error("Missing param element type for attribute upgrade");
385681ad6265SDimitry Andric 
3857fe6060f1SDimitry Andric       Attribute NewAttr;
3858fe6060f1SDimitry Andric       switch (Kind) {
3859fe6060f1SDimitry Andric       case Attribute::ByVal:
3860fe6060f1SDimitry Andric         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3861fe6060f1SDimitry Andric         break;
3862fe6060f1SDimitry Andric       case Attribute::StructRet:
3863fe6060f1SDimitry Andric         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3864fe6060f1SDimitry Andric         break;
3865fe6060f1SDimitry Andric       case Attribute::InAlloca:
3866fe6060f1SDimitry Andric         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3867fe6060f1SDimitry Andric         break;
3868fe6060f1SDimitry Andric       default:
3869fe6060f1SDimitry Andric         llvm_unreachable("not an upgraded type attribute");
3870fe6060f1SDimitry Andric       }
3871fe6060f1SDimitry Andric 
3872e8d8bef9SDimitry Andric       Func->addParamAttr(i, NewAttr);
3873e8d8bef9SDimitry Andric     }
3874*0b57cec5SDimitry Andric   }
3875*0b57cec5SDimitry Andric 
387681ad6265SDimitry Andric   if (Func->getCallingConv() == CallingConv::X86_INTR &&
387781ad6265SDimitry Andric       !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {
387881ad6265SDimitry Andric     unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
387981ad6265SDimitry Andric     Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
388081ad6265SDimitry Andric     if (!ByValTy)
388181ad6265SDimitry Andric       return error("Missing param element type for x86_intrcc upgrade");
388281ad6265SDimitry Andric     Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
388381ad6265SDimitry Andric     Func->addParamAttr(0, NewAttr);
388481ad6265SDimitry Andric   }
388581ad6265SDimitry Andric 
38868bcb0991SDimitry Andric   MaybeAlign Alignment;
3887*0b57cec5SDimitry Andric   if (Error Err = parseAlignmentValue(Record[5], Alignment))
3888*0b57cec5SDimitry Andric     return Err;
3889*0b57cec5SDimitry Andric   Func->setAlignment(Alignment);
3890*0b57cec5SDimitry Andric   if (Record[6]) {
3891*0b57cec5SDimitry Andric     if (Record[6] - 1 >= SectionTable.size())
3892*0b57cec5SDimitry Andric       return error("Invalid ID");
3893*0b57cec5SDimitry Andric     Func->setSection(SectionTable[Record[6] - 1]);
3894*0b57cec5SDimitry Andric   }
3895*0b57cec5SDimitry Andric   // Local linkage must have default visibility.
38965ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
3897*0b57cec5SDimitry Andric   if (!Func->hasLocalLinkage())
3898*0b57cec5SDimitry Andric     Func->setVisibility(getDecodedVisibility(Record[7]));
3899*0b57cec5SDimitry Andric   if (Record.size() > 8 && Record[8]) {
3900*0b57cec5SDimitry Andric     if (Record[8] - 1 >= GCTable.size())
3901*0b57cec5SDimitry Andric       return error("Invalid ID");
3902*0b57cec5SDimitry Andric     Func->setGC(GCTable[Record[8] - 1]);
3903*0b57cec5SDimitry Andric   }
3904*0b57cec5SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3905*0b57cec5SDimitry Andric   if (Record.size() > 9)
3906*0b57cec5SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3907*0b57cec5SDimitry Andric   Func->setUnnamedAddr(UnnamedAddr);
3908349cc55cSDimitry Andric 
3909349cc55cSDimitry Andric   FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
3910349cc55cSDimitry Andric   if (Record.size() > 10)
3911349cc55cSDimitry Andric     OperandInfo.Prologue = Record[10];
3912*0b57cec5SDimitry Andric 
3913*0b57cec5SDimitry Andric   if (Record.size() > 11)
3914*0b57cec5SDimitry Andric     Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3915*0b57cec5SDimitry Andric   else
3916*0b57cec5SDimitry Andric     upgradeDLLImportExportLinkage(Func, RawLinkage);
3917*0b57cec5SDimitry Andric 
3918*0b57cec5SDimitry Andric   if (Record.size() > 12) {
3919*0b57cec5SDimitry Andric     if (unsigned ComdatID = Record[12]) {
3920*0b57cec5SDimitry Andric       if (ComdatID > ComdatList.size())
3921*0b57cec5SDimitry Andric         return error("Invalid function comdat ID");
3922*0b57cec5SDimitry Andric       Func->setComdat(ComdatList[ComdatID - 1]);
3923*0b57cec5SDimitry Andric     }
3924*0b57cec5SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
39250eae32dcSDimitry Andric     ImplicitComdatObjects.insert(Func);
3926*0b57cec5SDimitry Andric   }
3927*0b57cec5SDimitry Andric 
3928349cc55cSDimitry Andric   if (Record.size() > 13)
3929349cc55cSDimitry Andric     OperandInfo.Prefix = Record[13];
3930*0b57cec5SDimitry Andric 
3931349cc55cSDimitry Andric   if (Record.size() > 14)
3932349cc55cSDimitry Andric     OperandInfo.PersonalityFn = Record[14];
3933*0b57cec5SDimitry Andric 
3934*0b57cec5SDimitry Andric   if (Record.size() > 15) {
3935*0b57cec5SDimitry Andric     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3936*0b57cec5SDimitry Andric   }
3937*0b57cec5SDimitry Andric   inferDSOLocal(Func);
3938*0b57cec5SDimitry Andric 
3939*0b57cec5SDimitry Andric   // Record[16] is the address space number.
3940*0b57cec5SDimitry Andric 
3941fe6060f1SDimitry Andric   // Check whether we have enough values to read a partition name. Also make
3942fe6060f1SDimitry Andric   // sure Strtab has enough values.
3943fe6060f1SDimitry Andric   if (Record.size() > 18 && Strtab.data() &&
3944fe6060f1SDimitry Andric       Record[17] + Record[18] <= Strtab.size()) {
3945*0b57cec5SDimitry Andric     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
3946fe6060f1SDimitry Andric   }
3947*0b57cec5SDimitry Andric 
394881ad6265SDimitry Andric   ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
3949*0b57cec5SDimitry Andric 
3950349cc55cSDimitry Andric   if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
3951349cc55cSDimitry Andric     FunctionOperands.push_back(OperandInfo);
3952349cc55cSDimitry Andric 
3953*0b57cec5SDimitry Andric   // If this is a function with a body, remember the prototype we are
3954*0b57cec5SDimitry Andric   // creating now, so that we can match up the body with them later.
3955*0b57cec5SDimitry Andric   if (!isProto) {
3956*0b57cec5SDimitry Andric     Func->setIsMaterializable(true);
3957*0b57cec5SDimitry Andric     FunctionsWithBodies.push_back(Func);
3958*0b57cec5SDimitry Andric     DeferredFunctionInfo[Func] = 0;
3959*0b57cec5SDimitry Andric   }
3960*0b57cec5SDimitry Andric   return Error::success();
3961*0b57cec5SDimitry Andric }
3962*0b57cec5SDimitry Andric 
3963*0b57cec5SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3964*0b57cec5SDimitry Andric     unsigned BitCode, ArrayRef<uint64_t> Record) {
3965*0b57cec5SDimitry Andric   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3966*0b57cec5SDimitry Andric   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3967*0b57cec5SDimitry Andric   // dllstorageclass, threadlocal, unnamed_addr,
3968*0b57cec5SDimitry Andric   // preemption specifier] (name in VST)
3969*0b57cec5SDimitry Andric   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3970*0b57cec5SDimitry Andric   // visibility, dllstorageclass, threadlocal, unnamed_addr,
3971*0b57cec5SDimitry Andric   // preemption specifier] (name in VST)
3972*0b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
3973*0b57cec5SDimitry Andric   StringRef Name;
3974*0b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
3975*0b57cec5SDimitry Andric 
3976*0b57cec5SDimitry Andric   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3977*0b57cec5SDimitry Andric   if (Record.size() < (3 + (unsigned)NewRecord))
3978*0b57cec5SDimitry Andric     return error("Invalid record");
3979*0b57cec5SDimitry Andric   unsigned OpNum = 0;
398081ad6265SDimitry Andric   unsigned TypeID = Record[OpNum++];
398181ad6265SDimitry Andric   Type *Ty = getTypeByID(TypeID);
3982*0b57cec5SDimitry Andric   if (!Ty)
3983*0b57cec5SDimitry Andric     return error("Invalid record");
3984*0b57cec5SDimitry Andric 
3985*0b57cec5SDimitry Andric   unsigned AddrSpace;
3986*0b57cec5SDimitry Andric   if (!NewRecord) {
3987*0b57cec5SDimitry Andric     auto *PTy = dyn_cast<PointerType>(Ty);
3988*0b57cec5SDimitry Andric     if (!PTy)
3989*0b57cec5SDimitry Andric       return error("Invalid type for value");
3990*0b57cec5SDimitry Andric     AddrSpace = PTy->getAddressSpace();
399181ad6265SDimitry Andric     TypeID = getContainedTypeID(TypeID);
399281ad6265SDimitry Andric     Ty = getTypeByID(TypeID);
399381ad6265SDimitry Andric     if (!Ty)
399481ad6265SDimitry Andric       return error("Missing element type for old-style indirect symbol");
3995*0b57cec5SDimitry Andric   } else {
3996*0b57cec5SDimitry Andric     AddrSpace = Record[OpNum++];
3997*0b57cec5SDimitry Andric   }
3998*0b57cec5SDimitry Andric 
3999*0b57cec5SDimitry Andric   auto Val = Record[OpNum++];
4000*0b57cec5SDimitry Andric   auto Linkage = Record[OpNum++];
4001349cc55cSDimitry Andric   GlobalValue *NewGA;
4002*0b57cec5SDimitry Andric   if (BitCode == bitc::MODULE_CODE_ALIAS ||
4003*0b57cec5SDimitry Andric       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
4004*0b57cec5SDimitry Andric     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4005*0b57cec5SDimitry Andric                                 TheModule);
4006*0b57cec5SDimitry Andric   else
4007*0b57cec5SDimitry Andric     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4008*0b57cec5SDimitry Andric                                 nullptr, TheModule);
4009*0b57cec5SDimitry Andric 
4010*0b57cec5SDimitry Andric   // Local linkage must have default visibility.
40115ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
4012*0b57cec5SDimitry Andric   if (OpNum != Record.size()) {
4013*0b57cec5SDimitry Andric     auto VisInd = OpNum++;
4014*0b57cec5SDimitry Andric     if (!NewGA->hasLocalLinkage())
4015*0b57cec5SDimitry Andric       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
4016*0b57cec5SDimitry Andric   }
4017*0b57cec5SDimitry Andric   if (BitCode == bitc::MODULE_CODE_ALIAS ||
4018*0b57cec5SDimitry Andric       BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
4019*0b57cec5SDimitry Andric     if (OpNum != Record.size())
4020*0b57cec5SDimitry Andric       NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
4021*0b57cec5SDimitry Andric     else
4022*0b57cec5SDimitry Andric       upgradeDLLImportExportLinkage(NewGA, Linkage);
4023*0b57cec5SDimitry Andric     if (OpNum != Record.size())
4024*0b57cec5SDimitry Andric       NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
4025*0b57cec5SDimitry Andric     if (OpNum != Record.size())
4026*0b57cec5SDimitry Andric       NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
4027*0b57cec5SDimitry Andric   }
4028*0b57cec5SDimitry Andric   if (OpNum != Record.size())
4029*0b57cec5SDimitry Andric     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
4030*0b57cec5SDimitry Andric   inferDSOLocal(NewGA);
4031*0b57cec5SDimitry Andric 
4032*0b57cec5SDimitry Andric   // Check whether we have enough values to read a partition name.
4033*0b57cec5SDimitry Andric   if (OpNum + 1 < Record.size()) {
4034*0b57cec5SDimitry Andric     NewGA->setPartition(
4035*0b57cec5SDimitry Andric         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
4036*0b57cec5SDimitry Andric     OpNum += 2;
4037*0b57cec5SDimitry Andric   }
4038*0b57cec5SDimitry Andric 
403981ad6265SDimitry Andric   ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
4040*0b57cec5SDimitry Andric   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4041*0b57cec5SDimitry Andric   return Error::success();
4042*0b57cec5SDimitry Andric }
4043*0b57cec5SDimitry Andric 
4044*0b57cec5SDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit,
40455ffd83dbSDimitry Andric                                  bool ShouldLazyLoadMetadata,
40465ffd83dbSDimitry Andric                                  DataLayoutCallbackTy DataLayoutCallback) {
4047*0b57cec5SDimitry Andric   if (ResumeBit) {
4048*0b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
4049*0b57cec5SDimitry Andric       return JumpFailed;
4050*0b57cec5SDimitry Andric   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4051*0b57cec5SDimitry Andric     return Err;
4052*0b57cec5SDimitry Andric 
4053*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
4054*0b57cec5SDimitry Andric 
40555ffd83dbSDimitry Andric   // Parts of bitcode parsing depend on the datalayout.  Make sure we
40565ffd83dbSDimitry Andric   // finalize the datalayout before we run any of that code.
40575ffd83dbSDimitry Andric   bool ResolvedDataLayout = false;
40585ffd83dbSDimitry Andric   auto ResolveDataLayout = [&] {
40595ffd83dbSDimitry Andric     if (ResolvedDataLayout)
40605ffd83dbSDimitry Andric       return;
40615ffd83dbSDimitry Andric 
40625ffd83dbSDimitry Andric     // datalayout and triple can't be parsed after this point.
40635ffd83dbSDimitry Andric     ResolvedDataLayout = true;
40645ffd83dbSDimitry Andric 
40655ffd83dbSDimitry Andric     // Upgrade data layout string.
40665ffd83dbSDimitry Andric     std::string DL = llvm::UpgradeDataLayoutString(
40675ffd83dbSDimitry Andric         TheModule->getDataLayoutStr(), TheModule->getTargetTriple());
40685ffd83dbSDimitry Andric     TheModule->setDataLayout(DL);
40695ffd83dbSDimitry Andric 
40705ffd83dbSDimitry Andric     if (auto LayoutOverride =
40715ffd83dbSDimitry Andric             DataLayoutCallback(TheModule->getTargetTriple()))
40725ffd83dbSDimitry Andric       TheModule->setDataLayout(*LayoutOverride);
40735ffd83dbSDimitry Andric   };
40745ffd83dbSDimitry Andric 
4075*0b57cec5SDimitry Andric   // Read all the records for this module.
4076*0b57cec5SDimitry Andric   while (true) {
4077*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4078*0b57cec5SDimitry Andric     if (!MaybeEntry)
4079*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
4080*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
4081*0b57cec5SDimitry Andric 
4082*0b57cec5SDimitry Andric     switch (Entry.Kind) {
4083*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
4084*0b57cec5SDimitry Andric       return error("Malformed block");
4085*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
40865ffd83dbSDimitry Andric       ResolveDataLayout();
4087*0b57cec5SDimitry Andric       return globalCleanup();
4088*0b57cec5SDimitry Andric 
4089*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
4090*0b57cec5SDimitry Andric       switch (Entry.ID) {
4091*0b57cec5SDimitry Andric       default:  // Skip unknown content.
4092*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
4093*0b57cec5SDimitry Andric           return Err;
4094*0b57cec5SDimitry Andric         break;
4095*0b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
409681ad6265SDimitry Andric         if (Error Err = readBlockInfo())
409781ad6265SDimitry Andric           return Err;
4098*0b57cec5SDimitry Andric         break;
4099*0b57cec5SDimitry Andric       case bitc::PARAMATTR_BLOCK_ID:
4100*0b57cec5SDimitry Andric         if (Error Err = parseAttributeBlock())
4101*0b57cec5SDimitry Andric           return Err;
4102*0b57cec5SDimitry Andric         break;
4103*0b57cec5SDimitry Andric       case bitc::PARAMATTR_GROUP_BLOCK_ID:
4104*0b57cec5SDimitry Andric         if (Error Err = parseAttributeGroupBlock())
4105*0b57cec5SDimitry Andric           return Err;
4106*0b57cec5SDimitry Andric         break;
4107*0b57cec5SDimitry Andric       case bitc::TYPE_BLOCK_ID_NEW:
4108*0b57cec5SDimitry Andric         if (Error Err = parseTypeTable())
4109*0b57cec5SDimitry Andric           return Err;
4110*0b57cec5SDimitry Andric         break;
4111*0b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
4112*0b57cec5SDimitry Andric         if (!SeenValueSymbolTable) {
4113*0b57cec5SDimitry Andric           // Either this is an old form VST without function index and an
4114*0b57cec5SDimitry Andric           // associated VST forward declaration record (which would have caused
4115*0b57cec5SDimitry Andric           // the VST to be jumped to and parsed before it was encountered
4116*0b57cec5SDimitry Andric           // normally in the stream), or there were no function blocks to
4117*0b57cec5SDimitry Andric           // trigger an earlier parsing of the VST.
4118*0b57cec5SDimitry Andric           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4119*0b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable())
4120*0b57cec5SDimitry Andric             return Err;
4121*0b57cec5SDimitry Andric           SeenValueSymbolTable = true;
4122*0b57cec5SDimitry Andric         } else {
4123*0b57cec5SDimitry Andric           // We must have had a VST forward declaration record, which caused
4124*0b57cec5SDimitry Andric           // the parser to jump to and parse the VST earlier.
4125*0b57cec5SDimitry Andric           assert(VSTOffset > 0);
4126*0b57cec5SDimitry Andric           if (Error Err = Stream.SkipBlock())
4127*0b57cec5SDimitry Andric             return Err;
4128*0b57cec5SDimitry Andric         }
4129*0b57cec5SDimitry Andric         break;
4130*0b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
4131*0b57cec5SDimitry Andric         if (Error Err = parseConstants())
4132*0b57cec5SDimitry Andric           return Err;
4133*0b57cec5SDimitry Andric         if (Error Err = resolveGlobalAndIndirectSymbolInits())
4134*0b57cec5SDimitry Andric           return Err;
4135*0b57cec5SDimitry Andric         break;
4136*0b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
4137*0b57cec5SDimitry Andric         if (ShouldLazyLoadMetadata) {
4138*0b57cec5SDimitry Andric           if (Error Err = rememberAndSkipMetadata())
4139*0b57cec5SDimitry Andric             return Err;
4140*0b57cec5SDimitry Andric           break;
4141*0b57cec5SDimitry Andric         }
4142*0b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
4143*0b57cec5SDimitry Andric         if (Error Err = MDLoader->parseModuleMetadata())
4144*0b57cec5SDimitry Andric           return Err;
4145*0b57cec5SDimitry Andric         break;
4146*0b57cec5SDimitry Andric       case bitc::METADATA_KIND_BLOCK_ID:
4147*0b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataKinds())
4148*0b57cec5SDimitry Andric           return Err;
4149*0b57cec5SDimitry Andric         break;
4150*0b57cec5SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
41515ffd83dbSDimitry Andric         ResolveDataLayout();
41525ffd83dbSDimitry Andric 
4153*0b57cec5SDimitry Andric         // If this is the first function body we've seen, reverse the
4154*0b57cec5SDimitry Andric         // FunctionsWithBodies list.
4155*0b57cec5SDimitry Andric         if (!SeenFirstFunctionBody) {
4156*0b57cec5SDimitry Andric           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4157*0b57cec5SDimitry Andric           if (Error Err = globalCleanup())
4158*0b57cec5SDimitry Andric             return Err;
4159*0b57cec5SDimitry Andric           SeenFirstFunctionBody = true;
4160*0b57cec5SDimitry Andric         }
4161*0b57cec5SDimitry Andric 
4162*0b57cec5SDimitry Andric         if (VSTOffset > 0) {
4163*0b57cec5SDimitry Andric           // If we have a VST forward declaration record, make sure we
4164*0b57cec5SDimitry Andric           // parse the VST now if we haven't already. It is needed to
4165*0b57cec5SDimitry Andric           // set up the DeferredFunctionInfo vector for lazy reading.
4166*0b57cec5SDimitry Andric           if (!SeenValueSymbolTable) {
4167*0b57cec5SDimitry Andric             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4168*0b57cec5SDimitry Andric               return Err;
4169*0b57cec5SDimitry Andric             SeenValueSymbolTable = true;
4170*0b57cec5SDimitry Andric             // Fall through so that we record the NextUnreadBit below.
4171*0b57cec5SDimitry Andric             // This is necessary in case we have an anonymous function that
4172*0b57cec5SDimitry Andric             // is later materialized. Since it will not have a VST entry we
4173*0b57cec5SDimitry Andric             // need to fall back to the lazy parse to find its offset.
4174*0b57cec5SDimitry Andric           } else {
4175*0b57cec5SDimitry Andric             // If we have a VST forward declaration record, but have already
4176*0b57cec5SDimitry Andric             // parsed the VST (just above, when the first function body was
4177*0b57cec5SDimitry Andric             // encountered here), then we are resuming the parse after
4178*0b57cec5SDimitry Andric             // materializing functions. The ResumeBit points to the
4179*0b57cec5SDimitry Andric             // start of the last function block recorded in the
4180*0b57cec5SDimitry Andric             // DeferredFunctionInfo map. Skip it.
4181*0b57cec5SDimitry Andric             if (Error Err = Stream.SkipBlock())
4182*0b57cec5SDimitry Andric               return Err;
4183*0b57cec5SDimitry Andric             continue;
4184*0b57cec5SDimitry Andric           }
4185*0b57cec5SDimitry Andric         }
4186*0b57cec5SDimitry Andric 
4187*0b57cec5SDimitry Andric         // Support older bitcode files that did not have the function
4188*0b57cec5SDimitry Andric         // index in the VST, nor a VST forward declaration record, as
4189*0b57cec5SDimitry Andric         // well as anonymous functions that do not have VST entries.
4190*0b57cec5SDimitry Andric         // Build the DeferredFunctionInfo vector on the fly.
4191*0b57cec5SDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
4192*0b57cec5SDimitry Andric           return Err;
4193*0b57cec5SDimitry Andric 
4194*0b57cec5SDimitry Andric         // Suspend parsing when we reach the function bodies. Subsequent
4195*0b57cec5SDimitry Andric         // materialization calls will resume it when necessary. If the bitcode
4196*0b57cec5SDimitry Andric         // file is old, the symbol table will be at the end instead and will not
4197*0b57cec5SDimitry Andric         // have been seen yet. In this case, just finish the parse now.
4198*0b57cec5SDimitry Andric         if (SeenValueSymbolTable) {
4199*0b57cec5SDimitry Andric           NextUnreadBit = Stream.GetCurrentBitNo();
4200*0b57cec5SDimitry Andric           // After the VST has been parsed, we need to make sure intrinsic name
4201*0b57cec5SDimitry Andric           // are auto-upgraded.
4202*0b57cec5SDimitry Andric           return globalCleanup();
4203*0b57cec5SDimitry Andric         }
4204*0b57cec5SDimitry Andric         break;
4205*0b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
4206*0b57cec5SDimitry Andric         if (Error Err = parseUseLists())
4207*0b57cec5SDimitry Andric           return Err;
4208*0b57cec5SDimitry Andric         break;
4209*0b57cec5SDimitry Andric       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
4210*0b57cec5SDimitry Andric         if (Error Err = parseOperandBundleTags())
4211*0b57cec5SDimitry Andric           return Err;
4212*0b57cec5SDimitry Andric         break;
4213*0b57cec5SDimitry Andric       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
4214*0b57cec5SDimitry Andric         if (Error Err = parseSyncScopeNames())
4215*0b57cec5SDimitry Andric           return Err;
4216*0b57cec5SDimitry Andric         break;
4217*0b57cec5SDimitry Andric       }
4218*0b57cec5SDimitry Andric       continue;
4219*0b57cec5SDimitry Andric 
4220*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
4221*0b57cec5SDimitry Andric       // The interesting case.
4222*0b57cec5SDimitry Andric       break;
4223*0b57cec5SDimitry Andric     }
4224*0b57cec5SDimitry Andric 
4225*0b57cec5SDimitry Andric     // Read a record.
4226*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4227*0b57cec5SDimitry Andric     if (!MaybeBitCode)
4228*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
4229*0b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
4230*0b57cec5SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
4231*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_VERSION: {
4232*0b57cec5SDimitry Andric       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4233*0b57cec5SDimitry Andric       if (!VersionOrErr)
4234*0b57cec5SDimitry Andric         return VersionOrErr.takeError();
4235*0b57cec5SDimitry Andric       UseRelativeIDs = *VersionOrErr >= 1;
4236*0b57cec5SDimitry Andric       break;
4237*0b57cec5SDimitry Andric     }
4238*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
42395ffd83dbSDimitry Andric       if (ResolvedDataLayout)
42405ffd83dbSDimitry Andric         return error("target triple too late in module");
4241*0b57cec5SDimitry Andric       std::string S;
4242*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
4243*0b57cec5SDimitry Andric         return error("Invalid record");
4244*0b57cec5SDimitry Andric       TheModule->setTargetTriple(S);
4245*0b57cec5SDimitry Andric       break;
4246*0b57cec5SDimitry Andric     }
4247*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
42485ffd83dbSDimitry Andric       if (ResolvedDataLayout)
42495ffd83dbSDimitry Andric         return error("datalayout too late in module");
4250*0b57cec5SDimitry Andric       std::string S;
4251*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
4252*0b57cec5SDimitry Andric         return error("Invalid record");
425381ad6265SDimitry Andric       Expected<DataLayout> MaybeDL = DataLayout::parse(S);
425481ad6265SDimitry Andric       if (!MaybeDL)
425581ad6265SDimitry Andric         return MaybeDL.takeError();
425681ad6265SDimitry Andric       TheModule->setDataLayout(MaybeDL.get());
4257*0b57cec5SDimitry Andric       break;
4258*0b57cec5SDimitry Andric     }
4259*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
4260*0b57cec5SDimitry Andric       std::string S;
4261*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
4262*0b57cec5SDimitry Andric         return error("Invalid record");
4263*0b57cec5SDimitry Andric       TheModule->setModuleInlineAsm(S);
4264*0b57cec5SDimitry Andric       break;
4265*0b57cec5SDimitry Andric     }
4266*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
42675ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
4268*0b57cec5SDimitry Andric       std::string S;
4269*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
4270*0b57cec5SDimitry Andric         return error("Invalid record");
4271*0b57cec5SDimitry Andric       // Ignore value.
4272*0b57cec5SDimitry Andric       break;
4273*0b57cec5SDimitry Andric     }
4274*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
4275*0b57cec5SDimitry Andric       std::string S;
4276*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
4277*0b57cec5SDimitry Andric         return error("Invalid record");
4278*0b57cec5SDimitry Andric       SectionTable.push_back(S);
4279*0b57cec5SDimitry Andric       break;
4280*0b57cec5SDimitry Andric     }
4281*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
4282*0b57cec5SDimitry Andric       std::string S;
4283*0b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
4284*0b57cec5SDimitry Andric         return error("Invalid record");
4285*0b57cec5SDimitry Andric       GCTable.push_back(S);
4286*0b57cec5SDimitry Andric       break;
4287*0b57cec5SDimitry Andric     }
4288*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_COMDAT:
4289*0b57cec5SDimitry Andric       if (Error Err = parseComdatRecord(Record))
4290*0b57cec5SDimitry Andric         return Err;
4291*0b57cec5SDimitry Andric       break;
429204eeddc0SDimitry Andric     // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
429304eeddc0SDimitry Andric     // written by ThinLinkBitcodeWriter. See
429404eeddc0SDimitry Andric     // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
429504eeddc0SDimitry Andric     // record
429604eeddc0SDimitry Andric     // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4297*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_GLOBALVAR:
4298*0b57cec5SDimitry Andric       if (Error Err = parseGlobalVarRecord(Record))
4299*0b57cec5SDimitry Andric         return Err;
4300*0b57cec5SDimitry Andric       break;
4301*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_FUNCTION:
43025ffd83dbSDimitry Andric       ResolveDataLayout();
4303*0b57cec5SDimitry Andric       if (Error Err = parseFunctionRecord(Record))
4304*0b57cec5SDimitry Andric         return Err;
4305*0b57cec5SDimitry Andric       break;
4306*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_IFUNC:
4307*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS:
4308*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS_OLD:
4309*0b57cec5SDimitry Andric       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4310*0b57cec5SDimitry Andric         return Err;
4311*0b57cec5SDimitry Andric       break;
4312*0b57cec5SDimitry Andric     /// MODULE_CODE_VSTOFFSET: [offset]
4313*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_VSTOFFSET:
4314e8d8bef9SDimitry Andric       if (Record.empty())
4315*0b57cec5SDimitry Andric         return error("Invalid record");
4316*0b57cec5SDimitry Andric       // Note that we subtract 1 here because the offset is relative to one word
4317*0b57cec5SDimitry Andric       // before the start of the identification or module block, which was
4318*0b57cec5SDimitry Andric       // historically always the start of the regular bitcode header.
4319*0b57cec5SDimitry Andric       VSTOffset = Record[0] - 1;
4320*0b57cec5SDimitry Andric       break;
4321*0b57cec5SDimitry Andric     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4322*0b57cec5SDimitry Andric     case bitc::MODULE_CODE_SOURCE_FILENAME:
4323*0b57cec5SDimitry Andric       SmallString<128> ValueName;
4324*0b57cec5SDimitry Andric       if (convertToString(Record, 0, ValueName))
4325*0b57cec5SDimitry Andric         return error("Invalid record");
4326*0b57cec5SDimitry Andric       TheModule->setSourceFileName(ValueName);
4327*0b57cec5SDimitry Andric       break;
4328*0b57cec5SDimitry Andric     }
4329*0b57cec5SDimitry Andric     Record.clear();
4330*0b57cec5SDimitry Andric   }
4331*0b57cec5SDimitry Andric }
4332*0b57cec5SDimitry Andric 
4333*0b57cec5SDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
43345ffd83dbSDimitry Andric                                       bool IsImporting,
43355ffd83dbSDimitry Andric                                       DataLayoutCallbackTy DataLayoutCallback) {
4336*0b57cec5SDimitry Andric   TheModule = M;
4337*0b57cec5SDimitry Andric   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
4338*0b57cec5SDimitry Andric                             [&](unsigned ID) { return getTypeByID(ID); });
43395ffd83dbSDimitry Andric   return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback);
4340*0b57cec5SDimitry Andric }
4341*0b57cec5SDimitry Andric 
4342*0b57cec5SDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4343*0b57cec5SDimitry Andric   if (!isa<PointerType>(PtrType))
4344*0b57cec5SDimitry Andric     return error("Load/Store operand is not a pointer type");
4345*0b57cec5SDimitry Andric 
4346fe6060f1SDimitry Andric   if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType))
4347*0b57cec5SDimitry Andric     return error("Explicit load/store type does not match pointee "
4348*0b57cec5SDimitry Andric                  "type of pointer operand");
4349fe6060f1SDimitry Andric   if (!PointerType::isLoadableOrStorableType(ValType))
4350*0b57cec5SDimitry Andric     return error("Cannot load/store from pointer");
4351*0b57cec5SDimitry Andric   return Error::success();
4352*0b57cec5SDimitry Andric }
4353*0b57cec5SDimitry Andric 
435481ad6265SDimitry Andric Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
435581ad6265SDimitry Andric                                              ArrayRef<unsigned> ArgTyIDs) {
435681ad6265SDimitry Andric   AttributeList Attrs = CB->getAttributes();
4357*0b57cec5SDimitry Andric   for (unsigned i = 0; i != CB->arg_size(); ++i) {
4358fe6060f1SDimitry Andric     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4359fe6060f1SDimitry Andric                                      Attribute::InAlloca}) {
436081ad6265SDimitry Andric       if (!Attrs.hasParamAttr(i, Kind) ||
436181ad6265SDimitry Andric           Attrs.getParamAttr(i, Kind).getValueAsType())
4362*0b57cec5SDimitry Andric         continue;
4363*0b57cec5SDimitry Andric 
436481ad6265SDimitry Andric       Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
436581ad6265SDimitry Andric       if (!PtrEltTy)
436681ad6265SDimitry Andric         return error("Missing element type for typed attribute upgrade");
4367e8d8bef9SDimitry Andric 
4368fe6060f1SDimitry Andric       Attribute NewAttr;
4369fe6060f1SDimitry Andric       switch (Kind) {
4370fe6060f1SDimitry Andric       case Attribute::ByVal:
4371fe6060f1SDimitry Andric         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4372fe6060f1SDimitry Andric         break;
4373fe6060f1SDimitry Andric       case Attribute::StructRet:
4374fe6060f1SDimitry Andric         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4375fe6060f1SDimitry Andric         break;
4376fe6060f1SDimitry Andric       case Attribute::InAlloca:
4377fe6060f1SDimitry Andric         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4378fe6060f1SDimitry Andric         break;
4379fe6060f1SDimitry Andric       default:
4380fe6060f1SDimitry Andric         llvm_unreachable("not an upgraded type attribute");
4381fe6060f1SDimitry Andric       }
4382fe6060f1SDimitry Andric 
438381ad6265SDimitry Andric       Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
4384e8d8bef9SDimitry Andric     }
4385*0b57cec5SDimitry Andric   }
4386fe6060f1SDimitry Andric 
438704eeddc0SDimitry Andric   if (CB->isInlineAsm()) {
438804eeddc0SDimitry Andric     const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
438904eeddc0SDimitry Andric     unsigned ArgNo = 0;
439004eeddc0SDimitry Andric     for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
439104eeddc0SDimitry Andric       if (!CI.hasArg())
439204eeddc0SDimitry Andric         continue;
439304eeddc0SDimitry Andric 
439481ad6265SDimitry Andric       if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
439581ad6265SDimitry Andric         Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
439681ad6265SDimitry Andric         if (!ElemTy)
439781ad6265SDimitry Andric           return error("Missing element type for inline asm upgrade");
439881ad6265SDimitry Andric         Attrs = Attrs.addParamAttribute(
439981ad6265SDimitry Andric             Context, ArgNo,
440081ad6265SDimitry Andric             Attribute::get(Context, Attribute::ElementType, ElemTy));
440104eeddc0SDimitry Andric       }
440204eeddc0SDimitry Andric 
440304eeddc0SDimitry Andric       ArgNo++;
440404eeddc0SDimitry Andric     }
440504eeddc0SDimitry Andric   }
440604eeddc0SDimitry Andric 
4407fe6060f1SDimitry Andric   switch (CB->getIntrinsicID()) {
4408fe6060f1SDimitry Andric   case Intrinsic::preserve_array_access_index:
4409fe6060f1SDimitry Andric   case Intrinsic::preserve_struct_access_index:
441081ad6265SDimitry Andric   case Intrinsic::aarch64_ldaxr:
441181ad6265SDimitry Andric   case Intrinsic::aarch64_ldxr:
441281ad6265SDimitry Andric   case Intrinsic::aarch64_stlxr:
441381ad6265SDimitry Andric   case Intrinsic::aarch64_stxr:
441481ad6265SDimitry Andric   case Intrinsic::arm_ldaex:
441581ad6265SDimitry Andric   case Intrinsic::arm_ldrex:
441681ad6265SDimitry Andric   case Intrinsic::arm_stlex:
441781ad6265SDimitry Andric   case Intrinsic::arm_strex: {
441881ad6265SDimitry Andric     unsigned ArgNo;
441981ad6265SDimitry Andric     switch (CB->getIntrinsicID()) {
442081ad6265SDimitry Andric     case Intrinsic::aarch64_stlxr:
442181ad6265SDimitry Andric     case Intrinsic::aarch64_stxr:
442281ad6265SDimitry Andric     case Intrinsic::arm_stlex:
442381ad6265SDimitry Andric     case Intrinsic::arm_strex:
442481ad6265SDimitry Andric       ArgNo = 1;
442581ad6265SDimitry Andric       break;
442681ad6265SDimitry Andric     default:
442781ad6265SDimitry Andric       ArgNo = 0;
442881ad6265SDimitry Andric       break;
442981ad6265SDimitry Andric     }
443081ad6265SDimitry Andric     if (!Attrs.getParamElementType(ArgNo)) {
443181ad6265SDimitry Andric       Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
443281ad6265SDimitry Andric       if (!ElTy)
443381ad6265SDimitry Andric         return error("Missing element type for elementtype upgrade");
4434fe6060f1SDimitry Andric       Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
443581ad6265SDimitry Andric       Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4436fe6060f1SDimitry Andric     }
4437fe6060f1SDimitry Andric     break;
443881ad6265SDimitry Andric   }
4439fe6060f1SDimitry Andric   default:
4440fe6060f1SDimitry Andric     break;
4441fe6060f1SDimitry Andric   }
444281ad6265SDimitry Andric 
444381ad6265SDimitry Andric   CB->setAttributes(Attrs);
444481ad6265SDimitry Andric   return Error::success();
4445*0b57cec5SDimitry Andric }
4446*0b57cec5SDimitry Andric 
4447*0b57cec5SDimitry Andric /// Lazily parse the specified function body block.
4448*0b57cec5SDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) {
4449*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4450*0b57cec5SDimitry Andric     return Err;
4451*0b57cec5SDimitry Andric 
4452*0b57cec5SDimitry Andric   // Unexpected unresolved metadata when parsing function.
4453*0b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
4454*0b57cec5SDimitry Andric     return error("Invalid function metadata: incoming forward references");
4455*0b57cec5SDimitry Andric 
4456*0b57cec5SDimitry Andric   InstructionList.clear();
4457*0b57cec5SDimitry Andric   unsigned ModuleValueListSize = ValueList.size();
4458*0b57cec5SDimitry Andric   unsigned ModuleMDLoaderSize = MDLoader->size();
4459*0b57cec5SDimitry Andric 
4460*0b57cec5SDimitry Andric   // Add all the function arguments to the value table.
4461*0b57cec5SDimitry Andric   unsigned ArgNo = 0;
446281ad6265SDimitry Andric   unsigned FTyID = FunctionTypeIDs[F];
4463*0b57cec5SDimitry Andric   for (Argument &I : F->args()) {
446481ad6265SDimitry Andric     unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
446581ad6265SDimitry Andric     assert(I.getType() == getTypeByID(ArgTyID) &&
4466*0b57cec5SDimitry Andric            "Incorrect fully specified type for Function Argument");
446781ad6265SDimitry Andric     ValueList.push_back(&I, ArgTyID);
446881ad6265SDimitry Andric     ++ArgNo;
4469*0b57cec5SDimitry Andric   }
4470*0b57cec5SDimitry Andric   unsigned NextValueNo = ValueList.size();
4471*0b57cec5SDimitry Andric   BasicBlock *CurBB = nullptr;
4472*0b57cec5SDimitry Andric   unsigned CurBBNo = 0;
447381ad6265SDimitry Andric   // Block into which constant expressions from phi nodes are materialized.
447481ad6265SDimitry Andric   BasicBlock *PhiConstExprBB = nullptr;
447581ad6265SDimitry Andric   // Edge blocks for phi nodes into which constant expressions have been
447681ad6265SDimitry Andric   // expanded.
447781ad6265SDimitry Andric   SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4>
447881ad6265SDimitry Andric     ConstExprEdgeBBs;
4479*0b57cec5SDimitry Andric 
4480*0b57cec5SDimitry Andric   DebugLoc LastLoc;
4481*0b57cec5SDimitry Andric   auto getLastInstruction = [&]() -> Instruction * {
4482*0b57cec5SDimitry Andric     if (CurBB && !CurBB->empty())
4483*0b57cec5SDimitry Andric       return &CurBB->back();
4484*0b57cec5SDimitry Andric     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4485*0b57cec5SDimitry Andric              !FunctionBBs[CurBBNo - 1]->empty())
4486*0b57cec5SDimitry Andric       return &FunctionBBs[CurBBNo - 1]->back();
4487*0b57cec5SDimitry Andric     return nullptr;
4488*0b57cec5SDimitry Andric   };
4489*0b57cec5SDimitry Andric 
4490*0b57cec5SDimitry Andric   std::vector<OperandBundleDef> OperandBundles;
4491*0b57cec5SDimitry Andric 
4492*0b57cec5SDimitry Andric   // Read all the records.
4493*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
4494*0b57cec5SDimitry Andric 
4495*0b57cec5SDimitry Andric   while (true) {
4496*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4497*0b57cec5SDimitry Andric     if (!MaybeEntry)
4498*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
4499*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
4500*0b57cec5SDimitry Andric 
4501*0b57cec5SDimitry Andric     switch (Entry.Kind) {
4502*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
4503*0b57cec5SDimitry Andric       return error("Malformed block");
4504*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
4505*0b57cec5SDimitry Andric       goto OutOfRecordLoop;
4506*0b57cec5SDimitry Andric 
4507*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
4508*0b57cec5SDimitry Andric       switch (Entry.ID) {
4509*0b57cec5SDimitry Andric       default:  // Skip unknown content.
4510*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
4511*0b57cec5SDimitry Andric           return Err;
4512*0b57cec5SDimitry Andric         break;
4513*0b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
4514*0b57cec5SDimitry Andric         if (Error Err = parseConstants())
4515*0b57cec5SDimitry Andric           return Err;
4516*0b57cec5SDimitry Andric         NextValueNo = ValueList.size();
4517*0b57cec5SDimitry Andric         break;
4518*0b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
4519*0b57cec5SDimitry Andric         if (Error Err = parseValueSymbolTable())
4520*0b57cec5SDimitry Andric           return Err;
4521*0b57cec5SDimitry Andric         break;
4522*0b57cec5SDimitry Andric       case bitc::METADATA_ATTACHMENT_ID:
4523*0b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
4524*0b57cec5SDimitry Andric           return Err;
4525*0b57cec5SDimitry Andric         break;
4526*0b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
4527*0b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() &&
4528*0b57cec5SDimitry Andric                "Must read all module-level metadata before function-level");
4529*0b57cec5SDimitry Andric         if (Error Err = MDLoader->parseFunctionMetadata())
4530*0b57cec5SDimitry Andric           return Err;
4531*0b57cec5SDimitry Andric         break;
4532*0b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
4533*0b57cec5SDimitry Andric         if (Error Err = parseUseLists())
4534*0b57cec5SDimitry Andric           return Err;
4535*0b57cec5SDimitry Andric         break;
4536*0b57cec5SDimitry Andric       }
4537*0b57cec5SDimitry Andric       continue;
4538*0b57cec5SDimitry Andric 
4539*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
4540*0b57cec5SDimitry Andric       // The interesting case.
4541*0b57cec5SDimitry Andric       break;
4542*0b57cec5SDimitry Andric     }
4543*0b57cec5SDimitry Andric 
4544*0b57cec5SDimitry Andric     // Read a record.
4545*0b57cec5SDimitry Andric     Record.clear();
4546*0b57cec5SDimitry Andric     Instruction *I = nullptr;
454781ad6265SDimitry Andric     unsigned ResTypeID = InvalidTypeID;
4548*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4549*0b57cec5SDimitry Andric     if (!MaybeBitCode)
4550*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
4551*0b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
4552*0b57cec5SDimitry Andric     default: // Default behavior: reject
4553*0b57cec5SDimitry Andric       return error("Invalid value");
4554*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4555e8d8bef9SDimitry Andric       if (Record.empty() || Record[0] == 0)
4556*0b57cec5SDimitry Andric         return error("Invalid record");
4557*0b57cec5SDimitry Andric       // Create all the basic blocks for the function.
4558*0b57cec5SDimitry Andric       FunctionBBs.resize(Record[0]);
4559*0b57cec5SDimitry Andric 
4560*0b57cec5SDimitry Andric       // See if anything took the address of blocks in this function.
4561*0b57cec5SDimitry Andric       auto BBFRI = BasicBlockFwdRefs.find(F);
4562*0b57cec5SDimitry Andric       if (BBFRI == BasicBlockFwdRefs.end()) {
45634824e7fdSDimitry Andric         for (BasicBlock *&BB : FunctionBBs)
45644824e7fdSDimitry Andric           BB = BasicBlock::Create(Context, "", F);
4565*0b57cec5SDimitry Andric       } else {
4566*0b57cec5SDimitry Andric         auto &BBRefs = BBFRI->second;
4567*0b57cec5SDimitry Andric         // Check for invalid basic block references.
4568*0b57cec5SDimitry Andric         if (BBRefs.size() > FunctionBBs.size())
4569*0b57cec5SDimitry Andric           return error("Invalid ID");
4570*0b57cec5SDimitry Andric         assert(!BBRefs.empty() && "Unexpected empty array");
4571*0b57cec5SDimitry Andric         assert(!BBRefs.front() && "Invalid reference to entry block");
4572*0b57cec5SDimitry Andric         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4573*0b57cec5SDimitry Andric              ++I)
4574*0b57cec5SDimitry Andric           if (I < RE && BBRefs[I]) {
4575*0b57cec5SDimitry Andric             BBRefs[I]->insertInto(F);
4576*0b57cec5SDimitry Andric             FunctionBBs[I] = BBRefs[I];
4577*0b57cec5SDimitry Andric           } else {
4578*0b57cec5SDimitry Andric             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4579*0b57cec5SDimitry Andric           }
4580*0b57cec5SDimitry Andric 
4581*0b57cec5SDimitry Andric         // Erase from the table.
4582*0b57cec5SDimitry Andric         BasicBlockFwdRefs.erase(BBFRI);
4583*0b57cec5SDimitry Andric       }
4584*0b57cec5SDimitry Andric 
4585*0b57cec5SDimitry Andric       CurBB = FunctionBBs[0];
4586*0b57cec5SDimitry Andric       continue;
4587*0b57cec5SDimitry Andric     }
4588*0b57cec5SDimitry Andric 
458981ad6265SDimitry Andric     case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
459081ad6265SDimitry Andric       // The record should not be emitted if it's an empty list.
459181ad6265SDimitry Andric       if (Record.empty())
459281ad6265SDimitry Andric         return error("Invalid record");
459381ad6265SDimitry Andric       // When we have the RARE case of a BlockAddress Constant that is not
459481ad6265SDimitry Andric       // scoped to the Function it refers to, we need to conservatively
459581ad6265SDimitry Andric       // materialize the referred to Function, regardless of whether or not
459681ad6265SDimitry Andric       // that Function will ultimately be linked, otherwise users of
459781ad6265SDimitry Andric       // BitcodeReader might start splicing out Function bodies such that we
459881ad6265SDimitry Andric       // might no longer be able to materialize the BlockAddress since the
459981ad6265SDimitry Andric       // BasicBlock (and entire body of the Function) the BlockAddress refers
460081ad6265SDimitry Andric       // to may have been moved. In the case that the user of BitcodeReader
460181ad6265SDimitry Andric       // decides ultimately not to link the Function body, materializing here
460281ad6265SDimitry Andric       // could be considered wasteful, but it's better than a deserialization
460381ad6265SDimitry Andric       // failure as described. This keeps BitcodeReader unaware of complex
460481ad6265SDimitry Andric       // linkage policy decisions such as those use by LTO, leaving those
460581ad6265SDimitry Andric       // decisions "one layer up."
460681ad6265SDimitry Andric       for (uint64_t ValID : Record)
460781ad6265SDimitry Andric         if (auto *F = dyn_cast<Function>(ValueList[ValID]))
460881ad6265SDimitry Andric           BackwardRefFunctions.push_back(F);
460981ad6265SDimitry Andric         else
461081ad6265SDimitry Andric           return error("Invalid record");
461181ad6265SDimitry Andric 
461281ad6265SDimitry Andric       continue;
461381ad6265SDimitry Andric 
4614*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4615*0b57cec5SDimitry Andric       // This record indicates that the last instruction is at the same
4616*0b57cec5SDimitry Andric       // location as the previous instruction with a location.
4617*0b57cec5SDimitry Andric       I = getLastInstruction();
4618*0b57cec5SDimitry Andric 
4619*0b57cec5SDimitry Andric       if (!I)
4620*0b57cec5SDimitry Andric         return error("Invalid record");
4621*0b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
4622*0b57cec5SDimitry Andric       I = nullptr;
4623*0b57cec5SDimitry Andric       continue;
4624*0b57cec5SDimitry Andric 
4625*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
4626*0b57cec5SDimitry Andric       I = getLastInstruction();
4627*0b57cec5SDimitry Andric       if (!I || Record.size() < 4)
4628*0b57cec5SDimitry Andric         return error("Invalid record");
4629*0b57cec5SDimitry Andric 
4630*0b57cec5SDimitry Andric       unsigned Line = Record[0], Col = Record[1];
4631*0b57cec5SDimitry Andric       unsigned ScopeID = Record[2], IAID = Record[3];
4632*0b57cec5SDimitry Andric       bool isImplicitCode = Record.size() == 5 && Record[4];
4633*0b57cec5SDimitry Andric 
4634*0b57cec5SDimitry Andric       MDNode *Scope = nullptr, *IA = nullptr;
4635*0b57cec5SDimitry Andric       if (ScopeID) {
4636*0b57cec5SDimitry Andric         Scope = dyn_cast_or_null<MDNode>(
4637*0b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
4638*0b57cec5SDimitry Andric         if (!Scope)
4639*0b57cec5SDimitry Andric           return error("Invalid record");
4640*0b57cec5SDimitry Andric       }
4641*0b57cec5SDimitry Andric       if (IAID) {
4642*0b57cec5SDimitry Andric         IA = dyn_cast_or_null<MDNode>(
4643*0b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
4644*0b57cec5SDimitry Andric         if (!IA)
4645*0b57cec5SDimitry Andric           return error("Invalid record");
4646*0b57cec5SDimitry Andric       }
4647e8d8bef9SDimitry Andric       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4648e8d8bef9SDimitry Andric                                 isImplicitCode);
4649*0b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
4650*0b57cec5SDimitry Andric       I = nullptr;
4651*0b57cec5SDimitry Andric       continue;
4652*0b57cec5SDimitry Andric     }
4653*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
4654*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4655*0b57cec5SDimitry Andric       Value *LHS;
465681ad6265SDimitry Andric       unsigned TypeID;
465781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
4658*0b57cec5SDimitry Andric           OpNum+1 > Record.size())
4659*0b57cec5SDimitry Andric         return error("Invalid record");
4660*0b57cec5SDimitry Andric 
4661*0b57cec5SDimitry Andric       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
4662*0b57cec5SDimitry Andric       if (Opc == -1)
4663*0b57cec5SDimitry Andric         return error("Invalid record");
4664*0b57cec5SDimitry Andric       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
466581ad6265SDimitry Andric       ResTypeID = TypeID;
4666*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4667*0b57cec5SDimitry Andric       if (OpNum < Record.size()) {
4668*0b57cec5SDimitry Andric         if (isa<FPMathOperator>(I)) {
4669*0b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4670*0b57cec5SDimitry Andric           if (FMF.any())
4671*0b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
4672*0b57cec5SDimitry Andric         }
4673*0b57cec5SDimitry Andric       }
4674*0b57cec5SDimitry Andric       break;
4675*0b57cec5SDimitry Andric     }
4676*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4677*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4678*0b57cec5SDimitry Andric       Value *LHS, *RHS;
467981ad6265SDimitry Andric       unsigned TypeID;
468081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
468181ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
468281ad6265SDimitry Andric                    CurBB) ||
4683*0b57cec5SDimitry Andric           OpNum+1 > Record.size())
4684*0b57cec5SDimitry Andric         return error("Invalid record");
4685*0b57cec5SDimitry Andric 
4686*0b57cec5SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4687*0b57cec5SDimitry Andric       if (Opc == -1)
4688*0b57cec5SDimitry Andric         return error("Invalid record");
4689*0b57cec5SDimitry Andric       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
469081ad6265SDimitry Andric       ResTypeID = TypeID;
4691*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4692*0b57cec5SDimitry Andric       if (OpNum < Record.size()) {
4693*0b57cec5SDimitry Andric         if (Opc == Instruction::Add ||
4694*0b57cec5SDimitry Andric             Opc == Instruction::Sub ||
4695*0b57cec5SDimitry Andric             Opc == Instruction::Mul ||
4696*0b57cec5SDimitry Andric             Opc == Instruction::Shl) {
4697*0b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4698*0b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4699*0b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4700*0b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4701*0b57cec5SDimitry Andric         } else if (Opc == Instruction::SDiv ||
4702*0b57cec5SDimitry Andric                    Opc == Instruction::UDiv ||
4703*0b57cec5SDimitry Andric                    Opc == Instruction::LShr ||
4704*0b57cec5SDimitry Andric                    Opc == Instruction::AShr) {
4705*0b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4706*0b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setIsExact(true);
4707*0b57cec5SDimitry Andric         } else if (isa<FPMathOperator>(I)) {
4708*0b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4709*0b57cec5SDimitry Andric           if (FMF.any())
4710*0b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
4711*0b57cec5SDimitry Andric         }
4712*0b57cec5SDimitry Andric 
4713*0b57cec5SDimitry Andric       }
4714*0b57cec5SDimitry Andric       break;
4715*0b57cec5SDimitry Andric     }
4716*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4717*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4718*0b57cec5SDimitry Andric       Value *Op;
471981ad6265SDimitry Andric       unsigned OpTypeID;
472081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
4721*0b57cec5SDimitry Andric           OpNum+2 != Record.size())
4722*0b57cec5SDimitry Andric         return error("Invalid record");
4723*0b57cec5SDimitry Andric 
472481ad6265SDimitry Andric       ResTypeID = Record[OpNum];
472581ad6265SDimitry Andric       Type *ResTy = getTypeByID(ResTypeID);
4726*0b57cec5SDimitry Andric       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4727*0b57cec5SDimitry Andric       if (Opc == -1 || !ResTy)
4728*0b57cec5SDimitry Andric         return error("Invalid record");
4729*0b57cec5SDimitry Andric       Instruction *Temp = nullptr;
4730*0b57cec5SDimitry Andric       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4731*0b57cec5SDimitry Andric         if (Temp) {
4732*0b57cec5SDimitry Andric           InstructionList.push_back(Temp);
4733480093f4SDimitry Andric           assert(CurBB && "No current BB?");
4734*0b57cec5SDimitry Andric           CurBB->getInstList().push_back(Temp);
4735*0b57cec5SDimitry Andric         }
4736*0b57cec5SDimitry Andric       } else {
4737*0b57cec5SDimitry Andric         auto CastOp = (Instruction::CastOps)Opc;
4738*0b57cec5SDimitry Andric         if (!CastInst::castIsValid(CastOp, Op, ResTy))
4739*0b57cec5SDimitry Andric           return error("Invalid cast");
4740*0b57cec5SDimitry Andric         I = CastInst::Create(CastOp, Op, ResTy);
4741*0b57cec5SDimitry Andric       }
4742*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4743*0b57cec5SDimitry Andric       break;
4744*0b57cec5SDimitry Andric     }
4745*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4746*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP_OLD:
4747*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4748*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4749*0b57cec5SDimitry Andric 
475081ad6265SDimitry Andric       unsigned TyID;
4751*0b57cec5SDimitry Andric       Type *Ty;
4752*0b57cec5SDimitry Andric       bool InBounds;
4753*0b57cec5SDimitry Andric 
4754*0b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4755*0b57cec5SDimitry Andric         InBounds = Record[OpNum++];
475681ad6265SDimitry Andric         TyID = Record[OpNum++];
475781ad6265SDimitry Andric         Ty = getTypeByID(TyID);
4758*0b57cec5SDimitry Andric       } else {
4759*0b57cec5SDimitry Andric         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
476081ad6265SDimitry Andric         TyID = InvalidTypeID;
4761*0b57cec5SDimitry Andric         Ty = nullptr;
4762*0b57cec5SDimitry Andric       }
4763*0b57cec5SDimitry Andric 
4764*0b57cec5SDimitry Andric       Value *BasePtr;
476581ad6265SDimitry Andric       unsigned BasePtrTypeID;
476681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
476781ad6265SDimitry Andric                            CurBB))
4768*0b57cec5SDimitry Andric         return error("Invalid record");
4769*0b57cec5SDimitry Andric 
4770*0b57cec5SDimitry Andric       if (!Ty) {
477181ad6265SDimitry Andric         TyID = getContainedTypeID(BasePtrTypeID);
477281ad6265SDimitry Andric         if (BasePtr->getType()->isVectorTy())
477381ad6265SDimitry Andric           TyID = getContainedTypeID(TyID);
477481ad6265SDimitry Andric         Ty = getTypeByID(TyID);
4775fe6060f1SDimitry Andric       } else if (!cast<PointerType>(BasePtr->getType()->getScalarType())
4776fe6060f1SDimitry Andric                       ->isOpaqueOrPointeeTypeMatches(Ty)) {
4777*0b57cec5SDimitry Andric         return error(
4778*0b57cec5SDimitry Andric             "Explicit gep type does not match pointee type of pointer operand");
4779fe6060f1SDimitry Andric       }
4780*0b57cec5SDimitry Andric 
4781*0b57cec5SDimitry Andric       SmallVector<Value*, 16> GEPIdx;
4782*0b57cec5SDimitry Andric       while (OpNum != Record.size()) {
4783*0b57cec5SDimitry Andric         Value *Op;
478481ad6265SDimitry Andric         unsigned OpTypeID;
478581ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
4786*0b57cec5SDimitry Andric           return error("Invalid record");
4787*0b57cec5SDimitry Andric         GEPIdx.push_back(Op);
4788*0b57cec5SDimitry Andric       }
4789*0b57cec5SDimitry Andric 
4790*0b57cec5SDimitry Andric       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4791*0b57cec5SDimitry Andric 
479281ad6265SDimitry Andric       ResTypeID = TyID;
479381ad6265SDimitry Andric       if (cast<GEPOperator>(I)->getNumIndices() != 0) {
479481ad6265SDimitry Andric         auto GTI = std::next(gep_type_begin(I));
479581ad6265SDimitry Andric         for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
479681ad6265SDimitry Andric           unsigned SubType = 0;
479781ad6265SDimitry Andric           if (GTI.isStruct()) {
479881ad6265SDimitry Andric             ConstantInt *IdxC =
479981ad6265SDimitry Andric                 Idx->getType()->isVectorTy()
480081ad6265SDimitry Andric                     ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
480181ad6265SDimitry Andric                     : cast<ConstantInt>(Idx);
480281ad6265SDimitry Andric             SubType = IdxC->getZExtValue();
480381ad6265SDimitry Andric           }
480481ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID, SubType);
480581ad6265SDimitry Andric           ++GTI;
480681ad6265SDimitry Andric         }
480781ad6265SDimitry Andric       }
480881ad6265SDimitry Andric 
480981ad6265SDimitry Andric       // At this point ResTypeID is the result element type. We need a pointer
481081ad6265SDimitry Andric       // or vector of pointer to it.
481181ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
481281ad6265SDimitry Andric       if (I->getType()->isVectorTy())
481381ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
481481ad6265SDimitry Andric 
4815*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4816*0b57cec5SDimitry Andric       if (InBounds)
4817*0b57cec5SDimitry Andric         cast<GetElementPtrInst>(I)->setIsInBounds(true);
4818*0b57cec5SDimitry Andric       break;
4819*0b57cec5SDimitry Andric     }
4820*0b57cec5SDimitry Andric 
4821*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4822*0b57cec5SDimitry Andric                                        // EXTRACTVAL: [opty, opval, n x indices]
4823*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4824*0b57cec5SDimitry Andric       Value *Agg;
482581ad6265SDimitry Andric       unsigned AggTypeID;
482681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
4827*0b57cec5SDimitry Andric         return error("Invalid record");
4828fe6060f1SDimitry Andric       Type *Ty = Agg->getType();
4829*0b57cec5SDimitry Andric 
4830*0b57cec5SDimitry Andric       unsigned RecSize = Record.size();
4831*0b57cec5SDimitry Andric       if (OpNum == RecSize)
4832*0b57cec5SDimitry Andric         return error("EXTRACTVAL: Invalid instruction with 0 indices");
4833*0b57cec5SDimitry Andric 
4834*0b57cec5SDimitry Andric       SmallVector<unsigned, 4> EXTRACTVALIdx;
483581ad6265SDimitry Andric       ResTypeID = AggTypeID;
4836*0b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
4837fe6060f1SDimitry Andric         bool IsArray = Ty->isArrayTy();
4838fe6060f1SDimitry Andric         bool IsStruct = Ty->isStructTy();
4839*0b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
4840*0b57cec5SDimitry Andric 
4841*0b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
4842*0b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid type");
4843*0b57cec5SDimitry Andric         if ((unsigned)Index != Index)
4844*0b57cec5SDimitry Andric           return error("Invalid value");
4845fe6060f1SDimitry Andric         if (IsStruct && Index >= Ty->getStructNumElements())
4846*0b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid struct index");
4847fe6060f1SDimitry Andric         if (IsArray && Index >= Ty->getArrayNumElements())
4848*0b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid array index");
4849*0b57cec5SDimitry Andric         EXTRACTVALIdx.push_back((unsigned)Index);
4850*0b57cec5SDimitry Andric 
485181ad6265SDimitry Andric         if (IsStruct) {
4852fe6060f1SDimitry Andric           Ty = Ty->getStructElementType(Index);
485381ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID, Index);
485481ad6265SDimitry Andric         } else {
4855fe6060f1SDimitry Andric           Ty = Ty->getArrayElementType();
485681ad6265SDimitry Andric           ResTypeID = getContainedTypeID(ResTypeID);
485781ad6265SDimitry Andric         }
4858*0b57cec5SDimitry Andric       }
4859*0b57cec5SDimitry Andric 
4860*0b57cec5SDimitry Andric       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4861*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4862*0b57cec5SDimitry Andric       break;
4863*0b57cec5SDimitry Andric     }
4864*0b57cec5SDimitry Andric 
4865*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTVAL: {
4866*0b57cec5SDimitry Andric                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
4867*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4868*0b57cec5SDimitry Andric       Value *Agg;
486981ad6265SDimitry Andric       unsigned AggTypeID;
487081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
4871*0b57cec5SDimitry Andric         return error("Invalid record");
4872*0b57cec5SDimitry Andric       Value *Val;
487381ad6265SDimitry Andric       unsigned ValTypeID;
487481ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
4875*0b57cec5SDimitry Andric         return error("Invalid record");
4876*0b57cec5SDimitry Andric 
4877*0b57cec5SDimitry Andric       unsigned RecSize = Record.size();
4878*0b57cec5SDimitry Andric       if (OpNum == RecSize)
4879*0b57cec5SDimitry Andric         return error("INSERTVAL: Invalid instruction with 0 indices");
4880*0b57cec5SDimitry Andric 
4881*0b57cec5SDimitry Andric       SmallVector<unsigned, 4> INSERTVALIdx;
4882*0b57cec5SDimitry Andric       Type *CurTy = Agg->getType();
4883*0b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
4884*0b57cec5SDimitry Andric         bool IsArray = CurTy->isArrayTy();
4885*0b57cec5SDimitry Andric         bool IsStruct = CurTy->isStructTy();
4886*0b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
4887*0b57cec5SDimitry Andric 
4888*0b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
4889*0b57cec5SDimitry Andric           return error("INSERTVAL: Invalid type");
4890*0b57cec5SDimitry Andric         if ((unsigned)Index != Index)
4891*0b57cec5SDimitry Andric           return error("Invalid value");
4892*0b57cec5SDimitry Andric         if (IsStruct && Index >= CurTy->getStructNumElements())
4893*0b57cec5SDimitry Andric           return error("INSERTVAL: Invalid struct index");
4894*0b57cec5SDimitry Andric         if (IsArray && Index >= CurTy->getArrayNumElements())
4895*0b57cec5SDimitry Andric           return error("INSERTVAL: Invalid array index");
4896*0b57cec5SDimitry Andric 
4897*0b57cec5SDimitry Andric         INSERTVALIdx.push_back((unsigned)Index);
4898*0b57cec5SDimitry Andric         if (IsStruct)
4899*0b57cec5SDimitry Andric           CurTy = CurTy->getStructElementType(Index);
4900*0b57cec5SDimitry Andric         else
4901*0b57cec5SDimitry Andric           CurTy = CurTy->getArrayElementType();
4902*0b57cec5SDimitry Andric       }
4903*0b57cec5SDimitry Andric 
4904*0b57cec5SDimitry Andric       if (CurTy != Val->getType())
4905*0b57cec5SDimitry Andric         return error("Inserted value type doesn't match aggregate type");
4906*0b57cec5SDimitry Andric 
4907*0b57cec5SDimitry Andric       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
490881ad6265SDimitry Andric       ResTypeID = AggTypeID;
4909*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4910*0b57cec5SDimitry Andric       break;
4911*0b57cec5SDimitry Andric     }
4912*0b57cec5SDimitry Andric 
4913*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4914*0b57cec5SDimitry Andric       // obsolete form of select
4915*0b57cec5SDimitry Andric       // handles select i1 ... in old bitcode
4916*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4917*0b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
491881ad6265SDimitry Andric       unsigned TypeID;
491981ad6265SDimitry Andric       Type *CondType = Type::getInt1Ty(Context);
492081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
492181ad6265SDimitry Andric                            CurBB) ||
492281ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
492381ad6265SDimitry Andric                    FalseVal, CurBB) ||
492481ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, CondType,
492581ad6265SDimitry Andric                    getVirtualTypeID(CondType), Cond, CurBB))
4926*0b57cec5SDimitry Andric         return error("Invalid record");
4927*0b57cec5SDimitry Andric 
4928*0b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
492981ad6265SDimitry Andric       ResTypeID = TypeID;
4930*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4931*0b57cec5SDimitry Andric       break;
4932*0b57cec5SDimitry Andric     }
4933*0b57cec5SDimitry Andric 
4934*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4935*0b57cec5SDimitry Andric       // new form of select
4936*0b57cec5SDimitry Andric       // handles select i1 or select [N x i1]
4937*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4938*0b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
493981ad6265SDimitry Andric       unsigned ValTypeID, CondTypeID;
494081ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
494181ad6265SDimitry Andric                            CurBB) ||
494281ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
494381ad6265SDimitry Andric                    FalseVal, CurBB) ||
494481ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
4945*0b57cec5SDimitry Andric         return error("Invalid record");
4946*0b57cec5SDimitry Andric 
4947*0b57cec5SDimitry Andric       // select condition can be either i1 or [N x i1]
4948*0b57cec5SDimitry Andric       if (VectorType* vector_type =
4949*0b57cec5SDimitry Andric           dyn_cast<VectorType>(Cond->getType())) {
4950*0b57cec5SDimitry Andric         // expect <n x i1>
4951*0b57cec5SDimitry Andric         if (vector_type->getElementType() != Type::getInt1Ty(Context))
4952*0b57cec5SDimitry Andric           return error("Invalid type for value");
4953*0b57cec5SDimitry Andric       } else {
4954*0b57cec5SDimitry Andric         // expect i1
4955*0b57cec5SDimitry Andric         if (Cond->getType() != Type::getInt1Ty(Context))
4956*0b57cec5SDimitry Andric           return error("Invalid type for value");
4957*0b57cec5SDimitry Andric       }
4958*0b57cec5SDimitry Andric 
4959*0b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
496081ad6265SDimitry Andric       ResTypeID = ValTypeID;
4961*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4962*0b57cec5SDimitry Andric       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
4963*0b57cec5SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4964*0b57cec5SDimitry Andric         if (FMF.any())
4965*0b57cec5SDimitry Andric           I->setFastMathFlags(FMF);
4966*0b57cec5SDimitry Andric       }
4967*0b57cec5SDimitry Andric       break;
4968*0b57cec5SDimitry Andric     }
4969*0b57cec5SDimitry Andric 
4970*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4971*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4972*0b57cec5SDimitry Andric       Value *Vec, *Idx;
497381ad6265SDimitry Andric       unsigned VecTypeID, IdxTypeID;
497481ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
497581ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
4976*0b57cec5SDimitry Andric         return error("Invalid record");
4977*0b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
4978*0b57cec5SDimitry Andric         return error("Invalid type for value");
4979*0b57cec5SDimitry Andric       I = ExtractElementInst::Create(Vec, Idx);
498081ad6265SDimitry Andric       ResTypeID = getContainedTypeID(VecTypeID);
4981*0b57cec5SDimitry Andric       InstructionList.push_back(I);
4982*0b57cec5SDimitry Andric       break;
4983*0b57cec5SDimitry Andric     }
4984*0b57cec5SDimitry Andric 
4985*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4986*0b57cec5SDimitry Andric       unsigned OpNum = 0;
4987*0b57cec5SDimitry Andric       Value *Vec, *Elt, *Idx;
498881ad6265SDimitry Andric       unsigned VecTypeID, IdxTypeID;
498981ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
4990*0b57cec5SDimitry Andric         return error("Invalid record");
4991*0b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
4992*0b57cec5SDimitry Andric         return error("Invalid type for value");
4993*0b57cec5SDimitry Andric       if (popValue(Record, OpNum, NextValueNo,
499481ad6265SDimitry Andric                    cast<VectorType>(Vec->getType())->getElementType(),
499581ad6265SDimitry Andric                    getContainedTypeID(VecTypeID), Elt, CurBB) ||
499681ad6265SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
4997*0b57cec5SDimitry Andric         return error("Invalid record");
4998*0b57cec5SDimitry Andric       I = InsertElementInst::Create(Vec, Elt, Idx);
499981ad6265SDimitry Andric       ResTypeID = VecTypeID;
5000*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5001*0b57cec5SDimitry Andric       break;
5002*0b57cec5SDimitry Andric     }
5003*0b57cec5SDimitry Andric 
5004*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
5005*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5006*0b57cec5SDimitry Andric       Value *Vec1, *Vec2, *Mask;
500781ad6265SDimitry Andric       unsigned Vec1TypeID;
500881ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
500981ad6265SDimitry Andric                            CurBB) ||
501081ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
501181ad6265SDimitry Andric                    Vec2, CurBB))
5012*0b57cec5SDimitry Andric         return error("Invalid record");
5013*0b57cec5SDimitry Andric 
501481ad6265SDimitry Andric       unsigned MaskTypeID;
501581ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5016*0b57cec5SDimitry Andric         return error("Invalid record");
5017*0b57cec5SDimitry Andric       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
5018*0b57cec5SDimitry Andric         return error("Invalid type for value");
50195ffd83dbSDimitry Andric 
5020*0b57cec5SDimitry Andric       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
502181ad6265SDimitry Andric       ResTypeID =
502281ad6265SDimitry Andric           getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
5023*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5024*0b57cec5SDimitry Andric       break;
5025*0b57cec5SDimitry Andric     }
5026*0b57cec5SDimitry Andric 
5027*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
5028*0b57cec5SDimitry Andric       // Old form of ICmp/FCmp returning bool
5029*0b57cec5SDimitry Andric       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
5030*0b57cec5SDimitry Andric       // both legal on vectors but had different behaviour.
5031*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
5032*0b57cec5SDimitry Andric       // FCmp/ICmp returning bool or vector of bool
5033*0b57cec5SDimitry Andric 
5034*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5035*0b57cec5SDimitry Andric       Value *LHS, *RHS;
503681ad6265SDimitry Andric       unsigned LHSTypeID;
503781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
503881ad6265SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
503981ad6265SDimitry Andric                    CurBB))
5040*0b57cec5SDimitry Andric         return error("Invalid record");
5041*0b57cec5SDimitry Andric 
5042*0b57cec5SDimitry Andric       if (OpNum >= Record.size())
5043*0b57cec5SDimitry Andric         return error(
5044*0b57cec5SDimitry Andric             "Invalid record: operand number exceeded available operands");
5045*0b57cec5SDimitry Andric 
5046*0b57cec5SDimitry Andric       unsigned PredVal = Record[OpNum];
5047*0b57cec5SDimitry Andric       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
5048*0b57cec5SDimitry Andric       FastMathFlags FMF;
5049*0b57cec5SDimitry Andric       if (IsFP && Record.size() > OpNum+1)
5050*0b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[++OpNum]);
5051*0b57cec5SDimitry Andric 
5052*0b57cec5SDimitry Andric       if (OpNum+1 != Record.size())
5053*0b57cec5SDimitry Andric         return error("Invalid record");
5054*0b57cec5SDimitry Andric 
5055*0b57cec5SDimitry Andric       if (LHS->getType()->isFPOrFPVectorTy())
5056*0b57cec5SDimitry Andric         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
5057*0b57cec5SDimitry Andric       else
5058*0b57cec5SDimitry Andric         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
5059*0b57cec5SDimitry Andric 
506081ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
506181ad6265SDimitry Andric       if (LHS->getType()->isVectorTy())
506281ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
506381ad6265SDimitry Andric 
5064*0b57cec5SDimitry Andric       if (FMF.any())
5065*0b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
5066*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5067*0b57cec5SDimitry Andric       break;
5068*0b57cec5SDimitry Andric     }
5069*0b57cec5SDimitry Andric 
5070*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
5071*0b57cec5SDimitry Andric       {
5072*0b57cec5SDimitry Andric         unsigned Size = Record.size();
5073*0b57cec5SDimitry Andric         if (Size == 0) {
5074*0b57cec5SDimitry Andric           I = ReturnInst::Create(Context);
5075*0b57cec5SDimitry Andric           InstructionList.push_back(I);
5076*0b57cec5SDimitry Andric           break;
5077*0b57cec5SDimitry Andric         }
5078*0b57cec5SDimitry Andric 
5079*0b57cec5SDimitry Andric         unsigned OpNum = 0;
5080*0b57cec5SDimitry Andric         Value *Op = nullptr;
508181ad6265SDimitry Andric         unsigned OpTypeID;
508281ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5083*0b57cec5SDimitry Andric           return error("Invalid record");
5084*0b57cec5SDimitry Andric         if (OpNum != Record.size())
5085*0b57cec5SDimitry Andric           return error("Invalid record");
5086*0b57cec5SDimitry Andric 
5087*0b57cec5SDimitry Andric         I = ReturnInst::Create(Context, Op);
5088*0b57cec5SDimitry Andric         InstructionList.push_back(I);
5089*0b57cec5SDimitry Andric         break;
5090*0b57cec5SDimitry Andric       }
5091*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
5092*0b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 3)
5093*0b57cec5SDimitry Andric         return error("Invalid record");
5094*0b57cec5SDimitry Andric       BasicBlock *TrueDest = getBasicBlock(Record[0]);
5095*0b57cec5SDimitry Andric       if (!TrueDest)
5096*0b57cec5SDimitry Andric         return error("Invalid record");
5097*0b57cec5SDimitry Andric 
5098*0b57cec5SDimitry Andric       if (Record.size() == 1) {
5099*0b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest);
5100*0b57cec5SDimitry Andric         InstructionList.push_back(I);
5101*0b57cec5SDimitry Andric       }
5102*0b57cec5SDimitry Andric       else {
5103*0b57cec5SDimitry Andric         BasicBlock *FalseDest = getBasicBlock(Record[1]);
510481ad6265SDimitry Andric         Type *CondType = Type::getInt1Ty(Context);
510581ad6265SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, CondType,
510681ad6265SDimitry Andric                                getVirtualTypeID(CondType), CurBB);
5107*0b57cec5SDimitry Andric         if (!FalseDest || !Cond)
5108*0b57cec5SDimitry Andric           return error("Invalid record");
5109*0b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest, FalseDest, Cond);
5110*0b57cec5SDimitry Andric         InstructionList.push_back(I);
5111*0b57cec5SDimitry Andric       }
5112*0b57cec5SDimitry Andric       break;
5113*0b57cec5SDimitry Andric     }
5114*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
5115*0b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 2)
5116*0b57cec5SDimitry Andric         return error("Invalid record");
5117*0b57cec5SDimitry Andric       unsigned Idx = 0;
511881ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
511981ad6265SDimitry Andric       Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
512081ad6265SDimitry Andric                                    getVirtualTypeID(TokenTy), CurBB);
5121*0b57cec5SDimitry Andric       if (!CleanupPad)
5122*0b57cec5SDimitry Andric         return error("Invalid record");
5123*0b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
5124*0b57cec5SDimitry Andric       if (Record.size() == 2) {
5125*0b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
5126*0b57cec5SDimitry Andric         if (!UnwindDest)
5127*0b57cec5SDimitry Andric           return error("Invalid record");
5128*0b57cec5SDimitry Andric       }
5129*0b57cec5SDimitry Andric 
5130*0b57cec5SDimitry Andric       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
5131*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5132*0b57cec5SDimitry Andric       break;
5133*0b57cec5SDimitry Andric     }
5134*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5135*0b57cec5SDimitry Andric       if (Record.size() != 2)
5136*0b57cec5SDimitry Andric         return error("Invalid record");
5137*0b57cec5SDimitry Andric       unsigned Idx = 0;
513881ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
513981ad6265SDimitry Andric       Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
514081ad6265SDimitry Andric                                  getVirtualTypeID(TokenTy), CurBB);
5141*0b57cec5SDimitry Andric       if (!CatchPad)
5142*0b57cec5SDimitry Andric         return error("Invalid record");
5143*0b57cec5SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[Idx++]);
5144*0b57cec5SDimitry Andric       if (!BB)
5145*0b57cec5SDimitry Andric         return error("Invalid record");
5146*0b57cec5SDimitry Andric 
5147*0b57cec5SDimitry Andric       I = CatchReturnInst::Create(CatchPad, BB);
5148*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5149*0b57cec5SDimitry Andric       break;
5150*0b57cec5SDimitry Andric     }
5151*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5152*0b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
5153*0b57cec5SDimitry Andric       if (Record.size() < 2)
5154*0b57cec5SDimitry Andric         return error("Invalid record");
5155*0b57cec5SDimitry Andric 
5156*0b57cec5SDimitry Andric       unsigned Idx = 0;
5157*0b57cec5SDimitry Andric 
515881ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
515981ad6265SDimitry Andric       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
516081ad6265SDimitry Andric                                   getVirtualTypeID(TokenTy), CurBB);
5161*0b57cec5SDimitry Andric 
5162*0b57cec5SDimitry Andric       unsigned NumHandlers = Record[Idx++];
5163*0b57cec5SDimitry Andric 
5164*0b57cec5SDimitry Andric       SmallVector<BasicBlock *, 2> Handlers;
5165*0b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5166*0b57cec5SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[Idx++]);
5167*0b57cec5SDimitry Andric         if (!BB)
5168*0b57cec5SDimitry Andric           return error("Invalid record");
5169*0b57cec5SDimitry Andric         Handlers.push_back(BB);
5170*0b57cec5SDimitry Andric       }
5171*0b57cec5SDimitry Andric 
5172*0b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
5173*0b57cec5SDimitry Andric       if (Idx + 1 == Record.size()) {
5174*0b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
5175*0b57cec5SDimitry Andric         if (!UnwindDest)
5176*0b57cec5SDimitry Andric           return error("Invalid record");
5177*0b57cec5SDimitry Andric       }
5178*0b57cec5SDimitry Andric 
5179*0b57cec5SDimitry Andric       if (Record.size() != Idx)
5180*0b57cec5SDimitry Andric         return error("Invalid record");
5181*0b57cec5SDimitry Andric 
5182*0b57cec5SDimitry Andric       auto *CatchSwitch =
5183*0b57cec5SDimitry Andric           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5184*0b57cec5SDimitry Andric       for (BasicBlock *Handler : Handlers)
5185*0b57cec5SDimitry Andric         CatchSwitch->addHandler(Handler);
5186*0b57cec5SDimitry Andric       I = CatchSwitch;
518781ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType());
5188*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5189*0b57cec5SDimitry Andric       break;
5190*0b57cec5SDimitry Andric     }
5191*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHPAD:
5192*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
5193*0b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
5194*0b57cec5SDimitry Andric       if (Record.size() < 2)
5195*0b57cec5SDimitry Andric         return error("Invalid record");
5196*0b57cec5SDimitry Andric 
5197*0b57cec5SDimitry Andric       unsigned Idx = 0;
5198*0b57cec5SDimitry Andric 
519981ad6265SDimitry Andric       Type *TokenTy = Type::getTokenTy(Context);
520081ad6265SDimitry Andric       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
520181ad6265SDimitry Andric                                   getVirtualTypeID(TokenTy), CurBB);
5202*0b57cec5SDimitry Andric 
5203*0b57cec5SDimitry Andric       unsigned NumArgOperands = Record[Idx++];
5204*0b57cec5SDimitry Andric 
5205*0b57cec5SDimitry Andric       SmallVector<Value *, 2> Args;
5206*0b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5207*0b57cec5SDimitry Andric         Value *Val;
520881ad6265SDimitry Andric         unsigned ValTypeID;
520981ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
5210*0b57cec5SDimitry Andric           return error("Invalid record");
5211*0b57cec5SDimitry Andric         Args.push_back(Val);
5212*0b57cec5SDimitry Andric       }
5213*0b57cec5SDimitry Andric 
5214*0b57cec5SDimitry Andric       if (Record.size() != Idx)
5215*0b57cec5SDimitry Andric         return error("Invalid record");
5216*0b57cec5SDimitry Andric 
5217*0b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5218*0b57cec5SDimitry Andric         I = CleanupPadInst::Create(ParentPad, Args);
5219*0b57cec5SDimitry Andric       else
5220*0b57cec5SDimitry Andric         I = CatchPadInst::Create(ParentPad, Args);
522181ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType());
5222*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5223*0b57cec5SDimitry Andric       break;
5224*0b57cec5SDimitry Andric     }
5225*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
5226*0b57cec5SDimitry Andric       // Check magic
5227*0b57cec5SDimitry Andric       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5228*0b57cec5SDimitry Andric         // "New" SwitchInst format with case ranges. The changes to write this
5229*0b57cec5SDimitry Andric         // format were reverted but we still recognize bitcode that uses it.
5230*0b57cec5SDimitry Andric         // Hopefully someday we will have support for case ranges and can use
5231*0b57cec5SDimitry Andric         // this format again.
5232*0b57cec5SDimitry Andric 
523381ad6265SDimitry Andric         unsigned OpTyID = Record[1];
523481ad6265SDimitry Andric         Type *OpTy = getTypeByID(OpTyID);
5235*0b57cec5SDimitry Andric         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5236*0b57cec5SDimitry Andric 
523781ad6265SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
5238*0b57cec5SDimitry Andric         BasicBlock *Default = getBasicBlock(Record[3]);
5239*0b57cec5SDimitry Andric         if (!OpTy || !Cond || !Default)
5240*0b57cec5SDimitry Andric           return error("Invalid record");
5241*0b57cec5SDimitry Andric 
5242*0b57cec5SDimitry Andric         unsigned NumCases = Record[4];
5243*0b57cec5SDimitry Andric 
5244*0b57cec5SDimitry Andric         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5245*0b57cec5SDimitry Andric         InstructionList.push_back(SI);
5246*0b57cec5SDimitry Andric 
5247*0b57cec5SDimitry Andric         unsigned CurIdx = 5;
5248*0b57cec5SDimitry Andric         for (unsigned i = 0; i != NumCases; ++i) {
5249*0b57cec5SDimitry Andric           SmallVector<ConstantInt*, 1> CaseVals;
5250*0b57cec5SDimitry Andric           unsigned NumItems = Record[CurIdx++];
5251*0b57cec5SDimitry Andric           for (unsigned ci = 0; ci != NumItems; ++ci) {
5252*0b57cec5SDimitry Andric             bool isSingleNumber = Record[CurIdx++];
5253*0b57cec5SDimitry Andric 
5254*0b57cec5SDimitry Andric             APInt Low;
5255*0b57cec5SDimitry Andric             unsigned ActiveWords = 1;
5256*0b57cec5SDimitry Andric             if (ValueBitWidth > 64)
5257*0b57cec5SDimitry Andric               ActiveWords = Record[CurIdx++];
5258*0b57cec5SDimitry Andric             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
5259*0b57cec5SDimitry Andric                                 ValueBitWidth);
5260*0b57cec5SDimitry Andric             CurIdx += ActiveWords;
5261*0b57cec5SDimitry Andric 
5262*0b57cec5SDimitry Andric             if (!isSingleNumber) {
5263*0b57cec5SDimitry Andric               ActiveWords = 1;
5264*0b57cec5SDimitry Andric               if (ValueBitWidth > 64)
5265*0b57cec5SDimitry Andric                 ActiveWords = Record[CurIdx++];
5266*0b57cec5SDimitry Andric               APInt High = readWideAPInt(
5267*0b57cec5SDimitry Andric                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
5268*0b57cec5SDimitry Andric               CurIdx += ActiveWords;
5269*0b57cec5SDimitry Andric 
5270*0b57cec5SDimitry Andric               // FIXME: It is not clear whether values in the range should be
5271*0b57cec5SDimitry Andric               // compared as signed or unsigned values. The partially
5272*0b57cec5SDimitry Andric               // implemented changes that used this format in the past used
5273*0b57cec5SDimitry Andric               // unsigned comparisons.
5274*0b57cec5SDimitry Andric               for ( ; Low.ule(High); ++Low)
5275*0b57cec5SDimitry Andric                 CaseVals.push_back(ConstantInt::get(Context, Low));
5276*0b57cec5SDimitry Andric             } else
5277*0b57cec5SDimitry Andric               CaseVals.push_back(ConstantInt::get(Context, Low));
5278*0b57cec5SDimitry Andric           }
5279*0b57cec5SDimitry Andric           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
52804824e7fdSDimitry Andric           for (ConstantInt *Cst : CaseVals)
52814824e7fdSDimitry Andric             SI->addCase(Cst, DestBB);
5282*0b57cec5SDimitry Andric         }
5283*0b57cec5SDimitry Andric         I = SI;
5284*0b57cec5SDimitry Andric         break;
5285*0b57cec5SDimitry Andric       }
5286*0b57cec5SDimitry Andric 
5287*0b57cec5SDimitry Andric       // Old SwitchInst format without case ranges.
5288*0b57cec5SDimitry Andric 
5289*0b57cec5SDimitry Andric       if (Record.size() < 3 || (Record.size() & 1) == 0)
5290*0b57cec5SDimitry Andric         return error("Invalid record");
529181ad6265SDimitry Andric       unsigned OpTyID = Record[0];
529281ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
529381ad6265SDimitry Andric       Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5294*0b57cec5SDimitry Andric       BasicBlock *Default = getBasicBlock(Record[2]);
5295*0b57cec5SDimitry Andric       if (!OpTy || !Cond || !Default)
5296*0b57cec5SDimitry Andric         return error("Invalid record");
5297*0b57cec5SDimitry Andric       unsigned NumCases = (Record.size()-3)/2;
5298*0b57cec5SDimitry Andric       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5299*0b57cec5SDimitry Andric       InstructionList.push_back(SI);
5300*0b57cec5SDimitry Andric       for (unsigned i = 0, e = NumCases; i != e; ++i) {
530181ad6265SDimitry Andric         ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
530281ad6265SDimitry Andric             getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
5303*0b57cec5SDimitry Andric         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5304*0b57cec5SDimitry Andric         if (!CaseVal || !DestBB) {
5305*0b57cec5SDimitry Andric           delete SI;
5306*0b57cec5SDimitry Andric           return error("Invalid record");
5307*0b57cec5SDimitry Andric         }
5308*0b57cec5SDimitry Andric         SI->addCase(CaseVal, DestBB);
5309*0b57cec5SDimitry Andric       }
5310*0b57cec5SDimitry Andric       I = SI;
5311*0b57cec5SDimitry Andric       break;
5312*0b57cec5SDimitry Andric     }
5313*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
5314*0b57cec5SDimitry Andric       if (Record.size() < 2)
5315*0b57cec5SDimitry Andric         return error("Invalid record");
531681ad6265SDimitry Andric       unsigned OpTyID = Record[0];
531781ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
531881ad6265SDimitry Andric       Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5319*0b57cec5SDimitry Andric       if (!OpTy || !Address)
5320*0b57cec5SDimitry Andric         return error("Invalid record");
5321*0b57cec5SDimitry Andric       unsigned NumDests = Record.size()-2;
5322*0b57cec5SDimitry Andric       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
5323*0b57cec5SDimitry Andric       InstructionList.push_back(IBI);
5324*0b57cec5SDimitry Andric       for (unsigned i = 0, e = NumDests; i != e; ++i) {
5325*0b57cec5SDimitry Andric         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5326*0b57cec5SDimitry Andric           IBI->addDestination(DestBB);
5327*0b57cec5SDimitry Andric         } else {
5328*0b57cec5SDimitry Andric           delete IBI;
5329*0b57cec5SDimitry Andric           return error("Invalid record");
5330*0b57cec5SDimitry Andric         }
5331*0b57cec5SDimitry Andric       }
5332*0b57cec5SDimitry Andric       I = IBI;
5333*0b57cec5SDimitry Andric       break;
5334*0b57cec5SDimitry Andric     }
5335*0b57cec5SDimitry Andric 
5336*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INVOKE: {
5337*0b57cec5SDimitry Andric       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5338*0b57cec5SDimitry Andric       if (Record.size() < 4)
5339*0b57cec5SDimitry Andric         return error("Invalid record");
5340*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5341*0b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
5342*0b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
5343*0b57cec5SDimitry Andric       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5344*0b57cec5SDimitry Andric       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5345*0b57cec5SDimitry Andric 
534681ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
5347*0b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
5348*0b57cec5SDimitry Andric       if ((CCInfo >> 13) & 1) {
534981ad6265SDimitry Andric         FTyID = Record[OpNum++];
535081ad6265SDimitry Andric         FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5351fe6060f1SDimitry Andric         if (!FTy)
5352*0b57cec5SDimitry Andric           return error("Explicit invoke type is not a function type");
5353*0b57cec5SDimitry Andric       }
5354*0b57cec5SDimitry Andric 
5355*0b57cec5SDimitry Andric       Value *Callee;
535681ad6265SDimitry Andric       unsigned CalleeTypeID;
535781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
535881ad6265SDimitry Andric                            CurBB))
5359*0b57cec5SDimitry Andric         return error("Invalid record");
5360*0b57cec5SDimitry Andric 
5361*0b57cec5SDimitry Andric       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5362*0b57cec5SDimitry Andric       if (!CalleeTy)
5363*0b57cec5SDimitry Andric         return error("Callee is not a pointer");
5364*0b57cec5SDimitry Andric       if (!FTy) {
536581ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
536681ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5367fe6060f1SDimitry Andric         if (!FTy)
5368*0b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
5369fe6060f1SDimitry Andric       } else if (!CalleeTy->isOpaqueOrPointeeTypeMatches(FTy))
5370*0b57cec5SDimitry Andric         return error("Explicit invoke type does not match pointee type of "
5371*0b57cec5SDimitry Andric                      "callee operand");
5372*0b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
5373*0b57cec5SDimitry Andric         return error("Insufficient operands to call");
5374*0b57cec5SDimitry Andric 
5375*0b57cec5SDimitry Andric       SmallVector<Value*, 16> Ops;
537681ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
5377*0b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
537881ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
537981ad6265SDimitry Andric         Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
538081ad6265SDimitry Andric                                ArgTyID, CurBB));
538181ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
5382*0b57cec5SDimitry Andric         if (!Ops.back())
5383*0b57cec5SDimitry Andric           return error("Invalid record");
5384*0b57cec5SDimitry Andric       }
5385*0b57cec5SDimitry Andric 
5386*0b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
5387*0b57cec5SDimitry Andric         if (Record.size() != OpNum)
5388*0b57cec5SDimitry Andric           return error("Invalid record");
5389*0b57cec5SDimitry Andric       } else {
5390*0b57cec5SDimitry Andric         // Read type/value pairs for varargs params.
5391*0b57cec5SDimitry Andric         while (OpNum != Record.size()) {
5392*0b57cec5SDimitry Andric           Value *Op;
539381ad6265SDimitry Andric           unsigned OpTypeID;
539481ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5395*0b57cec5SDimitry Andric             return error("Invalid record");
5396*0b57cec5SDimitry Andric           Ops.push_back(Op);
539781ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
5398*0b57cec5SDimitry Andric         }
5399*0b57cec5SDimitry Andric       }
5400*0b57cec5SDimitry Andric 
540181ad6265SDimitry Andric       // Upgrade the bundles if needed.
540281ad6265SDimitry Andric       if (!OperandBundles.empty())
540381ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
540481ad6265SDimitry Andric 
5405*0b57cec5SDimitry Andric       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
5406*0b57cec5SDimitry Andric                              OperandBundles);
540781ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
5408*0b57cec5SDimitry Andric       OperandBundles.clear();
5409*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5410*0b57cec5SDimitry Andric       cast<InvokeInst>(I)->setCallingConv(
5411*0b57cec5SDimitry Andric           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5412*0b57cec5SDimitry Andric       cast<InvokeInst>(I)->setAttributes(PAL);
541381ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
541481ad6265SDimitry Andric         I->deleteValue();
541581ad6265SDimitry Andric         return Err;
541681ad6265SDimitry Andric       }
5417*0b57cec5SDimitry Andric 
5418*0b57cec5SDimitry Andric       break;
5419*0b57cec5SDimitry Andric     }
5420*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5421*0b57cec5SDimitry Andric       unsigned Idx = 0;
5422*0b57cec5SDimitry Andric       Value *Val = nullptr;
542381ad6265SDimitry Andric       unsigned ValTypeID;
542481ad6265SDimitry Andric       if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
5425*0b57cec5SDimitry Andric         return error("Invalid record");
5426*0b57cec5SDimitry Andric       I = ResumeInst::Create(Val);
5427*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5428*0b57cec5SDimitry Andric       break;
5429*0b57cec5SDimitry Andric     }
5430*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALLBR: {
5431*0b57cec5SDimitry Andric       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
5432*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5433*0b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
5434*0b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
5435*0b57cec5SDimitry Andric 
5436*0b57cec5SDimitry Andric       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5437*0b57cec5SDimitry Andric       unsigned NumIndirectDests = Record[OpNum++];
5438*0b57cec5SDimitry Andric       SmallVector<BasicBlock *, 16> IndirectDests;
5439*0b57cec5SDimitry Andric       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
5440*0b57cec5SDimitry Andric         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
5441*0b57cec5SDimitry Andric 
544281ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
5443*0b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
5444*0b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
544581ad6265SDimitry Andric         FTyID = Record[OpNum++];
544681ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5447fe6060f1SDimitry Andric         if (!FTy)
5448*0b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
5449*0b57cec5SDimitry Andric       }
5450*0b57cec5SDimitry Andric 
5451*0b57cec5SDimitry Andric       Value *Callee;
545281ad6265SDimitry Andric       unsigned CalleeTypeID;
545381ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
545481ad6265SDimitry Andric                            CurBB))
5455*0b57cec5SDimitry Andric         return error("Invalid record");
5456*0b57cec5SDimitry Andric 
5457*0b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5458*0b57cec5SDimitry Andric       if (!OpTy)
5459*0b57cec5SDimitry Andric         return error("Callee is not a pointer type");
5460*0b57cec5SDimitry Andric       if (!FTy) {
546181ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
546281ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5463fe6060f1SDimitry Andric         if (!FTy)
5464*0b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
546504eeddc0SDimitry Andric       } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
5466*0b57cec5SDimitry Andric         return error("Explicit call type does not match pointee type of "
5467*0b57cec5SDimitry Andric                      "callee operand");
5468*0b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
5469*0b57cec5SDimitry Andric         return error("Insufficient operands to call");
5470*0b57cec5SDimitry Andric 
5471*0b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
547281ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
5473*0b57cec5SDimitry Andric       // Read the fixed params.
5474*0b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
547504eeddc0SDimitry Andric         Value *Arg;
547681ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5477*0b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
547804eeddc0SDimitry Andric           Arg = getBasicBlock(Record[OpNum]);
5479*0b57cec5SDimitry Andric         else
548081ad6265SDimitry Andric           Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
548181ad6265SDimitry Andric                          ArgTyID, CurBB);
548204eeddc0SDimitry Andric         if (!Arg)
5483*0b57cec5SDimitry Andric           return error("Invalid record");
548404eeddc0SDimitry Andric         Args.push_back(Arg);
548581ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
5486*0b57cec5SDimitry Andric       }
5487*0b57cec5SDimitry Andric 
5488*0b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
5489*0b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
5490*0b57cec5SDimitry Andric         if (OpNum != Record.size())
5491*0b57cec5SDimitry Andric           return error("Invalid record");
5492*0b57cec5SDimitry Andric       } else {
5493*0b57cec5SDimitry Andric         while (OpNum != Record.size()) {
5494*0b57cec5SDimitry Andric           Value *Op;
549581ad6265SDimitry Andric           unsigned OpTypeID;
549681ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5497*0b57cec5SDimitry Andric             return error("Invalid record");
5498*0b57cec5SDimitry Andric           Args.push_back(Op);
549981ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
5500*0b57cec5SDimitry Andric         }
5501*0b57cec5SDimitry Andric       }
5502*0b57cec5SDimitry Andric 
550381ad6265SDimitry Andric       // Upgrade the bundles if needed.
550481ad6265SDimitry Andric       if (!OperandBundles.empty())
550581ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
550681ad6265SDimitry Andric 
5507*0b57cec5SDimitry Andric       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
5508*0b57cec5SDimitry Andric                              OperandBundles);
550981ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
5510*0b57cec5SDimitry Andric       OperandBundles.clear();
5511*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5512*0b57cec5SDimitry Andric       cast<CallBrInst>(I)->setCallingConv(
5513*0b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5514*0b57cec5SDimitry Andric       cast<CallBrInst>(I)->setAttributes(PAL);
551581ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
551681ad6265SDimitry Andric         I->deleteValue();
551781ad6265SDimitry Andric         return Err;
551881ad6265SDimitry Andric       }
5519*0b57cec5SDimitry Andric       break;
5520*0b57cec5SDimitry Andric     }
5521*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
5522*0b57cec5SDimitry Andric       I = new UnreachableInst(Context);
5523*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5524*0b57cec5SDimitry Andric       break;
5525*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5526e8d8bef9SDimitry Andric       if (Record.empty())
552781ad6265SDimitry Andric         return error("Invalid phi record");
55288bcb0991SDimitry Andric       // The first record specifies the type.
552981ad6265SDimitry Andric       unsigned TyID = Record[0];
553081ad6265SDimitry Andric       Type *Ty = getTypeByID(TyID);
5531*0b57cec5SDimitry Andric       if (!Ty)
553281ad6265SDimitry Andric         return error("Invalid phi record");
5533*0b57cec5SDimitry Andric 
55348bcb0991SDimitry Andric       // Phi arguments are pairs of records of [value, basic block].
55358bcb0991SDimitry Andric       // There is an optional final record for fast-math-flags if this phi has a
55368bcb0991SDimitry Andric       // floating-point type.
55378bcb0991SDimitry Andric       size_t NumArgs = (Record.size() - 1) / 2;
55388bcb0991SDimitry Andric       PHINode *PN = PHINode::Create(Ty, NumArgs);
553981ad6265SDimitry Andric       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
554081ad6265SDimitry Andric         PN->deleteValue();
554181ad6265SDimitry Andric         return error("Invalid phi record");
554281ad6265SDimitry Andric       }
5543*0b57cec5SDimitry Andric       InstructionList.push_back(PN);
5544*0b57cec5SDimitry Andric 
554581ad6265SDimitry Andric       SmallDenseMap<BasicBlock *, Value *> Args;
55468bcb0991SDimitry Andric       for (unsigned i = 0; i != NumArgs; i++) {
554781ad6265SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
554881ad6265SDimitry Andric         if (!BB) {
554981ad6265SDimitry Andric           PN->deleteValue();
555081ad6265SDimitry Andric           return error("Invalid phi BB");
555181ad6265SDimitry Andric         }
555281ad6265SDimitry Andric 
555381ad6265SDimitry Andric         // Phi nodes may contain the same predecessor multiple times, in which
555481ad6265SDimitry Andric         // case the incoming value must be identical. Directly reuse the already
555581ad6265SDimitry Andric         // seen value here, to avoid expanding a constant expression multiple
555681ad6265SDimitry Andric         // times.
555781ad6265SDimitry Andric         auto It = Args.find(BB);
555881ad6265SDimitry Andric         if (It != Args.end()) {
555981ad6265SDimitry Andric           PN->addIncoming(It->second, BB);
556081ad6265SDimitry Andric           continue;
556181ad6265SDimitry Andric         }
556281ad6265SDimitry Andric 
556381ad6265SDimitry Andric         // If there already is a block for this edge (from a different phi),
556481ad6265SDimitry Andric         // use it.
556581ad6265SDimitry Andric         BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
556681ad6265SDimitry Andric         if (!EdgeBB) {
556781ad6265SDimitry Andric           // Otherwise, use a temporary block (that we will discard if it
556881ad6265SDimitry Andric           // turns out to be unnecessary).
556981ad6265SDimitry Andric           if (!PhiConstExprBB)
557081ad6265SDimitry Andric             PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F);
557181ad6265SDimitry Andric           EdgeBB = PhiConstExprBB;
557281ad6265SDimitry Andric         }
557381ad6265SDimitry Andric 
5574*0b57cec5SDimitry Andric         // With the new function encoding, it is possible that operands have
5575*0b57cec5SDimitry Andric         // negative IDs (for forward references).  Use a signed VBR
5576*0b57cec5SDimitry Andric         // representation to keep the encoding small.
557781ad6265SDimitry Andric         Value *V;
5578*0b57cec5SDimitry Andric         if (UseRelativeIDs)
557981ad6265SDimitry Andric           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
5580*0b57cec5SDimitry Andric         else
558181ad6265SDimitry Andric           V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
558281ad6265SDimitry Andric         if (!V) {
558381ad6265SDimitry Andric           PN->deleteValue();
558481ad6265SDimitry Andric           PhiConstExprBB->eraseFromParent();
558581ad6265SDimitry Andric           return error("Invalid phi record");
558681ad6265SDimitry Andric         }
558781ad6265SDimitry Andric 
558881ad6265SDimitry Andric         if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
558981ad6265SDimitry Andric           ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
559081ad6265SDimitry Andric           PhiConstExprBB = nullptr;
559181ad6265SDimitry Andric         }
5592*0b57cec5SDimitry Andric         PN->addIncoming(V, BB);
559381ad6265SDimitry Andric         Args.insert({BB, V});
5594*0b57cec5SDimitry Andric       }
5595*0b57cec5SDimitry Andric       I = PN;
559681ad6265SDimitry Andric       ResTypeID = TyID;
55978bcb0991SDimitry Andric 
55988bcb0991SDimitry Andric       // If there are an even number of records, the final record must be FMF.
55998bcb0991SDimitry Andric       if (Record.size() % 2 == 0) {
56008bcb0991SDimitry Andric         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
56018bcb0991SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
56028bcb0991SDimitry Andric         if (FMF.any())
56038bcb0991SDimitry Andric           I->setFastMathFlags(FMF);
56048bcb0991SDimitry Andric       }
56058bcb0991SDimitry Andric 
5606*0b57cec5SDimitry Andric       break;
5607*0b57cec5SDimitry Andric     }
5608*0b57cec5SDimitry Andric 
5609*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD:
5610*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
5611*0b57cec5SDimitry Andric       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5612*0b57cec5SDimitry Andric       unsigned Idx = 0;
5613*0b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5614*0b57cec5SDimitry Andric         if (Record.size() < 3)
5615*0b57cec5SDimitry Andric           return error("Invalid record");
5616*0b57cec5SDimitry Andric       } else {
5617*0b57cec5SDimitry Andric         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5618*0b57cec5SDimitry Andric         if (Record.size() < 4)
5619*0b57cec5SDimitry Andric           return error("Invalid record");
5620*0b57cec5SDimitry Andric       }
562181ad6265SDimitry Andric       ResTypeID = Record[Idx++];
562281ad6265SDimitry Andric       Type *Ty = getTypeByID(ResTypeID);
5623*0b57cec5SDimitry Andric       if (!Ty)
5624*0b57cec5SDimitry Andric         return error("Invalid record");
5625*0b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5626*0b57cec5SDimitry Andric         Value *PersFn = nullptr;
562781ad6265SDimitry Andric         unsigned PersFnTypeID;
562881ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
562981ad6265SDimitry Andric                              nullptr))
5630*0b57cec5SDimitry Andric           return error("Invalid record");
5631*0b57cec5SDimitry Andric 
5632*0b57cec5SDimitry Andric         if (!F->hasPersonalityFn())
5633*0b57cec5SDimitry Andric           F->setPersonalityFn(cast<Constant>(PersFn));
5634*0b57cec5SDimitry Andric         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5635*0b57cec5SDimitry Andric           return error("Personality function mismatch");
5636*0b57cec5SDimitry Andric       }
5637*0b57cec5SDimitry Andric 
5638*0b57cec5SDimitry Andric       bool IsCleanup = !!Record[Idx++];
5639*0b57cec5SDimitry Andric       unsigned NumClauses = Record[Idx++];
5640*0b57cec5SDimitry Andric       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
5641*0b57cec5SDimitry Andric       LP->setCleanup(IsCleanup);
5642*0b57cec5SDimitry Andric       for (unsigned J = 0; J != NumClauses; ++J) {
5643*0b57cec5SDimitry Andric         LandingPadInst::ClauseType CT =
5644*0b57cec5SDimitry Andric           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5645*0b57cec5SDimitry Andric         Value *Val;
564681ad6265SDimitry Andric         unsigned ValTypeID;
5647*0b57cec5SDimitry Andric 
564881ad6265SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
564981ad6265SDimitry Andric                              nullptr)) {
5650*0b57cec5SDimitry Andric           delete LP;
5651*0b57cec5SDimitry Andric           return error("Invalid record");
5652*0b57cec5SDimitry Andric         }
5653*0b57cec5SDimitry Andric 
5654*0b57cec5SDimitry Andric         assert((CT != LandingPadInst::Catch ||
5655*0b57cec5SDimitry Andric                 !isa<ArrayType>(Val->getType())) &&
5656*0b57cec5SDimitry Andric                "Catch clause has a invalid type!");
5657*0b57cec5SDimitry Andric         assert((CT != LandingPadInst::Filter ||
5658*0b57cec5SDimitry Andric                 isa<ArrayType>(Val->getType())) &&
5659*0b57cec5SDimitry Andric                "Filter clause has invalid type!");
5660*0b57cec5SDimitry Andric         LP->addClause(cast<Constant>(Val));
5661*0b57cec5SDimitry Andric       }
5662*0b57cec5SDimitry Andric 
5663*0b57cec5SDimitry Andric       I = LP;
5664*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5665*0b57cec5SDimitry Andric       break;
5666*0b57cec5SDimitry Andric     }
5667*0b57cec5SDimitry Andric 
5668*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
566981ad6265SDimitry Andric       if (Record.size() != 4 && Record.size() != 5)
5670*0b57cec5SDimitry Andric         return error("Invalid record");
5671e8d8bef9SDimitry Andric       using APV = AllocaPackedValues;
5672e8d8bef9SDimitry Andric       const uint64_t Rec = Record[3];
5673e8d8bef9SDimitry Andric       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
5674e8d8bef9SDimitry Andric       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
567581ad6265SDimitry Andric       unsigned TyID = Record[0];
567681ad6265SDimitry Andric       Type *Ty = getTypeByID(TyID);
5677e8d8bef9SDimitry Andric       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
567881ad6265SDimitry Andric         TyID = getContainedTypeID(TyID);
567981ad6265SDimitry Andric         Ty = getTypeByID(TyID);
568081ad6265SDimitry Andric         if (!Ty)
568181ad6265SDimitry Andric           return error("Missing element type for old-style alloca");
5682*0b57cec5SDimitry Andric       }
568381ad6265SDimitry Andric       unsigned OpTyID = Record[1];
568481ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
568581ad6265SDimitry Andric       Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
56868bcb0991SDimitry Andric       MaybeAlign Align;
5687349cc55cSDimitry Andric       uint64_t AlignExp =
5688349cc55cSDimitry Andric           Bitfield::get<APV::AlignLower>(Rec) |
5689349cc55cSDimitry Andric           (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
5690349cc55cSDimitry Andric       if (Error Err = parseAlignmentValue(AlignExp, Align)) {
5691*0b57cec5SDimitry Andric         return Err;
5692*0b57cec5SDimitry Andric       }
5693*0b57cec5SDimitry Andric       if (!Ty || !Size)
5694*0b57cec5SDimitry Andric         return error("Invalid record");
5695*0b57cec5SDimitry Andric 
5696*0b57cec5SDimitry Andric       const DataLayout &DL = TheModule->getDataLayout();
569781ad6265SDimitry Andric       unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
5698*0b57cec5SDimitry Andric 
56995ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
57005ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
57015ffd83dbSDimitry Andric         return error("alloca of unsized type");
57025ffd83dbSDimitry Andric       if (!Align)
57035ffd83dbSDimitry Andric         Align = DL.getPrefTypeAlign(Ty);
57045ffd83dbSDimitry Andric 
57055ffd83dbSDimitry Andric       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
5706*0b57cec5SDimitry Andric       AI->setUsedWithInAlloca(InAlloca);
5707*0b57cec5SDimitry Andric       AI->setSwiftError(SwiftError);
5708*0b57cec5SDimitry Andric       I = AI;
570981ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(AI->getType(), TyID);
5710*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5711*0b57cec5SDimitry Andric       break;
5712*0b57cec5SDimitry Andric     }
5713*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
5714*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5715*0b57cec5SDimitry Andric       Value *Op;
571681ad6265SDimitry Andric       unsigned OpTypeID;
571781ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
5718*0b57cec5SDimitry Andric           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
5719*0b57cec5SDimitry Andric         return error("Invalid record");
5720*0b57cec5SDimitry Andric 
5721*0b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
5722*0b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
5723*0b57cec5SDimitry Andric 
5724*0b57cec5SDimitry Andric       Type *Ty = nullptr;
5725*0b57cec5SDimitry Andric       if (OpNum + 3 == Record.size()) {
572681ad6265SDimitry Andric         ResTypeID = Record[OpNum++];
572781ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
5728fe6060f1SDimitry Andric       } else {
572981ad6265SDimitry Andric         ResTypeID = getContainedTypeID(OpTypeID);
573081ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
573181ad6265SDimitry Andric         if (!Ty)
573281ad6265SDimitry Andric           return error("Missing element type for old-style load");
5733fe6060f1SDimitry Andric       }
5734*0b57cec5SDimitry Andric 
5735*0b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5736*0b57cec5SDimitry Andric         return Err;
5737*0b57cec5SDimitry Andric 
57388bcb0991SDimitry Andric       MaybeAlign Align;
5739*0b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5740*0b57cec5SDimitry Andric         return Err;
57415ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
57425ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
57435ffd83dbSDimitry Andric         return error("load of unsized type");
57445ffd83dbSDimitry Andric       if (!Align)
57455ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
57465ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
5747*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5748*0b57cec5SDimitry Andric       break;
5749*0b57cec5SDimitry Andric     }
5750*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOADATOMIC: {
5751*0b57cec5SDimitry Andric        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
5752*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5753*0b57cec5SDimitry Andric       Value *Op;
575481ad6265SDimitry Andric       unsigned OpTypeID;
575581ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
5756*0b57cec5SDimitry Andric           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
5757*0b57cec5SDimitry Andric         return error("Invalid record");
5758*0b57cec5SDimitry Andric 
5759*0b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
5760*0b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
5761*0b57cec5SDimitry Andric 
5762*0b57cec5SDimitry Andric       Type *Ty = nullptr;
5763*0b57cec5SDimitry Andric       if (OpNum + 5 == Record.size()) {
576481ad6265SDimitry Andric         ResTypeID = Record[OpNum++];
576581ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
5766fe6060f1SDimitry Andric       } else {
576781ad6265SDimitry Andric         ResTypeID = getContainedTypeID(OpTypeID);
576881ad6265SDimitry Andric         Ty = getTypeByID(ResTypeID);
576981ad6265SDimitry Andric         if (!Ty)
577081ad6265SDimitry Andric           return error("Missing element type for old style atomic load");
5771fe6060f1SDimitry Andric       }
5772*0b57cec5SDimitry Andric 
5773*0b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5774*0b57cec5SDimitry Andric         return Err;
5775*0b57cec5SDimitry Andric 
5776*0b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5777*0b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
5778*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::Release ||
5779*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
5780*0b57cec5SDimitry Andric         return error("Invalid record");
5781*0b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5782*0b57cec5SDimitry Andric         return error("Invalid record");
5783*0b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5784*0b57cec5SDimitry Andric 
57858bcb0991SDimitry Andric       MaybeAlign Align;
5786*0b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5787*0b57cec5SDimitry Andric         return Err;
57885ffd83dbSDimitry Andric       if (!Align)
57895ffd83dbSDimitry Andric         return error("Alignment missing from atomic load");
57905ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
5791*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5792*0b57cec5SDimitry Andric       break;
5793*0b57cec5SDimitry Andric     }
5794*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE:
5795*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5796*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5797*0b57cec5SDimitry Andric       Value *Val, *Ptr;
579881ad6265SDimitry Andric       unsigned PtrTypeID, ValTypeID;
579981ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
580081ad6265SDimitry Andric         return error("Invalid record");
580181ad6265SDimitry Andric 
580281ad6265SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_STORE) {
580381ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
580481ad6265SDimitry Andric           return error("Invalid record");
580581ad6265SDimitry Andric       } else {
580681ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
580781ad6265SDimitry Andric         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
580881ad6265SDimitry Andric                      ValTypeID, Val, CurBB))
580981ad6265SDimitry Andric           return error("Invalid record");
581081ad6265SDimitry Andric       }
581181ad6265SDimitry Andric 
581281ad6265SDimitry Andric       if (OpNum + 2 != Record.size())
5813*0b57cec5SDimitry Andric         return error("Invalid record");
5814*0b57cec5SDimitry Andric 
5815*0b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5816*0b57cec5SDimitry Andric         return Err;
58178bcb0991SDimitry Andric       MaybeAlign Align;
5818*0b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5819*0b57cec5SDimitry Andric         return Err;
58205ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
58215ffd83dbSDimitry Andric       if (!Align && !Val->getType()->isSized(&Visited))
58225ffd83dbSDimitry Andric         return error("store of unsized type");
58235ffd83dbSDimitry Andric       if (!Align)
58245ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
58255ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
5826*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5827*0b57cec5SDimitry Andric       break;
5828*0b57cec5SDimitry Andric     }
5829*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC:
5830*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5831*0b57cec5SDimitry Andric       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
5832*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5833*0b57cec5SDimitry Andric       Value *Val, *Ptr;
583481ad6265SDimitry Andric       unsigned PtrTypeID, ValTypeID;
583581ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
583681ad6265SDimitry Andric           !isa<PointerType>(Ptr->getType()))
583781ad6265SDimitry Andric         return error("Invalid record");
583881ad6265SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
583981ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
584081ad6265SDimitry Andric           return error("Invalid record");
584181ad6265SDimitry Andric       } else {
584281ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
584381ad6265SDimitry Andric         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
584481ad6265SDimitry Andric                      ValTypeID, Val, CurBB))
584581ad6265SDimitry Andric           return error("Invalid record");
584681ad6265SDimitry Andric       }
584781ad6265SDimitry Andric 
584881ad6265SDimitry Andric       if (OpNum + 4 != Record.size())
5849*0b57cec5SDimitry Andric         return error("Invalid record");
5850*0b57cec5SDimitry Andric 
5851*0b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5852*0b57cec5SDimitry Andric         return Err;
5853*0b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5854*0b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
5855*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::Acquire ||
5856*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
5857*0b57cec5SDimitry Andric         return error("Invalid record");
5858*0b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5859*0b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5860*0b57cec5SDimitry Andric         return error("Invalid record");
5861*0b57cec5SDimitry Andric 
58628bcb0991SDimitry Andric       MaybeAlign Align;
5863*0b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5864*0b57cec5SDimitry Andric         return Err;
58655ffd83dbSDimitry Andric       if (!Align)
58665ffd83dbSDimitry Andric         return error("Alignment missing from atomic store");
58675ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
5868*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5869*0b57cec5SDimitry Andric       break;
5870*0b57cec5SDimitry Andric     }
5871e8d8bef9SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
5872e8d8bef9SDimitry Andric       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
5873e8d8bef9SDimitry Andric       // failure_ordering?, weak?]
5874e8d8bef9SDimitry Andric       const size_t NumRecords = Record.size();
5875*0b57cec5SDimitry Andric       unsigned OpNum = 0;
5876e8d8bef9SDimitry Andric       Value *Ptr = nullptr;
587781ad6265SDimitry Andric       unsigned PtrTypeID;
587881ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
5879*0b57cec5SDimitry Andric         return error("Invalid record");
5880*0b57cec5SDimitry Andric 
5881*0b57cec5SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
5882*0b57cec5SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
5883*0b57cec5SDimitry Andric 
5884e8d8bef9SDimitry Andric       Value *Cmp = nullptr;
588581ad6265SDimitry Andric       unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
588681ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
588781ad6265SDimitry Andric                    CmpTypeID, Cmp, CurBB))
5888*0b57cec5SDimitry Andric         return error("Invalid record");
5889e8d8bef9SDimitry Andric 
5890e8d8bef9SDimitry Andric       Value *New = nullptr;
589181ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
589281ad6265SDimitry Andric                    New, CurBB) ||
5893e8d8bef9SDimitry Andric           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
5894*0b57cec5SDimitry Andric         return error("Invalid record");
5895*0b57cec5SDimitry Andric 
5896e8d8bef9SDimitry Andric       const AtomicOrdering SuccessOrdering =
5897e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
5898*0b57cec5SDimitry Andric       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5899*0b57cec5SDimitry Andric           SuccessOrdering == AtomicOrdering::Unordered)
5900*0b57cec5SDimitry Andric         return error("Invalid record");
5901e8d8bef9SDimitry Andric 
5902e8d8bef9SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5903*0b57cec5SDimitry Andric 
5904*0b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5905*0b57cec5SDimitry Andric         return Err;
5906*0b57cec5SDimitry Andric 
5907e8d8bef9SDimitry Andric       const AtomicOrdering FailureOrdering =
5908e8d8bef9SDimitry Andric           NumRecords < 7
5909e8d8bef9SDimitry Andric               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
5910e8d8bef9SDimitry Andric               : getDecodedOrdering(Record[OpNum + 3]);
5911e8d8bef9SDimitry Andric 
5912fe6060f1SDimitry Andric       if (FailureOrdering == AtomicOrdering::NotAtomic ||
5913fe6060f1SDimitry Andric           FailureOrdering == AtomicOrdering::Unordered)
5914fe6060f1SDimitry Andric         return error("Invalid record");
5915fe6060f1SDimitry Andric 
5916e8d8bef9SDimitry Andric       const Align Alignment(
59175ffd83dbSDimitry Andric           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5918e8d8bef9SDimitry Andric 
59195ffd83dbSDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
59205ffd83dbSDimitry Andric                                 FailureOrdering, SSID);
5921*0b57cec5SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5922*0b57cec5SDimitry Andric 
5923e8d8bef9SDimitry Andric       if (NumRecords < 8) {
5924*0b57cec5SDimitry Andric         // Before weak cmpxchgs existed, the instruction simply returned the
5925*0b57cec5SDimitry Andric         // value loaded from memory, so bitcode files from that era will be
5926*0b57cec5SDimitry Andric         // expecting the first component of a modern cmpxchg.
5927*0b57cec5SDimitry Andric         CurBB->getInstList().push_back(I);
5928*0b57cec5SDimitry Andric         I = ExtractValueInst::Create(I, 0);
592981ad6265SDimitry Andric         ResTypeID = CmpTypeID;
5930*0b57cec5SDimitry Andric       } else {
5931*0b57cec5SDimitry Andric         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
593281ad6265SDimitry Andric         unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
593381ad6265SDimitry Andric         ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
5934*0b57cec5SDimitry Andric       }
5935*0b57cec5SDimitry Andric 
5936*0b57cec5SDimitry Andric       InstructionList.push_back(I);
5937*0b57cec5SDimitry Andric       break;
5938*0b57cec5SDimitry Andric     }
5939e8d8bef9SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG: {
5940e8d8bef9SDimitry Andric       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
5941fe6060f1SDimitry Andric       // failure_ordering, weak, align?]
5942e8d8bef9SDimitry Andric       const size_t NumRecords = Record.size();
5943e8d8bef9SDimitry Andric       unsigned OpNum = 0;
5944e8d8bef9SDimitry Andric       Value *Ptr = nullptr;
594581ad6265SDimitry Andric       unsigned PtrTypeID;
594681ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
5947e8d8bef9SDimitry Andric         return error("Invalid record");
5948e8d8bef9SDimitry Andric 
5949e8d8bef9SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
5950e8d8bef9SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
5951e8d8bef9SDimitry Andric 
5952e8d8bef9SDimitry Andric       Value *Cmp = nullptr;
595381ad6265SDimitry Andric       unsigned CmpTypeID;
595481ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
5955e8d8bef9SDimitry Andric         return error("Invalid record");
5956e8d8bef9SDimitry Andric 
5957e8d8bef9SDimitry Andric       Value *Val = nullptr;
595881ad6265SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
595981ad6265SDimitry Andric                    CurBB))
5960e8d8bef9SDimitry Andric         return error("Invalid record");
5961e8d8bef9SDimitry Andric 
5962fe6060f1SDimitry Andric       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
5963fe6060f1SDimitry Andric         return error("Invalid record");
5964fe6060f1SDimitry Andric 
5965fe6060f1SDimitry Andric       const bool IsVol = Record[OpNum];
5966fe6060f1SDimitry Andric 
5967e8d8bef9SDimitry Andric       const AtomicOrdering SuccessOrdering =
5968e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
5969fe6060f1SDimitry Andric       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
5970fe6060f1SDimitry Andric         return error("Invalid cmpxchg success ordering");
5971e8d8bef9SDimitry Andric 
5972e8d8bef9SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5973e8d8bef9SDimitry Andric 
5974e8d8bef9SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5975e8d8bef9SDimitry Andric         return Err;
5976e8d8bef9SDimitry Andric 
5977e8d8bef9SDimitry Andric       const AtomicOrdering FailureOrdering =
5978e8d8bef9SDimitry Andric           getDecodedOrdering(Record[OpNum + 3]);
5979fe6060f1SDimitry Andric       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
5980fe6060f1SDimitry Andric         return error("Invalid cmpxchg failure ordering");
5981e8d8bef9SDimitry Andric 
5982fe6060f1SDimitry Andric       const bool IsWeak = Record[OpNum + 4];
5983e8d8bef9SDimitry Andric 
5984fe6060f1SDimitry Andric       MaybeAlign Alignment;
5985fe6060f1SDimitry Andric 
5986fe6060f1SDimitry Andric       if (NumRecords == (OpNum + 6)) {
5987fe6060f1SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
5988fe6060f1SDimitry Andric           return Err;
5989fe6060f1SDimitry Andric       }
5990fe6060f1SDimitry Andric       if (!Alignment)
5991fe6060f1SDimitry Andric         Alignment =
5992fe6060f1SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5993fe6060f1SDimitry Andric 
5994fe6060f1SDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
5995e8d8bef9SDimitry Andric                                 FailureOrdering, SSID);
5996fe6060f1SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
5997fe6060f1SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
5998e8d8bef9SDimitry Andric 
599981ad6265SDimitry Andric       unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
600081ad6265SDimitry Andric       ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
600181ad6265SDimitry Andric 
6002e8d8bef9SDimitry Andric       InstructionList.push_back(I);
6003e8d8bef9SDimitry Andric       break;
6004e8d8bef9SDimitry Andric     }
6005fe6060f1SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
6006*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW: {
6007fe6060f1SDimitry Andric       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6008fe6060f1SDimitry Andric       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6009fe6060f1SDimitry Andric       const size_t NumRecords = Record.size();
6010*0b57cec5SDimitry Andric       unsigned OpNum = 0;
6011fe6060f1SDimitry Andric 
6012fe6060f1SDimitry Andric       Value *Ptr = nullptr;
601381ad6265SDimitry Andric       unsigned PtrTypeID;
601481ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6015*0b57cec5SDimitry Andric         return error("Invalid record");
6016fe6060f1SDimitry Andric 
6017fe6060f1SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
6018fe6060f1SDimitry Andric         return error("Invalid record");
6019fe6060f1SDimitry Andric 
6020fe6060f1SDimitry Andric       Value *Val = nullptr;
602181ad6265SDimitry Andric       unsigned ValTypeID = InvalidTypeID;
6022fe6060f1SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
602381ad6265SDimitry Andric         ValTypeID = getContainedTypeID(PtrTypeID);
6024fe6060f1SDimitry Andric         if (popValue(Record, OpNum, NextValueNo,
602581ad6265SDimitry Andric                      getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6026fe6060f1SDimitry Andric           return error("Invalid record");
6027fe6060f1SDimitry Andric       } else {
602881ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6029fe6060f1SDimitry Andric           return error("Invalid record");
6030fe6060f1SDimitry Andric       }
6031fe6060f1SDimitry Andric 
6032fe6060f1SDimitry Andric       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6033fe6060f1SDimitry Andric         return error("Invalid record");
6034fe6060f1SDimitry Andric 
6035fe6060f1SDimitry Andric       const AtomicRMWInst::BinOp Operation =
6036fe6060f1SDimitry Andric           getDecodedRMWOperation(Record[OpNum]);
6037*0b57cec5SDimitry Andric       if (Operation < AtomicRMWInst::FIRST_BINOP ||
6038*0b57cec5SDimitry Andric           Operation > AtomicRMWInst::LAST_BINOP)
6039*0b57cec5SDimitry Andric         return error("Invalid record");
6040fe6060f1SDimitry Andric 
6041fe6060f1SDimitry Andric       const bool IsVol = Record[OpNum + 1];
6042fe6060f1SDimitry Andric 
6043fe6060f1SDimitry Andric       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6044*0b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
6045*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered)
6046*0b57cec5SDimitry Andric         return error("Invalid record");
6047fe6060f1SDimitry Andric 
6048fe6060f1SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6049fe6060f1SDimitry Andric 
6050fe6060f1SDimitry Andric       MaybeAlign Alignment;
6051fe6060f1SDimitry Andric 
6052fe6060f1SDimitry Andric       if (NumRecords == (OpNum + 5)) {
6053fe6060f1SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6054fe6060f1SDimitry Andric           return Err;
6055fe6060f1SDimitry Andric       }
6056fe6060f1SDimitry Andric 
6057fe6060f1SDimitry Andric       if (!Alignment)
6058fe6060f1SDimitry Andric         Alignment =
6059fe6060f1SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
6060fe6060f1SDimitry Andric 
6061fe6060f1SDimitry Andric       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
606281ad6265SDimitry Andric       ResTypeID = ValTypeID;
6063fe6060f1SDimitry Andric       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
6064fe6060f1SDimitry Andric 
6065*0b57cec5SDimitry Andric       InstructionList.push_back(I);
6066*0b57cec5SDimitry Andric       break;
6067*0b57cec5SDimitry Andric     }
6068*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
6069*0b57cec5SDimitry Andric       if (2 != Record.size())
6070*0b57cec5SDimitry Andric         return error("Invalid record");
6071*0b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
6072*0b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
6073*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered ||
6074*0b57cec5SDimitry Andric           Ordering == AtomicOrdering::Monotonic)
6075*0b57cec5SDimitry Andric         return error("Invalid record");
6076*0b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
6077*0b57cec5SDimitry Andric       I = new FenceInst(Context, Ordering, SSID);
6078*0b57cec5SDimitry Andric       InstructionList.push_back(I);
6079*0b57cec5SDimitry Andric       break;
6080*0b57cec5SDimitry Andric     }
6081*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALL: {
6082*0b57cec5SDimitry Andric       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
6083*0b57cec5SDimitry Andric       if (Record.size() < 3)
6084*0b57cec5SDimitry Andric         return error("Invalid record");
6085*0b57cec5SDimitry Andric 
6086*0b57cec5SDimitry Andric       unsigned OpNum = 0;
6087*0b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
6088*0b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
6089*0b57cec5SDimitry Andric 
6090*0b57cec5SDimitry Andric       FastMathFlags FMF;
6091*0b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_FMF) & 1) {
6092*0b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[OpNum++]);
6093*0b57cec5SDimitry Andric         if (!FMF.any())
6094*0b57cec5SDimitry Andric           return error("Fast math flags indicator set for call with no FMF");
6095*0b57cec5SDimitry Andric       }
6096*0b57cec5SDimitry Andric 
609781ad6265SDimitry Andric       unsigned FTyID = InvalidTypeID;
6098*0b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
6099*0b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
610081ad6265SDimitry Andric         FTyID = Record[OpNum++];
610181ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6102fe6060f1SDimitry Andric         if (!FTy)
6103*0b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
6104*0b57cec5SDimitry Andric       }
6105*0b57cec5SDimitry Andric 
6106*0b57cec5SDimitry Andric       Value *Callee;
610781ad6265SDimitry Andric       unsigned CalleeTypeID;
610881ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
610981ad6265SDimitry Andric                            CurBB))
6110*0b57cec5SDimitry Andric         return error("Invalid record");
6111*0b57cec5SDimitry Andric 
6112*0b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
6113*0b57cec5SDimitry Andric       if (!OpTy)
6114*0b57cec5SDimitry Andric         return error("Callee is not a pointer type");
6115*0b57cec5SDimitry Andric       if (!FTy) {
611681ad6265SDimitry Andric         FTyID = getContainedTypeID(CalleeTypeID);
611781ad6265SDimitry Andric         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6118fe6060f1SDimitry Andric         if (!FTy)
6119*0b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
6120fe6060f1SDimitry Andric       } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
6121*0b57cec5SDimitry Andric         return error("Explicit call type does not match pointee type of "
6122*0b57cec5SDimitry Andric                      "callee operand");
6123*0b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
6124*0b57cec5SDimitry Andric         return error("Insufficient operands to call");
6125*0b57cec5SDimitry Andric 
6126*0b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
612781ad6265SDimitry Andric       SmallVector<unsigned, 16> ArgTyIDs;
6128*0b57cec5SDimitry Andric       // Read the fixed params.
6129*0b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
613081ad6265SDimitry Andric         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6131*0b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
6132*0b57cec5SDimitry Andric           Args.push_back(getBasicBlock(Record[OpNum]));
6133*0b57cec5SDimitry Andric         else
6134*0b57cec5SDimitry Andric           Args.push_back(getValue(Record, OpNum, NextValueNo,
613581ad6265SDimitry Andric                                   FTy->getParamType(i), ArgTyID, CurBB));
613681ad6265SDimitry Andric         ArgTyIDs.push_back(ArgTyID);
6137*0b57cec5SDimitry Andric         if (!Args.back())
6138*0b57cec5SDimitry Andric           return error("Invalid record");
6139*0b57cec5SDimitry Andric       }
6140*0b57cec5SDimitry Andric 
6141*0b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
6142*0b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
6143*0b57cec5SDimitry Andric         if (OpNum != Record.size())
6144*0b57cec5SDimitry Andric           return error("Invalid record");
6145*0b57cec5SDimitry Andric       } else {
6146*0b57cec5SDimitry Andric         while (OpNum != Record.size()) {
6147*0b57cec5SDimitry Andric           Value *Op;
614881ad6265SDimitry Andric           unsigned OpTypeID;
614981ad6265SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6150*0b57cec5SDimitry Andric             return error("Invalid record");
6151*0b57cec5SDimitry Andric           Args.push_back(Op);
615281ad6265SDimitry Andric           ArgTyIDs.push_back(OpTypeID);
6153*0b57cec5SDimitry Andric         }
6154*0b57cec5SDimitry Andric       }
6155*0b57cec5SDimitry Andric 
615681ad6265SDimitry Andric       // Upgrade the bundles if needed.
615781ad6265SDimitry Andric       if (!OperandBundles.empty())
615881ad6265SDimitry Andric         UpgradeOperandBundles(OperandBundles);
615981ad6265SDimitry Andric 
6160*0b57cec5SDimitry Andric       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
616181ad6265SDimitry Andric       ResTypeID = getContainedTypeID(FTyID);
6162*0b57cec5SDimitry Andric       OperandBundles.clear();
6163*0b57cec5SDimitry Andric       InstructionList.push_back(I);
6164*0b57cec5SDimitry Andric       cast<CallInst>(I)->setCallingConv(
6165*0b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
6166*0b57cec5SDimitry Andric       CallInst::TailCallKind TCK = CallInst::TCK_None;
6167*0b57cec5SDimitry Andric       if (CCInfo & 1 << bitc::CALL_TAIL)
6168*0b57cec5SDimitry Andric         TCK = CallInst::TCK_Tail;
6169*0b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
6170*0b57cec5SDimitry Andric         TCK = CallInst::TCK_MustTail;
6171*0b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_NOTAIL))
6172*0b57cec5SDimitry Andric         TCK = CallInst::TCK_NoTail;
6173*0b57cec5SDimitry Andric       cast<CallInst>(I)->setTailCallKind(TCK);
6174*0b57cec5SDimitry Andric       cast<CallInst>(I)->setAttributes(PAL);
617581ad6265SDimitry Andric       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
617681ad6265SDimitry Andric         I->deleteValue();
617781ad6265SDimitry Andric         return Err;
617881ad6265SDimitry Andric       }
6179*0b57cec5SDimitry Andric       if (FMF.any()) {
6180*0b57cec5SDimitry Andric         if (!isa<FPMathOperator>(I))
6181*0b57cec5SDimitry Andric           return error("Fast-math-flags specified for call without "
6182*0b57cec5SDimitry Andric                        "floating-point scalar or vector return type");
6183*0b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
6184*0b57cec5SDimitry Andric       }
6185*0b57cec5SDimitry Andric       break;
6186*0b57cec5SDimitry Andric     }
6187*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
6188*0b57cec5SDimitry Andric       if (Record.size() < 3)
6189*0b57cec5SDimitry Andric         return error("Invalid record");
619081ad6265SDimitry Andric       unsigned OpTyID = Record[0];
619181ad6265SDimitry Andric       Type *OpTy = getTypeByID(OpTyID);
619281ad6265SDimitry Andric       Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
619381ad6265SDimitry Andric       ResTypeID = Record[2];
619481ad6265SDimitry Andric       Type *ResTy = getTypeByID(ResTypeID);
6195*0b57cec5SDimitry Andric       if (!OpTy || !Op || !ResTy)
6196*0b57cec5SDimitry Andric         return error("Invalid record");
6197*0b57cec5SDimitry Andric       I = new VAArgInst(Op, ResTy);
6198*0b57cec5SDimitry Andric       InstructionList.push_back(I);
6199*0b57cec5SDimitry Andric       break;
6200*0b57cec5SDimitry Andric     }
6201*0b57cec5SDimitry Andric 
6202*0b57cec5SDimitry Andric     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
6203*0b57cec5SDimitry Andric       // A call or an invoke can be optionally prefixed with some variable
6204*0b57cec5SDimitry Andric       // number of operand bundle blocks.  These blocks are read into
6205*0b57cec5SDimitry Andric       // OperandBundles and consumed at the next call or invoke instruction.
6206*0b57cec5SDimitry Andric 
6207e8d8bef9SDimitry Andric       if (Record.empty() || Record[0] >= BundleTags.size())
6208*0b57cec5SDimitry Andric         return error("Invalid record");
6209*0b57cec5SDimitry Andric 
6210*0b57cec5SDimitry Andric       std::vector<Value *> Inputs;
6211*0b57cec5SDimitry Andric 
6212*0b57cec5SDimitry Andric       unsigned OpNum = 1;
6213*0b57cec5SDimitry Andric       while (OpNum != Record.size()) {
6214*0b57cec5SDimitry Andric         Value *Op;
621581ad6265SDimitry Andric         unsigned OpTypeID;
621681ad6265SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6217*0b57cec5SDimitry Andric           return error("Invalid record");
6218*0b57cec5SDimitry Andric         Inputs.push_back(Op);
6219*0b57cec5SDimitry Andric       }
6220*0b57cec5SDimitry Andric 
6221*0b57cec5SDimitry Andric       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6222*0b57cec5SDimitry Andric       continue;
6223*0b57cec5SDimitry Andric     }
6224480093f4SDimitry Andric 
6225480093f4SDimitry Andric     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6226480093f4SDimitry Andric       unsigned OpNum = 0;
6227480093f4SDimitry Andric       Value *Op = nullptr;
622881ad6265SDimitry Andric       unsigned OpTypeID;
622981ad6265SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6230480093f4SDimitry Andric         return error("Invalid record");
6231480093f4SDimitry Andric       if (OpNum != Record.size())
6232480093f4SDimitry Andric         return error("Invalid record");
6233480093f4SDimitry Andric 
6234480093f4SDimitry Andric       I = new FreezeInst(Op);
623581ad6265SDimitry Andric       ResTypeID = OpTypeID;
6236480093f4SDimitry Andric       InstructionList.push_back(I);
6237480093f4SDimitry Andric       break;
6238480093f4SDimitry Andric     }
6239*0b57cec5SDimitry Andric     }
6240*0b57cec5SDimitry Andric 
6241*0b57cec5SDimitry Andric     // Add instruction to end of current BB.  If there is no current BB, reject
6242*0b57cec5SDimitry Andric     // this file.
6243*0b57cec5SDimitry Andric     if (!CurBB) {
6244*0b57cec5SDimitry Andric       I->deleteValue();
6245*0b57cec5SDimitry Andric       return error("Invalid instruction with no BB");
6246*0b57cec5SDimitry Andric     }
6247*0b57cec5SDimitry Andric     if (!OperandBundles.empty()) {
6248*0b57cec5SDimitry Andric       I->deleteValue();
6249*0b57cec5SDimitry Andric       return error("Operand bundles found with no consumer");
6250*0b57cec5SDimitry Andric     }
6251*0b57cec5SDimitry Andric     CurBB->getInstList().push_back(I);
6252*0b57cec5SDimitry Andric 
6253*0b57cec5SDimitry Andric     // If this was a terminator instruction, move to the next block.
6254*0b57cec5SDimitry Andric     if (I->isTerminator()) {
6255*0b57cec5SDimitry Andric       ++CurBBNo;
6256*0b57cec5SDimitry Andric       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
6257*0b57cec5SDimitry Andric     }
6258*0b57cec5SDimitry Andric 
6259*0b57cec5SDimitry Andric     // Non-void values get registered in the value table for future use.
626081ad6265SDimitry Andric     if (!I->getType()->isVoidTy()) {
626181ad6265SDimitry Andric       assert(I->getType() == getTypeByID(ResTypeID) &&
626281ad6265SDimitry Andric              "Incorrect result type ID");
626381ad6265SDimitry Andric       if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
626481ad6265SDimitry Andric         return Err;
626581ad6265SDimitry Andric     }
6266*0b57cec5SDimitry Andric   }
6267*0b57cec5SDimitry Andric 
6268*0b57cec5SDimitry Andric OutOfRecordLoop:
6269*0b57cec5SDimitry Andric 
6270*0b57cec5SDimitry Andric   if (!OperandBundles.empty())
6271*0b57cec5SDimitry Andric     return error("Operand bundles found with no consumer");
6272*0b57cec5SDimitry Andric 
6273*0b57cec5SDimitry Andric   // Check the function list for unresolved values.
6274*0b57cec5SDimitry Andric   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
6275*0b57cec5SDimitry Andric     if (!A->getParent()) {
6276*0b57cec5SDimitry Andric       // We found at least one unresolved value.  Nuke them all to avoid leaks.
6277*0b57cec5SDimitry Andric       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
6278*0b57cec5SDimitry Andric         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
6279*0b57cec5SDimitry Andric           A->replaceAllUsesWith(UndefValue::get(A->getType()));
6280*0b57cec5SDimitry Andric           delete A;
6281*0b57cec5SDimitry Andric         }
6282*0b57cec5SDimitry Andric       }
6283*0b57cec5SDimitry Andric       return error("Never resolved value found in function");
6284*0b57cec5SDimitry Andric     }
6285*0b57cec5SDimitry Andric   }
6286*0b57cec5SDimitry Andric 
6287*0b57cec5SDimitry Andric   // Unexpected unresolved metadata about to be dropped.
6288*0b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
6289*0b57cec5SDimitry Andric     return error("Invalid function metadata: outgoing forward refs");
6290*0b57cec5SDimitry Andric 
629181ad6265SDimitry Andric   if (PhiConstExprBB)
629281ad6265SDimitry Andric     PhiConstExprBB->eraseFromParent();
629381ad6265SDimitry Andric 
629481ad6265SDimitry Andric   for (const auto &Pair : ConstExprEdgeBBs) {
629581ad6265SDimitry Andric     BasicBlock *From = Pair.first.first;
629681ad6265SDimitry Andric     BasicBlock *To = Pair.first.second;
629781ad6265SDimitry Andric     BasicBlock *EdgeBB = Pair.second;
629881ad6265SDimitry Andric     BranchInst::Create(To, EdgeBB);
629981ad6265SDimitry Andric     From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
630081ad6265SDimitry Andric     To->replacePhiUsesWith(From, EdgeBB);
630181ad6265SDimitry Andric     EdgeBB->moveBefore(To);
630281ad6265SDimitry Andric   }
630381ad6265SDimitry Andric 
6304*0b57cec5SDimitry Andric   // Trim the value list down to the size it was before we parsed this function.
6305*0b57cec5SDimitry Andric   ValueList.shrinkTo(ModuleValueListSize);
6306*0b57cec5SDimitry Andric   MDLoader->shrinkTo(ModuleMDLoaderSize);
6307*0b57cec5SDimitry Andric   std::vector<BasicBlock*>().swap(FunctionBBs);
6308*0b57cec5SDimitry Andric   return Error::success();
6309*0b57cec5SDimitry Andric }
6310*0b57cec5SDimitry Andric 
6311*0b57cec5SDimitry Andric /// Find the function body in the bitcode stream
6312*0b57cec5SDimitry Andric Error BitcodeReader::findFunctionInStream(
6313*0b57cec5SDimitry Andric     Function *F,
6314*0b57cec5SDimitry Andric     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
6315*0b57cec5SDimitry Andric   while (DeferredFunctionInfoIterator->second == 0) {
6316*0b57cec5SDimitry Andric     // This is the fallback handling for the old format bitcode that
6317*0b57cec5SDimitry Andric     // didn't contain the function index in the VST, or when we have
6318*0b57cec5SDimitry Andric     // an anonymous function which would not have a VST entry.
6319*0b57cec5SDimitry Andric     // Assert that we have one of those two cases.
6320*0b57cec5SDimitry Andric     assert(VSTOffset == 0 || !F->hasName());
6321*0b57cec5SDimitry Andric     // Parse the next body in the stream and set its position in the
6322*0b57cec5SDimitry Andric     // DeferredFunctionInfo map.
6323*0b57cec5SDimitry Andric     if (Error Err = rememberAndSkipFunctionBodies())
6324*0b57cec5SDimitry Andric       return Err;
6325*0b57cec5SDimitry Andric   }
6326*0b57cec5SDimitry Andric   return Error::success();
6327*0b57cec5SDimitry Andric }
6328*0b57cec5SDimitry Andric 
6329*0b57cec5SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
6330*0b57cec5SDimitry Andric   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
6331*0b57cec5SDimitry Andric     return SyncScope::ID(Val);
6332*0b57cec5SDimitry Andric   if (Val >= SSIDs.size())
6333*0b57cec5SDimitry Andric     return SyncScope::System; // Map unknown synchronization scopes to system.
6334*0b57cec5SDimitry Andric   return SSIDs[Val];
6335*0b57cec5SDimitry Andric }
6336*0b57cec5SDimitry Andric 
6337*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6338*0b57cec5SDimitry Andric // GVMaterializer implementation
6339*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
6340*0b57cec5SDimitry Andric 
6341*0b57cec5SDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) {
6342*0b57cec5SDimitry Andric   Function *F = dyn_cast<Function>(GV);
6343*0b57cec5SDimitry Andric   // If it's not a function or is already material, ignore the request.
6344*0b57cec5SDimitry Andric   if (!F || !F->isMaterializable())
6345*0b57cec5SDimitry Andric     return Error::success();
6346*0b57cec5SDimitry Andric 
6347*0b57cec5SDimitry Andric   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
6348*0b57cec5SDimitry Andric   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
6349*0b57cec5SDimitry Andric   // If its position is recorded as 0, its body is somewhere in the stream
6350*0b57cec5SDimitry Andric   // but we haven't seen it yet.
6351*0b57cec5SDimitry Andric   if (DFII->second == 0)
6352*0b57cec5SDimitry Andric     if (Error Err = findFunctionInStream(F, DFII))
6353*0b57cec5SDimitry Andric       return Err;
6354*0b57cec5SDimitry Andric 
6355*0b57cec5SDimitry Andric   // Materialize metadata before parsing any function bodies.
6356*0b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
6357*0b57cec5SDimitry Andric     return Err;
6358*0b57cec5SDimitry Andric 
6359*0b57cec5SDimitry Andric   // Move the bit stream to the saved position of the deferred function body.
6360*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
6361*0b57cec5SDimitry Andric     return JumpFailed;
6362*0b57cec5SDimitry Andric   if (Error Err = parseFunctionBody(F))
6363*0b57cec5SDimitry Andric     return Err;
6364*0b57cec5SDimitry Andric   F->setIsMaterializable(false);
6365*0b57cec5SDimitry Andric 
6366*0b57cec5SDimitry Andric   if (StripDebugInfo)
6367*0b57cec5SDimitry Andric     stripDebugInfo(*F);
6368*0b57cec5SDimitry Andric 
6369*0b57cec5SDimitry Andric   // Upgrade any old intrinsic calls in the function.
6370*0b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
6371349cc55cSDimitry Andric     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
6372*0b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
6373*0b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
6374*0b57cec5SDimitry Andric   }
6375*0b57cec5SDimitry Andric 
6376*0b57cec5SDimitry Andric   // Update calls to the remangled intrinsics
6377*0b57cec5SDimitry Andric   for (auto &I : RemangledIntrinsics)
6378349cc55cSDimitry Andric     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
6379*0b57cec5SDimitry Andric       // Don't expect any other users than call sites
6380349cc55cSDimitry Andric       cast<CallBase>(U)->setCalledFunction(I.second);
6381*0b57cec5SDimitry Andric 
6382*0b57cec5SDimitry Andric   // Finish fn->subprogram upgrade for materialized functions.
6383*0b57cec5SDimitry Andric   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
6384*0b57cec5SDimitry Andric     F->setSubprogram(SP);
6385*0b57cec5SDimitry Andric 
6386*0b57cec5SDimitry Andric   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
6387*0b57cec5SDimitry Andric   if (!MDLoader->isStrippingTBAA()) {
6388*0b57cec5SDimitry Andric     for (auto &I : instructions(F)) {
6389*0b57cec5SDimitry Andric       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
6390*0b57cec5SDimitry Andric       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
6391*0b57cec5SDimitry Andric         continue;
6392*0b57cec5SDimitry Andric       MDLoader->setStripTBAA(true);
6393*0b57cec5SDimitry Andric       stripTBAA(F->getParent());
6394*0b57cec5SDimitry Andric     }
6395*0b57cec5SDimitry Andric   }
6396*0b57cec5SDimitry Andric 
6397e8d8bef9SDimitry Andric   for (auto &I : instructions(F)) {
6398fe6060f1SDimitry Andric     // "Upgrade" older incorrect branch weights by dropping them.
6399e8d8bef9SDimitry Andric     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
6400e8d8bef9SDimitry Andric       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
6401e8d8bef9SDimitry Andric         MDString *MDS = cast<MDString>(MD->getOperand(0));
6402e8d8bef9SDimitry Andric         StringRef ProfName = MDS->getString();
6403e8d8bef9SDimitry Andric         // Check consistency of !prof branch_weights metadata.
6404e8d8bef9SDimitry Andric         if (!ProfName.equals("branch_weights"))
6405e8d8bef9SDimitry Andric           continue;
6406e8d8bef9SDimitry Andric         unsigned ExpectedNumOperands = 0;
6407e8d8bef9SDimitry Andric         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
6408e8d8bef9SDimitry Andric           ExpectedNumOperands = BI->getNumSuccessors();
6409e8d8bef9SDimitry Andric         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
6410e8d8bef9SDimitry Andric           ExpectedNumOperands = SI->getNumSuccessors();
6411e8d8bef9SDimitry Andric         else if (isa<CallInst>(&I))
6412e8d8bef9SDimitry Andric           ExpectedNumOperands = 1;
6413e8d8bef9SDimitry Andric         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
6414e8d8bef9SDimitry Andric           ExpectedNumOperands = IBI->getNumDestinations();
6415e8d8bef9SDimitry Andric         else if (isa<SelectInst>(&I))
6416e8d8bef9SDimitry Andric           ExpectedNumOperands = 2;
6417e8d8bef9SDimitry Andric         else
6418e8d8bef9SDimitry Andric           continue; // ignore and continue.
6419e8d8bef9SDimitry Andric 
6420e8d8bef9SDimitry Andric         // If branch weight doesn't match, just strip branch weight.
6421e8d8bef9SDimitry Andric         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
6422e8d8bef9SDimitry Andric           I.setMetadata(LLVMContext::MD_prof, nullptr);
6423e8d8bef9SDimitry Andric       }
6424e8d8bef9SDimitry Andric     }
6425fe6060f1SDimitry Andric 
6426fe6060f1SDimitry Andric     // Remove incompatible attributes on function calls.
6427fe6060f1SDimitry Andric     if (auto *CI = dyn_cast<CallBase>(&I)) {
6428349cc55cSDimitry Andric       CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
6429fe6060f1SDimitry Andric           CI->getFunctionType()->getReturnType()));
6430fe6060f1SDimitry Andric 
6431fe6060f1SDimitry Andric       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
6432fe6060f1SDimitry Andric         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
6433fe6060f1SDimitry Andric                                         CI->getArgOperand(ArgNo)->getType()));
6434fe6060f1SDimitry Andric     }
6435e8d8bef9SDimitry Andric   }
6436e8d8bef9SDimitry Andric 
64375ffd83dbSDimitry Andric   // Look for functions that rely on old function attribute behavior.
64385ffd83dbSDimitry Andric   UpgradeFunctionAttributes(*F);
64395ffd83dbSDimitry Andric 
6440*0b57cec5SDimitry Andric   // Bring in any functions that this function forward-referenced via
6441*0b57cec5SDimitry Andric   // blockaddresses.
6442*0b57cec5SDimitry Andric   return materializeForwardReferencedFunctions();
6443*0b57cec5SDimitry Andric }
6444*0b57cec5SDimitry Andric 
6445*0b57cec5SDimitry Andric Error BitcodeReader::materializeModule() {
6446*0b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
6447*0b57cec5SDimitry Andric     return Err;
6448*0b57cec5SDimitry Andric 
6449*0b57cec5SDimitry Andric   // Promise to materialize all forward references.
6450*0b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = true;
6451*0b57cec5SDimitry Andric 
6452*0b57cec5SDimitry Andric   // Iterate over the module, deserializing any functions that are still on
6453*0b57cec5SDimitry Andric   // disk.
6454*0b57cec5SDimitry Andric   for (Function &F : *TheModule) {
6455*0b57cec5SDimitry Andric     if (Error Err = materialize(&F))
6456*0b57cec5SDimitry Andric       return Err;
6457*0b57cec5SDimitry Andric   }
6458*0b57cec5SDimitry Andric   // At this point, if there are any function bodies, parse the rest of
6459*0b57cec5SDimitry Andric   // the bits in the module past the last function block we have recorded
6460*0b57cec5SDimitry Andric   // through either lazy scanning or the VST.
6461*0b57cec5SDimitry Andric   if (LastFunctionBlockBit || NextUnreadBit)
6462*0b57cec5SDimitry Andric     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
6463*0b57cec5SDimitry Andric                                     ? LastFunctionBlockBit
6464*0b57cec5SDimitry Andric                                     : NextUnreadBit))
6465*0b57cec5SDimitry Andric       return Err;
6466*0b57cec5SDimitry Andric 
6467*0b57cec5SDimitry Andric   // Check that all block address forward references got resolved (as we
6468*0b57cec5SDimitry Andric   // promised above).
6469*0b57cec5SDimitry Andric   if (!BasicBlockFwdRefs.empty())
6470*0b57cec5SDimitry Andric     return error("Never resolved function from blockaddress");
6471*0b57cec5SDimitry Andric 
6472*0b57cec5SDimitry Andric   // Upgrade any intrinsic calls that slipped through (should not happen!) and
6473*0b57cec5SDimitry Andric   // delete the old functions to clean up. We can't do this unless the entire
6474*0b57cec5SDimitry Andric   // module is materialized because there could always be another function body
6475*0b57cec5SDimitry Andric   // with calls to the old function.
6476*0b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
6477*0b57cec5SDimitry Andric     for (auto *U : I.first->users()) {
6478*0b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
6479*0b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
6480*0b57cec5SDimitry Andric     }
6481*0b57cec5SDimitry Andric     if (!I.first->use_empty())
6482*0b57cec5SDimitry Andric       I.first->replaceAllUsesWith(I.second);
6483*0b57cec5SDimitry Andric     I.first->eraseFromParent();
6484*0b57cec5SDimitry Andric   }
6485*0b57cec5SDimitry Andric   UpgradedIntrinsics.clear();
6486*0b57cec5SDimitry Andric   // Do the same for remangled intrinsics
6487*0b57cec5SDimitry Andric   for (auto &I : RemangledIntrinsics) {
6488*0b57cec5SDimitry Andric     I.first->replaceAllUsesWith(I.second);
6489*0b57cec5SDimitry Andric     I.first->eraseFromParent();
6490*0b57cec5SDimitry Andric   }
6491*0b57cec5SDimitry Andric   RemangledIntrinsics.clear();
6492*0b57cec5SDimitry Andric 
6493*0b57cec5SDimitry Andric   UpgradeDebugInfo(*TheModule);
6494*0b57cec5SDimitry Andric 
6495*0b57cec5SDimitry Andric   UpgradeModuleFlags(*TheModule);
6496*0b57cec5SDimitry Andric 
64978bcb0991SDimitry Andric   UpgradeARCRuntime(*TheModule);
6498*0b57cec5SDimitry Andric 
6499*0b57cec5SDimitry Andric   return Error::success();
6500*0b57cec5SDimitry Andric }
6501*0b57cec5SDimitry Andric 
6502*0b57cec5SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
6503*0b57cec5SDimitry Andric   return IdentifiedStructTypes;
6504*0b57cec5SDimitry Andric }
6505*0b57cec5SDimitry Andric 
6506*0b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
6507*0b57cec5SDimitry Andric     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
6508*0b57cec5SDimitry Andric     StringRef ModulePath, unsigned ModuleId)
6509*0b57cec5SDimitry Andric     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
6510*0b57cec5SDimitry Andric       ModulePath(ModulePath), ModuleId(ModuleId) {}
6511*0b57cec5SDimitry Andric 
6512*0b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::addThisModule() {
6513*0b57cec5SDimitry Andric   TheIndex.addModule(ModulePath, ModuleId);
6514*0b57cec5SDimitry Andric }
6515*0b57cec5SDimitry Andric 
6516*0b57cec5SDimitry Andric ModuleSummaryIndex::ModuleInfo *
6517*0b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getThisModule() {
6518*0b57cec5SDimitry Andric   return TheIndex.getModule(ModulePath);
6519*0b57cec5SDimitry Andric }
6520*0b57cec5SDimitry Andric 
6521*0b57cec5SDimitry Andric std::pair<ValueInfo, GlobalValue::GUID>
6522*0b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
6523*0b57cec5SDimitry Andric   auto VGI = ValueIdToValueInfoMap[ValueId];
6524*0b57cec5SDimitry Andric   assert(VGI.first);
6525*0b57cec5SDimitry Andric   return VGI;
6526*0b57cec5SDimitry Andric }
6527*0b57cec5SDimitry Andric 
6528*0b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID(
6529*0b57cec5SDimitry Andric     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
6530*0b57cec5SDimitry Andric     StringRef SourceFileName) {
6531*0b57cec5SDimitry Andric   std::string GlobalId =
6532*0b57cec5SDimitry Andric       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
6533*0b57cec5SDimitry Andric   auto ValueGUID = GlobalValue::getGUID(GlobalId);
6534*0b57cec5SDimitry Andric   auto OriginalNameID = ValueGUID;
6535*0b57cec5SDimitry Andric   if (GlobalValue::isLocalLinkage(Linkage))
6536*0b57cec5SDimitry Andric     OriginalNameID = GlobalValue::getGUID(ValueName);
6537*0b57cec5SDimitry Andric   if (PrintSummaryGUIDs)
6538*0b57cec5SDimitry Andric     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
6539*0b57cec5SDimitry Andric            << ValueName << "\n";
6540*0b57cec5SDimitry Andric 
6541*0b57cec5SDimitry Andric   // UseStrtab is false for legacy summary formats and value names are
6542*0b57cec5SDimitry Andric   // created on stack. In that case we save the name in a string saver in
6543*0b57cec5SDimitry Andric   // the index so that the value name can be recorded.
6544*0b57cec5SDimitry Andric   ValueIdToValueInfoMap[ValueID] = std::make_pair(
6545*0b57cec5SDimitry Andric       TheIndex.getOrInsertValueInfo(
6546*0b57cec5SDimitry Andric           ValueGUID,
6547*0b57cec5SDimitry Andric           UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
6548*0b57cec5SDimitry Andric       OriginalNameID);
6549*0b57cec5SDimitry Andric }
6550*0b57cec5SDimitry Andric 
6551*0b57cec5SDimitry Andric // Specialized value symbol table parser used when reading module index
6552*0b57cec5SDimitry Andric // blocks where we don't actually create global values. The parsed information
6553*0b57cec5SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries.
6554*0b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
6555*0b57cec5SDimitry Andric     uint64_t Offset,
6556*0b57cec5SDimitry Andric     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
6557*0b57cec5SDimitry Andric   // With a strtab the VST is not required to parse the summary.
6558*0b57cec5SDimitry Andric   if (UseStrtab)
6559*0b57cec5SDimitry Andric     return Error::success();
6560*0b57cec5SDimitry Andric 
6561*0b57cec5SDimitry Andric   assert(Offset > 0 && "Expected non-zero VST offset");
6562*0b57cec5SDimitry Andric   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
6563*0b57cec5SDimitry Andric   if (!MaybeCurrentBit)
6564*0b57cec5SDimitry Andric     return MaybeCurrentBit.takeError();
6565*0b57cec5SDimitry Andric   uint64_t CurrentBit = MaybeCurrentBit.get();
6566*0b57cec5SDimitry Andric 
6567*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
6568*0b57cec5SDimitry Andric     return Err;
6569*0b57cec5SDimitry Andric 
6570*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
6571*0b57cec5SDimitry Andric 
6572*0b57cec5SDimitry Andric   // Read all the records for this value table.
6573*0b57cec5SDimitry Andric   SmallString<128> ValueName;
6574*0b57cec5SDimitry Andric 
6575*0b57cec5SDimitry Andric   while (true) {
6576*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6577*0b57cec5SDimitry Andric     if (!MaybeEntry)
6578*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
6579*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
6580*0b57cec5SDimitry Andric 
6581*0b57cec5SDimitry Andric     switch (Entry.Kind) {
6582*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
6583*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
6584*0b57cec5SDimitry Andric       return error("Malformed block");
6585*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
6586*0b57cec5SDimitry Andric       // Done parsing VST, jump back to wherever we came from.
6587*0b57cec5SDimitry Andric       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
6588*0b57cec5SDimitry Andric         return JumpFailed;
6589*0b57cec5SDimitry Andric       return Error::success();
6590*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
6591*0b57cec5SDimitry Andric       // The interesting case.
6592*0b57cec5SDimitry Andric       break;
6593*0b57cec5SDimitry Andric     }
6594*0b57cec5SDimitry Andric 
6595*0b57cec5SDimitry Andric     // Read a record.
6596*0b57cec5SDimitry Andric     Record.clear();
6597*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6598*0b57cec5SDimitry Andric     if (!MaybeRecord)
6599*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
6600*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
6601*0b57cec5SDimitry Andric     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
6602*0b57cec5SDimitry Andric       break;
6603*0b57cec5SDimitry Andric     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
6604*0b57cec5SDimitry Andric       if (convertToString(Record, 1, ValueName))
6605*0b57cec5SDimitry Andric         return error("Invalid record");
6606*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
6607*0b57cec5SDimitry Andric       assert(!SourceFileName.empty());
6608*0b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
6609*0b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
6610*0b57cec5SDimitry Andric              "No linkage found for VST entry?");
6611*0b57cec5SDimitry Andric       auto Linkage = VLI->second;
6612*0b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
6613*0b57cec5SDimitry Andric       ValueName.clear();
6614*0b57cec5SDimitry Andric       break;
6615*0b57cec5SDimitry Andric     }
6616*0b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
6617*0b57cec5SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
6618*0b57cec5SDimitry Andric       if (convertToString(Record, 2, ValueName))
6619*0b57cec5SDimitry Andric         return error("Invalid record");
6620*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
6621*0b57cec5SDimitry Andric       assert(!SourceFileName.empty());
6622*0b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
6623*0b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
6624*0b57cec5SDimitry Andric              "No linkage found for VST entry?");
6625*0b57cec5SDimitry Andric       auto Linkage = VLI->second;
6626*0b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
6627*0b57cec5SDimitry Andric       ValueName.clear();
6628*0b57cec5SDimitry Andric       break;
6629*0b57cec5SDimitry Andric     }
6630*0b57cec5SDimitry Andric     case bitc::VST_CODE_COMBINED_ENTRY: {
6631*0b57cec5SDimitry Andric       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
6632*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
6633*0b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
6634*0b57cec5SDimitry Andric       // The "original name", which is the second value of the pair will be
6635*0b57cec5SDimitry Andric       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
6636*0b57cec5SDimitry Andric       ValueIdToValueInfoMap[ValueID] =
6637*0b57cec5SDimitry Andric           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
6638*0b57cec5SDimitry Andric       break;
6639*0b57cec5SDimitry Andric     }
6640*0b57cec5SDimitry Andric     }
6641*0b57cec5SDimitry Andric   }
6642*0b57cec5SDimitry Andric }
6643*0b57cec5SDimitry Andric 
6644*0b57cec5SDimitry Andric // Parse just the blocks needed for building the index out of the module.
6645*0b57cec5SDimitry Andric // At the end of this routine the module Index is populated with a map
6646*0b57cec5SDimitry Andric // from global value id to GlobalValueSummary objects.
6647*0b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() {
6648*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6649*0b57cec5SDimitry Andric     return Err;
6650*0b57cec5SDimitry Andric 
6651*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
6652*0b57cec5SDimitry Andric   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
6653*0b57cec5SDimitry Andric   unsigned ValueId = 0;
6654*0b57cec5SDimitry Andric 
6655*0b57cec5SDimitry Andric   // Read the index for this module.
6656*0b57cec5SDimitry Andric   while (true) {
6657*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6658*0b57cec5SDimitry Andric     if (!MaybeEntry)
6659*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
6660*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
6661*0b57cec5SDimitry Andric 
6662*0b57cec5SDimitry Andric     switch (Entry.Kind) {
6663*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
6664*0b57cec5SDimitry Andric       return error("Malformed block");
6665*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
6666*0b57cec5SDimitry Andric       return Error::success();
6667*0b57cec5SDimitry Andric 
6668*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
6669*0b57cec5SDimitry Andric       switch (Entry.ID) {
6670*0b57cec5SDimitry Andric       default: // Skip unknown content.
6671*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
6672*0b57cec5SDimitry Andric           return Err;
6673*0b57cec5SDimitry Andric         break;
6674*0b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
6675*0b57cec5SDimitry Andric         // Need to parse these to get abbrev ids (e.g. for VST)
667681ad6265SDimitry Andric         if (Error Err = readBlockInfo())
667781ad6265SDimitry Andric           return Err;
6678*0b57cec5SDimitry Andric         break;
6679*0b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
6680*0b57cec5SDimitry Andric         // Should have been parsed earlier via VSTOffset, unless there
6681*0b57cec5SDimitry Andric         // is no summary section.
6682*0b57cec5SDimitry Andric         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
6683*0b57cec5SDimitry Andric                 !SeenGlobalValSummary) &&
6684*0b57cec5SDimitry Andric                "Expected early VST parse via VSTOffset record");
6685*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
6686*0b57cec5SDimitry Andric           return Err;
6687*0b57cec5SDimitry Andric         break;
6688*0b57cec5SDimitry Andric       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
6689*0b57cec5SDimitry Andric       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
6690*0b57cec5SDimitry Andric         // Add the module if it is a per-module index (has a source file name).
6691*0b57cec5SDimitry Andric         if (!SourceFileName.empty())
6692*0b57cec5SDimitry Andric           addThisModule();
6693*0b57cec5SDimitry Andric         assert(!SeenValueSymbolTable &&
6694*0b57cec5SDimitry Andric                "Already read VST when parsing summary block?");
6695*0b57cec5SDimitry Andric         // We might not have a VST if there were no values in the
6696*0b57cec5SDimitry Andric         // summary. An empty summary block generated when we are
6697*0b57cec5SDimitry Andric         // performing ThinLTO compiles so we don't later invoke
6698*0b57cec5SDimitry Andric         // the regular LTO process on them.
6699*0b57cec5SDimitry Andric         if (VSTOffset > 0) {
6700*0b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
6701*0b57cec5SDimitry Andric             return Err;
6702*0b57cec5SDimitry Andric           SeenValueSymbolTable = true;
6703*0b57cec5SDimitry Andric         }
6704*0b57cec5SDimitry Andric         SeenGlobalValSummary = true;
6705*0b57cec5SDimitry Andric         if (Error Err = parseEntireSummary(Entry.ID))
6706*0b57cec5SDimitry Andric           return Err;
6707*0b57cec5SDimitry Andric         break;
6708*0b57cec5SDimitry Andric       case bitc::MODULE_STRTAB_BLOCK_ID:
6709*0b57cec5SDimitry Andric         if (Error Err = parseModuleStringTable())
6710*0b57cec5SDimitry Andric           return Err;
6711*0b57cec5SDimitry Andric         break;
6712*0b57cec5SDimitry Andric       }
6713*0b57cec5SDimitry Andric       continue;
6714*0b57cec5SDimitry Andric 
6715*0b57cec5SDimitry Andric     case BitstreamEntry::Record: {
6716*0b57cec5SDimitry Andric         Record.clear();
6717*0b57cec5SDimitry Andric         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6718*0b57cec5SDimitry Andric         if (!MaybeBitCode)
6719*0b57cec5SDimitry Andric           return MaybeBitCode.takeError();
6720*0b57cec5SDimitry Andric         switch (MaybeBitCode.get()) {
6721*0b57cec5SDimitry Andric         default:
6722*0b57cec5SDimitry Andric           break; // Default behavior, ignore unknown content.
6723*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_VERSION: {
6724*0b57cec5SDimitry Andric           if (Error Err = parseVersionRecord(Record).takeError())
6725*0b57cec5SDimitry Andric             return Err;
6726*0b57cec5SDimitry Andric           break;
6727*0b57cec5SDimitry Andric         }
6728*0b57cec5SDimitry Andric         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
6729*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_SOURCE_FILENAME: {
6730*0b57cec5SDimitry Andric           SmallString<128> ValueName;
6731*0b57cec5SDimitry Andric           if (convertToString(Record, 0, ValueName))
6732*0b57cec5SDimitry Andric             return error("Invalid record");
6733*0b57cec5SDimitry Andric           SourceFileName = ValueName.c_str();
6734*0b57cec5SDimitry Andric           break;
6735*0b57cec5SDimitry Andric         }
6736*0b57cec5SDimitry Andric         /// MODULE_CODE_HASH: [5*i32]
6737*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_HASH: {
6738*0b57cec5SDimitry Andric           if (Record.size() != 5)
6739*0b57cec5SDimitry Andric             return error("Invalid hash length " + Twine(Record.size()).str());
6740*0b57cec5SDimitry Andric           auto &Hash = getThisModule()->second.second;
6741*0b57cec5SDimitry Andric           int Pos = 0;
6742*0b57cec5SDimitry Andric           for (auto &Val : Record) {
6743*0b57cec5SDimitry Andric             assert(!(Val >> 32) && "Unexpected high bits set");
6744*0b57cec5SDimitry Andric             Hash[Pos++] = Val;
6745*0b57cec5SDimitry Andric           }
6746*0b57cec5SDimitry Andric           break;
6747*0b57cec5SDimitry Andric         }
6748*0b57cec5SDimitry Andric         /// MODULE_CODE_VSTOFFSET: [offset]
6749*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_VSTOFFSET:
6750e8d8bef9SDimitry Andric           if (Record.empty())
6751*0b57cec5SDimitry Andric             return error("Invalid record");
6752*0b57cec5SDimitry Andric           // Note that we subtract 1 here because the offset is relative to one
6753*0b57cec5SDimitry Andric           // word before the start of the identification or module block, which
6754*0b57cec5SDimitry Andric           // was historically always the start of the regular bitcode header.
6755*0b57cec5SDimitry Andric           VSTOffset = Record[0] - 1;
6756*0b57cec5SDimitry Andric           break;
6757*0b57cec5SDimitry Andric         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
6758*0b57cec5SDimitry Andric         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
6759*0b57cec5SDimitry Andric         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
6760*0b57cec5SDimitry Andric         // v2: [strtab offset, strtab size, v1]
6761*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_GLOBALVAR:
6762*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_FUNCTION:
6763*0b57cec5SDimitry Andric         case bitc::MODULE_CODE_ALIAS: {
6764*0b57cec5SDimitry Andric           StringRef Name;
6765*0b57cec5SDimitry Andric           ArrayRef<uint64_t> GVRecord;
6766*0b57cec5SDimitry Andric           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
6767*0b57cec5SDimitry Andric           if (GVRecord.size() <= 3)
6768*0b57cec5SDimitry Andric             return error("Invalid record");
6769*0b57cec5SDimitry Andric           uint64_t RawLinkage = GVRecord[3];
6770*0b57cec5SDimitry Andric           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6771*0b57cec5SDimitry Andric           if (!UseStrtab) {
6772*0b57cec5SDimitry Andric             ValueIdToLinkageMap[ValueId++] = Linkage;
6773*0b57cec5SDimitry Andric             break;
6774*0b57cec5SDimitry Andric           }
6775*0b57cec5SDimitry Andric 
6776*0b57cec5SDimitry Andric           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
6777*0b57cec5SDimitry Andric           break;
6778*0b57cec5SDimitry Andric         }
6779*0b57cec5SDimitry Andric         }
6780*0b57cec5SDimitry Andric       }
6781*0b57cec5SDimitry Andric       continue;
6782*0b57cec5SDimitry Andric     }
6783*0b57cec5SDimitry Andric   }
6784*0b57cec5SDimitry Andric }
6785*0b57cec5SDimitry Andric 
6786*0b57cec5SDimitry Andric std::vector<ValueInfo>
6787*0b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
6788*0b57cec5SDimitry Andric   std::vector<ValueInfo> Ret;
6789*0b57cec5SDimitry Andric   Ret.reserve(Record.size());
6790*0b57cec5SDimitry Andric   for (uint64_t RefValueId : Record)
6791*0b57cec5SDimitry Andric     Ret.push_back(getValueInfoFromValueId(RefValueId).first);
6792*0b57cec5SDimitry Andric   return Ret;
6793*0b57cec5SDimitry Andric }
6794*0b57cec5SDimitry Andric 
6795*0b57cec5SDimitry Andric std::vector<FunctionSummary::EdgeTy>
6796*0b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
6797*0b57cec5SDimitry Andric                                               bool IsOldProfileFormat,
6798*0b57cec5SDimitry Andric                                               bool HasProfile, bool HasRelBF) {
6799*0b57cec5SDimitry Andric   std::vector<FunctionSummary::EdgeTy> Ret;
6800*0b57cec5SDimitry Andric   Ret.reserve(Record.size());
6801*0b57cec5SDimitry Andric   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
6802*0b57cec5SDimitry Andric     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
6803*0b57cec5SDimitry Andric     uint64_t RelBF = 0;
6804*0b57cec5SDimitry Andric     ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6805*0b57cec5SDimitry Andric     if (IsOldProfileFormat) {
6806*0b57cec5SDimitry Andric       I += 1; // Skip old callsitecount field
6807*0b57cec5SDimitry Andric       if (HasProfile)
6808*0b57cec5SDimitry Andric         I += 1; // Skip old profilecount field
6809*0b57cec5SDimitry Andric     } else if (HasProfile)
6810*0b57cec5SDimitry Andric       Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
6811*0b57cec5SDimitry Andric     else if (HasRelBF)
6812*0b57cec5SDimitry Andric       RelBF = Record[++I];
6813*0b57cec5SDimitry Andric     Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
6814*0b57cec5SDimitry Andric   }
6815*0b57cec5SDimitry Andric   return Ret;
6816*0b57cec5SDimitry Andric }
6817*0b57cec5SDimitry Andric 
6818*0b57cec5SDimitry Andric static void
6819*0b57cec5SDimitry Andric parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
6820*0b57cec5SDimitry Andric                                        WholeProgramDevirtResolution &Wpd) {
6821*0b57cec5SDimitry Andric   uint64_t ArgNum = Record[Slot++];
6822*0b57cec5SDimitry Andric   WholeProgramDevirtResolution::ByArg &B =
6823*0b57cec5SDimitry Andric       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
6824*0b57cec5SDimitry Andric   Slot += ArgNum;
6825*0b57cec5SDimitry Andric 
6826*0b57cec5SDimitry Andric   B.TheKind =
6827*0b57cec5SDimitry Andric       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
6828*0b57cec5SDimitry Andric   B.Info = Record[Slot++];
6829*0b57cec5SDimitry Andric   B.Byte = Record[Slot++];
6830*0b57cec5SDimitry Andric   B.Bit = Record[Slot++];
6831*0b57cec5SDimitry Andric }
6832*0b57cec5SDimitry Andric 
6833*0b57cec5SDimitry Andric static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
6834*0b57cec5SDimitry Andric                                               StringRef Strtab, size_t &Slot,
6835*0b57cec5SDimitry Andric                                               TypeIdSummary &TypeId) {
6836*0b57cec5SDimitry Andric   uint64_t Id = Record[Slot++];
6837*0b57cec5SDimitry Andric   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
6838*0b57cec5SDimitry Andric 
6839*0b57cec5SDimitry Andric   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
6840*0b57cec5SDimitry Andric   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
6841*0b57cec5SDimitry Andric                         static_cast<size_t>(Record[Slot + 1])};
6842*0b57cec5SDimitry Andric   Slot += 2;
6843*0b57cec5SDimitry Andric 
6844*0b57cec5SDimitry Andric   uint64_t ResByArgNum = Record[Slot++];
6845*0b57cec5SDimitry Andric   for (uint64_t I = 0; I != ResByArgNum; ++I)
6846*0b57cec5SDimitry Andric     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
6847*0b57cec5SDimitry Andric }
6848*0b57cec5SDimitry Andric 
6849*0b57cec5SDimitry Andric static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
6850*0b57cec5SDimitry Andric                                      StringRef Strtab,
6851*0b57cec5SDimitry Andric                                      ModuleSummaryIndex &TheIndex) {
6852*0b57cec5SDimitry Andric   size_t Slot = 0;
6853*0b57cec5SDimitry Andric   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
6854*0b57cec5SDimitry Andric       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
6855*0b57cec5SDimitry Andric   Slot += 2;
6856*0b57cec5SDimitry Andric 
6857*0b57cec5SDimitry Andric   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
6858*0b57cec5SDimitry Andric   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
6859*0b57cec5SDimitry Andric   TypeId.TTRes.AlignLog2 = Record[Slot++];
6860*0b57cec5SDimitry Andric   TypeId.TTRes.SizeM1 = Record[Slot++];
6861*0b57cec5SDimitry Andric   TypeId.TTRes.BitMask = Record[Slot++];
6862*0b57cec5SDimitry Andric   TypeId.TTRes.InlineBits = Record[Slot++];
6863*0b57cec5SDimitry Andric 
6864*0b57cec5SDimitry Andric   while (Slot < Record.size())
6865*0b57cec5SDimitry Andric     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
6866*0b57cec5SDimitry Andric }
6867*0b57cec5SDimitry Andric 
6868e8d8bef9SDimitry Andric std::vector<FunctionSummary::ParamAccess>
6869e8d8bef9SDimitry Andric ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
68705ffd83dbSDimitry Andric   auto ReadRange = [&]() {
68715ffd83dbSDimitry Andric     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
68725ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
68735ffd83dbSDimitry Andric     Record = Record.drop_front();
68745ffd83dbSDimitry Andric     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
68755ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
68765ffd83dbSDimitry Andric     Record = Record.drop_front();
68775ffd83dbSDimitry Andric     ConstantRange Range{Lower, Upper};
68785ffd83dbSDimitry Andric     assert(!Range.isFullSet());
68795ffd83dbSDimitry Andric     assert(!Range.isUpperSignWrapped());
68805ffd83dbSDimitry Andric     return Range;
68815ffd83dbSDimitry Andric   };
68825ffd83dbSDimitry Andric 
68835ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
68845ffd83dbSDimitry Andric   while (!Record.empty()) {
68855ffd83dbSDimitry Andric     PendingParamAccesses.emplace_back();
68865ffd83dbSDimitry Andric     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
68875ffd83dbSDimitry Andric     ParamAccess.ParamNo = Record.front();
68885ffd83dbSDimitry Andric     Record = Record.drop_front();
68895ffd83dbSDimitry Andric     ParamAccess.Use = ReadRange();
68905ffd83dbSDimitry Andric     ParamAccess.Calls.resize(Record.front());
68915ffd83dbSDimitry Andric     Record = Record.drop_front();
68925ffd83dbSDimitry Andric     for (auto &Call : ParamAccess.Calls) {
68935ffd83dbSDimitry Andric       Call.ParamNo = Record.front();
68945ffd83dbSDimitry Andric       Record = Record.drop_front();
6895e8d8bef9SDimitry Andric       Call.Callee = getValueInfoFromValueId(Record.front()).first;
68965ffd83dbSDimitry Andric       Record = Record.drop_front();
68975ffd83dbSDimitry Andric       Call.Offsets = ReadRange();
68985ffd83dbSDimitry Andric     }
68995ffd83dbSDimitry Andric   }
69005ffd83dbSDimitry Andric   return PendingParamAccesses;
69015ffd83dbSDimitry Andric }
69025ffd83dbSDimitry Andric 
6903*0b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
6904*0b57cec5SDimitry Andric     ArrayRef<uint64_t> Record, size_t &Slot,
6905*0b57cec5SDimitry Andric     TypeIdCompatibleVtableInfo &TypeId) {
6906*0b57cec5SDimitry Andric   uint64_t Offset = Record[Slot++];
6907*0b57cec5SDimitry Andric   ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first;
6908*0b57cec5SDimitry Andric   TypeId.push_back({Offset, Callee});
6909*0b57cec5SDimitry Andric }
6910*0b57cec5SDimitry Andric 
6911*0b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
6912*0b57cec5SDimitry Andric     ArrayRef<uint64_t> Record) {
6913*0b57cec5SDimitry Andric   size_t Slot = 0;
6914*0b57cec5SDimitry Andric   TypeIdCompatibleVtableInfo &TypeId =
6915*0b57cec5SDimitry Andric       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
6916*0b57cec5SDimitry Andric           {Strtab.data() + Record[Slot],
6917*0b57cec5SDimitry Andric            static_cast<size_t>(Record[Slot + 1])});
6918*0b57cec5SDimitry Andric   Slot += 2;
6919*0b57cec5SDimitry Andric 
6920*0b57cec5SDimitry Andric   while (Slot < Record.size())
6921*0b57cec5SDimitry Andric     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
6922*0b57cec5SDimitry Andric }
6923*0b57cec5SDimitry Andric 
6924*0b57cec5SDimitry Andric static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
6925*0b57cec5SDimitry Andric                            unsigned WOCnt) {
6926*0b57cec5SDimitry Andric   // Readonly and writeonly refs are in the end of the refs list.
6927*0b57cec5SDimitry Andric   assert(ROCnt + WOCnt <= Refs.size());
6928*0b57cec5SDimitry Andric   unsigned FirstWORef = Refs.size() - WOCnt;
6929*0b57cec5SDimitry Andric   unsigned RefNo = FirstWORef - ROCnt;
6930*0b57cec5SDimitry Andric   for (; RefNo < FirstWORef; ++RefNo)
6931*0b57cec5SDimitry Andric     Refs[RefNo].setReadOnly();
6932*0b57cec5SDimitry Andric   for (; RefNo < Refs.size(); ++RefNo)
6933*0b57cec5SDimitry Andric     Refs[RefNo].setWriteOnly();
6934*0b57cec5SDimitry Andric }
6935*0b57cec5SDimitry Andric 
6936*0b57cec5SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary
6937*0b57cec5SDimitry Andric // objects in the index.
6938*0b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
6939*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
6940*0b57cec5SDimitry Andric     return Err;
6941*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
6942*0b57cec5SDimitry Andric 
6943*0b57cec5SDimitry Andric   // Parse version
6944*0b57cec5SDimitry Andric   {
6945*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6946*0b57cec5SDimitry Andric     if (!MaybeEntry)
6947*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
6948*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
6949*0b57cec5SDimitry Andric 
6950*0b57cec5SDimitry Andric     if (Entry.Kind != BitstreamEntry::Record)
6951*0b57cec5SDimitry Andric       return error("Invalid Summary Block: record for version expected");
6952*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6953*0b57cec5SDimitry Andric     if (!MaybeRecord)
6954*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
6955*0b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::FS_VERSION)
6956*0b57cec5SDimitry Andric       return error("Invalid Summary Block: version expected");
6957*0b57cec5SDimitry Andric   }
6958*0b57cec5SDimitry Andric   const uint64_t Version = Record[0];
6959*0b57cec5SDimitry Andric   const bool IsOldProfileFormat = Version == 1;
6960480093f4SDimitry Andric   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
6961*0b57cec5SDimitry Andric     return error("Invalid summary version " + Twine(Version) +
6962480093f4SDimitry Andric                  ". Version should be in the range [1-" +
6963480093f4SDimitry Andric                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
6964480093f4SDimitry Andric                  "].");
6965*0b57cec5SDimitry Andric   Record.clear();
6966*0b57cec5SDimitry Andric 
6967*0b57cec5SDimitry Andric   // Keep around the last seen summary to be used when we see an optional
6968*0b57cec5SDimitry Andric   // "OriginalName" attachement.
6969*0b57cec5SDimitry Andric   GlobalValueSummary *LastSeenSummary = nullptr;
6970*0b57cec5SDimitry Andric   GlobalValue::GUID LastSeenGUID = 0;
6971*0b57cec5SDimitry Andric 
6972*0b57cec5SDimitry Andric   // We can expect to see any number of type ID information records before
6973*0b57cec5SDimitry Andric   // each function summary records; these variables store the information
6974*0b57cec5SDimitry Andric   // collected so far so that it can be used to create the summary object.
6975*0b57cec5SDimitry Andric   std::vector<GlobalValue::GUID> PendingTypeTests;
6976*0b57cec5SDimitry Andric   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
6977*0b57cec5SDimitry Andric       PendingTypeCheckedLoadVCalls;
6978*0b57cec5SDimitry Andric   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
6979*0b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls;
69805ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6981*0b57cec5SDimitry Andric 
6982*0b57cec5SDimitry Andric   while (true) {
6983*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6984*0b57cec5SDimitry Andric     if (!MaybeEntry)
6985*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
6986*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
6987*0b57cec5SDimitry Andric 
6988*0b57cec5SDimitry Andric     switch (Entry.Kind) {
6989*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
6990*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
6991*0b57cec5SDimitry Andric       return error("Malformed block");
6992*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
6993*0b57cec5SDimitry Andric       return Error::success();
6994*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
6995*0b57cec5SDimitry Andric       // The interesting case.
6996*0b57cec5SDimitry Andric       break;
6997*0b57cec5SDimitry Andric     }
6998*0b57cec5SDimitry Andric 
6999*0b57cec5SDimitry Andric     // Read a record. The record format depends on whether this
7000*0b57cec5SDimitry Andric     // is a per-module index or a combined index file. In the per-module
7001*0b57cec5SDimitry Andric     // case the records contain the associated value's ID for correlation
7002*0b57cec5SDimitry Andric     // with VST entries. In the combined index the correlation is done
7003*0b57cec5SDimitry Andric     // via the bitcode offset of the summary records (which were saved
7004*0b57cec5SDimitry Andric     // in the combined index VST entries). The records also contain
7005*0b57cec5SDimitry Andric     // information used for ThinLTO renaming and importing.
7006*0b57cec5SDimitry Andric     Record.clear();
7007*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7008*0b57cec5SDimitry Andric     if (!MaybeBitCode)
7009*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
7010*0b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
7011*0b57cec5SDimitry Andric     default: // Default behavior: ignore.
7012*0b57cec5SDimitry Andric       break;
7013*0b57cec5SDimitry Andric     case bitc::FS_FLAGS: {  // [flags]
70145ffd83dbSDimitry Andric       TheIndex.setFlags(Record[0]);
7015*0b57cec5SDimitry Andric       break;
7016*0b57cec5SDimitry Andric     }
7017*0b57cec5SDimitry Andric     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
7018*0b57cec5SDimitry Andric       uint64_t ValueID = Record[0];
7019*0b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
7020*0b57cec5SDimitry Andric       ValueIdToValueInfoMap[ValueID] =
7021*0b57cec5SDimitry Andric           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
7022*0b57cec5SDimitry Andric       break;
7023*0b57cec5SDimitry Andric     }
7024*0b57cec5SDimitry Andric     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
7025*0b57cec5SDimitry Andric     //                numrefs x valueid, n x (valueid)]
7026*0b57cec5SDimitry Andric     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
7027*0b57cec5SDimitry Andric     //                        numrefs x valueid,
7028*0b57cec5SDimitry Andric     //                        n x (valueid, hotness)]
7029*0b57cec5SDimitry Andric     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
7030*0b57cec5SDimitry Andric     //                      numrefs x valueid,
7031*0b57cec5SDimitry Andric     //                      n x (valueid, relblockfreq)]
7032*0b57cec5SDimitry Andric     case bitc::FS_PERMODULE:
7033*0b57cec5SDimitry Andric     case bitc::FS_PERMODULE_RELBF:
7034*0b57cec5SDimitry Andric     case bitc::FS_PERMODULE_PROFILE: {
7035*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
7036*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
7037*0b57cec5SDimitry Andric       unsigned InstCount = Record[2];
7038*0b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
7039*0b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
7040*0b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
7041*0b57cec5SDimitry Andric       int RefListStartIndex = 4;
7042*0b57cec5SDimitry Andric       if (Version >= 4) {
7043*0b57cec5SDimitry Andric         RawFunFlags = Record[3];
7044*0b57cec5SDimitry Andric         NumRefs = Record[4];
7045*0b57cec5SDimitry Andric         RefListStartIndex = 5;
7046*0b57cec5SDimitry Andric         if (Version >= 5) {
7047*0b57cec5SDimitry Andric           NumRORefs = Record[5];
7048*0b57cec5SDimitry Andric           RefListStartIndex = 6;
7049*0b57cec5SDimitry Andric           if (Version >= 7) {
7050*0b57cec5SDimitry Andric             NumWORefs = Record[6];
7051*0b57cec5SDimitry Andric             RefListStartIndex = 7;
7052*0b57cec5SDimitry Andric           }
7053*0b57cec5SDimitry Andric         }
7054*0b57cec5SDimitry Andric       }
7055*0b57cec5SDimitry Andric 
7056*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7057*0b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
7058*0b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
7059*0b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
7060*0b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
7061*0b57cec5SDimitry Andric       // ownership.
7062*0b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7063*0b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
7064*0b57cec5SDimitry Andric              "Record size inconsistent with number of references");
7065*0b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
7066*0b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7067*0b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
7068*0b57cec5SDimitry Andric       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
7069*0b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
7070*0b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7071*0b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, HasRelBF);
7072*0b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
70738bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
7074*0b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
7075*0b57cec5SDimitry Andric           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
7076*0b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
7077*0b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
7078*0b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
70795ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
70805ffd83dbSDimitry Andric           std::move(PendingParamAccesses));
7081*0b57cec5SDimitry Andric       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7082*0b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
7083*0b57cec5SDimitry Andric       FS->setOriginalName(VIAndOriginalGUID.second);
7084*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
7085*0b57cec5SDimitry Andric       break;
7086*0b57cec5SDimitry Andric     }
7087*0b57cec5SDimitry Andric     // FS_ALIAS: [valueid, flags, valueid]
7088*0b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
7089*0b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
7090*0b57cec5SDimitry Andric     case bitc::FS_ALIAS: {
7091*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
7092*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
7093*0b57cec5SDimitry Andric       unsigned AliaseeID = Record[2];
7094*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
70958bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
7096*0b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
7097*0b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
7098*0b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
7099*0b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
7100*0b57cec5SDimitry Andric       // ownership.
7101*0b57cec5SDimitry Andric       AS->setModulePath(getThisModule()->first());
7102*0b57cec5SDimitry Andric 
7103*0b57cec5SDimitry Andric       auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
7104*0b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
7105*0b57cec5SDimitry Andric       if (!AliaseeInModule)
7106*0b57cec5SDimitry Andric         return error("Alias expects aliasee summary to be parsed");
7107*0b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
7108*0b57cec5SDimitry Andric 
7109*0b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7110*0b57cec5SDimitry Andric       AS->setOriginalName(GUID.second);
7111*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
7112*0b57cec5SDimitry Andric       break;
7113*0b57cec5SDimitry Andric     }
7114*0b57cec5SDimitry Andric     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
7115*0b57cec5SDimitry Andric     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
7116*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
7117*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
7118*0b57cec5SDimitry Andric       unsigned RefArrayStart = 2;
7119*0b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
71205ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
71215ffd83dbSDimitry Andric                                       /* Constant */ false,
71225ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
7123*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7124*0b57cec5SDimitry Andric       if (Version >= 5) {
7125*0b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[2]);
7126*0b57cec5SDimitry Andric         RefArrayStart = 3;
7127*0b57cec5SDimitry Andric       }
7128*0b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
7129*0b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7130*0b57cec5SDimitry Andric       auto FS =
71318bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7132*0b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
7133*0b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7134*0b57cec5SDimitry Andric       FS->setOriginalName(GUID.second);
7135*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
7136*0b57cec5SDimitry Andric       break;
7137*0b57cec5SDimitry Andric     }
7138*0b57cec5SDimitry Andric     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
7139*0b57cec5SDimitry Andric     //                        numrefs, numrefs x valueid,
7140*0b57cec5SDimitry Andric     //                        n x (valueid, offset)]
7141*0b57cec5SDimitry Andric     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
7142*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
7143*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
7144*0b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
7145*0b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
7146*0b57cec5SDimitry Andric       unsigned RefListStartIndex = 4;
7147*0b57cec5SDimitry Andric       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7148*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7149*0b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
7150*0b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7151*0b57cec5SDimitry Andric       VTableFuncList VTableFuncs;
7152*0b57cec5SDimitry Andric       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
7153*0b57cec5SDimitry Andric         ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
7154*0b57cec5SDimitry Andric         uint64_t Offset = Record[++I];
7155*0b57cec5SDimitry Andric         VTableFuncs.push_back({Callee, Offset});
7156*0b57cec5SDimitry Andric       }
7157*0b57cec5SDimitry Andric       auto VS =
71588bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7159*0b57cec5SDimitry Andric       VS->setModulePath(getThisModule()->first());
7160*0b57cec5SDimitry Andric       VS->setVTableFuncs(VTableFuncs);
7161*0b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
7162*0b57cec5SDimitry Andric       VS->setOriginalName(GUID.second);
7163*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(VS));
7164*0b57cec5SDimitry Andric       break;
7165*0b57cec5SDimitry Andric     }
7166*0b57cec5SDimitry Andric     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
7167*0b57cec5SDimitry Andric     //               numrefs x valueid, n x (valueid)]
7168*0b57cec5SDimitry Andric     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
7169*0b57cec5SDimitry Andric     //                       numrefs x valueid, n x (valueid, hotness)]
7170*0b57cec5SDimitry Andric     case bitc::FS_COMBINED:
7171*0b57cec5SDimitry Andric     case bitc::FS_COMBINED_PROFILE: {
7172*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
7173*0b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
7174*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
7175*0b57cec5SDimitry Andric       unsigned InstCount = Record[3];
7176*0b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
7177*0b57cec5SDimitry Andric       uint64_t EntryCount = 0;
7178*0b57cec5SDimitry Andric       unsigned NumRefs = Record[4];
7179*0b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
7180*0b57cec5SDimitry Andric       int RefListStartIndex = 5;
7181*0b57cec5SDimitry Andric 
7182*0b57cec5SDimitry Andric       if (Version >= 4) {
7183*0b57cec5SDimitry Andric         RawFunFlags = Record[4];
7184*0b57cec5SDimitry Andric         RefListStartIndex = 6;
7185*0b57cec5SDimitry Andric         size_t NumRefsIndex = 5;
7186*0b57cec5SDimitry Andric         if (Version >= 5) {
7187*0b57cec5SDimitry Andric           unsigned NumRORefsOffset = 1;
7188*0b57cec5SDimitry Andric           RefListStartIndex = 7;
7189*0b57cec5SDimitry Andric           if (Version >= 6) {
7190*0b57cec5SDimitry Andric             NumRefsIndex = 6;
7191*0b57cec5SDimitry Andric             EntryCount = Record[5];
7192*0b57cec5SDimitry Andric             RefListStartIndex = 8;
7193*0b57cec5SDimitry Andric             if (Version >= 7) {
7194*0b57cec5SDimitry Andric               RefListStartIndex = 9;
7195*0b57cec5SDimitry Andric               NumWORefs = Record[8];
7196*0b57cec5SDimitry Andric               NumRORefsOffset = 2;
7197*0b57cec5SDimitry Andric             }
7198*0b57cec5SDimitry Andric           }
7199*0b57cec5SDimitry Andric           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
7200*0b57cec5SDimitry Andric         }
7201*0b57cec5SDimitry Andric         NumRefs = Record[NumRefsIndex];
7202*0b57cec5SDimitry Andric       }
7203*0b57cec5SDimitry Andric 
7204*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7205*0b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7206*0b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
7207*0b57cec5SDimitry Andric              "Record size inconsistent with number of references");
7208*0b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
7209*0b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7210*0b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
7211*0b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
7212*0b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7213*0b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, false);
7214*0b57cec5SDimitry Andric       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
7215*0b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
72168bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
7217*0b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
7218*0b57cec5SDimitry Andric           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
7219*0b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
7220*0b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
7221*0b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
72225ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
72235ffd83dbSDimitry Andric           std::move(PendingParamAccesses));
7224*0b57cec5SDimitry Andric       LastSeenSummary = FS.get();
7225*0b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
7226*0b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
7227*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
7228*0b57cec5SDimitry Andric       break;
7229*0b57cec5SDimitry Andric     }
7230*0b57cec5SDimitry Andric     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
7231*0b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
7232*0b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
7233*0b57cec5SDimitry Andric     case bitc::FS_COMBINED_ALIAS: {
7234*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
7235*0b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
7236*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
7237*0b57cec5SDimitry Andric       unsigned AliaseeValueId = Record[3];
7238*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
72398bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
7240*0b57cec5SDimitry Andric       LastSeenSummary = AS.get();
7241*0b57cec5SDimitry Andric       AS->setModulePath(ModuleIdMap[ModuleId]);
7242*0b57cec5SDimitry Andric 
7243*0b57cec5SDimitry Andric       auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
7244*0b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
7245*0b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
7246*0b57cec5SDimitry Andric 
7247*0b57cec5SDimitry Andric       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
7248*0b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
7249*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(AS));
7250*0b57cec5SDimitry Andric       break;
7251*0b57cec5SDimitry Andric     }
7252*0b57cec5SDimitry Andric     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
7253*0b57cec5SDimitry Andric     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
7254*0b57cec5SDimitry Andric       unsigned ValueID = Record[0];
7255*0b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
7256*0b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
7257*0b57cec5SDimitry Andric       unsigned RefArrayStart = 3;
7258*0b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
72595ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
72605ffd83dbSDimitry Andric                                       /* Constant */ false,
72615ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
7262*0b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7263*0b57cec5SDimitry Andric       if (Version >= 5) {
7264*0b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[3]);
7265*0b57cec5SDimitry Andric         RefArrayStart = 4;
7266*0b57cec5SDimitry Andric       }
7267*0b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
7268*0b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7269*0b57cec5SDimitry Andric       auto FS =
72708bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7271*0b57cec5SDimitry Andric       LastSeenSummary = FS.get();
7272*0b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
7273*0b57cec5SDimitry Andric       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
7274*0b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
7275*0b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
7276*0b57cec5SDimitry Andric       break;
7277*0b57cec5SDimitry Andric     }
7278*0b57cec5SDimitry Andric     // FS_COMBINED_ORIGINAL_NAME: [original_name]
7279*0b57cec5SDimitry Andric     case bitc::FS_COMBINED_ORIGINAL_NAME: {
7280*0b57cec5SDimitry Andric       uint64_t OriginalName = Record[0];
7281*0b57cec5SDimitry Andric       if (!LastSeenSummary)
7282*0b57cec5SDimitry Andric         return error("Name attachment that does not follow a combined record");
7283*0b57cec5SDimitry Andric       LastSeenSummary->setOriginalName(OriginalName);
7284*0b57cec5SDimitry Andric       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
7285*0b57cec5SDimitry Andric       // Reset the LastSeenSummary
7286*0b57cec5SDimitry Andric       LastSeenSummary = nullptr;
7287*0b57cec5SDimitry Andric       LastSeenGUID = 0;
7288*0b57cec5SDimitry Andric       break;
7289*0b57cec5SDimitry Andric     }
7290*0b57cec5SDimitry Andric     case bitc::FS_TYPE_TESTS:
7291*0b57cec5SDimitry Andric       assert(PendingTypeTests.empty());
7292e8d8bef9SDimitry Andric       llvm::append_range(PendingTypeTests, Record);
7293*0b57cec5SDimitry Andric       break;
7294*0b57cec5SDimitry Andric 
7295*0b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
7296*0b57cec5SDimitry Andric       assert(PendingTypeTestAssumeVCalls.empty());
7297*0b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
7298*0b57cec5SDimitry Andric         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
7299*0b57cec5SDimitry Andric       break;
7300*0b57cec5SDimitry Andric 
7301*0b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
7302*0b57cec5SDimitry Andric       assert(PendingTypeCheckedLoadVCalls.empty());
7303*0b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
7304*0b57cec5SDimitry Andric         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
7305*0b57cec5SDimitry Andric       break;
7306*0b57cec5SDimitry Andric 
7307*0b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
7308*0b57cec5SDimitry Andric       PendingTypeTestAssumeConstVCalls.push_back(
7309*0b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
7310*0b57cec5SDimitry Andric       break;
7311*0b57cec5SDimitry Andric 
7312*0b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
7313*0b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls.push_back(
7314*0b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
7315*0b57cec5SDimitry Andric       break;
7316*0b57cec5SDimitry Andric 
7317*0b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DEFS: {
7318*0b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
7319*0b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
7320*0b57cec5SDimitry Andric         CfiFunctionDefs.insert(
7321*0b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
7322*0b57cec5SDimitry Andric       break;
7323*0b57cec5SDimitry Andric     }
7324*0b57cec5SDimitry Andric 
7325*0b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DECLS: {
7326*0b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
7327*0b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
7328*0b57cec5SDimitry Andric         CfiFunctionDecls.insert(
7329*0b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
7330*0b57cec5SDimitry Andric       break;
7331*0b57cec5SDimitry Andric     }
7332*0b57cec5SDimitry Andric 
7333*0b57cec5SDimitry Andric     case bitc::FS_TYPE_ID:
7334*0b57cec5SDimitry Andric       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
7335*0b57cec5SDimitry Andric       break;
7336*0b57cec5SDimitry Andric 
7337*0b57cec5SDimitry Andric     case bitc::FS_TYPE_ID_METADATA:
7338*0b57cec5SDimitry Andric       parseTypeIdCompatibleVtableSummaryRecord(Record);
7339*0b57cec5SDimitry Andric       break;
73405ffd83dbSDimitry Andric 
73415ffd83dbSDimitry Andric     case bitc::FS_BLOCK_COUNT:
73425ffd83dbSDimitry Andric       TheIndex.addBlockCount(Record[0]);
73435ffd83dbSDimitry Andric       break;
73445ffd83dbSDimitry Andric 
73455ffd83dbSDimitry Andric     case bitc::FS_PARAM_ACCESS: {
73465ffd83dbSDimitry Andric       PendingParamAccesses = parseParamAccesses(Record);
73475ffd83dbSDimitry Andric       break;
73485ffd83dbSDimitry Andric     }
7349*0b57cec5SDimitry Andric     }
7350*0b57cec5SDimitry Andric   }
7351*0b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
7352*0b57cec5SDimitry Andric }
7353*0b57cec5SDimitry Andric 
7354*0b57cec5SDimitry Andric // Parse the  module string table block into the Index.
7355*0b57cec5SDimitry Andric // This populates the ModulePathStringTable map in the index.
7356*0b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
7357*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
7358*0b57cec5SDimitry Andric     return Err;
7359*0b57cec5SDimitry Andric 
7360*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
7361*0b57cec5SDimitry Andric 
7362*0b57cec5SDimitry Andric   SmallString<128> ModulePath;
7363*0b57cec5SDimitry Andric   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
7364*0b57cec5SDimitry Andric 
7365*0b57cec5SDimitry Andric   while (true) {
7366*0b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7367*0b57cec5SDimitry Andric     if (!MaybeEntry)
7368*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
7369*0b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
7370*0b57cec5SDimitry Andric 
7371*0b57cec5SDimitry Andric     switch (Entry.Kind) {
7372*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
7373*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
7374*0b57cec5SDimitry Andric       return error("Malformed block");
7375*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
7376*0b57cec5SDimitry Andric       return Error::success();
7377*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
7378*0b57cec5SDimitry Andric       // The interesting case.
7379*0b57cec5SDimitry Andric       break;
7380*0b57cec5SDimitry Andric     }
7381*0b57cec5SDimitry Andric 
7382*0b57cec5SDimitry Andric     Record.clear();
7383*0b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7384*0b57cec5SDimitry Andric     if (!MaybeRecord)
7385*0b57cec5SDimitry Andric       return MaybeRecord.takeError();
7386*0b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
7387*0b57cec5SDimitry Andric     default: // Default behavior: ignore.
7388*0b57cec5SDimitry Andric       break;
7389*0b57cec5SDimitry Andric     case bitc::MST_CODE_ENTRY: {
7390*0b57cec5SDimitry Andric       // MST_ENTRY: [modid, namechar x N]
7391*0b57cec5SDimitry Andric       uint64_t ModuleId = Record[0];
7392*0b57cec5SDimitry Andric 
7393*0b57cec5SDimitry Andric       if (convertToString(Record, 1, ModulePath))
7394*0b57cec5SDimitry Andric         return error("Invalid record");
7395*0b57cec5SDimitry Andric 
7396*0b57cec5SDimitry Andric       LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
7397*0b57cec5SDimitry Andric       ModuleIdMap[ModuleId] = LastSeenModule->first();
7398*0b57cec5SDimitry Andric 
7399*0b57cec5SDimitry Andric       ModulePath.clear();
7400*0b57cec5SDimitry Andric       break;
7401*0b57cec5SDimitry Andric     }
7402*0b57cec5SDimitry Andric     /// MST_CODE_HASH: [5*i32]
7403*0b57cec5SDimitry Andric     case bitc::MST_CODE_HASH: {
7404*0b57cec5SDimitry Andric       if (Record.size() != 5)
7405*0b57cec5SDimitry Andric         return error("Invalid hash length " + Twine(Record.size()).str());
7406*0b57cec5SDimitry Andric       if (!LastSeenModule)
7407*0b57cec5SDimitry Andric         return error("Invalid hash that does not follow a module path");
7408*0b57cec5SDimitry Andric       int Pos = 0;
7409*0b57cec5SDimitry Andric       for (auto &Val : Record) {
7410*0b57cec5SDimitry Andric         assert(!(Val >> 32) && "Unexpected high bits set");
7411*0b57cec5SDimitry Andric         LastSeenModule->second.second[Pos++] = Val;
7412*0b57cec5SDimitry Andric       }
7413*0b57cec5SDimitry Andric       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
7414*0b57cec5SDimitry Andric       LastSeenModule = nullptr;
7415*0b57cec5SDimitry Andric       break;
7416*0b57cec5SDimitry Andric     }
7417*0b57cec5SDimitry Andric     }
7418*0b57cec5SDimitry Andric   }
7419*0b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
7420*0b57cec5SDimitry Andric }
7421*0b57cec5SDimitry Andric 
7422*0b57cec5SDimitry Andric namespace {
7423*0b57cec5SDimitry Andric 
7424*0b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
7425*0b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
7426*0b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
7427*0b57cec5SDimitry Andric class BitcodeErrorCategoryType : public std::error_category {
7428*0b57cec5SDimitry Andric   const char *name() const noexcept override {
7429*0b57cec5SDimitry Andric     return "llvm.bitcode";
7430*0b57cec5SDimitry Andric   }
7431*0b57cec5SDimitry Andric 
7432*0b57cec5SDimitry Andric   std::string message(int IE) const override {
7433*0b57cec5SDimitry Andric     BitcodeError E = static_cast<BitcodeError>(IE);
7434*0b57cec5SDimitry Andric     switch (E) {
7435*0b57cec5SDimitry Andric     case BitcodeError::CorruptedBitcode:
7436*0b57cec5SDimitry Andric       return "Corrupted bitcode";
7437*0b57cec5SDimitry Andric     }
7438*0b57cec5SDimitry Andric     llvm_unreachable("Unknown error type!");
7439*0b57cec5SDimitry Andric   }
7440*0b57cec5SDimitry Andric };
7441*0b57cec5SDimitry Andric 
7442*0b57cec5SDimitry Andric } // end anonymous namespace
7443*0b57cec5SDimitry Andric 
7444*0b57cec5SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
7445*0b57cec5SDimitry Andric 
7446*0b57cec5SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() {
7447*0b57cec5SDimitry Andric   return *ErrorCategory;
7448*0b57cec5SDimitry Andric }
7449*0b57cec5SDimitry Andric 
7450*0b57cec5SDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
7451*0b57cec5SDimitry Andric                                             unsigned Block, unsigned RecordID) {
7452*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(Block))
7453*0b57cec5SDimitry Andric     return std::move(Err);
7454*0b57cec5SDimitry Andric 
7455*0b57cec5SDimitry Andric   StringRef Strtab;
7456*0b57cec5SDimitry Andric   while (true) {
7457*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7458*0b57cec5SDimitry Andric     if (!MaybeEntry)
7459*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
7460*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
7461*0b57cec5SDimitry Andric 
7462*0b57cec5SDimitry Andric     switch (Entry.Kind) {
7463*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
7464*0b57cec5SDimitry Andric       return Strtab;
7465*0b57cec5SDimitry Andric 
7466*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
7467*0b57cec5SDimitry Andric       return error("Malformed block");
7468*0b57cec5SDimitry Andric 
7469*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
7470*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
7471*0b57cec5SDimitry Andric         return std::move(Err);
7472*0b57cec5SDimitry Andric       break;
7473*0b57cec5SDimitry Andric 
7474*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
7475*0b57cec5SDimitry Andric       StringRef Blob;
7476*0b57cec5SDimitry Andric       SmallVector<uint64_t, 1> Record;
7477*0b57cec5SDimitry Andric       Expected<unsigned> MaybeRecord =
7478*0b57cec5SDimitry Andric           Stream.readRecord(Entry.ID, Record, &Blob);
7479*0b57cec5SDimitry Andric       if (!MaybeRecord)
7480*0b57cec5SDimitry Andric         return MaybeRecord.takeError();
7481*0b57cec5SDimitry Andric       if (MaybeRecord.get() == RecordID)
7482*0b57cec5SDimitry Andric         Strtab = Blob;
7483*0b57cec5SDimitry Andric       break;
7484*0b57cec5SDimitry Andric     }
7485*0b57cec5SDimitry Andric   }
7486*0b57cec5SDimitry Andric }
7487*0b57cec5SDimitry Andric 
7488*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7489*0b57cec5SDimitry Andric // External interface
7490*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
7491*0b57cec5SDimitry Andric 
7492*0b57cec5SDimitry Andric Expected<std::vector<BitcodeModule>>
7493*0b57cec5SDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
7494*0b57cec5SDimitry Andric   auto FOrErr = getBitcodeFileContents(Buffer);
7495*0b57cec5SDimitry Andric   if (!FOrErr)
7496*0b57cec5SDimitry Andric     return FOrErr.takeError();
7497*0b57cec5SDimitry Andric   return std::move(FOrErr->Mods);
7498*0b57cec5SDimitry Andric }
7499*0b57cec5SDimitry Andric 
7500*0b57cec5SDimitry Andric Expected<BitcodeFileContents>
7501*0b57cec5SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
7502*0b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7503*0b57cec5SDimitry Andric   if (!StreamOrErr)
7504*0b57cec5SDimitry Andric     return StreamOrErr.takeError();
7505*0b57cec5SDimitry Andric   BitstreamCursor &Stream = *StreamOrErr;
7506*0b57cec5SDimitry Andric 
7507*0b57cec5SDimitry Andric   BitcodeFileContents F;
7508*0b57cec5SDimitry Andric   while (true) {
7509*0b57cec5SDimitry Andric     uint64_t BCBegin = Stream.getCurrentByteNo();
7510*0b57cec5SDimitry Andric 
7511*0b57cec5SDimitry Andric     // We may be consuming bitcode from a client that leaves garbage at the end
7512*0b57cec5SDimitry Andric     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
7513*0b57cec5SDimitry Andric     // the end that there cannot possibly be another module, stop looking.
7514*0b57cec5SDimitry Andric     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
7515*0b57cec5SDimitry Andric       return F;
7516*0b57cec5SDimitry Andric 
7517*0b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7518*0b57cec5SDimitry Andric     if (!MaybeEntry)
7519*0b57cec5SDimitry Andric       return MaybeEntry.takeError();
7520*0b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
7521*0b57cec5SDimitry Andric 
7522*0b57cec5SDimitry Andric     switch (Entry.Kind) {
7523*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
7524*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
7525*0b57cec5SDimitry Andric       return error("Malformed block");
7526*0b57cec5SDimitry Andric 
7527*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: {
7528*0b57cec5SDimitry Andric       uint64_t IdentificationBit = -1ull;
7529*0b57cec5SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
7530*0b57cec5SDimitry Andric         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
7531*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
7532*0b57cec5SDimitry Andric           return std::move(Err);
7533*0b57cec5SDimitry Andric 
7534*0b57cec5SDimitry Andric         {
7535*0b57cec5SDimitry Andric           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7536*0b57cec5SDimitry Andric           if (!MaybeEntry)
7537*0b57cec5SDimitry Andric             return MaybeEntry.takeError();
7538*0b57cec5SDimitry Andric           Entry = MaybeEntry.get();
7539*0b57cec5SDimitry Andric         }
7540*0b57cec5SDimitry Andric 
7541*0b57cec5SDimitry Andric         if (Entry.Kind != BitstreamEntry::SubBlock ||
7542*0b57cec5SDimitry Andric             Entry.ID != bitc::MODULE_BLOCK_ID)
7543*0b57cec5SDimitry Andric           return error("Malformed block");
7544*0b57cec5SDimitry Andric       }
7545*0b57cec5SDimitry Andric 
7546*0b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
7547*0b57cec5SDimitry Andric         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
7548*0b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
7549*0b57cec5SDimitry Andric           return std::move(Err);
7550*0b57cec5SDimitry Andric 
7551*0b57cec5SDimitry Andric         F.Mods.push_back({Stream.getBitcodeBytes().slice(
7552*0b57cec5SDimitry Andric                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
7553*0b57cec5SDimitry Andric                           Buffer.getBufferIdentifier(), IdentificationBit,
7554*0b57cec5SDimitry Andric                           ModuleBit});
7555*0b57cec5SDimitry Andric         continue;
7556*0b57cec5SDimitry Andric       }
7557*0b57cec5SDimitry Andric 
7558*0b57cec5SDimitry Andric       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
7559*0b57cec5SDimitry Andric         Expected<StringRef> Strtab =
7560*0b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
7561*0b57cec5SDimitry Andric         if (!Strtab)
7562*0b57cec5SDimitry Andric           return Strtab.takeError();
7563*0b57cec5SDimitry Andric         // This string table is used by every preceding bitcode module that does
7564*0b57cec5SDimitry Andric         // not have its own string table. A bitcode file may have multiple
7565*0b57cec5SDimitry Andric         // string tables if it was created by binary concatenation, for example
7566*0b57cec5SDimitry Andric         // with "llvm-cat -b".
75670eae32dcSDimitry Andric         for (BitcodeModule &I : llvm::reverse(F.Mods)) {
75680eae32dcSDimitry Andric           if (!I.Strtab.empty())
7569*0b57cec5SDimitry Andric             break;
75700eae32dcSDimitry Andric           I.Strtab = *Strtab;
7571*0b57cec5SDimitry Andric         }
7572*0b57cec5SDimitry Andric         // Similarly, the string table is used by every preceding symbol table;
7573*0b57cec5SDimitry Andric         // normally there will be just one unless the bitcode file was created
7574*0b57cec5SDimitry Andric         // by binary concatenation.
7575*0b57cec5SDimitry Andric         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
7576*0b57cec5SDimitry Andric           F.StrtabForSymtab = *Strtab;
7577*0b57cec5SDimitry Andric         continue;
7578*0b57cec5SDimitry Andric       }
7579*0b57cec5SDimitry Andric 
7580*0b57cec5SDimitry Andric       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
7581*0b57cec5SDimitry Andric         Expected<StringRef> SymtabOrErr =
7582*0b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
7583*0b57cec5SDimitry Andric         if (!SymtabOrErr)
7584*0b57cec5SDimitry Andric           return SymtabOrErr.takeError();
7585*0b57cec5SDimitry Andric 
7586*0b57cec5SDimitry Andric         // We can expect the bitcode file to have multiple symbol tables if it
7587*0b57cec5SDimitry Andric         // was created by binary concatenation. In that case we silently
7588*0b57cec5SDimitry Andric         // ignore any subsequent symbol tables, which is fine because this is a
7589*0b57cec5SDimitry Andric         // low level function. The client is expected to notice that the number
7590*0b57cec5SDimitry Andric         // of modules in the symbol table does not match the number of modules
7591*0b57cec5SDimitry Andric         // in the input file and regenerate the symbol table.
7592*0b57cec5SDimitry Andric         if (F.Symtab.empty())
7593*0b57cec5SDimitry Andric           F.Symtab = *SymtabOrErr;
7594*0b57cec5SDimitry Andric         continue;
7595*0b57cec5SDimitry Andric       }
7596*0b57cec5SDimitry Andric 
7597*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
7598*0b57cec5SDimitry Andric         return std::move(Err);
7599*0b57cec5SDimitry Andric       continue;
7600*0b57cec5SDimitry Andric     }
7601*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
7602349cc55cSDimitry Andric       if (Error E = Stream.skipRecord(Entry.ID).takeError())
7603349cc55cSDimitry Andric         return std::move(E);
7604*0b57cec5SDimitry Andric       continue;
7605*0b57cec5SDimitry Andric     }
7606*0b57cec5SDimitry Andric   }
7607*0b57cec5SDimitry Andric }
7608*0b57cec5SDimitry Andric 
7609*0b57cec5SDimitry Andric /// Get a lazy one-at-time loading module from bitcode.
7610*0b57cec5SDimitry Andric ///
7611*0b57cec5SDimitry Andric /// This isn't always used in a lazy context.  In particular, it's also used by
7612*0b57cec5SDimitry Andric /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
7613*0b57cec5SDimitry Andric /// in forward-referenced functions from block address references.
7614*0b57cec5SDimitry Andric ///
7615*0b57cec5SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize
7616*0b57cec5SDimitry Andric /// everything.
7617*0b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
7618*0b57cec5SDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
76195ffd83dbSDimitry Andric                              bool ShouldLazyLoadMetadata, bool IsImporting,
76205ffd83dbSDimitry Andric                              DataLayoutCallbackTy DataLayoutCallback) {
7621*0b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
7622*0b57cec5SDimitry Andric 
7623*0b57cec5SDimitry Andric   std::string ProducerIdentification;
7624*0b57cec5SDimitry Andric   if (IdentificationBit != -1ull) {
7625*0b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
7626*0b57cec5SDimitry Andric       return std::move(JumpFailed);
7627349cc55cSDimitry Andric     if (Error E =
7628349cc55cSDimitry Andric             readIdentificationBlock(Stream).moveInto(ProducerIdentification))
7629349cc55cSDimitry Andric       return std::move(E);
7630*0b57cec5SDimitry Andric   }
7631*0b57cec5SDimitry Andric 
7632*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7633*0b57cec5SDimitry Andric     return std::move(JumpFailed);
7634*0b57cec5SDimitry Andric   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
7635*0b57cec5SDimitry Andric                               Context);
7636*0b57cec5SDimitry Andric 
7637*0b57cec5SDimitry Andric   std::unique_ptr<Module> M =
76388bcb0991SDimitry Andric       std::make_unique<Module>(ModuleIdentifier, Context);
7639*0b57cec5SDimitry Andric   M->setMaterializer(R);
7640*0b57cec5SDimitry Andric 
7641*0b57cec5SDimitry Andric   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
76425ffd83dbSDimitry Andric   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
76435ffd83dbSDimitry Andric                                       IsImporting, DataLayoutCallback))
7644*0b57cec5SDimitry Andric     return std::move(Err);
7645*0b57cec5SDimitry Andric 
7646*0b57cec5SDimitry Andric   if (MaterializeAll) {
7647*0b57cec5SDimitry Andric     // Read in the entire module, and destroy the BitcodeReader.
7648*0b57cec5SDimitry Andric     if (Error Err = M->materializeAll())
7649*0b57cec5SDimitry Andric       return std::move(Err);
7650*0b57cec5SDimitry Andric   } else {
7651*0b57cec5SDimitry Andric     // Resolve forward references from blockaddresses.
7652*0b57cec5SDimitry Andric     if (Error Err = R->materializeForwardReferencedFunctions())
7653*0b57cec5SDimitry Andric       return std::move(Err);
7654*0b57cec5SDimitry Andric   }
7655*0b57cec5SDimitry Andric   return std::move(M);
7656*0b57cec5SDimitry Andric }
7657*0b57cec5SDimitry Andric 
7658*0b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
7659*0b57cec5SDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
7660*0b57cec5SDimitry Andric                              bool IsImporting) {
76615ffd83dbSDimitry Andric   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
76625ffd83dbSDimitry Andric                        [](StringRef) { return None; });
7663*0b57cec5SDimitry Andric }
7664*0b57cec5SDimitry Andric 
7665*0b57cec5SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex.
7666*0b57cec5SDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the
7667*0b57cec5SDimitry Andric // module path used in the combined summary (e.g. when reading summaries for
7668*0b57cec5SDimitry Andric // regular LTO modules).
7669*0b57cec5SDimitry Andric Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
7670*0b57cec5SDimitry Andric                                  StringRef ModulePath, uint64_t ModuleId) {
7671*0b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
7672*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7673*0b57cec5SDimitry Andric     return JumpFailed;
7674*0b57cec5SDimitry Andric 
7675*0b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
7676*0b57cec5SDimitry Andric                                     ModulePath, ModuleId);
7677*0b57cec5SDimitry Andric   return R.parseModule();
7678*0b57cec5SDimitry Andric }
7679*0b57cec5SDimitry Andric 
7680*0b57cec5SDimitry Andric // Parse the specified bitcode buffer, returning the function info index.
7681*0b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
7682*0b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
7683*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7684*0b57cec5SDimitry Andric     return std::move(JumpFailed);
7685*0b57cec5SDimitry Andric 
76868bcb0991SDimitry Andric   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
7687*0b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
7688*0b57cec5SDimitry Andric                                     ModuleIdentifier, 0);
7689*0b57cec5SDimitry Andric 
7690*0b57cec5SDimitry Andric   if (Error Err = R.parseModule())
7691*0b57cec5SDimitry Andric     return std::move(Err);
7692*0b57cec5SDimitry Andric 
7693*0b57cec5SDimitry Andric   return std::move(Index);
7694*0b57cec5SDimitry Andric }
7695*0b57cec5SDimitry Andric 
7696*0b57cec5SDimitry Andric static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
7697*0b57cec5SDimitry Andric                                                 unsigned ID) {
7698*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
7699*0b57cec5SDimitry Andric     return std::move(Err);
7700*0b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
7701*0b57cec5SDimitry Andric 
7702*0b57cec5SDimitry Andric   while (true) {
7703349cc55cSDimitry Andric     BitstreamEntry Entry;
7704349cc55cSDimitry Andric     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
7705349cc55cSDimitry Andric       return std::move(E);
7706*0b57cec5SDimitry Andric 
7707*0b57cec5SDimitry Andric     switch (Entry.Kind) {
7708*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
7709*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
7710*0b57cec5SDimitry Andric       return error("Malformed block");
7711*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
7712*0b57cec5SDimitry Andric       // If no flags record found, conservatively return true to mimic
7713*0b57cec5SDimitry Andric       // behavior before this flag was added.
7714*0b57cec5SDimitry Andric       return true;
7715*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
7716*0b57cec5SDimitry Andric       // The interesting case.
7717*0b57cec5SDimitry Andric       break;
7718*0b57cec5SDimitry Andric     }
7719*0b57cec5SDimitry Andric 
7720*0b57cec5SDimitry Andric     // Look for the FS_FLAGS record.
7721*0b57cec5SDimitry Andric     Record.clear();
7722*0b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7723*0b57cec5SDimitry Andric     if (!MaybeBitCode)
7724*0b57cec5SDimitry Andric       return MaybeBitCode.takeError();
7725*0b57cec5SDimitry Andric     switch (MaybeBitCode.get()) {
7726*0b57cec5SDimitry Andric     default: // Default behavior: ignore.
7727*0b57cec5SDimitry Andric       break;
7728*0b57cec5SDimitry Andric     case bitc::FS_FLAGS: { // [flags]
7729*0b57cec5SDimitry Andric       uint64_t Flags = Record[0];
7730*0b57cec5SDimitry Andric       // Scan flags.
7731fe6060f1SDimitry Andric       assert(Flags <= 0x7f && "Unexpected bits in flag");
7732*0b57cec5SDimitry Andric 
7733*0b57cec5SDimitry Andric       return Flags & 0x8;
7734*0b57cec5SDimitry Andric     }
7735*0b57cec5SDimitry Andric     }
7736*0b57cec5SDimitry Andric   }
7737*0b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
7738*0b57cec5SDimitry Andric }
7739*0b57cec5SDimitry Andric 
7740*0b57cec5SDimitry Andric // Check if the given bitcode buffer contains a global value summary block.
7741*0b57cec5SDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
7742*0b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
7743*0b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7744*0b57cec5SDimitry Andric     return std::move(JumpFailed);
7745*0b57cec5SDimitry Andric 
7746*0b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
7747*0b57cec5SDimitry Andric     return std::move(Err);
7748*0b57cec5SDimitry Andric 
7749*0b57cec5SDimitry Andric   while (true) {
7750349cc55cSDimitry Andric     llvm::BitstreamEntry Entry;
7751349cc55cSDimitry Andric     if (Error E = Stream.advance().moveInto(Entry))
7752349cc55cSDimitry Andric       return std::move(E);
7753*0b57cec5SDimitry Andric 
7754*0b57cec5SDimitry Andric     switch (Entry.Kind) {
7755*0b57cec5SDimitry Andric     case BitstreamEntry::Error:
7756*0b57cec5SDimitry Andric       return error("Malformed block");
7757*0b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
7758*0b57cec5SDimitry Andric       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
7759*0b57cec5SDimitry Andric                             /*EnableSplitLTOUnit=*/false};
7760*0b57cec5SDimitry Andric 
7761*0b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
7762*0b57cec5SDimitry Andric       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
7763*0b57cec5SDimitry Andric         Expected<bool> EnableSplitLTOUnit =
7764*0b57cec5SDimitry Andric             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
7765*0b57cec5SDimitry Andric         if (!EnableSplitLTOUnit)
7766*0b57cec5SDimitry Andric           return EnableSplitLTOUnit.takeError();
7767*0b57cec5SDimitry Andric         return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
7768*0b57cec5SDimitry Andric                               *EnableSplitLTOUnit};
7769*0b57cec5SDimitry Andric       }
7770*0b57cec5SDimitry Andric 
7771*0b57cec5SDimitry Andric       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
7772*0b57cec5SDimitry Andric         Expected<bool> EnableSplitLTOUnit =
7773*0b57cec5SDimitry Andric             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
7774*0b57cec5SDimitry Andric         if (!EnableSplitLTOUnit)
7775*0b57cec5SDimitry Andric           return EnableSplitLTOUnit.takeError();
7776*0b57cec5SDimitry Andric         return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
7777*0b57cec5SDimitry Andric                               *EnableSplitLTOUnit};
7778*0b57cec5SDimitry Andric       }
7779*0b57cec5SDimitry Andric 
7780*0b57cec5SDimitry Andric       // Ignore other sub-blocks.
7781*0b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
7782*0b57cec5SDimitry Andric         return std::move(Err);
7783*0b57cec5SDimitry Andric       continue;
7784*0b57cec5SDimitry Andric 
7785*0b57cec5SDimitry Andric     case BitstreamEntry::Record:
7786*0b57cec5SDimitry Andric       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
7787*0b57cec5SDimitry Andric         continue;
7788*0b57cec5SDimitry Andric       else
7789*0b57cec5SDimitry Andric         return StreamFailed.takeError();
7790*0b57cec5SDimitry Andric     }
7791*0b57cec5SDimitry Andric   }
7792*0b57cec5SDimitry Andric }
7793*0b57cec5SDimitry Andric 
7794*0b57cec5SDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
7795*0b57cec5SDimitry Andric   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
7796*0b57cec5SDimitry Andric   if (!MsOrErr)
7797*0b57cec5SDimitry Andric     return MsOrErr.takeError();
7798*0b57cec5SDimitry Andric 
7799*0b57cec5SDimitry Andric   if (MsOrErr->size() != 1)
7800*0b57cec5SDimitry Andric     return error("Expected a single module");
7801*0b57cec5SDimitry Andric 
7802*0b57cec5SDimitry Andric   return (*MsOrErr)[0];
7803*0b57cec5SDimitry Andric }
7804*0b57cec5SDimitry Andric 
7805*0b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
7806*0b57cec5SDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
7807*0b57cec5SDimitry Andric                            bool ShouldLazyLoadMetadata, bool IsImporting) {
7808*0b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7809*0b57cec5SDimitry Andric   if (!BM)
7810*0b57cec5SDimitry Andric     return BM.takeError();
7811*0b57cec5SDimitry Andric 
7812*0b57cec5SDimitry Andric   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
7813*0b57cec5SDimitry Andric }
7814*0b57cec5SDimitry Andric 
7815*0b57cec5SDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
7816*0b57cec5SDimitry Andric     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
7817*0b57cec5SDimitry Andric     bool ShouldLazyLoadMetadata, bool IsImporting) {
7818*0b57cec5SDimitry Andric   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
7819*0b57cec5SDimitry Andric                                      IsImporting);
7820*0b57cec5SDimitry Andric   if (MOrErr)
7821*0b57cec5SDimitry Andric     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
7822*0b57cec5SDimitry Andric   return MOrErr;
7823*0b57cec5SDimitry Andric }
7824*0b57cec5SDimitry Andric 
7825*0b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
78265ffd83dbSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context,
78275ffd83dbSDimitry Andric                            DataLayoutCallbackTy DataLayoutCallback) {
78285ffd83dbSDimitry Andric   return getModuleImpl(Context, true, false, false, DataLayoutCallback);
7829*0b57cec5SDimitry Andric   // TODO: Restore the use-lists to the in-memory state when the bitcode was
7830*0b57cec5SDimitry Andric   // written.  We must defer until the Module has been fully materialized.
7831*0b57cec5SDimitry Andric }
7832*0b57cec5SDimitry Andric 
78335ffd83dbSDimitry Andric Expected<std::unique_ptr<Module>>
78345ffd83dbSDimitry Andric llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
78355ffd83dbSDimitry Andric                        DataLayoutCallbackTy DataLayoutCallback) {
7836*0b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7837*0b57cec5SDimitry Andric   if (!BM)
7838*0b57cec5SDimitry Andric     return BM.takeError();
7839*0b57cec5SDimitry Andric 
78405ffd83dbSDimitry Andric   return BM->parseModule(Context, DataLayoutCallback);
7841*0b57cec5SDimitry Andric }
7842*0b57cec5SDimitry Andric 
7843*0b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
7844*0b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7845*0b57cec5SDimitry Andric   if (!StreamOrErr)
7846*0b57cec5SDimitry Andric     return StreamOrErr.takeError();
7847*0b57cec5SDimitry Andric 
7848*0b57cec5SDimitry Andric   return readTriple(*StreamOrErr);
7849*0b57cec5SDimitry Andric }
7850*0b57cec5SDimitry Andric 
7851*0b57cec5SDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
7852*0b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7853*0b57cec5SDimitry Andric   if (!StreamOrErr)
7854*0b57cec5SDimitry Andric     return StreamOrErr.takeError();
7855*0b57cec5SDimitry Andric 
7856*0b57cec5SDimitry Andric   return hasObjCCategory(*StreamOrErr);
7857*0b57cec5SDimitry Andric }
7858*0b57cec5SDimitry Andric 
7859*0b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
7860*0b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7861*0b57cec5SDimitry Andric   if (!StreamOrErr)
7862*0b57cec5SDimitry Andric     return StreamOrErr.takeError();
7863*0b57cec5SDimitry Andric 
7864*0b57cec5SDimitry Andric   return readIdentificationCode(*StreamOrErr);
7865*0b57cec5SDimitry Andric }
7866*0b57cec5SDimitry Andric 
7867*0b57cec5SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
7868*0b57cec5SDimitry Andric                                    ModuleSummaryIndex &CombinedIndex,
7869*0b57cec5SDimitry Andric                                    uint64_t ModuleId) {
7870*0b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7871*0b57cec5SDimitry Andric   if (!BM)
7872*0b57cec5SDimitry Andric     return BM.takeError();
7873*0b57cec5SDimitry Andric 
7874*0b57cec5SDimitry Andric   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
7875*0b57cec5SDimitry Andric }
7876*0b57cec5SDimitry Andric 
7877*0b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
7878*0b57cec5SDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
7879*0b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7880*0b57cec5SDimitry Andric   if (!BM)
7881*0b57cec5SDimitry Andric     return BM.takeError();
7882*0b57cec5SDimitry Andric 
7883*0b57cec5SDimitry Andric   return BM->getSummary();
7884*0b57cec5SDimitry Andric }
7885*0b57cec5SDimitry Andric 
7886*0b57cec5SDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
7887*0b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7888*0b57cec5SDimitry Andric   if (!BM)
7889*0b57cec5SDimitry Andric     return BM.takeError();
7890*0b57cec5SDimitry Andric 
7891*0b57cec5SDimitry Andric   return BM->getLTOInfo();
7892*0b57cec5SDimitry Andric }
7893*0b57cec5SDimitry Andric 
7894*0b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
7895*0b57cec5SDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path,
7896*0b57cec5SDimitry Andric                                    bool IgnoreEmptyThinLTOIndexFile) {
7897*0b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
7898*0b57cec5SDimitry Andric       MemoryBuffer::getFileOrSTDIN(Path);
7899*0b57cec5SDimitry Andric   if (!FileOrErr)
7900*0b57cec5SDimitry Andric     return errorCodeToError(FileOrErr.getError());
7901*0b57cec5SDimitry Andric   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
7902*0b57cec5SDimitry Andric     return nullptr;
7903*0b57cec5SDimitry Andric   return getModuleSummaryIndex(**FileOrErr);
7904*0b57cec5SDimitry Andric }
7905