1f22ef01cSRoman Divacky //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky 
10d88c1a5aSDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
11d88c1a5aSDimitry Andric #include "MetadataLoader.h"
12d88c1a5aSDimitry Andric #include "ValueList.h"
13d88c1a5aSDimitry Andric 
14d88c1a5aSDimitry Andric #include "llvm/ADT/APFloat.h"
15d88c1a5aSDimitry Andric #include "llvm/ADT/APInt.h"
16d88c1a5aSDimitry Andric #include "llvm/ADT/ArrayRef.h"
17d88c1a5aSDimitry Andric #include "llvm/ADT/DenseMap.h"
18d88c1a5aSDimitry Andric #include "llvm/ADT/None.h"
19ff0cc061SDimitry Andric #include "llvm/ADT/STLExtras.h"
20f22ef01cSRoman Divacky #include "llvm/ADT/SmallString.h"
21f22ef01cSRoman Divacky #include "llvm/ADT/SmallVector.h"
22d88c1a5aSDimitry Andric #include "llvm/ADT/StringRef.h"
23ff0cc061SDimitry Andric #include "llvm/ADT/Triple.h"
24d88c1a5aSDimitry Andric #include "llvm/ADT/Twine.h"
25ff0cc061SDimitry Andric #include "llvm/Bitcode/BitstreamReader.h"
26f785676fSDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
27d88c1a5aSDimitry Andric #include "llvm/IR/Argument.h"
28d88c1a5aSDimitry Andric #include "llvm/IR/Attributes.h"
2991bc56edSDimitry Andric #include "llvm/IR/AutoUpgrade.h"
30d88c1a5aSDimitry Andric #include "llvm/IR/BasicBlock.h"
31d88c1a5aSDimitry Andric #include "llvm/IR/CallingConv.h"
323ca95b02SDimitry Andric #include "llvm/IR/CallSite.h"
33d88c1a5aSDimitry Andric #include "llvm/IR/Comdat.h"
34d88c1a5aSDimitry Andric #include "llvm/IR/Constant.h"
35139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
36ff0cc061SDimitry Andric #include "llvm/IR/DebugInfo.h"
37ff0cc061SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
38d88c1a5aSDimitry Andric #include "llvm/IR/DebugLoc.h"
39139f7f9bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
40d88c1a5aSDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
4139d628a0SDimitry Andric #include "llvm/IR/DiagnosticPrinter.h"
42d88c1a5aSDimitry Andric #include "llvm/IR/Function.h"
43d88c1a5aSDimitry Andric #include "llvm/IR/GlobalAlias.h"
44d88c1a5aSDimitry Andric #include "llvm/IR/GlobalIFunc.h"
45d88c1a5aSDimitry Andric #include "llvm/IR/GlobalIndirectSymbol.h"
46d88c1a5aSDimitry Andric #include "llvm/IR/GlobalObject.h"
47d88c1a5aSDimitry Andric #include "llvm/IR/GlobalValue.h"
48d88c1a5aSDimitry Andric #include "llvm/IR/GlobalVariable.h"
49ff0cc061SDimitry Andric #include "llvm/IR/GVMaterializer.h"
50139f7f9bSDimitry Andric #include "llvm/IR/InlineAsm.h"
51d88c1a5aSDimitry Andric #include "llvm/IR/InstIterator.h"
52d88c1a5aSDimitry Andric #include "llvm/IR/InstrTypes.h"
53d88c1a5aSDimitry Andric #include "llvm/IR/Instruction.h"
54d88c1a5aSDimitry Andric #include "llvm/IR/Instructions.h"
55d88c1a5aSDimitry Andric #include "llvm/IR/Intrinsics.h"
56f785676fSDimitry Andric #include "llvm/IR/LLVMContext.h"
57139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
583ca95b02SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
59139f7f9bSDimitry Andric #include "llvm/IR/OperandTraits.h"
60139f7f9bSDimitry Andric #include "llvm/IR/Operator.h"
61d88c1a5aSDimitry Andric #include "llvm/IR/TrackingMDRef.h"
62d88c1a5aSDimitry Andric #include "llvm/IR/Type.h"
63ff0cc061SDimitry Andric #include "llvm/IR/ValueHandle.h"
64d88c1a5aSDimitry Andric #include "llvm/IR/Verifier.h"
65d88c1a5aSDimitry Andric #include "llvm/Support/AtomicOrdering.h"
66d88c1a5aSDimitry Andric #include "llvm/Support/Casting.h"
673ca95b02SDimitry Andric #include "llvm/Support/CommandLine.h"
68d88c1a5aSDimitry Andric #include "llvm/Support/Compiler.h"
693ca95b02SDimitry Andric #include "llvm/Support/Debug.h"
70d88c1a5aSDimitry Andric #include "llvm/Support/Error.h"
71d88c1a5aSDimitry Andric #include "llvm/Support/ErrorHandling.h"
7239d628a0SDimitry Andric #include "llvm/Support/ManagedStatic.h"
73f22ef01cSRoman Divacky #include "llvm/Support/MemoryBuffer.h"
74f785676fSDimitry Andric #include "llvm/Support/raw_ostream.h"
75d88c1a5aSDimitry Andric #include <algorithm>
76d88c1a5aSDimitry Andric #include <cassert>
77d88c1a5aSDimitry Andric #include <cstddef>
78d88c1a5aSDimitry Andric #include <cstdint>
79ff0cc061SDimitry Andric #include <deque>
80d88c1a5aSDimitry Andric #include <limits>
81d88c1a5aSDimitry Andric #include <map>
82d88c1a5aSDimitry Andric #include <memory>
83d88c1a5aSDimitry Andric #include <string>
84d88c1a5aSDimitry Andric #include <system_error>
85d88c1a5aSDimitry Andric #include <tuple>
863ca95b02SDimitry Andric #include <utility>
87d88c1a5aSDimitry Andric #include <vector>
883ca95b02SDimitry Andric 
89f22ef01cSRoman Divacky using namespace llvm;
90f22ef01cSRoman Divacky 
913ca95b02SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs(
923ca95b02SDimitry Andric     "print-summary-global-ids", cl::init(false), cl::Hidden,
933ca95b02SDimitry Andric     cl::desc(
943ca95b02SDimitry Andric         "Print the global id for each value when reading the module summary"));
953ca95b02SDimitry Andric 
96ff0cc061SDimitry Andric namespace {
97d88c1a5aSDimitry Andric 
987ae0e2c9SDimitry Andric enum {
997ae0e2c9SDimitry Andric   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
1007ae0e2c9SDimitry Andric };
1017ae0e2c9SDimitry Andric 
102d88c1a5aSDimitry Andric Error error(const Twine &Message) {
103d88c1a5aSDimitry Andric   return make_error<StringError>(
104d88c1a5aSDimitry Andric       Message, make_error_code(BitcodeError::CorruptedBitcode));
105ff0cc061SDimitry Andric }
106ff0cc061SDimitry Andric 
107d88c1a5aSDimitry Andric /// Helper to read the header common to all bitcode files.
108d88c1a5aSDimitry Andric bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
109d88c1a5aSDimitry Andric   // Sniff for the signature.
110d88c1a5aSDimitry Andric   if (!Stream.canSkipToPos(4) ||
111d88c1a5aSDimitry Andric       Stream.Read(8) != 'B' ||
112d88c1a5aSDimitry Andric       Stream.Read(8) != 'C' ||
113d88c1a5aSDimitry Andric       Stream.Read(4) != 0x0 ||
114d88c1a5aSDimitry Andric       Stream.Read(4) != 0xC ||
115d88c1a5aSDimitry Andric       Stream.Read(4) != 0xE ||
116d88c1a5aSDimitry Andric       Stream.Read(4) != 0xD)
117d88c1a5aSDimitry Andric     return false;
118d88c1a5aSDimitry Andric   return true;
119ff0cc061SDimitry Andric }
120ff0cc061SDimitry Andric 
121d88c1a5aSDimitry Andric Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
122d88c1a5aSDimitry Andric   const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
123d88c1a5aSDimitry Andric   const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
124d88c1a5aSDimitry Andric 
125d88c1a5aSDimitry Andric   if (Buffer.getBufferSize() & 3)
126d88c1a5aSDimitry Andric     return error("Invalid bitcode signature");
127d88c1a5aSDimitry Andric 
128d88c1a5aSDimitry Andric   // If we have a wrapper header, parse it and ignore the non-bc file contents.
129d88c1a5aSDimitry Andric   // The magic number is 0x0B17C0DE stored in little endian.
130d88c1a5aSDimitry Andric   if (isBitcodeWrapper(BufPtr, BufEnd))
131d88c1a5aSDimitry Andric     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
132d88c1a5aSDimitry Andric       return error("Invalid bitcode wrapper header");
133d88c1a5aSDimitry Andric 
134d88c1a5aSDimitry Andric   BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
135d88c1a5aSDimitry Andric   if (!hasValidBitcodeHeader(Stream))
136d88c1a5aSDimitry Andric     return error("Invalid bitcode signature");
137d88c1a5aSDimitry Andric 
138d88c1a5aSDimitry Andric   return std::move(Stream);
139ff0cc061SDimitry Andric }
140ff0cc061SDimitry Andric 
141d88c1a5aSDimitry Andric /// Convert a string from a record into an std::string, return true on failure.
142d88c1a5aSDimitry Andric template <typename StrTy>
143d88c1a5aSDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
144d88c1a5aSDimitry Andric                             StrTy &Result) {
145d88c1a5aSDimitry Andric   if (Idx > Record.size())
146d88c1a5aSDimitry Andric     return true;
147d88c1a5aSDimitry Andric 
148d88c1a5aSDimitry Andric   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
149d88c1a5aSDimitry Andric     Result += (char)Record[i];
150d88c1a5aSDimitry Andric   return false;
151ff0cc061SDimitry Andric }
152ff0cc061SDimitry Andric 
153d88c1a5aSDimitry Andric // Strip all the TBAA attachment for the module.
154d88c1a5aSDimitry Andric void stripTBAA(Module *M) {
155d88c1a5aSDimitry Andric   for (auto &F : *M) {
156d88c1a5aSDimitry Andric     if (F.isMaterializable())
157d88c1a5aSDimitry Andric       continue;
158d88c1a5aSDimitry Andric     for (auto &I : instructions(F))
159d88c1a5aSDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, nullptr);
160d88c1a5aSDimitry Andric   }
161d88c1a5aSDimitry Andric }
162ff0cc061SDimitry Andric 
163d88c1a5aSDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
164d88c1a5aSDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any.
165d88c1a5aSDimitry Andric Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
166d88c1a5aSDimitry Andric   if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
167d88c1a5aSDimitry Andric     return error("Invalid record");
168ff0cc061SDimitry Andric 
169d88c1a5aSDimitry Andric   // Read all the records.
170d88c1a5aSDimitry Andric   SmallVector<uint64_t, 64> Record;
171d88c1a5aSDimitry Andric 
172d88c1a5aSDimitry Andric   std::string ProducerIdentification;
173d88c1a5aSDimitry Andric 
174d88c1a5aSDimitry Andric   while (true) {
175d88c1a5aSDimitry Andric     BitstreamEntry Entry = Stream.advance();
176d88c1a5aSDimitry Andric 
177d88c1a5aSDimitry Andric     switch (Entry.Kind) {
178d88c1a5aSDimitry Andric     default:
179d88c1a5aSDimitry Andric     case BitstreamEntry::Error:
180d88c1a5aSDimitry Andric       return error("Malformed block");
181d88c1a5aSDimitry Andric     case BitstreamEntry::EndBlock:
182d88c1a5aSDimitry Andric       return ProducerIdentification;
183d88c1a5aSDimitry Andric     case BitstreamEntry::Record:
184d88c1a5aSDimitry Andric       // The interesting case.
185d88c1a5aSDimitry Andric       break;
186d88c1a5aSDimitry Andric     }
187d88c1a5aSDimitry Andric 
188d88c1a5aSDimitry Andric     // Read a record.
189d88c1a5aSDimitry Andric     Record.clear();
190d88c1a5aSDimitry Andric     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
191d88c1a5aSDimitry Andric     switch (BitCode) {
192d88c1a5aSDimitry Andric     default: // Default behavior: reject
193d88c1a5aSDimitry Andric       return error("Invalid value");
194d88c1a5aSDimitry Andric     case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
195d88c1a5aSDimitry Andric       convertToString(Record, 0, ProducerIdentification);
196d88c1a5aSDimitry Andric       break;
197d88c1a5aSDimitry Andric     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
198d88c1a5aSDimitry Andric       unsigned epoch = (unsigned)Record[0];
199d88c1a5aSDimitry Andric       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
200d88c1a5aSDimitry Andric         return error(
201d88c1a5aSDimitry Andric           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
202d88c1a5aSDimitry Andric           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
203d88c1a5aSDimitry Andric       }
204d88c1a5aSDimitry Andric     }
205d88c1a5aSDimitry Andric     }
206d88c1a5aSDimitry Andric   }
207d88c1a5aSDimitry Andric }
208d88c1a5aSDimitry Andric 
209d88c1a5aSDimitry Andric Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
210d88c1a5aSDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
211d88c1a5aSDimitry Andric   // need to understand them all.
212d88c1a5aSDimitry Andric   while (true) {
213d88c1a5aSDimitry Andric     if (Stream.AtEndOfStream())
214d88c1a5aSDimitry Andric       return "";
215d88c1a5aSDimitry Andric 
216d88c1a5aSDimitry Andric     BitstreamEntry Entry = Stream.advance();
217d88c1a5aSDimitry Andric     switch (Entry.Kind) {
218d88c1a5aSDimitry Andric     case BitstreamEntry::EndBlock:
219d88c1a5aSDimitry Andric     case BitstreamEntry::Error:
220d88c1a5aSDimitry Andric       return error("Malformed block");
221d88c1a5aSDimitry Andric 
222d88c1a5aSDimitry Andric     case BitstreamEntry::SubBlock:
223d88c1a5aSDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
224d88c1a5aSDimitry Andric         return readIdentificationBlock(Stream);
225d88c1a5aSDimitry Andric 
226d88c1a5aSDimitry Andric       // Ignore other sub-blocks.
227d88c1a5aSDimitry Andric       if (Stream.SkipBlock())
228d88c1a5aSDimitry Andric         return error("Malformed block");
229d88c1a5aSDimitry Andric       continue;
230d88c1a5aSDimitry Andric     case BitstreamEntry::Record:
231d88c1a5aSDimitry Andric       Stream.skipRecord(Entry.ID);
232d88c1a5aSDimitry Andric       continue;
233d88c1a5aSDimitry Andric     }
234d88c1a5aSDimitry Andric   }
235d88c1a5aSDimitry Andric }
236d88c1a5aSDimitry Andric 
237d88c1a5aSDimitry Andric Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
238d88c1a5aSDimitry Andric   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
239d88c1a5aSDimitry Andric     return error("Invalid record");
240d88c1a5aSDimitry Andric 
241d88c1a5aSDimitry Andric   SmallVector<uint64_t, 64> Record;
242d88c1a5aSDimitry Andric   // Read all the records for this module.
243d88c1a5aSDimitry Andric 
244d88c1a5aSDimitry Andric   while (true) {
245d88c1a5aSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
246d88c1a5aSDimitry Andric 
247d88c1a5aSDimitry Andric     switch (Entry.Kind) {
248d88c1a5aSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
249d88c1a5aSDimitry Andric     case BitstreamEntry::Error:
250d88c1a5aSDimitry Andric       return error("Malformed block");
251d88c1a5aSDimitry Andric     case BitstreamEntry::EndBlock:
252d88c1a5aSDimitry Andric       return false;
253d88c1a5aSDimitry Andric     case BitstreamEntry::Record:
254d88c1a5aSDimitry Andric       // The interesting case.
255d88c1a5aSDimitry Andric       break;
256d88c1a5aSDimitry Andric     }
257d88c1a5aSDimitry Andric 
258d88c1a5aSDimitry Andric     // Read a record.
259d88c1a5aSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
260d88c1a5aSDimitry Andric     default:
261d88c1a5aSDimitry Andric       break; // Default behavior, ignore unknown content.
262d88c1a5aSDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
263d88c1a5aSDimitry Andric       std::string S;
264d88c1a5aSDimitry Andric       if (convertToString(Record, 0, S))
265d88c1a5aSDimitry Andric         return error("Invalid record");
266d88c1a5aSDimitry Andric       // Check for the i386 and other (x86_64, ARM) conventions
267d88c1a5aSDimitry Andric       if (S.find("__DATA, __objc_catlist") != std::string::npos ||
268d88c1a5aSDimitry Andric           S.find("__OBJC,__category") != std::string::npos)
269d88c1a5aSDimitry Andric         return true;
270d88c1a5aSDimitry Andric       break;
271d88c1a5aSDimitry Andric     }
272d88c1a5aSDimitry Andric     }
273d88c1a5aSDimitry Andric     Record.clear();
274d88c1a5aSDimitry Andric   }
275d88c1a5aSDimitry Andric   llvm_unreachable("Exit infinite loop");
276d88c1a5aSDimitry Andric }
277d88c1a5aSDimitry Andric 
278d88c1a5aSDimitry Andric Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
279d88c1a5aSDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
280d88c1a5aSDimitry Andric   // need to understand them all.
281d88c1a5aSDimitry Andric   while (true) {
282d88c1a5aSDimitry Andric     BitstreamEntry Entry = Stream.advance();
283d88c1a5aSDimitry Andric 
284d88c1a5aSDimitry Andric     switch (Entry.Kind) {
285d88c1a5aSDimitry Andric     case BitstreamEntry::Error:
286d88c1a5aSDimitry Andric       return error("Malformed block");
287d88c1a5aSDimitry Andric     case BitstreamEntry::EndBlock:
288d88c1a5aSDimitry Andric       return false;
289d88c1a5aSDimitry Andric 
290d88c1a5aSDimitry Andric     case BitstreamEntry::SubBlock:
291d88c1a5aSDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
292d88c1a5aSDimitry Andric         return hasObjCCategoryInModule(Stream);
293d88c1a5aSDimitry Andric 
294d88c1a5aSDimitry Andric       // Ignore other sub-blocks.
295d88c1a5aSDimitry Andric       if (Stream.SkipBlock())
296d88c1a5aSDimitry Andric         return error("Malformed block");
297d88c1a5aSDimitry Andric       continue;
298d88c1a5aSDimitry Andric 
299d88c1a5aSDimitry Andric     case BitstreamEntry::Record:
300d88c1a5aSDimitry Andric       Stream.skipRecord(Entry.ID);
301d88c1a5aSDimitry Andric       continue;
302d88c1a5aSDimitry Andric     }
303d88c1a5aSDimitry Andric   }
304d88c1a5aSDimitry Andric }
305d88c1a5aSDimitry Andric 
306d88c1a5aSDimitry Andric Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
307d88c1a5aSDimitry Andric   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
308d88c1a5aSDimitry Andric     return error("Invalid record");
309d88c1a5aSDimitry Andric 
310d88c1a5aSDimitry Andric   SmallVector<uint64_t, 64> Record;
311d88c1a5aSDimitry Andric 
312d88c1a5aSDimitry Andric   std::string Triple;
313d88c1a5aSDimitry Andric 
314d88c1a5aSDimitry Andric   // Read all the records for this module.
315d88c1a5aSDimitry Andric   while (true) {
316d88c1a5aSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
317d88c1a5aSDimitry Andric 
318d88c1a5aSDimitry Andric     switch (Entry.Kind) {
319d88c1a5aSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
320d88c1a5aSDimitry Andric     case BitstreamEntry::Error:
321d88c1a5aSDimitry Andric       return error("Malformed block");
322d88c1a5aSDimitry Andric     case BitstreamEntry::EndBlock:
323d88c1a5aSDimitry Andric       return Triple;
324d88c1a5aSDimitry Andric     case BitstreamEntry::Record:
325d88c1a5aSDimitry Andric       // The interesting case.
326d88c1a5aSDimitry Andric       break;
327d88c1a5aSDimitry Andric     }
328d88c1a5aSDimitry Andric 
329d88c1a5aSDimitry Andric     // Read a record.
330d88c1a5aSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
331d88c1a5aSDimitry Andric     default: break;  // Default behavior, ignore unknown content.
332d88c1a5aSDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
333d88c1a5aSDimitry Andric       std::string S;
334d88c1a5aSDimitry Andric       if (convertToString(Record, 0, S))
335d88c1a5aSDimitry Andric         return error("Invalid record");
336d88c1a5aSDimitry Andric       Triple = S;
337d88c1a5aSDimitry Andric       break;
338d88c1a5aSDimitry Andric     }
339d88c1a5aSDimitry Andric     }
340d88c1a5aSDimitry Andric     Record.clear();
341d88c1a5aSDimitry Andric   }
342d88c1a5aSDimitry Andric   llvm_unreachable("Exit infinite loop");
343d88c1a5aSDimitry Andric }
344d88c1a5aSDimitry Andric 
345d88c1a5aSDimitry Andric Expected<std::string> readTriple(BitstreamCursor &Stream) {
346d88c1a5aSDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
347d88c1a5aSDimitry Andric   // need to understand them all.
348d88c1a5aSDimitry Andric   while (true) {
349d88c1a5aSDimitry Andric     BitstreamEntry Entry = Stream.advance();
350d88c1a5aSDimitry Andric 
351d88c1a5aSDimitry Andric     switch (Entry.Kind) {
352d88c1a5aSDimitry Andric     case BitstreamEntry::Error:
353d88c1a5aSDimitry Andric       return error("Malformed block");
354d88c1a5aSDimitry Andric     case BitstreamEntry::EndBlock:
355d88c1a5aSDimitry Andric       return "";
356d88c1a5aSDimitry Andric 
357d88c1a5aSDimitry Andric     case BitstreamEntry::SubBlock:
358d88c1a5aSDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
359d88c1a5aSDimitry Andric         return readModuleTriple(Stream);
360d88c1a5aSDimitry Andric 
361d88c1a5aSDimitry Andric       // Ignore other sub-blocks.
362d88c1a5aSDimitry Andric       if (Stream.SkipBlock())
363d88c1a5aSDimitry Andric         return error("Malformed block");
364d88c1a5aSDimitry Andric       continue;
365d88c1a5aSDimitry Andric 
366d88c1a5aSDimitry Andric     case BitstreamEntry::Record:
367d88c1a5aSDimitry Andric       Stream.skipRecord(Entry.ID);
368d88c1a5aSDimitry Andric       continue;
369d88c1a5aSDimitry Andric     }
370d88c1a5aSDimitry Andric   }
371d88c1a5aSDimitry Andric }
372d88c1a5aSDimitry Andric 
373d88c1a5aSDimitry Andric class BitcodeReaderBase {
374d88c1a5aSDimitry Andric protected:
375d88c1a5aSDimitry Andric   BitcodeReaderBase(BitstreamCursor Stream) : Stream(std::move(Stream)) {
376d88c1a5aSDimitry Andric     this->Stream.setBlockInfo(&BlockInfo);
377d88c1a5aSDimitry Andric   }
378d88c1a5aSDimitry Andric 
379d88c1a5aSDimitry Andric   BitstreamBlockInfo BlockInfo;
380d88c1a5aSDimitry Andric   BitstreamCursor Stream;
381d88c1a5aSDimitry Andric 
3827a7e6055SDimitry Andric   Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
3837a7e6055SDimitry Andric 
384d88c1a5aSDimitry Andric   bool readBlockInfo();
385d88c1a5aSDimitry Andric 
386d88c1a5aSDimitry Andric   // Contains an arbitrary and optional string identifying the bitcode producer
387d88c1a5aSDimitry Andric   std::string ProducerIdentification;
388d88c1a5aSDimitry Andric 
389d88c1a5aSDimitry Andric   Error error(const Twine &Message);
390ff0cc061SDimitry Andric };
391ff0cc061SDimitry Andric 
392d88c1a5aSDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) {
393d88c1a5aSDimitry Andric   std::string FullMsg = Message.str();
394d88c1a5aSDimitry Andric   if (!ProducerIdentification.empty())
395d88c1a5aSDimitry Andric     FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
396d88c1a5aSDimitry Andric                LLVM_VERSION_STRING "')";
397d88c1a5aSDimitry Andric   return ::error(FullMsg);
398ff0cc061SDimitry Andric }
399ff0cc061SDimitry Andric 
4007a7e6055SDimitry Andric Expected<unsigned>
4017a7e6055SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
4027a7e6055SDimitry Andric   if (Record.size() < 1)
4037a7e6055SDimitry Andric     return error("Invalid record");
4047a7e6055SDimitry Andric   unsigned ModuleVersion = Record[0];
4057a7e6055SDimitry Andric   if (ModuleVersion > 1)
4067a7e6055SDimitry Andric     return error("Invalid value");
4077a7e6055SDimitry Andric   return ModuleVersion;
4087a7e6055SDimitry Andric }
4097a7e6055SDimitry Andric 
410d88c1a5aSDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
411ff0cc061SDimitry Andric   LLVMContext &Context;
4128f0fd8f6SDimitry Andric   Module *TheModule = nullptr;
4137d523365SDimitry Andric   // Next offset to start scanning for lazy parsing of function bodies.
4148f0fd8f6SDimitry Andric   uint64_t NextUnreadBit = 0;
4157d523365SDimitry Andric   // Last function offset found in the VST.
4167d523365SDimitry Andric   uint64_t LastFunctionBlockBit = 0;
4178f0fd8f6SDimitry Andric   bool SeenValueSymbolTable = false;
4187d523365SDimitry Andric   uint64_t VSTOffset = 0;
419ff0cc061SDimitry Andric 
4207a7e6055SDimitry Andric   std::vector<std::string> SectionTable;
4217a7e6055SDimitry Andric   std::vector<std::string> GCTable;
4227a7e6055SDimitry Andric 
423ff0cc061SDimitry Andric   std::vector<Type*> TypeList;
424ff0cc061SDimitry Andric   BitcodeReaderValueList ValueList;
425d88c1a5aSDimitry Andric   Optional<MetadataLoader> MDLoader;
426ff0cc061SDimitry Andric   std::vector<Comdat *> ComdatList;
427ff0cc061SDimitry Andric   SmallVector<Instruction *, 64> InstructionList;
428ff0cc061SDimitry Andric 
429ff0cc061SDimitry Andric   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
4303ca95b02SDimitry Andric   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
431ff0cc061SDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
432ff0cc061SDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
4338f0fd8f6SDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
434ff0cc061SDimitry Andric 
4358f0fd8f6SDimitry Andric   /// The set of attributes by index.  Index zero in the file is for null, and
4368f0fd8f6SDimitry Andric   /// is thus not represented here.  As such all indices are off by one.
4377a7e6055SDimitry Andric   std::vector<AttributeList> MAttributes;
438ff0cc061SDimitry Andric 
4397d523365SDimitry Andric   /// The set of attribute groups.
4407a7e6055SDimitry Andric   std::map<unsigned, AttributeList> MAttributeGroups;
441ff0cc061SDimitry Andric 
4428f0fd8f6SDimitry Andric   /// While parsing a function body, this is a list of the basic blocks for the
4438f0fd8f6SDimitry Andric   /// function.
444ff0cc061SDimitry Andric   std::vector<BasicBlock*> FunctionBBs;
445ff0cc061SDimitry Andric 
446ff0cc061SDimitry Andric   // When reading the module header, this list is populated with functions that
447ff0cc061SDimitry Andric   // have bodies later in the file.
448ff0cc061SDimitry Andric   std::vector<Function*> FunctionsWithBodies;
449ff0cc061SDimitry Andric 
450ff0cc061SDimitry Andric   // When intrinsic functions are encountered which require upgrading they are
451ff0cc061SDimitry Andric   // stored here with their replacement function.
4523ca95b02SDimitry Andric   typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
4533ca95b02SDimitry Andric   UpdatedIntrinsicMap UpgradedIntrinsics;
4543ca95b02SDimitry Andric   // Intrinsics which were remangled because of types rename
4553ca95b02SDimitry Andric   UpdatedIntrinsicMap RemangledIntrinsics;
456ff0cc061SDimitry Andric 
457ff0cc061SDimitry Andric   // Several operations happen after the module header has been read, but
458ff0cc061SDimitry Andric   // before function bodies are processed. This keeps track of whether
459ff0cc061SDimitry Andric   // we've done this yet.
4608f0fd8f6SDimitry Andric   bool SeenFirstFunctionBody = false;
461ff0cc061SDimitry Andric 
4628f0fd8f6SDimitry Andric   /// When function bodies are initially scanned, this map contains info about
4638f0fd8f6SDimitry Andric   /// where to find deferred function body in the stream.
464ff0cc061SDimitry Andric   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
465ff0cc061SDimitry Andric 
466ff0cc061SDimitry Andric   /// When Metadata block is initially scanned when parsing the module, we may
467ff0cc061SDimitry Andric   /// choose to defer parsing of the metadata. This vector contains info about
468ff0cc061SDimitry Andric   /// which Metadata blocks are deferred.
469ff0cc061SDimitry Andric   std::vector<uint64_t> DeferredMetadataInfo;
470ff0cc061SDimitry Andric 
471ff0cc061SDimitry Andric   /// These are basic blocks forward-referenced by block addresses.  They are
472ff0cc061SDimitry Andric   /// inserted lazily into functions when they're loaded.  The basic block ID is
473ff0cc061SDimitry Andric   /// its index into the vector.
474ff0cc061SDimitry Andric   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
475ff0cc061SDimitry Andric   std::deque<Function *> BasicBlockFwdRefQueue;
476ff0cc061SDimitry Andric 
4778f0fd8f6SDimitry Andric   /// Indicates that we are using a new encoding for instruction operands where
4788f0fd8f6SDimitry Andric   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
4798f0fd8f6SDimitry Andric   /// instruction number, for a more compact encoding.  Some instruction
4808f0fd8f6SDimitry Andric   /// operands are not relative to the instruction ID: basic block numbers, and
4818f0fd8f6SDimitry Andric   /// types. Once the old style function blocks have been phased out, we would
482ff0cc061SDimitry Andric   /// not need this flag.
4838f0fd8f6SDimitry Andric   bool UseRelativeIDs = false;
484ff0cc061SDimitry Andric 
485ff0cc061SDimitry Andric   /// True if all functions will be materialized, negating the need to process
486ff0cc061SDimitry Andric   /// (e.g.) blockaddress forward references.
4878f0fd8f6SDimitry Andric   bool WillMaterializeAllForwardRefs = false;
488ff0cc061SDimitry Andric 
489ff0cc061SDimitry Andric   bool StripDebugInfo = false;
490d88c1a5aSDimitry Andric   TBAAVerifier TBAAVerifyHelper;
4917d523365SDimitry Andric 
4927d523365SDimitry Andric   std::vector<std::string> BundleTags;
4937d523365SDimitry Andric 
494ff0cc061SDimitry Andric public:
495d88c1a5aSDimitry Andric   BitcodeReader(BitstreamCursor Stream, StringRef ProducerIdentification,
496d88c1a5aSDimitry Andric                 LLVMContext &Context);
497ff0cc061SDimitry Andric 
498d88c1a5aSDimitry Andric   Error materializeForwardReferencedFunctions();
499ff0cc061SDimitry Andric 
500d88c1a5aSDimitry Andric   Error materialize(GlobalValue *GV) override;
501d88c1a5aSDimitry Andric   Error materializeModule() override;
502ff0cc061SDimitry Andric   std::vector<StructType *> getIdentifiedStructTypes() const override;
503ff0cc061SDimitry Andric 
5048f0fd8f6SDimitry Andric   /// \brief Main interface to parsing a bitcode buffer.
5058f0fd8f6SDimitry Andric   /// \returns true if an error occurred.
506d88c1a5aSDimitry Andric   Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
507d88c1a5aSDimitry Andric                          bool IsImporting = false);
5083ca95b02SDimitry Andric 
509ff0cc061SDimitry Andric   static uint64_t decodeSignRotatedValue(uint64_t V);
510ff0cc061SDimitry Andric 
511ff0cc061SDimitry Andric   /// Materialize any deferred Metadata block.
512d88c1a5aSDimitry Andric   Error materializeMetadata() override;
513ff0cc061SDimitry Andric 
514ff0cc061SDimitry Andric   void setStripDebugInfo() override;
515ff0cc061SDimitry Andric 
516ff0cc061SDimitry Andric private:
517ff0cc061SDimitry Andric   std::vector<StructType *> IdentifiedStructTypes;
518ff0cc061SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
519ff0cc061SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context);
520ff0cc061SDimitry Andric 
521ff0cc061SDimitry Andric   Type *getTypeByID(unsigned ID);
522d88c1a5aSDimitry Andric 
523ff0cc061SDimitry Andric   Value *getFnValueByID(unsigned ID, Type *Ty) {
524ff0cc061SDimitry Andric     if (Ty && Ty->isMetadataTy())
525ff0cc061SDimitry Andric       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
526ff0cc061SDimitry Andric     return ValueList.getValueFwdRef(ID, Ty);
527ff0cc061SDimitry Andric   }
528d88c1a5aSDimitry Andric 
529ff0cc061SDimitry Andric   Metadata *getFnMetadataByID(unsigned ID) {
530f8496407SDimitry Andric     return MDLoader->getMetadataFwdRefOrLoad(ID);
531ff0cc061SDimitry Andric   }
532d88c1a5aSDimitry Andric 
533ff0cc061SDimitry Andric   BasicBlock *getBasicBlock(unsigned ID) const {
534ff0cc061SDimitry Andric     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
535ff0cc061SDimitry Andric     return FunctionBBs[ID];
536ff0cc061SDimitry Andric   }
537d88c1a5aSDimitry Andric 
5387a7e6055SDimitry Andric   AttributeList getAttributes(unsigned i) const {
539ff0cc061SDimitry Andric     if (i-1 < MAttributes.size())
540ff0cc061SDimitry Andric       return MAttributes[i-1];
5417a7e6055SDimitry Andric     return AttributeList();
542ff0cc061SDimitry Andric   }
543ff0cc061SDimitry Andric 
5448f0fd8f6SDimitry Andric   /// Read a value/type pair out of the specified record from slot 'Slot'.
5458f0fd8f6SDimitry Andric   /// Increment Slot past the number of slots used in the record. Return true on
5468f0fd8f6SDimitry Andric   /// failure.
547ff0cc061SDimitry Andric   bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
548ff0cc061SDimitry Andric                         unsigned InstNum, Value *&ResVal) {
549ff0cc061SDimitry Andric     if (Slot == Record.size()) return true;
550ff0cc061SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot++];
551ff0cc061SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
552ff0cc061SDimitry Andric     if (UseRelativeIDs)
553ff0cc061SDimitry Andric       ValNo = InstNum - ValNo;
554ff0cc061SDimitry Andric     if (ValNo < InstNum) {
555ff0cc061SDimitry Andric       // If this is not a forward reference, just return the value we already
556ff0cc061SDimitry Andric       // have.
557ff0cc061SDimitry Andric       ResVal = getFnValueByID(ValNo, nullptr);
558ff0cc061SDimitry Andric       return ResVal == nullptr;
559ff0cc061SDimitry Andric     }
560ff0cc061SDimitry Andric     if (Slot == Record.size())
561ff0cc061SDimitry Andric       return true;
562ff0cc061SDimitry Andric 
563ff0cc061SDimitry Andric     unsigned TypeNo = (unsigned)Record[Slot++];
564ff0cc061SDimitry Andric     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
565ff0cc061SDimitry Andric     return ResVal == nullptr;
566ff0cc061SDimitry Andric   }
567ff0cc061SDimitry Andric 
5688f0fd8f6SDimitry Andric   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
5698f0fd8f6SDimitry Andric   /// past the number of slots used by the value in the record. Return true if
5708f0fd8f6SDimitry Andric   /// there is an error.
571ff0cc061SDimitry Andric   bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
572ff0cc061SDimitry Andric                 unsigned InstNum, Type *Ty, Value *&ResVal) {
573ff0cc061SDimitry Andric     if (getValue(Record, Slot, InstNum, Ty, ResVal))
574ff0cc061SDimitry Andric       return true;
575ff0cc061SDimitry Andric     // All values currently take a single record slot.
576ff0cc061SDimitry Andric     ++Slot;
577ff0cc061SDimitry Andric     return false;
578ff0cc061SDimitry Andric   }
579ff0cc061SDimitry Andric 
5808f0fd8f6SDimitry Andric   /// Like popValue, but does not increment the Slot number.
581ff0cc061SDimitry Andric   bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
582ff0cc061SDimitry Andric                 unsigned InstNum, Type *Ty, Value *&ResVal) {
583ff0cc061SDimitry Andric     ResVal = getValue(Record, Slot, InstNum, Ty);
584ff0cc061SDimitry Andric     return ResVal == nullptr;
585ff0cc061SDimitry Andric   }
586ff0cc061SDimitry Andric 
5878f0fd8f6SDimitry Andric   /// Version of getValue that returns ResVal directly, or 0 if there is an
5888f0fd8f6SDimitry Andric   /// error.
589ff0cc061SDimitry Andric   Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
590ff0cc061SDimitry Andric                   unsigned InstNum, Type *Ty) {
591ff0cc061SDimitry Andric     if (Slot == Record.size()) return nullptr;
592ff0cc061SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot];
593ff0cc061SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
594ff0cc061SDimitry Andric     if (UseRelativeIDs)
595ff0cc061SDimitry Andric       ValNo = InstNum - ValNo;
596ff0cc061SDimitry Andric     return getFnValueByID(ValNo, Ty);
597ff0cc061SDimitry Andric   }
598ff0cc061SDimitry Andric 
5998f0fd8f6SDimitry Andric   /// Like getValue, but decodes signed VBRs.
600ff0cc061SDimitry Andric   Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
601ff0cc061SDimitry Andric                         unsigned InstNum, Type *Ty) {
602ff0cc061SDimitry Andric     if (Slot == Record.size()) return nullptr;
603ff0cc061SDimitry Andric     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
604ff0cc061SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
605ff0cc061SDimitry Andric     if (UseRelativeIDs)
606ff0cc061SDimitry Andric       ValNo = InstNum - ValNo;
607ff0cc061SDimitry Andric     return getFnValueByID(ValNo, Ty);
608ff0cc061SDimitry Andric   }
609ff0cc061SDimitry Andric 
610ff0cc061SDimitry Andric   /// Converts alignment exponent (i.e. power of two (or zero)) to the
611ff0cc061SDimitry Andric   /// corresponding alignment to use. If alignment is too large, returns
612ff0cc061SDimitry Andric   /// a corresponding error code.
613d88c1a5aSDimitry Andric   Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
614d88c1a5aSDimitry Andric   Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
615d88c1a5aSDimitry Andric   Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
6167a7e6055SDimitry Andric 
6177a7e6055SDimitry Andric   Error parseComdatRecord(ArrayRef<uint64_t> Record);
6187a7e6055SDimitry Andric   Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
6197a7e6055SDimitry Andric   Error parseFunctionRecord(ArrayRef<uint64_t> Record);
6207a7e6055SDimitry Andric   Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
6217a7e6055SDimitry Andric                                         ArrayRef<uint64_t> Record);
6227a7e6055SDimitry Andric 
623d88c1a5aSDimitry Andric   Error parseAttributeBlock();
624d88c1a5aSDimitry Andric   Error parseAttributeGroupBlock();
625d88c1a5aSDimitry Andric   Error parseTypeTable();
626d88c1a5aSDimitry Andric   Error parseTypeTableBody();
627d88c1a5aSDimitry Andric   Error parseOperandBundleTags();
628ff0cc061SDimitry Andric 
629d88c1a5aSDimitry Andric   Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
6307d523365SDimitry Andric                                 unsigned NameIndex, Triple &TT);
631d88c1a5aSDimitry Andric   Error parseValueSymbolTable(uint64_t Offset = 0);
632d88c1a5aSDimitry Andric   Error parseConstants();
633d88c1a5aSDimitry Andric   Error rememberAndSkipFunctionBodies();
634d88c1a5aSDimitry Andric   Error rememberAndSkipFunctionBody();
635ff0cc061SDimitry Andric   /// Save the positions of the Metadata blocks and skip parsing the blocks.
636d88c1a5aSDimitry Andric   Error rememberAndSkipMetadata();
637d88c1a5aSDimitry Andric   Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
638d88c1a5aSDimitry Andric   Error parseFunctionBody(Function *F);
639d88c1a5aSDimitry Andric   Error globalCleanup();
640d88c1a5aSDimitry Andric   Error resolveGlobalAndIndirectSymbolInits();
641d88c1a5aSDimitry Andric   Error parseUseLists();
642d88c1a5aSDimitry Andric   Error findFunctionInStream(
643ff0cc061SDimitry Andric       Function *F,
644ff0cc061SDimitry Andric       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
645ff0cc061SDimitry Andric };
6467d523365SDimitry Andric 
6477d523365SDimitry Andric /// Class to manage reading and parsing function summary index bitcode
6487d523365SDimitry Andric /// files/sections.
649d88c1a5aSDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
650d88c1a5aSDimitry Andric   /// The module index built during parsing.
651d88c1a5aSDimitry Andric   ModuleSummaryIndex &TheIndex;
6527d523365SDimitry Andric 
6533ca95b02SDimitry Andric   /// Indicates whether we have encountered a global value summary section
654d88c1a5aSDimitry Andric   /// yet during parsing.
6553ca95b02SDimitry Andric   bool SeenGlobalValSummary = false;
6567d523365SDimitry Andric 
6573ca95b02SDimitry Andric   /// Indicates whether we have already parsed the VST, used for error checking.
6583ca95b02SDimitry Andric   bool SeenValueSymbolTable = false;
6593ca95b02SDimitry Andric 
6603ca95b02SDimitry Andric   /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
6613ca95b02SDimitry Andric   /// Used to enable on-demand parsing of the VST.
6623ca95b02SDimitry Andric   uint64_t VSTOffset = 0;
6633ca95b02SDimitry Andric 
6643ca95b02SDimitry Andric   // Map to save ValueId to GUID association that was recorded in the
6653ca95b02SDimitry Andric   // ValueSymbolTable. It is used after the VST is parsed to convert
6663ca95b02SDimitry Andric   // call graph edges read from the function summary from referencing
6673ca95b02SDimitry Andric   // callees by their ValueId to using the GUID instead, which is how
6683ca95b02SDimitry Andric   // they are recorded in the summary index being built.
6693ca95b02SDimitry Andric   // We save a second GUID which is the same as the first one, but ignoring the
6703ca95b02SDimitry Andric   // linkage, i.e. for value other than local linkage they are identical.
6713ca95b02SDimitry Andric   DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>>
6723ca95b02SDimitry Andric       ValueIdToCallGraphGUIDMap;
6737d523365SDimitry Andric 
6747d523365SDimitry Andric   /// Map populated during module path string table parsing, from the
6757d523365SDimitry Andric   /// module ID to a string reference owned by the index's module
6763ca95b02SDimitry Andric   /// path string table, used to correlate with combined index
6777d523365SDimitry Andric   /// summary records.
6787d523365SDimitry Andric   DenseMap<uint64_t, StringRef> ModuleIdMap;
6797d523365SDimitry Andric 
6803ca95b02SDimitry Andric   /// Original source file name recorded in a bitcode record.
6813ca95b02SDimitry Andric   std::string SourceFileName;
6823ca95b02SDimitry Andric 
6837d523365SDimitry Andric public:
6843ca95b02SDimitry Andric   ModuleSummaryIndexBitcodeReader(
685d88c1a5aSDimitry Andric       BitstreamCursor Stream, ModuleSummaryIndex &TheIndex);
6867d523365SDimitry Andric 
687d88c1a5aSDimitry Andric   Error parseModule(StringRef ModulePath);
6887d523365SDimitry Andric 
6897d523365SDimitry Andric private:
690d88c1a5aSDimitry Andric   Error parseValueSymbolTable(
6913ca95b02SDimitry Andric       uint64_t Offset,
6923ca95b02SDimitry Andric       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
693d88c1a5aSDimitry Andric   std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
694d88c1a5aSDimitry Andric   std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
695d88c1a5aSDimitry Andric                                                     bool IsOldProfileFormat,
696d88c1a5aSDimitry Andric                                                     bool HasProfile);
697d88c1a5aSDimitry Andric   Error parseEntireSummary(StringRef ModulePath);
698d88c1a5aSDimitry Andric   Error parseModuleStringTable();
699d88c1a5aSDimitry Andric 
7003ca95b02SDimitry Andric   std::pair<GlobalValue::GUID, GlobalValue::GUID>
7013ca95b02SDimitry Andric   getGUIDFromValueId(unsigned ValueId);
7027d523365SDimitry Andric };
703d88c1a5aSDimitry Andric 
7043ca95b02SDimitry Andric } // end anonymous namespace
705ff0cc061SDimitry Andric 
706d88c1a5aSDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
707d88c1a5aSDimitry Andric                                                     Error Err) {
708d88c1a5aSDimitry Andric   if (Err) {
709d88c1a5aSDimitry Andric     std::error_code EC;
710d88c1a5aSDimitry Andric     handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
711d88c1a5aSDimitry Andric       EC = EIB.convertToErrorCode();
712d88c1a5aSDimitry Andric       Ctx.emitError(EIB.message());
713d88c1a5aSDimitry Andric     });
71439d628a0SDimitry Andric     return EC;
715dff0c46cSDimitry Andric   }
71639d628a0SDimitry Andric   return std::error_code();
717d88c1a5aSDimitry Andric }
718d88c1a5aSDimitry Andric 
719d88c1a5aSDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream,
720d88c1a5aSDimitry Andric                              StringRef ProducerIdentification,
721d88c1a5aSDimitry Andric                              LLVMContext &Context)
722d88c1a5aSDimitry Andric     : BitcodeReaderBase(std::move(Stream)), Context(Context),
723d88c1a5aSDimitry Andric       ValueList(Context) {
724d88c1a5aSDimitry Andric   this->ProducerIdentification = ProducerIdentification;
725d88c1a5aSDimitry Andric }
726d88c1a5aSDimitry Andric 
727d88c1a5aSDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() {
728d88c1a5aSDimitry Andric   if (WillMaterializeAllForwardRefs)
729d88c1a5aSDimitry Andric     return Error::success();
73039d628a0SDimitry Andric 
73139d628a0SDimitry Andric   // Prevent recursion.
73239d628a0SDimitry Andric   WillMaterializeAllForwardRefs = true;
73339d628a0SDimitry Andric 
73439d628a0SDimitry Andric   while (!BasicBlockFwdRefQueue.empty()) {
73539d628a0SDimitry Andric     Function *F = BasicBlockFwdRefQueue.front();
73639d628a0SDimitry Andric     BasicBlockFwdRefQueue.pop_front();
73739d628a0SDimitry Andric     assert(F && "Expected valid function");
73839d628a0SDimitry Andric     if (!BasicBlockFwdRefs.count(F))
73939d628a0SDimitry Andric       // Already materialized.
74039d628a0SDimitry Andric       continue;
74139d628a0SDimitry Andric 
74239d628a0SDimitry Andric     // Check for a function that isn't materializable to prevent an infinite
74339d628a0SDimitry Andric     // loop.  When parsing a blockaddress stored in a global variable, there
74439d628a0SDimitry Andric     // isn't a trivial way to check if a function will have a body without a
74539d628a0SDimitry Andric     // linear search through FunctionsWithBodies, so just check it here.
74639d628a0SDimitry Andric     if (!F->isMaterializable())
7478f0fd8f6SDimitry Andric       return error("Never resolved function from blockaddress");
74839d628a0SDimitry Andric 
74939d628a0SDimitry Andric     // Try to materialize F.
750d88c1a5aSDimitry Andric     if (Error Err = materialize(F))
751d88c1a5aSDimitry Andric       return Err;
75239d628a0SDimitry Andric   }
75339d628a0SDimitry Andric   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
75439d628a0SDimitry Andric 
75539d628a0SDimitry Andric   // Reset state.
75639d628a0SDimitry Andric   WillMaterializeAllForwardRefs = false;
757d88c1a5aSDimitry Andric   return Error::success();
758f22ef01cSRoman Divacky }
759f22ef01cSRoman Divacky 
760f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
761f22ef01cSRoman Divacky //  Helper functions to implement forward reference resolution, etc.
762f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
763f22ef01cSRoman Divacky 
764ff0cc061SDimitry Andric static bool hasImplicitComdat(size_t Val) {
765ff0cc061SDimitry Andric   switch (Val) {
766ff0cc061SDimitry Andric   default:
767ff0cc061SDimitry Andric     return false;
768ff0cc061SDimitry Andric   case 1:  // Old WeakAnyLinkage
769ff0cc061SDimitry Andric   case 4:  // Old LinkOnceAnyLinkage
770ff0cc061SDimitry Andric   case 10: // Old WeakODRLinkage
771ff0cc061SDimitry Andric   case 11: // Old LinkOnceODRLinkage
772ff0cc061SDimitry Andric     return true;
773ff0cc061SDimitry Andric   }
774ff0cc061SDimitry Andric }
775ff0cc061SDimitry Andric 
77639d628a0SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
777f22ef01cSRoman Divacky   switch (Val) {
778f22ef01cSRoman Divacky   default: // Map unknown/new linkages to external
77939d628a0SDimitry Andric   case 0:
78039d628a0SDimitry Andric     return GlobalValue::ExternalLinkage;
78139d628a0SDimitry Andric   case 2:
78239d628a0SDimitry Andric     return GlobalValue::AppendingLinkage;
78339d628a0SDimitry Andric   case 3:
78439d628a0SDimitry Andric     return GlobalValue::InternalLinkage;
78539d628a0SDimitry Andric   case 5:
78639d628a0SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
78739d628a0SDimitry Andric   case 6:
78839d628a0SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
78939d628a0SDimitry Andric   case 7:
79039d628a0SDimitry Andric     return GlobalValue::ExternalWeakLinkage;
79139d628a0SDimitry Andric   case 8:
79239d628a0SDimitry Andric     return GlobalValue::CommonLinkage;
79339d628a0SDimitry Andric   case 9:
79439d628a0SDimitry Andric     return GlobalValue::PrivateLinkage;
79539d628a0SDimitry Andric   case 12:
79639d628a0SDimitry Andric     return GlobalValue::AvailableExternallyLinkage;
79791bc56edSDimitry Andric   case 13:
79891bc56edSDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
79991bc56edSDimitry Andric   case 14:
80091bc56edSDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
80139d628a0SDimitry Andric   case 15:
80239d628a0SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
803ff0cc061SDimitry Andric   case 1: // Old value with implicit comdat.
804ff0cc061SDimitry Andric   case 16:
805ff0cc061SDimitry Andric     return GlobalValue::WeakAnyLinkage;
806ff0cc061SDimitry Andric   case 10: // Old value with implicit comdat.
807ff0cc061SDimitry Andric   case 17:
808ff0cc061SDimitry Andric     return GlobalValue::WeakODRLinkage;
809ff0cc061SDimitry Andric   case 4: // Old value with implicit comdat.
810ff0cc061SDimitry Andric   case 18:
811ff0cc061SDimitry Andric     return GlobalValue::LinkOnceAnyLinkage;
812ff0cc061SDimitry Andric   case 11: // Old value with implicit comdat.
813ff0cc061SDimitry Andric   case 19:
814ff0cc061SDimitry Andric     return GlobalValue::LinkOnceODRLinkage;
815f22ef01cSRoman Divacky   }
816f22ef01cSRoman Divacky }
817f22ef01cSRoman Divacky 
818d88c1a5aSDimitry Andric /// Decode the flags for GlobalValue in the summary.
8193ca95b02SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
8203ca95b02SDimitry Andric                                                             uint64_t Version) {
8213ca95b02SDimitry Andric   // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
8223ca95b02SDimitry Andric   // like getDecodedLinkage() above. Any future change to the linkage enum and
8233ca95b02SDimitry Andric   // to getDecodedLinkage() will need to be taken into account here as above.
8243ca95b02SDimitry Andric   auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
8253ca95b02SDimitry Andric   RawFlags = RawFlags >> 4;
82695ec533aSDimitry Andric   bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
82795ec533aSDimitry Andric   // The LiveRoot flag wasn't introduced until version 3. For dead stripping
82895ec533aSDimitry Andric   // to work correctly on earlier versions, we must conservatively treat all
82995ec533aSDimitry Andric   // values as live.
83095ec533aSDimitry Andric   bool LiveRoot = (RawFlags & 0x2) || Version < 3;
83195ec533aSDimitry Andric   return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, LiveRoot);
8323ca95b02SDimitry Andric }
8333ca95b02SDimitry Andric 
8348f0fd8f6SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
835f22ef01cSRoman Divacky   switch (Val) {
836f22ef01cSRoman Divacky   default: // Map unknown visibilities to default.
837f22ef01cSRoman Divacky   case 0: return GlobalValue::DefaultVisibility;
838f22ef01cSRoman Divacky   case 1: return GlobalValue::HiddenVisibility;
839f22ef01cSRoman Divacky   case 2: return GlobalValue::ProtectedVisibility;
840f22ef01cSRoman Divacky   }
841f22ef01cSRoman Divacky }
842f22ef01cSRoman Divacky 
84391bc56edSDimitry Andric static GlobalValue::DLLStorageClassTypes
8448f0fd8f6SDimitry Andric getDecodedDLLStorageClass(unsigned Val) {
84591bc56edSDimitry Andric   switch (Val) {
84691bc56edSDimitry Andric   default: // Map unknown values to default.
84791bc56edSDimitry Andric   case 0: return GlobalValue::DefaultStorageClass;
84891bc56edSDimitry Andric   case 1: return GlobalValue::DLLImportStorageClass;
84991bc56edSDimitry Andric   case 2: return GlobalValue::DLLExportStorageClass;
85091bc56edSDimitry Andric   }
85191bc56edSDimitry Andric }
85291bc56edSDimitry Andric 
8538f0fd8f6SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
8547ae0e2c9SDimitry Andric   switch (Val) {
8557ae0e2c9SDimitry Andric     case 0: return GlobalVariable::NotThreadLocal;
8567ae0e2c9SDimitry Andric     default: // Map unknown non-zero value to general dynamic.
8577ae0e2c9SDimitry Andric     case 1: return GlobalVariable::GeneralDynamicTLSModel;
8587ae0e2c9SDimitry Andric     case 2: return GlobalVariable::LocalDynamicTLSModel;
8597ae0e2c9SDimitry Andric     case 3: return GlobalVariable::InitialExecTLSModel;
8607ae0e2c9SDimitry Andric     case 4: return GlobalVariable::LocalExecTLSModel;
8617ae0e2c9SDimitry Andric   }
8627ae0e2c9SDimitry Andric }
8637ae0e2c9SDimitry Andric 
8643ca95b02SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
8653ca95b02SDimitry Andric   switch (Val) {
8663ca95b02SDimitry Andric     default: // Map unknown to UnnamedAddr::None.
8673ca95b02SDimitry Andric     case 0: return GlobalVariable::UnnamedAddr::None;
8683ca95b02SDimitry Andric     case 1: return GlobalVariable::UnnamedAddr::Global;
8693ca95b02SDimitry Andric     case 2: return GlobalVariable::UnnamedAddr::Local;
8703ca95b02SDimitry Andric   }
8713ca95b02SDimitry Andric }
8723ca95b02SDimitry Andric 
8738f0fd8f6SDimitry Andric static int getDecodedCastOpcode(unsigned Val) {
874f22ef01cSRoman Divacky   switch (Val) {
875f22ef01cSRoman Divacky   default: return -1;
876f22ef01cSRoman Divacky   case bitc::CAST_TRUNC   : return Instruction::Trunc;
877f22ef01cSRoman Divacky   case bitc::CAST_ZEXT    : return Instruction::ZExt;
878f22ef01cSRoman Divacky   case bitc::CAST_SEXT    : return Instruction::SExt;
879f22ef01cSRoman Divacky   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
880f22ef01cSRoman Divacky   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
881f22ef01cSRoman Divacky   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
882f22ef01cSRoman Divacky   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
883f22ef01cSRoman Divacky   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
884f22ef01cSRoman Divacky   case bitc::CAST_FPEXT   : return Instruction::FPExt;
885f22ef01cSRoman Divacky   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
886f22ef01cSRoman Divacky   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
887f22ef01cSRoman Divacky   case bitc::CAST_BITCAST : return Instruction::BitCast;
888f785676fSDimitry Andric   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
889f22ef01cSRoman Divacky   }
890f22ef01cSRoman Divacky }
891ff0cc061SDimitry Andric 
8928f0fd8f6SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
893ff0cc061SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
894ff0cc061SDimitry Andric   // BinOps are only valid for int/fp or vector of int/fp types
895ff0cc061SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
896ff0cc061SDimitry Andric     return -1;
897ff0cc061SDimitry Andric 
898f22ef01cSRoman Divacky   switch (Val) {
899ff0cc061SDimitry Andric   default:
900ff0cc061SDimitry Andric     return -1;
901f22ef01cSRoman Divacky   case bitc::BINOP_ADD:
902ff0cc061SDimitry Andric     return IsFP ? Instruction::FAdd : Instruction::Add;
903f22ef01cSRoman Divacky   case bitc::BINOP_SUB:
904ff0cc061SDimitry Andric     return IsFP ? Instruction::FSub : Instruction::Sub;
905f22ef01cSRoman Divacky   case bitc::BINOP_MUL:
906ff0cc061SDimitry Andric     return IsFP ? Instruction::FMul : Instruction::Mul;
907ff0cc061SDimitry Andric   case bitc::BINOP_UDIV:
908ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::UDiv;
909f22ef01cSRoman Divacky   case bitc::BINOP_SDIV:
910ff0cc061SDimitry Andric     return IsFP ? Instruction::FDiv : Instruction::SDiv;
911ff0cc061SDimitry Andric   case bitc::BINOP_UREM:
912ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::URem;
913f22ef01cSRoman Divacky   case bitc::BINOP_SREM:
914ff0cc061SDimitry Andric     return IsFP ? Instruction::FRem : Instruction::SRem;
915ff0cc061SDimitry Andric   case bitc::BINOP_SHL:
916ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::Shl;
917ff0cc061SDimitry Andric   case bitc::BINOP_LSHR:
918ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::LShr;
919ff0cc061SDimitry Andric   case bitc::BINOP_ASHR:
920ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::AShr;
921ff0cc061SDimitry Andric   case bitc::BINOP_AND:
922ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::And;
923ff0cc061SDimitry Andric   case bitc::BINOP_OR:
924ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::Or;
925ff0cc061SDimitry Andric   case bitc::BINOP_XOR:
926ff0cc061SDimitry Andric     return IsFP ? -1 : Instruction::Xor;
927f22ef01cSRoman Divacky   }
928f22ef01cSRoman Divacky }
929f22ef01cSRoman Divacky 
9308f0fd8f6SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
9316122f3e6SDimitry Andric   switch (Val) {
9326122f3e6SDimitry Andric   default: return AtomicRMWInst::BAD_BINOP;
9336122f3e6SDimitry Andric   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
9346122f3e6SDimitry Andric   case bitc::RMW_ADD: return AtomicRMWInst::Add;
9356122f3e6SDimitry Andric   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
9366122f3e6SDimitry Andric   case bitc::RMW_AND: return AtomicRMWInst::And;
9376122f3e6SDimitry Andric   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
9386122f3e6SDimitry Andric   case bitc::RMW_OR: return AtomicRMWInst::Or;
9396122f3e6SDimitry Andric   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
9406122f3e6SDimitry Andric   case bitc::RMW_MAX: return AtomicRMWInst::Max;
9416122f3e6SDimitry Andric   case bitc::RMW_MIN: return AtomicRMWInst::Min;
9426122f3e6SDimitry Andric   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
9436122f3e6SDimitry Andric   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
9446122f3e6SDimitry Andric   }
9456122f3e6SDimitry Andric }
9466122f3e6SDimitry Andric 
9478f0fd8f6SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) {
9486122f3e6SDimitry Andric   switch (Val) {
9493ca95b02SDimitry Andric   case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
9503ca95b02SDimitry Andric   case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
9513ca95b02SDimitry Andric   case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
9523ca95b02SDimitry Andric   case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
9533ca95b02SDimitry Andric   case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
9543ca95b02SDimitry Andric   case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
9556122f3e6SDimitry Andric   default: // Map unknown orderings to sequentially-consistent.
9563ca95b02SDimitry Andric   case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
9576122f3e6SDimitry Andric   }
9586122f3e6SDimitry Andric }
9596122f3e6SDimitry Andric 
9608f0fd8f6SDimitry Andric static SynchronizationScope getDecodedSynchScope(unsigned Val) {
9616122f3e6SDimitry Andric   switch (Val) {
9626122f3e6SDimitry Andric   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
9636122f3e6SDimitry Andric   default: // Map unknown scopes to cross-thread.
9646122f3e6SDimitry Andric   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
9656122f3e6SDimitry Andric   }
9666122f3e6SDimitry Andric }
9676122f3e6SDimitry Andric 
96891bc56edSDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
96991bc56edSDimitry Andric   switch (Val) {
97091bc56edSDimitry Andric   default: // Map unknown selection kinds to any.
97191bc56edSDimitry Andric   case bitc::COMDAT_SELECTION_KIND_ANY:
97291bc56edSDimitry Andric     return Comdat::Any;
97391bc56edSDimitry Andric   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
97491bc56edSDimitry Andric     return Comdat::ExactMatch;
97591bc56edSDimitry Andric   case bitc::COMDAT_SELECTION_KIND_LARGEST:
97691bc56edSDimitry Andric     return Comdat::Largest;
97791bc56edSDimitry Andric   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
97891bc56edSDimitry Andric     return Comdat::NoDuplicates;
97991bc56edSDimitry Andric   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
98091bc56edSDimitry Andric     return Comdat::SameSize;
98191bc56edSDimitry Andric   }
98291bc56edSDimitry Andric }
98391bc56edSDimitry Andric 
984875ed548SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
985875ed548SDimitry Andric   FastMathFlags FMF;
986875ed548SDimitry Andric   if (0 != (Val & FastMathFlags::UnsafeAlgebra))
987875ed548SDimitry Andric     FMF.setUnsafeAlgebra();
988875ed548SDimitry Andric   if (0 != (Val & FastMathFlags::NoNaNs))
989875ed548SDimitry Andric     FMF.setNoNaNs();
990875ed548SDimitry Andric   if (0 != (Val & FastMathFlags::NoInfs))
991875ed548SDimitry Andric     FMF.setNoInfs();
992875ed548SDimitry Andric   if (0 != (Val & FastMathFlags::NoSignedZeros))
993875ed548SDimitry Andric     FMF.setNoSignedZeros();
994875ed548SDimitry Andric   if (0 != (Val & FastMathFlags::AllowReciprocal))
995875ed548SDimitry Andric     FMF.setAllowReciprocal();
9967a7e6055SDimitry Andric   if (0 != (Val & FastMathFlags::AllowContract))
9977a7e6055SDimitry Andric     FMF.setAllowContract(true);
998875ed548SDimitry Andric   return FMF;
999875ed548SDimitry Andric }
1000875ed548SDimitry Andric 
1001d88c1a5aSDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
100291bc56edSDimitry Andric   switch (Val) {
100391bc56edSDimitry Andric   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
100491bc56edSDimitry Andric   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
100591bc56edSDimitry Andric   }
100691bc56edSDimitry Andric }
100791bc56edSDimitry Andric 
10083ca95b02SDimitry Andric 
100917a519f9SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) {
101017a519f9SDimitry Andric   // The type table size is always specified correctly.
101117a519f9SDimitry Andric   if (ID >= TypeList.size())
101291bc56edSDimitry Andric     return nullptr;
1013f22ef01cSRoman Divacky 
101417a519f9SDimitry Andric   if (Type *Ty = TypeList[ID])
101517a519f9SDimitry Andric     return Ty;
101617a519f9SDimitry Andric 
101717a519f9SDimitry Andric   // If we have a forward reference, the only possible case is when it is to a
101817a519f9SDimitry Andric   // named struct.  Just create a placeholder for now.
101939d628a0SDimitry Andric   return TypeList[ID] = createIdentifiedStructType(Context);
102039d628a0SDimitry Andric }
102139d628a0SDimitry Andric 
102239d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
102339d628a0SDimitry Andric                                                       StringRef Name) {
102439d628a0SDimitry Andric   auto *Ret = StructType::create(Context, Name);
102539d628a0SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
102639d628a0SDimitry Andric   return Ret;
102739d628a0SDimitry Andric }
102839d628a0SDimitry Andric 
102939d628a0SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
103039d628a0SDimitry Andric   auto *Ret = StructType::create(Context);
103139d628a0SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
103239d628a0SDimitry Andric   return Ret;
1033f22ef01cSRoman Divacky }
1034f22ef01cSRoman Divacky 
1035f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1036f22ef01cSRoman Divacky //  Functions for parsing blocks from the bitcode file
1037f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1038f22ef01cSRoman Divacky 
1039d88c1a5aSDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1040d88c1a5aSDimitry Andric   switch (Val) {
1041d88c1a5aSDimitry Andric   case Attribute::EndAttrKinds:
1042d88c1a5aSDimitry Andric     llvm_unreachable("Synthetic enumerators which should never get here");
1043d88c1a5aSDimitry Andric 
1044d88c1a5aSDimitry Andric   case Attribute::None:            return 0;
1045d88c1a5aSDimitry Andric   case Attribute::ZExt:            return 1 << 0;
1046d88c1a5aSDimitry Andric   case Attribute::SExt:            return 1 << 1;
1047d88c1a5aSDimitry Andric   case Attribute::NoReturn:        return 1 << 2;
1048d88c1a5aSDimitry Andric   case Attribute::InReg:           return 1 << 3;
1049d88c1a5aSDimitry Andric   case Attribute::StructRet:       return 1 << 4;
1050d88c1a5aSDimitry Andric   case Attribute::NoUnwind:        return 1 << 5;
1051d88c1a5aSDimitry Andric   case Attribute::NoAlias:         return 1 << 6;
1052d88c1a5aSDimitry Andric   case Attribute::ByVal:           return 1 << 7;
1053d88c1a5aSDimitry Andric   case Attribute::Nest:            return 1 << 8;
1054d88c1a5aSDimitry Andric   case Attribute::ReadNone:        return 1 << 9;
1055d88c1a5aSDimitry Andric   case Attribute::ReadOnly:        return 1 << 10;
1056d88c1a5aSDimitry Andric   case Attribute::NoInline:        return 1 << 11;
1057d88c1a5aSDimitry Andric   case Attribute::AlwaysInline:    return 1 << 12;
1058d88c1a5aSDimitry Andric   case Attribute::OptimizeForSize: return 1 << 13;
1059d88c1a5aSDimitry Andric   case Attribute::StackProtect:    return 1 << 14;
1060d88c1a5aSDimitry Andric   case Attribute::StackProtectReq: return 1 << 15;
1061d88c1a5aSDimitry Andric   case Attribute::Alignment:       return 31 << 16;
1062d88c1a5aSDimitry Andric   case Attribute::NoCapture:       return 1 << 21;
1063d88c1a5aSDimitry Andric   case Attribute::NoRedZone:       return 1 << 22;
1064d88c1a5aSDimitry Andric   case Attribute::NoImplicitFloat: return 1 << 23;
1065d88c1a5aSDimitry Andric   case Attribute::Naked:           return 1 << 24;
1066d88c1a5aSDimitry Andric   case Attribute::InlineHint:      return 1 << 25;
1067d88c1a5aSDimitry Andric   case Attribute::StackAlignment:  return 7 << 26;
1068d88c1a5aSDimitry Andric   case Attribute::ReturnsTwice:    return 1 << 29;
1069d88c1a5aSDimitry Andric   case Attribute::UWTable:         return 1 << 30;
1070d88c1a5aSDimitry Andric   case Attribute::NonLazyBind:     return 1U << 31;
1071d88c1a5aSDimitry Andric   case Attribute::SanitizeAddress: return 1ULL << 32;
1072d88c1a5aSDimitry Andric   case Attribute::MinSize:         return 1ULL << 33;
1073d88c1a5aSDimitry Andric   case Attribute::NoDuplicate:     return 1ULL << 34;
1074d88c1a5aSDimitry Andric   case Attribute::StackProtectStrong: return 1ULL << 35;
1075d88c1a5aSDimitry Andric   case Attribute::SanitizeThread:  return 1ULL << 36;
1076d88c1a5aSDimitry Andric   case Attribute::SanitizeMemory:  return 1ULL << 37;
1077d88c1a5aSDimitry Andric   case Attribute::NoBuiltin:       return 1ULL << 38;
1078d88c1a5aSDimitry Andric   case Attribute::Returned:        return 1ULL << 39;
1079d88c1a5aSDimitry Andric   case Attribute::Cold:            return 1ULL << 40;
1080d88c1a5aSDimitry Andric   case Attribute::Builtin:         return 1ULL << 41;
1081d88c1a5aSDimitry Andric   case Attribute::OptimizeNone:    return 1ULL << 42;
1082d88c1a5aSDimitry Andric   case Attribute::InAlloca:        return 1ULL << 43;
1083d88c1a5aSDimitry Andric   case Attribute::NonNull:         return 1ULL << 44;
1084d88c1a5aSDimitry Andric   case Attribute::JumpTable:       return 1ULL << 45;
1085d88c1a5aSDimitry Andric   case Attribute::Convergent:      return 1ULL << 46;
1086d88c1a5aSDimitry Andric   case Attribute::SafeStack:       return 1ULL << 47;
1087d88c1a5aSDimitry Andric   case Attribute::NoRecurse:       return 1ULL << 48;
1088d88c1a5aSDimitry Andric   case Attribute::InaccessibleMemOnly:         return 1ULL << 49;
1089d88c1a5aSDimitry Andric   case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1090d88c1a5aSDimitry Andric   case Attribute::SwiftSelf:       return 1ULL << 51;
1091d88c1a5aSDimitry Andric   case Attribute::SwiftError:      return 1ULL << 52;
1092d88c1a5aSDimitry Andric   case Attribute::WriteOnly:       return 1ULL << 53;
1093d88c1a5aSDimitry Andric   case Attribute::Dereferenceable:
1094d88c1a5aSDimitry Andric     llvm_unreachable("dereferenceable attribute not supported in raw format");
1095d88c1a5aSDimitry Andric     break;
1096d88c1a5aSDimitry Andric   case Attribute::DereferenceableOrNull:
1097d88c1a5aSDimitry Andric     llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1098d88c1a5aSDimitry Andric                      "format");
1099d88c1a5aSDimitry Andric     break;
1100d88c1a5aSDimitry Andric   case Attribute::ArgMemOnly:
1101d88c1a5aSDimitry Andric     llvm_unreachable("argmemonly attribute not supported in raw format");
1102d88c1a5aSDimitry Andric     break;
1103d88c1a5aSDimitry Andric   case Attribute::AllocSize:
1104d88c1a5aSDimitry Andric     llvm_unreachable("allocsize not supported in raw format");
1105d88c1a5aSDimitry Andric     break;
1106d88c1a5aSDimitry Andric   }
1107d88c1a5aSDimitry Andric   llvm_unreachable("Unsupported attribute type");
1108d88c1a5aSDimitry Andric }
1109d88c1a5aSDimitry Andric 
1110d88c1a5aSDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1111d88c1a5aSDimitry Andric   if (!Val) return;
1112d88c1a5aSDimitry Andric 
1113d88c1a5aSDimitry Andric   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1114d88c1a5aSDimitry Andric        I = Attribute::AttrKind(I + 1)) {
1115d88c1a5aSDimitry Andric     if (I == Attribute::Dereferenceable ||
1116d88c1a5aSDimitry Andric         I == Attribute::DereferenceableOrNull ||
1117d88c1a5aSDimitry Andric         I == Attribute::ArgMemOnly ||
1118d88c1a5aSDimitry Andric         I == Attribute::AllocSize)
1119d88c1a5aSDimitry Andric       continue;
1120d88c1a5aSDimitry Andric     if (uint64_t A = (Val & getRawAttributeMask(I))) {
1121d88c1a5aSDimitry Andric       if (I == Attribute::Alignment)
1122d88c1a5aSDimitry Andric         B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1123d88c1a5aSDimitry Andric       else if (I == Attribute::StackAlignment)
1124d88c1a5aSDimitry Andric         B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1125d88c1a5aSDimitry Andric       else
1126d88c1a5aSDimitry Andric         B.addAttribute(I);
1127d88c1a5aSDimitry Andric     }
1128d88c1a5aSDimitry Andric   }
1129d88c1a5aSDimitry Andric }
1130139f7f9bSDimitry Andric 
1131139f7f9bSDimitry Andric /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1132139f7f9bSDimitry Andric /// been decoded from the given integer. This function must stay in sync with
1133139f7f9bSDimitry Andric /// 'encodeLLVMAttributesForBitcode'.
1134139f7f9bSDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1135139f7f9bSDimitry Andric                                            uint64_t EncodedAttrs) {
1136139f7f9bSDimitry Andric   // FIXME: Remove in 4.0.
1137139f7f9bSDimitry Andric 
1138139f7f9bSDimitry Andric   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
1139139f7f9bSDimitry Andric   // the bits above 31 down by 11 bits.
1140139f7f9bSDimitry Andric   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1141139f7f9bSDimitry Andric   assert((!Alignment || isPowerOf2_32(Alignment)) &&
1142139f7f9bSDimitry Andric          "Alignment must be a power of two.");
1143139f7f9bSDimitry Andric 
1144139f7f9bSDimitry Andric   if (Alignment)
1145139f7f9bSDimitry Andric     B.addAlignmentAttr(Alignment);
1146d88c1a5aSDimitry Andric   addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1147139f7f9bSDimitry Andric                           (EncodedAttrs & 0xffff));
1148139f7f9bSDimitry Andric }
1149139f7f9bSDimitry Andric 
1150d88c1a5aSDimitry Andric Error BitcodeReader::parseAttributeBlock() {
1151f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
11528f0fd8f6SDimitry Andric     return error("Invalid record");
1153f22ef01cSRoman Divacky 
1154f22ef01cSRoman Divacky   if (!MAttributes.empty())
11558f0fd8f6SDimitry Andric     return error("Invalid multiple blocks");
1156f22ef01cSRoman Divacky 
1157f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
1158f22ef01cSRoman Divacky 
11597a7e6055SDimitry Andric   SmallVector<AttributeList, 8> Attrs;
1160f22ef01cSRoman Divacky 
1161f22ef01cSRoman Divacky   // Read all the records.
1162d88c1a5aSDimitry Andric   while (true) {
1163139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1164139f7f9bSDimitry Andric 
1165139f7f9bSDimitry Andric     switch (Entry.Kind) {
1166139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1167139f7f9bSDimitry Andric     case BitstreamEntry::Error:
11688f0fd8f6SDimitry Andric       return error("Malformed block");
1169139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
1170d88c1a5aSDimitry Andric       return Error::success();
1171139f7f9bSDimitry Andric     case BitstreamEntry::Record:
1172139f7f9bSDimitry Andric       // The interesting case.
1173139f7f9bSDimitry Andric       break;
1174f22ef01cSRoman Divacky     }
1175f22ef01cSRoman Divacky 
1176f22ef01cSRoman Divacky     // Read a record.
1177f22ef01cSRoman Divacky     Record.clear();
1178139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
1179f22ef01cSRoman Divacky     default:  // Default behavior: ignore.
1180f22ef01cSRoman Divacky       break;
1181139f7f9bSDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1182139f7f9bSDimitry Andric       // FIXME: Remove in 4.0.
1183f22ef01cSRoman Divacky       if (Record.size() & 1)
11848f0fd8f6SDimitry Andric         return error("Invalid record");
1185f22ef01cSRoman Divacky 
1186f22ef01cSRoman Divacky       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1187139f7f9bSDimitry Andric         AttrBuilder B;
1188139f7f9bSDimitry Andric         decodeLLVMAttributesForBitcode(B, Record[i+1]);
11897a7e6055SDimitry Andric         Attrs.push_back(AttributeList::get(Context, Record[i], B));
1190f22ef01cSRoman Divacky       }
1191f22ef01cSRoman Divacky 
11927a7e6055SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
1193f22ef01cSRoman Divacky       Attrs.clear();
1194f22ef01cSRoman Divacky       break;
1195f22ef01cSRoman Divacky     }
1196139f7f9bSDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1197139f7f9bSDimitry Andric       for (unsigned i = 0, e = Record.size(); i != e; ++i)
1198139f7f9bSDimitry Andric         Attrs.push_back(MAttributeGroups[Record[i]]);
1199139f7f9bSDimitry Andric 
12007a7e6055SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
1201139f7f9bSDimitry Andric       Attrs.clear();
1202139f7f9bSDimitry Andric       break;
1203139f7f9bSDimitry Andric     }
1204139f7f9bSDimitry Andric     }
1205139f7f9bSDimitry Andric   }
1206139f7f9bSDimitry Andric }
1207139f7f9bSDimitry Andric 
1208f785676fSDimitry Andric // Returns Attribute::None on unrecognized codes.
12098f0fd8f6SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1210f785676fSDimitry Andric   switch (Code) {
1211f785676fSDimitry Andric   default:
1212f785676fSDimitry Andric     return Attribute::None;
1213f785676fSDimitry Andric   case bitc::ATTR_KIND_ALIGNMENT:
1214f785676fSDimitry Andric     return Attribute::Alignment;
1215f785676fSDimitry Andric   case bitc::ATTR_KIND_ALWAYS_INLINE:
1216f785676fSDimitry Andric     return Attribute::AlwaysInline;
1217875ed548SDimitry Andric   case bitc::ATTR_KIND_ARGMEMONLY:
1218875ed548SDimitry Andric     return Attribute::ArgMemOnly;
1219f785676fSDimitry Andric   case bitc::ATTR_KIND_BUILTIN:
1220f785676fSDimitry Andric     return Attribute::Builtin;
1221f785676fSDimitry Andric   case bitc::ATTR_KIND_BY_VAL:
1222f785676fSDimitry Andric     return Attribute::ByVal;
122391bc56edSDimitry Andric   case bitc::ATTR_KIND_IN_ALLOCA:
122491bc56edSDimitry Andric     return Attribute::InAlloca;
1225f785676fSDimitry Andric   case bitc::ATTR_KIND_COLD:
1226f785676fSDimitry Andric     return Attribute::Cold;
1227ff0cc061SDimitry Andric   case bitc::ATTR_KIND_CONVERGENT:
1228ff0cc061SDimitry Andric     return Attribute::Convergent;
12297d523365SDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
12307d523365SDimitry Andric     return Attribute::InaccessibleMemOnly;
12317d523365SDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
12327d523365SDimitry Andric     return Attribute::InaccessibleMemOrArgMemOnly;
1233f785676fSDimitry Andric   case bitc::ATTR_KIND_INLINE_HINT:
1234f785676fSDimitry Andric     return Attribute::InlineHint;
1235f785676fSDimitry Andric   case bitc::ATTR_KIND_IN_REG:
1236f785676fSDimitry Andric     return Attribute::InReg;
123791bc56edSDimitry Andric   case bitc::ATTR_KIND_JUMP_TABLE:
123891bc56edSDimitry Andric     return Attribute::JumpTable;
1239f785676fSDimitry Andric   case bitc::ATTR_KIND_MIN_SIZE:
1240f785676fSDimitry Andric     return Attribute::MinSize;
1241f785676fSDimitry Andric   case bitc::ATTR_KIND_NAKED:
1242f785676fSDimitry Andric     return Attribute::Naked;
1243f785676fSDimitry Andric   case bitc::ATTR_KIND_NEST:
1244f785676fSDimitry Andric     return Attribute::Nest;
1245f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_ALIAS:
1246f785676fSDimitry Andric     return Attribute::NoAlias;
1247f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_BUILTIN:
1248f785676fSDimitry Andric     return Attribute::NoBuiltin;
1249f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_CAPTURE:
1250f785676fSDimitry Andric     return Attribute::NoCapture;
1251f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_DUPLICATE:
1252f785676fSDimitry Andric     return Attribute::NoDuplicate;
1253f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1254f785676fSDimitry Andric     return Attribute::NoImplicitFloat;
1255f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_INLINE:
1256f785676fSDimitry Andric     return Attribute::NoInline;
12577d523365SDimitry Andric   case bitc::ATTR_KIND_NO_RECURSE:
12587d523365SDimitry Andric     return Attribute::NoRecurse;
1259f785676fSDimitry Andric   case bitc::ATTR_KIND_NON_LAZY_BIND:
1260f785676fSDimitry Andric     return Attribute::NonLazyBind;
126191bc56edSDimitry Andric   case bitc::ATTR_KIND_NON_NULL:
126291bc56edSDimitry Andric     return Attribute::NonNull;
126391bc56edSDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE:
126491bc56edSDimitry Andric     return Attribute::Dereferenceable;
1265ff0cc061SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1266ff0cc061SDimitry Andric     return Attribute::DereferenceableOrNull;
12673ca95b02SDimitry Andric   case bitc::ATTR_KIND_ALLOC_SIZE:
12683ca95b02SDimitry Andric     return Attribute::AllocSize;
1269f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_RED_ZONE:
1270f785676fSDimitry Andric     return Attribute::NoRedZone;
1271f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_RETURN:
1272f785676fSDimitry Andric     return Attribute::NoReturn;
1273f785676fSDimitry Andric   case bitc::ATTR_KIND_NO_UNWIND:
1274f785676fSDimitry Andric     return Attribute::NoUnwind;
1275f785676fSDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1276f785676fSDimitry Andric     return Attribute::OptimizeForSize;
1277f785676fSDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_NONE:
1278f785676fSDimitry Andric     return Attribute::OptimizeNone;
1279f785676fSDimitry Andric   case bitc::ATTR_KIND_READ_NONE:
1280f785676fSDimitry Andric     return Attribute::ReadNone;
1281f785676fSDimitry Andric   case bitc::ATTR_KIND_READ_ONLY:
1282f785676fSDimitry Andric     return Attribute::ReadOnly;
1283f785676fSDimitry Andric   case bitc::ATTR_KIND_RETURNED:
1284f785676fSDimitry Andric     return Attribute::Returned;
1285f785676fSDimitry Andric   case bitc::ATTR_KIND_RETURNS_TWICE:
1286f785676fSDimitry Andric     return Attribute::ReturnsTwice;
1287f785676fSDimitry Andric   case bitc::ATTR_KIND_S_EXT:
1288f785676fSDimitry Andric     return Attribute::SExt;
1289f785676fSDimitry Andric   case bitc::ATTR_KIND_STACK_ALIGNMENT:
1290f785676fSDimitry Andric     return Attribute::StackAlignment;
1291f785676fSDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT:
1292f785676fSDimitry Andric     return Attribute::StackProtect;
1293f785676fSDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1294f785676fSDimitry Andric     return Attribute::StackProtectReq;
1295f785676fSDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1296f785676fSDimitry Andric     return Attribute::StackProtectStrong;
12978f0fd8f6SDimitry Andric   case bitc::ATTR_KIND_SAFESTACK:
12988f0fd8f6SDimitry Andric     return Attribute::SafeStack;
1299f785676fSDimitry Andric   case bitc::ATTR_KIND_STRUCT_RET:
1300f785676fSDimitry Andric     return Attribute::StructRet;
1301f785676fSDimitry Andric   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1302f785676fSDimitry Andric     return Attribute::SanitizeAddress;
1303f785676fSDimitry Andric   case bitc::ATTR_KIND_SANITIZE_THREAD:
1304f785676fSDimitry Andric     return Attribute::SanitizeThread;
1305f785676fSDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMORY:
1306f785676fSDimitry Andric     return Attribute::SanitizeMemory;
13073ca95b02SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ERROR:
13083ca95b02SDimitry Andric     return Attribute::SwiftError;
13093ca95b02SDimitry Andric   case bitc::ATTR_KIND_SWIFT_SELF:
13103ca95b02SDimitry Andric     return Attribute::SwiftSelf;
1311f785676fSDimitry Andric   case bitc::ATTR_KIND_UW_TABLE:
1312f785676fSDimitry Andric     return Attribute::UWTable;
13133ca95b02SDimitry Andric   case bitc::ATTR_KIND_WRITEONLY:
13143ca95b02SDimitry Andric     return Attribute::WriteOnly;
1315f785676fSDimitry Andric   case bitc::ATTR_KIND_Z_EXT:
1316f785676fSDimitry Andric     return Attribute::ZExt;
1317f785676fSDimitry Andric   }
1318f785676fSDimitry Andric }
1319f785676fSDimitry Andric 
1320d88c1a5aSDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1321ff0cc061SDimitry Andric                                          unsigned &Alignment) {
1322ff0cc061SDimitry Andric   // Note: Alignment in bitcode files is incremented by 1, so that zero
1323ff0cc061SDimitry Andric   // can be used for default alignment.
1324ff0cc061SDimitry Andric   if (Exponent > Value::MaxAlignmentExponent + 1)
13258f0fd8f6SDimitry Andric     return error("Invalid alignment value");
1326ff0cc061SDimitry Andric   Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1327d88c1a5aSDimitry Andric   return Error::success();
1328ff0cc061SDimitry Andric }
1329ff0cc061SDimitry Andric 
1330d88c1a5aSDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
13318f0fd8f6SDimitry Andric   *Kind = getAttrFromCode(Code);
1332f785676fSDimitry Andric   if (*Kind == Attribute::None)
1333d88c1a5aSDimitry Andric     return error("Unknown attribute kind (" + Twine(Code) + ")");
1334d88c1a5aSDimitry Andric   return Error::success();
1335f785676fSDimitry Andric }
1336f785676fSDimitry Andric 
1337d88c1a5aSDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() {
1338139f7f9bSDimitry Andric   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
13398f0fd8f6SDimitry Andric     return error("Invalid record");
1340139f7f9bSDimitry Andric 
1341139f7f9bSDimitry Andric   if (!MAttributeGroups.empty())
13428f0fd8f6SDimitry Andric     return error("Invalid multiple blocks");
1343139f7f9bSDimitry Andric 
1344139f7f9bSDimitry Andric   SmallVector<uint64_t, 64> Record;
1345139f7f9bSDimitry Andric 
1346139f7f9bSDimitry Andric   // Read all the records.
1347d88c1a5aSDimitry Andric   while (true) {
1348139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1349139f7f9bSDimitry Andric 
1350139f7f9bSDimitry Andric     switch (Entry.Kind) {
1351139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1352139f7f9bSDimitry Andric     case BitstreamEntry::Error:
13538f0fd8f6SDimitry Andric       return error("Malformed block");
1354139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
1355d88c1a5aSDimitry Andric       return Error::success();
1356139f7f9bSDimitry Andric     case BitstreamEntry::Record:
1357139f7f9bSDimitry Andric       // The interesting case.
1358139f7f9bSDimitry Andric       break;
1359139f7f9bSDimitry Andric     }
1360139f7f9bSDimitry Andric 
1361139f7f9bSDimitry Andric     // Read a record.
1362139f7f9bSDimitry Andric     Record.clear();
1363139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
1364139f7f9bSDimitry Andric     default:  // Default behavior: ignore.
1365139f7f9bSDimitry Andric       break;
1366139f7f9bSDimitry Andric     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1367139f7f9bSDimitry Andric       if (Record.size() < 3)
13688f0fd8f6SDimitry Andric         return error("Invalid record");
1369139f7f9bSDimitry Andric 
1370139f7f9bSDimitry Andric       uint64_t GrpID = Record[0];
1371139f7f9bSDimitry Andric       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1372139f7f9bSDimitry Andric 
1373139f7f9bSDimitry Andric       AttrBuilder B;
1374139f7f9bSDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1375139f7f9bSDimitry Andric         if (Record[i] == 0) {        // Enum attribute
1376f785676fSDimitry Andric           Attribute::AttrKind Kind;
1377d88c1a5aSDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
1378d88c1a5aSDimitry Andric             return Err;
1379f785676fSDimitry Andric 
1380f785676fSDimitry Andric           B.addAttribute(Kind);
138191bc56edSDimitry Andric         } else if (Record[i] == 1) { // Integer attribute
1382f785676fSDimitry Andric           Attribute::AttrKind Kind;
1383d88c1a5aSDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
1384d88c1a5aSDimitry Andric             return Err;
1385f785676fSDimitry Andric           if (Kind == Attribute::Alignment)
1386139f7f9bSDimitry Andric             B.addAlignmentAttr(Record[++i]);
138791bc56edSDimitry Andric           else if (Kind == Attribute::StackAlignment)
1388139f7f9bSDimitry Andric             B.addStackAlignmentAttr(Record[++i]);
138991bc56edSDimitry Andric           else if (Kind == Attribute::Dereferenceable)
139091bc56edSDimitry Andric             B.addDereferenceableAttr(Record[++i]);
1391ff0cc061SDimitry Andric           else if (Kind == Attribute::DereferenceableOrNull)
1392ff0cc061SDimitry Andric             B.addDereferenceableOrNullAttr(Record[++i]);
13933ca95b02SDimitry Andric           else if (Kind == Attribute::AllocSize)
13943ca95b02SDimitry Andric             B.addAllocSizeAttrFromRawRepr(Record[++i]);
1395139f7f9bSDimitry Andric         } else {                     // String attribute
1396139f7f9bSDimitry Andric           assert((Record[i] == 3 || Record[i] == 4) &&
1397139f7f9bSDimitry Andric                  "Invalid attribute group entry");
1398139f7f9bSDimitry Andric           bool HasValue = (Record[i++] == 4);
1399139f7f9bSDimitry Andric           SmallString<64> KindStr;
1400139f7f9bSDimitry Andric           SmallString<64> ValStr;
1401139f7f9bSDimitry Andric 
1402139f7f9bSDimitry Andric           while (Record[i] != 0 && i != e)
1403139f7f9bSDimitry Andric             KindStr += Record[i++];
1404139f7f9bSDimitry Andric           assert(Record[i] == 0 && "Kind string not null terminated");
1405139f7f9bSDimitry Andric 
1406139f7f9bSDimitry Andric           if (HasValue) {
1407139f7f9bSDimitry Andric             // Has a value associated with it.
1408139f7f9bSDimitry Andric             ++i; // Skip the '0' that terminates the "kind" string.
1409139f7f9bSDimitry Andric             while (Record[i] != 0 && i != e)
1410139f7f9bSDimitry Andric               ValStr += Record[i++];
1411139f7f9bSDimitry Andric             assert(Record[i] == 0 && "Value string not null terminated");
1412139f7f9bSDimitry Andric           }
1413139f7f9bSDimitry Andric 
1414139f7f9bSDimitry Andric           B.addAttribute(KindStr.str(), ValStr.str());
1415139f7f9bSDimitry Andric         }
1416139f7f9bSDimitry Andric       }
1417139f7f9bSDimitry Andric 
14187a7e6055SDimitry Andric       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
1419139f7f9bSDimitry Andric       break;
1420139f7f9bSDimitry Andric     }
1421f22ef01cSRoman Divacky     }
1422f22ef01cSRoman Divacky   }
1423f22ef01cSRoman Divacky }
1424f22ef01cSRoman Divacky 
1425d88c1a5aSDimitry Andric Error BitcodeReader::parseTypeTable() {
142617a519f9SDimitry Andric   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
14278f0fd8f6SDimitry Andric     return error("Invalid record");
1428f22ef01cSRoman Divacky 
14298f0fd8f6SDimitry Andric   return parseTypeTableBody();
143017a519f9SDimitry Andric }
143117a519f9SDimitry Andric 
1432d88c1a5aSDimitry Andric Error BitcodeReader::parseTypeTableBody() {
1433f22ef01cSRoman Divacky   if (!TypeList.empty())
14348f0fd8f6SDimitry Andric     return error("Invalid multiple blocks");
1435f22ef01cSRoman Divacky 
1436f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
1437f22ef01cSRoman Divacky   unsigned NumRecords = 0;
1438f22ef01cSRoman Divacky 
143917a519f9SDimitry Andric   SmallString<64> TypeName;
144017a519f9SDimitry Andric 
1441f22ef01cSRoman Divacky   // Read all the records for this type table.
1442d88c1a5aSDimitry Andric   while (true) {
1443139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1444139f7f9bSDimitry Andric 
1445139f7f9bSDimitry Andric     switch (Entry.Kind) {
1446139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1447139f7f9bSDimitry Andric     case BitstreamEntry::Error:
14488f0fd8f6SDimitry Andric       return error("Malformed block");
1449139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
1450f22ef01cSRoman Divacky       if (NumRecords != TypeList.size())
14518f0fd8f6SDimitry Andric         return error("Malformed block");
1452d88c1a5aSDimitry Andric       return Error::success();
1453139f7f9bSDimitry Andric     case BitstreamEntry::Record:
1454139f7f9bSDimitry Andric       // The interesting case.
1455139f7f9bSDimitry Andric       break;
1456f22ef01cSRoman Divacky     }
1457f22ef01cSRoman Divacky 
1458f22ef01cSRoman Divacky     // Read a record.
1459f22ef01cSRoman Divacky     Record.clear();
146091bc56edSDimitry Andric     Type *ResultTy = nullptr;
1461139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
1462f785676fSDimitry Andric     default:
14638f0fd8f6SDimitry Andric       return error("Invalid value");
1464f22ef01cSRoman Divacky     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1465f22ef01cSRoman Divacky       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1466f22ef01cSRoman Divacky       // type list.  This allows us to reserve space.
1467f22ef01cSRoman Divacky       if (Record.size() < 1)
14688f0fd8f6SDimitry Andric         return error("Invalid record");
146917a519f9SDimitry Andric       TypeList.resize(Record[0]);
1470f22ef01cSRoman Divacky       continue;
1471f22ef01cSRoman Divacky     case bitc::TYPE_CODE_VOID:      // VOID
1472f22ef01cSRoman Divacky       ResultTy = Type::getVoidTy(Context);
1473f22ef01cSRoman Divacky       break;
1474dff0c46cSDimitry Andric     case bitc::TYPE_CODE_HALF:     // HALF
1475dff0c46cSDimitry Andric       ResultTy = Type::getHalfTy(Context);
1476dff0c46cSDimitry Andric       break;
1477f22ef01cSRoman Divacky     case bitc::TYPE_CODE_FLOAT:     // FLOAT
1478f22ef01cSRoman Divacky       ResultTy = Type::getFloatTy(Context);
1479f22ef01cSRoman Divacky       break;
1480f22ef01cSRoman Divacky     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
1481f22ef01cSRoman Divacky       ResultTy = Type::getDoubleTy(Context);
1482f22ef01cSRoman Divacky       break;
1483f22ef01cSRoman Divacky     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
1484f22ef01cSRoman Divacky       ResultTy = Type::getX86_FP80Ty(Context);
1485f22ef01cSRoman Divacky       break;
1486f22ef01cSRoman Divacky     case bitc::TYPE_CODE_FP128:     // FP128
1487f22ef01cSRoman Divacky       ResultTy = Type::getFP128Ty(Context);
1488f22ef01cSRoman Divacky       break;
1489f22ef01cSRoman Divacky     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1490f22ef01cSRoman Divacky       ResultTy = Type::getPPC_FP128Ty(Context);
1491f22ef01cSRoman Divacky       break;
1492f22ef01cSRoman Divacky     case bitc::TYPE_CODE_LABEL:     // LABEL
1493f22ef01cSRoman Divacky       ResultTy = Type::getLabelTy(Context);
1494f22ef01cSRoman Divacky       break;
1495f22ef01cSRoman Divacky     case bitc::TYPE_CODE_METADATA:  // METADATA
1496f22ef01cSRoman Divacky       ResultTy = Type::getMetadataTy(Context);
1497f22ef01cSRoman Divacky       break;
14982754fe60SDimitry Andric     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
14992754fe60SDimitry Andric       ResultTy = Type::getX86_MMXTy(Context);
15002754fe60SDimitry Andric       break;
15017d523365SDimitry Andric     case bitc::TYPE_CODE_TOKEN:     // TOKEN
15027d523365SDimitry Andric       ResultTy = Type::getTokenTy(Context);
15037d523365SDimitry Andric       break;
1504ff0cc061SDimitry Andric     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1505f22ef01cSRoman Divacky       if (Record.size() < 1)
15068f0fd8f6SDimitry Andric         return error("Invalid record");
1507f22ef01cSRoman Divacky 
1508ff0cc061SDimitry Andric       uint64_t NumBits = Record[0];
1509ff0cc061SDimitry Andric       if (NumBits < IntegerType::MIN_INT_BITS ||
1510ff0cc061SDimitry Andric           NumBits > IntegerType::MAX_INT_BITS)
15118f0fd8f6SDimitry Andric         return error("Bitwidth for integer type out of range");
1512ff0cc061SDimitry Andric       ResultTy = IntegerType::get(Context, NumBits);
1513f22ef01cSRoman Divacky       break;
1514ff0cc061SDimitry Andric     }
1515f22ef01cSRoman Divacky     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1516f22ef01cSRoman Divacky                                     //          [pointee type, address space]
1517f22ef01cSRoman Divacky       if (Record.size() < 1)
15188f0fd8f6SDimitry Andric         return error("Invalid record");
1519f22ef01cSRoman Divacky       unsigned AddressSpace = 0;
1520f22ef01cSRoman Divacky       if (Record.size() == 2)
1521f22ef01cSRoman Divacky         AddressSpace = Record[1];
152217a519f9SDimitry Andric       ResultTy = getTypeByID(Record[0]);
1523ff0cc061SDimitry Andric       if (!ResultTy ||
1524ff0cc061SDimitry Andric           !PointerType::isValidElementType(ResultTy))
15258f0fd8f6SDimitry Andric         return error("Invalid type");
152617a519f9SDimitry Andric       ResultTy = PointerType::get(ResultTy, AddressSpace);
1527f22ef01cSRoman Divacky       break;
1528f22ef01cSRoman Divacky     }
1529dff0c46cSDimitry Andric     case bitc::TYPE_CODE_FUNCTION_OLD: {
15307ae0e2c9SDimitry Andric       // FIXME: attrid is dead, remove it in LLVM 4.0
1531f22ef01cSRoman Divacky       // FUNCTION: [vararg, attrid, retty, paramty x N]
1532f22ef01cSRoman Divacky       if (Record.size() < 3)
15338f0fd8f6SDimitry Andric         return error("Invalid record");
1534dff0c46cSDimitry Andric       SmallVector<Type*, 8> ArgTys;
153517a519f9SDimitry Andric       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
153617a519f9SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
153717a519f9SDimitry Andric           ArgTys.push_back(T);
153817a519f9SDimitry Andric         else
1539f22ef01cSRoman Divacky           break;
1540f22ef01cSRoman Divacky       }
154117a519f9SDimitry Andric 
154217a519f9SDimitry Andric       ResultTy = getTypeByID(Record[2]);
154391bc56edSDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-3)
15448f0fd8f6SDimitry Andric         return error("Invalid type");
154517a519f9SDimitry Andric 
154617a519f9SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
154717a519f9SDimitry Andric       break;
154817a519f9SDimitry Andric     }
1549dff0c46cSDimitry Andric     case bitc::TYPE_CODE_FUNCTION: {
1550dff0c46cSDimitry Andric       // FUNCTION: [vararg, retty, paramty x N]
1551dff0c46cSDimitry Andric       if (Record.size() < 2)
15528f0fd8f6SDimitry Andric         return error("Invalid record");
1553dff0c46cSDimitry Andric       SmallVector<Type*, 8> ArgTys;
1554dff0c46cSDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1555ff0cc061SDimitry Andric         if (Type *T = getTypeByID(Record[i])) {
1556ff0cc061SDimitry Andric           if (!FunctionType::isValidArgumentType(T))
15578f0fd8f6SDimitry Andric             return error("Invalid function argument type");
1558dff0c46cSDimitry Andric           ArgTys.push_back(T);
1559ff0cc061SDimitry Andric         }
1560dff0c46cSDimitry Andric         else
1561dff0c46cSDimitry Andric           break;
1562dff0c46cSDimitry Andric       }
1563dff0c46cSDimitry Andric 
1564dff0c46cSDimitry Andric       ResultTy = getTypeByID(Record[1]);
156591bc56edSDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-2)
15668f0fd8f6SDimitry Andric         return error("Invalid type");
1567dff0c46cSDimitry Andric 
1568dff0c46cSDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1569dff0c46cSDimitry Andric       break;
1570dff0c46cSDimitry Andric     }
157117a519f9SDimitry Andric     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1572f22ef01cSRoman Divacky       if (Record.size() < 1)
15738f0fd8f6SDimitry Andric         return error("Invalid record");
1574dff0c46cSDimitry Andric       SmallVector<Type*, 8> EltTys;
157517a519f9SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
157617a519f9SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
157717a519f9SDimitry Andric           EltTys.push_back(T);
157817a519f9SDimitry Andric         else
157917a519f9SDimitry Andric           break;
158017a519f9SDimitry Andric       }
158117a519f9SDimitry Andric       if (EltTys.size() != Record.size()-1)
15828f0fd8f6SDimitry Andric         return error("Invalid type");
1583f22ef01cSRoman Divacky       ResultTy = StructType::get(Context, EltTys, Record[0]);
1584f22ef01cSRoman Divacky       break;
1585f22ef01cSRoman Divacky     }
158617a519f9SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
15878f0fd8f6SDimitry Andric       if (convertToString(Record, 0, TypeName))
15888f0fd8f6SDimitry Andric         return error("Invalid record");
158917a519f9SDimitry Andric       continue;
159017a519f9SDimitry Andric 
159117a519f9SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
159217a519f9SDimitry Andric       if (Record.size() < 1)
15938f0fd8f6SDimitry Andric         return error("Invalid record");
159417a519f9SDimitry Andric 
159517a519f9SDimitry Andric       if (NumRecords >= TypeList.size())
15968f0fd8f6SDimitry Andric         return error("Invalid TYPE table");
159717a519f9SDimitry Andric 
159817a519f9SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
159917a519f9SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
160017a519f9SDimitry Andric       if (Res) {
160117a519f9SDimitry Andric         Res->setName(TypeName);
160291bc56edSDimitry Andric         TypeList[NumRecords] = nullptr;
160317a519f9SDimitry Andric       } else  // Otherwise, create a new struct.
160439d628a0SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
160517a519f9SDimitry Andric       TypeName.clear();
160617a519f9SDimitry Andric 
160717a519f9SDimitry Andric       SmallVector<Type*, 8> EltTys;
160817a519f9SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
160917a519f9SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
161017a519f9SDimitry Andric           EltTys.push_back(T);
161117a519f9SDimitry Andric         else
161217a519f9SDimitry Andric           break;
161317a519f9SDimitry Andric       }
161417a519f9SDimitry Andric       if (EltTys.size() != Record.size()-1)
16158f0fd8f6SDimitry Andric         return error("Invalid record");
161617a519f9SDimitry Andric       Res->setBody(EltTys, Record[0]);
161717a519f9SDimitry Andric       ResultTy = Res;
161817a519f9SDimitry Andric       break;
161917a519f9SDimitry Andric     }
162017a519f9SDimitry Andric     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
162117a519f9SDimitry Andric       if (Record.size() != 1)
16228f0fd8f6SDimitry Andric         return error("Invalid record");
162317a519f9SDimitry Andric 
162417a519f9SDimitry Andric       if (NumRecords >= TypeList.size())
16258f0fd8f6SDimitry Andric         return error("Invalid TYPE table");
162617a519f9SDimitry Andric 
162717a519f9SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
162817a519f9SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
162917a519f9SDimitry Andric       if (Res) {
163017a519f9SDimitry Andric         Res->setName(TypeName);
163191bc56edSDimitry Andric         TypeList[NumRecords] = nullptr;
163217a519f9SDimitry Andric       } else  // Otherwise, create a new struct with no body.
163339d628a0SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
163417a519f9SDimitry Andric       TypeName.clear();
163517a519f9SDimitry Andric       ResultTy = Res;
163617a519f9SDimitry Andric       break;
163717a519f9SDimitry Andric     }
1638f22ef01cSRoman Divacky     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1639f22ef01cSRoman Divacky       if (Record.size() < 2)
16408f0fd8f6SDimitry Andric         return error("Invalid record");
1641ff0cc061SDimitry Andric       ResultTy = getTypeByID(Record[1]);
1642ff0cc061SDimitry Andric       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
16438f0fd8f6SDimitry Andric         return error("Invalid type");
1644ff0cc061SDimitry Andric       ResultTy = ArrayType::get(ResultTy, Record[0]);
1645f22ef01cSRoman Divacky       break;
1646f22ef01cSRoman Divacky     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
1647f22ef01cSRoman Divacky       if (Record.size() < 2)
16488f0fd8f6SDimitry Andric         return error("Invalid record");
164997bc6c73SDimitry Andric       if (Record[0] == 0)
16508f0fd8f6SDimitry Andric         return error("Invalid vector length");
1651ff0cc061SDimitry Andric       ResultTy = getTypeByID(Record[1]);
1652ff0cc061SDimitry Andric       if (!ResultTy || !StructType::isValidElementType(ResultTy))
16538f0fd8f6SDimitry Andric         return error("Invalid type");
1654ff0cc061SDimitry Andric       ResultTy = VectorType::get(ResultTy, Record[0]);
1655f22ef01cSRoman Divacky       break;
1656f22ef01cSRoman Divacky     }
1657f22ef01cSRoman Divacky 
165817a519f9SDimitry Andric     if (NumRecords >= TypeList.size())
16598f0fd8f6SDimitry Andric       return error("Invalid TYPE table");
1660ff0cc061SDimitry Andric     if (TypeList[NumRecords])
16618f0fd8f6SDimitry Andric       return error(
1662ff0cc061SDimitry Andric           "Invalid TYPE table: Only named structs can be forward referenced");
166317a519f9SDimitry Andric     assert(ResultTy && "Didn't read a type?");
166417a519f9SDimitry Andric     TypeList[NumRecords++] = ResultTy;
1665f22ef01cSRoman Divacky   }
1666f22ef01cSRoman Divacky }
166717a519f9SDimitry Andric 
1668d88c1a5aSDimitry Andric Error BitcodeReader::parseOperandBundleTags() {
16697d523365SDimitry Andric   if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
16707d523365SDimitry Andric     return error("Invalid record");
16717d523365SDimitry Andric 
16727d523365SDimitry Andric   if (!BundleTags.empty())
16737d523365SDimitry Andric     return error("Invalid multiple blocks");
16747d523365SDimitry Andric 
16757d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
16767d523365SDimitry Andric 
1677d88c1a5aSDimitry Andric   while (true) {
16787d523365SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
16797d523365SDimitry Andric 
16807d523365SDimitry Andric     switch (Entry.Kind) {
16817d523365SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
16827d523365SDimitry Andric     case BitstreamEntry::Error:
16837d523365SDimitry Andric       return error("Malformed block");
16847d523365SDimitry Andric     case BitstreamEntry::EndBlock:
1685d88c1a5aSDimitry Andric       return Error::success();
16867d523365SDimitry Andric     case BitstreamEntry::Record:
16877d523365SDimitry Andric       // The interesting case.
16887d523365SDimitry Andric       break;
16897d523365SDimitry Andric     }
16907d523365SDimitry Andric 
16917d523365SDimitry Andric     // Tags are implicitly mapped to integers by their order.
16927d523365SDimitry Andric 
16937d523365SDimitry Andric     if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
16947d523365SDimitry Andric       return error("Invalid record");
16957d523365SDimitry Andric 
16967d523365SDimitry Andric     // OPERAND_BUNDLE_TAG: [strchr x N]
16977d523365SDimitry Andric     BundleTags.emplace_back();
16987d523365SDimitry Andric     if (convertToString(Record, 0, BundleTags.back()))
16997d523365SDimitry Andric       return error("Invalid record");
17007d523365SDimitry Andric     Record.clear();
17017d523365SDimitry Andric   }
17027d523365SDimitry Andric }
17037d523365SDimitry Andric 
17047d523365SDimitry Andric /// Associate a value with its name from the given index in the provided record.
1705d88c1a5aSDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
17067d523365SDimitry Andric                                              unsigned NameIndex, Triple &TT) {
17077d523365SDimitry Andric   SmallString<128> ValueName;
17087d523365SDimitry Andric   if (convertToString(Record, NameIndex, ValueName))
17097d523365SDimitry Andric     return error("Invalid record");
17107d523365SDimitry Andric   unsigned ValueID = Record[0];
17117d523365SDimitry Andric   if (ValueID >= ValueList.size() || !ValueList[ValueID])
17127d523365SDimitry Andric     return error("Invalid record");
17137d523365SDimitry Andric   Value *V = ValueList[ValueID];
17147d523365SDimitry Andric 
17157d523365SDimitry Andric   StringRef NameStr(ValueName.data(), ValueName.size());
17167d523365SDimitry Andric   if (NameStr.find_first_of(0) != StringRef::npos)
17177d523365SDimitry Andric     return error("Invalid value name");
17187d523365SDimitry Andric   V->setName(NameStr);
17197d523365SDimitry Andric   auto *GO = dyn_cast<GlobalObject>(V);
17207d523365SDimitry Andric   if (GO) {
17217d523365SDimitry Andric     if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
17227d523365SDimitry Andric       if (TT.isOSBinFormatMachO())
17237d523365SDimitry Andric         GO->setComdat(nullptr);
17247d523365SDimitry Andric       else
17257d523365SDimitry Andric         GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
17267d523365SDimitry Andric     }
17277d523365SDimitry Andric   }
17287d523365SDimitry Andric   return V;
17297d523365SDimitry Andric }
17307d523365SDimitry Andric 
17313ca95b02SDimitry Andric /// Helper to note and return the current location, and jump to the given
17323ca95b02SDimitry Andric /// offset.
17333ca95b02SDimitry Andric static uint64_t jumpToValueSymbolTable(uint64_t Offset,
17343ca95b02SDimitry Andric                                        BitstreamCursor &Stream) {
17357d523365SDimitry Andric   // Save the current parsing location so we can jump back at the end
17367d523365SDimitry Andric   // of the VST read.
17373ca95b02SDimitry Andric   uint64_t CurrentBit = Stream.GetCurrentBitNo();
17387d523365SDimitry Andric   Stream.JumpToBit(Offset * 32);
17397d523365SDimitry Andric #ifndef NDEBUG
17407d523365SDimitry Andric   // Do some checking if we are in debug mode.
17417d523365SDimitry Andric   BitstreamEntry Entry = Stream.advance();
17427d523365SDimitry Andric   assert(Entry.Kind == BitstreamEntry::SubBlock);
17437d523365SDimitry Andric   assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
17447d523365SDimitry Andric #else
17457d523365SDimitry Andric   // In NDEBUG mode ignore the output so we don't get an unused variable
17467d523365SDimitry Andric   // warning.
17477d523365SDimitry Andric   Stream.advance();
17487d523365SDimitry Andric #endif
17493ca95b02SDimitry Andric   return CurrentBit;
17507d523365SDimitry Andric }
17517d523365SDimitry Andric 
17523ca95b02SDimitry Andric /// Parse the value symbol table at either the current parsing location or
17533ca95b02SDimitry Andric /// at the given bit offset if provided.
1754d88c1a5aSDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
17553ca95b02SDimitry Andric   uint64_t CurrentBit;
17563ca95b02SDimitry Andric   // Pass in the Offset to distinguish between calling for the module-level
17573ca95b02SDimitry Andric   // VST (where we want to jump to the VST offset) and the function-level
17583ca95b02SDimitry Andric   // VST (where we don't).
17593ca95b02SDimitry Andric   if (Offset > 0)
17603ca95b02SDimitry Andric     CurrentBit = jumpToValueSymbolTable(Offset, Stream);
17613ca95b02SDimitry Andric 
17627d523365SDimitry Andric   // Compute the delta between the bitcode indices in the VST (the word offset
17637d523365SDimitry Andric   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
17647d523365SDimitry Andric   // expected by the lazy reader. The reader's EnterSubBlock expects to have
17657d523365SDimitry Andric   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
17667d523365SDimitry Andric   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
17677d523365SDimitry Andric   // just before entering the VST subblock because: 1) the EnterSubBlock
17687d523365SDimitry Andric   // changes the AbbrevID width; 2) the VST block is nested within the same
17697d523365SDimitry Andric   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
17707d523365SDimitry Andric   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
17717d523365SDimitry Andric   // jump to the FUNCTION_BLOCK using this offset later, we don't want
17727d523365SDimitry Andric   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
17737d523365SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
17747d523365SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
17757d523365SDimitry Andric 
1776f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
17778f0fd8f6SDimitry Andric     return error("Invalid record");
1778f22ef01cSRoman Divacky 
1779f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
1780f22ef01cSRoman Divacky 
1781ff0cc061SDimitry Andric   Triple TT(TheModule->getTargetTriple());
1782ff0cc061SDimitry Andric 
1783f22ef01cSRoman Divacky   // Read all the records for this value table.
1784f22ef01cSRoman Divacky   SmallString<128> ValueName;
1785d88c1a5aSDimitry Andric 
1786d88c1a5aSDimitry Andric   while (true) {
1787139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1788f22ef01cSRoman Divacky 
1789139f7f9bSDimitry Andric     switch (Entry.Kind) {
1790139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1791139f7f9bSDimitry Andric     case BitstreamEntry::Error:
17928f0fd8f6SDimitry Andric       return error("Malformed block");
1793139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
17947d523365SDimitry Andric       if (Offset > 0)
17957d523365SDimitry Andric         Stream.JumpToBit(CurrentBit);
1796d88c1a5aSDimitry Andric       return Error::success();
1797139f7f9bSDimitry Andric     case BitstreamEntry::Record:
1798139f7f9bSDimitry Andric       // The interesting case.
1799139f7f9bSDimitry Andric       break;
1800f22ef01cSRoman Divacky     }
1801f22ef01cSRoman Divacky 
1802f22ef01cSRoman Divacky     // Read a record.
1803f22ef01cSRoman Divacky     Record.clear();
1804139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
1805f22ef01cSRoman Divacky     default:  // Default behavior: unknown type.
1806f22ef01cSRoman Divacky       break;
18073ca95b02SDimitry Andric     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
1808d88c1a5aSDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
1809d88c1a5aSDimitry Andric       if (Error Err = ValOrErr.takeError())
1810d88c1a5aSDimitry Andric         return Err;
18117d523365SDimitry Andric       ValOrErr.get();
18127d523365SDimitry Andric       break;
18137d523365SDimitry Andric     }
18147d523365SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
18153ca95b02SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
1816d88c1a5aSDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
1817d88c1a5aSDimitry Andric       if (Error Err = ValOrErr.takeError())
1818d88c1a5aSDimitry Andric         return Err;
18197d523365SDimitry Andric       Value *V = ValOrErr.get();
1820f22ef01cSRoman Divacky 
18217a7e6055SDimitry Andric       auto *F = dyn_cast<Function>(V);
18227a7e6055SDimitry Andric       // Ignore function offsets emitted for aliases of functions in older
18237a7e6055SDimitry Andric       // versions of LLVM.
18247a7e6055SDimitry Andric       if (!F)
18257a7e6055SDimitry Andric         break;
18267d523365SDimitry Andric 
1827d88c1a5aSDimitry Andric       // Note that we subtract 1 here because the offset is relative to one word
1828d88c1a5aSDimitry Andric       // before the start of the identification or module block, which was
1829d88c1a5aSDimitry Andric       // historically always the start of the regular bitcode header.
1830d88c1a5aSDimitry Andric       uint64_t FuncWordOffset = Record[1] - 1;
18317d523365SDimitry Andric       uint64_t FuncBitOffset = FuncWordOffset * 32;
18327d523365SDimitry Andric       DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
18337d523365SDimitry Andric       // Set the LastFunctionBlockBit to point to the last function block.
18347d523365SDimitry Andric       // Later when parsing is resumed after function materialization,
18357d523365SDimitry Andric       // we can simply skip that last function block.
18367d523365SDimitry Andric       if (FuncBitOffset > LastFunctionBlockBit)
18377d523365SDimitry Andric         LastFunctionBlockBit = FuncBitOffset;
1838f22ef01cSRoman Divacky       break;
1839f22ef01cSRoman Divacky     }
1840f22ef01cSRoman Divacky     case bitc::VST_CODE_BBENTRY: {
18418f0fd8f6SDimitry Andric       if (convertToString(Record, 1, ValueName))
18428f0fd8f6SDimitry Andric         return error("Invalid record");
1843f22ef01cSRoman Divacky       BasicBlock *BB = getBasicBlock(Record[0]);
184491bc56edSDimitry Andric       if (!BB)
18458f0fd8f6SDimitry Andric         return error("Invalid record");
1846f22ef01cSRoman Divacky 
1847f22ef01cSRoman Divacky       BB->setName(StringRef(ValueName.data(), ValueName.size()));
1848f22ef01cSRoman Divacky       ValueName.clear();
1849f22ef01cSRoman Divacky       break;
1850f22ef01cSRoman Divacky     }
1851f22ef01cSRoman Divacky     }
1852f22ef01cSRoman Divacky   }
1853f22ef01cSRoman Divacky }
1854f22ef01cSRoman Divacky 
18558f0fd8f6SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR
18568f0fd8f6SDimitry Andric /// encoding.
18573861d79fSDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1858f22ef01cSRoman Divacky   if ((V & 1) == 0)
1859f22ef01cSRoman Divacky     return V >> 1;
1860f22ef01cSRoman Divacky   if (V != 1)
1861f22ef01cSRoman Divacky     return -(V >> 1);
1862f22ef01cSRoman Divacky   // There is no such thing as -0 with integers.  "-0" really means MININT.
1863f22ef01cSRoman Divacky   return 1ULL << 63;
1864f22ef01cSRoman Divacky }
1865f22ef01cSRoman Divacky 
18668f0fd8f6SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can.
1867d88c1a5aSDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
1868f22ef01cSRoman Divacky   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
18693ca95b02SDimitry Andric   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
18703ca95b02SDimitry Andric       IndirectSymbolInitWorklist;
1871f785676fSDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
187239d628a0SDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
18738f0fd8f6SDimitry Andric   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
1874f22ef01cSRoman Divacky 
1875f22ef01cSRoman Divacky   GlobalInitWorklist.swap(GlobalInits);
18763ca95b02SDimitry Andric   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
1877f785676fSDimitry Andric   FunctionPrefixWorklist.swap(FunctionPrefixes);
187839d628a0SDimitry Andric   FunctionPrologueWorklist.swap(FunctionPrologues);
18798f0fd8f6SDimitry Andric   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
1880f22ef01cSRoman Divacky 
1881f22ef01cSRoman Divacky   while (!GlobalInitWorklist.empty()) {
1882f22ef01cSRoman Divacky     unsigned ValID = GlobalInitWorklist.back().second;
1883f22ef01cSRoman Divacky     if (ValID >= ValueList.size()) {
1884f22ef01cSRoman Divacky       // Not ready to resolve this yet, it requires something later in the file.
1885f22ef01cSRoman Divacky       GlobalInits.push_back(GlobalInitWorklist.back());
1886f22ef01cSRoman Divacky     } else {
188791bc56edSDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1888f22ef01cSRoman Divacky         GlobalInitWorklist.back().first->setInitializer(C);
1889f22ef01cSRoman Divacky       else
18908f0fd8f6SDimitry Andric         return error("Expected a constant");
1891f22ef01cSRoman Divacky     }
1892f22ef01cSRoman Divacky     GlobalInitWorklist.pop_back();
1893f22ef01cSRoman Divacky   }
1894f22ef01cSRoman Divacky 
18953ca95b02SDimitry Andric   while (!IndirectSymbolInitWorklist.empty()) {
18963ca95b02SDimitry Andric     unsigned ValID = IndirectSymbolInitWorklist.back().second;
1897f22ef01cSRoman Divacky     if (ValID >= ValueList.size()) {
18983ca95b02SDimitry Andric       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
1899f22ef01cSRoman Divacky     } else {
190097bc6c73SDimitry Andric       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
190197bc6c73SDimitry Andric       if (!C)
19028f0fd8f6SDimitry Andric         return error("Expected a constant");
19033ca95b02SDimitry Andric       GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
19043ca95b02SDimitry Andric       if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
19058f0fd8f6SDimitry Andric         return error("Alias and aliasee types don't match");
19063ca95b02SDimitry Andric       GIS->setIndirectSymbol(C);
1907f22ef01cSRoman Divacky     }
19083ca95b02SDimitry Andric     IndirectSymbolInitWorklist.pop_back();
1909f22ef01cSRoman Divacky   }
1910f785676fSDimitry Andric 
1911f785676fSDimitry Andric   while (!FunctionPrefixWorklist.empty()) {
1912f785676fSDimitry Andric     unsigned ValID = FunctionPrefixWorklist.back().second;
1913f785676fSDimitry Andric     if (ValID >= ValueList.size()) {
1914f785676fSDimitry Andric       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1915f785676fSDimitry Andric     } else {
191691bc56edSDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1917f785676fSDimitry Andric         FunctionPrefixWorklist.back().first->setPrefixData(C);
1918f785676fSDimitry Andric       else
19198f0fd8f6SDimitry Andric         return error("Expected a constant");
1920f785676fSDimitry Andric     }
1921f785676fSDimitry Andric     FunctionPrefixWorklist.pop_back();
1922f785676fSDimitry Andric   }
1923f785676fSDimitry Andric 
192439d628a0SDimitry Andric   while (!FunctionPrologueWorklist.empty()) {
192539d628a0SDimitry Andric     unsigned ValID = FunctionPrologueWorklist.back().second;
192639d628a0SDimitry Andric     if (ValID >= ValueList.size()) {
192739d628a0SDimitry Andric       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
192839d628a0SDimitry Andric     } else {
192939d628a0SDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
193039d628a0SDimitry Andric         FunctionPrologueWorklist.back().first->setPrologueData(C);
193139d628a0SDimitry Andric       else
19328f0fd8f6SDimitry Andric         return error("Expected a constant");
193339d628a0SDimitry Andric     }
193439d628a0SDimitry Andric     FunctionPrologueWorklist.pop_back();
193539d628a0SDimitry Andric   }
193639d628a0SDimitry Andric 
19378f0fd8f6SDimitry Andric   while (!FunctionPersonalityFnWorklist.empty()) {
19388f0fd8f6SDimitry Andric     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
19398f0fd8f6SDimitry Andric     if (ValID >= ValueList.size()) {
19408f0fd8f6SDimitry Andric       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
19418f0fd8f6SDimitry Andric     } else {
19428f0fd8f6SDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
19438f0fd8f6SDimitry Andric         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
19448f0fd8f6SDimitry Andric       else
19458f0fd8f6SDimitry Andric         return error("Expected a constant");
19468f0fd8f6SDimitry Andric     }
19478f0fd8f6SDimitry Andric     FunctionPersonalityFnWorklist.pop_back();
19488f0fd8f6SDimitry Andric   }
19498f0fd8f6SDimitry Andric 
1950d88c1a5aSDimitry Andric   return Error::success();
1951f22ef01cSRoman Divacky }
1952f22ef01cSRoman Divacky 
19538f0fd8f6SDimitry Andric static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
19547ae0e2c9SDimitry Andric   SmallVector<uint64_t, 8> Words(Vals.size());
1955d88c1a5aSDimitry Andric   transform(Vals, Words.begin(),
19563861d79fSDimitry Andric                  BitcodeReader::decodeSignRotatedValue);
19577ae0e2c9SDimitry Andric 
19587ae0e2c9SDimitry Andric   return APInt(TypeBits, Words);
19597ae0e2c9SDimitry Andric }
19607ae0e2c9SDimitry Andric 
1961d88c1a5aSDimitry Andric Error BitcodeReader::parseConstants() {
1962f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
19638f0fd8f6SDimitry Andric     return error("Invalid record");
1964f22ef01cSRoman Divacky 
1965f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
1966f22ef01cSRoman Divacky 
1967f22ef01cSRoman Divacky   // Read all the records for this value table.
19686122f3e6SDimitry Andric   Type *CurTy = Type::getInt32Ty(Context);
1969f22ef01cSRoman Divacky   unsigned NextCstNo = ValueList.size();
1970d88c1a5aSDimitry Andric 
1971d88c1a5aSDimitry Andric   while (true) {
1972139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1973139f7f9bSDimitry Andric 
1974139f7f9bSDimitry Andric     switch (Entry.Kind) {
1975139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
1976139f7f9bSDimitry Andric     case BitstreamEntry::Error:
19778f0fd8f6SDimitry Andric       return error("Malformed block");
1978139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
1979139f7f9bSDimitry Andric       if (NextCstNo != ValueList.size())
19803ca95b02SDimitry Andric         return error("Invalid constant reference");
1981139f7f9bSDimitry Andric 
1982139f7f9bSDimitry Andric       // Once all the constants have been read, go through and resolve forward
1983139f7f9bSDimitry Andric       // references.
19848f0fd8f6SDimitry Andric       ValueList.resolveConstantForwardRefs();
1985d88c1a5aSDimitry Andric       return Error::success();
1986139f7f9bSDimitry Andric     case BitstreamEntry::Record:
1987139f7f9bSDimitry Andric       // The interesting case.
1988f22ef01cSRoman Divacky       break;
1989f22ef01cSRoman Divacky     }
1990f22ef01cSRoman Divacky 
1991f22ef01cSRoman Divacky     // Read a record.
1992f22ef01cSRoman Divacky     Record.clear();
19933ca95b02SDimitry Andric     Type *VoidType = Type::getVoidTy(Context);
199491bc56edSDimitry Andric     Value *V = nullptr;
1995139f7f9bSDimitry Andric     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1996f22ef01cSRoman Divacky     switch (BitCode) {
1997f22ef01cSRoman Divacky     default:  // Default behavior: unknown constant
1998f22ef01cSRoman Divacky     case bitc::CST_CODE_UNDEF:     // UNDEF
1999f22ef01cSRoman Divacky       V = UndefValue::get(CurTy);
2000f22ef01cSRoman Divacky       break;
2001f22ef01cSRoman Divacky     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2002f22ef01cSRoman Divacky       if (Record.empty())
20038f0fd8f6SDimitry Andric         return error("Invalid record");
200491bc56edSDimitry Andric       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
20058f0fd8f6SDimitry Andric         return error("Invalid record");
20063ca95b02SDimitry Andric       if (TypeList[Record[0]] == VoidType)
20073ca95b02SDimitry Andric         return error("Invalid constant type");
2008f22ef01cSRoman Divacky       CurTy = TypeList[Record[0]];
2009f22ef01cSRoman Divacky       continue;  // Skip the ValueList manipulation.
2010f22ef01cSRoman Divacky     case bitc::CST_CODE_NULL:      // NULL
2011f22ef01cSRoman Divacky       V = Constant::getNullValue(CurTy);
2012f22ef01cSRoman Divacky       break;
2013f22ef01cSRoman Divacky     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2014f22ef01cSRoman Divacky       if (!CurTy->isIntegerTy() || Record.empty())
20158f0fd8f6SDimitry Andric         return error("Invalid record");
20163861d79fSDimitry Andric       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2017f22ef01cSRoman Divacky       break;
2018f22ef01cSRoman Divacky     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2019f22ef01cSRoman Divacky       if (!CurTy->isIntegerTy() || Record.empty())
20208f0fd8f6SDimitry Andric         return error("Invalid record");
2021f22ef01cSRoman Divacky 
20228f0fd8f6SDimitry Andric       APInt VInt =
20238f0fd8f6SDimitry Andric           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
20247ae0e2c9SDimitry Andric       V = ConstantInt::get(Context, VInt);
20257ae0e2c9SDimitry Andric 
2026f22ef01cSRoman Divacky       break;
2027f22ef01cSRoman Divacky     }
2028f22ef01cSRoman Divacky     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2029f22ef01cSRoman Divacky       if (Record.empty())
20308f0fd8f6SDimitry Andric         return error("Invalid record");
2031dff0c46cSDimitry Andric       if (CurTy->isHalfTy())
2032d88c1a5aSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2033139f7f9bSDimitry Andric                                              APInt(16, (uint16_t)Record[0])));
2034dff0c46cSDimitry Andric       else if (CurTy->isFloatTy())
2035d88c1a5aSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2036139f7f9bSDimitry Andric                                              APInt(32, (uint32_t)Record[0])));
2037f22ef01cSRoman Divacky       else if (CurTy->isDoubleTy())
2038d88c1a5aSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2039139f7f9bSDimitry Andric                                              APInt(64, Record[0])));
2040f22ef01cSRoman Divacky       else if (CurTy->isX86_FP80Ty()) {
2041f22ef01cSRoman Divacky         // Bits are not stored the same way as a normal i80 APInt, compensate.
2042f22ef01cSRoman Divacky         uint64_t Rearrange[2];
2043f22ef01cSRoman Divacky         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2044f22ef01cSRoman Divacky         Rearrange[1] = Record[0] >> 48;
2045d88c1a5aSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2046139f7f9bSDimitry Andric                                              APInt(80, Rearrange)));
2047f22ef01cSRoman Divacky       } else if (CurTy->isFP128Ty())
2048d88c1a5aSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2049139f7f9bSDimitry Andric                                              APInt(128, Record)));
2050f22ef01cSRoman Divacky       else if (CurTy->isPPC_FP128Ty())
2051d88c1a5aSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2052139f7f9bSDimitry Andric                                              APInt(128, Record)));
2053f22ef01cSRoman Divacky       else
2054f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);
2055f22ef01cSRoman Divacky       break;
2056f22ef01cSRoman Divacky     }
2057f22ef01cSRoman Divacky 
2058f22ef01cSRoman Divacky     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2059f22ef01cSRoman Divacky       if (Record.empty())
20608f0fd8f6SDimitry Andric         return error("Invalid record");
2061f22ef01cSRoman Divacky 
2062f22ef01cSRoman Divacky       unsigned Size = Record.size();
2063dff0c46cSDimitry Andric       SmallVector<Constant*, 16> Elts;
2064f22ef01cSRoman Divacky 
20656122f3e6SDimitry Andric       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2066f22ef01cSRoman Divacky         for (unsigned i = 0; i != Size; ++i)
2067f22ef01cSRoman Divacky           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2068f22ef01cSRoman Divacky                                                      STy->getElementType(i)));
2069f22ef01cSRoman Divacky         V = ConstantStruct::get(STy, Elts);
20706122f3e6SDimitry Andric       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
20716122f3e6SDimitry Andric         Type *EltTy = ATy->getElementType();
2072f22ef01cSRoman Divacky         for (unsigned i = 0; i != Size; ++i)
2073f22ef01cSRoman Divacky           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2074f22ef01cSRoman Divacky         V = ConstantArray::get(ATy, Elts);
20756122f3e6SDimitry Andric       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
20766122f3e6SDimitry Andric         Type *EltTy = VTy->getElementType();
2077f22ef01cSRoman Divacky         for (unsigned i = 0; i != Size; ++i)
2078f22ef01cSRoman Divacky           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2079f22ef01cSRoman Divacky         V = ConstantVector::get(Elts);
2080f22ef01cSRoman Divacky       } else {
2081f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);
2082f22ef01cSRoman Divacky       }
2083f22ef01cSRoman Divacky       break;
2084f22ef01cSRoman Divacky     }
2085dff0c46cSDimitry Andric     case bitc::CST_CODE_STRING:    // STRING: [values]
2086f22ef01cSRoman Divacky     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2087f22ef01cSRoman Divacky       if (Record.empty())
20888f0fd8f6SDimitry Andric         return error("Invalid record");
2089f22ef01cSRoman Divacky 
20907ae0e2c9SDimitry Andric       SmallString<16> Elts(Record.begin(), Record.end());
2091dff0c46cSDimitry Andric       V = ConstantDataArray::getString(Context, Elts,
2092dff0c46cSDimitry Andric                                        BitCode == bitc::CST_CODE_CSTRING);
2093f22ef01cSRoman Divacky       break;
2094f22ef01cSRoman Divacky     }
2095dff0c46cSDimitry Andric     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2096dff0c46cSDimitry Andric       if (Record.empty())
20978f0fd8f6SDimitry Andric         return error("Invalid record");
2098dff0c46cSDimitry Andric 
2099dff0c46cSDimitry Andric       Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2100dff0c46cSDimitry Andric       if (EltTy->isIntegerTy(8)) {
2101dff0c46cSDimitry Andric         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2102dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
2103dff0c46cSDimitry Andric           V = ConstantDataVector::get(Context, Elts);
2104dff0c46cSDimitry Andric         else
2105dff0c46cSDimitry Andric           V = ConstantDataArray::get(Context, Elts);
2106dff0c46cSDimitry Andric       } else if (EltTy->isIntegerTy(16)) {
2107dff0c46cSDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2108dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
2109dff0c46cSDimitry Andric           V = ConstantDataVector::get(Context, Elts);
2110dff0c46cSDimitry Andric         else
2111dff0c46cSDimitry Andric           V = ConstantDataArray::get(Context, Elts);
2112dff0c46cSDimitry Andric       } else if (EltTy->isIntegerTy(32)) {
2113dff0c46cSDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2114dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
2115dff0c46cSDimitry Andric           V = ConstantDataVector::get(Context, Elts);
2116dff0c46cSDimitry Andric         else
2117dff0c46cSDimitry Andric           V = ConstantDataArray::get(Context, Elts);
2118dff0c46cSDimitry Andric       } else if (EltTy->isIntegerTy(64)) {
2119dff0c46cSDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2120dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
2121dff0c46cSDimitry Andric           V = ConstantDataVector::get(Context, Elts);
2122dff0c46cSDimitry Andric         else
2123dff0c46cSDimitry Andric           V = ConstantDataArray::get(Context, Elts);
2124444ed5c5SDimitry Andric       } else if (EltTy->isHalfTy()) {
2125444ed5c5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2126444ed5c5SDimitry Andric         if (isa<VectorType>(CurTy))
2127444ed5c5SDimitry Andric           V = ConstantDataVector::getFP(Context, Elts);
2128444ed5c5SDimitry Andric         else
2129444ed5c5SDimitry Andric           V = ConstantDataArray::getFP(Context, Elts);
2130dff0c46cSDimitry Andric       } else if (EltTy->isFloatTy()) {
2131444ed5c5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2132dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
2133444ed5c5SDimitry Andric           V = ConstantDataVector::getFP(Context, Elts);
2134dff0c46cSDimitry Andric         else
2135444ed5c5SDimitry Andric           V = ConstantDataArray::getFP(Context, Elts);
2136dff0c46cSDimitry Andric       } else if (EltTy->isDoubleTy()) {
2137444ed5c5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2138dff0c46cSDimitry Andric         if (isa<VectorType>(CurTy))
2139444ed5c5SDimitry Andric           V = ConstantDataVector::getFP(Context, Elts);
2140dff0c46cSDimitry Andric         else
2141444ed5c5SDimitry Andric           V = ConstantDataArray::getFP(Context, Elts);
2142dff0c46cSDimitry Andric       } else {
21438f0fd8f6SDimitry Andric         return error("Invalid type for value");
2144dff0c46cSDimitry Andric       }
2145dff0c46cSDimitry Andric       break;
2146dff0c46cSDimitry Andric     }
2147f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2148f785676fSDimitry Andric       if (Record.size() < 3)
21498f0fd8f6SDimitry Andric         return error("Invalid record");
21508f0fd8f6SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2151f22ef01cSRoman Divacky       if (Opc < 0) {
2152f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);  // Unknown binop.
2153f22ef01cSRoman Divacky       } else {
2154f22ef01cSRoman Divacky         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2155f22ef01cSRoman Divacky         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2156f22ef01cSRoman Divacky         unsigned Flags = 0;
2157f22ef01cSRoman Divacky         if (Record.size() >= 4) {
2158f22ef01cSRoman Divacky           if (Opc == Instruction::Add ||
2159f22ef01cSRoman Divacky               Opc == Instruction::Sub ||
21602754fe60SDimitry Andric               Opc == Instruction::Mul ||
21612754fe60SDimitry Andric               Opc == Instruction::Shl) {
2162f22ef01cSRoman Divacky             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2163f22ef01cSRoman Divacky               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2164f22ef01cSRoman Divacky             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2165f22ef01cSRoman Divacky               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
21662754fe60SDimitry Andric           } else if (Opc == Instruction::SDiv ||
21672754fe60SDimitry Andric                      Opc == Instruction::UDiv ||
21682754fe60SDimitry Andric                      Opc == Instruction::LShr ||
21692754fe60SDimitry Andric                      Opc == Instruction::AShr) {
21702754fe60SDimitry Andric             if (Record[3] & (1 << bitc::PEO_EXACT))
2171f22ef01cSRoman Divacky               Flags |= SDivOperator::IsExact;
2172f22ef01cSRoman Divacky           }
2173f22ef01cSRoman Divacky         }
2174f22ef01cSRoman Divacky         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2175f22ef01cSRoman Divacky       }
2176f22ef01cSRoman Divacky       break;
2177f22ef01cSRoman Divacky     }
2178f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2179f785676fSDimitry Andric       if (Record.size() < 3)
21808f0fd8f6SDimitry Andric         return error("Invalid record");
21818f0fd8f6SDimitry Andric       int Opc = getDecodedCastOpcode(Record[0]);
2182f22ef01cSRoman Divacky       if (Opc < 0) {
2183f22ef01cSRoman Divacky         V = UndefValue::get(CurTy);  // Unknown cast.
2184f22ef01cSRoman Divacky       } else {
21856122f3e6SDimitry Andric         Type *OpTy = getTypeByID(Record[1]);
2186f785676fSDimitry Andric         if (!OpTy)
21878f0fd8f6SDimitry Andric           return error("Invalid record");
2188f22ef01cSRoman Divacky         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2189f785676fSDimitry Andric         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2190f785676fSDimitry Andric         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2191f22ef01cSRoman Divacky       }
2192f22ef01cSRoman Divacky       break;
2193f22ef01cSRoman Divacky     }
2194d88c1a5aSDimitry Andric     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2195d88c1a5aSDimitry Andric     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2196d88c1a5aSDimitry Andric     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2197d88c1a5aSDimitry Andric                                                      // operands]
2198ff0cc061SDimitry Andric       unsigned OpNum = 0;
2199ff0cc061SDimitry Andric       Type *PointeeType = nullptr;
2200d88c1a5aSDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2201d88c1a5aSDimitry Andric           Record.size() % 2)
2202ff0cc061SDimitry Andric         PointeeType = getTypeByID(Record[OpNum++]);
2203d88c1a5aSDimitry Andric 
2204d88c1a5aSDimitry Andric       bool InBounds = false;
2205d88c1a5aSDimitry Andric       Optional<unsigned> InRangeIndex;
2206d88c1a5aSDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2207d88c1a5aSDimitry Andric         uint64_t Op = Record[OpNum++];
2208d88c1a5aSDimitry Andric         InBounds = Op & 1;
2209d88c1a5aSDimitry Andric         InRangeIndex = Op >> 1;
2210d88c1a5aSDimitry Andric       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2211d88c1a5aSDimitry Andric         InBounds = true;
2212d88c1a5aSDimitry Andric 
2213f22ef01cSRoman Divacky       SmallVector<Constant*, 16> Elts;
2214ff0cc061SDimitry Andric       while (OpNum != Record.size()) {
2215ff0cc061SDimitry Andric         Type *ElTy = getTypeByID(Record[OpNum++]);
2216f785676fSDimitry Andric         if (!ElTy)
22178f0fd8f6SDimitry Andric           return error("Invalid record");
2218ff0cc061SDimitry Andric         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2219f22ef01cSRoman Divacky       }
2220ff0cc061SDimitry Andric 
2221ff0cc061SDimitry Andric       if (PointeeType &&
2222ff0cc061SDimitry Andric           PointeeType !=
2223d88c1a5aSDimitry Andric               cast<PointerType>(Elts[0]->getType()->getScalarType())
2224ff0cc061SDimitry Andric                   ->getElementType())
22258f0fd8f6SDimitry Andric         return error("Explicit gep operator type does not match pointee type "
2226ff0cc061SDimitry Andric                      "of pointer operand");
2227ff0cc061SDimitry Andric 
22283ca95b02SDimitry Andric       if (Elts.size() < 1)
22293ca95b02SDimitry Andric         return error("Invalid gep with no operands");
22303ca95b02SDimitry Andric 
22316122f3e6SDimitry Andric       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2232ff0cc061SDimitry Andric       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2233d88c1a5aSDimitry Andric                                          InBounds, InRangeIndex);
2234f22ef01cSRoman Divacky       break;
2235f22ef01cSRoman Divacky     }
2236f785676fSDimitry Andric     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2237f785676fSDimitry Andric       if (Record.size() < 3)
22388f0fd8f6SDimitry Andric         return error("Invalid record");
2239f785676fSDimitry Andric 
2240f785676fSDimitry Andric       Type *SelectorTy = Type::getInt1Ty(Context);
2241f785676fSDimitry Andric 
22427d523365SDimitry Andric       // The selector might be an i1 or an <n x i1>
22437d523365SDimitry Andric       // Get the type from the ValueList before getting a forward ref.
2244f785676fSDimitry Andric       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
22457d523365SDimitry Andric         if (Value *V = ValueList[Record[0]])
22467d523365SDimitry Andric           if (SelectorTy != V->getType())
22477d523365SDimitry Andric             SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2248f785676fSDimitry Andric 
2249f785676fSDimitry Andric       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2250f785676fSDimitry Andric                                                               SelectorTy),
2251f22ef01cSRoman Divacky                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2252f22ef01cSRoman Divacky                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2253f22ef01cSRoman Divacky       break;
2254f785676fSDimitry Andric     }
225591bc56edSDimitry Andric     case bitc::CST_CODE_CE_EXTRACTELT
225691bc56edSDimitry Andric         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2257f785676fSDimitry Andric       if (Record.size() < 3)
22588f0fd8f6SDimitry Andric         return error("Invalid record");
22596122f3e6SDimitry Andric       VectorType *OpTy =
2260f22ef01cSRoman Divacky         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
226191bc56edSDimitry Andric       if (!OpTy)
22628f0fd8f6SDimitry Andric         return error("Invalid record");
2263f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
226491bc56edSDimitry Andric       Constant *Op1 = nullptr;
226591bc56edSDimitry Andric       if (Record.size() == 4) {
226691bc56edSDimitry Andric         Type *IdxTy = getTypeByID(Record[2]);
226791bc56edSDimitry Andric         if (!IdxTy)
22688f0fd8f6SDimitry Andric           return error("Invalid record");
226991bc56edSDimitry Andric         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
227091bc56edSDimitry Andric       } else // TODO: Remove with llvm 4.0
227191bc56edSDimitry Andric         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
227291bc56edSDimitry Andric       if (!Op1)
22738f0fd8f6SDimitry Andric         return error("Invalid record");
2274f22ef01cSRoman Divacky       V = ConstantExpr::getExtractElement(Op0, Op1);
2275f22ef01cSRoman Divacky       break;
2276f22ef01cSRoman Divacky     }
227791bc56edSDimitry Andric     case bitc::CST_CODE_CE_INSERTELT
227891bc56edSDimitry Andric         : { // CE_INSERTELT: [opval, opval, opty, opval]
22796122f3e6SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
228091bc56edSDimitry Andric       if (Record.size() < 3 || !OpTy)
22818f0fd8f6SDimitry Andric         return error("Invalid record");
2282f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2283f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2284f22ef01cSRoman Divacky                                                   OpTy->getElementType());
228591bc56edSDimitry Andric       Constant *Op2 = nullptr;
228691bc56edSDimitry Andric       if (Record.size() == 4) {
228791bc56edSDimitry Andric         Type *IdxTy = getTypeByID(Record[2]);
228891bc56edSDimitry Andric         if (!IdxTy)
22898f0fd8f6SDimitry Andric           return error("Invalid record");
229091bc56edSDimitry Andric         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
229191bc56edSDimitry Andric       } else // TODO: Remove with llvm 4.0
229291bc56edSDimitry Andric         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
229391bc56edSDimitry Andric       if (!Op2)
22948f0fd8f6SDimitry Andric         return error("Invalid record");
2295f22ef01cSRoman Divacky       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2296f22ef01cSRoman Divacky       break;
2297f22ef01cSRoman Divacky     }
2298f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
22996122f3e6SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
230091bc56edSDimitry Andric       if (Record.size() < 3 || !OpTy)
23018f0fd8f6SDimitry Andric         return error("Invalid record");
2302f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2303f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
23046122f3e6SDimitry Andric       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2305f22ef01cSRoman Divacky                                                  OpTy->getNumElements());
2306f22ef01cSRoman Divacky       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2307f22ef01cSRoman Divacky       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2308f22ef01cSRoman Divacky       break;
2309f22ef01cSRoman Divacky     }
2310f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
23116122f3e6SDimitry Andric       VectorType *RTy = dyn_cast<VectorType>(CurTy);
23126122f3e6SDimitry Andric       VectorType *OpTy =
23132754fe60SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
231491bc56edSDimitry Andric       if (Record.size() < 4 || !RTy || !OpTy)
23158f0fd8f6SDimitry Andric         return error("Invalid record");
2316f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2317f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
23186122f3e6SDimitry Andric       Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2319f22ef01cSRoman Divacky                                                  RTy->getNumElements());
2320f22ef01cSRoman Divacky       Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2321f22ef01cSRoman Divacky       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2322f22ef01cSRoman Divacky       break;
2323f22ef01cSRoman Divacky     }
2324f22ef01cSRoman Divacky     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2325f785676fSDimitry Andric       if (Record.size() < 4)
23268f0fd8f6SDimitry Andric         return error("Invalid record");
23276122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
232891bc56edSDimitry Andric       if (!OpTy)
23298f0fd8f6SDimitry Andric         return error("Invalid record");
2330f22ef01cSRoman Divacky       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2331f22ef01cSRoman Divacky       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2332f22ef01cSRoman Divacky 
2333f22ef01cSRoman Divacky       if (OpTy->isFPOrFPVectorTy())
2334f22ef01cSRoman Divacky         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2335f22ef01cSRoman Divacky       else
2336f22ef01cSRoman Divacky         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2337f22ef01cSRoman Divacky       break;
2338f22ef01cSRoman Divacky     }
23393861d79fSDimitry Andric     // This maintains backward compatibility, pre-asm dialect keywords.
23403861d79fSDimitry Andric     // FIXME: Remove with the 4.0 release.
23413861d79fSDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD: {
2342f785676fSDimitry Andric       if (Record.size() < 2)
23438f0fd8f6SDimitry Andric         return error("Invalid record");
2344f22ef01cSRoman Divacky       std::string AsmStr, ConstrStr;
2345f22ef01cSRoman Divacky       bool HasSideEffects = Record[0] & 1;
2346f22ef01cSRoman Divacky       bool IsAlignStack = Record[0] >> 1;
2347f22ef01cSRoman Divacky       unsigned AsmStrSize = Record[1];
2348f22ef01cSRoman Divacky       if (2+AsmStrSize >= Record.size())
23498f0fd8f6SDimitry Andric         return error("Invalid record");
2350f22ef01cSRoman Divacky       unsigned ConstStrSize = Record[2+AsmStrSize];
2351f22ef01cSRoman Divacky       if (3+AsmStrSize+ConstStrSize > Record.size())
23528f0fd8f6SDimitry Andric         return error("Invalid record");
2353f22ef01cSRoman Divacky 
2354f22ef01cSRoman Divacky       for (unsigned i = 0; i != AsmStrSize; ++i)
2355f22ef01cSRoman Divacky         AsmStr += (char)Record[2+i];
2356f22ef01cSRoman Divacky       for (unsigned i = 0; i != ConstStrSize; ++i)
2357f22ef01cSRoman Divacky         ConstrStr += (char)Record[3+AsmStrSize+i];
23586122f3e6SDimitry Andric       PointerType *PTy = cast<PointerType>(CurTy);
2359f22ef01cSRoman Divacky       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2360f22ef01cSRoman Divacky                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2361f22ef01cSRoman Divacky       break;
2362f22ef01cSRoman Divacky     }
23633861d79fSDimitry Andric     // This version adds support for the asm dialect keywords (e.g.,
23643861d79fSDimitry Andric     // inteldialect).
23653861d79fSDimitry Andric     case bitc::CST_CODE_INLINEASM: {
2366f785676fSDimitry Andric       if (Record.size() < 2)
23678f0fd8f6SDimitry Andric         return error("Invalid record");
23683861d79fSDimitry Andric       std::string AsmStr, ConstrStr;
23693861d79fSDimitry Andric       bool HasSideEffects = Record[0] & 1;
23703861d79fSDimitry Andric       bool IsAlignStack = (Record[0] >> 1) & 1;
23713861d79fSDimitry Andric       unsigned AsmDialect = Record[0] >> 2;
23723861d79fSDimitry Andric       unsigned AsmStrSize = Record[1];
23733861d79fSDimitry Andric       if (2+AsmStrSize >= Record.size())
23748f0fd8f6SDimitry Andric         return error("Invalid record");
23753861d79fSDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
23763861d79fSDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
23778f0fd8f6SDimitry Andric         return error("Invalid record");
23783861d79fSDimitry Andric 
23793861d79fSDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
23803861d79fSDimitry Andric         AsmStr += (char)Record[2+i];
23813861d79fSDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
23823861d79fSDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
23833861d79fSDimitry Andric       PointerType *PTy = cast<PointerType>(CurTy);
23843861d79fSDimitry Andric       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
23853861d79fSDimitry Andric                          AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
23863861d79fSDimitry Andric                          InlineAsm::AsmDialect(AsmDialect));
23873861d79fSDimitry Andric       break;
23883861d79fSDimitry Andric     }
2389f22ef01cSRoman Divacky     case bitc::CST_CODE_BLOCKADDRESS:{
2390f785676fSDimitry Andric       if (Record.size() < 3)
23918f0fd8f6SDimitry Andric         return error("Invalid record");
23926122f3e6SDimitry Andric       Type *FnTy = getTypeByID(Record[0]);
239391bc56edSDimitry Andric       if (!FnTy)
23948f0fd8f6SDimitry Andric         return error("Invalid record");
2395f22ef01cSRoman Divacky       Function *Fn =
2396f22ef01cSRoman Divacky         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
239791bc56edSDimitry Andric       if (!Fn)
23988f0fd8f6SDimitry Andric         return error("Invalid record");
239939d628a0SDimitry Andric 
24003861d79fSDimitry Andric       // If the function is already parsed we can insert the block address right
24013861d79fSDimitry Andric       // away.
240239d628a0SDimitry Andric       BasicBlock *BB;
240339d628a0SDimitry Andric       unsigned BBID = Record[2];
240439d628a0SDimitry Andric       if (!BBID)
240539d628a0SDimitry Andric         // Invalid reference to entry block.
24068f0fd8f6SDimitry Andric         return error("Invalid ID");
24073861d79fSDimitry Andric       if (!Fn->empty()) {
24083861d79fSDimitry Andric         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
240939d628a0SDimitry Andric         for (size_t I = 0, E = BBID; I != E; ++I) {
24103861d79fSDimitry Andric           if (BBI == BBE)
24118f0fd8f6SDimitry Andric             return error("Invalid ID");
24123861d79fSDimitry Andric           ++BBI;
24133861d79fSDimitry Andric         }
24147d523365SDimitry Andric         BB = &*BBI;
24153861d79fSDimitry Andric       } else {
24163861d79fSDimitry Andric         // Otherwise insert a placeholder and remember it so it can be inserted
24173861d79fSDimitry Andric         // when the function is parsed.
241839d628a0SDimitry Andric         auto &FwdBBs = BasicBlockFwdRefs[Fn];
241939d628a0SDimitry Andric         if (FwdBBs.empty())
242039d628a0SDimitry Andric           BasicBlockFwdRefQueue.push_back(Fn);
242139d628a0SDimitry Andric         if (FwdBBs.size() < BBID + 1)
242239d628a0SDimitry Andric           FwdBBs.resize(BBID + 1);
242339d628a0SDimitry Andric         if (!FwdBBs[BBID])
242439d628a0SDimitry Andric           FwdBBs[BBID] = BasicBlock::Create(Context);
242539d628a0SDimitry Andric         BB = FwdBBs[BBID];
24263861d79fSDimitry Andric       }
242739d628a0SDimitry Andric       V = BlockAddress::get(Fn, BB);
2428f22ef01cSRoman Divacky       break;
2429f22ef01cSRoman Divacky     }
2430f22ef01cSRoman Divacky     }
2431f22ef01cSRoman Divacky 
24328f0fd8f6SDimitry Andric     ValueList.assignValue(V, NextCstNo);
2433f22ef01cSRoman Divacky     ++NextCstNo;
2434f22ef01cSRoman Divacky   }
2435f22ef01cSRoman Divacky }
2436f22ef01cSRoman Divacky 
2437d88c1a5aSDimitry Andric Error BitcodeReader::parseUseLists() {
2438dff0c46cSDimitry Andric   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
24398f0fd8f6SDimitry Andric     return error("Invalid record");
2440dff0c46cSDimitry Andric 
2441dff0c46cSDimitry Andric   // Read all the records.
244239d628a0SDimitry Andric   SmallVector<uint64_t, 64> Record;
2443d88c1a5aSDimitry Andric 
2444d88c1a5aSDimitry Andric   while (true) {
2445139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2446139f7f9bSDimitry Andric 
2447139f7f9bSDimitry Andric     switch (Entry.Kind) {
2448139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2449139f7f9bSDimitry Andric     case BitstreamEntry::Error:
24508f0fd8f6SDimitry Andric       return error("Malformed block");
2451139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
2452d88c1a5aSDimitry Andric       return Error::success();
2453139f7f9bSDimitry Andric     case BitstreamEntry::Record:
2454139f7f9bSDimitry Andric       // The interesting case.
2455139f7f9bSDimitry Andric       break;
2456dff0c46cSDimitry Andric     }
2457dff0c46cSDimitry Andric 
2458dff0c46cSDimitry Andric     // Read a use list record.
2459dff0c46cSDimitry Andric     Record.clear();
246039d628a0SDimitry Andric     bool IsBB = false;
2461139f7f9bSDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
2462dff0c46cSDimitry Andric     default:  // Default behavior: unknown type.
2463dff0c46cSDimitry Andric       break;
246439d628a0SDimitry Andric     case bitc::USELIST_CODE_BB:
246539d628a0SDimitry Andric       IsBB = true;
2466d88c1a5aSDimitry Andric       LLVM_FALLTHROUGH;
246739d628a0SDimitry Andric     case bitc::USELIST_CODE_DEFAULT: {
2468dff0c46cSDimitry Andric       unsigned RecordLength = Record.size();
246939d628a0SDimitry Andric       if (RecordLength < 3)
247039d628a0SDimitry Andric         // Records should have at least an ID and two indexes.
24718f0fd8f6SDimitry Andric         return error("Invalid record");
247239d628a0SDimitry Andric       unsigned ID = Record.back();
247339d628a0SDimitry Andric       Record.pop_back();
247439d628a0SDimitry Andric 
247539d628a0SDimitry Andric       Value *V;
247639d628a0SDimitry Andric       if (IsBB) {
247739d628a0SDimitry Andric         assert(ID < FunctionBBs.size() && "Basic block not found");
247839d628a0SDimitry Andric         V = FunctionBBs[ID];
247939d628a0SDimitry Andric       } else
248039d628a0SDimitry Andric         V = ValueList[ID];
248139d628a0SDimitry Andric       unsigned NumUses = 0;
248239d628a0SDimitry Andric       SmallDenseMap<const Use *, unsigned, 16> Order;
24837d523365SDimitry Andric       for (const Use &U : V->materialized_uses()) {
248439d628a0SDimitry Andric         if (++NumUses > Record.size())
248539d628a0SDimitry Andric           break;
248639d628a0SDimitry Andric         Order[&U] = Record[NumUses - 1];
248739d628a0SDimitry Andric       }
248839d628a0SDimitry Andric       if (Order.size() != Record.size() || NumUses > Record.size())
248939d628a0SDimitry Andric         // Mismatches can happen if the functions are being materialized lazily
249039d628a0SDimitry Andric         // (out-of-order), or a value has been upgraded.
249139d628a0SDimitry Andric         break;
249239d628a0SDimitry Andric 
249339d628a0SDimitry Andric       V->sortUseList([&](const Use &L, const Use &R) {
249439d628a0SDimitry Andric         return Order.lookup(&L) < Order.lookup(&R);
249539d628a0SDimitry Andric       });
2496dff0c46cSDimitry Andric       break;
2497dff0c46cSDimitry Andric     }
2498dff0c46cSDimitry Andric     }
2499dff0c46cSDimitry Andric   }
2500dff0c46cSDimitry Andric }
2501dff0c46cSDimitry Andric 
2502ff0cc061SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it.
2503ff0cc061SDimitry Andric /// This lets us lazily deserialize the metadata.
2504d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() {
2505ff0cc061SDimitry Andric   // Save the current stream state.
2506ff0cc061SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
2507ff0cc061SDimitry Andric   DeferredMetadataInfo.push_back(CurBit);
2508ff0cc061SDimitry Andric 
2509ff0cc061SDimitry Andric   // Skip over the block for now.
2510ff0cc061SDimitry Andric   if (Stream.SkipBlock())
25118f0fd8f6SDimitry Andric     return error("Invalid record");
2512d88c1a5aSDimitry Andric   return Error::success();
2513ff0cc061SDimitry Andric }
2514ff0cc061SDimitry Andric 
2515d88c1a5aSDimitry Andric Error BitcodeReader::materializeMetadata() {
2516ff0cc061SDimitry Andric   for (uint64_t BitPos : DeferredMetadataInfo) {
2517ff0cc061SDimitry Andric     // Move the bit stream to the saved position.
2518ff0cc061SDimitry Andric     Stream.JumpToBit(BitPos);
2519d88c1a5aSDimitry Andric     if (Error Err = MDLoader->parseModuleMetadata())
2520d88c1a5aSDimitry Andric       return Err;
2521ff0cc061SDimitry Andric   }
2522ff0cc061SDimitry Andric   DeferredMetadataInfo.clear();
2523d88c1a5aSDimitry Andric   return Error::success();
2524ff0cc061SDimitry Andric }
2525ff0cc061SDimitry Andric 
2526ff0cc061SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2527ff0cc061SDimitry Andric 
25288f0fd8f6SDimitry Andric /// When we see the block for a function body, remember where it is and then
25298f0fd8f6SDimitry Andric /// skip it.  This lets us lazily deserialize the functions.
2530d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() {
2531f22ef01cSRoman Divacky   // Get the function we are talking about.
2532f22ef01cSRoman Divacky   if (FunctionsWithBodies.empty())
25338f0fd8f6SDimitry Andric     return error("Insufficient function protos");
2534f22ef01cSRoman Divacky 
2535f22ef01cSRoman Divacky   Function *Fn = FunctionsWithBodies.back();
2536f22ef01cSRoman Divacky   FunctionsWithBodies.pop_back();
2537f22ef01cSRoman Divacky 
2538f22ef01cSRoman Divacky   // Save the current stream state.
2539f22ef01cSRoman Divacky   uint64_t CurBit = Stream.GetCurrentBitNo();
25407d523365SDimitry Andric   assert(
25417d523365SDimitry Andric       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
25427d523365SDimitry Andric       "Mismatch between VST and scanned function offsets");
2543f22ef01cSRoman Divacky   DeferredFunctionInfo[Fn] = CurBit;
2544f22ef01cSRoman Divacky 
2545f22ef01cSRoman Divacky   // Skip over the function block for now.
2546f22ef01cSRoman Divacky   if (Stream.SkipBlock())
25478f0fd8f6SDimitry Andric     return error("Invalid record");
2548d88c1a5aSDimitry Andric   return Error::success();
2549f22ef01cSRoman Divacky }
2550f22ef01cSRoman Divacky 
2551d88c1a5aSDimitry Andric Error BitcodeReader::globalCleanup() {
2552f22ef01cSRoman Divacky   // Patch the initializers for globals and aliases up.
2553d88c1a5aSDimitry Andric   if (Error Err = resolveGlobalAndIndirectSymbolInits())
2554d88c1a5aSDimitry Andric     return Err;
25553ca95b02SDimitry Andric   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
25568f0fd8f6SDimitry Andric     return error("Malformed global initializer set");
2557f22ef01cSRoman Divacky 
2558f22ef01cSRoman Divacky   // Look for intrinsic functions which need to be upgraded at some point
25598f0fd8f6SDimitry Andric   for (Function &F : *TheModule) {
2560f22ef01cSRoman Divacky     Function *NewFn;
25618f0fd8f6SDimitry Andric     if (UpgradeIntrinsicFunction(&F, NewFn))
25623dac3a9bSDimitry Andric       UpgradedIntrinsics[&F] = NewFn;
25633ca95b02SDimitry Andric     else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
25643ca95b02SDimitry Andric       // Some types could be renamed during loading if several modules are
25653ca95b02SDimitry Andric       // loaded in the same LLVMContext (LTO scenario). In this case we should
25663ca95b02SDimitry Andric       // remangle intrinsics names as well.
25673ca95b02SDimitry Andric       RemangledIntrinsics[&F] = Remangled.getValue();
2568f22ef01cSRoman Divacky   }
2569f22ef01cSRoman Divacky 
2570e580952dSDimitry Andric   // Look for global variables which need to be renamed.
25718f0fd8f6SDimitry Andric   for (GlobalVariable &GV : TheModule->globals())
25728f0fd8f6SDimitry Andric     UpgradeGlobalVariable(&GV);
257391bc56edSDimitry Andric 
2574f22ef01cSRoman Divacky   // Force deallocation of memory for these vectors to favor the client that
2575f22ef01cSRoman Divacky   // want lazy deserialization.
2576f22ef01cSRoman Divacky   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
25773ca95b02SDimitry Andric   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
25783ca95b02SDimitry Andric       IndirectSymbolInits);
2579d88c1a5aSDimitry Andric   return Error::success();
2580f22ef01cSRoman Divacky }
2581f22ef01cSRoman Divacky 
25827d523365SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we
25837d523365SDimitry Andric /// either have an old bitcode file without a VST forward declaration record,
25847d523365SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous
25857d523365SDimitry Andric /// functions do not have a name and are therefore not in the VST.
2586d88c1a5aSDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() {
2587dff0c46cSDimitry Andric   Stream.JumpToBit(NextUnreadBit);
25887d523365SDimitry Andric 
25897d523365SDimitry Andric   if (Stream.AtEndOfStream())
25907d523365SDimitry Andric     return error("Could not find function in stream");
25917d523365SDimitry Andric 
25927d523365SDimitry Andric   if (!SeenFirstFunctionBody)
25937d523365SDimitry Andric     return error("Trying to materialize functions before seeing function blocks");
25947d523365SDimitry Andric 
25957d523365SDimitry Andric   // An old bitcode file with the symbol table at the end would have
25967d523365SDimitry Andric   // finished the parse greedily.
25977d523365SDimitry Andric   assert(SeenValueSymbolTable);
25987d523365SDimitry Andric 
25997d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
26007d523365SDimitry Andric 
2601d88c1a5aSDimitry Andric   while (true) {
26027d523365SDimitry Andric     BitstreamEntry Entry = Stream.advance();
26037d523365SDimitry Andric     switch (Entry.Kind) {
26047d523365SDimitry Andric     default:
26057d523365SDimitry Andric       return error("Expect SubBlock");
26067d523365SDimitry Andric     case BitstreamEntry::SubBlock:
26077d523365SDimitry Andric       switch (Entry.ID) {
26087d523365SDimitry Andric       default:
26097d523365SDimitry Andric         return error("Expect function block");
26107d523365SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
2611d88c1a5aSDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
2612d88c1a5aSDimitry Andric           return Err;
26137d523365SDimitry Andric         NextUnreadBit = Stream.GetCurrentBitNo();
2614d88c1a5aSDimitry Andric         return Error::success();
26157d523365SDimitry Andric       }
26167d523365SDimitry Andric     }
26177d523365SDimitry Andric   }
26187d523365SDimitry Andric }
26197d523365SDimitry Andric 
2620d88c1a5aSDimitry Andric bool BitcodeReaderBase::readBlockInfo() {
2621d88c1a5aSDimitry Andric   Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2622d88c1a5aSDimitry Andric   if (!NewBlockInfo)
2623d88c1a5aSDimitry Andric     return true;
2624d88c1a5aSDimitry Andric   BlockInfo = std::move(*NewBlockInfo);
2625d88c1a5aSDimitry Andric   return false;
26267d523365SDimitry Andric }
26277d523365SDimitry Andric 
26287a7e6055SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
26297a7e6055SDimitry Andric   // [selection_kind, name]
26307a7e6055SDimitry Andric   if (Record.size() < 2)
26317a7e6055SDimitry Andric     return error("Invalid record");
26327a7e6055SDimitry Andric   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
26337a7e6055SDimitry Andric   std::string Name;
26347a7e6055SDimitry Andric   unsigned ComdatNameSize = Record[1];
26357a7e6055SDimitry Andric   Name.reserve(ComdatNameSize);
26367a7e6055SDimitry Andric   for (unsigned i = 0; i != ComdatNameSize; ++i)
26377a7e6055SDimitry Andric     Name += (char)Record[2 + i];
26387a7e6055SDimitry Andric   Comdat *C = TheModule->getOrInsertComdat(Name);
26397a7e6055SDimitry Andric   C->setSelectionKind(SK);
26407a7e6055SDimitry Andric   ComdatList.push_back(C);
26417a7e6055SDimitry Andric   return Error::success();
26427a7e6055SDimitry Andric }
26437a7e6055SDimitry Andric 
26447a7e6055SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
26457a7e6055SDimitry Andric   // [pointer type, isconst, initid, linkage, alignment, section,
26467a7e6055SDimitry Andric   // visibility, threadlocal, unnamed_addr, externally_initialized,
26477a7e6055SDimitry Andric   // dllstorageclass, comdat]
26487a7e6055SDimitry Andric   if (Record.size() < 6)
26497a7e6055SDimitry Andric     return error("Invalid record");
26507a7e6055SDimitry Andric   Type *Ty = getTypeByID(Record[0]);
26517a7e6055SDimitry Andric   if (!Ty)
26527a7e6055SDimitry Andric     return error("Invalid record");
26537a7e6055SDimitry Andric   bool isConstant = Record[1] & 1;
26547a7e6055SDimitry Andric   bool explicitType = Record[1] & 2;
26557a7e6055SDimitry Andric   unsigned AddressSpace;
26567a7e6055SDimitry Andric   if (explicitType) {
26577a7e6055SDimitry Andric     AddressSpace = Record[1] >> 2;
26587a7e6055SDimitry Andric   } else {
26597a7e6055SDimitry Andric     if (!Ty->isPointerTy())
26607a7e6055SDimitry Andric       return error("Invalid type for value");
26617a7e6055SDimitry Andric     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
26627a7e6055SDimitry Andric     Ty = cast<PointerType>(Ty)->getElementType();
26637a7e6055SDimitry Andric   }
26647a7e6055SDimitry Andric 
26657a7e6055SDimitry Andric   uint64_t RawLinkage = Record[3];
26667a7e6055SDimitry Andric   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
26677a7e6055SDimitry Andric   unsigned Alignment;
26687a7e6055SDimitry Andric   if (Error Err = parseAlignmentValue(Record[4], Alignment))
26697a7e6055SDimitry Andric     return Err;
26707a7e6055SDimitry Andric   std::string Section;
26717a7e6055SDimitry Andric   if (Record[5]) {
26727a7e6055SDimitry Andric     if (Record[5] - 1 >= SectionTable.size())
26737a7e6055SDimitry Andric       return error("Invalid ID");
26747a7e6055SDimitry Andric     Section = SectionTable[Record[5] - 1];
26757a7e6055SDimitry Andric   }
26767a7e6055SDimitry Andric   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
26777a7e6055SDimitry Andric   // Local linkage must have default visibility.
26787a7e6055SDimitry Andric   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
26797a7e6055SDimitry Andric     // FIXME: Change to an error if non-default in 4.0.
26807a7e6055SDimitry Andric     Visibility = getDecodedVisibility(Record[6]);
26817a7e6055SDimitry Andric 
26827a7e6055SDimitry Andric   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
26837a7e6055SDimitry Andric   if (Record.size() > 7)
26847a7e6055SDimitry Andric     TLM = getDecodedThreadLocalMode(Record[7]);
26857a7e6055SDimitry Andric 
26867a7e6055SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
26877a7e6055SDimitry Andric   if (Record.size() > 8)
26887a7e6055SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
26897a7e6055SDimitry Andric 
26907a7e6055SDimitry Andric   bool ExternallyInitialized = false;
26917a7e6055SDimitry Andric   if (Record.size() > 9)
26927a7e6055SDimitry Andric     ExternallyInitialized = Record[9];
26937a7e6055SDimitry Andric 
26947a7e6055SDimitry Andric   GlobalVariable *NewGV =
26957a7e6055SDimitry Andric       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "",
26967a7e6055SDimitry Andric                          nullptr, TLM, AddressSpace, ExternallyInitialized);
26977a7e6055SDimitry Andric   NewGV->setAlignment(Alignment);
26987a7e6055SDimitry Andric   if (!Section.empty())
26997a7e6055SDimitry Andric     NewGV->setSection(Section);
27007a7e6055SDimitry Andric   NewGV->setVisibility(Visibility);
27017a7e6055SDimitry Andric   NewGV->setUnnamedAddr(UnnamedAddr);
27027a7e6055SDimitry Andric 
27037a7e6055SDimitry Andric   if (Record.size() > 10)
27047a7e6055SDimitry Andric     NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
27057a7e6055SDimitry Andric   else
27067a7e6055SDimitry Andric     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
27077a7e6055SDimitry Andric 
27087a7e6055SDimitry Andric   ValueList.push_back(NewGV);
27097a7e6055SDimitry Andric 
27107a7e6055SDimitry Andric   // Remember which value to use for the global initializer.
27117a7e6055SDimitry Andric   if (unsigned InitID = Record[2])
27127a7e6055SDimitry Andric     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
27137a7e6055SDimitry Andric 
27147a7e6055SDimitry Andric   if (Record.size() > 11) {
27157a7e6055SDimitry Andric     if (unsigned ComdatID = Record[11]) {
27167a7e6055SDimitry Andric       if (ComdatID > ComdatList.size())
27177a7e6055SDimitry Andric         return error("Invalid global variable comdat ID");
27187a7e6055SDimitry Andric       NewGV->setComdat(ComdatList[ComdatID - 1]);
27197a7e6055SDimitry Andric     }
27207a7e6055SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
27217a7e6055SDimitry Andric     NewGV->setComdat(reinterpret_cast<Comdat *>(1));
27227a7e6055SDimitry Andric   }
27237a7e6055SDimitry Andric   return Error::success();
27247a7e6055SDimitry Andric }
27257a7e6055SDimitry Andric 
27267a7e6055SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
27277a7e6055SDimitry Andric   // [type, callingconv, isproto, linkage, paramattr, alignment, section,
27287a7e6055SDimitry Andric   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
27297a7e6055SDimitry Andric   // prefixdata]
27307a7e6055SDimitry Andric   if (Record.size() < 8)
27317a7e6055SDimitry Andric     return error("Invalid record");
27327a7e6055SDimitry Andric   Type *Ty = getTypeByID(Record[0]);
27337a7e6055SDimitry Andric   if (!Ty)
27347a7e6055SDimitry Andric     return error("Invalid record");
27357a7e6055SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(Ty))
27367a7e6055SDimitry Andric     Ty = PTy->getElementType();
27377a7e6055SDimitry Andric   auto *FTy = dyn_cast<FunctionType>(Ty);
27387a7e6055SDimitry Andric   if (!FTy)
27397a7e6055SDimitry Andric     return error("Invalid type for value");
27407a7e6055SDimitry Andric   auto CC = static_cast<CallingConv::ID>(Record[1]);
27417a7e6055SDimitry Andric   if (CC & ~CallingConv::MaxID)
27427a7e6055SDimitry Andric     return error("Invalid calling convention ID");
27437a7e6055SDimitry Andric 
27447a7e6055SDimitry Andric   Function *Func =
27457a7e6055SDimitry Andric       Function::Create(FTy, GlobalValue::ExternalLinkage, "", TheModule);
27467a7e6055SDimitry Andric 
27477a7e6055SDimitry Andric   Func->setCallingConv(CC);
27487a7e6055SDimitry Andric   bool isProto = Record[2];
27497a7e6055SDimitry Andric   uint64_t RawLinkage = Record[3];
27507a7e6055SDimitry Andric   Func->setLinkage(getDecodedLinkage(RawLinkage));
27517a7e6055SDimitry Andric   Func->setAttributes(getAttributes(Record[4]));
27527a7e6055SDimitry Andric 
27537a7e6055SDimitry Andric   unsigned Alignment;
27547a7e6055SDimitry Andric   if (Error Err = parseAlignmentValue(Record[5], Alignment))
27557a7e6055SDimitry Andric     return Err;
27567a7e6055SDimitry Andric   Func->setAlignment(Alignment);
27577a7e6055SDimitry Andric   if (Record[6]) {
27587a7e6055SDimitry Andric     if (Record[6] - 1 >= SectionTable.size())
27597a7e6055SDimitry Andric       return error("Invalid ID");
27607a7e6055SDimitry Andric     Func->setSection(SectionTable[Record[6] - 1]);
27617a7e6055SDimitry Andric   }
27627a7e6055SDimitry Andric   // Local linkage must have default visibility.
27637a7e6055SDimitry Andric   if (!Func->hasLocalLinkage())
27647a7e6055SDimitry Andric     // FIXME: Change to an error if non-default in 4.0.
27657a7e6055SDimitry Andric     Func->setVisibility(getDecodedVisibility(Record[7]));
27667a7e6055SDimitry Andric   if (Record.size() > 8 && Record[8]) {
27677a7e6055SDimitry Andric     if (Record[8] - 1 >= GCTable.size())
27687a7e6055SDimitry Andric       return error("Invalid ID");
27697a7e6055SDimitry Andric     Func->setGC(GCTable[Record[8] - 1]);
27707a7e6055SDimitry Andric   }
27717a7e6055SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
27727a7e6055SDimitry Andric   if (Record.size() > 9)
27737a7e6055SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
27747a7e6055SDimitry Andric   Func->setUnnamedAddr(UnnamedAddr);
27757a7e6055SDimitry Andric   if (Record.size() > 10 && Record[10] != 0)
27767a7e6055SDimitry Andric     FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
27777a7e6055SDimitry Andric 
27787a7e6055SDimitry Andric   if (Record.size() > 11)
27797a7e6055SDimitry Andric     Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
27807a7e6055SDimitry Andric   else
27817a7e6055SDimitry Andric     upgradeDLLImportExportLinkage(Func, RawLinkage);
27827a7e6055SDimitry Andric 
27837a7e6055SDimitry Andric   if (Record.size() > 12) {
27847a7e6055SDimitry Andric     if (unsigned ComdatID = Record[12]) {
27857a7e6055SDimitry Andric       if (ComdatID > ComdatList.size())
27867a7e6055SDimitry Andric         return error("Invalid function comdat ID");
27877a7e6055SDimitry Andric       Func->setComdat(ComdatList[ComdatID - 1]);
27887a7e6055SDimitry Andric     }
27897a7e6055SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
27907a7e6055SDimitry Andric     Func->setComdat(reinterpret_cast<Comdat *>(1));
27917a7e6055SDimitry Andric   }
27927a7e6055SDimitry Andric 
27937a7e6055SDimitry Andric   if (Record.size() > 13 && Record[13] != 0)
27947a7e6055SDimitry Andric     FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
27957a7e6055SDimitry Andric 
27967a7e6055SDimitry Andric   if (Record.size() > 14 && Record[14] != 0)
27977a7e6055SDimitry Andric     FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
27987a7e6055SDimitry Andric 
27997a7e6055SDimitry Andric   ValueList.push_back(Func);
28007a7e6055SDimitry Andric 
28017a7e6055SDimitry Andric   // If this is a function with a body, remember the prototype we are
28027a7e6055SDimitry Andric   // creating now, so that we can match up the body with them later.
28037a7e6055SDimitry Andric   if (!isProto) {
28047a7e6055SDimitry Andric     Func->setIsMaterializable(true);
28057a7e6055SDimitry Andric     FunctionsWithBodies.push_back(Func);
28067a7e6055SDimitry Andric     DeferredFunctionInfo[Func] = 0;
28077a7e6055SDimitry Andric   }
28087a7e6055SDimitry Andric   return Error::success();
28097a7e6055SDimitry Andric }
28107a7e6055SDimitry Andric 
28117a7e6055SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord(
28127a7e6055SDimitry Andric     unsigned BitCode, ArrayRef<uint64_t> Record) {
28137a7e6055SDimitry Andric   // ALIAS_OLD: [alias type, aliasee val#, linkage]
28147a7e6055SDimitry Andric   // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
28157a7e6055SDimitry Andric   // dllstorageclass]
28167a7e6055SDimitry Andric   // IFUNC: [alias type, addrspace, aliasee val#, linkage,
28177a7e6055SDimitry Andric   // visibility, dllstorageclass]
28187a7e6055SDimitry Andric   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
28197a7e6055SDimitry Andric   if (Record.size() < (3 + (unsigned)NewRecord))
28207a7e6055SDimitry Andric     return error("Invalid record");
28217a7e6055SDimitry Andric   unsigned OpNum = 0;
28227a7e6055SDimitry Andric   Type *Ty = getTypeByID(Record[OpNum++]);
28237a7e6055SDimitry Andric   if (!Ty)
28247a7e6055SDimitry Andric     return error("Invalid record");
28257a7e6055SDimitry Andric 
28267a7e6055SDimitry Andric   unsigned AddrSpace;
28277a7e6055SDimitry Andric   if (!NewRecord) {
28287a7e6055SDimitry Andric     auto *PTy = dyn_cast<PointerType>(Ty);
28297a7e6055SDimitry Andric     if (!PTy)
28307a7e6055SDimitry Andric       return error("Invalid type for value");
28317a7e6055SDimitry Andric     Ty = PTy->getElementType();
28327a7e6055SDimitry Andric     AddrSpace = PTy->getAddressSpace();
28337a7e6055SDimitry Andric   } else {
28347a7e6055SDimitry Andric     AddrSpace = Record[OpNum++];
28357a7e6055SDimitry Andric   }
28367a7e6055SDimitry Andric 
28377a7e6055SDimitry Andric   auto Val = Record[OpNum++];
28387a7e6055SDimitry Andric   auto Linkage = Record[OpNum++];
28397a7e6055SDimitry Andric   GlobalIndirectSymbol *NewGA;
28407a7e6055SDimitry Andric   if (BitCode == bitc::MODULE_CODE_ALIAS ||
28417a7e6055SDimitry Andric       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
28427a7e6055SDimitry Andric     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), "",
28437a7e6055SDimitry Andric                                 TheModule);
28447a7e6055SDimitry Andric   else
28457a7e6055SDimitry Andric     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), "",
28467a7e6055SDimitry Andric                                 nullptr, TheModule);
28477a7e6055SDimitry Andric   // Old bitcode files didn't have visibility field.
28487a7e6055SDimitry Andric   // Local linkage must have default visibility.
28497a7e6055SDimitry Andric   if (OpNum != Record.size()) {
28507a7e6055SDimitry Andric     auto VisInd = OpNum++;
28517a7e6055SDimitry Andric     if (!NewGA->hasLocalLinkage())
28527a7e6055SDimitry Andric       // FIXME: Change to an error if non-default in 4.0.
28537a7e6055SDimitry Andric       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
28547a7e6055SDimitry Andric   }
28557a7e6055SDimitry Andric   if (OpNum != Record.size())
28567a7e6055SDimitry Andric     NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
28577a7e6055SDimitry Andric   else
28587a7e6055SDimitry Andric     upgradeDLLImportExportLinkage(NewGA, Linkage);
28597a7e6055SDimitry Andric   if (OpNum != Record.size())
28607a7e6055SDimitry Andric     NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
28617a7e6055SDimitry Andric   if (OpNum != Record.size())
28627a7e6055SDimitry Andric     NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
28637a7e6055SDimitry Andric   ValueList.push_back(NewGA);
28647a7e6055SDimitry Andric   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
28657a7e6055SDimitry Andric   return Error::success();
28667a7e6055SDimitry Andric }
28677a7e6055SDimitry Andric 
2868d88c1a5aSDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit,
28697d523365SDimitry Andric                                  bool ShouldLazyLoadMetadata) {
28707d523365SDimitry Andric   if (ResumeBit)
28717d523365SDimitry Andric     Stream.JumpToBit(ResumeBit);
2872dff0c46cSDimitry Andric   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
28738f0fd8f6SDimitry Andric     return error("Invalid record");
2874dff0c46cSDimitry Andric 
2875dff0c46cSDimitry Andric   SmallVector<uint64_t, 64> Record;
2876dff0c46cSDimitry Andric 
2877dff0c46cSDimitry Andric   // Read all the records for this module.
2878d88c1a5aSDimitry Andric   while (true) {
2879139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advance();
2880dff0c46cSDimitry Andric 
2881139f7f9bSDimitry Andric     switch (Entry.Kind) {
2882139f7f9bSDimitry Andric     case BitstreamEntry::Error:
28838f0fd8f6SDimitry Andric       return error("Malformed block");
2884139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
28858f0fd8f6SDimitry Andric       return globalCleanup();
2886dff0c46cSDimitry Andric 
2887139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock:
2888139f7f9bSDimitry Andric       switch (Entry.ID) {
2889f22ef01cSRoman Divacky       default:  // Skip unknown content.
2890f22ef01cSRoman Divacky         if (Stream.SkipBlock())
28918f0fd8f6SDimitry Andric           return error("Invalid record");
2892f22ef01cSRoman Divacky         break;
2893f22ef01cSRoman Divacky       case bitc::BLOCKINFO_BLOCK_ID:
2894d88c1a5aSDimitry Andric         if (readBlockInfo())
28958f0fd8f6SDimitry Andric           return error("Malformed block");
2896f22ef01cSRoman Divacky         break;
2897f22ef01cSRoman Divacky       case bitc::PARAMATTR_BLOCK_ID:
2898d88c1a5aSDimitry Andric         if (Error Err = parseAttributeBlock())
2899d88c1a5aSDimitry Andric           return Err;
2900f22ef01cSRoman Divacky         break;
2901139f7f9bSDimitry Andric       case bitc::PARAMATTR_GROUP_BLOCK_ID:
2902d88c1a5aSDimitry Andric         if (Error Err = parseAttributeGroupBlock())
2903d88c1a5aSDimitry Andric           return Err;
2904139f7f9bSDimitry Andric         break;
290517a519f9SDimitry Andric       case bitc::TYPE_BLOCK_ID_NEW:
2906d88c1a5aSDimitry Andric         if (Error Err = parseTypeTable())
2907d88c1a5aSDimitry Andric           return Err;
2908f22ef01cSRoman Divacky         break;
2909f22ef01cSRoman Divacky       case bitc::VALUE_SYMTAB_BLOCK_ID:
29107d523365SDimitry Andric         if (!SeenValueSymbolTable) {
29117d523365SDimitry Andric           // Either this is an old form VST without function index and an
29127d523365SDimitry Andric           // associated VST forward declaration record (which would have caused
29137d523365SDimitry Andric           // the VST to be jumped to and parsed before it was encountered
29147d523365SDimitry Andric           // normally in the stream), or there were no function blocks to
29157d523365SDimitry Andric           // trigger an earlier parsing of the VST.
29167d523365SDimitry Andric           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
2917d88c1a5aSDimitry Andric           if (Error Err = parseValueSymbolTable())
2918d88c1a5aSDimitry Andric             return Err;
2919dff0c46cSDimitry Andric           SeenValueSymbolTable = true;
29207d523365SDimitry Andric         } else {
29217d523365SDimitry Andric           // We must have had a VST forward declaration record, which caused
29227d523365SDimitry Andric           // the parser to jump to and parse the VST earlier.
29237d523365SDimitry Andric           assert(VSTOffset > 0);
29247d523365SDimitry Andric           if (Stream.SkipBlock())
29257d523365SDimitry Andric             return error("Invalid record");
29267d523365SDimitry Andric         }
2927f22ef01cSRoman Divacky         break;
2928f22ef01cSRoman Divacky       case bitc::CONSTANTS_BLOCK_ID:
2929d88c1a5aSDimitry Andric         if (Error Err = parseConstants())
2930d88c1a5aSDimitry Andric           return Err;
2931d88c1a5aSDimitry Andric         if (Error Err = resolveGlobalAndIndirectSymbolInits())
2932d88c1a5aSDimitry Andric           return Err;
2933f22ef01cSRoman Divacky         break;
2934f22ef01cSRoman Divacky       case bitc::METADATA_BLOCK_ID:
2935d88c1a5aSDimitry Andric         if (ShouldLazyLoadMetadata) {
2936d88c1a5aSDimitry Andric           if (Error Err = rememberAndSkipMetadata())
2937d88c1a5aSDimitry Andric             return Err;
2938ff0cc061SDimitry Andric           break;
2939ff0cc061SDimitry Andric         }
2940ff0cc061SDimitry Andric         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2941d88c1a5aSDimitry Andric         if (Error Err = MDLoader->parseModuleMetadata())
2942d88c1a5aSDimitry Andric           return Err;
29437d523365SDimitry Andric         break;
29447d523365SDimitry Andric       case bitc::METADATA_KIND_BLOCK_ID:
2945d88c1a5aSDimitry Andric         if (Error Err = MDLoader->parseMetadataKinds())
2946d88c1a5aSDimitry Andric           return Err;
2947f22ef01cSRoman Divacky         break;
2948f22ef01cSRoman Divacky       case bitc::FUNCTION_BLOCK_ID:
2949f22ef01cSRoman Divacky         // If this is the first function body we've seen, reverse the
2950f22ef01cSRoman Divacky         // FunctionsWithBodies list.
2951dff0c46cSDimitry Andric         if (!SeenFirstFunctionBody) {
2952f22ef01cSRoman Divacky           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2953d88c1a5aSDimitry Andric           if (Error Err = globalCleanup())
2954d88c1a5aSDimitry Andric             return Err;
2955dff0c46cSDimitry Andric           SeenFirstFunctionBody = true;
2956f22ef01cSRoman Divacky         }
2957f22ef01cSRoman Divacky 
29587d523365SDimitry Andric         if (VSTOffset > 0) {
29597d523365SDimitry Andric           // If we have a VST forward declaration record, make sure we
29607d523365SDimitry Andric           // parse the VST now if we haven't already. It is needed to
29617d523365SDimitry Andric           // set up the DeferredFunctionInfo vector for lazy reading.
29627d523365SDimitry Andric           if (!SeenValueSymbolTable) {
2963d88c1a5aSDimitry Andric             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
2964d88c1a5aSDimitry Andric               return Err;
29657d523365SDimitry Andric             SeenValueSymbolTable = true;
29667d523365SDimitry Andric             // Fall through so that we record the NextUnreadBit below.
29677d523365SDimitry Andric             // This is necessary in case we have an anonymous function that
29687d523365SDimitry Andric             // is later materialized. Since it will not have a VST entry we
29697d523365SDimitry Andric             // need to fall back to the lazy parse to find its offset.
29707d523365SDimitry Andric           } else {
29717d523365SDimitry Andric             // If we have a VST forward declaration record, but have already
29727d523365SDimitry Andric             // parsed the VST (just above, when the first function body was
29737d523365SDimitry Andric             // encountered here), then we are resuming the parse after
29747d523365SDimitry Andric             // materializing functions. The ResumeBit points to the
29757d523365SDimitry Andric             // start of the last function block recorded in the
29767d523365SDimitry Andric             // DeferredFunctionInfo map. Skip it.
29777d523365SDimitry Andric             if (Stream.SkipBlock())
29787d523365SDimitry Andric               return error("Invalid record");
29797d523365SDimitry Andric             continue;
29807d523365SDimitry Andric           }
29817d523365SDimitry Andric         }
29827d523365SDimitry Andric 
29837d523365SDimitry Andric         // Support older bitcode files that did not have the function
29847d523365SDimitry Andric         // index in the VST, nor a VST forward declaration record, as
29857d523365SDimitry Andric         // well as anonymous functions that do not have VST entries.
29867d523365SDimitry Andric         // Build the DeferredFunctionInfo vector on the fly.
2987d88c1a5aSDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
2988d88c1a5aSDimitry Andric           return Err;
29897d523365SDimitry Andric 
29903dac3a9bSDimitry Andric         // Suspend parsing when we reach the function bodies. Subsequent
29913dac3a9bSDimitry Andric         // materialization calls will resume it when necessary. If the bitcode
29923dac3a9bSDimitry Andric         // file is old, the symbol table will be at the end instead and will not
29933dac3a9bSDimitry Andric         // have been seen yet. In this case, just finish the parse now.
29943dac3a9bSDimitry Andric         if (SeenValueSymbolTable) {
2995dff0c46cSDimitry Andric           NextUnreadBit = Stream.GetCurrentBitNo();
2996d88c1a5aSDimitry Andric           // After the VST has been parsed, we need to make sure intrinsic name
2997d88c1a5aSDimitry Andric           // are auto-upgraded.
2998d88c1a5aSDimitry Andric           return globalCleanup();
2999dff0c46cSDimitry Andric         }
3000dff0c46cSDimitry Andric         break;
3001dff0c46cSDimitry Andric       case bitc::USELIST_BLOCK_ID:
3002d88c1a5aSDimitry Andric         if (Error Err = parseUseLists())
3003d88c1a5aSDimitry Andric           return Err;
3004f22ef01cSRoman Divacky         break;
30057d523365SDimitry Andric       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3006d88c1a5aSDimitry Andric         if (Error Err = parseOperandBundleTags())
3007d88c1a5aSDimitry Andric           return Err;
30087d523365SDimitry Andric         break;
3009f22ef01cSRoman Divacky       }
3010f22ef01cSRoman Divacky       continue;
3011139f7f9bSDimitry Andric 
3012139f7f9bSDimitry Andric     case BitstreamEntry::Record:
3013139f7f9bSDimitry Andric       // The interesting case.
3014139f7f9bSDimitry Andric       break;
3015f22ef01cSRoman Divacky     }
3016f22ef01cSRoman Divacky 
3017f22ef01cSRoman Divacky     // Read a record.
30187d523365SDimitry Andric     auto BitCode = Stream.readRecord(Entry.ID, Record);
30197d523365SDimitry Andric     switch (BitCode) {
3020f22ef01cSRoman Divacky     default: break;  // Default behavior, ignore unknown content.
30217a7e6055SDimitry Andric     case bitc::MODULE_CODE_VERSION: {
30227a7e6055SDimitry Andric       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
30237a7e6055SDimitry Andric       if (!VersionOrErr)
30247a7e6055SDimitry Andric         return VersionOrErr.takeError();
30257a7e6055SDimitry Andric       UseRelativeIDs = *VersionOrErr >= 1;
30263861d79fSDimitry Andric       break;
30273861d79fSDimitry Andric     }
3028f22ef01cSRoman Divacky     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3029f22ef01cSRoman Divacky       std::string S;
30308f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
30318f0fd8f6SDimitry Andric         return error("Invalid record");
3032f22ef01cSRoman Divacky       TheModule->setTargetTriple(S);
3033f22ef01cSRoman Divacky       break;
3034f22ef01cSRoman Divacky     }
3035f22ef01cSRoman Divacky     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3036f22ef01cSRoman Divacky       std::string S;
30378f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
30388f0fd8f6SDimitry Andric         return error("Invalid record");
3039f22ef01cSRoman Divacky       TheModule->setDataLayout(S);
3040f22ef01cSRoman Divacky       break;
3041f22ef01cSRoman Divacky     }
3042f22ef01cSRoman Divacky     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3043f22ef01cSRoman Divacky       std::string S;
30448f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
30458f0fd8f6SDimitry Andric         return error("Invalid record");
3046f22ef01cSRoman Divacky       TheModule->setModuleInlineAsm(S);
3047f22ef01cSRoman Divacky       break;
3048f22ef01cSRoman Divacky     }
3049f22ef01cSRoman Divacky     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3050139f7f9bSDimitry Andric       // FIXME: Remove in 4.0.
3051f22ef01cSRoman Divacky       std::string S;
30528f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
30538f0fd8f6SDimitry Andric         return error("Invalid record");
3054139f7f9bSDimitry Andric       // Ignore value.
3055f22ef01cSRoman Divacky       break;
3056f22ef01cSRoman Divacky     }
3057f22ef01cSRoman Divacky     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3058f22ef01cSRoman Divacky       std::string S;
30598f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
30608f0fd8f6SDimitry Andric         return error("Invalid record");
3061f22ef01cSRoman Divacky       SectionTable.push_back(S);
3062f22ef01cSRoman Divacky       break;
3063f22ef01cSRoman Divacky     }
3064f22ef01cSRoman Divacky     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3065f22ef01cSRoman Divacky       std::string S;
30668f0fd8f6SDimitry Andric       if (convertToString(Record, 0, S))
30678f0fd8f6SDimitry Andric         return error("Invalid record");
3068f22ef01cSRoman Divacky       GCTable.push_back(S);
3069f22ef01cSRoman Divacky       break;
3070f22ef01cSRoman Divacky     }
30717a7e6055SDimitry Andric     case bitc::MODULE_CODE_COMDAT: {
30727a7e6055SDimitry Andric       if (Error Err = parseComdatRecord(Record))
30737a7e6055SDimitry Andric         return Err;
307491bc56edSDimitry Andric       break;
307591bc56edSDimitry Andric     }
3076f22ef01cSRoman Divacky     case bitc::MODULE_CODE_GLOBALVAR: {
30777a7e6055SDimitry Andric       if (Error Err = parseGlobalVarRecord(Record))
3078d88c1a5aSDimitry Andric         return Err;
3079f22ef01cSRoman Divacky       break;
3080f22ef01cSRoman Divacky     }
3081f22ef01cSRoman Divacky     case bitc::MODULE_CODE_FUNCTION: {
30827a7e6055SDimitry Andric       if (Error Err = parseFunctionRecord(Record))
3083d88c1a5aSDimitry Andric         return Err;
3084f22ef01cSRoman Divacky       break;
3085f22ef01cSRoman Divacky     }
30863ca95b02SDimitry Andric     case bitc::MODULE_CODE_IFUNC:
30877d523365SDimitry Andric     case bitc::MODULE_CODE_ALIAS:
30887d523365SDimitry Andric     case bitc::MODULE_CODE_ALIAS_OLD: {
30897a7e6055SDimitry Andric       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
30907a7e6055SDimitry Andric         return Err;
3091f22ef01cSRoman Divacky       break;
3092f22ef01cSRoman Divacky     }
30937d523365SDimitry Andric     /// MODULE_CODE_VSTOFFSET: [offset]
30947d523365SDimitry Andric     case bitc::MODULE_CODE_VSTOFFSET:
30957d523365SDimitry Andric       if (Record.size() < 1)
30967d523365SDimitry Andric         return error("Invalid record");
3097d88c1a5aSDimitry Andric       // Note that we subtract 1 here because the offset is relative to one word
3098d88c1a5aSDimitry Andric       // before the start of the identification or module block, which was
3099d88c1a5aSDimitry Andric       // historically always the start of the regular bitcode header.
3100d88c1a5aSDimitry Andric       VSTOffset = Record[0] - 1;
31017d523365SDimitry Andric       break;
31023ca95b02SDimitry Andric     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
31033ca95b02SDimitry Andric     case bitc::MODULE_CODE_SOURCE_FILENAME:
31043ca95b02SDimitry Andric       SmallString<128> ValueName;
31053ca95b02SDimitry Andric       if (convertToString(Record, 0, ValueName))
31067d523365SDimitry Andric         return error("Invalid record");
31073ca95b02SDimitry Andric       TheModule->setSourceFileName(ValueName);
31087d523365SDimitry Andric       break;
3109f22ef01cSRoman Divacky     }
3110f22ef01cSRoman Divacky     Record.clear();
3111f22ef01cSRoman Divacky   }
3112f22ef01cSRoman Divacky }
3113f22ef01cSRoman Divacky 
3114d88c1a5aSDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3115d88c1a5aSDimitry Andric                                       bool IsImporting) {
31168f0fd8f6SDimitry Andric   TheModule = M;
3117d88c1a5aSDimitry Andric   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3118d88c1a5aSDimitry Andric                             [&](unsigned ID) { return getTypeByID(ID); });
31197d523365SDimitry Andric   return parseModule(0, ShouldLazyLoadMetadata);
3120f22ef01cSRoman Divacky }
3121f22ef01cSRoman Divacky 
31222754fe60SDimitry Andric 
3123d88c1a5aSDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3124ff0cc061SDimitry Andric   if (!isa<PointerType>(PtrType))
3125d88c1a5aSDimitry Andric     return error("Load/Store operand is not a pointer type");
3126ff0cc061SDimitry Andric   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3127ff0cc061SDimitry Andric 
3128ff0cc061SDimitry Andric   if (ValType && ValType != ElemType)
3129d88c1a5aSDimitry Andric     return error("Explicit load/store type does not match pointee "
31307d523365SDimitry Andric                  "type of pointer operand");
3131ff0cc061SDimitry Andric   if (!PointerType::isLoadableOrStorableType(ElemType))
3132d88c1a5aSDimitry Andric     return error("Cannot load/store from pointer");
3133d88c1a5aSDimitry Andric   return Error::success();
3134ff0cc061SDimitry Andric }
3135ff0cc061SDimitry Andric 
31368f0fd8f6SDimitry Andric /// Lazily parse the specified function body block.
3137d88c1a5aSDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) {
3138f22ef01cSRoman Divacky   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
31398f0fd8f6SDimitry Andric     return error("Invalid record");
3140f22ef01cSRoman Divacky 
31413ca95b02SDimitry Andric   // Unexpected unresolved metadata when parsing function.
3142d88c1a5aSDimitry Andric   if (MDLoader->hasFwdRefs())
31433ca95b02SDimitry Andric     return error("Invalid function metadata: incoming forward references");
31443ca95b02SDimitry Andric 
3145f22ef01cSRoman Divacky   InstructionList.clear();
3146f22ef01cSRoman Divacky   unsigned ModuleValueListSize = ValueList.size();
3147d88c1a5aSDimitry Andric   unsigned ModuleMDLoaderSize = MDLoader->size();
3148f22ef01cSRoman Divacky 
3149f22ef01cSRoman Divacky   // Add all the function arguments to the value table.
31507d523365SDimitry Andric   for (Argument &I : F->args())
31517d523365SDimitry Andric     ValueList.push_back(&I);
3152f22ef01cSRoman Divacky 
3153f22ef01cSRoman Divacky   unsigned NextValueNo = ValueList.size();
315491bc56edSDimitry Andric   BasicBlock *CurBB = nullptr;
3155f22ef01cSRoman Divacky   unsigned CurBBNo = 0;
3156f22ef01cSRoman Divacky 
3157f22ef01cSRoman Divacky   DebugLoc LastLoc;
315839d628a0SDimitry Andric   auto getLastInstruction = [&]() -> Instruction * {
315939d628a0SDimitry Andric     if (CurBB && !CurBB->empty())
316039d628a0SDimitry Andric       return &CurBB->back();
316139d628a0SDimitry Andric     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
316239d628a0SDimitry Andric              !FunctionBBs[CurBBNo - 1]->empty())
316339d628a0SDimitry Andric       return &FunctionBBs[CurBBNo - 1]->back();
316439d628a0SDimitry Andric     return nullptr;
316539d628a0SDimitry Andric   };
3166f22ef01cSRoman Divacky 
31677d523365SDimitry Andric   std::vector<OperandBundleDef> OperandBundles;
31687d523365SDimitry Andric 
3169f22ef01cSRoman Divacky   // Read all the records.
3170f22ef01cSRoman Divacky   SmallVector<uint64_t, 64> Record;
3171d88c1a5aSDimitry Andric 
3172d88c1a5aSDimitry Andric   while (true) {
3173139f7f9bSDimitry Andric     BitstreamEntry Entry = Stream.advance();
3174f22ef01cSRoman Divacky 
3175139f7f9bSDimitry Andric     switch (Entry.Kind) {
3176139f7f9bSDimitry Andric     case BitstreamEntry::Error:
31778f0fd8f6SDimitry Andric       return error("Malformed block");
3178139f7f9bSDimitry Andric     case BitstreamEntry::EndBlock:
3179139f7f9bSDimitry Andric       goto OutOfRecordLoop;
3180139f7f9bSDimitry Andric 
3181139f7f9bSDimitry Andric     case BitstreamEntry::SubBlock:
3182139f7f9bSDimitry Andric       switch (Entry.ID) {
3183f22ef01cSRoman Divacky       default:  // Skip unknown content.
3184f22ef01cSRoman Divacky         if (Stream.SkipBlock())
31858f0fd8f6SDimitry Andric           return error("Invalid record");
3186f22ef01cSRoman Divacky         break;
3187f22ef01cSRoman Divacky       case bitc::CONSTANTS_BLOCK_ID:
3188d88c1a5aSDimitry Andric         if (Error Err = parseConstants())
3189d88c1a5aSDimitry Andric           return Err;
3190f22ef01cSRoman Divacky         NextValueNo = ValueList.size();
3191f22ef01cSRoman Divacky         break;
3192f22ef01cSRoman Divacky       case bitc::VALUE_SYMTAB_BLOCK_ID:
3193d88c1a5aSDimitry Andric         if (Error Err = parseValueSymbolTable())
3194d88c1a5aSDimitry Andric           return Err;
3195f22ef01cSRoman Divacky         break;
3196f22ef01cSRoman Divacky       case bitc::METADATA_ATTACHMENT_ID:
3197d88c1a5aSDimitry Andric         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3198d88c1a5aSDimitry Andric           return Err;
3199f22ef01cSRoman Divacky         break;
3200f22ef01cSRoman Divacky       case bitc::METADATA_BLOCK_ID:
3201d88c1a5aSDimitry Andric         assert(DeferredMetadataInfo.empty() &&
3202d88c1a5aSDimitry Andric                "Must read all module-level metadata before function-level");
3203d88c1a5aSDimitry Andric         if (Error Err = MDLoader->parseFunctionMetadata())
3204d88c1a5aSDimitry Andric           return Err;
3205f22ef01cSRoman Divacky         break;
320639d628a0SDimitry Andric       case bitc::USELIST_BLOCK_ID:
3207d88c1a5aSDimitry Andric         if (Error Err = parseUseLists())
3208d88c1a5aSDimitry Andric           return Err;
320939d628a0SDimitry Andric         break;
3210f22ef01cSRoman Divacky       }
3211f22ef01cSRoman Divacky       continue;
3212f22ef01cSRoman Divacky 
3213139f7f9bSDimitry Andric     case BitstreamEntry::Record:
3214139f7f9bSDimitry Andric       // The interesting case.
3215139f7f9bSDimitry Andric       break;
3216f22ef01cSRoman Divacky     }
3217f22ef01cSRoman Divacky 
3218f22ef01cSRoman Divacky     // Read a record.
3219f22ef01cSRoman Divacky     Record.clear();
322091bc56edSDimitry Andric     Instruction *I = nullptr;
3221139f7f9bSDimitry Andric     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3222f22ef01cSRoman Divacky     switch (BitCode) {
3223f22ef01cSRoman Divacky     default: // Default behavior: reject
32248f0fd8f6SDimitry Andric       return error("Invalid value");
322539d628a0SDimitry Andric     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3226f22ef01cSRoman Divacky       if (Record.size() < 1 || Record[0] == 0)
32278f0fd8f6SDimitry Andric         return error("Invalid record");
3228f22ef01cSRoman Divacky       // Create all the basic blocks for the function.
3229f22ef01cSRoman Divacky       FunctionBBs.resize(Record[0]);
323039d628a0SDimitry Andric 
323139d628a0SDimitry Andric       // See if anything took the address of blocks in this function.
323239d628a0SDimitry Andric       auto BBFRI = BasicBlockFwdRefs.find(F);
323339d628a0SDimitry Andric       if (BBFRI == BasicBlockFwdRefs.end()) {
3234f22ef01cSRoman Divacky         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3235f22ef01cSRoman Divacky           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
323639d628a0SDimitry Andric       } else {
323739d628a0SDimitry Andric         auto &BBRefs = BBFRI->second;
323839d628a0SDimitry Andric         // Check for invalid basic block references.
323939d628a0SDimitry Andric         if (BBRefs.size() > FunctionBBs.size())
32408f0fd8f6SDimitry Andric           return error("Invalid ID");
324139d628a0SDimitry Andric         assert(!BBRefs.empty() && "Unexpected empty array");
324239d628a0SDimitry Andric         assert(!BBRefs.front() && "Invalid reference to entry block");
324339d628a0SDimitry Andric         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
324439d628a0SDimitry Andric              ++I)
324539d628a0SDimitry Andric           if (I < RE && BBRefs[I]) {
324639d628a0SDimitry Andric             BBRefs[I]->insertInto(F);
324739d628a0SDimitry Andric             FunctionBBs[I] = BBRefs[I];
324839d628a0SDimitry Andric           } else {
324939d628a0SDimitry Andric             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
325039d628a0SDimitry Andric           }
325139d628a0SDimitry Andric 
325239d628a0SDimitry Andric         // Erase from the table.
325339d628a0SDimitry Andric         BasicBlockFwdRefs.erase(BBFRI);
325439d628a0SDimitry Andric       }
325539d628a0SDimitry Andric 
3256f22ef01cSRoman Divacky       CurBB = FunctionBBs[0];
3257f22ef01cSRoman Divacky       continue;
325839d628a0SDimitry Andric     }
3259f22ef01cSRoman Divacky 
3260f22ef01cSRoman Divacky     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
3261f22ef01cSRoman Divacky       // This record indicates that the last instruction is at the same
3262f22ef01cSRoman Divacky       // location as the previous instruction with a location.
326339d628a0SDimitry Andric       I = getLastInstruction();
3264f22ef01cSRoman Divacky 
326591bc56edSDimitry Andric       if (!I)
32668f0fd8f6SDimitry Andric         return error("Invalid record");
3267f22ef01cSRoman Divacky       I->setDebugLoc(LastLoc);
326891bc56edSDimitry Andric       I = nullptr;
3269f22ef01cSRoman Divacky       continue;
3270f22ef01cSRoman Divacky 
327117a519f9SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
327239d628a0SDimitry Andric       I = getLastInstruction();
327391bc56edSDimitry Andric       if (!I || Record.size() < 4)
32748f0fd8f6SDimitry Andric         return error("Invalid record");
3275f22ef01cSRoman Divacky 
3276f22ef01cSRoman Divacky       unsigned Line = Record[0], Col = Record[1];
3277f22ef01cSRoman Divacky       unsigned ScopeID = Record[2], IAID = Record[3];
3278f22ef01cSRoman Divacky 
327991bc56edSDimitry Andric       MDNode *Scope = nullptr, *IA = nullptr;
32803ca95b02SDimitry Andric       if (ScopeID) {
3281d88c1a5aSDimitry Andric         Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
32823ca95b02SDimitry Andric         if (!Scope)
32833ca95b02SDimitry Andric           return error("Invalid record");
32843ca95b02SDimitry Andric       }
32853ca95b02SDimitry Andric       if (IAID) {
3286d88c1a5aSDimitry Andric         IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
32873ca95b02SDimitry Andric         if (!IA)
32883ca95b02SDimitry Andric           return error("Invalid record");
32893ca95b02SDimitry Andric       }
3290f22ef01cSRoman Divacky       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3291f22ef01cSRoman Divacky       I->setDebugLoc(LastLoc);
329291bc56edSDimitry Andric       I = nullptr;
3293f22ef01cSRoman Divacky       continue;
3294f22ef01cSRoman Divacky     }
3295f22ef01cSRoman Divacky 
3296f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
3297f22ef01cSRoman Divacky       unsigned OpNum = 0;
3298f22ef01cSRoman Divacky       Value *LHS, *RHS;
3299f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
33003861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3301f22ef01cSRoman Divacky           OpNum+1 > Record.size())
33028f0fd8f6SDimitry Andric         return error("Invalid record");
3303f22ef01cSRoman Divacky 
33048f0fd8f6SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3305f785676fSDimitry Andric       if (Opc == -1)
33068f0fd8f6SDimitry Andric         return error("Invalid record");
3307f22ef01cSRoman Divacky       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3308f22ef01cSRoman Divacky       InstructionList.push_back(I);
3309f22ef01cSRoman Divacky       if (OpNum < Record.size()) {
3310f22ef01cSRoman Divacky         if (Opc == Instruction::Add ||
3311f22ef01cSRoman Divacky             Opc == Instruction::Sub ||
33122754fe60SDimitry Andric             Opc == Instruction::Mul ||
33132754fe60SDimitry Andric             Opc == Instruction::Shl) {
3314f22ef01cSRoman Divacky           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3315f22ef01cSRoman Divacky             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3316f22ef01cSRoman Divacky           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3317f22ef01cSRoman Divacky             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
33182754fe60SDimitry Andric         } else if (Opc == Instruction::SDiv ||
33192754fe60SDimitry Andric                    Opc == Instruction::UDiv ||
33202754fe60SDimitry Andric                    Opc == Instruction::LShr ||
33212754fe60SDimitry Andric                    Opc == Instruction::AShr) {
33222754fe60SDimitry Andric           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3323f22ef01cSRoman Divacky             cast<BinaryOperator>(I)->setIsExact(true);
3324139f7f9bSDimitry Andric         } else if (isa<FPMathOperator>(I)) {
3325875ed548SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3326139f7f9bSDimitry Andric           if (FMF.any())
3327139f7f9bSDimitry Andric             I->setFastMathFlags(FMF);
3328f22ef01cSRoman Divacky         }
3329139f7f9bSDimitry Andric 
3330f22ef01cSRoman Divacky       }
3331f22ef01cSRoman Divacky       break;
3332f22ef01cSRoman Divacky     }
3333f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
3334f22ef01cSRoman Divacky       unsigned OpNum = 0;
3335f22ef01cSRoman Divacky       Value *Op;
3336f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3337f22ef01cSRoman Divacky           OpNum+2 != Record.size())
33388f0fd8f6SDimitry Andric         return error("Invalid record");
3339f22ef01cSRoman Divacky 
33406122f3e6SDimitry Andric       Type *ResTy = getTypeByID(Record[OpNum]);
33418f0fd8f6SDimitry Andric       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
334291bc56edSDimitry Andric       if (Opc == -1 || !ResTy)
33438f0fd8f6SDimitry Andric         return error("Invalid record");
334491bc56edSDimitry Andric       Instruction *Temp = nullptr;
3345f785676fSDimitry Andric       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3346f785676fSDimitry Andric         if (Temp) {
3347f785676fSDimitry Andric           InstructionList.push_back(Temp);
3348f785676fSDimitry Andric           CurBB->getInstList().push_back(Temp);
3349f785676fSDimitry Andric         }
3350f785676fSDimitry Andric       } else {
33517d523365SDimitry Andric         auto CastOp = (Instruction::CastOps)Opc;
33527d523365SDimitry Andric         if (!CastInst::castIsValid(CastOp, Op, ResTy))
33537d523365SDimitry Andric           return error("Invalid cast");
33547d523365SDimitry Andric         I = CastInst::Create(CastOp, Op, ResTy);
3355f785676fSDimitry Andric       }
3356f22ef01cSRoman Divacky       InstructionList.push_back(I);
3357f22ef01cSRoman Divacky       break;
3358f22ef01cSRoman Divacky     }
3359ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3360ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_GEP_OLD:
3361ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3362f22ef01cSRoman Divacky       unsigned OpNum = 0;
3363ff0cc061SDimitry Andric 
3364ff0cc061SDimitry Andric       Type *Ty;
3365ff0cc061SDimitry Andric       bool InBounds;
3366ff0cc061SDimitry Andric 
3367ff0cc061SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3368ff0cc061SDimitry Andric         InBounds = Record[OpNum++];
3369ff0cc061SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
3370ff0cc061SDimitry Andric       } else {
3371ff0cc061SDimitry Andric         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3372ff0cc061SDimitry Andric         Ty = nullptr;
3373ff0cc061SDimitry Andric       }
3374ff0cc061SDimitry Andric 
3375f22ef01cSRoman Divacky       Value *BasePtr;
3376f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
33778f0fd8f6SDimitry Andric         return error("Invalid record");
3378f22ef01cSRoman Divacky 
3379ff0cc061SDimitry Andric       if (!Ty)
3380d88c1a5aSDimitry Andric         Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
3381ff0cc061SDimitry Andric                  ->getElementType();
3382ff0cc061SDimitry Andric       else if (Ty !=
3383d88c1a5aSDimitry Andric                cast<PointerType>(BasePtr->getType()->getScalarType())
3384ff0cc061SDimitry Andric                    ->getElementType())
33858f0fd8f6SDimitry Andric         return error(
3386ff0cc061SDimitry Andric             "Explicit gep type does not match pointee type of pointer operand");
3387ff0cc061SDimitry Andric 
3388f22ef01cSRoman Divacky       SmallVector<Value*, 16> GEPIdx;
3389f22ef01cSRoman Divacky       while (OpNum != Record.size()) {
3390f22ef01cSRoman Divacky         Value *Op;
3391f22ef01cSRoman Divacky         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
33928f0fd8f6SDimitry Andric           return error("Invalid record");
3393f22ef01cSRoman Divacky         GEPIdx.push_back(Op);
3394f22ef01cSRoman Divacky       }
3395f22ef01cSRoman Divacky 
3396ff0cc061SDimitry Andric       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3397ff0cc061SDimitry Andric 
3398f22ef01cSRoman Divacky       InstructionList.push_back(I);
3399ff0cc061SDimitry Andric       if (InBounds)
3400f22ef01cSRoman Divacky         cast<GetElementPtrInst>(I)->setIsInBounds(true);
3401f22ef01cSRoman Divacky       break;
3402f22ef01cSRoman Divacky     }
3403f22ef01cSRoman Divacky 
3404f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3405f22ef01cSRoman Divacky                                        // EXTRACTVAL: [opty, opval, n x indices]
3406f22ef01cSRoman Divacky       unsigned OpNum = 0;
3407f22ef01cSRoman Divacky       Value *Agg;
3408f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
34098f0fd8f6SDimitry Andric         return error("Invalid record");
3410f22ef01cSRoman Divacky 
3411ff0cc061SDimitry Andric       unsigned RecSize = Record.size();
3412ff0cc061SDimitry Andric       if (OpNum == RecSize)
34138f0fd8f6SDimitry Andric         return error("EXTRACTVAL: Invalid instruction with 0 indices");
3414ff0cc061SDimitry Andric 
3415f22ef01cSRoman Divacky       SmallVector<unsigned, 4> EXTRACTVALIdx;
3416ff0cc061SDimitry Andric       Type *CurTy = Agg->getType();
3417ff0cc061SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
3418ff0cc061SDimitry Andric         bool IsArray = CurTy->isArrayTy();
3419ff0cc061SDimitry Andric         bool IsStruct = CurTy->isStructTy();
3420f22ef01cSRoman Divacky         uint64_t Index = Record[OpNum];
3421ff0cc061SDimitry Andric 
3422ff0cc061SDimitry Andric         if (!IsStruct && !IsArray)
34238f0fd8f6SDimitry Andric           return error("EXTRACTVAL: Invalid type");
3424f22ef01cSRoman Divacky         if ((unsigned)Index != Index)
34258f0fd8f6SDimitry Andric           return error("Invalid value");
3426ff0cc061SDimitry Andric         if (IsStruct && Index >= CurTy->subtypes().size())
34278f0fd8f6SDimitry Andric           return error("EXTRACTVAL: Invalid struct index");
3428ff0cc061SDimitry Andric         if (IsArray && Index >= CurTy->getArrayNumElements())
34298f0fd8f6SDimitry Andric           return error("EXTRACTVAL: Invalid array index");
3430f22ef01cSRoman Divacky         EXTRACTVALIdx.push_back((unsigned)Index);
3431ff0cc061SDimitry Andric 
3432ff0cc061SDimitry Andric         if (IsStruct)
3433ff0cc061SDimitry Andric           CurTy = CurTy->subtypes()[Index];
3434ff0cc061SDimitry Andric         else
3435ff0cc061SDimitry Andric           CurTy = CurTy->subtypes()[0];
3436f22ef01cSRoman Divacky       }
3437f22ef01cSRoman Divacky 
343817a519f9SDimitry Andric       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3439f22ef01cSRoman Divacky       InstructionList.push_back(I);
3440f22ef01cSRoman Divacky       break;
3441f22ef01cSRoman Divacky     }
3442f22ef01cSRoman Divacky 
3443f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INSERTVAL: {
3444f22ef01cSRoman Divacky                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
3445f22ef01cSRoman Divacky       unsigned OpNum = 0;
3446f22ef01cSRoman Divacky       Value *Agg;
3447f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
34488f0fd8f6SDimitry Andric         return error("Invalid record");
3449f22ef01cSRoman Divacky       Value *Val;
3450f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
34518f0fd8f6SDimitry Andric         return error("Invalid record");
3452f22ef01cSRoman Divacky 
3453ff0cc061SDimitry Andric       unsigned RecSize = Record.size();
3454ff0cc061SDimitry Andric       if (OpNum == RecSize)
34558f0fd8f6SDimitry Andric         return error("INSERTVAL: Invalid instruction with 0 indices");
3456ff0cc061SDimitry Andric 
3457f22ef01cSRoman Divacky       SmallVector<unsigned, 4> INSERTVALIdx;
3458ff0cc061SDimitry Andric       Type *CurTy = Agg->getType();
3459ff0cc061SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
3460ff0cc061SDimitry Andric         bool IsArray = CurTy->isArrayTy();
3461ff0cc061SDimitry Andric         bool IsStruct = CurTy->isStructTy();
3462f22ef01cSRoman Divacky         uint64_t Index = Record[OpNum];
3463ff0cc061SDimitry Andric 
3464ff0cc061SDimitry Andric         if (!IsStruct && !IsArray)
34658f0fd8f6SDimitry Andric           return error("INSERTVAL: Invalid type");
3466f22ef01cSRoman Divacky         if ((unsigned)Index != Index)
34678f0fd8f6SDimitry Andric           return error("Invalid value");
3468ff0cc061SDimitry Andric         if (IsStruct && Index >= CurTy->subtypes().size())
34698f0fd8f6SDimitry Andric           return error("INSERTVAL: Invalid struct index");
3470ff0cc061SDimitry Andric         if (IsArray && Index >= CurTy->getArrayNumElements())
34718f0fd8f6SDimitry Andric           return error("INSERTVAL: Invalid array index");
3472ff0cc061SDimitry Andric 
3473f22ef01cSRoman Divacky         INSERTVALIdx.push_back((unsigned)Index);
3474ff0cc061SDimitry Andric         if (IsStruct)
3475ff0cc061SDimitry Andric           CurTy = CurTy->subtypes()[Index];
3476ff0cc061SDimitry Andric         else
3477ff0cc061SDimitry Andric           CurTy = CurTy->subtypes()[0];
3478f22ef01cSRoman Divacky       }
3479f22ef01cSRoman Divacky 
3480ff0cc061SDimitry Andric       if (CurTy != Val->getType())
34818f0fd8f6SDimitry Andric         return error("Inserted value type doesn't match aggregate type");
3482ff0cc061SDimitry Andric 
348317a519f9SDimitry Andric       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3484f22ef01cSRoman Divacky       InstructionList.push_back(I);
3485f22ef01cSRoman Divacky       break;
3486f22ef01cSRoman Divacky     }
3487f22ef01cSRoman Divacky 
3488f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3489f22ef01cSRoman Divacky       // obsolete form of select
3490f22ef01cSRoman Divacky       // handles select i1 ... in old bitcode
3491f22ef01cSRoman Divacky       unsigned OpNum = 0;
3492f22ef01cSRoman Divacky       Value *TrueVal, *FalseVal, *Cond;
3493f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
34943861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
34953861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
34968f0fd8f6SDimitry Andric         return error("Invalid record");
3497f22ef01cSRoman Divacky 
3498f22ef01cSRoman Divacky       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3499f22ef01cSRoman Divacky       InstructionList.push_back(I);
3500f22ef01cSRoman Divacky       break;
3501f22ef01cSRoman Divacky     }
3502f22ef01cSRoman Divacky 
3503f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3504f22ef01cSRoman Divacky       // new form of select
3505f22ef01cSRoman Divacky       // handles select i1 or select [N x i1]
3506f22ef01cSRoman Divacky       unsigned OpNum = 0;
3507f22ef01cSRoman Divacky       Value *TrueVal, *FalseVal, *Cond;
3508f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
35093861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3510f22ef01cSRoman Divacky           getValueTypePair(Record, OpNum, NextValueNo, Cond))
35118f0fd8f6SDimitry Andric         return error("Invalid record");
3512f22ef01cSRoman Divacky 
3513f22ef01cSRoman Divacky       // select condition can be either i1 or [N x i1]
35146122f3e6SDimitry Andric       if (VectorType* vector_type =
35156122f3e6SDimitry Andric           dyn_cast<VectorType>(Cond->getType())) {
3516f22ef01cSRoman Divacky         // expect <n x i1>
3517f22ef01cSRoman Divacky         if (vector_type->getElementType() != Type::getInt1Ty(Context))
35188f0fd8f6SDimitry Andric           return error("Invalid type for value");
3519f22ef01cSRoman Divacky       } else {
3520f22ef01cSRoman Divacky         // expect i1
3521f22ef01cSRoman Divacky         if (Cond->getType() != Type::getInt1Ty(Context))
35228f0fd8f6SDimitry Andric           return error("Invalid type for value");
3523f22ef01cSRoman Divacky       }
3524f22ef01cSRoman Divacky 
3525f22ef01cSRoman Divacky       I = SelectInst::Create(Cond, TrueVal, FalseVal);
3526f22ef01cSRoman Divacky       InstructionList.push_back(I);
3527f22ef01cSRoman Divacky       break;
3528f22ef01cSRoman Divacky     }
3529f22ef01cSRoman Divacky 
3530f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3531f22ef01cSRoman Divacky       unsigned OpNum = 0;
3532f22ef01cSRoman Divacky       Value *Vec, *Idx;
3533f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
353491bc56edSDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx))
35358f0fd8f6SDimitry Andric         return error("Invalid record");
3536ff0cc061SDimitry Andric       if (!Vec->getType()->isVectorTy())
35378f0fd8f6SDimitry Andric         return error("Invalid type for value");
3538f22ef01cSRoman Divacky       I = ExtractElementInst::Create(Vec, Idx);
3539f22ef01cSRoman Divacky       InstructionList.push_back(I);
3540f22ef01cSRoman Divacky       break;
3541f22ef01cSRoman Divacky     }
3542f22ef01cSRoman Divacky 
3543f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3544f22ef01cSRoman Divacky       unsigned OpNum = 0;
3545f22ef01cSRoman Divacky       Value *Vec, *Elt, *Idx;
3546ff0cc061SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
35478f0fd8f6SDimitry Andric         return error("Invalid record");
3548ff0cc061SDimitry Andric       if (!Vec->getType()->isVectorTy())
35498f0fd8f6SDimitry Andric         return error("Invalid type for value");
3550ff0cc061SDimitry Andric       if (popValue(Record, OpNum, NextValueNo,
3551f22ef01cSRoman Divacky                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
355291bc56edSDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx))
35538f0fd8f6SDimitry Andric         return error("Invalid record");
3554f22ef01cSRoman Divacky       I = InsertElementInst::Create(Vec, Elt, Idx);
3555f22ef01cSRoman Divacky       InstructionList.push_back(I);
3556f22ef01cSRoman Divacky       break;
3557f22ef01cSRoman Divacky     }
3558f22ef01cSRoman Divacky 
3559f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3560f22ef01cSRoman Divacky       unsigned OpNum = 0;
3561f22ef01cSRoman Divacky       Value *Vec1, *Vec2, *Mask;
3562f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
35633861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
35648f0fd8f6SDimitry Andric         return error("Invalid record");
3565f22ef01cSRoman Divacky 
3566f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
35678f0fd8f6SDimitry Andric         return error("Invalid record");
3568ff0cc061SDimitry Andric       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
35698f0fd8f6SDimitry Andric         return error("Invalid type for value");
3570f22ef01cSRoman Divacky       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3571f22ef01cSRoman Divacky       InstructionList.push_back(I);
3572f22ef01cSRoman Divacky       break;
3573f22ef01cSRoman Divacky     }
3574f22ef01cSRoman Divacky 
3575f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
3576f22ef01cSRoman Divacky       // Old form of ICmp/FCmp returning bool
3577f22ef01cSRoman Divacky       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3578f22ef01cSRoman Divacky       // both legal on vectors but had different behaviour.
3579f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3580f22ef01cSRoman Divacky       // FCmp/ICmp returning bool or vector of bool
3581f22ef01cSRoman Divacky 
3582f22ef01cSRoman Divacky       unsigned OpNum = 0;
3583f22ef01cSRoman Divacky       Value *LHS, *RHS;
3584f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3585875ed548SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3586875ed548SDimitry Andric         return error("Invalid record");
3587875ed548SDimitry Andric 
3588875ed548SDimitry Andric       unsigned PredVal = Record[OpNum];
3589875ed548SDimitry Andric       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3590875ed548SDimitry Andric       FastMathFlags FMF;
3591875ed548SDimitry Andric       if (IsFP && Record.size() > OpNum+1)
3592875ed548SDimitry Andric         FMF = getDecodedFastMathFlags(Record[++OpNum]);
3593875ed548SDimitry Andric 
3594875ed548SDimitry Andric       if (OpNum+1 != Record.size())
35958f0fd8f6SDimitry Andric         return error("Invalid record");
3596f22ef01cSRoman Divacky 
3597f22ef01cSRoman Divacky       if (LHS->getType()->isFPOrFPVectorTy())
3598875ed548SDimitry Andric         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3599f22ef01cSRoman Divacky       else
3600875ed548SDimitry Andric         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3601875ed548SDimitry Andric 
3602875ed548SDimitry Andric       if (FMF.any())
3603875ed548SDimitry Andric         I->setFastMathFlags(FMF);
3604f22ef01cSRoman Divacky       InstructionList.push_back(I);
3605f22ef01cSRoman Divacky       break;
3606f22ef01cSRoman Divacky     }
3607f22ef01cSRoman Divacky 
3608f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3609f22ef01cSRoman Divacky       {
3610f22ef01cSRoman Divacky         unsigned Size = Record.size();
3611f22ef01cSRoman Divacky         if (Size == 0) {
3612f22ef01cSRoman Divacky           I = ReturnInst::Create(Context);
3613f22ef01cSRoman Divacky           InstructionList.push_back(I);
3614f22ef01cSRoman Divacky           break;
3615f22ef01cSRoman Divacky         }
3616f22ef01cSRoman Divacky 
3617f22ef01cSRoman Divacky         unsigned OpNum = 0;
361891bc56edSDimitry Andric         Value *Op = nullptr;
3619f22ef01cSRoman Divacky         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
36208f0fd8f6SDimitry Andric           return error("Invalid record");
362117a519f9SDimitry Andric         if (OpNum != Record.size())
36228f0fd8f6SDimitry Andric           return error("Invalid record");
3623f22ef01cSRoman Divacky 
362417a519f9SDimitry Andric         I = ReturnInst::Create(Context, Op);
3625f22ef01cSRoman Divacky         InstructionList.push_back(I);
3626f22ef01cSRoman Divacky         break;
3627f22ef01cSRoman Divacky       }
3628f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3629f22ef01cSRoman Divacky       if (Record.size() != 1 && Record.size() != 3)
36308f0fd8f6SDimitry Andric         return error("Invalid record");
3631f22ef01cSRoman Divacky       BasicBlock *TrueDest = getBasicBlock(Record[0]);
363291bc56edSDimitry Andric       if (!TrueDest)
36338f0fd8f6SDimitry Andric         return error("Invalid record");
3634f22ef01cSRoman Divacky 
3635f22ef01cSRoman Divacky       if (Record.size() == 1) {
3636f22ef01cSRoman Divacky         I = BranchInst::Create(TrueDest);
3637f22ef01cSRoman Divacky         InstructionList.push_back(I);
3638f22ef01cSRoman Divacky       }
3639f22ef01cSRoman Divacky       else {
3640f22ef01cSRoman Divacky         BasicBlock *FalseDest = getBasicBlock(Record[1]);
36413861d79fSDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo,
36423861d79fSDimitry Andric                                Type::getInt1Ty(Context));
364391bc56edSDimitry Andric         if (!FalseDest || !Cond)
36448f0fd8f6SDimitry Andric           return error("Invalid record");
3645f22ef01cSRoman Divacky         I = BranchInst::Create(TrueDest, FalseDest, Cond);
3646f22ef01cSRoman Divacky         InstructionList.push_back(I);
3647f22ef01cSRoman Divacky       }
3648f22ef01cSRoman Divacky       break;
3649f22ef01cSRoman Divacky     }
36507d523365SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
36517d523365SDimitry Andric       if (Record.size() != 1 && Record.size() != 2)
36527d523365SDimitry Andric         return error("Invalid record");
36537d523365SDimitry Andric       unsigned Idx = 0;
36547d523365SDimitry Andric       Value *CleanupPad =
36557d523365SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
36567d523365SDimitry Andric       if (!CleanupPad)
36577d523365SDimitry Andric         return error("Invalid record");
36587d523365SDimitry Andric       BasicBlock *UnwindDest = nullptr;
36597d523365SDimitry Andric       if (Record.size() == 2) {
36607d523365SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
36617d523365SDimitry Andric         if (!UnwindDest)
36627d523365SDimitry Andric           return error("Invalid record");
36637d523365SDimitry Andric       }
36647d523365SDimitry Andric 
36657d523365SDimitry Andric       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
36667d523365SDimitry Andric       InstructionList.push_back(I);
36677d523365SDimitry Andric       break;
36687d523365SDimitry Andric     }
36697d523365SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
36707d523365SDimitry Andric       if (Record.size() != 2)
36717d523365SDimitry Andric         return error("Invalid record");
36727d523365SDimitry Andric       unsigned Idx = 0;
36737d523365SDimitry Andric       Value *CatchPad =
36747d523365SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
36757d523365SDimitry Andric       if (!CatchPad)
36767d523365SDimitry Andric         return error("Invalid record");
36777d523365SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[Idx++]);
36787d523365SDimitry Andric       if (!BB)
36797d523365SDimitry Andric         return error("Invalid record");
36807d523365SDimitry Andric 
36817d523365SDimitry Andric       I = CatchReturnInst::Create(CatchPad, BB);
36827d523365SDimitry Andric       InstructionList.push_back(I);
36837d523365SDimitry Andric       break;
36847d523365SDimitry Andric     }
36857d523365SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
36867d523365SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
36877d523365SDimitry Andric       if (Record.size() < 2)
36887d523365SDimitry Andric         return error("Invalid record");
36897d523365SDimitry Andric 
36907d523365SDimitry Andric       unsigned Idx = 0;
36917d523365SDimitry Andric 
36927d523365SDimitry Andric       Value *ParentPad =
36937d523365SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
36947d523365SDimitry Andric 
36957d523365SDimitry Andric       unsigned NumHandlers = Record[Idx++];
36967d523365SDimitry Andric 
36977d523365SDimitry Andric       SmallVector<BasicBlock *, 2> Handlers;
36987d523365SDimitry Andric       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
36997d523365SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[Idx++]);
37007d523365SDimitry Andric         if (!BB)
37017d523365SDimitry Andric           return error("Invalid record");
37027d523365SDimitry Andric         Handlers.push_back(BB);
37037d523365SDimitry Andric       }
37047d523365SDimitry Andric 
37057d523365SDimitry Andric       BasicBlock *UnwindDest = nullptr;
37067d523365SDimitry Andric       if (Idx + 1 == Record.size()) {
37077d523365SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
37087d523365SDimitry Andric         if (!UnwindDest)
37097d523365SDimitry Andric           return error("Invalid record");
37107d523365SDimitry Andric       }
37117d523365SDimitry Andric 
37127d523365SDimitry Andric       if (Record.size() != Idx)
37137d523365SDimitry Andric         return error("Invalid record");
37147d523365SDimitry Andric 
37157d523365SDimitry Andric       auto *CatchSwitch =
37167d523365SDimitry Andric           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
37177d523365SDimitry Andric       for (BasicBlock *Handler : Handlers)
37187d523365SDimitry Andric         CatchSwitch->addHandler(Handler);
37197d523365SDimitry Andric       I = CatchSwitch;
37207d523365SDimitry Andric       InstructionList.push_back(I);
37217d523365SDimitry Andric       break;
37227d523365SDimitry Andric     }
37237d523365SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHPAD:
37247d523365SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
37257d523365SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
37267d523365SDimitry Andric       if (Record.size() < 2)
37277d523365SDimitry Andric         return error("Invalid record");
37287d523365SDimitry Andric 
37297d523365SDimitry Andric       unsigned Idx = 0;
37307d523365SDimitry Andric 
37317d523365SDimitry Andric       Value *ParentPad =
37327d523365SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
37337d523365SDimitry Andric 
37347d523365SDimitry Andric       unsigned NumArgOperands = Record[Idx++];
37357d523365SDimitry Andric 
37367d523365SDimitry Andric       SmallVector<Value *, 2> Args;
37377d523365SDimitry Andric       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
37387d523365SDimitry Andric         Value *Val;
37397d523365SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val))
37407d523365SDimitry Andric           return error("Invalid record");
37417d523365SDimitry Andric         Args.push_back(Val);
37427d523365SDimitry Andric       }
37437d523365SDimitry Andric 
37447d523365SDimitry Andric       if (Record.size() != Idx)
37457d523365SDimitry Andric         return error("Invalid record");
37467d523365SDimitry Andric 
37477d523365SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
37487d523365SDimitry Andric         I = CleanupPadInst::Create(ParentPad, Args);
37497d523365SDimitry Andric       else
37507d523365SDimitry Andric         I = CatchPadInst::Create(ParentPad, Args);
37517d523365SDimitry Andric       InstructionList.push_back(I);
37527d523365SDimitry Andric       break;
37537d523365SDimitry Andric     }
3754f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
37557ae0e2c9SDimitry Andric       // Check magic
37567ae0e2c9SDimitry Andric       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3757f785676fSDimitry Andric         // "New" SwitchInst format with case ranges. The changes to write this
3758f785676fSDimitry Andric         // format were reverted but we still recognize bitcode that uses it.
3759f785676fSDimitry Andric         // Hopefully someday we will have support for case ranges and can use
3760f785676fSDimitry Andric         // this format again.
37617ae0e2c9SDimitry Andric 
37627ae0e2c9SDimitry Andric         Type *OpTy = getTypeByID(Record[1]);
37637ae0e2c9SDimitry Andric         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
37647ae0e2c9SDimitry Andric 
37653861d79fSDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
37667ae0e2c9SDimitry Andric         BasicBlock *Default = getBasicBlock(Record[3]);
376791bc56edSDimitry Andric         if (!OpTy || !Cond || !Default)
37688f0fd8f6SDimitry Andric           return error("Invalid record");
37697ae0e2c9SDimitry Andric 
37707ae0e2c9SDimitry Andric         unsigned NumCases = Record[4];
37717ae0e2c9SDimitry Andric 
37727ae0e2c9SDimitry Andric         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
37737ae0e2c9SDimitry Andric         InstructionList.push_back(SI);
37747ae0e2c9SDimitry Andric 
37757ae0e2c9SDimitry Andric         unsigned CurIdx = 5;
37767ae0e2c9SDimitry Andric         for (unsigned i = 0; i != NumCases; ++i) {
3777f785676fSDimitry Andric           SmallVector<ConstantInt*, 1> CaseVals;
37787ae0e2c9SDimitry Andric           unsigned NumItems = Record[CurIdx++];
37797ae0e2c9SDimitry Andric           for (unsigned ci = 0; ci != NumItems; ++ci) {
37807ae0e2c9SDimitry Andric             bool isSingleNumber = Record[CurIdx++];
37817ae0e2c9SDimitry Andric 
37827ae0e2c9SDimitry Andric             APInt Low;
37837ae0e2c9SDimitry Andric             unsigned ActiveWords = 1;
37847ae0e2c9SDimitry Andric             if (ValueBitWidth > 64)
37857ae0e2c9SDimitry Andric               ActiveWords = Record[CurIdx++];
37868f0fd8f6SDimitry Andric             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
37877ae0e2c9SDimitry Andric                                 ValueBitWidth);
37887ae0e2c9SDimitry Andric             CurIdx += ActiveWords;
37897ae0e2c9SDimitry Andric 
37907ae0e2c9SDimitry Andric             if (!isSingleNumber) {
37917ae0e2c9SDimitry Andric               ActiveWords = 1;
37927ae0e2c9SDimitry Andric               if (ValueBitWidth > 64)
37937ae0e2c9SDimitry Andric                 ActiveWords = Record[CurIdx++];
37948f0fd8f6SDimitry Andric               APInt High = readWideAPInt(
37958f0fd8f6SDimitry Andric                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
37967ae0e2c9SDimitry Andric               CurIdx += ActiveWords;
3797f785676fSDimitry Andric 
3798f785676fSDimitry Andric               // FIXME: It is not clear whether values in the range should be
3799f785676fSDimitry Andric               // compared as signed or unsigned values. The partially
3800f785676fSDimitry Andric               // implemented changes that used this format in the past used
3801f785676fSDimitry Andric               // unsigned comparisons.
3802f785676fSDimitry Andric               for ( ; Low.ule(High); ++Low)
3803f785676fSDimitry Andric                 CaseVals.push_back(ConstantInt::get(Context, Low));
38047ae0e2c9SDimitry Andric             } else
3805f785676fSDimitry Andric               CaseVals.push_back(ConstantInt::get(Context, Low));
38067ae0e2c9SDimitry Andric           }
38077ae0e2c9SDimitry Andric           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3808f785676fSDimitry Andric           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3809f785676fSDimitry Andric                  cve = CaseVals.end(); cvi != cve; ++cvi)
3810f785676fSDimitry Andric             SI->addCase(*cvi, DestBB);
38117ae0e2c9SDimitry Andric         }
38127ae0e2c9SDimitry Andric         I = SI;
38137ae0e2c9SDimitry Andric         break;
38147ae0e2c9SDimitry Andric       }
38157ae0e2c9SDimitry Andric 
38167ae0e2c9SDimitry Andric       // Old SwitchInst format without case ranges.
38177ae0e2c9SDimitry Andric 
3818f22ef01cSRoman Divacky       if (Record.size() < 3 || (Record.size() & 1) == 0)
38198f0fd8f6SDimitry Andric         return error("Invalid record");
38206122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
38213861d79fSDimitry Andric       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3822f22ef01cSRoman Divacky       BasicBlock *Default = getBasicBlock(Record[2]);
382391bc56edSDimitry Andric       if (!OpTy || !Cond || !Default)
38248f0fd8f6SDimitry Andric         return error("Invalid record");
3825f22ef01cSRoman Divacky       unsigned NumCases = (Record.size()-3)/2;
3826f22ef01cSRoman Divacky       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3827f22ef01cSRoman Divacky       InstructionList.push_back(SI);
3828f22ef01cSRoman Divacky       for (unsigned i = 0, e = NumCases; i != e; ++i) {
3829f22ef01cSRoman Divacky         ConstantInt *CaseVal =
3830f22ef01cSRoman Divacky           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3831f22ef01cSRoman Divacky         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
383291bc56edSDimitry Andric         if (!CaseVal || !DestBB) {
3833f22ef01cSRoman Divacky           delete SI;
38348f0fd8f6SDimitry Andric           return error("Invalid record");
3835f22ef01cSRoman Divacky         }
3836f22ef01cSRoman Divacky         SI->addCase(CaseVal, DestBB);
3837f22ef01cSRoman Divacky       }
3838f22ef01cSRoman Divacky       I = SI;
3839f22ef01cSRoman Divacky       break;
3840f22ef01cSRoman Divacky     }
3841f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3842f22ef01cSRoman Divacky       if (Record.size() < 2)
38438f0fd8f6SDimitry Andric         return error("Invalid record");
38446122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
38453861d79fSDimitry Andric       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
384691bc56edSDimitry Andric       if (!OpTy || !Address)
38478f0fd8f6SDimitry Andric         return error("Invalid record");
3848f22ef01cSRoman Divacky       unsigned NumDests = Record.size()-2;
3849f22ef01cSRoman Divacky       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3850f22ef01cSRoman Divacky       InstructionList.push_back(IBI);
3851f22ef01cSRoman Divacky       for (unsigned i = 0, e = NumDests; i != e; ++i) {
3852f22ef01cSRoman Divacky         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3853f22ef01cSRoman Divacky           IBI->addDestination(DestBB);
3854f22ef01cSRoman Divacky         } else {
3855f22ef01cSRoman Divacky           delete IBI;
38568f0fd8f6SDimitry Andric           return error("Invalid record");
3857f22ef01cSRoman Divacky         }
3858f22ef01cSRoman Divacky       }
3859f22ef01cSRoman Divacky       I = IBI;
3860f22ef01cSRoman Divacky       break;
3861f22ef01cSRoman Divacky     }
3862f22ef01cSRoman Divacky 
3863f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_INVOKE: {
3864f22ef01cSRoman Divacky       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3865f785676fSDimitry Andric       if (Record.size() < 4)
38668f0fd8f6SDimitry Andric         return error("Invalid record");
3867ff0cc061SDimitry Andric       unsigned OpNum = 0;
38687a7e6055SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
3869ff0cc061SDimitry Andric       unsigned CCInfo = Record[OpNum++];
3870ff0cc061SDimitry Andric       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3871ff0cc061SDimitry Andric       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3872f22ef01cSRoman Divacky 
3873ff0cc061SDimitry Andric       FunctionType *FTy = nullptr;
3874ff0cc061SDimitry Andric       if (CCInfo >> 13 & 1 &&
3875ff0cc061SDimitry Andric           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
38768f0fd8f6SDimitry Andric         return error("Explicit invoke type is not a function type");
3877ff0cc061SDimitry Andric 
3878f22ef01cSRoman Divacky       Value *Callee;
3879f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
38808f0fd8f6SDimitry Andric         return error("Invalid record");
3881f22ef01cSRoman Divacky 
38826122f3e6SDimitry Andric       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3883ff0cc061SDimitry Andric       if (!CalleeTy)
38848f0fd8f6SDimitry Andric         return error("Callee is not a pointer");
3885ff0cc061SDimitry Andric       if (!FTy) {
3886ff0cc061SDimitry Andric         FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3887ff0cc061SDimitry Andric         if (!FTy)
38888f0fd8f6SDimitry Andric           return error("Callee is not of pointer to function type");
3889ff0cc061SDimitry Andric       } else if (CalleeTy->getElementType() != FTy)
38908f0fd8f6SDimitry Andric         return error("Explicit invoke type does not match pointee type of "
3891ff0cc061SDimitry Andric                      "callee operand");
3892ff0cc061SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
38938f0fd8f6SDimitry Andric         return error("Insufficient operands to call");
3894f22ef01cSRoman Divacky 
3895f22ef01cSRoman Divacky       SmallVector<Value*, 16> Ops;
3896f22ef01cSRoman Divacky       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
38973861d79fSDimitry Andric         Ops.push_back(getValue(Record, OpNum, NextValueNo,
38983861d79fSDimitry Andric                                FTy->getParamType(i)));
389991bc56edSDimitry Andric         if (!Ops.back())
39008f0fd8f6SDimitry Andric           return error("Invalid record");
3901f22ef01cSRoman Divacky       }
3902f22ef01cSRoman Divacky 
3903f22ef01cSRoman Divacky       if (!FTy->isVarArg()) {
3904f22ef01cSRoman Divacky         if (Record.size() != OpNum)
39058f0fd8f6SDimitry Andric           return error("Invalid record");
3906f22ef01cSRoman Divacky       } else {
3907f22ef01cSRoman Divacky         // Read type/value pairs for varargs params.
3908f22ef01cSRoman Divacky         while (OpNum != Record.size()) {
3909f22ef01cSRoman Divacky           Value *Op;
3910f22ef01cSRoman Divacky           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
39118f0fd8f6SDimitry Andric             return error("Invalid record");
3912f22ef01cSRoman Divacky           Ops.push_back(Op);
3913f22ef01cSRoman Divacky         }
3914f22ef01cSRoman Divacky       }
3915f22ef01cSRoman Divacky 
39167d523365SDimitry Andric       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
39177d523365SDimitry Andric       OperandBundles.clear();
3918f22ef01cSRoman Divacky       InstructionList.push_back(I);
39197d523365SDimitry Andric       cast<InvokeInst>(I)->setCallingConv(
39207d523365SDimitry Andric           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
3921f22ef01cSRoman Divacky       cast<InvokeInst>(I)->setAttributes(PAL);
3922f22ef01cSRoman Divacky       break;
3923f22ef01cSRoman Divacky     }
39246122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
39256122f3e6SDimitry Andric       unsigned Idx = 0;
392691bc56edSDimitry Andric       Value *Val = nullptr;
39276122f3e6SDimitry Andric       if (getValueTypePair(Record, Idx, NextValueNo, Val))
39288f0fd8f6SDimitry Andric         return error("Invalid record");
39296122f3e6SDimitry Andric       I = ResumeInst::Create(Val);
39306122f3e6SDimitry Andric       InstructionList.push_back(I);
39316122f3e6SDimitry Andric       break;
39326122f3e6SDimitry Andric     }
3933f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3934f22ef01cSRoman Divacky       I = new UnreachableInst(Context);
3935f22ef01cSRoman Divacky       InstructionList.push_back(I);
3936f22ef01cSRoman Divacky       break;
3937f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3938f22ef01cSRoman Divacky       if (Record.size() < 1 || ((Record.size()-1)&1))
39398f0fd8f6SDimitry Andric         return error("Invalid record");
39406122f3e6SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
3941f785676fSDimitry Andric       if (!Ty)
39428f0fd8f6SDimitry Andric         return error("Invalid record");
3943f22ef01cSRoman Divacky 
39443b0f4066SDimitry Andric       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3945f22ef01cSRoman Divacky       InstructionList.push_back(PN);
3946f22ef01cSRoman Divacky 
3947f22ef01cSRoman Divacky       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
39483861d79fSDimitry Andric         Value *V;
39493861d79fSDimitry Andric         // With the new function encoding, it is possible that operands have
39503861d79fSDimitry Andric         // negative IDs (for forward references).  Use a signed VBR
39513861d79fSDimitry Andric         // representation to keep the encoding small.
39523861d79fSDimitry Andric         if (UseRelativeIDs)
39533861d79fSDimitry Andric           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
39543861d79fSDimitry Andric         else
39553861d79fSDimitry Andric           V = getValue(Record, 1+i, NextValueNo, Ty);
3956f22ef01cSRoman Divacky         BasicBlock *BB = getBasicBlock(Record[2+i]);
3957f785676fSDimitry Andric         if (!V || !BB)
39588f0fd8f6SDimitry Andric           return error("Invalid record");
3959f22ef01cSRoman Divacky         PN->addIncoming(V, BB);
3960f22ef01cSRoman Divacky       }
3961f22ef01cSRoman Divacky       I = PN;
3962f22ef01cSRoman Divacky       break;
3963f22ef01cSRoman Divacky     }
3964f22ef01cSRoman Divacky 
39658f0fd8f6SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD:
39668f0fd8f6SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
39676122f3e6SDimitry Andric       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
39686122f3e6SDimitry Andric       unsigned Idx = 0;
39698f0fd8f6SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
39708f0fd8f6SDimitry Andric         if (Record.size() < 3)
39718f0fd8f6SDimitry Andric           return error("Invalid record");
39728f0fd8f6SDimitry Andric       } else {
39738f0fd8f6SDimitry Andric         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
39746122f3e6SDimitry Andric         if (Record.size() < 4)
39758f0fd8f6SDimitry Andric           return error("Invalid record");
39768f0fd8f6SDimitry Andric       }
39776122f3e6SDimitry Andric       Type *Ty = getTypeByID(Record[Idx++]);
3978f785676fSDimitry Andric       if (!Ty)
39798f0fd8f6SDimitry Andric         return error("Invalid record");
39808f0fd8f6SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
398191bc56edSDimitry Andric         Value *PersFn = nullptr;
39826122f3e6SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
39838f0fd8f6SDimitry Andric           return error("Invalid record");
39848f0fd8f6SDimitry Andric 
39858f0fd8f6SDimitry Andric         if (!F->hasPersonalityFn())
39868f0fd8f6SDimitry Andric           F->setPersonalityFn(cast<Constant>(PersFn));
39878f0fd8f6SDimitry Andric         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
39888f0fd8f6SDimitry Andric           return error("Personality function mismatch");
39898f0fd8f6SDimitry Andric       }
39906122f3e6SDimitry Andric 
39916122f3e6SDimitry Andric       bool IsCleanup = !!Record[Idx++];
39926122f3e6SDimitry Andric       unsigned NumClauses = Record[Idx++];
39938f0fd8f6SDimitry Andric       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
39946122f3e6SDimitry Andric       LP->setCleanup(IsCleanup);
39956122f3e6SDimitry Andric       for (unsigned J = 0; J != NumClauses; ++J) {
39966122f3e6SDimitry Andric         LandingPadInst::ClauseType CT =
39976122f3e6SDimitry Andric           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
39986122f3e6SDimitry Andric         Value *Val;
39996122f3e6SDimitry Andric 
40006122f3e6SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
40016122f3e6SDimitry Andric           delete LP;
40028f0fd8f6SDimitry Andric           return error("Invalid record");
40036122f3e6SDimitry Andric         }
40046122f3e6SDimitry Andric 
40056122f3e6SDimitry Andric         assert((CT != LandingPadInst::Catch ||
40066122f3e6SDimitry Andric                 !isa<ArrayType>(Val->getType())) &&
40076122f3e6SDimitry Andric                "Catch clause has a invalid type!");
40086122f3e6SDimitry Andric         assert((CT != LandingPadInst::Filter ||
40096122f3e6SDimitry Andric                 isa<ArrayType>(Val->getType())) &&
40106122f3e6SDimitry Andric                "Filter clause has invalid type!");
401191bc56edSDimitry Andric         LP->addClause(cast<Constant>(Val));
40126122f3e6SDimitry Andric       }
40136122f3e6SDimitry Andric 
40146122f3e6SDimitry Andric       I = LP;
40156122f3e6SDimitry Andric       InstructionList.push_back(I);
40166122f3e6SDimitry Andric       break;
40176122f3e6SDimitry Andric     }
40186122f3e6SDimitry Andric 
401917a519f9SDimitry Andric     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
402017a519f9SDimitry Andric       if (Record.size() != 4)
40218f0fd8f6SDimitry Andric         return error("Invalid record");
4022ff0cc061SDimitry Andric       uint64_t AlignRecord = Record[3];
4023ff0cc061SDimitry Andric       const uint64_t InAllocaMask = uint64_t(1) << 5;
4024ff0cc061SDimitry Andric       const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
40253ca95b02SDimitry Andric       const uint64_t SwiftErrorMask = uint64_t(1) << 7;
40263ca95b02SDimitry Andric       const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
40273ca95b02SDimitry Andric                                 SwiftErrorMask;
4028ff0cc061SDimitry Andric       bool InAlloca = AlignRecord & InAllocaMask;
40293ca95b02SDimitry Andric       bool SwiftError = AlignRecord & SwiftErrorMask;
4030ff0cc061SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
4031ff0cc061SDimitry Andric       if ((AlignRecord & ExplicitTypeMask) == 0) {
4032ff0cc061SDimitry Andric         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4033ff0cc061SDimitry Andric         if (!PTy)
40348f0fd8f6SDimitry Andric           return error("Old-style alloca with a non-pointer type");
4035ff0cc061SDimitry Andric         Ty = PTy->getElementType();
4036ff0cc061SDimitry Andric       }
40376122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[1]);
403817a519f9SDimitry Andric       Value *Size = getFnValueByID(Record[2], OpTy);
4039ff0cc061SDimitry Andric       unsigned Align;
4040d88c1a5aSDimitry Andric       if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4041d88c1a5aSDimitry Andric         return Err;
4042ff0cc061SDimitry Andric       }
4043f785676fSDimitry Andric       if (!Ty || !Size)
40448f0fd8f6SDimitry Andric         return error("Invalid record");
40457a7e6055SDimitry Andric 
40467a7e6055SDimitry Andric       // FIXME: Make this an optional field.
40477a7e6055SDimitry Andric       const DataLayout &DL = TheModule->getDataLayout();
40487a7e6055SDimitry Andric       unsigned AS = DL.getAllocaAddrSpace();
40497a7e6055SDimitry Andric 
40507a7e6055SDimitry Andric       AllocaInst *AI = new AllocaInst(Ty, AS, Size, Align);
405191bc56edSDimitry Andric       AI->setUsedWithInAlloca(InAlloca);
40523ca95b02SDimitry Andric       AI->setSwiftError(SwiftError);
405391bc56edSDimitry Andric       I = AI;
4054f22ef01cSRoman Divacky       InstructionList.push_back(I);
4055f22ef01cSRoman Divacky       break;
4056f22ef01cSRoman Divacky     }
4057f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4058f22ef01cSRoman Divacky       unsigned OpNum = 0;
4059f22ef01cSRoman Divacky       Value *Op;
4060f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4061ff0cc061SDimitry Andric           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
40628f0fd8f6SDimitry Andric         return error("Invalid record");
4063f22ef01cSRoman Divacky 
4064ff0cc061SDimitry Andric       Type *Ty = nullptr;
4065ff0cc061SDimitry Andric       if (OpNum + 3 == Record.size())
4066ff0cc061SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
4067d88c1a5aSDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4068d88c1a5aSDimitry Andric         return Err;
4069ff0cc061SDimitry Andric       if (!Ty)
4070ff0cc061SDimitry Andric         Ty = cast<PointerType>(Op->getType())->getElementType();
4071ff0cc061SDimitry Andric 
4072ff0cc061SDimitry Andric       unsigned Align;
4073d88c1a5aSDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4074d88c1a5aSDimitry Andric         return Err;
4075ff0cc061SDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4076ff0cc061SDimitry Andric 
4077f22ef01cSRoman Divacky       InstructionList.push_back(I);
4078f22ef01cSRoman Divacky       break;
4079f22ef01cSRoman Divacky     }
40806122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_LOADATOMIC: {
40816122f3e6SDimitry Andric        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
40826122f3e6SDimitry Andric       unsigned OpNum = 0;
40836122f3e6SDimitry Andric       Value *Op;
40846122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4085ff0cc061SDimitry Andric           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
40868f0fd8f6SDimitry Andric         return error("Invalid record");
40876122f3e6SDimitry Andric 
4088ff0cc061SDimitry Andric       Type *Ty = nullptr;
4089ff0cc061SDimitry Andric       if (OpNum + 5 == Record.size())
4090ff0cc061SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
4091d88c1a5aSDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4092d88c1a5aSDimitry Andric         return Err;
4093ff0cc061SDimitry Andric       if (!Ty)
4094ff0cc061SDimitry Andric         Ty = cast<PointerType>(Op->getType())->getElementType();
4095ff0cc061SDimitry Andric 
40968f0fd8f6SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
40973ca95b02SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
40983ca95b02SDimitry Andric           Ordering == AtomicOrdering::Release ||
40993ca95b02SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
41008f0fd8f6SDimitry Andric         return error("Invalid record");
41013ca95b02SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
41028f0fd8f6SDimitry Andric         return error("Invalid record");
41038f0fd8f6SDimitry Andric       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
41046122f3e6SDimitry Andric 
4105ff0cc061SDimitry Andric       unsigned Align;
4106d88c1a5aSDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4107d88c1a5aSDimitry Andric         return Err;
4108ff0cc061SDimitry Andric       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4109ff0cc061SDimitry Andric 
41106122f3e6SDimitry Andric       InstructionList.push_back(I);
41116122f3e6SDimitry Andric       break;
41126122f3e6SDimitry Andric     }
4113ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_STORE:
4114ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4115f22ef01cSRoman Divacky       unsigned OpNum = 0;
4116f22ef01cSRoman Divacky       Value *Val, *Ptr;
4117f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4118ff0cc061SDimitry Andric           (BitCode == bitc::FUNC_CODE_INST_STORE
4119ff0cc061SDimitry Andric                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4120ff0cc061SDimitry Andric                : popValue(Record, OpNum, NextValueNo,
4121ff0cc061SDimitry Andric                           cast<PointerType>(Ptr->getType())->getElementType(),
4122ff0cc061SDimitry Andric                           Val)) ||
4123f22ef01cSRoman Divacky           OpNum + 2 != Record.size())
41248f0fd8f6SDimitry Andric         return error("Invalid record");
4125f22ef01cSRoman Divacky 
4126d88c1a5aSDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4127d88c1a5aSDimitry Andric         return Err;
4128ff0cc061SDimitry Andric       unsigned Align;
4129d88c1a5aSDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4130d88c1a5aSDimitry Andric         return Err;
4131ff0cc061SDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4132f22ef01cSRoman Divacky       InstructionList.push_back(I);
4133f22ef01cSRoman Divacky       break;
4134f22ef01cSRoman Divacky     }
4135ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC:
4136ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
41376122f3e6SDimitry Andric       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
41386122f3e6SDimitry Andric       unsigned OpNum = 0;
41396122f3e6SDimitry Andric       Value *Val, *Ptr;
41406122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
41413ca95b02SDimitry Andric           !isa<PointerType>(Ptr->getType()) ||
4142ff0cc061SDimitry Andric           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4143ff0cc061SDimitry Andric                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4144ff0cc061SDimitry Andric                : popValue(Record, OpNum, NextValueNo,
4145ff0cc061SDimitry Andric                           cast<PointerType>(Ptr->getType())->getElementType(),
4146ff0cc061SDimitry Andric                           Val)) ||
41476122f3e6SDimitry Andric           OpNum + 4 != Record.size())
41488f0fd8f6SDimitry Andric         return error("Invalid record");
41496122f3e6SDimitry Andric 
4150d88c1a5aSDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4151d88c1a5aSDimitry Andric         return Err;
41528f0fd8f6SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
41533ca95b02SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
41543ca95b02SDimitry Andric           Ordering == AtomicOrdering::Acquire ||
41553ca95b02SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
41568f0fd8f6SDimitry Andric         return error("Invalid record");
41578f0fd8f6SDimitry Andric       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
41583ca95b02SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
41598f0fd8f6SDimitry Andric         return error("Invalid record");
41606122f3e6SDimitry Andric 
4161ff0cc061SDimitry Andric       unsigned Align;
4162d88c1a5aSDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4163d88c1a5aSDimitry Andric         return Err;
4164ff0cc061SDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
41656122f3e6SDimitry Andric       InstructionList.push_back(I);
41666122f3e6SDimitry Andric       break;
41676122f3e6SDimitry Andric     }
4168ff0cc061SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
41696122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG: {
417091bc56edSDimitry Andric       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
417191bc56edSDimitry Andric       //          failureordering?, isweak?]
41726122f3e6SDimitry Andric       unsigned OpNum = 0;
41736122f3e6SDimitry Andric       Value *Ptr, *Cmp, *New;
41746122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4175ff0cc061SDimitry Andric           (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4176ff0cc061SDimitry Andric                ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4177ff0cc061SDimitry Andric                : popValue(Record, OpNum, NextValueNo,
4178ff0cc061SDimitry Andric                           cast<PointerType>(Ptr->getType())->getElementType(),
4179ff0cc061SDimitry Andric                           Cmp)) ||
4180ff0cc061SDimitry Andric           popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4181ff0cc061SDimitry Andric           Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
41828f0fd8f6SDimitry Andric         return error("Invalid record");
41838f0fd8f6SDimitry Andric       AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
41843ca95b02SDimitry Andric       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
41853ca95b02SDimitry Andric           SuccessOrdering == AtomicOrdering::Unordered)
41868f0fd8f6SDimitry Andric         return error("Invalid record");
41878f0fd8f6SDimitry Andric       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
418891bc56edSDimitry Andric 
4189d88c1a5aSDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4190d88c1a5aSDimitry Andric         return Err;
419191bc56edSDimitry Andric       AtomicOrdering FailureOrdering;
419291bc56edSDimitry Andric       if (Record.size() < 7)
419391bc56edSDimitry Andric         FailureOrdering =
419491bc56edSDimitry Andric             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
419591bc56edSDimitry Andric       else
41968f0fd8f6SDimitry Andric         FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
419791bc56edSDimitry Andric 
419891bc56edSDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
419991bc56edSDimitry Andric                                 SynchScope);
42006122f3e6SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
420191bc56edSDimitry Andric 
420291bc56edSDimitry Andric       if (Record.size() < 8) {
420391bc56edSDimitry Andric         // Before weak cmpxchgs existed, the instruction simply returned the
420491bc56edSDimitry Andric         // value loaded from memory, so bitcode files from that era will be
420591bc56edSDimitry Andric         // expecting the first component of a modern cmpxchg.
420691bc56edSDimitry Andric         CurBB->getInstList().push_back(I);
420791bc56edSDimitry Andric         I = ExtractValueInst::Create(I, 0);
420891bc56edSDimitry Andric       } else {
420991bc56edSDimitry Andric         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
421091bc56edSDimitry Andric       }
421191bc56edSDimitry Andric 
42126122f3e6SDimitry Andric       InstructionList.push_back(I);
42136122f3e6SDimitry Andric       break;
42146122f3e6SDimitry Andric     }
42156122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW: {
42166122f3e6SDimitry Andric       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
42176122f3e6SDimitry Andric       unsigned OpNum = 0;
42186122f3e6SDimitry Andric       Value *Ptr, *Val;
42196122f3e6SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
42203ca95b02SDimitry Andric           !isa<PointerType>(Ptr->getType()) ||
42213861d79fSDimitry Andric           popValue(Record, OpNum, NextValueNo,
42226122f3e6SDimitry Andric                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
42236122f3e6SDimitry Andric           OpNum+4 != Record.size())
42248f0fd8f6SDimitry Andric         return error("Invalid record");
42258f0fd8f6SDimitry Andric       AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
42266122f3e6SDimitry Andric       if (Operation < AtomicRMWInst::FIRST_BINOP ||
42276122f3e6SDimitry Andric           Operation > AtomicRMWInst::LAST_BINOP)
42288f0fd8f6SDimitry Andric         return error("Invalid record");
42298f0fd8f6SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
42303ca95b02SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
42313ca95b02SDimitry Andric           Ordering == AtomicOrdering::Unordered)
42328f0fd8f6SDimitry Andric         return error("Invalid record");
42338f0fd8f6SDimitry Andric       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
42346122f3e6SDimitry Andric       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
42356122f3e6SDimitry Andric       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
42366122f3e6SDimitry Andric       InstructionList.push_back(I);
42376122f3e6SDimitry Andric       break;
42386122f3e6SDimitry Andric     }
42396122f3e6SDimitry Andric     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
42406122f3e6SDimitry Andric       if (2 != Record.size())
42418f0fd8f6SDimitry Andric         return error("Invalid record");
42428f0fd8f6SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
42433ca95b02SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
42443ca95b02SDimitry Andric           Ordering == AtomicOrdering::Unordered ||
42453ca95b02SDimitry Andric           Ordering == AtomicOrdering::Monotonic)
42468f0fd8f6SDimitry Andric         return error("Invalid record");
42478f0fd8f6SDimitry Andric       SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
42486122f3e6SDimitry Andric       I = new FenceInst(Context, Ordering, SynchScope);
42496122f3e6SDimitry Andric       InstructionList.push_back(I);
42506122f3e6SDimitry Andric       break;
42516122f3e6SDimitry Andric     }
425217a519f9SDimitry Andric     case bitc::FUNC_CODE_INST_CALL: {
42537d523365SDimitry Andric       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4254f22ef01cSRoman Divacky       if (Record.size() < 3)
42558f0fd8f6SDimitry Andric         return error("Invalid record");
4256f22ef01cSRoman Divacky 
4257ff0cc061SDimitry Andric       unsigned OpNum = 0;
42587a7e6055SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
4259ff0cc061SDimitry Andric       unsigned CCInfo = Record[OpNum++];
4260f22ef01cSRoman Divacky 
42617d523365SDimitry Andric       FastMathFlags FMF;
42627d523365SDimitry Andric       if ((CCInfo >> bitc::CALL_FMF) & 1) {
42637d523365SDimitry Andric         FMF = getDecodedFastMathFlags(Record[OpNum++]);
42647d523365SDimitry Andric         if (!FMF.any())
42657d523365SDimitry Andric           return error("Fast math flags indicator set for call with no FMF");
42667d523365SDimitry Andric       }
42677d523365SDimitry Andric 
4268ff0cc061SDimitry Andric       FunctionType *FTy = nullptr;
42697d523365SDimitry Andric       if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4270ff0cc061SDimitry Andric           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
42718f0fd8f6SDimitry Andric         return error("Explicit call type is not a function type");
4272ff0cc061SDimitry Andric 
4273f22ef01cSRoman Divacky       Value *Callee;
4274f22ef01cSRoman Divacky       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
42758f0fd8f6SDimitry Andric         return error("Invalid record");
4276f22ef01cSRoman Divacky 
42776122f3e6SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4278ff0cc061SDimitry Andric       if (!OpTy)
42798f0fd8f6SDimitry Andric         return error("Callee is not a pointer type");
4280ff0cc061SDimitry Andric       if (!FTy) {
4281ff0cc061SDimitry Andric         FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4282ff0cc061SDimitry Andric         if (!FTy)
42838f0fd8f6SDimitry Andric           return error("Callee is not of pointer to function type");
4284ff0cc061SDimitry Andric       } else if (OpTy->getElementType() != FTy)
42858f0fd8f6SDimitry Andric         return error("Explicit call type does not match pointee type of "
4286ff0cc061SDimitry Andric                      "callee operand");
4287ff0cc061SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
42888f0fd8f6SDimitry Andric         return error("Insufficient operands to call");
4289f22ef01cSRoman Divacky 
4290f22ef01cSRoman Divacky       SmallVector<Value*, 16> Args;
4291f22ef01cSRoman Divacky       // Read the fixed params.
4292f22ef01cSRoman Divacky       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
429317a519f9SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
4294f22ef01cSRoman Divacky           Args.push_back(getBasicBlock(Record[OpNum]));
4295f22ef01cSRoman Divacky         else
42963861d79fSDimitry Andric           Args.push_back(getValue(Record, OpNum, NextValueNo,
42973861d79fSDimitry Andric                                   FTy->getParamType(i)));
429891bc56edSDimitry Andric         if (!Args.back())
42998f0fd8f6SDimitry Andric           return error("Invalid record");
4300f22ef01cSRoman Divacky       }
4301f22ef01cSRoman Divacky 
4302f22ef01cSRoman Divacky       // Read type/value pairs for varargs params.
4303f22ef01cSRoman Divacky       if (!FTy->isVarArg()) {
4304f22ef01cSRoman Divacky         if (OpNum != Record.size())
43058f0fd8f6SDimitry Andric           return error("Invalid record");
4306f22ef01cSRoman Divacky       } else {
4307f22ef01cSRoman Divacky         while (OpNum != Record.size()) {
4308f22ef01cSRoman Divacky           Value *Op;
4309f22ef01cSRoman Divacky           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
43108f0fd8f6SDimitry Andric             return error("Invalid record");
4311f22ef01cSRoman Divacky           Args.push_back(Op);
4312f22ef01cSRoman Divacky         }
4313f22ef01cSRoman Divacky       }
4314f22ef01cSRoman Divacky 
43157d523365SDimitry Andric       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
43167d523365SDimitry Andric       OperandBundles.clear();
4317f22ef01cSRoman Divacky       InstructionList.push_back(I);
4318f22ef01cSRoman Divacky       cast<CallInst>(I)->setCallingConv(
43197d523365SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
432091bc56edSDimitry Andric       CallInst::TailCallKind TCK = CallInst::TCK_None;
43217d523365SDimitry Andric       if (CCInfo & 1 << bitc::CALL_TAIL)
432291bc56edSDimitry Andric         TCK = CallInst::TCK_Tail;
43237d523365SDimitry Andric       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
432491bc56edSDimitry Andric         TCK = CallInst::TCK_MustTail;
43257d523365SDimitry Andric       if (CCInfo & (1 << bitc::CALL_NOTAIL))
43267d523365SDimitry Andric         TCK = CallInst::TCK_NoTail;
432791bc56edSDimitry Andric       cast<CallInst>(I)->setTailCallKind(TCK);
4328f22ef01cSRoman Divacky       cast<CallInst>(I)->setAttributes(PAL);
43297d523365SDimitry Andric       if (FMF.any()) {
43307d523365SDimitry Andric         if (!isa<FPMathOperator>(I))
43317d523365SDimitry Andric           return error("Fast-math-flags specified for call without "
43327d523365SDimitry Andric                        "floating-point scalar or vector return type");
43337d523365SDimitry Andric         I->setFastMathFlags(FMF);
43347d523365SDimitry Andric       }
4335f22ef01cSRoman Divacky       break;
4336f22ef01cSRoman Divacky     }
4337f22ef01cSRoman Divacky     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4338f22ef01cSRoman Divacky       if (Record.size() < 3)
43398f0fd8f6SDimitry Andric         return error("Invalid record");
43406122f3e6SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
43413861d79fSDimitry Andric       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
43426122f3e6SDimitry Andric       Type *ResTy = getTypeByID(Record[2]);
4343f22ef01cSRoman Divacky       if (!OpTy || !Op || !ResTy)
43448f0fd8f6SDimitry Andric         return error("Invalid record");
4345f22ef01cSRoman Divacky       I = new VAArgInst(Op, ResTy);
4346f22ef01cSRoman Divacky       InstructionList.push_back(I);
4347f22ef01cSRoman Divacky       break;
4348f22ef01cSRoman Divacky     }
43497d523365SDimitry Andric 
43507d523365SDimitry Andric     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
43517d523365SDimitry Andric       // A call or an invoke can be optionally prefixed with some variable
43527d523365SDimitry Andric       // number of operand bundle blocks.  These blocks are read into
43537d523365SDimitry Andric       // OperandBundles and consumed at the next call or invoke instruction.
43547d523365SDimitry Andric 
43557d523365SDimitry Andric       if (Record.size() < 1 || Record[0] >= BundleTags.size())
43567d523365SDimitry Andric         return error("Invalid record");
43577d523365SDimitry Andric 
43587d523365SDimitry Andric       std::vector<Value *> Inputs;
43597d523365SDimitry Andric 
43607d523365SDimitry Andric       unsigned OpNum = 1;
43617d523365SDimitry Andric       while (OpNum != Record.size()) {
43627d523365SDimitry Andric         Value *Op;
43637d523365SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
43647d523365SDimitry Andric           return error("Invalid record");
43657d523365SDimitry Andric         Inputs.push_back(Op);
43667d523365SDimitry Andric       }
43677d523365SDimitry Andric 
43687d523365SDimitry Andric       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
43697d523365SDimitry Andric       continue;
43707d523365SDimitry Andric     }
4371f22ef01cSRoman Divacky     }
4372f22ef01cSRoman Divacky 
4373f22ef01cSRoman Divacky     // Add instruction to end of current BB.  If there is no current BB, reject
4374f22ef01cSRoman Divacky     // this file.
437591bc56edSDimitry Andric     if (!CurBB) {
4376f22ef01cSRoman Divacky       delete I;
43778f0fd8f6SDimitry Andric       return error("Invalid instruction with no BB");
4378f22ef01cSRoman Divacky     }
43797d523365SDimitry Andric     if (!OperandBundles.empty()) {
43807d523365SDimitry Andric       delete I;
43817d523365SDimitry Andric       return error("Operand bundles found with no consumer");
43827d523365SDimitry Andric     }
4383f22ef01cSRoman Divacky     CurBB->getInstList().push_back(I);
4384f22ef01cSRoman Divacky 
4385f22ef01cSRoman Divacky     // If this was a terminator instruction, move to the next block.
4386f22ef01cSRoman Divacky     if (isa<TerminatorInst>(I)) {
4387f22ef01cSRoman Divacky       ++CurBBNo;
438891bc56edSDimitry Andric       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4389f22ef01cSRoman Divacky     }
4390f22ef01cSRoman Divacky 
4391f22ef01cSRoman Divacky     // Non-void values get registered in the value table for future use.
4392f22ef01cSRoman Divacky     if (I && !I->getType()->isVoidTy())
43938f0fd8f6SDimitry Andric       ValueList.assignValue(I, NextValueNo++);
4394f22ef01cSRoman Divacky   }
4395f22ef01cSRoman Divacky 
4396139f7f9bSDimitry Andric OutOfRecordLoop:
4397139f7f9bSDimitry Andric 
43987d523365SDimitry Andric   if (!OperandBundles.empty())
43997d523365SDimitry Andric     return error("Operand bundles found with no consumer");
44007d523365SDimitry Andric 
4401f22ef01cSRoman Divacky   // Check the function list for unresolved values.
4402f22ef01cSRoman Divacky   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
440391bc56edSDimitry Andric     if (!A->getParent()) {
4404f22ef01cSRoman Divacky       // We found at least one unresolved value.  Nuke them all to avoid leaks.
4405f22ef01cSRoman Divacky       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
440691bc56edSDimitry Andric         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4407f22ef01cSRoman Divacky           A->replaceAllUsesWith(UndefValue::get(A->getType()));
4408f22ef01cSRoman Divacky           delete A;
4409f22ef01cSRoman Divacky         }
4410f22ef01cSRoman Divacky       }
44118f0fd8f6SDimitry Andric       return error("Never resolved value found in function");
4412f22ef01cSRoman Divacky     }
4413f22ef01cSRoman Divacky   }
4414f22ef01cSRoman Divacky 
44153ca95b02SDimitry Andric   // Unexpected unresolved metadata about to be dropped.
4416d88c1a5aSDimitry Andric   if (MDLoader->hasFwdRefs())
44173ca95b02SDimitry Andric     return error("Invalid function metadata: outgoing forward refs");
4418e580952dSDimitry Andric 
4419f22ef01cSRoman Divacky   // Trim the value list down to the size it was before we parsed this function.
4420f22ef01cSRoman Divacky   ValueList.shrinkTo(ModuleValueListSize);
4421d88c1a5aSDimitry Andric   MDLoader->shrinkTo(ModuleMDLoaderSize);
4422f22ef01cSRoman Divacky   std::vector<BasicBlock*>().swap(FunctionBBs);
4423d88c1a5aSDimitry Andric   return Error::success();
4424f22ef01cSRoman Divacky }
4425f22ef01cSRoman Divacky 
4426f785676fSDimitry Andric /// Find the function body in the bitcode stream
4427d88c1a5aSDimitry Andric Error BitcodeReader::findFunctionInStream(
442891bc56edSDimitry Andric     Function *F,
4429dff0c46cSDimitry Andric     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4430dff0c46cSDimitry Andric   while (DeferredFunctionInfoIterator->second == 0) {
44317d523365SDimitry Andric     // This is the fallback handling for the old format bitcode that
44327d523365SDimitry Andric     // didn't contain the function index in the VST, or when we have
44337d523365SDimitry Andric     // an anonymous function which would not have a VST entry.
44347d523365SDimitry Andric     // Assert that we have one of those two cases.
44357d523365SDimitry Andric     assert(VSTOffset == 0 || !F->hasName());
44367d523365SDimitry Andric     // Parse the next body in the stream and set its position in the
44377d523365SDimitry Andric     // DeferredFunctionInfo map.
4438d88c1a5aSDimitry Andric     if (Error Err = rememberAndSkipFunctionBodies())
4439d88c1a5aSDimitry Andric       return Err;
4440dff0c46cSDimitry Andric   }
4441d88c1a5aSDimitry Andric   return Error::success();
4442dff0c46cSDimitry Andric }
4443dff0c46cSDimitry Andric 
4444f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
4445f22ef01cSRoman Divacky // GVMaterializer implementation
4446f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
4447f22ef01cSRoman Divacky 
4448d88c1a5aSDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) {
4449f22ef01cSRoman Divacky   Function *F = dyn_cast<Function>(GV);
4450f22ef01cSRoman Divacky   // If it's not a function or is already material, ignore the request.
4451f785676fSDimitry Andric   if (!F || !F->isMaterializable())
4452d88c1a5aSDimitry Andric     return Error::success();
4453f22ef01cSRoman Divacky 
4454f22ef01cSRoman Divacky   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4455f22ef01cSRoman Divacky   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4456dff0c46cSDimitry Andric   // If its position is recorded as 0, its body is somewhere in the stream
4457dff0c46cSDimitry Andric   // but we haven't seen it yet.
44583dac3a9bSDimitry Andric   if (DFII->second == 0)
4459d88c1a5aSDimitry Andric     if (Error Err = findFunctionInStream(F, DFII))
4460d88c1a5aSDimitry Andric       return Err;
4461f22ef01cSRoman Divacky 
44623ca95b02SDimitry Andric   // Materialize metadata before parsing any function bodies.
4463d88c1a5aSDimitry Andric   if (Error Err = materializeMetadata())
4464d88c1a5aSDimitry Andric     return Err;
44653ca95b02SDimitry Andric 
4466f22ef01cSRoman Divacky   // Move the bit stream to the saved position of the deferred function body.
4467f22ef01cSRoman Divacky   Stream.JumpToBit(DFII->second);
4468f22ef01cSRoman Divacky 
4469d88c1a5aSDimitry Andric   if (Error Err = parseFunctionBody(F))
4470d88c1a5aSDimitry Andric     return Err;
447139d628a0SDimitry Andric   F->setIsMaterializable(false);
4472f22ef01cSRoman Divacky 
4473ff0cc061SDimitry Andric   if (StripDebugInfo)
4474ff0cc061SDimitry Andric     stripDebugInfo(*F);
4475ff0cc061SDimitry Andric 
4476f22ef01cSRoman Divacky   // Upgrade any old intrinsic calls in the function.
44773dac3a9bSDimitry Andric   for (auto &I : UpgradedIntrinsics) {
44787d523365SDimitry Andric     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
44797d523365SDimitry Andric          UI != UE;) {
44803dac3a9bSDimitry Andric       User *U = *UI;
44813dac3a9bSDimitry Andric       ++UI;
44823dac3a9bSDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
44833dac3a9bSDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
4484f22ef01cSRoman Divacky     }
4485f22ef01cSRoman Divacky   }
4486f22ef01cSRoman Divacky 
44873ca95b02SDimitry Andric   // Update calls to the remangled intrinsics
44883ca95b02SDimitry Andric   for (auto &I : RemangledIntrinsics)
44893ca95b02SDimitry Andric     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
44903ca95b02SDimitry Andric          UI != UE;)
44913ca95b02SDimitry Andric       // Don't expect any other users than call sites
44923ca95b02SDimitry Andric       CallSite(*UI++).setCalledFunction(I.second);
44933ca95b02SDimitry Andric 
44947d523365SDimitry Andric   // Finish fn->subprogram upgrade for materialized functions.
4495d88c1a5aSDimitry Andric   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
44967d523365SDimitry Andric     F->setSubprogram(SP);
44977d523365SDimitry Andric 
4498d88c1a5aSDimitry Andric   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4499d88c1a5aSDimitry Andric   if (!MDLoader->isStrippingTBAA()) {
4500d88c1a5aSDimitry Andric     for (auto &I : instructions(F)) {
4501d88c1a5aSDimitry Andric       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4502d88c1a5aSDimitry Andric       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4503d88c1a5aSDimitry Andric         continue;
4504d88c1a5aSDimitry Andric       MDLoader->setStripTBAA(true);
4505d88c1a5aSDimitry Andric       stripTBAA(F->getParent());
4506d88c1a5aSDimitry Andric     }
4507d88c1a5aSDimitry Andric   }
4508d88c1a5aSDimitry Andric 
450939d628a0SDimitry Andric   // Bring in any functions that this function forward-referenced via
451039d628a0SDimitry Andric   // blockaddresses.
451139d628a0SDimitry Andric   return materializeForwardReferencedFunctions();
4512f22ef01cSRoman Divacky }
4513f22ef01cSRoman Divacky 
4514d88c1a5aSDimitry Andric Error BitcodeReader::materializeModule() {
4515d88c1a5aSDimitry Andric   if (Error Err = materializeMetadata())
4516d88c1a5aSDimitry Andric     return Err;
4517ff0cc061SDimitry Andric 
451839d628a0SDimitry Andric   // Promise to materialize all forward references.
451939d628a0SDimitry Andric   WillMaterializeAllForwardRefs = true;
452039d628a0SDimitry Andric 
4521f22ef01cSRoman Divacky   // Iterate over the module, deserializing any functions that are still on
4522f22ef01cSRoman Divacky   // disk.
45237d523365SDimitry Andric   for (Function &F : *TheModule) {
4524d88c1a5aSDimitry Andric     if (Error Err = materialize(&F))
4525d88c1a5aSDimitry Andric       return Err;
4526f785676fSDimitry Andric   }
45277d523365SDimitry Andric   // At this point, if there are any function bodies, parse the rest of
45287d523365SDimitry Andric   // the bits in the module past the last function block we have recorded
45297d523365SDimitry Andric   // through either lazy scanning or the VST.
45307d523365SDimitry Andric   if (LastFunctionBlockBit || NextUnreadBit)
4531d88c1a5aSDimitry Andric     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4532d88c1a5aSDimitry Andric                                     ? LastFunctionBlockBit
4533d88c1a5aSDimitry Andric                                     : NextUnreadBit))
4534d88c1a5aSDimitry Andric       return Err;
4535dff0c46cSDimitry Andric 
453639d628a0SDimitry Andric   // Check that all block address forward references got resolved (as we
453739d628a0SDimitry Andric   // promised above).
453839d628a0SDimitry Andric   if (!BasicBlockFwdRefs.empty())
45398f0fd8f6SDimitry Andric     return error("Never resolved function from blockaddress");
454039d628a0SDimitry Andric 
4541f22ef01cSRoman Divacky   // Upgrade any intrinsic calls that slipped through (should not happen!) and
4542f22ef01cSRoman Divacky   // delete the old functions to clean up. We can't do this unless the entire
4543f22ef01cSRoman Divacky   // module is materialized because there could always be another function body
4544f22ef01cSRoman Divacky   // with calls to the old function.
45453dac3a9bSDimitry Andric   for (auto &I : UpgradedIntrinsics) {
45463dac3a9bSDimitry Andric     for (auto *U : I.first->users()) {
45473dac3a9bSDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
45483dac3a9bSDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
4549f22ef01cSRoman Divacky     }
45503dac3a9bSDimitry Andric     if (!I.first->use_empty())
45513dac3a9bSDimitry Andric       I.first->replaceAllUsesWith(I.second);
45523dac3a9bSDimitry Andric     I.first->eraseFromParent();
4553f22ef01cSRoman Divacky   }
45543dac3a9bSDimitry Andric   UpgradedIntrinsics.clear();
45553ca95b02SDimitry Andric   // Do the same for remangled intrinsics
45563ca95b02SDimitry Andric   for (auto &I : RemangledIntrinsics) {
45573ca95b02SDimitry Andric     I.first->replaceAllUsesWith(I.second);
45583ca95b02SDimitry Andric     I.first->eraseFromParent();
45593ca95b02SDimitry Andric   }
45603ca95b02SDimitry Andric   RemangledIntrinsics.clear();
4561f785676fSDimitry Andric 
45627d523365SDimitry Andric   UpgradeDebugInfo(*TheModule);
45633ca95b02SDimitry Andric 
45643ca95b02SDimitry Andric   UpgradeModuleFlags(*TheModule);
4565d88c1a5aSDimitry Andric   return Error::success();
4566dff0c46cSDimitry Andric }
45676122f3e6SDimitry Andric 
456839d628a0SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
456939d628a0SDimitry Andric   return IdentifiedStructTypes;
457039d628a0SDimitry Andric }
457139d628a0SDimitry Andric 
45723ca95b02SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4573d88c1a5aSDimitry Andric     BitstreamCursor Cursor, ModuleSummaryIndex &TheIndex)
4574d88c1a5aSDimitry Andric     : BitcodeReaderBase(std::move(Cursor)), TheIndex(TheIndex) {}
45753ca95b02SDimitry Andric 
45763ca95b02SDimitry Andric std::pair<GlobalValue::GUID, GlobalValue::GUID>
45773ca95b02SDimitry Andric ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
45783ca95b02SDimitry Andric   auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
45793ca95b02SDimitry Andric   assert(VGI != ValueIdToCallGraphGUIDMap.end());
45803ca95b02SDimitry Andric   return VGI->second;
45817d523365SDimitry Andric }
45827d523365SDimitry Andric 
45833ca95b02SDimitry Andric // Specialized value symbol table parser used when reading module index
45843ca95b02SDimitry Andric // blocks where we don't actually create global values. The parsed information
45853ca95b02SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries.
4586d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
45873ca95b02SDimitry Andric     uint64_t Offset,
45883ca95b02SDimitry Andric     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
45893ca95b02SDimitry Andric   assert(Offset > 0 && "Expected non-zero VST offset");
45903ca95b02SDimitry Andric   uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
45917d523365SDimitry Andric 
45927d523365SDimitry Andric   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
45937d523365SDimitry Andric     return error("Invalid record");
45947d523365SDimitry Andric 
45957d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
45967d523365SDimitry Andric 
45977d523365SDimitry Andric   // Read all the records for this value table.
45987d523365SDimitry Andric   SmallString<128> ValueName;
4599d88c1a5aSDimitry Andric 
4600d88c1a5aSDimitry Andric   while (true) {
46017d523365SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
46027d523365SDimitry Andric 
46037d523365SDimitry Andric     switch (Entry.Kind) {
46047d523365SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
46057d523365SDimitry Andric     case BitstreamEntry::Error:
46067d523365SDimitry Andric       return error("Malformed block");
46077d523365SDimitry Andric     case BitstreamEntry::EndBlock:
46083ca95b02SDimitry Andric       // Done parsing VST, jump back to wherever we came from.
46093ca95b02SDimitry Andric       Stream.JumpToBit(CurrentBit);
4610d88c1a5aSDimitry Andric       return Error::success();
46117d523365SDimitry Andric     case BitstreamEntry::Record:
46127d523365SDimitry Andric       // The interesting case.
46137d523365SDimitry Andric       break;
46147d523365SDimitry Andric     }
46157d523365SDimitry Andric 
46167d523365SDimitry Andric     // Read a record.
46177d523365SDimitry Andric     Record.clear();
46187d523365SDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
46197d523365SDimitry Andric     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
46207d523365SDimitry Andric       break;
46213ca95b02SDimitry Andric     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
46223ca95b02SDimitry Andric       if (convertToString(Record, 1, ValueName))
46233ca95b02SDimitry Andric         return error("Invalid record");
46243ca95b02SDimitry Andric       unsigned ValueID = Record[0];
46253ca95b02SDimitry Andric       assert(!SourceFileName.empty());
46263ca95b02SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
46273ca95b02SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
46283ca95b02SDimitry Andric              "No linkage found for VST entry?");
46293ca95b02SDimitry Andric       auto Linkage = VLI->second;
46303ca95b02SDimitry Andric       std::string GlobalId =
46313ca95b02SDimitry Andric           GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
46323ca95b02SDimitry Andric       auto ValueGUID = GlobalValue::getGUID(GlobalId);
46333ca95b02SDimitry Andric       auto OriginalNameID = ValueGUID;
46343ca95b02SDimitry Andric       if (GlobalValue::isLocalLinkage(Linkage))
46353ca95b02SDimitry Andric         OriginalNameID = GlobalValue::getGUID(ValueName);
46363ca95b02SDimitry Andric       if (PrintSummaryGUIDs)
46373ca95b02SDimitry Andric         dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
46383ca95b02SDimitry Andric                << ValueName << "\n";
46393ca95b02SDimitry Andric       ValueIdToCallGraphGUIDMap[ValueID] =
46403ca95b02SDimitry Andric           std::make_pair(ValueGUID, OriginalNameID);
46413ca95b02SDimitry Andric       ValueName.clear();
46423ca95b02SDimitry Andric       break;
46433ca95b02SDimitry Andric     }
46447d523365SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
46453ca95b02SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
46467d523365SDimitry Andric       if (convertToString(Record, 2, ValueName))
46477d523365SDimitry Andric         return error("Invalid record");
46487d523365SDimitry Andric       unsigned ValueID = Record[0];
46493ca95b02SDimitry Andric       assert(!SourceFileName.empty());
46503ca95b02SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
46513ca95b02SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
46523ca95b02SDimitry Andric              "No linkage found for VST entry?");
46533ca95b02SDimitry Andric       auto Linkage = VLI->second;
46543ca95b02SDimitry Andric       std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
46553ca95b02SDimitry Andric           ValueName, VLI->second, SourceFileName);
46563ca95b02SDimitry Andric       auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
46573ca95b02SDimitry Andric       auto OriginalNameID = FunctionGUID;
46583ca95b02SDimitry Andric       if (GlobalValue::isLocalLinkage(Linkage))
46593ca95b02SDimitry Andric         OriginalNameID = GlobalValue::getGUID(ValueName);
46603ca95b02SDimitry Andric       if (PrintSummaryGUIDs)
46613ca95b02SDimitry Andric         dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
46623ca95b02SDimitry Andric                << ValueName << "\n";
46633ca95b02SDimitry Andric       ValueIdToCallGraphGUIDMap[ValueID] =
46643ca95b02SDimitry Andric           std::make_pair(FunctionGUID, OriginalNameID);
46657d523365SDimitry Andric 
46667d523365SDimitry Andric       ValueName.clear();
46677d523365SDimitry Andric       break;
46687d523365SDimitry Andric     }
46693ca95b02SDimitry Andric     case bitc::VST_CODE_COMBINED_ENTRY: {
46703ca95b02SDimitry Andric       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
46713ca95b02SDimitry Andric       unsigned ValueID = Record[0];
46723ca95b02SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
46733ca95b02SDimitry Andric       // The "original name", which is the second value of the pair will be
46743ca95b02SDimitry Andric       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
46753ca95b02SDimitry Andric       ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
46767d523365SDimitry Andric       break;
46777d523365SDimitry Andric     }
46787d523365SDimitry Andric     }
46797d523365SDimitry Andric   }
46807d523365SDimitry Andric }
46817d523365SDimitry Andric 
46823ca95b02SDimitry Andric // Parse just the blocks needed for building the index out of the module.
46833ca95b02SDimitry Andric // At the end of this routine the module Index is populated with a map
46843ca95b02SDimitry Andric // from global value id to GlobalValueSummary objects.
4685d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule(StringRef ModulePath) {
46867d523365SDimitry Andric   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
46877d523365SDimitry Andric     return error("Invalid record");
46887d523365SDimitry Andric 
46893ca95b02SDimitry Andric   SmallVector<uint64_t, 64> Record;
46903ca95b02SDimitry Andric   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
46913ca95b02SDimitry Andric   unsigned ValueId = 0;
46923ca95b02SDimitry Andric 
46933ca95b02SDimitry Andric   // Read the index for this module.
4694d88c1a5aSDimitry Andric   while (true) {
46957d523365SDimitry Andric     BitstreamEntry Entry = Stream.advance();
46967d523365SDimitry Andric 
46977d523365SDimitry Andric     switch (Entry.Kind) {
46987d523365SDimitry Andric     case BitstreamEntry::Error:
46997d523365SDimitry Andric       return error("Malformed block");
47007d523365SDimitry Andric     case BitstreamEntry::EndBlock:
4701d88c1a5aSDimitry Andric       return Error::success();
47027d523365SDimitry Andric 
47037d523365SDimitry Andric     case BitstreamEntry::SubBlock:
47047d523365SDimitry Andric       switch (Entry.ID) {
47057d523365SDimitry Andric       default: // Skip unknown content.
47067d523365SDimitry Andric         if (Stream.SkipBlock())
47077d523365SDimitry Andric           return error("Invalid record");
47087d523365SDimitry Andric         break;
47097d523365SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
47107d523365SDimitry Andric         // Need to parse these to get abbrev ids (e.g. for VST)
4711d88c1a5aSDimitry Andric         if (readBlockInfo())
47127d523365SDimitry Andric           return error("Malformed block");
47137d523365SDimitry Andric         break;
47147d523365SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
47153ca95b02SDimitry Andric         // Should have been parsed earlier via VSTOffset, unless there
47163ca95b02SDimitry Andric         // is no summary section.
47173ca95b02SDimitry Andric         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
47183ca95b02SDimitry Andric                 !SeenGlobalValSummary) &&
47193ca95b02SDimitry Andric                "Expected early VST parse via VSTOffset record");
47207d523365SDimitry Andric         if (Stream.SkipBlock())
47217d523365SDimitry Andric           return error("Invalid record");
47223ca95b02SDimitry Andric         break;
47233ca95b02SDimitry Andric       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
47243ca95b02SDimitry Andric         assert(!SeenValueSymbolTable &&
47253ca95b02SDimitry Andric                "Already read VST when parsing summary block?");
4726d88c1a5aSDimitry Andric         // We might not have a VST if there were no values in the
4727d88c1a5aSDimitry Andric         // summary. An empty summary block generated when we are
4728d88c1a5aSDimitry Andric         // performing ThinLTO compiles so we don't later invoke
4729d88c1a5aSDimitry Andric         // the regular LTO process on them.
4730d88c1a5aSDimitry Andric         if (VSTOffset > 0) {
4731d88c1a5aSDimitry Andric           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4732d88c1a5aSDimitry Andric             return Err;
47333ca95b02SDimitry Andric           SeenValueSymbolTable = true;
4734d88c1a5aSDimitry Andric         }
47353ca95b02SDimitry Andric         SeenGlobalValSummary = true;
4736d88c1a5aSDimitry Andric         if (Error Err = parseEntireSummary(ModulePath))
4737d88c1a5aSDimitry Andric           return Err;
47387d523365SDimitry Andric         break;
47397d523365SDimitry Andric       case bitc::MODULE_STRTAB_BLOCK_ID:
4740d88c1a5aSDimitry Andric         if (Error Err = parseModuleStringTable())
4741d88c1a5aSDimitry Andric           return Err;
47427d523365SDimitry Andric         break;
47437d523365SDimitry Andric       }
47447d523365SDimitry Andric       continue;
47457d523365SDimitry Andric 
47463ca95b02SDimitry Andric     case BitstreamEntry::Record: {
47473ca95b02SDimitry Andric         Record.clear();
47483ca95b02SDimitry Andric         auto BitCode = Stream.readRecord(Entry.ID, Record);
47493ca95b02SDimitry Andric         switch (BitCode) {
47503ca95b02SDimitry Andric         default:
47513ca95b02SDimitry Andric           break; // Default behavior, ignore unknown content.
47523ca95b02SDimitry Andric         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
47533ca95b02SDimitry Andric         case bitc::MODULE_CODE_SOURCE_FILENAME: {
47543ca95b02SDimitry Andric           SmallString<128> ValueName;
47553ca95b02SDimitry Andric           if (convertToString(Record, 0, ValueName))
47563ca95b02SDimitry Andric             return error("Invalid record");
47573ca95b02SDimitry Andric           SourceFileName = ValueName.c_str();
47583ca95b02SDimitry Andric           break;
47593ca95b02SDimitry Andric         }
47603ca95b02SDimitry Andric         /// MODULE_CODE_HASH: [5*i32]
47613ca95b02SDimitry Andric         case bitc::MODULE_CODE_HASH: {
47623ca95b02SDimitry Andric           if (Record.size() != 5)
47633ca95b02SDimitry Andric             return error("Invalid hash length " + Twine(Record.size()).str());
4764d88c1a5aSDimitry Andric           if (TheIndex.modulePaths().empty())
4765d88c1a5aSDimitry Andric             // We always seed the index with the module.
4766d88c1a5aSDimitry Andric             TheIndex.addModulePath(ModulePath, 0);
4767d88c1a5aSDimitry Andric           if (TheIndex.modulePaths().size() != 1)
47683ca95b02SDimitry Andric             return error("Don't expect multiple modules defined?");
4769d88c1a5aSDimitry Andric           auto &Hash = TheIndex.modulePaths().begin()->second.second;
47703ca95b02SDimitry Andric           int Pos = 0;
47713ca95b02SDimitry Andric           for (auto &Val : Record) {
47723ca95b02SDimitry Andric             assert(!(Val >> 32) && "Unexpected high bits set");
47733ca95b02SDimitry Andric             Hash[Pos++] = Val;
47743ca95b02SDimitry Andric           }
47753ca95b02SDimitry Andric           break;
47763ca95b02SDimitry Andric         }
47773ca95b02SDimitry Andric         /// MODULE_CODE_VSTOFFSET: [offset]
47783ca95b02SDimitry Andric         case bitc::MODULE_CODE_VSTOFFSET:
47793ca95b02SDimitry Andric           if (Record.size() < 1)
47803ca95b02SDimitry Andric             return error("Invalid record");
4781d88c1a5aSDimitry Andric           // Note that we subtract 1 here because the offset is relative to one
4782d88c1a5aSDimitry Andric           // word before the start of the identification or module block, which
4783d88c1a5aSDimitry Andric           // was historically always the start of the regular bitcode header.
4784d88c1a5aSDimitry Andric           VSTOffset = Record[0] - 1;
47853ca95b02SDimitry Andric           break;
47867a7e6055SDimitry Andric         // GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
47877a7e6055SDimitry Andric         // FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
47887a7e6055SDimitry Andric         // ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
47897a7e6055SDimitry Andric         case bitc::MODULE_CODE_GLOBALVAR:
47907a7e6055SDimitry Andric         case bitc::MODULE_CODE_FUNCTION:
47913ca95b02SDimitry Andric         case bitc::MODULE_CODE_ALIAS: {
47927a7e6055SDimitry Andric           if (Record.size() <= 3)
47933ca95b02SDimitry Andric             return error("Invalid record");
47943ca95b02SDimitry Andric           uint64_t RawLinkage = Record[3];
47953ca95b02SDimitry Andric           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
47963ca95b02SDimitry Andric           ValueIdToLinkageMap[ValueId++] = Linkage;
47973ca95b02SDimitry Andric           break;
47983ca95b02SDimitry Andric         }
47993ca95b02SDimitry Andric         }
48003ca95b02SDimitry Andric       }
48017d523365SDimitry Andric       continue;
48027d523365SDimitry Andric     }
48037d523365SDimitry Andric   }
48047d523365SDimitry Andric }
48057d523365SDimitry Andric 
4806d88c1a5aSDimitry Andric std::vector<ValueInfo>
4807d88c1a5aSDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
4808d88c1a5aSDimitry Andric   std::vector<ValueInfo> Ret;
4809d88c1a5aSDimitry Andric   Ret.reserve(Record.size());
4810d88c1a5aSDimitry Andric   for (uint64_t RefValueId : Record)
4811d88c1a5aSDimitry Andric     Ret.push_back(getGUIDFromValueId(RefValueId).first);
4812d88c1a5aSDimitry Andric   return Ret;
4813d88c1a5aSDimitry Andric }
4814d88c1a5aSDimitry Andric 
4815d88c1a5aSDimitry Andric std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
4816d88c1a5aSDimitry Andric     ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) {
4817d88c1a5aSDimitry Andric   std::vector<FunctionSummary::EdgeTy> Ret;
4818d88c1a5aSDimitry Andric   Ret.reserve(Record.size());
4819d88c1a5aSDimitry Andric   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
4820d88c1a5aSDimitry Andric     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
4821d88c1a5aSDimitry Andric     GlobalValue::GUID CalleeGUID = getGUIDFromValueId(Record[I]).first;
4822d88c1a5aSDimitry Andric     if (IsOldProfileFormat) {
4823d88c1a5aSDimitry Andric       I += 1; // Skip old callsitecount field
4824d88c1a5aSDimitry Andric       if (HasProfile)
4825d88c1a5aSDimitry Andric         I += 1; // Skip old profilecount field
4826d88c1a5aSDimitry Andric     } else if (HasProfile)
4827d88c1a5aSDimitry Andric       Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
4828d88c1a5aSDimitry Andric     Ret.push_back(FunctionSummary::EdgeTy{CalleeGUID, CalleeInfo{Hotness}});
4829d88c1a5aSDimitry Andric   }
4830d88c1a5aSDimitry Andric   return Ret;
4831d88c1a5aSDimitry Andric }
4832d88c1a5aSDimitry Andric 
48333ca95b02SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary
48343ca95b02SDimitry Andric // objects in the index.
4835d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
4836d88c1a5aSDimitry Andric     StringRef ModulePath) {
48373ca95b02SDimitry Andric   if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
48387d523365SDimitry Andric     return error("Invalid record");
48397d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
48407d523365SDimitry Andric 
48413ca95b02SDimitry Andric   // Parse version
48423ca95b02SDimitry Andric   {
48433ca95b02SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
48443ca95b02SDimitry Andric     if (Entry.Kind != BitstreamEntry::Record)
48453ca95b02SDimitry Andric       return error("Invalid Summary Block: record for version expected");
48463ca95b02SDimitry Andric     if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
48473ca95b02SDimitry Andric       return error("Invalid Summary Block: version expected");
48483ca95b02SDimitry Andric   }
48493ca95b02SDimitry Andric   const uint64_t Version = Record[0];
4850d88c1a5aSDimitry Andric   const bool IsOldProfileFormat = Version == 1;
485195ec533aSDimitry Andric   if (Version < 1 || Version > 3)
4852d88c1a5aSDimitry Andric     return error("Invalid summary version " + Twine(Version) +
485395ec533aSDimitry Andric                  ", 1, 2 or 3 expected");
48543ca95b02SDimitry Andric   Record.clear();
48553ca95b02SDimitry Andric 
48563ca95b02SDimitry Andric   // Keep around the last seen summary to be used when we see an optional
48573ca95b02SDimitry Andric   // "OriginalName" attachement.
48583ca95b02SDimitry Andric   GlobalValueSummary *LastSeenSummary = nullptr;
48597a7e6055SDimitry Andric   GlobalValue::GUID LastSeenGUID = 0;
48603ca95b02SDimitry Andric   bool Combined = false;
48617a7e6055SDimitry Andric 
48627a7e6055SDimitry Andric   // We can expect to see any number of type ID information records before
48637a7e6055SDimitry Andric   // each function summary records; these variables store the information
48647a7e6055SDimitry Andric   // collected so far so that it can be used to create the summary object.
4865d88c1a5aSDimitry Andric   std::vector<GlobalValue::GUID> PendingTypeTests;
48667a7e6055SDimitry Andric   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
48677a7e6055SDimitry Andric       PendingTypeCheckedLoadVCalls;
48687a7e6055SDimitry Andric   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
48697a7e6055SDimitry Andric       PendingTypeCheckedLoadConstVCalls;
4870d88c1a5aSDimitry Andric 
4871d88c1a5aSDimitry Andric   while (true) {
48727d523365SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
48737d523365SDimitry Andric 
48747d523365SDimitry Andric     switch (Entry.Kind) {
48757d523365SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
48767d523365SDimitry Andric     case BitstreamEntry::Error:
48777d523365SDimitry Andric       return error("Malformed block");
48787d523365SDimitry Andric     case BitstreamEntry::EndBlock:
48793ca95b02SDimitry Andric       // For a per-module index, remove any entries that still have empty
48803ca95b02SDimitry Andric       // summaries. The VST parsing creates entries eagerly for all symbols,
48813ca95b02SDimitry Andric       // but not all have associated summaries (e.g. it doesn't know how to
48823ca95b02SDimitry Andric       // distinguish between VST_CODE_ENTRY for function declarations vs global
48833ca95b02SDimitry Andric       // variables with initializers that end up with a summary). Remove those
48843ca95b02SDimitry Andric       // entries now so that we don't need to rely on the combined index merger
48853ca95b02SDimitry Andric       // to clean them up (especially since that may not run for the first
48863ca95b02SDimitry Andric       // module's index if we merge into that).
48873ca95b02SDimitry Andric       if (!Combined)
4888d88c1a5aSDimitry Andric         TheIndex.removeEmptySummaryEntries();
4889d88c1a5aSDimitry Andric       return Error::success();
48907d523365SDimitry Andric     case BitstreamEntry::Record:
48917d523365SDimitry Andric       // The interesting case.
48927d523365SDimitry Andric       break;
48937d523365SDimitry Andric     }
48947d523365SDimitry Andric 
48957d523365SDimitry Andric     // Read a record. The record format depends on whether this
48967d523365SDimitry Andric     // is a per-module index or a combined index file. In the per-module
48977d523365SDimitry Andric     // case the records contain the associated value's ID for correlation
48987d523365SDimitry Andric     // with VST entries. In the combined index the correlation is done
48997d523365SDimitry Andric     // via the bitcode offset of the summary records (which were saved
49007d523365SDimitry Andric     // in the combined index VST entries). The records also contain
49017d523365SDimitry Andric     // information used for ThinLTO renaming and importing.
49027d523365SDimitry Andric     Record.clear();
49033ca95b02SDimitry Andric     auto BitCode = Stream.readRecord(Entry.ID, Record);
49043ca95b02SDimitry Andric     switch (BitCode) {
49057d523365SDimitry Andric     default: // Default behavior: ignore.
49067d523365SDimitry Andric       break;
49073ca95b02SDimitry Andric     // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
4908d88c1a5aSDimitry Andric     //                n x (valueid)]
49093ca95b02SDimitry Andric     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
49103ca95b02SDimitry Andric     //                        numrefs x valueid,
4911d88c1a5aSDimitry Andric     //                        n x (valueid, hotness)]
49123ca95b02SDimitry Andric     case bitc::FS_PERMODULE:
49133ca95b02SDimitry Andric     case bitc::FS_PERMODULE_PROFILE: {
49147d523365SDimitry Andric       unsigned ValueID = Record[0];
49153ca95b02SDimitry Andric       uint64_t RawFlags = Record[1];
49167d523365SDimitry Andric       unsigned InstCount = Record[2];
49173ca95b02SDimitry Andric       unsigned NumRefs = Record[3];
49183ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
49197d523365SDimitry Andric       // The module path string ref set in the summary must be owned by the
49207d523365SDimitry Andric       // index's module string table. Since we don't have a module path
49217d523365SDimitry Andric       // string table section in the per-module index, we create a single
49227d523365SDimitry Andric       // module path string table entry with an empty (0) ID to take
49237d523365SDimitry Andric       // ownership.
49243ca95b02SDimitry Andric       static int RefListStartIndex = 4;
49253ca95b02SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
49263ca95b02SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
49273ca95b02SDimitry Andric              "Record size inconsistent with number of references");
4928d88c1a5aSDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
4929d88c1a5aSDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
49303ca95b02SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
4931d88c1a5aSDimitry Andric       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
4932d88c1a5aSDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
4933d88c1a5aSDimitry Andric           IsOldProfileFormat, HasProfile);
4934d88c1a5aSDimitry Andric       auto FS = llvm::make_unique<FunctionSummary>(
4935d88c1a5aSDimitry Andric           Flags, InstCount, std::move(Refs), std::move(Calls),
49367a7e6055SDimitry Andric           std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls),
49377a7e6055SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
49387a7e6055SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
49397a7e6055SDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls));
4940d88c1a5aSDimitry Andric       PendingTypeTests.clear();
49417a7e6055SDimitry Andric       PendingTypeTestAssumeVCalls.clear();
49427a7e6055SDimitry Andric       PendingTypeCheckedLoadVCalls.clear();
49437a7e6055SDimitry Andric       PendingTypeTestAssumeConstVCalls.clear();
49447a7e6055SDimitry Andric       PendingTypeCheckedLoadConstVCalls.clear();
49453ca95b02SDimitry Andric       auto GUID = getGUIDFromValueId(ValueID);
4946d88c1a5aSDimitry Andric       FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
49473ca95b02SDimitry Andric       FS->setOriginalName(GUID.second);
4948d88c1a5aSDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
49493ca95b02SDimitry Andric       break;
49503ca95b02SDimitry Andric     }
49513ca95b02SDimitry Andric     // FS_ALIAS: [valueid, flags, valueid]
49523ca95b02SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
49533ca95b02SDimitry Andric     // they expect all aliasee summaries to be available.
49543ca95b02SDimitry Andric     case bitc::FS_ALIAS: {
49553ca95b02SDimitry Andric       unsigned ValueID = Record[0];
49563ca95b02SDimitry Andric       uint64_t RawFlags = Record[1];
49573ca95b02SDimitry Andric       unsigned AliaseeID = Record[2];
49583ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
4959d88c1a5aSDimitry Andric       auto AS =
4960d88c1a5aSDimitry Andric           llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
49613ca95b02SDimitry Andric       // The module path string ref set in the summary must be owned by the
49623ca95b02SDimitry Andric       // index's module string table. Since we don't have a module path
49633ca95b02SDimitry Andric       // string table section in the per-module index, we create a single
49643ca95b02SDimitry Andric       // module path string table entry with an empty (0) ID to take
49653ca95b02SDimitry Andric       // ownership.
4966d88c1a5aSDimitry Andric       AS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
49673ca95b02SDimitry Andric 
49683ca95b02SDimitry Andric       GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
4969d88c1a5aSDimitry Andric       auto *AliaseeSummary = TheIndex.getGlobalValueSummary(AliaseeGUID);
49703ca95b02SDimitry Andric       if (!AliaseeSummary)
49713ca95b02SDimitry Andric         return error("Alias expects aliasee summary to be parsed");
49723ca95b02SDimitry Andric       AS->setAliasee(AliaseeSummary);
49733ca95b02SDimitry Andric 
49743ca95b02SDimitry Andric       auto GUID = getGUIDFromValueId(ValueID);
49753ca95b02SDimitry Andric       AS->setOriginalName(GUID.second);
4976d88c1a5aSDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
49773ca95b02SDimitry Andric       break;
49783ca95b02SDimitry Andric     }
49793ca95b02SDimitry Andric     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
49803ca95b02SDimitry Andric     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
49813ca95b02SDimitry Andric       unsigned ValueID = Record[0];
49823ca95b02SDimitry Andric       uint64_t RawFlags = Record[1];
49833ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
4984d88c1a5aSDimitry Andric       std::vector<ValueInfo> Refs =
4985d88c1a5aSDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(2));
4986d88c1a5aSDimitry Andric       auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
4987d88c1a5aSDimitry Andric       FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
49883ca95b02SDimitry Andric       auto GUID = getGUIDFromValueId(ValueID);
49893ca95b02SDimitry Andric       FS->setOriginalName(GUID.second);
4990d88c1a5aSDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
49913ca95b02SDimitry Andric       break;
49923ca95b02SDimitry Andric     }
49933ca95b02SDimitry Andric     // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
4994d88c1a5aSDimitry Andric     //               numrefs x valueid, n x (valueid)]
49953ca95b02SDimitry Andric     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
4996d88c1a5aSDimitry Andric     //                       numrefs x valueid, n x (valueid, hotness)]
49973ca95b02SDimitry Andric     case bitc::FS_COMBINED:
49983ca95b02SDimitry Andric     case bitc::FS_COMBINED_PROFILE: {
49993ca95b02SDimitry Andric       unsigned ValueID = Record[0];
50003ca95b02SDimitry Andric       uint64_t ModuleId = Record[1];
50013ca95b02SDimitry Andric       uint64_t RawFlags = Record[2];
50023ca95b02SDimitry Andric       unsigned InstCount = Record[3];
50033ca95b02SDimitry Andric       unsigned NumRefs = Record[4];
50043ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
50053ca95b02SDimitry Andric       static int RefListStartIndex = 5;
50063ca95b02SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
50073ca95b02SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
50083ca95b02SDimitry Andric              "Record size inconsistent with number of references");
5009d88c1a5aSDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
5010d88c1a5aSDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
50113ca95b02SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5012d88c1a5aSDimitry Andric       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
5013d88c1a5aSDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
5014d88c1a5aSDimitry Andric           IsOldProfileFormat, HasProfile);
50153ca95b02SDimitry Andric       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
5016d88c1a5aSDimitry Andric       auto FS = llvm::make_unique<FunctionSummary>(
5017d88c1a5aSDimitry Andric           Flags, InstCount, std::move(Refs), std::move(Edges),
50187a7e6055SDimitry Andric           std::move(PendingTypeTests), std::move(PendingTypeTestAssumeVCalls),
50197a7e6055SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
50207a7e6055SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
50217a7e6055SDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls));
5022d88c1a5aSDimitry Andric       PendingTypeTests.clear();
50237a7e6055SDimitry Andric       PendingTypeTestAssumeVCalls.clear();
50247a7e6055SDimitry Andric       PendingTypeCheckedLoadVCalls.clear();
50257a7e6055SDimitry Andric       PendingTypeTestAssumeConstVCalls.clear();
50267a7e6055SDimitry Andric       PendingTypeCheckedLoadConstVCalls.clear();
5027d88c1a5aSDimitry Andric       LastSeenSummary = FS.get();
50287a7e6055SDimitry Andric       LastSeenGUID = GUID;
5029d88c1a5aSDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
5030d88c1a5aSDimitry Andric       TheIndex.addGlobalValueSummary(GUID, std::move(FS));
50313ca95b02SDimitry Andric       Combined = true;
50323ca95b02SDimitry Andric       break;
50333ca95b02SDimitry Andric     }
50343ca95b02SDimitry Andric     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
50353ca95b02SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
50363ca95b02SDimitry Andric     // they expect all aliasee summaries to be available.
50373ca95b02SDimitry Andric     case bitc::FS_COMBINED_ALIAS: {
50383ca95b02SDimitry Andric       unsigned ValueID = Record[0];
50393ca95b02SDimitry Andric       uint64_t ModuleId = Record[1];
50403ca95b02SDimitry Andric       uint64_t RawFlags = Record[2];
50413ca95b02SDimitry Andric       unsigned AliaseeValueId = Record[3];
50423ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5043d88c1a5aSDimitry Andric       auto AS = llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
50443ca95b02SDimitry Andric       LastSeenSummary = AS.get();
50453ca95b02SDimitry Andric       AS->setModulePath(ModuleIdMap[ModuleId]);
50463ca95b02SDimitry Andric 
50473ca95b02SDimitry Andric       auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
50483ca95b02SDimitry Andric       auto AliaseeInModule =
5049d88c1a5aSDimitry Andric           TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
50503ca95b02SDimitry Andric       if (!AliaseeInModule)
50513ca95b02SDimitry Andric         return error("Alias expects aliasee summary to be parsed");
50523ca95b02SDimitry Andric       AS->setAliasee(AliaseeInModule);
50533ca95b02SDimitry Andric 
50543ca95b02SDimitry Andric       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
50557a7e6055SDimitry Andric       LastSeenGUID = GUID;
5056d88c1a5aSDimitry Andric       TheIndex.addGlobalValueSummary(GUID, std::move(AS));
50573ca95b02SDimitry Andric       Combined = true;
50583ca95b02SDimitry Andric       break;
50593ca95b02SDimitry Andric     }
50603ca95b02SDimitry Andric     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
50613ca95b02SDimitry Andric     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
50623ca95b02SDimitry Andric       unsigned ValueID = Record[0];
50633ca95b02SDimitry Andric       uint64_t ModuleId = Record[1];
50643ca95b02SDimitry Andric       uint64_t RawFlags = Record[2];
50653ca95b02SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5066d88c1a5aSDimitry Andric       std::vector<ValueInfo> Refs =
5067d88c1a5aSDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(3));
5068d88c1a5aSDimitry Andric       auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
50693ca95b02SDimitry Andric       LastSeenSummary = FS.get();
50703ca95b02SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
50713ca95b02SDimitry Andric       GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
50727a7e6055SDimitry Andric       LastSeenGUID = GUID;
5073d88c1a5aSDimitry Andric       TheIndex.addGlobalValueSummary(GUID, std::move(FS));
50743ca95b02SDimitry Andric       Combined = true;
50753ca95b02SDimitry Andric       break;
50763ca95b02SDimitry Andric     }
50773ca95b02SDimitry Andric     // FS_COMBINED_ORIGINAL_NAME: [original_name]
50783ca95b02SDimitry Andric     case bitc::FS_COMBINED_ORIGINAL_NAME: {
50793ca95b02SDimitry Andric       uint64_t OriginalName = Record[0];
50803ca95b02SDimitry Andric       if (!LastSeenSummary)
50813ca95b02SDimitry Andric         return error("Name attachment that does not follow a combined record");
50823ca95b02SDimitry Andric       LastSeenSummary->setOriginalName(OriginalName);
50837a7e6055SDimitry Andric       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
50843ca95b02SDimitry Andric       // Reset the LastSeenSummary
50853ca95b02SDimitry Andric       LastSeenSummary = nullptr;
50867a7e6055SDimitry Andric       LastSeenGUID = 0;
5087d88c1a5aSDimitry Andric       break;
5088d88c1a5aSDimitry Andric     }
5089d88c1a5aSDimitry Andric     case bitc::FS_TYPE_TESTS: {
5090d88c1a5aSDimitry Andric       assert(PendingTypeTests.empty());
5091d88c1a5aSDimitry Andric       PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5092d88c1a5aSDimitry Andric                               Record.end());
5093d88c1a5aSDimitry Andric       break;
50947d523365SDimitry Andric     }
50957a7e6055SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_VCALLS: {
50967a7e6055SDimitry Andric       assert(PendingTypeTestAssumeVCalls.empty());
50977a7e6055SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
50987a7e6055SDimitry Andric         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
50997a7e6055SDimitry Andric       break;
51007a7e6055SDimitry Andric     }
51017a7e6055SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: {
51027a7e6055SDimitry Andric       assert(PendingTypeCheckedLoadVCalls.empty());
51037a7e6055SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
51047a7e6055SDimitry Andric         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
51057a7e6055SDimitry Andric       break;
51067a7e6055SDimitry Andric     }
51077a7e6055SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: {
51087a7e6055SDimitry Andric       PendingTypeTestAssumeConstVCalls.push_back(
51097a7e6055SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
51107a7e6055SDimitry Andric       break;
51117a7e6055SDimitry Andric     }
51127a7e6055SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL: {
51137a7e6055SDimitry Andric       PendingTypeCheckedLoadConstVCalls.push_back(
51147a7e6055SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
51157a7e6055SDimitry Andric       break;
51167a7e6055SDimitry Andric     }
51177d523365SDimitry Andric     }
51187d523365SDimitry Andric   }
51197d523365SDimitry Andric   llvm_unreachable("Exit infinite loop");
51207d523365SDimitry Andric }
51217d523365SDimitry Andric 
51227d523365SDimitry Andric // Parse the  module string table block into the Index.
51237d523365SDimitry Andric // This populates the ModulePathStringTable map in the index.
5124d88c1a5aSDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
51257d523365SDimitry Andric   if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
51267d523365SDimitry Andric     return error("Invalid record");
51277d523365SDimitry Andric 
51287d523365SDimitry Andric   SmallVector<uint64_t, 64> Record;
51297d523365SDimitry Andric 
51307d523365SDimitry Andric   SmallString<128> ModulePath;
51313ca95b02SDimitry Andric   ModulePathStringTableTy::iterator LastSeenModulePath;
5132d88c1a5aSDimitry Andric 
5133d88c1a5aSDimitry Andric   while (true) {
51347d523365SDimitry Andric     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
51357d523365SDimitry Andric 
51367d523365SDimitry Andric     switch (Entry.Kind) {
51377d523365SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
51387d523365SDimitry Andric     case BitstreamEntry::Error:
51397d523365SDimitry Andric       return error("Malformed block");
51407d523365SDimitry Andric     case BitstreamEntry::EndBlock:
5141d88c1a5aSDimitry Andric       return Error::success();
51427d523365SDimitry Andric     case BitstreamEntry::Record:
51437d523365SDimitry Andric       // The interesting case.
51447d523365SDimitry Andric       break;
51457d523365SDimitry Andric     }
51467d523365SDimitry Andric 
51477d523365SDimitry Andric     Record.clear();
51487d523365SDimitry Andric     switch (Stream.readRecord(Entry.ID, Record)) {
51497d523365SDimitry Andric     default: // Default behavior: ignore.
51507d523365SDimitry Andric       break;
51517d523365SDimitry Andric     case bitc::MST_CODE_ENTRY: {
51527d523365SDimitry Andric       // MST_ENTRY: [modid, namechar x N]
51533ca95b02SDimitry Andric       uint64_t ModuleId = Record[0];
51543ca95b02SDimitry Andric 
51557d523365SDimitry Andric       if (convertToString(Record, 1, ModulePath))
51567d523365SDimitry Andric         return error("Invalid record");
51573ca95b02SDimitry Andric 
5158d88c1a5aSDimitry Andric       LastSeenModulePath = TheIndex.addModulePath(ModulePath, ModuleId);
51593ca95b02SDimitry Andric       ModuleIdMap[ModuleId] = LastSeenModulePath->first();
51603ca95b02SDimitry Andric 
51617d523365SDimitry Andric       ModulePath.clear();
51627d523365SDimitry Andric       break;
51637d523365SDimitry Andric     }
51643ca95b02SDimitry Andric     /// MST_CODE_HASH: [5*i32]
51653ca95b02SDimitry Andric     case bitc::MST_CODE_HASH: {
51663ca95b02SDimitry Andric       if (Record.size() != 5)
51673ca95b02SDimitry Andric         return error("Invalid hash length " + Twine(Record.size()).str());
5168d88c1a5aSDimitry Andric       if (LastSeenModulePath == TheIndex.modulePaths().end())
51693ca95b02SDimitry Andric         return error("Invalid hash that does not follow a module path");
51703ca95b02SDimitry Andric       int Pos = 0;
51713ca95b02SDimitry Andric       for (auto &Val : Record) {
51723ca95b02SDimitry Andric         assert(!(Val >> 32) && "Unexpected high bits set");
51733ca95b02SDimitry Andric         LastSeenModulePath->second.second[Pos++] = Val;
51743ca95b02SDimitry Andric       }
51753ca95b02SDimitry Andric       // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
5176d88c1a5aSDimitry Andric       LastSeenModulePath = TheIndex.modulePaths().end();
51773ca95b02SDimitry Andric       break;
51783ca95b02SDimitry Andric     }
51797d523365SDimitry Andric     }
51807d523365SDimitry Andric   }
51817d523365SDimitry Andric   llvm_unreachable("Exit infinite loop");
51827d523365SDimitry Andric }
51837d523365SDimitry Andric 
5184f785676fSDimitry Andric namespace {
5185d88c1a5aSDimitry Andric 
51863ca95b02SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
51873ca95b02SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
51883ca95b02SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
518991bc56edSDimitry Andric class BitcodeErrorCategoryType : public std::error_category {
5190d88c1a5aSDimitry Andric   const char *name() const noexcept override {
5191f785676fSDimitry Andric     return "llvm.bitcode";
5192f785676fSDimitry Andric   }
519391bc56edSDimitry Andric   std::string message(int IE) const override {
519439d628a0SDimitry Andric     BitcodeError E = static_cast<BitcodeError>(IE);
5195f785676fSDimitry Andric     switch (E) {
519639d628a0SDimitry Andric     case BitcodeError::CorruptedBitcode:
519739d628a0SDimitry Andric       return "Corrupted bitcode";
5198f785676fSDimitry Andric     }
5199f785676fSDimitry Andric     llvm_unreachable("Unknown error type!");
5200f785676fSDimitry Andric   }
5201f785676fSDimitry Andric };
5202d88c1a5aSDimitry Andric 
52033ca95b02SDimitry Andric } // end anonymous namespace
5204f785676fSDimitry Andric 
520539d628a0SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
520639d628a0SDimitry Andric 
520739d628a0SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() {
520839d628a0SDimitry Andric   return *ErrorCategory;
5209dff0c46cSDimitry Andric }
5210f22ef01cSRoman Divacky 
5211f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
5212f22ef01cSRoman Divacky // External interface
5213f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
5214f22ef01cSRoman Divacky 
5215d88c1a5aSDimitry Andric Expected<std::vector<BitcodeModule>>
5216d88c1a5aSDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
5217d88c1a5aSDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5218d88c1a5aSDimitry Andric   if (!StreamOrErr)
5219d88c1a5aSDimitry Andric     return StreamOrErr.takeError();
5220d88c1a5aSDimitry Andric   BitstreamCursor &Stream = *StreamOrErr;
52218f0fd8f6SDimitry Andric 
5222d88c1a5aSDimitry Andric   std::vector<BitcodeModule> Modules;
5223d88c1a5aSDimitry Andric   while (true) {
5224d88c1a5aSDimitry Andric     uint64_t BCBegin = Stream.getCurrentByteNo();
52258f0fd8f6SDimitry Andric 
5226d88c1a5aSDimitry Andric     // We may be consuming bitcode from a client that leaves garbage at the end
5227d88c1a5aSDimitry Andric     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5228d88c1a5aSDimitry Andric     // the end that there cannot possibly be another module, stop looking.
5229d88c1a5aSDimitry Andric     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
5230d88c1a5aSDimitry Andric       return Modules;
52318f0fd8f6SDimitry Andric 
5232d88c1a5aSDimitry Andric     BitstreamEntry Entry = Stream.advance();
5233d88c1a5aSDimitry Andric     switch (Entry.Kind) {
5234d88c1a5aSDimitry Andric     case BitstreamEntry::EndBlock:
5235d88c1a5aSDimitry Andric     case BitstreamEntry::Error:
5236d88c1a5aSDimitry Andric       return error("Malformed block");
5237d88c1a5aSDimitry Andric 
5238d88c1a5aSDimitry Andric     case BitstreamEntry::SubBlock: {
5239d88c1a5aSDimitry Andric       uint64_t IdentificationBit = -1ull;
5240d88c1a5aSDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5241d88c1a5aSDimitry Andric         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5242d88c1a5aSDimitry Andric         if (Stream.SkipBlock())
5243d88c1a5aSDimitry Andric           return error("Malformed block");
5244d88c1a5aSDimitry Andric 
5245d88c1a5aSDimitry Andric         Entry = Stream.advance();
5246d88c1a5aSDimitry Andric         if (Entry.Kind != BitstreamEntry::SubBlock ||
5247d88c1a5aSDimitry Andric             Entry.ID != bitc::MODULE_BLOCK_ID)
5248d88c1a5aSDimitry Andric           return error("Malformed block");
52498f0fd8f6SDimitry Andric       }
5250d88c1a5aSDimitry Andric 
5251d88c1a5aSDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5252d88c1a5aSDimitry Andric         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5253d88c1a5aSDimitry Andric         if (Stream.SkipBlock())
5254d88c1a5aSDimitry Andric           return error("Malformed block");
5255d88c1a5aSDimitry Andric 
5256d88c1a5aSDimitry Andric         Modules.push_back({Stream.getBitcodeBytes().slice(
5257d88c1a5aSDimitry Andric                                BCBegin, Stream.getCurrentByteNo() - BCBegin),
5258d88c1a5aSDimitry Andric                            Buffer.getBufferIdentifier(), IdentificationBit,
5259d88c1a5aSDimitry Andric                            ModuleBit});
5260d88c1a5aSDimitry Andric         continue;
5261d88c1a5aSDimitry Andric       }
5262d88c1a5aSDimitry Andric 
5263d88c1a5aSDimitry Andric       if (Stream.SkipBlock())
5264d88c1a5aSDimitry Andric         return error("Malformed block");
5265d88c1a5aSDimitry Andric       continue;
5266d88c1a5aSDimitry Andric     }
5267d88c1a5aSDimitry Andric     case BitstreamEntry::Record:
5268d88c1a5aSDimitry Andric       Stream.skipRecord(Entry.ID);
5269d88c1a5aSDimitry Andric       continue;
5270d88c1a5aSDimitry Andric     }
5271d88c1a5aSDimitry Andric   }
52728f0fd8f6SDimitry Andric }
52738f0fd8f6SDimitry Andric 
527439d628a0SDimitry Andric /// \brief Get a lazy one-at-time loading module from bitcode.
5275f22ef01cSRoman Divacky ///
527639d628a0SDimitry Andric /// This isn't always used in a lazy context.  In particular, it's also used by
5277d88c1a5aSDimitry Andric /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
527839d628a0SDimitry Andric /// in forward-referenced functions from block address references.
527939d628a0SDimitry Andric ///
52808f0fd8f6SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize
52818f0fd8f6SDimitry Andric /// everything.
5282d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>>
5283d88c1a5aSDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
5284d88c1a5aSDimitry Andric                              bool ShouldLazyLoadMetadata, bool IsImporting) {
5285d88c1a5aSDimitry Andric   BitstreamCursor Stream(Buffer);
528639d628a0SDimitry Andric 
5287d88c1a5aSDimitry Andric   std::string ProducerIdentification;
5288d88c1a5aSDimitry Andric   if (IdentificationBit != -1ull) {
5289d88c1a5aSDimitry Andric     Stream.JumpToBit(IdentificationBit);
5290d88c1a5aSDimitry Andric     Expected<std::string> ProducerIdentificationOrErr =
5291d88c1a5aSDimitry Andric         readIdentificationBlock(Stream);
5292d88c1a5aSDimitry Andric     if (!ProducerIdentificationOrErr)
5293d88c1a5aSDimitry Andric       return ProducerIdentificationOrErr.takeError();
529439d628a0SDimitry Andric 
5295d88c1a5aSDimitry Andric     ProducerIdentification = *ProducerIdentificationOrErr;
5296dff0c46cSDimitry Andric   }
5297dff0c46cSDimitry Andric 
5298d88c1a5aSDimitry Andric   Stream.JumpToBit(ModuleBit);
5299d88c1a5aSDimitry Andric   auto *R =
5300d88c1a5aSDimitry Andric       new BitcodeReader(std::move(Stream), ProducerIdentification, Context);
5301d88c1a5aSDimitry Andric 
5302d88c1a5aSDimitry Andric   std::unique_ptr<Module> M =
5303d88c1a5aSDimitry Andric       llvm::make_unique<Module>(ModuleIdentifier, Context);
5304d88c1a5aSDimitry Andric   M->setMaterializer(R);
5305d88c1a5aSDimitry Andric 
5306d88c1a5aSDimitry Andric   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5307d88c1a5aSDimitry Andric   if (Error Err =
5308d88c1a5aSDimitry Andric           R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
5309d88c1a5aSDimitry Andric     return std::move(Err);
5310d88c1a5aSDimitry Andric 
5311d88c1a5aSDimitry Andric   if (MaterializeAll) {
5312d88c1a5aSDimitry Andric     // Read in the entire module, and destroy the BitcodeReader.
5313d88c1a5aSDimitry Andric     if (Error Err = M->materializeAll())
5314d88c1a5aSDimitry Andric       return std::move(Err);
5315d88c1a5aSDimitry Andric   } else {
5316d88c1a5aSDimitry Andric     // Resolve forward references from blockaddresses.
5317d88c1a5aSDimitry Andric     if (Error Err = R->materializeForwardReferencedFunctions())
5318d88c1a5aSDimitry Andric       return std::move(Err);
5319d88c1a5aSDimitry Andric   }
5320d88c1a5aSDimitry Andric   return std::move(M);
5321f22ef01cSRoman Divacky }
5322f22ef01cSRoman Divacky 
5323d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>>
5324d88c1a5aSDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5325d88c1a5aSDimitry Andric                              bool IsImporting) {
5326d88c1a5aSDimitry Andric   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
53277d523365SDimitry Andric }
53287d523365SDimitry Andric 
53297d523365SDimitry Andric // Parse the specified bitcode buffer, returning the function info index.
5330d88c1a5aSDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
5331d88c1a5aSDimitry Andric   BitstreamCursor Stream(Buffer);
5332d88c1a5aSDimitry Andric   Stream.JumpToBit(ModuleBit);
53337d523365SDimitry Andric 
53343ca95b02SDimitry Andric   auto Index = llvm::make_unique<ModuleSummaryIndex>();
5335d88c1a5aSDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), *Index);
53367d523365SDimitry Andric 
5337d88c1a5aSDimitry Andric   if (Error Err = R.parseModule(ModuleIdentifier))
5338d88c1a5aSDimitry Andric     return std::move(Err);
53397d523365SDimitry Andric 
53407d523365SDimitry Andric   return std::move(Index);
53417d523365SDimitry Andric }
53427d523365SDimitry Andric 
53433ca95b02SDimitry Andric // Check if the given bitcode buffer contains a global value summary block.
5344d88c1a5aSDimitry Andric Expected<bool> BitcodeModule::hasSummary() {
5345d88c1a5aSDimitry Andric   BitstreamCursor Stream(Buffer);
5346d88c1a5aSDimitry Andric   Stream.JumpToBit(ModuleBit);
53477d523365SDimitry Andric 
5348d88c1a5aSDimitry Andric   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5349d88c1a5aSDimitry Andric     return error("Invalid record");
5350d88c1a5aSDimitry Andric 
5351d88c1a5aSDimitry Andric   while (true) {
5352d88c1a5aSDimitry Andric     BitstreamEntry Entry = Stream.advance();
5353d88c1a5aSDimitry Andric 
5354d88c1a5aSDimitry Andric     switch (Entry.Kind) {
5355d88c1a5aSDimitry Andric     case BitstreamEntry::Error:
5356d88c1a5aSDimitry Andric       return error("Malformed block");
5357d88c1a5aSDimitry Andric     case BitstreamEntry::EndBlock:
53587d523365SDimitry Andric       return false;
53597d523365SDimitry Andric 
5360d88c1a5aSDimitry Andric     case BitstreamEntry::SubBlock:
5361d88c1a5aSDimitry Andric       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID)
5362d88c1a5aSDimitry Andric         return true;
53637d523365SDimitry Andric 
5364d88c1a5aSDimitry Andric       // Ignore other sub-blocks.
5365d88c1a5aSDimitry Andric       if (Stream.SkipBlock())
5366d88c1a5aSDimitry Andric         return error("Malformed block");
5367d88c1a5aSDimitry Andric       continue;
5368d88c1a5aSDimitry Andric 
5369d88c1a5aSDimitry Andric     case BitstreamEntry::Record:
5370d88c1a5aSDimitry Andric       Stream.skipRecord(Entry.ID);
5371d88c1a5aSDimitry Andric       continue;
5372d88c1a5aSDimitry Andric     }
5373d88c1a5aSDimitry Andric   }
5374d88c1a5aSDimitry Andric }
5375d88c1a5aSDimitry Andric 
5376d88c1a5aSDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
5377d88c1a5aSDimitry Andric   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
5378d88c1a5aSDimitry Andric   if (!MsOrErr)
5379d88c1a5aSDimitry Andric     return MsOrErr.takeError();
5380d88c1a5aSDimitry Andric 
5381d88c1a5aSDimitry Andric   if (MsOrErr->size() != 1)
5382d88c1a5aSDimitry Andric     return error("Expected a single module");
5383d88c1a5aSDimitry Andric 
5384d88c1a5aSDimitry Andric   return (*MsOrErr)[0];
5385d88c1a5aSDimitry Andric }
5386d88c1a5aSDimitry Andric 
5387d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>>
5388d88c1a5aSDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
5389d88c1a5aSDimitry Andric                            bool ShouldLazyLoadMetadata, bool IsImporting) {
5390d88c1a5aSDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5391d88c1a5aSDimitry Andric   if (!BM)
5392d88c1a5aSDimitry Andric     return BM.takeError();
5393d88c1a5aSDimitry Andric 
5394d88c1a5aSDimitry Andric   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
5395d88c1a5aSDimitry Andric }
5396d88c1a5aSDimitry Andric 
5397d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
5398d88c1a5aSDimitry Andric     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5399d88c1a5aSDimitry Andric     bool ShouldLazyLoadMetadata, bool IsImporting) {
5400d88c1a5aSDimitry Andric   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
5401d88c1a5aSDimitry Andric                                      IsImporting);
5402d88c1a5aSDimitry Andric   if (MOrErr)
5403d88c1a5aSDimitry Andric     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5404d88c1a5aSDimitry Andric   return MOrErr;
5405d88c1a5aSDimitry Andric }
5406d88c1a5aSDimitry Andric 
5407d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>>
5408d88c1a5aSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context) {
5409d88c1a5aSDimitry Andric   return getModuleImpl(Context, true, false, false);
5410d88c1a5aSDimitry Andric   // TODO: Restore the use-lists to the in-memory state when the bitcode was
5411d88c1a5aSDimitry Andric   // written.  We must defer until the Module has been fully materialized.
5412d88c1a5aSDimitry Andric }
5413d88c1a5aSDimitry Andric 
5414d88c1a5aSDimitry Andric Expected<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5415d88c1a5aSDimitry Andric                                                          LLVMContext &Context) {
5416d88c1a5aSDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5417d88c1a5aSDimitry Andric   if (!BM)
5418d88c1a5aSDimitry Andric     return BM.takeError();
5419d88c1a5aSDimitry Andric 
5420d88c1a5aSDimitry Andric   return BM->parseModule(Context);
5421d88c1a5aSDimitry Andric }
5422d88c1a5aSDimitry Andric 
5423d88c1a5aSDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
5424d88c1a5aSDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5425d88c1a5aSDimitry Andric   if (!StreamOrErr)
5426d88c1a5aSDimitry Andric     return StreamOrErr.takeError();
5427d88c1a5aSDimitry Andric 
5428d88c1a5aSDimitry Andric   return readTriple(*StreamOrErr);
5429d88c1a5aSDimitry Andric }
5430d88c1a5aSDimitry Andric 
5431d88c1a5aSDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
5432d88c1a5aSDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5433d88c1a5aSDimitry Andric   if (!StreamOrErr)
5434d88c1a5aSDimitry Andric     return StreamOrErr.takeError();
5435d88c1a5aSDimitry Andric 
5436d88c1a5aSDimitry Andric   return hasObjCCategory(*StreamOrErr);
5437d88c1a5aSDimitry Andric }
5438d88c1a5aSDimitry Andric 
5439d88c1a5aSDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
5440d88c1a5aSDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5441d88c1a5aSDimitry Andric   if (!StreamOrErr)
5442d88c1a5aSDimitry Andric     return StreamOrErr.takeError();
5443d88c1a5aSDimitry Andric 
5444d88c1a5aSDimitry Andric   return readIdentificationCode(*StreamOrErr);
5445d88c1a5aSDimitry Andric }
5446d88c1a5aSDimitry Andric 
5447d88c1a5aSDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
5448d88c1a5aSDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
5449d88c1a5aSDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5450d88c1a5aSDimitry Andric   if (!BM)
5451d88c1a5aSDimitry Andric     return BM.takeError();
5452d88c1a5aSDimitry Andric 
5453d88c1a5aSDimitry Andric   return BM->getSummary();
5454d88c1a5aSDimitry Andric }
5455d88c1a5aSDimitry Andric 
5456d88c1a5aSDimitry Andric Expected<bool> llvm::hasGlobalValueSummary(MemoryBufferRef Buffer) {
5457d88c1a5aSDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
5458d88c1a5aSDimitry Andric   if (!BM)
5459d88c1a5aSDimitry Andric     return BM.takeError();
5460d88c1a5aSDimitry Andric 
5461d88c1a5aSDimitry Andric   return BM->hasSummary();
54627d523365SDimitry Andric }
5463