10b57cec5SDimitry Andric //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
100b57cec5SDimitry Andric #include "MetadataLoader.h"
110b57cec5SDimitry Andric #include "ValueList.h"
120b57cec5SDimitry Andric #include "llvm/ADT/APFloat.h"
130b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
140b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
150b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
160b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
170b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
180b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
190b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
200b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
210b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
220b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
23af732203SDimitry Andric #include "llvm/Bitcode/BitcodeCommon.h"
240b57cec5SDimitry Andric #include "llvm/Bitcode/LLVMBitCodes.h"
25af732203SDimitry Andric #include "llvm/Bitstream/BitstreamReader.h"
260b57cec5SDimitry Andric #include "llvm/Config/llvm-config.h"
270b57cec5SDimitry Andric #include "llvm/IR/Argument.h"
280b57cec5SDimitry Andric #include "llvm/IR/Attributes.h"
290b57cec5SDimitry Andric #include "llvm/IR/AutoUpgrade.h"
300b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
310b57cec5SDimitry Andric #include "llvm/IR/CallingConv.h"
320b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
330b57cec5SDimitry Andric #include "llvm/IR/Constant.h"
340b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
350b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
360b57cec5SDimitry Andric #include "llvm/IR/DebugInfo.h"
370b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
380b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
390b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
400b57cec5SDimitry Andric #include "llvm/IR/Function.h"
410b57cec5SDimitry Andric #include "llvm/IR/GVMaterializer.h"
420b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
430b57cec5SDimitry Andric #include "llvm/IR/GlobalIFunc.h"
440b57cec5SDimitry Andric #include "llvm/IR/GlobalIndirectSymbol.h"
450b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
460b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
470b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
480b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
490b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
500b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
510b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
520b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
530b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
540b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
550b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
560b57cec5SDimitry Andric #include "llvm/IR/Module.h"
570b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
580b57cec5SDimitry Andric #include "llvm/IR/Operator.h"
590b57cec5SDimitry Andric #include "llvm/IR/Type.h"
600b57cec5SDimitry Andric #include "llvm/IR/Value.h"
610b57cec5SDimitry Andric #include "llvm/IR/Verifier.h"
620b57cec5SDimitry Andric #include "llvm/Support/AtomicOrdering.h"
630b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
640b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
650b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
660b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
670b57cec5SDimitry Andric #include "llvm/Support/Error.h"
680b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
690b57cec5SDimitry Andric #include "llvm/Support/ErrorOr.h"
700b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
710b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
720b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
730b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
740b57cec5SDimitry Andric #include <algorithm>
750b57cec5SDimitry Andric #include <cassert>
760b57cec5SDimitry Andric #include <cstddef>
770b57cec5SDimitry Andric #include <cstdint>
780b57cec5SDimitry Andric #include <deque>
790b57cec5SDimitry Andric #include <map>
800b57cec5SDimitry Andric #include <memory>
810b57cec5SDimitry Andric #include <set>
820b57cec5SDimitry Andric #include <string>
830b57cec5SDimitry Andric #include <system_error>
840b57cec5SDimitry Andric #include <tuple>
850b57cec5SDimitry Andric #include <utility>
860b57cec5SDimitry Andric #include <vector>
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric using namespace llvm;
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric static cl::opt<bool> PrintSummaryGUIDs(
910b57cec5SDimitry Andric     "print-summary-global-ids", cl::init(false), cl::Hidden,
920b57cec5SDimitry Andric     cl::desc(
930b57cec5SDimitry Andric         "Print the global id for each value when reading the module summary"));
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric namespace {
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric enum {
980b57cec5SDimitry Andric   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
990b57cec5SDimitry Andric };
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric } // end anonymous namespace
1020b57cec5SDimitry Andric 
error(const Twine & Message)1030b57cec5SDimitry Andric static Error error(const Twine &Message) {
1040b57cec5SDimitry Andric   return make_error<StringError>(
1050b57cec5SDimitry Andric       Message, make_error_code(BitcodeError::CorruptedBitcode));
1060b57cec5SDimitry Andric }
1070b57cec5SDimitry Andric 
hasInvalidBitcodeHeader(BitstreamCursor & Stream)1080b57cec5SDimitry Andric static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
1090b57cec5SDimitry Andric   if (!Stream.canSkipToPos(4))
1100b57cec5SDimitry Andric     return createStringError(std::errc::illegal_byte_sequence,
1110b57cec5SDimitry Andric                              "file too small to contain bitcode header");
1120b57cec5SDimitry Andric   for (unsigned C : {'B', 'C'})
1130b57cec5SDimitry Andric     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
1140b57cec5SDimitry Andric       if (Res.get() != C)
1150b57cec5SDimitry Andric         return createStringError(std::errc::illegal_byte_sequence,
1160b57cec5SDimitry Andric                                  "file doesn't start with bitcode header");
1170b57cec5SDimitry Andric     } else
1180b57cec5SDimitry Andric       return Res.takeError();
1190b57cec5SDimitry Andric   for (unsigned C : {0x0, 0xC, 0xE, 0xD})
1200b57cec5SDimitry Andric     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
1210b57cec5SDimitry Andric       if (Res.get() != C)
1220b57cec5SDimitry Andric         return createStringError(std::errc::illegal_byte_sequence,
1230b57cec5SDimitry Andric                                  "file doesn't start with bitcode header");
1240b57cec5SDimitry Andric     } else
1250b57cec5SDimitry Andric       return Res.takeError();
1260b57cec5SDimitry Andric   return Error::success();
1270b57cec5SDimitry Andric }
1280b57cec5SDimitry Andric 
initStream(MemoryBufferRef Buffer)1290b57cec5SDimitry Andric static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
1300b57cec5SDimitry Andric   const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
1310b57cec5SDimitry Andric   const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   if (Buffer.getBufferSize() & 3)
1340b57cec5SDimitry Andric     return error("Invalid bitcode signature");
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric   // If we have a wrapper header, parse it and ignore the non-bc file contents.
1370b57cec5SDimitry Andric   // The magic number is 0x0B17C0DE stored in little endian.
1380b57cec5SDimitry Andric   if (isBitcodeWrapper(BufPtr, BufEnd))
1390b57cec5SDimitry Andric     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
1400b57cec5SDimitry Andric       return error("Invalid bitcode wrapper header");
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric   BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
1430b57cec5SDimitry Andric   if (Error Err = hasInvalidBitcodeHeader(Stream))
1440b57cec5SDimitry Andric     return std::move(Err);
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric   return std::move(Stream);
1470b57cec5SDimitry Andric }
1480b57cec5SDimitry Andric 
1490b57cec5SDimitry Andric /// Convert a string from a record into an std::string, return true on failure.
1500b57cec5SDimitry Andric template <typename StrTy>
convertToString(ArrayRef<uint64_t> Record,unsigned Idx,StrTy & Result)1510b57cec5SDimitry Andric static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
1520b57cec5SDimitry Andric                             StrTy &Result) {
1530b57cec5SDimitry Andric   if (Idx > Record.size())
1540b57cec5SDimitry Andric     return true;
1550b57cec5SDimitry Andric 
1565ffd83dbSDimitry Andric   Result.append(Record.begin() + Idx, Record.end());
1570b57cec5SDimitry Andric   return false;
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric // Strip all the TBAA attachment for the module.
stripTBAA(Module * M)1610b57cec5SDimitry Andric static void stripTBAA(Module *M) {
1620b57cec5SDimitry Andric   for (auto &F : *M) {
1630b57cec5SDimitry Andric     if (F.isMaterializable())
1640b57cec5SDimitry Andric       continue;
1650b57cec5SDimitry Andric     for (auto &I : instructions(F))
1660b57cec5SDimitry Andric       I.setMetadata(LLVMContext::MD_tbaa, nullptr);
1670b57cec5SDimitry Andric   }
1680b57cec5SDimitry Andric }
1690b57cec5SDimitry Andric 
1700b57cec5SDimitry Andric /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
1710b57cec5SDimitry Andric /// "epoch" encoded in the bitcode, and return the producer name if any.
readIdentificationBlock(BitstreamCursor & Stream)1720b57cec5SDimitry Andric static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
1730b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
1740b57cec5SDimitry Andric     return std::move(Err);
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric   // Read all the records.
1770b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric   std::string ProducerIdentification;
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric   while (true) {
1820b57cec5SDimitry Andric     BitstreamEntry Entry;
1830b57cec5SDimitry Andric     if (Expected<BitstreamEntry> Res = Stream.advance())
1840b57cec5SDimitry Andric       Entry = Res.get();
1850b57cec5SDimitry Andric     else
1860b57cec5SDimitry Andric       return Res.takeError();
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric     switch (Entry.Kind) {
1890b57cec5SDimitry Andric     default:
1900b57cec5SDimitry Andric     case BitstreamEntry::Error:
1910b57cec5SDimitry Andric       return error("Malformed block");
1920b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
1930b57cec5SDimitry Andric       return ProducerIdentification;
1940b57cec5SDimitry Andric     case BitstreamEntry::Record:
1950b57cec5SDimitry Andric       // The interesting case.
1960b57cec5SDimitry Andric       break;
1970b57cec5SDimitry Andric     }
1980b57cec5SDimitry Andric 
1990b57cec5SDimitry Andric     // Read a record.
2000b57cec5SDimitry Andric     Record.clear();
2010b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2020b57cec5SDimitry Andric     if (!MaybeBitCode)
2030b57cec5SDimitry Andric       return MaybeBitCode.takeError();
2040b57cec5SDimitry Andric     switch (MaybeBitCode.get()) {
2050b57cec5SDimitry Andric     default: // Default behavior: reject
2060b57cec5SDimitry Andric       return error("Invalid value");
2070b57cec5SDimitry Andric     case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
2080b57cec5SDimitry Andric       convertToString(Record, 0, ProducerIdentification);
2090b57cec5SDimitry Andric       break;
2100b57cec5SDimitry Andric     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
2110b57cec5SDimitry Andric       unsigned epoch = (unsigned)Record[0];
2120b57cec5SDimitry Andric       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
2130b57cec5SDimitry Andric         return error(
2140b57cec5SDimitry Andric           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
2150b57cec5SDimitry Andric           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
2160b57cec5SDimitry Andric       }
2170b57cec5SDimitry Andric     }
2180b57cec5SDimitry Andric     }
2190b57cec5SDimitry Andric   }
2200b57cec5SDimitry Andric }
2210b57cec5SDimitry Andric 
readIdentificationCode(BitstreamCursor & Stream)2220b57cec5SDimitry Andric static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
2230b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
2240b57cec5SDimitry Andric   // need to understand them all.
2250b57cec5SDimitry Andric   while (true) {
2260b57cec5SDimitry Andric     if (Stream.AtEndOfStream())
2270b57cec5SDimitry Andric       return "";
2280b57cec5SDimitry Andric 
2290b57cec5SDimitry Andric     BitstreamEntry Entry;
2300b57cec5SDimitry Andric     if (Expected<BitstreamEntry> Res = Stream.advance())
2310b57cec5SDimitry Andric       Entry = std::move(Res.get());
2320b57cec5SDimitry Andric     else
2330b57cec5SDimitry Andric       return Res.takeError();
2340b57cec5SDimitry Andric 
2350b57cec5SDimitry Andric     switch (Entry.Kind) {
2360b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2370b57cec5SDimitry Andric     case BitstreamEntry::Error:
2380b57cec5SDimitry Andric       return error("Malformed block");
2390b57cec5SDimitry Andric 
2400b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
2410b57cec5SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
2420b57cec5SDimitry Andric         return readIdentificationBlock(Stream);
2430b57cec5SDimitry Andric 
2440b57cec5SDimitry Andric       // Ignore other sub-blocks.
2450b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
2460b57cec5SDimitry Andric         return std::move(Err);
2470b57cec5SDimitry Andric       continue;
2480b57cec5SDimitry Andric     case BitstreamEntry::Record:
2490b57cec5SDimitry Andric       if (Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
2500b57cec5SDimitry Andric         continue;
2510b57cec5SDimitry Andric       else
2520b57cec5SDimitry Andric         return Skipped.takeError();
2530b57cec5SDimitry Andric     }
2540b57cec5SDimitry Andric   }
2550b57cec5SDimitry Andric }
2560b57cec5SDimitry Andric 
hasObjCCategoryInModule(BitstreamCursor & Stream)2570b57cec5SDimitry Andric static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
2580b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2590b57cec5SDimitry Andric     return std::move(Err);
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
2620b57cec5SDimitry Andric   // Read all the records for this module.
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric   while (true) {
2650b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2660b57cec5SDimitry Andric     if (!MaybeEntry)
2670b57cec5SDimitry Andric       return MaybeEntry.takeError();
2680b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
2690b57cec5SDimitry Andric 
2700b57cec5SDimitry Andric     switch (Entry.Kind) {
2710b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
2720b57cec5SDimitry Andric     case BitstreamEntry::Error:
2730b57cec5SDimitry Andric       return error("Malformed block");
2740b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
2750b57cec5SDimitry Andric       return false;
2760b57cec5SDimitry Andric     case BitstreamEntry::Record:
2770b57cec5SDimitry Andric       // The interesting case.
2780b57cec5SDimitry Andric       break;
2790b57cec5SDimitry Andric     }
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric     // Read a record.
2820b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2830b57cec5SDimitry Andric     if (!MaybeRecord)
2840b57cec5SDimitry Andric       return MaybeRecord.takeError();
2850b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
2860b57cec5SDimitry Andric     default:
2870b57cec5SDimitry Andric       break; // Default behavior, ignore unknown content.
2880b57cec5SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2890b57cec5SDimitry Andric       std::string S;
2900b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
2910b57cec5SDimitry Andric         return error("Invalid record");
2920b57cec5SDimitry Andric       // Check for the i386 and other (x86_64, ARM) conventions
2930b57cec5SDimitry Andric       if (S.find("__DATA,__objc_catlist") != std::string::npos ||
2940b57cec5SDimitry Andric           S.find("__OBJC,__category") != std::string::npos)
2950b57cec5SDimitry Andric         return true;
2960b57cec5SDimitry Andric       break;
2970b57cec5SDimitry Andric     }
2980b57cec5SDimitry Andric     }
2990b57cec5SDimitry Andric     Record.clear();
3000b57cec5SDimitry Andric   }
3010b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
3020b57cec5SDimitry Andric }
3030b57cec5SDimitry Andric 
hasObjCCategory(BitstreamCursor & Stream)3040b57cec5SDimitry Andric static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
3050b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
3060b57cec5SDimitry Andric   // need to understand them all.
3070b57cec5SDimitry Andric   while (true) {
3080b57cec5SDimitry Andric     BitstreamEntry Entry;
3090b57cec5SDimitry Andric     if (Expected<BitstreamEntry> Res = Stream.advance())
3100b57cec5SDimitry Andric       Entry = std::move(Res.get());
3110b57cec5SDimitry Andric     else
3120b57cec5SDimitry Andric       return Res.takeError();
3130b57cec5SDimitry Andric 
3140b57cec5SDimitry Andric     switch (Entry.Kind) {
3150b57cec5SDimitry Andric     case BitstreamEntry::Error:
3160b57cec5SDimitry Andric       return error("Malformed block");
3170b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
3180b57cec5SDimitry Andric       return false;
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
3210b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
3220b57cec5SDimitry Andric         return hasObjCCategoryInModule(Stream);
3230b57cec5SDimitry Andric 
3240b57cec5SDimitry Andric       // Ignore other sub-blocks.
3250b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
3260b57cec5SDimitry Andric         return std::move(Err);
3270b57cec5SDimitry Andric       continue;
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric     case BitstreamEntry::Record:
3300b57cec5SDimitry Andric       if (Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
3310b57cec5SDimitry Andric         continue;
3320b57cec5SDimitry Andric       else
3330b57cec5SDimitry Andric         return Skipped.takeError();
3340b57cec5SDimitry Andric     }
3350b57cec5SDimitry Andric   }
3360b57cec5SDimitry Andric }
3370b57cec5SDimitry Andric 
readModuleTriple(BitstreamCursor & Stream)3380b57cec5SDimitry Andric static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
3390b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3400b57cec5SDimitry Andric     return std::move(Err);
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   std::string Triple;
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric   // Read all the records for this module.
3470b57cec5SDimitry Andric   while (true) {
3480b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3490b57cec5SDimitry Andric     if (!MaybeEntry)
3500b57cec5SDimitry Andric       return MaybeEntry.takeError();
3510b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
3520b57cec5SDimitry Andric 
3530b57cec5SDimitry Andric     switch (Entry.Kind) {
3540b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
3550b57cec5SDimitry Andric     case BitstreamEntry::Error:
3560b57cec5SDimitry Andric       return error("Malformed block");
3570b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
3580b57cec5SDimitry Andric       return Triple;
3590b57cec5SDimitry Andric     case BitstreamEntry::Record:
3600b57cec5SDimitry Andric       // The interesting case.
3610b57cec5SDimitry Andric       break;
3620b57cec5SDimitry Andric     }
3630b57cec5SDimitry Andric 
3640b57cec5SDimitry Andric     // Read a record.
3650b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3660b57cec5SDimitry Andric     if (!MaybeRecord)
3670b57cec5SDimitry Andric       return MaybeRecord.takeError();
3680b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
3690b57cec5SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
3700b57cec5SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3710b57cec5SDimitry Andric       std::string S;
3720b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
3730b57cec5SDimitry Andric         return error("Invalid record");
3740b57cec5SDimitry Andric       Triple = S;
3750b57cec5SDimitry Andric       break;
3760b57cec5SDimitry Andric     }
3770b57cec5SDimitry Andric     }
3780b57cec5SDimitry Andric     Record.clear();
3790b57cec5SDimitry Andric   }
3800b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
3810b57cec5SDimitry Andric }
3820b57cec5SDimitry Andric 
readTriple(BitstreamCursor & Stream)3830b57cec5SDimitry Andric static Expected<std::string> readTriple(BitstreamCursor &Stream) {
3840b57cec5SDimitry Andric   // We expect a number of well-defined blocks, though we don't necessarily
3850b57cec5SDimitry Andric   // need to understand them all.
3860b57cec5SDimitry Andric   while (true) {
3870b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advance();
3880b57cec5SDimitry Andric     if (!MaybeEntry)
3890b57cec5SDimitry Andric       return MaybeEntry.takeError();
3900b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric     switch (Entry.Kind) {
3930b57cec5SDimitry Andric     case BitstreamEntry::Error:
3940b57cec5SDimitry Andric       return error("Malformed block");
3950b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
3960b57cec5SDimitry Andric       return "";
3970b57cec5SDimitry Andric 
3980b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
3990b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID)
4000b57cec5SDimitry Andric         return readModuleTriple(Stream);
4010b57cec5SDimitry Andric 
4020b57cec5SDimitry Andric       // Ignore other sub-blocks.
4030b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
4040b57cec5SDimitry Andric         return std::move(Err);
4050b57cec5SDimitry Andric       continue;
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric     case BitstreamEntry::Record:
4080b57cec5SDimitry Andric       if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
4090b57cec5SDimitry Andric         continue;
4100b57cec5SDimitry Andric       else
4110b57cec5SDimitry Andric         return Skipped.takeError();
4120b57cec5SDimitry Andric     }
4130b57cec5SDimitry Andric   }
4140b57cec5SDimitry Andric }
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric namespace {
4170b57cec5SDimitry Andric 
4180b57cec5SDimitry Andric class BitcodeReaderBase {
4190b57cec5SDimitry Andric protected:
BitcodeReaderBase(BitstreamCursor Stream,StringRef Strtab)4200b57cec5SDimitry Andric   BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
4210b57cec5SDimitry Andric       : Stream(std::move(Stream)), Strtab(Strtab) {
4220b57cec5SDimitry Andric     this->Stream.setBlockInfo(&BlockInfo);
4230b57cec5SDimitry Andric   }
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric   BitstreamBlockInfo BlockInfo;
4260b57cec5SDimitry Andric   BitstreamCursor Stream;
4270b57cec5SDimitry Andric   StringRef Strtab;
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   /// In version 2 of the bitcode we store names of global values and comdats in
4300b57cec5SDimitry Andric   /// a string table rather than in the VST.
4310b57cec5SDimitry Andric   bool UseStrtab = false;
4320b57cec5SDimitry Andric 
4330b57cec5SDimitry Andric   Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   /// If this module uses a string table, pop the reference to the string table
4360b57cec5SDimitry Andric   /// and return the referenced string and the rest of the record. Otherwise
4370b57cec5SDimitry Andric   /// just return the record itself.
4380b57cec5SDimitry Andric   std::pair<StringRef, ArrayRef<uint64_t>>
4390b57cec5SDimitry Andric   readNameFromStrtab(ArrayRef<uint64_t> Record);
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   bool readBlockInfo();
4420b57cec5SDimitry Andric 
4430b57cec5SDimitry Andric   // Contains an arbitrary and optional string identifying the bitcode producer
4440b57cec5SDimitry Andric   std::string ProducerIdentification;
4450b57cec5SDimitry Andric 
4460b57cec5SDimitry Andric   Error error(const Twine &Message);
4470b57cec5SDimitry Andric };
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric } // end anonymous namespace
4500b57cec5SDimitry Andric 
error(const Twine & Message)4510b57cec5SDimitry Andric Error BitcodeReaderBase::error(const Twine &Message) {
4520b57cec5SDimitry Andric   std::string FullMsg = Message.str();
4530b57cec5SDimitry Andric   if (!ProducerIdentification.empty())
4540b57cec5SDimitry Andric     FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
4550b57cec5SDimitry Andric                LLVM_VERSION_STRING "')";
4560b57cec5SDimitry Andric   return ::error(FullMsg);
4570b57cec5SDimitry Andric }
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric Expected<unsigned>
parseVersionRecord(ArrayRef<uint64_t> Record)4600b57cec5SDimitry Andric BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
4610b57cec5SDimitry Andric   if (Record.empty())
4620b57cec5SDimitry Andric     return error("Invalid record");
4630b57cec5SDimitry Andric   unsigned ModuleVersion = Record[0];
4640b57cec5SDimitry Andric   if (ModuleVersion > 2)
4650b57cec5SDimitry Andric     return error("Invalid value");
4660b57cec5SDimitry Andric   UseStrtab = ModuleVersion >= 2;
4670b57cec5SDimitry Andric   return ModuleVersion;
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric 
4700b57cec5SDimitry Andric std::pair<StringRef, ArrayRef<uint64_t>>
readNameFromStrtab(ArrayRef<uint64_t> Record)4710b57cec5SDimitry Andric BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
4720b57cec5SDimitry Andric   if (!UseStrtab)
4730b57cec5SDimitry Andric     return {"", Record};
4740b57cec5SDimitry Andric   // Invalid reference. Let the caller complain about the record being empty.
4750b57cec5SDimitry Andric   if (Record[0] + Record[1] > Strtab.size())
4760b57cec5SDimitry Andric     return {"", {}};
4770b57cec5SDimitry Andric   return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
4780b57cec5SDimitry Andric }
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric namespace {
4810b57cec5SDimitry Andric 
4820b57cec5SDimitry Andric class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
4830b57cec5SDimitry Andric   LLVMContext &Context;
4840b57cec5SDimitry Andric   Module *TheModule = nullptr;
4850b57cec5SDimitry Andric   // Next offset to start scanning for lazy parsing of function bodies.
4860b57cec5SDimitry Andric   uint64_t NextUnreadBit = 0;
4870b57cec5SDimitry Andric   // Last function offset found in the VST.
4880b57cec5SDimitry Andric   uint64_t LastFunctionBlockBit = 0;
4890b57cec5SDimitry Andric   bool SeenValueSymbolTable = false;
4900b57cec5SDimitry Andric   uint64_t VSTOffset = 0;
4910b57cec5SDimitry Andric 
4920b57cec5SDimitry Andric   std::vector<std::string> SectionTable;
4930b57cec5SDimitry Andric   std::vector<std::string> GCTable;
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   std::vector<Type*> TypeList;
4960b57cec5SDimitry Andric   DenseMap<Function *, FunctionType *> FunctionTypes;
4970b57cec5SDimitry Andric   BitcodeReaderValueList ValueList;
4980b57cec5SDimitry Andric   Optional<MetadataLoader> MDLoader;
4990b57cec5SDimitry Andric   std::vector<Comdat *> ComdatList;
5000b57cec5SDimitry Andric   SmallVector<Instruction *, 64> InstructionList;
5010b57cec5SDimitry Andric 
5020b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
5030b57cec5SDimitry Andric   std::vector<std::pair<GlobalIndirectSymbol *, unsigned>> IndirectSymbolInits;
5040b57cec5SDimitry Andric   std::vector<std::pair<Function *, unsigned>> FunctionPrefixes;
5050b57cec5SDimitry Andric   std::vector<std::pair<Function *, unsigned>> FunctionPrologues;
5060b57cec5SDimitry Andric   std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFns;
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   /// The set of attributes by index.  Index zero in the file is for null, and
5090b57cec5SDimitry Andric   /// is thus not represented here.  As such all indices are off by one.
5100b57cec5SDimitry Andric   std::vector<AttributeList> MAttributes;
5110b57cec5SDimitry Andric 
5120b57cec5SDimitry Andric   /// The set of attribute groups.
5130b57cec5SDimitry Andric   std::map<unsigned, AttributeList> MAttributeGroups;
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric   /// While parsing a function body, this is a list of the basic blocks for the
5160b57cec5SDimitry Andric   /// function.
5170b57cec5SDimitry Andric   std::vector<BasicBlock*> FunctionBBs;
5180b57cec5SDimitry Andric 
5190b57cec5SDimitry Andric   // When reading the module header, this list is populated with functions that
5200b57cec5SDimitry Andric   // have bodies later in the file.
5210b57cec5SDimitry Andric   std::vector<Function*> FunctionsWithBodies;
5220b57cec5SDimitry Andric 
5230b57cec5SDimitry Andric   // When intrinsic functions are encountered which require upgrading they are
5240b57cec5SDimitry Andric   // stored here with their replacement function.
5250b57cec5SDimitry Andric   using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
5260b57cec5SDimitry Andric   UpdatedIntrinsicMap UpgradedIntrinsics;
5270b57cec5SDimitry Andric   // Intrinsics which were remangled because of types rename
5280b57cec5SDimitry Andric   UpdatedIntrinsicMap RemangledIntrinsics;
5290b57cec5SDimitry Andric 
5300b57cec5SDimitry Andric   // Several operations happen after the module header has been read, but
5310b57cec5SDimitry Andric   // before function bodies are processed. This keeps track of whether
5320b57cec5SDimitry Andric   // we've done this yet.
5330b57cec5SDimitry Andric   bool SeenFirstFunctionBody = false;
5340b57cec5SDimitry Andric 
5350b57cec5SDimitry Andric   /// When function bodies are initially scanned, this map contains info about
5360b57cec5SDimitry Andric   /// where to find deferred function body in the stream.
5370b57cec5SDimitry Andric   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
5380b57cec5SDimitry Andric 
5390b57cec5SDimitry Andric   /// When Metadata block is initially scanned when parsing the module, we may
5400b57cec5SDimitry Andric   /// choose to defer parsing of the metadata. This vector contains info about
5410b57cec5SDimitry Andric   /// which Metadata blocks are deferred.
5420b57cec5SDimitry Andric   std::vector<uint64_t> DeferredMetadataInfo;
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric   /// These are basic blocks forward-referenced by block addresses.  They are
5450b57cec5SDimitry Andric   /// inserted lazily into functions when they're loaded.  The basic block ID is
5460b57cec5SDimitry Andric   /// its index into the vector.
5470b57cec5SDimitry Andric   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
5480b57cec5SDimitry Andric   std::deque<Function *> BasicBlockFwdRefQueue;
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   /// Indicates that we are using a new encoding for instruction operands where
5510b57cec5SDimitry Andric   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
5520b57cec5SDimitry Andric   /// instruction number, for a more compact encoding.  Some instruction
5530b57cec5SDimitry Andric   /// operands are not relative to the instruction ID: basic block numbers, and
5540b57cec5SDimitry Andric   /// types. Once the old style function blocks have been phased out, we would
5550b57cec5SDimitry Andric   /// not need this flag.
5560b57cec5SDimitry Andric   bool UseRelativeIDs = false;
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   /// True if all functions will be materialized, negating the need to process
5590b57cec5SDimitry Andric   /// (e.g.) blockaddress forward references.
5600b57cec5SDimitry Andric   bool WillMaterializeAllForwardRefs = false;
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric   bool StripDebugInfo = false;
5630b57cec5SDimitry Andric   TBAAVerifier TBAAVerifyHelper;
5640b57cec5SDimitry Andric 
5650b57cec5SDimitry Andric   std::vector<std::string> BundleTags;
5660b57cec5SDimitry Andric   SmallVector<SyncScope::ID, 8> SSIDs;
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric public:
5690b57cec5SDimitry Andric   BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
5700b57cec5SDimitry Andric                 StringRef ProducerIdentification, LLVMContext &Context);
5710b57cec5SDimitry Andric 
5720b57cec5SDimitry Andric   Error materializeForwardReferencedFunctions();
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric   Error materialize(GlobalValue *GV) override;
5750b57cec5SDimitry Andric   Error materializeModule() override;
5760b57cec5SDimitry Andric   std::vector<StructType *> getIdentifiedStructTypes() const override;
5770b57cec5SDimitry Andric 
5780b57cec5SDimitry Andric   /// Main interface to parsing a bitcode buffer.
5790b57cec5SDimitry Andric   /// \returns true if an error occurred.
5805ffd83dbSDimitry Andric   Error parseBitcodeInto(
5815ffd83dbSDimitry Andric       Module *M, bool ShouldLazyLoadMetadata = false, bool IsImporting = false,
__anonba06ddfc0502(StringRef) 582af732203SDimitry Andric       DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });
5830b57cec5SDimitry Andric 
5840b57cec5SDimitry Andric   static uint64_t decodeSignRotatedValue(uint64_t V);
5850b57cec5SDimitry Andric 
5860b57cec5SDimitry Andric   /// Materialize any deferred Metadata block.
5870b57cec5SDimitry Andric   Error materializeMetadata() override;
5880b57cec5SDimitry Andric 
5890b57cec5SDimitry Andric   void setStripDebugInfo() override;
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric private:
5920b57cec5SDimitry Andric   std::vector<StructType *> IdentifiedStructTypes;
5930b57cec5SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
5940b57cec5SDimitry Andric   StructType *createIdentifiedStructType(LLVMContext &Context);
5950b57cec5SDimitry Andric 
596*5f7ddb14SDimitry Andric   Type *getTypeByID(unsigned ID);
5970b57cec5SDimitry Andric 
getFnValueByID(unsigned ID,Type * Ty)598*5f7ddb14SDimitry Andric   Value *getFnValueByID(unsigned ID, Type *Ty) {
5990b57cec5SDimitry Andric     if (Ty && Ty->isMetadataTy())
6000b57cec5SDimitry Andric       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
601*5f7ddb14SDimitry Andric     return ValueList.getValueFwdRef(ID, Ty);
6020b57cec5SDimitry Andric   }
6030b57cec5SDimitry Andric 
getFnMetadataByID(unsigned ID)6040b57cec5SDimitry Andric   Metadata *getFnMetadataByID(unsigned ID) {
6050b57cec5SDimitry Andric     return MDLoader->getMetadataFwdRefOrLoad(ID);
6060b57cec5SDimitry Andric   }
6070b57cec5SDimitry Andric 
getBasicBlock(unsigned ID) const6080b57cec5SDimitry Andric   BasicBlock *getBasicBlock(unsigned ID) const {
6090b57cec5SDimitry Andric     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
6100b57cec5SDimitry Andric     return FunctionBBs[ID];
6110b57cec5SDimitry Andric   }
6120b57cec5SDimitry Andric 
getAttributes(unsigned i) const6130b57cec5SDimitry Andric   AttributeList getAttributes(unsigned i) const {
6140b57cec5SDimitry Andric     if (i-1 < MAttributes.size())
6150b57cec5SDimitry Andric       return MAttributes[i-1];
6160b57cec5SDimitry Andric     return AttributeList();
6170b57cec5SDimitry Andric   }
6180b57cec5SDimitry Andric 
6190b57cec5SDimitry Andric   /// Read a value/type pair out of the specified record from slot 'Slot'.
6200b57cec5SDimitry Andric   /// Increment Slot past the number of slots used in the record. Return true on
6210b57cec5SDimitry Andric   /// failure.
getValueTypePair(const SmallVectorImpl<uint64_t> & Record,unsigned & Slot,unsigned InstNum,Value * & ResVal)622af732203SDimitry Andric   bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
623*5f7ddb14SDimitry Andric                         unsigned InstNum, Value *&ResVal) {
6240b57cec5SDimitry Andric     if (Slot == Record.size()) return true;
6250b57cec5SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot++];
6260b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
6270b57cec5SDimitry Andric     if (UseRelativeIDs)
6280b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
6290b57cec5SDimitry Andric     if (ValNo < InstNum) {
6300b57cec5SDimitry Andric       // If this is not a forward reference, just return the value we already
6310b57cec5SDimitry Andric       // have.
632*5f7ddb14SDimitry Andric       ResVal = getFnValueByID(ValNo, nullptr);
6330b57cec5SDimitry Andric       return ResVal == nullptr;
6340b57cec5SDimitry Andric     }
6350b57cec5SDimitry Andric     if (Slot == Record.size())
6360b57cec5SDimitry Andric       return true;
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric     unsigned TypeNo = (unsigned)Record[Slot++];
6390b57cec5SDimitry Andric     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
6400b57cec5SDimitry Andric     return ResVal == nullptr;
6410b57cec5SDimitry Andric   }
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
6440b57cec5SDimitry Andric   /// past the number of slots used by the value in the record. Return true if
6450b57cec5SDimitry Andric   /// there is an error.
popValue(const SmallVectorImpl<uint64_t> & Record,unsigned & Slot,unsigned InstNum,Type * Ty,Value * & ResVal)646af732203SDimitry Andric   bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
6470b57cec5SDimitry Andric                 unsigned InstNum, Type *Ty, Value *&ResVal) {
6480b57cec5SDimitry Andric     if (getValue(Record, Slot, InstNum, Ty, ResVal))
6490b57cec5SDimitry Andric       return true;
6500b57cec5SDimitry Andric     // All values currently take a single record slot.
6510b57cec5SDimitry Andric     ++Slot;
6520b57cec5SDimitry Andric     return false;
6530b57cec5SDimitry Andric   }
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric   /// Like popValue, but does not increment the Slot number.
getValue(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty,Value * & ResVal)656af732203SDimitry Andric   bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
6570b57cec5SDimitry Andric                 unsigned InstNum, Type *Ty, Value *&ResVal) {
6580b57cec5SDimitry Andric     ResVal = getValue(Record, Slot, InstNum, Ty);
6590b57cec5SDimitry Andric     return ResVal == nullptr;
6600b57cec5SDimitry Andric   }
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric   /// Version of getValue that returns ResVal directly, or 0 if there is an
6630b57cec5SDimitry Andric   /// error.
getValue(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty)664af732203SDimitry Andric   Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
6650b57cec5SDimitry Andric                   unsigned InstNum, Type *Ty) {
6660b57cec5SDimitry Andric     if (Slot == Record.size()) return nullptr;
6670b57cec5SDimitry Andric     unsigned ValNo = (unsigned)Record[Slot];
6680b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
6690b57cec5SDimitry Andric     if (UseRelativeIDs)
6700b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
6710b57cec5SDimitry Andric     return getFnValueByID(ValNo, Ty);
6720b57cec5SDimitry Andric   }
6730b57cec5SDimitry Andric 
6740b57cec5SDimitry Andric   /// Like getValue, but decodes signed VBRs.
getValueSigned(const SmallVectorImpl<uint64_t> & Record,unsigned Slot,unsigned InstNum,Type * Ty)675af732203SDimitry Andric   Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
6760b57cec5SDimitry Andric                         unsigned InstNum, Type *Ty) {
6770b57cec5SDimitry Andric     if (Slot == Record.size()) return nullptr;
6780b57cec5SDimitry Andric     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
6790b57cec5SDimitry Andric     // Adjust the ValNo, if it was encoded relative to the InstNum.
6800b57cec5SDimitry Andric     if (UseRelativeIDs)
6810b57cec5SDimitry Andric       ValNo = InstNum - ValNo;
6820b57cec5SDimitry Andric     return getFnValueByID(ValNo, Ty);
6830b57cec5SDimitry Andric   }
6840b57cec5SDimitry Andric 
685*5f7ddb14SDimitry Andric   /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
686*5f7ddb14SDimitry Andric   /// corresponding argument's pointee type. Also upgrades intrinsics that now
687*5f7ddb14SDimitry Andric   /// require an elementtype attribute.
688*5f7ddb14SDimitry Andric   void propagateAttributeTypes(CallBase *CB, ArrayRef<Type *> ArgsTys);
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric   /// Converts alignment exponent (i.e. power of two (or zero)) to the
6910b57cec5SDimitry Andric   /// corresponding alignment to use. If alignment is too large, returns
6920b57cec5SDimitry Andric   /// a corresponding error code.
6938bcb0991SDimitry Andric   Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
6940b57cec5SDimitry Andric   Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
6955ffd83dbSDimitry Andric   Error parseModule(
6965ffd83dbSDimitry Andric       uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
__anonba06ddfc0602(StringRef) 6975ffd83dbSDimitry Andric       DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric   Error parseComdatRecord(ArrayRef<uint64_t> Record);
7000b57cec5SDimitry Andric   Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
7010b57cec5SDimitry Andric   Error parseFunctionRecord(ArrayRef<uint64_t> Record);
7020b57cec5SDimitry Andric   Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
7030b57cec5SDimitry Andric                                         ArrayRef<uint64_t> Record);
7040b57cec5SDimitry Andric 
7050b57cec5SDimitry Andric   Error parseAttributeBlock();
7060b57cec5SDimitry Andric   Error parseAttributeGroupBlock();
7070b57cec5SDimitry Andric   Error parseTypeTable();
7080b57cec5SDimitry Andric   Error parseTypeTableBody();
7090b57cec5SDimitry Andric   Error parseOperandBundleTags();
7100b57cec5SDimitry Andric   Error parseSyncScopeNames();
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric   Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
7130b57cec5SDimitry Andric                                 unsigned NameIndex, Triple &TT);
7140b57cec5SDimitry Andric   void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
7150b57cec5SDimitry Andric                                ArrayRef<uint64_t> Record);
7160b57cec5SDimitry Andric   Error parseValueSymbolTable(uint64_t Offset = 0);
7170b57cec5SDimitry Andric   Error parseGlobalValueSymbolTable();
7180b57cec5SDimitry Andric   Error parseConstants();
7190b57cec5SDimitry Andric   Error rememberAndSkipFunctionBodies();
7200b57cec5SDimitry Andric   Error rememberAndSkipFunctionBody();
7210b57cec5SDimitry Andric   /// Save the positions of the Metadata blocks and skip parsing the blocks.
7220b57cec5SDimitry Andric   Error rememberAndSkipMetadata();
7230b57cec5SDimitry Andric   Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
7240b57cec5SDimitry Andric   Error parseFunctionBody(Function *F);
7250b57cec5SDimitry Andric   Error globalCleanup();
7260b57cec5SDimitry Andric   Error resolveGlobalAndIndirectSymbolInits();
7270b57cec5SDimitry Andric   Error parseUseLists();
7280b57cec5SDimitry Andric   Error findFunctionInStream(
7290b57cec5SDimitry Andric       Function *F,
7300b57cec5SDimitry Andric       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
7310b57cec5SDimitry Andric 
7320b57cec5SDimitry Andric   SyncScope::ID getDecodedSyncScopeID(unsigned Val);
7330b57cec5SDimitry Andric };
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric /// Class to manage reading and parsing function summary index bitcode
7360b57cec5SDimitry Andric /// files/sections.
7370b57cec5SDimitry Andric class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
7380b57cec5SDimitry Andric   /// The module index built during parsing.
7390b57cec5SDimitry Andric   ModuleSummaryIndex &TheIndex;
7400b57cec5SDimitry Andric 
7410b57cec5SDimitry Andric   /// Indicates whether we have encountered a global value summary section
7420b57cec5SDimitry Andric   /// yet during parsing.
7430b57cec5SDimitry Andric   bool SeenGlobalValSummary = false;
7440b57cec5SDimitry Andric 
7450b57cec5SDimitry Andric   /// Indicates whether we have already parsed the VST, used for error checking.
7460b57cec5SDimitry Andric   bool SeenValueSymbolTable = false;
7470b57cec5SDimitry Andric 
7480b57cec5SDimitry Andric   /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
7490b57cec5SDimitry Andric   /// Used to enable on-demand parsing of the VST.
7500b57cec5SDimitry Andric   uint64_t VSTOffset = 0;
7510b57cec5SDimitry Andric 
7520b57cec5SDimitry Andric   // Map to save ValueId to ValueInfo association that was recorded in the
7530b57cec5SDimitry Andric   // ValueSymbolTable. It is used after the VST is parsed to convert
7540b57cec5SDimitry Andric   // call graph edges read from the function summary from referencing
7550b57cec5SDimitry Andric   // callees by their ValueId to using the ValueInfo instead, which is how
7560b57cec5SDimitry Andric   // they are recorded in the summary index being built.
7570b57cec5SDimitry Andric   // We save a GUID which refers to the same global as the ValueInfo, but
7580b57cec5SDimitry Andric   // ignoring the linkage, i.e. for values other than local linkage they are
7590b57cec5SDimitry Andric   // identical.
7600b57cec5SDimitry Andric   DenseMap<unsigned, std::pair<ValueInfo, GlobalValue::GUID>>
7610b57cec5SDimitry Andric       ValueIdToValueInfoMap;
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric   /// Map populated during module path string table parsing, from the
7640b57cec5SDimitry Andric   /// module ID to a string reference owned by the index's module
7650b57cec5SDimitry Andric   /// path string table, used to correlate with combined index
7660b57cec5SDimitry Andric   /// summary records.
7670b57cec5SDimitry Andric   DenseMap<uint64_t, StringRef> ModuleIdMap;
7680b57cec5SDimitry Andric 
7690b57cec5SDimitry Andric   /// Original source file name recorded in a bitcode record.
7700b57cec5SDimitry Andric   std::string SourceFileName;
7710b57cec5SDimitry Andric 
7720b57cec5SDimitry Andric   /// The string identifier given to this module by the client, normally the
7730b57cec5SDimitry Andric   /// path to the bitcode file.
7740b57cec5SDimitry Andric   StringRef ModulePath;
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   /// For per-module summary indexes, the unique numerical identifier given to
7770b57cec5SDimitry Andric   /// this module by the client.
7780b57cec5SDimitry Andric   unsigned ModuleId;
7790b57cec5SDimitry Andric 
7800b57cec5SDimitry Andric public:
7810b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
7820b57cec5SDimitry Andric                                   ModuleSummaryIndex &TheIndex,
7830b57cec5SDimitry Andric                                   StringRef ModulePath, unsigned ModuleId);
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric   Error parseModule();
7860b57cec5SDimitry Andric 
7870b57cec5SDimitry Andric private:
7880b57cec5SDimitry Andric   void setValueGUID(uint64_t ValueID, StringRef ValueName,
7890b57cec5SDimitry Andric                     GlobalValue::LinkageTypes Linkage,
7900b57cec5SDimitry Andric                     StringRef SourceFileName);
7910b57cec5SDimitry Andric   Error parseValueSymbolTable(
7920b57cec5SDimitry Andric       uint64_t Offset,
7930b57cec5SDimitry Andric       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
7940b57cec5SDimitry Andric   std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
7950b57cec5SDimitry Andric   std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
7960b57cec5SDimitry Andric                                                     bool IsOldProfileFormat,
7970b57cec5SDimitry Andric                                                     bool HasProfile,
7980b57cec5SDimitry Andric                                                     bool HasRelBF);
7990b57cec5SDimitry Andric   Error parseEntireSummary(unsigned ID);
8000b57cec5SDimitry Andric   Error parseModuleStringTable();
8010b57cec5SDimitry Andric   void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
8020b57cec5SDimitry Andric   void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
8030b57cec5SDimitry Andric                                        TypeIdCompatibleVtableInfo &TypeId);
804af732203SDimitry Andric   std::vector<FunctionSummary::ParamAccess>
805af732203SDimitry Andric   parseParamAccesses(ArrayRef<uint64_t> Record);
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   std::pair<ValueInfo, GlobalValue::GUID>
8080b57cec5SDimitry Andric   getValueInfoFromValueId(unsigned ValueId);
8090b57cec5SDimitry Andric 
8100b57cec5SDimitry Andric   void addThisModule();
8110b57cec5SDimitry Andric   ModuleSummaryIndex::ModuleInfo *getThisModule();
8120b57cec5SDimitry Andric };
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric } // end anonymous namespace
8150b57cec5SDimitry Andric 
errorToErrorCodeAndEmitErrors(LLVMContext & Ctx,Error Err)8160b57cec5SDimitry Andric std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
8170b57cec5SDimitry Andric                                                     Error Err) {
8180b57cec5SDimitry Andric   if (Err) {
8190b57cec5SDimitry Andric     std::error_code EC;
8200b57cec5SDimitry Andric     handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
8210b57cec5SDimitry Andric       EC = EIB.convertToErrorCode();
8220b57cec5SDimitry Andric       Ctx.emitError(EIB.message());
8230b57cec5SDimitry Andric     });
8240b57cec5SDimitry Andric     return EC;
8250b57cec5SDimitry Andric   }
8260b57cec5SDimitry Andric   return std::error_code();
8270b57cec5SDimitry Andric }
8280b57cec5SDimitry Andric 
BitcodeReader(BitstreamCursor Stream,StringRef Strtab,StringRef ProducerIdentification,LLVMContext & Context)8290b57cec5SDimitry Andric BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
8300b57cec5SDimitry Andric                              StringRef ProducerIdentification,
8310b57cec5SDimitry Andric                              LLVMContext &Context)
8320b57cec5SDimitry Andric     : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
8330b57cec5SDimitry Andric       ValueList(Context, Stream.SizeInBytes()) {
8345ffd83dbSDimitry Andric   this->ProducerIdentification = std::string(ProducerIdentification);
8350b57cec5SDimitry Andric }
8360b57cec5SDimitry Andric 
materializeForwardReferencedFunctions()8370b57cec5SDimitry Andric Error BitcodeReader::materializeForwardReferencedFunctions() {
8380b57cec5SDimitry Andric   if (WillMaterializeAllForwardRefs)
8390b57cec5SDimitry Andric     return Error::success();
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric   // Prevent recursion.
8420b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = true;
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric   while (!BasicBlockFwdRefQueue.empty()) {
8450b57cec5SDimitry Andric     Function *F = BasicBlockFwdRefQueue.front();
8460b57cec5SDimitry Andric     BasicBlockFwdRefQueue.pop_front();
8470b57cec5SDimitry Andric     assert(F && "Expected valid function");
8480b57cec5SDimitry Andric     if (!BasicBlockFwdRefs.count(F))
8490b57cec5SDimitry Andric       // Already materialized.
8500b57cec5SDimitry Andric       continue;
8510b57cec5SDimitry Andric 
8520b57cec5SDimitry Andric     // Check for a function that isn't materializable to prevent an infinite
8530b57cec5SDimitry Andric     // loop.  When parsing a blockaddress stored in a global variable, there
8540b57cec5SDimitry Andric     // isn't a trivial way to check if a function will have a body without a
8550b57cec5SDimitry Andric     // linear search through FunctionsWithBodies, so just check it here.
8560b57cec5SDimitry Andric     if (!F->isMaterializable())
8570b57cec5SDimitry Andric       return error("Never resolved function from blockaddress");
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric     // Try to materialize F.
8600b57cec5SDimitry Andric     if (Error Err = materialize(F))
8610b57cec5SDimitry Andric       return Err;
8620b57cec5SDimitry Andric   }
8630b57cec5SDimitry Andric   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric   // Reset state.
8660b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = false;
8670b57cec5SDimitry Andric   return Error::success();
8680b57cec5SDimitry Andric }
8690b57cec5SDimitry Andric 
8700b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8710b57cec5SDimitry Andric //  Helper functions to implement forward reference resolution, etc.
8720b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8730b57cec5SDimitry Andric 
hasImplicitComdat(size_t Val)8740b57cec5SDimitry Andric static bool hasImplicitComdat(size_t Val) {
8750b57cec5SDimitry Andric   switch (Val) {
8760b57cec5SDimitry Andric   default:
8770b57cec5SDimitry Andric     return false;
8780b57cec5SDimitry Andric   case 1:  // Old WeakAnyLinkage
8790b57cec5SDimitry Andric   case 4:  // Old LinkOnceAnyLinkage
8800b57cec5SDimitry Andric   case 10: // Old WeakODRLinkage
8810b57cec5SDimitry Andric   case 11: // Old LinkOnceODRLinkage
8820b57cec5SDimitry Andric     return true;
8830b57cec5SDimitry Andric   }
8840b57cec5SDimitry Andric }
8850b57cec5SDimitry Andric 
getDecodedLinkage(unsigned Val)8860b57cec5SDimitry Andric static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
8870b57cec5SDimitry Andric   switch (Val) {
8880b57cec5SDimitry Andric   default: // Map unknown/new linkages to external
8890b57cec5SDimitry Andric   case 0:
8900b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage;
8910b57cec5SDimitry Andric   case 2:
8920b57cec5SDimitry Andric     return GlobalValue::AppendingLinkage;
8930b57cec5SDimitry Andric   case 3:
8940b57cec5SDimitry Andric     return GlobalValue::InternalLinkage;
8950b57cec5SDimitry Andric   case 5:
8960b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
8970b57cec5SDimitry Andric   case 6:
8980b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
8990b57cec5SDimitry Andric   case 7:
9000b57cec5SDimitry Andric     return GlobalValue::ExternalWeakLinkage;
9010b57cec5SDimitry Andric   case 8:
9020b57cec5SDimitry Andric     return GlobalValue::CommonLinkage;
9030b57cec5SDimitry Andric   case 9:
9040b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage;
9050b57cec5SDimitry Andric   case 12:
9060b57cec5SDimitry Andric     return GlobalValue::AvailableExternallyLinkage;
9070b57cec5SDimitry Andric   case 13:
9080b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
9090b57cec5SDimitry Andric   case 14:
9100b57cec5SDimitry Andric     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
9110b57cec5SDimitry Andric   case 15:
9120b57cec5SDimitry Andric     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
9130b57cec5SDimitry Andric   case 1: // Old value with implicit comdat.
9140b57cec5SDimitry Andric   case 16:
9150b57cec5SDimitry Andric     return GlobalValue::WeakAnyLinkage;
9160b57cec5SDimitry Andric   case 10: // Old value with implicit comdat.
9170b57cec5SDimitry Andric   case 17:
9180b57cec5SDimitry Andric     return GlobalValue::WeakODRLinkage;
9190b57cec5SDimitry Andric   case 4: // Old value with implicit comdat.
9200b57cec5SDimitry Andric   case 18:
9210b57cec5SDimitry Andric     return GlobalValue::LinkOnceAnyLinkage;
9220b57cec5SDimitry Andric   case 11: // Old value with implicit comdat.
9230b57cec5SDimitry Andric   case 19:
9240b57cec5SDimitry Andric     return GlobalValue::LinkOnceODRLinkage;
9250b57cec5SDimitry Andric   }
9260b57cec5SDimitry Andric }
9270b57cec5SDimitry Andric 
getDecodedFFlags(uint64_t RawFlags)9280b57cec5SDimitry Andric static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
9290b57cec5SDimitry Andric   FunctionSummary::FFlags Flags;
9300b57cec5SDimitry Andric   Flags.ReadNone = RawFlags & 0x1;
9310b57cec5SDimitry Andric   Flags.ReadOnly = (RawFlags >> 1) & 0x1;
9320b57cec5SDimitry Andric   Flags.NoRecurse = (RawFlags >> 2) & 0x1;
9330b57cec5SDimitry Andric   Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
9340b57cec5SDimitry Andric   Flags.NoInline = (RawFlags >> 4) & 0x1;
935480093f4SDimitry Andric   Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
9360b57cec5SDimitry Andric   return Flags;
9370b57cec5SDimitry Andric }
9380b57cec5SDimitry Andric 
939*5f7ddb14SDimitry Andric // Decode the flags for GlobalValue in the summary. The bits for each attribute:
940*5f7ddb14SDimitry Andric //
941*5f7ddb14SDimitry Andric // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
942*5f7ddb14SDimitry Andric // visibility: [8, 10).
getDecodedGVSummaryFlags(uint64_t RawFlags,uint64_t Version)9430b57cec5SDimitry Andric static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
9440b57cec5SDimitry Andric                                                             uint64_t Version) {
9450b57cec5SDimitry Andric   // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
9460b57cec5SDimitry Andric   // like getDecodedLinkage() above. Any future change to the linkage enum and
9470b57cec5SDimitry Andric   // to getDecodedLinkage() will need to be taken into account here as above.
9480b57cec5SDimitry Andric   auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
949*5f7ddb14SDimitry Andric   auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
9500b57cec5SDimitry Andric   RawFlags = RawFlags >> 4;
9510b57cec5SDimitry Andric   bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
9520b57cec5SDimitry Andric   // The Live flag wasn't introduced until version 3. For dead stripping
9530b57cec5SDimitry Andric   // to work correctly on earlier versions, we must conservatively treat all
9540b57cec5SDimitry Andric   // values as live.
9550b57cec5SDimitry Andric   bool Live = (RawFlags & 0x2) || Version < 3;
9560b57cec5SDimitry Andric   bool Local = (RawFlags & 0x4);
9570b57cec5SDimitry Andric   bool AutoHide = (RawFlags & 0x8);
9580b57cec5SDimitry Andric 
959*5f7ddb14SDimitry Andric   return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
960*5f7ddb14SDimitry Andric                                      Live, Local, AutoHide);
9610b57cec5SDimitry Andric }
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric // Decode the flags for GlobalVariable in the summary
getDecodedGVarFlags(uint64_t RawFlags)9640b57cec5SDimitry Andric static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
9655ffd83dbSDimitry Andric   return GlobalVarSummary::GVarFlags(
9665ffd83dbSDimitry Andric       (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
9675ffd83dbSDimitry Andric       (RawFlags & 0x4) ? true : false,
9685ffd83dbSDimitry Andric       (GlobalObject::VCallVisibility)(RawFlags >> 3));
9690b57cec5SDimitry Andric }
9700b57cec5SDimitry Andric 
getDecodedVisibility(unsigned Val)9710b57cec5SDimitry Andric static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
9720b57cec5SDimitry Andric   switch (Val) {
9730b57cec5SDimitry Andric   default: // Map unknown visibilities to default.
9740b57cec5SDimitry Andric   case 0: return GlobalValue::DefaultVisibility;
9750b57cec5SDimitry Andric   case 1: return GlobalValue::HiddenVisibility;
9760b57cec5SDimitry Andric   case 2: return GlobalValue::ProtectedVisibility;
9770b57cec5SDimitry Andric   }
9780b57cec5SDimitry Andric }
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric static GlobalValue::DLLStorageClassTypes
getDecodedDLLStorageClass(unsigned Val)9810b57cec5SDimitry Andric getDecodedDLLStorageClass(unsigned Val) {
9820b57cec5SDimitry Andric   switch (Val) {
9830b57cec5SDimitry Andric   default: // Map unknown values to default.
9840b57cec5SDimitry Andric   case 0: return GlobalValue::DefaultStorageClass;
9850b57cec5SDimitry Andric   case 1: return GlobalValue::DLLImportStorageClass;
9860b57cec5SDimitry Andric   case 2: return GlobalValue::DLLExportStorageClass;
9870b57cec5SDimitry Andric   }
9880b57cec5SDimitry Andric }
9890b57cec5SDimitry Andric 
getDecodedDSOLocal(unsigned Val)9900b57cec5SDimitry Andric static bool getDecodedDSOLocal(unsigned Val) {
9910b57cec5SDimitry Andric   switch(Val) {
9920b57cec5SDimitry Andric   default: // Map unknown values to preemptable.
9930b57cec5SDimitry Andric   case 0:  return false;
9940b57cec5SDimitry Andric   case 1:  return true;
9950b57cec5SDimitry Andric   }
9960b57cec5SDimitry Andric }
9970b57cec5SDimitry Andric 
getDecodedThreadLocalMode(unsigned Val)9980b57cec5SDimitry Andric static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
9990b57cec5SDimitry Andric   switch (Val) {
10000b57cec5SDimitry Andric     case 0: return GlobalVariable::NotThreadLocal;
10010b57cec5SDimitry Andric     default: // Map unknown non-zero value to general dynamic.
10020b57cec5SDimitry Andric     case 1: return GlobalVariable::GeneralDynamicTLSModel;
10030b57cec5SDimitry Andric     case 2: return GlobalVariable::LocalDynamicTLSModel;
10040b57cec5SDimitry Andric     case 3: return GlobalVariable::InitialExecTLSModel;
10050b57cec5SDimitry Andric     case 4: return GlobalVariable::LocalExecTLSModel;
10060b57cec5SDimitry Andric   }
10070b57cec5SDimitry Andric }
10080b57cec5SDimitry Andric 
getDecodedUnnamedAddrType(unsigned Val)10090b57cec5SDimitry Andric static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
10100b57cec5SDimitry Andric   switch (Val) {
10110b57cec5SDimitry Andric     default: // Map unknown to UnnamedAddr::None.
10120b57cec5SDimitry Andric     case 0: return GlobalVariable::UnnamedAddr::None;
10130b57cec5SDimitry Andric     case 1: return GlobalVariable::UnnamedAddr::Global;
10140b57cec5SDimitry Andric     case 2: return GlobalVariable::UnnamedAddr::Local;
10150b57cec5SDimitry Andric   }
10160b57cec5SDimitry Andric }
10170b57cec5SDimitry Andric 
getDecodedCastOpcode(unsigned Val)10180b57cec5SDimitry Andric static int getDecodedCastOpcode(unsigned Val) {
10190b57cec5SDimitry Andric   switch (Val) {
10200b57cec5SDimitry Andric   default: return -1;
10210b57cec5SDimitry Andric   case bitc::CAST_TRUNC   : return Instruction::Trunc;
10220b57cec5SDimitry Andric   case bitc::CAST_ZEXT    : return Instruction::ZExt;
10230b57cec5SDimitry Andric   case bitc::CAST_SEXT    : return Instruction::SExt;
10240b57cec5SDimitry Andric   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
10250b57cec5SDimitry Andric   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
10260b57cec5SDimitry Andric   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
10270b57cec5SDimitry Andric   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
10280b57cec5SDimitry Andric   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
10290b57cec5SDimitry Andric   case bitc::CAST_FPEXT   : return Instruction::FPExt;
10300b57cec5SDimitry Andric   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
10310b57cec5SDimitry Andric   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
10320b57cec5SDimitry Andric   case bitc::CAST_BITCAST : return Instruction::BitCast;
10330b57cec5SDimitry Andric   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
10340b57cec5SDimitry Andric   }
10350b57cec5SDimitry Andric }
10360b57cec5SDimitry Andric 
getDecodedUnaryOpcode(unsigned Val,Type * Ty)10370b57cec5SDimitry Andric static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
10380b57cec5SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
10390b57cec5SDimitry Andric   // UnOps are only valid for int/fp or vector of int/fp types
10400b57cec5SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
10410b57cec5SDimitry Andric     return -1;
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   switch (Val) {
10440b57cec5SDimitry Andric   default:
10450b57cec5SDimitry Andric     return -1;
10468bcb0991SDimitry Andric   case bitc::UNOP_FNEG:
10470b57cec5SDimitry Andric     return IsFP ? Instruction::FNeg : -1;
10480b57cec5SDimitry Andric   }
10490b57cec5SDimitry Andric }
10500b57cec5SDimitry Andric 
getDecodedBinaryOpcode(unsigned Val,Type * Ty)10510b57cec5SDimitry Andric static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
10520b57cec5SDimitry Andric   bool IsFP = Ty->isFPOrFPVectorTy();
10530b57cec5SDimitry Andric   // BinOps are only valid for int/fp or vector of int/fp types
10540b57cec5SDimitry Andric   if (!IsFP && !Ty->isIntOrIntVectorTy())
10550b57cec5SDimitry Andric     return -1;
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric   switch (Val) {
10580b57cec5SDimitry Andric   default:
10590b57cec5SDimitry Andric     return -1;
10600b57cec5SDimitry Andric   case bitc::BINOP_ADD:
10610b57cec5SDimitry Andric     return IsFP ? Instruction::FAdd : Instruction::Add;
10620b57cec5SDimitry Andric   case bitc::BINOP_SUB:
10630b57cec5SDimitry Andric     return IsFP ? Instruction::FSub : Instruction::Sub;
10640b57cec5SDimitry Andric   case bitc::BINOP_MUL:
10650b57cec5SDimitry Andric     return IsFP ? Instruction::FMul : Instruction::Mul;
10660b57cec5SDimitry Andric   case bitc::BINOP_UDIV:
10670b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::UDiv;
10680b57cec5SDimitry Andric   case bitc::BINOP_SDIV:
10690b57cec5SDimitry Andric     return IsFP ? Instruction::FDiv : Instruction::SDiv;
10700b57cec5SDimitry Andric   case bitc::BINOP_UREM:
10710b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::URem;
10720b57cec5SDimitry Andric   case bitc::BINOP_SREM:
10730b57cec5SDimitry Andric     return IsFP ? Instruction::FRem : Instruction::SRem;
10740b57cec5SDimitry Andric   case bitc::BINOP_SHL:
10750b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Shl;
10760b57cec5SDimitry Andric   case bitc::BINOP_LSHR:
10770b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::LShr;
10780b57cec5SDimitry Andric   case bitc::BINOP_ASHR:
10790b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::AShr;
10800b57cec5SDimitry Andric   case bitc::BINOP_AND:
10810b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::And;
10820b57cec5SDimitry Andric   case bitc::BINOP_OR:
10830b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Or;
10840b57cec5SDimitry Andric   case bitc::BINOP_XOR:
10850b57cec5SDimitry Andric     return IsFP ? -1 : Instruction::Xor;
10860b57cec5SDimitry Andric   }
10870b57cec5SDimitry Andric }
10880b57cec5SDimitry Andric 
getDecodedRMWOperation(unsigned Val)10890b57cec5SDimitry Andric static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
10900b57cec5SDimitry Andric   switch (Val) {
10910b57cec5SDimitry Andric   default: return AtomicRMWInst::BAD_BINOP;
10920b57cec5SDimitry Andric   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
10930b57cec5SDimitry Andric   case bitc::RMW_ADD: return AtomicRMWInst::Add;
10940b57cec5SDimitry Andric   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
10950b57cec5SDimitry Andric   case bitc::RMW_AND: return AtomicRMWInst::And;
10960b57cec5SDimitry Andric   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
10970b57cec5SDimitry Andric   case bitc::RMW_OR: return AtomicRMWInst::Or;
10980b57cec5SDimitry Andric   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
10990b57cec5SDimitry Andric   case bitc::RMW_MAX: return AtomicRMWInst::Max;
11000b57cec5SDimitry Andric   case bitc::RMW_MIN: return AtomicRMWInst::Min;
11010b57cec5SDimitry Andric   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
11020b57cec5SDimitry Andric   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
11030b57cec5SDimitry Andric   case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
11040b57cec5SDimitry Andric   case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
11050b57cec5SDimitry Andric   }
11060b57cec5SDimitry Andric }
11070b57cec5SDimitry Andric 
getDecodedOrdering(unsigned Val)11080b57cec5SDimitry Andric static AtomicOrdering getDecodedOrdering(unsigned Val) {
11090b57cec5SDimitry Andric   switch (Val) {
11100b57cec5SDimitry Andric   case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
11110b57cec5SDimitry Andric   case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
11120b57cec5SDimitry Andric   case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
11130b57cec5SDimitry Andric   case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
11140b57cec5SDimitry Andric   case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
11150b57cec5SDimitry Andric   case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
11160b57cec5SDimitry Andric   default: // Map unknown orderings to sequentially-consistent.
11170b57cec5SDimitry Andric   case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
11180b57cec5SDimitry Andric   }
11190b57cec5SDimitry Andric }
11200b57cec5SDimitry Andric 
getDecodedComdatSelectionKind(unsigned Val)11210b57cec5SDimitry Andric static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
11220b57cec5SDimitry Andric   switch (Val) {
11230b57cec5SDimitry Andric   default: // Map unknown selection kinds to any.
11240b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_ANY:
11250b57cec5SDimitry Andric     return Comdat::Any;
11260b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
11270b57cec5SDimitry Andric     return Comdat::ExactMatch;
11280b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_LARGEST:
11290b57cec5SDimitry Andric     return Comdat::Largest;
11300b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1131*5f7ddb14SDimitry Andric     return Comdat::NoDeduplicate;
11320b57cec5SDimitry Andric   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
11330b57cec5SDimitry Andric     return Comdat::SameSize;
11340b57cec5SDimitry Andric   }
11350b57cec5SDimitry Andric }
11360b57cec5SDimitry Andric 
getDecodedFastMathFlags(unsigned Val)11370b57cec5SDimitry Andric static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
11380b57cec5SDimitry Andric   FastMathFlags FMF;
11390b57cec5SDimitry Andric   if (0 != (Val & bitc::UnsafeAlgebra))
11400b57cec5SDimitry Andric     FMF.setFast();
11410b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowReassoc))
11420b57cec5SDimitry Andric     FMF.setAllowReassoc();
11430b57cec5SDimitry Andric   if (0 != (Val & bitc::NoNaNs))
11440b57cec5SDimitry Andric     FMF.setNoNaNs();
11450b57cec5SDimitry Andric   if (0 != (Val & bitc::NoInfs))
11460b57cec5SDimitry Andric     FMF.setNoInfs();
11470b57cec5SDimitry Andric   if (0 != (Val & bitc::NoSignedZeros))
11480b57cec5SDimitry Andric     FMF.setNoSignedZeros();
11490b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowReciprocal))
11500b57cec5SDimitry Andric     FMF.setAllowReciprocal();
11510b57cec5SDimitry Andric   if (0 != (Val & bitc::AllowContract))
11520b57cec5SDimitry Andric     FMF.setAllowContract(true);
11530b57cec5SDimitry Andric   if (0 != (Val & bitc::ApproxFunc))
11540b57cec5SDimitry Andric     FMF.setApproxFunc();
11550b57cec5SDimitry Andric   return FMF;
11560b57cec5SDimitry Andric }
11570b57cec5SDimitry Andric 
upgradeDLLImportExportLinkage(GlobalValue * GV,unsigned Val)11580b57cec5SDimitry Andric static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
11590b57cec5SDimitry Andric   switch (Val) {
11600b57cec5SDimitry Andric   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
11610b57cec5SDimitry Andric   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
11620b57cec5SDimitry Andric   }
11630b57cec5SDimitry Andric }
11640b57cec5SDimitry Andric 
getTypeByID(unsigned ID)1165*5f7ddb14SDimitry Andric Type *BitcodeReader::getTypeByID(unsigned ID) {
11660b57cec5SDimitry Andric   // The type table size is always specified correctly.
11670b57cec5SDimitry Andric   if (ID >= TypeList.size())
11680b57cec5SDimitry Andric     return nullptr;
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric   if (Type *Ty = TypeList[ID])
11710b57cec5SDimitry Andric     return Ty;
11720b57cec5SDimitry Andric 
11730b57cec5SDimitry Andric   // If we have a forward reference, the only possible case is when it is to a
11740b57cec5SDimitry Andric   // named struct.  Just create a placeholder for now.
11750b57cec5SDimitry Andric   return TypeList[ID] = createIdentifiedStructType(Context);
11760b57cec5SDimitry Andric }
11770b57cec5SDimitry Andric 
createIdentifiedStructType(LLVMContext & Context,StringRef Name)11780b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
11790b57cec5SDimitry Andric                                                       StringRef Name) {
11800b57cec5SDimitry Andric   auto *Ret = StructType::create(Context, Name);
11810b57cec5SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
11820b57cec5SDimitry Andric   return Ret;
11830b57cec5SDimitry Andric }
11840b57cec5SDimitry Andric 
createIdentifiedStructType(LLVMContext & Context)11850b57cec5SDimitry Andric StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
11860b57cec5SDimitry Andric   auto *Ret = StructType::create(Context);
11870b57cec5SDimitry Andric   IdentifiedStructTypes.push_back(Ret);
11880b57cec5SDimitry Andric   return Ret;
11890b57cec5SDimitry Andric }
11900b57cec5SDimitry Andric 
11910b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
11920b57cec5SDimitry Andric //  Functions for parsing blocks from the bitcode file
11930b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
11940b57cec5SDimitry Andric 
getRawAttributeMask(Attribute::AttrKind Val)11950b57cec5SDimitry Andric static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
11960b57cec5SDimitry Andric   switch (Val) {
11970b57cec5SDimitry Andric   case Attribute::EndAttrKinds:
11985ffd83dbSDimitry Andric   case Attribute::EmptyKey:
11995ffd83dbSDimitry Andric   case Attribute::TombstoneKey:
12000b57cec5SDimitry Andric     llvm_unreachable("Synthetic enumerators which should never get here");
12010b57cec5SDimitry Andric 
12020b57cec5SDimitry Andric   case Attribute::None:            return 0;
12030b57cec5SDimitry Andric   case Attribute::ZExt:            return 1 << 0;
12040b57cec5SDimitry Andric   case Attribute::SExt:            return 1 << 1;
12050b57cec5SDimitry Andric   case Attribute::NoReturn:        return 1 << 2;
12060b57cec5SDimitry Andric   case Attribute::InReg:           return 1 << 3;
12070b57cec5SDimitry Andric   case Attribute::StructRet:       return 1 << 4;
12080b57cec5SDimitry Andric   case Attribute::NoUnwind:        return 1 << 5;
12090b57cec5SDimitry Andric   case Attribute::NoAlias:         return 1 << 6;
12100b57cec5SDimitry Andric   case Attribute::ByVal:           return 1 << 7;
12110b57cec5SDimitry Andric   case Attribute::Nest:            return 1 << 8;
12120b57cec5SDimitry Andric   case Attribute::ReadNone:        return 1 << 9;
12130b57cec5SDimitry Andric   case Attribute::ReadOnly:        return 1 << 10;
12140b57cec5SDimitry Andric   case Attribute::NoInline:        return 1 << 11;
12150b57cec5SDimitry Andric   case Attribute::AlwaysInline:    return 1 << 12;
12160b57cec5SDimitry Andric   case Attribute::OptimizeForSize: return 1 << 13;
12170b57cec5SDimitry Andric   case Attribute::StackProtect:    return 1 << 14;
12180b57cec5SDimitry Andric   case Attribute::StackProtectReq: return 1 << 15;
12190b57cec5SDimitry Andric   case Attribute::Alignment:       return 31 << 16;
12200b57cec5SDimitry Andric   case Attribute::NoCapture:       return 1 << 21;
12210b57cec5SDimitry Andric   case Attribute::NoRedZone:       return 1 << 22;
12220b57cec5SDimitry Andric   case Attribute::NoImplicitFloat: return 1 << 23;
12230b57cec5SDimitry Andric   case Attribute::Naked:           return 1 << 24;
12240b57cec5SDimitry Andric   case Attribute::InlineHint:      return 1 << 25;
12250b57cec5SDimitry Andric   case Attribute::StackAlignment:  return 7 << 26;
12260b57cec5SDimitry Andric   case Attribute::ReturnsTwice:    return 1 << 29;
12270b57cec5SDimitry Andric   case Attribute::UWTable:         return 1 << 30;
12280b57cec5SDimitry Andric   case Attribute::NonLazyBind:     return 1U << 31;
12290b57cec5SDimitry Andric   case Attribute::SanitizeAddress: return 1ULL << 32;
12300b57cec5SDimitry Andric   case Attribute::MinSize:         return 1ULL << 33;
12310b57cec5SDimitry Andric   case Attribute::NoDuplicate:     return 1ULL << 34;
12320b57cec5SDimitry Andric   case Attribute::StackProtectStrong: return 1ULL << 35;
12330b57cec5SDimitry Andric   case Attribute::SanitizeThread:  return 1ULL << 36;
12340b57cec5SDimitry Andric   case Attribute::SanitizeMemory:  return 1ULL << 37;
12350b57cec5SDimitry Andric   case Attribute::NoBuiltin:       return 1ULL << 38;
12360b57cec5SDimitry Andric   case Attribute::Returned:        return 1ULL << 39;
12370b57cec5SDimitry Andric   case Attribute::Cold:            return 1ULL << 40;
12380b57cec5SDimitry Andric   case Attribute::Builtin:         return 1ULL << 41;
12390b57cec5SDimitry Andric   case Attribute::OptimizeNone:    return 1ULL << 42;
12400b57cec5SDimitry Andric   case Attribute::InAlloca:        return 1ULL << 43;
12410b57cec5SDimitry Andric   case Attribute::NonNull:         return 1ULL << 44;
12420b57cec5SDimitry Andric   case Attribute::JumpTable:       return 1ULL << 45;
12430b57cec5SDimitry Andric   case Attribute::Convergent:      return 1ULL << 46;
12440b57cec5SDimitry Andric   case Attribute::SafeStack:       return 1ULL << 47;
12450b57cec5SDimitry Andric   case Attribute::NoRecurse:       return 1ULL << 48;
12460b57cec5SDimitry Andric   case Attribute::InaccessibleMemOnly:         return 1ULL << 49;
12470b57cec5SDimitry Andric   case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
12480b57cec5SDimitry Andric   case Attribute::SwiftSelf:       return 1ULL << 51;
12490b57cec5SDimitry Andric   case Attribute::SwiftError:      return 1ULL << 52;
12500b57cec5SDimitry Andric   case Attribute::WriteOnly:       return 1ULL << 53;
12510b57cec5SDimitry Andric   case Attribute::Speculatable:    return 1ULL << 54;
12520b57cec5SDimitry Andric   case Attribute::StrictFP:        return 1ULL << 55;
12530b57cec5SDimitry Andric   case Attribute::SanitizeHWAddress: return 1ULL << 56;
12540b57cec5SDimitry Andric   case Attribute::NoCfCheck:       return 1ULL << 57;
12550b57cec5SDimitry Andric   case Attribute::OptForFuzzing:   return 1ULL << 58;
12560b57cec5SDimitry Andric   case Attribute::ShadowCallStack: return 1ULL << 59;
12570b57cec5SDimitry Andric   case Attribute::SpeculativeLoadHardening:
12580b57cec5SDimitry Andric     return 1ULL << 60;
12590b57cec5SDimitry Andric   case Attribute::ImmArg:
12600b57cec5SDimitry Andric     return 1ULL << 61;
12610b57cec5SDimitry Andric   case Attribute::WillReturn:
12620b57cec5SDimitry Andric     return 1ULL << 62;
12630b57cec5SDimitry Andric   case Attribute::NoFree:
12640b57cec5SDimitry Andric     return 1ULL << 63;
12655ffd83dbSDimitry Andric   default:
12665ffd83dbSDimitry Andric     // Other attributes are not supported in the raw format,
12675ffd83dbSDimitry Andric     // as we ran out of space.
12685ffd83dbSDimitry Andric     return 0;
12690b57cec5SDimitry Andric   }
12700b57cec5SDimitry Andric   llvm_unreachable("Unsupported attribute type");
12710b57cec5SDimitry Andric }
12720b57cec5SDimitry Andric 
addRawAttributeValue(AttrBuilder & B,uint64_t Val)12730b57cec5SDimitry Andric static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
12740b57cec5SDimitry Andric   if (!Val) return;
12750b57cec5SDimitry Andric 
12760b57cec5SDimitry Andric   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
12770b57cec5SDimitry Andric        I = Attribute::AttrKind(I + 1)) {
12780b57cec5SDimitry Andric     if (uint64_t A = (Val & getRawAttributeMask(I))) {
12790b57cec5SDimitry Andric       if (I == Attribute::Alignment)
12800b57cec5SDimitry Andric         B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
12810b57cec5SDimitry Andric       else if (I == Attribute::StackAlignment)
12820b57cec5SDimitry Andric         B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1283*5f7ddb14SDimitry Andric       else if (Attribute::isTypeAttrKind(I))
1284*5f7ddb14SDimitry Andric         B.addTypeAttr(I, nullptr); // Type will be auto-upgraded.
12850b57cec5SDimitry Andric       else
12860b57cec5SDimitry Andric         B.addAttribute(I);
12870b57cec5SDimitry Andric     }
12880b57cec5SDimitry Andric   }
12890b57cec5SDimitry Andric }
12900b57cec5SDimitry Andric 
12910b57cec5SDimitry Andric /// This fills an AttrBuilder object with the LLVM attributes that have
12920b57cec5SDimitry Andric /// been decoded from the given integer. This function must stay in sync with
12930b57cec5SDimitry Andric /// 'encodeLLVMAttributesForBitcode'.
decodeLLVMAttributesForBitcode(AttrBuilder & B,uint64_t EncodedAttrs)12940b57cec5SDimitry Andric static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
12950b57cec5SDimitry Andric                                            uint64_t EncodedAttrs) {
12960b57cec5SDimitry Andric   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
12970b57cec5SDimitry Andric   // the bits above 31 down by 11 bits.
12980b57cec5SDimitry Andric   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
12990b57cec5SDimitry Andric   assert((!Alignment || isPowerOf2_32(Alignment)) &&
13000b57cec5SDimitry Andric          "Alignment must be a power of two.");
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric   if (Alignment)
13030b57cec5SDimitry Andric     B.addAlignmentAttr(Alignment);
13040b57cec5SDimitry Andric   addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
13050b57cec5SDimitry Andric                           (EncodedAttrs & 0xffff));
13060b57cec5SDimitry Andric }
13070b57cec5SDimitry Andric 
parseAttributeBlock()13080b57cec5SDimitry Andric Error BitcodeReader::parseAttributeBlock() {
13090b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
13100b57cec5SDimitry Andric     return Err;
13110b57cec5SDimitry Andric 
13120b57cec5SDimitry Andric   if (!MAttributes.empty())
13130b57cec5SDimitry Andric     return error("Invalid multiple blocks");
13140b57cec5SDimitry Andric 
13150b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric   SmallVector<AttributeList, 8> Attrs;
13180b57cec5SDimitry Andric 
13190b57cec5SDimitry Andric   // Read all the records.
13200b57cec5SDimitry Andric   while (true) {
13210b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
13220b57cec5SDimitry Andric     if (!MaybeEntry)
13230b57cec5SDimitry Andric       return MaybeEntry.takeError();
13240b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
13250b57cec5SDimitry Andric 
13260b57cec5SDimitry Andric     switch (Entry.Kind) {
13270b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
13280b57cec5SDimitry Andric     case BitstreamEntry::Error:
13290b57cec5SDimitry Andric       return error("Malformed block");
13300b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
13310b57cec5SDimitry Andric       return Error::success();
13320b57cec5SDimitry Andric     case BitstreamEntry::Record:
13330b57cec5SDimitry Andric       // The interesting case.
13340b57cec5SDimitry Andric       break;
13350b57cec5SDimitry Andric     }
13360b57cec5SDimitry Andric 
13370b57cec5SDimitry Andric     // Read a record.
13380b57cec5SDimitry Andric     Record.clear();
13390b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
13400b57cec5SDimitry Andric     if (!MaybeRecord)
13410b57cec5SDimitry Andric       return MaybeRecord.takeError();
13420b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
13430b57cec5SDimitry Andric     default:  // Default behavior: ignore.
13440b57cec5SDimitry Andric       break;
13450b57cec5SDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
13465ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
13470b57cec5SDimitry Andric       if (Record.size() & 1)
13480b57cec5SDimitry Andric         return error("Invalid record");
13490b57cec5SDimitry Andric 
13500b57cec5SDimitry Andric       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
13510b57cec5SDimitry Andric         AttrBuilder B;
13520b57cec5SDimitry Andric         decodeLLVMAttributesForBitcode(B, Record[i+1]);
13530b57cec5SDimitry Andric         Attrs.push_back(AttributeList::get(Context, Record[i], B));
13540b57cec5SDimitry Andric       }
13550b57cec5SDimitry Andric 
13560b57cec5SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
13570b57cec5SDimitry Andric       Attrs.clear();
13580b57cec5SDimitry Andric       break;
13590b57cec5SDimitry Andric     case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
13600b57cec5SDimitry Andric       for (unsigned i = 0, e = Record.size(); i != e; ++i)
13610b57cec5SDimitry Andric         Attrs.push_back(MAttributeGroups[Record[i]]);
13620b57cec5SDimitry Andric 
13630b57cec5SDimitry Andric       MAttributes.push_back(AttributeList::get(Context, Attrs));
13640b57cec5SDimitry Andric       Attrs.clear();
13650b57cec5SDimitry Andric       break;
13660b57cec5SDimitry Andric     }
13670b57cec5SDimitry Andric   }
13680b57cec5SDimitry Andric }
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric // Returns Attribute::None on unrecognized codes.
getAttrFromCode(uint64_t Code)13710b57cec5SDimitry Andric static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
13720b57cec5SDimitry Andric   switch (Code) {
13730b57cec5SDimitry Andric   default:
13740b57cec5SDimitry Andric     return Attribute::None;
13750b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALIGNMENT:
13760b57cec5SDimitry Andric     return Attribute::Alignment;
13770b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALWAYS_INLINE:
13780b57cec5SDimitry Andric     return Attribute::AlwaysInline;
13790b57cec5SDimitry Andric   case bitc::ATTR_KIND_ARGMEMONLY:
13800b57cec5SDimitry Andric     return Attribute::ArgMemOnly;
13810b57cec5SDimitry Andric   case bitc::ATTR_KIND_BUILTIN:
13820b57cec5SDimitry Andric     return Attribute::Builtin;
13830b57cec5SDimitry Andric   case bitc::ATTR_KIND_BY_VAL:
13840b57cec5SDimitry Andric     return Attribute::ByVal;
13850b57cec5SDimitry Andric   case bitc::ATTR_KIND_IN_ALLOCA:
13860b57cec5SDimitry Andric     return Attribute::InAlloca;
13870b57cec5SDimitry Andric   case bitc::ATTR_KIND_COLD:
13880b57cec5SDimitry Andric     return Attribute::Cold;
13890b57cec5SDimitry Andric   case bitc::ATTR_KIND_CONVERGENT:
13900b57cec5SDimitry Andric     return Attribute::Convergent;
1391*5f7ddb14SDimitry Andric   case bitc::ATTR_KIND_ELEMENTTYPE:
1392*5f7ddb14SDimitry Andric     return Attribute::ElementType;
13930b57cec5SDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
13940b57cec5SDimitry Andric     return Attribute::InaccessibleMemOnly;
13950b57cec5SDimitry Andric   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
13960b57cec5SDimitry Andric     return Attribute::InaccessibleMemOrArgMemOnly;
13970b57cec5SDimitry Andric   case bitc::ATTR_KIND_INLINE_HINT:
13980b57cec5SDimitry Andric     return Attribute::InlineHint;
13990b57cec5SDimitry Andric   case bitc::ATTR_KIND_IN_REG:
14000b57cec5SDimitry Andric     return Attribute::InReg;
14010b57cec5SDimitry Andric   case bitc::ATTR_KIND_JUMP_TABLE:
14020b57cec5SDimitry Andric     return Attribute::JumpTable;
14030b57cec5SDimitry Andric   case bitc::ATTR_KIND_MIN_SIZE:
14040b57cec5SDimitry Andric     return Attribute::MinSize;
14050b57cec5SDimitry Andric   case bitc::ATTR_KIND_NAKED:
14060b57cec5SDimitry Andric     return Attribute::Naked;
14070b57cec5SDimitry Andric   case bitc::ATTR_KIND_NEST:
14080b57cec5SDimitry Andric     return Attribute::Nest;
14090b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_ALIAS:
14100b57cec5SDimitry Andric     return Attribute::NoAlias;
14110b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_BUILTIN:
14120b57cec5SDimitry Andric     return Attribute::NoBuiltin;
1413af732203SDimitry Andric   case bitc::ATTR_KIND_NO_CALLBACK:
1414af732203SDimitry Andric     return Attribute::NoCallback;
14150b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_CAPTURE:
14160b57cec5SDimitry Andric     return Attribute::NoCapture;
14170b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_DUPLICATE:
14180b57cec5SDimitry Andric     return Attribute::NoDuplicate;
14190b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOFREE:
14200b57cec5SDimitry Andric     return Attribute::NoFree;
14210b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
14220b57cec5SDimitry Andric     return Attribute::NoImplicitFloat;
14230b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_INLINE:
14240b57cec5SDimitry Andric     return Attribute::NoInline;
14250b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RECURSE:
14260b57cec5SDimitry Andric     return Attribute::NoRecurse;
14275ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NO_MERGE:
14285ffd83dbSDimitry Andric     return Attribute::NoMerge;
14290b57cec5SDimitry Andric   case bitc::ATTR_KIND_NON_LAZY_BIND:
14300b57cec5SDimitry Andric     return Attribute::NonLazyBind;
14310b57cec5SDimitry Andric   case bitc::ATTR_KIND_NON_NULL:
14320b57cec5SDimitry Andric     return Attribute::NonNull;
14330b57cec5SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE:
14340b57cec5SDimitry Andric     return Attribute::Dereferenceable;
14350b57cec5SDimitry Andric   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
14360b57cec5SDimitry Andric     return Attribute::DereferenceableOrNull;
14370b57cec5SDimitry Andric   case bitc::ATTR_KIND_ALLOC_SIZE:
14380b57cec5SDimitry Andric     return Attribute::AllocSize;
14390b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RED_ZONE:
14400b57cec5SDimitry Andric     return Attribute::NoRedZone;
14410b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_RETURN:
14420b57cec5SDimitry Andric     return Attribute::NoReturn;
14430b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOSYNC:
14440b57cec5SDimitry Andric     return Attribute::NoSync;
14450b57cec5SDimitry Andric   case bitc::ATTR_KIND_NOCF_CHECK:
14460b57cec5SDimitry Andric     return Attribute::NoCfCheck;
1447*5f7ddb14SDimitry Andric   case bitc::ATTR_KIND_NO_PROFILE:
1448*5f7ddb14SDimitry Andric     return Attribute::NoProfile;
14490b57cec5SDimitry Andric   case bitc::ATTR_KIND_NO_UNWIND:
14500b57cec5SDimitry Andric     return Attribute::NoUnwind;
1451*5f7ddb14SDimitry Andric   case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
1452*5f7ddb14SDimitry Andric     return Attribute::NoSanitizeCoverage;
14535ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
14545ffd83dbSDimitry Andric     return Attribute::NullPointerIsValid;
14550b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPT_FOR_FUZZING:
14560b57cec5SDimitry Andric     return Attribute::OptForFuzzing;
14570b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
14580b57cec5SDimitry Andric     return Attribute::OptimizeForSize;
14590b57cec5SDimitry Andric   case bitc::ATTR_KIND_OPTIMIZE_NONE:
14600b57cec5SDimitry Andric     return Attribute::OptimizeNone;
14610b57cec5SDimitry Andric   case bitc::ATTR_KIND_READ_NONE:
14620b57cec5SDimitry Andric     return Attribute::ReadNone;
14630b57cec5SDimitry Andric   case bitc::ATTR_KIND_READ_ONLY:
14640b57cec5SDimitry Andric     return Attribute::ReadOnly;
14650b57cec5SDimitry Andric   case bitc::ATTR_KIND_RETURNED:
14660b57cec5SDimitry Andric     return Attribute::Returned;
14670b57cec5SDimitry Andric   case bitc::ATTR_KIND_RETURNS_TWICE:
14680b57cec5SDimitry Andric     return Attribute::ReturnsTwice;
14690b57cec5SDimitry Andric   case bitc::ATTR_KIND_S_EXT:
14700b57cec5SDimitry Andric     return Attribute::SExt;
14710b57cec5SDimitry Andric   case bitc::ATTR_KIND_SPECULATABLE:
14720b57cec5SDimitry Andric     return Attribute::Speculatable;
14730b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_ALIGNMENT:
14740b57cec5SDimitry Andric     return Attribute::StackAlignment;
14750b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT:
14760b57cec5SDimitry Andric     return Attribute::StackProtect;
14770b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
14780b57cec5SDimitry Andric     return Attribute::StackProtectReq;
14790b57cec5SDimitry Andric   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
14800b57cec5SDimitry Andric     return Attribute::StackProtectStrong;
14810b57cec5SDimitry Andric   case bitc::ATTR_KIND_SAFESTACK:
14820b57cec5SDimitry Andric     return Attribute::SafeStack;
14830b57cec5SDimitry Andric   case bitc::ATTR_KIND_SHADOWCALLSTACK:
14840b57cec5SDimitry Andric     return Attribute::ShadowCallStack;
14850b57cec5SDimitry Andric   case bitc::ATTR_KIND_STRICT_FP:
14860b57cec5SDimitry Andric     return Attribute::StrictFP;
14870b57cec5SDimitry Andric   case bitc::ATTR_KIND_STRUCT_RET:
14880b57cec5SDimitry Andric     return Attribute::StructRet;
14890b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
14900b57cec5SDimitry Andric     return Attribute::SanitizeAddress;
14910b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
14920b57cec5SDimitry Andric     return Attribute::SanitizeHWAddress;
14930b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_THREAD:
14940b57cec5SDimitry Andric     return Attribute::SanitizeThread;
14950b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMORY:
14960b57cec5SDimitry Andric     return Attribute::SanitizeMemory;
14970b57cec5SDimitry Andric   case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
14980b57cec5SDimitry Andric     return Attribute::SpeculativeLoadHardening;
14990b57cec5SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ERROR:
15000b57cec5SDimitry Andric     return Attribute::SwiftError;
15010b57cec5SDimitry Andric   case bitc::ATTR_KIND_SWIFT_SELF:
15020b57cec5SDimitry Andric     return Attribute::SwiftSelf;
1503*5f7ddb14SDimitry Andric   case bitc::ATTR_KIND_SWIFT_ASYNC:
1504*5f7ddb14SDimitry Andric     return Attribute::SwiftAsync;
15050b57cec5SDimitry Andric   case bitc::ATTR_KIND_UW_TABLE:
15060b57cec5SDimitry Andric     return Attribute::UWTable;
1507*5f7ddb14SDimitry Andric   case bitc::ATTR_KIND_VSCALE_RANGE:
1508*5f7ddb14SDimitry Andric     return Attribute::VScaleRange;
15090b57cec5SDimitry Andric   case bitc::ATTR_KIND_WILLRETURN:
15100b57cec5SDimitry Andric     return Attribute::WillReturn;
15110b57cec5SDimitry Andric   case bitc::ATTR_KIND_WRITEONLY:
15120b57cec5SDimitry Andric     return Attribute::WriteOnly;
15130b57cec5SDimitry Andric   case bitc::ATTR_KIND_Z_EXT:
15140b57cec5SDimitry Andric     return Attribute::ZExt;
15150b57cec5SDimitry Andric   case bitc::ATTR_KIND_IMMARG:
15160b57cec5SDimitry Andric     return Attribute::ImmArg;
15170b57cec5SDimitry Andric   case bitc::ATTR_KIND_SANITIZE_MEMTAG:
15180b57cec5SDimitry Andric     return Attribute::SanitizeMemTag;
15195ffd83dbSDimitry Andric   case bitc::ATTR_KIND_PREALLOCATED:
15205ffd83dbSDimitry Andric     return Attribute::Preallocated;
15215ffd83dbSDimitry Andric   case bitc::ATTR_KIND_NOUNDEF:
15225ffd83dbSDimitry Andric     return Attribute::NoUndef;
1523af732203SDimitry Andric   case bitc::ATTR_KIND_BYREF:
1524af732203SDimitry Andric     return Attribute::ByRef;
1525af732203SDimitry Andric   case bitc::ATTR_KIND_MUSTPROGRESS:
1526af732203SDimitry Andric     return Attribute::MustProgress;
1527af732203SDimitry Andric   case bitc::ATTR_KIND_HOT:
1528af732203SDimitry Andric     return Attribute::Hot;
15290b57cec5SDimitry Andric   }
15300b57cec5SDimitry Andric }
15310b57cec5SDimitry Andric 
parseAlignmentValue(uint64_t Exponent,MaybeAlign & Alignment)15320b57cec5SDimitry Andric Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
15338bcb0991SDimitry Andric                                          MaybeAlign &Alignment) {
15340b57cec5SDimitry Andric   // Note: Alignment in bitcode files is incremented by 1, so that zero
15350b57cec5SDimitry Andric   // can be used for default alignment.
15360b57cec5SDimitry Andric   if (Exponent > Value::MaxAlignmentExponent + 1)
15370b57cec5SDimitry Andric     return error("Invalid alignment value");
15388bcb0991SDimitry Andric   Alignment = decodeMaybeAlign(Exponent);
15390b57cec5SDimitry Andric   return Error::success();
15400b57cec5SDimitry Andric }
15410b57cec5SDimitry Andric 
parseAttrKind(uint64_t Code,Attribute::AttrKind * Kind)15420b57cec5SDimitry Andric Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
15430b57cec5SDimitry Andric   *Kind = getAttrFromCode(Code);
15440b57cec5SDimitry Andric   if (*Kind == Attribute::None)
15450b57cec5SDimitry Andric     return error("Unknown attribute kind (" + Twine(Code) + ")");
15460b57cec5SDimitry Andric   return Error::success();
15470b57cec5SDimitry Andric }
15480b57cec5SDimitry Andric 
parseAttributeGroupBlock()15490b57cec5SDimitry Andric Error BitcodeReader::parseAttributeGroupBlock() {
15500b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
15510b57cec5SDimitry Andric     return Err;
15520b57cec5SDimitry Andric 
15530b57cec5SDimitry Andric   if (!MAttributeGroups.empty())
15540b57cec5SDimitry Andric     return error("Invalid multiple blocks");
15550b57cec5SDimitry Andric 
15560b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric   // Read all the records.
15590b57cec5SDimitry Andric   while (true) {
15600b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
15610b57cec5SDimitry Andric     if (!MaybeEntry)
15620b57cec5SDimitry Andric       return MaybeEntry.takeError();
15630b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
15640b57cec5SDimitry Andric 
15650b57cec5SDimitry Andric     switch (Entry.Kind) {
15660b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
15670b57cec5SDimitry Andric     case BitstreamEntry::Error:
15680b57cec5SDimitry Andric       return error("Malformed block");
15690b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
15700b57cec5SDimitry Andric       return Error::success();
15710b57cec5SDimitry Andric     case BitstreamEntry::Record:
15720b57cec5SDimitry Andric       // The interesting case.
15730b57cec5SDimitry Andric       break;
15740b57cec5SDimitry Andric     }
15750b57cec5SDimitry Andric 
15760b57cec5SDimitry Andric     // Read a record.
15770b57cec5SDimitry Andric     Record.clear();
15780b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
15790b57cec5SDimitry Andric     if (!MaybeRecord)
15800b57cec5SDimitry Andric       return MaybeRecord.takeError();
15810b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
15820b57cec5SDimitry Andric     default:  // Default behavior: ignore.
15830b57cec5SDimitry Andric       break;
15840b57cec5SDimitry Andric     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
15850b57cec5SDimitry Andric       if (Record.size() < 3)
15860b57cec5SDimitry Andric         return error("Invalid record");
15870b57cec5SDimitry Andric 
15880b57cec5SDimitry Andric       uint64_t GrpID = Record[0];
15890b57cec5SDimitry Andric       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric       AttrBuilder B;
15920b57cec5SDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
15930b57cec5SDimitry Andric         if (Record[i] == 0) {        // Enum attribute
15940b57cec5SDimitry Andric           Attribute::AttrKind Kind;
15950b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
15960b57cec5SDimitry Andric             return Err;
15970b57cec5SDimitry Andric 
15980b57cec5SDimitry Andric           // Upgrade old-style byval attribute to one with a type, even if it's
15990b57cec5SDimitry Andric           // nullptr. We will have to insert the real type when we associate
16000b57cec5SDimitry Andric           // this AttributeList with a function.
16010b57cec5SDimitry Andric           if (Kind == Attribute::ByVal)
16020b57cec5SDimitry Andric             B.addByValAttr(nullptr);
1603af732203SDimitry Andric           else if (Kind == Attribute::StructRet)
1604af732203SDimitry Andric             B.addStructRetAttr(nullptr);
1605*5f7ddb14SDimitry Andric           else if (Kind == Attribute::InAlloca)
1606*5f7ddb14SDimitry Andric             B.addInAllocaAttr(nullptr);
1607*5f7ddb14SDimitry Andric           else if (Attribute::isEnumAttrKind(Kind))
16080b57cec5SDimitry Andric             B.addAttribute(Kind);
1609*5f7ddb14SDimitry Andric           else
1610*5f7ddb14SDimitry Andric             return error("Not an enum attribute");
16110b57cec5SDimitry Andric         } else if (Record[i] == 1) { // Integer attribute
16120b57cec5SDimitry Andric           Attribute::AttrKind Kind;
16130b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
16140b57cec5SDimitry Andric             return Err;
1615*5f7ddb14SDimitry Andric           if (!Attribute::isIntAttrKind(Kind))
1616*5f7ddb14SDimitry Andric             return error("Not an int attribute");
16170b57cec5SDimitry Andric           if (Kind == Attribute::Alignment)
16180b57cec5SDimitry Andric             B.addAlignmentAttr(Record[++i]);
16190b57cec5SDimitry Andric           else if (Kind == Attribute::StackAlignment)
16200b57cec5SDimitry Andric             B.addStackAlignmentAttr(Record[++i]);
16210b57cec5SDimitry Andric           else if (Kind == Attribute::Dereferenceable)
16220b57cec5SDimitry Andric             B.addDereferenceableAttr(Record[++i]);
16230b57cec5SDimitry Andric           else if (Kind == Attribute::DereferenceableOrNull)
16240b57cec5SDimitry Andric             B.addDereferenceableOrNullAttr(Record[++i]);
16250b57cec5SDimitry Andric           else if (Kind == Attribute::AllocSize)
16260b57cec5SDimitry Andric             B.addAllocSizeAttrFromRawRepr(Record[++i]);
1627*5f7ddb14SDimitry Andric           else if (Kind == Attribute::VScaleRange)
1628*5f7ddb14SDimitry Andric             B.addVScaleRangeAttrFromRawRepr(Record[++i]);
16290b57cec5SDimitry Andric         } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
16300b57cec5SDimitry Andric           bool HasValue = (Record[i++] == 4);
16310b57cec5SDimitry Andric           SmallString<64> KindStr;
16320b57cec5SDimitry Andric           SmallString<64> ValStr;
16330b57cec5SDimitry Andric 
16340b57cec5SDimitry Andric           while (Record[i] != 0 && i != e)
16350b57cec5SDimitry Andric             KindStr += Record[i++];
16360b57cec5SDimitry Andric           assert(Record[i] == 0 && "Kind string not null terminated");
16370b57cec5SDimitry Andric 
16380b57cec5SDimitry Andric           if (HasValue) {
16390b57cec5SDimitry Andric             // Has a value associated with it.
16400b57cec5SDimitry Andric             ++i; // Skip the '0' that terminates the "kind" string.
16410b57cec5SDimitry Andric             while (Record[i] != 0 && i != e)
16420b57cec5SDimitry Andric               ValStr += Record[i++];
16430b57cec5SDimitry Andric             assert(Record[i] == 0 && "Value string not null terminated");
16440b57cec5SDimitry Andric           }
16450b57cec5SDimitry Andric 
16460b57cec5SDimitry Andric           B.addAttribute(KindStr.str(), ValStr.str());
16470b57cec5SDimitry Andric         } else {
16480b57cec5SDimitry Andric           assert((Record[i] == 5 || Record[i] == 6) &&
16490b57cec5SDimitry Andric                  "Invalid attribute group entry");
16500b57cec5SDimitry Andric           bool HasType = Record[i] == 6;
16510b57cec5SDimitry Andric           Attribute::AttrKind Kind;
16520b57cec5SDimitry Andric           if (Error Err = parseAttrKind(Record[++i], &Kind))
16530b57cec5SDimitry Andric             return Err;
1654*5f7ddb14SDimitry Andric           if (!Attribute::isTypeAttrKind(Kind))
1655*5f7ddb14SDimitry Andric             return error("Not a type attribute");
1656*5f7ddb14SDimitry Andric 
1657*5f7ddb14SDimitry Andric           B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
16580b57cec5SDimitry Andric         }
16590b57cec5SDimitry Andric       }
16600b57cec5SDimitry Andric 
16615ffd83dbSDimitry Andric       UpgradeAttributes(B);
16620b57cec5SDimitry Andric       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
16630b57cec5SDimitry Andric       break;
16640b57cec5SDimitry Andric     }
16650b57cec5SDimitry Andric     }
16660b57cec5SDimitry Andric   }
16670b57cec5SDimitry Andric }
16680b57cec5SDimitry Andric 
parseTypeTable()16690b57cec5SDimitry Andric Error BitcodeReader::parseTypeTable() {
16700b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
16710b57cec5SDimitry Andric     return Err;
16720b57cec5SDimitry Andric 
16730b57cec5SDimitry Andric   return parseTypeTableBody();
16740b57cec5SDimitry Andric }
16750b57cec5SDimitry Andric 
parseTypeTableBody()16760b57cec5SDimitry Andric Error BitcodeReader::parseTypeTableBody() {
16770b57cec5SDimitry Andric   if (!TypeList.empty())
16780b57cec5SDimitry Andric     return error("Invalid multiple blocks");
16790b57cec5SDimitry Andric 
16800b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
16810b57cec5SDimitry Andric   unsigned NumRecords = 0;
16820b57cec5SDimitry Andric 
16830b57cec5SDimitry Andric   SmallString<64> TypeName;
16840b57cec5SDimitry Andric 
16850b57cec5SDimitry Andric   // Read all the records for this type table.
16860b57cec5SDimitry Andric   while (true) {
16870b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
16880b57cec5SDimitry Andric     if (!MaybeEntry)
16890b57cec5SDimitry Andric       return MaybeEntry.takeError();
16900b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric     switch (Entry.Kind) {
16930b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
16940b57cec5SDimitry Andric     case BitstreamEntry::Error:
16950b57cec5SDimitry Andric       return error("Malformed block");
16960b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
16970b57cec5SDimitry Andric       if (NumRecords != TypeList.size())
16980b57cec5SDimitry Andric         return error("Malformed block");
16990b57cec5SDimitry Andric       return Error::success();
17000b57cec5SDimitry Andric     case BitstreamEntry::Record:
17010b57cec5SDimitry Andric       // The interesting case.
17020b57cec5SDimitry Andric       break;
17030b57cec5SDimitry Andric     }
17040b57cec5SDimitry Andric 
17050b57cec5SDimitry Andric     // Read a record.
17060b57cec5SDimitry Andric     Record.clear();
17070b57cec5SDimitry Andric     Type *ResultTy = nullptr;
17080b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
17090b57cec5SDimitry Andric     if (!MaybeRecord)
17100b57cec5SDimitry Andric       return MaybeRecord.takeError();
17110b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
17120b57cec5SDimitry Andric     default:
17130b57cec5SDimitry Andric       return error("Invalid value");
17140b57cec5SDimitry Andric     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
17150b57cec5SDimitry Andric       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
17160b57cec5SDimitry Andric       // type list.  This allows us to reserve space.
1717af732203SDimitry Andric       if (Record.empty())
17180b57cec5SDimitry Andric         return error("Invalid record");
17190b57cec5SDimitry Andric       TypeList.resize(Record[0]);
17200b57cec5SDimitry Andric       continue;
17210b57cec5SDimitry Andric     case bitc::TYPE_CODE_VOID:      // VOID
17220b57cec5SDimitry Andric       ResultTy = Type::getVoidTy(Context);
17230b57cec5SDimitry Andric       break;
17240b57cec5SDimitry Andric     case bitc::TYPE_CODE_HALF:     // HALF
17250b57cec5SDimitry Andric       ResultTy = Type::getHalfTy(Context);
17260b57cec5SDimitry Andric       break;
17275ffd83dbSDimitry Andric     case bitc::TYPE_CODE_BFLOAT:    // BFLOAT
17285ffd83dbSDimitry Andric       ResultTy = Type::getBFloatTy(Context);
17295ffd83dbSDimitry Andric       break;
17300b57cec5SDimitry Andric     case bitc::TYPE_CODE_FLOAT:     // FLOAT
17310b57cec5SDimitry Andric       ResultTy = Type::getFloatTy(Context);
17320b57cec5SDimitry Andric       break;
17330b57cec5SDimitry Andric     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
17340b57cec5SDimitry Andric       ResultTy = Type::getDoubleTy(Context);
17350b57cec5SDimitry Andric       break;
17360b57cec5SDimitry Andric     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
17370b57cec5SDimitry Andric       ResultTy = Type::getX86_FP80Ty(Context);
17380b57cec5SDimitry Andric       break;
17390b57cec5SDimitry Andric     case bitc::TYPE_CODE_FP128:     // FP128
17400b57cec5SDimitry Andric       ResultTy = Type::getFP128Ty(Context);
17410b57cec5SDimitry Andric       break;
17420b57cec5SDimitry Andric     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
17430b57cec5SDimitry Andric       ResultTy = Type::getPPC_FP128Ty(Context);
17440b57cec5SDimitry Andric       break;
17450b57cec5SDimitry Andric     case bitc::TYPE_CODE_LABEL:     // LABEL
17460b57cec5SDimitry Andric       ResultTy = Type::getLabelTy(Context);
17470b57cec5SDimitry Andric       break;
17480b57cec5SDimitry Andric     case bitc::TYPE_CODE_METADATA:  // METADATA
17490b57cec5SDimitry Andric       ResultTy = Type::getMetadataTy(Context);
17500b57cec5SDimitry Andric       break;
17510b57cec5SDimitry Andric     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
17520b57cec5SDimitry Andric       ResultTy = Type::getX86_MMXTy(Context);
17530b57cec5SDimitry Andric       break;
1754af732203SDimitry Andric     case bitc::TYPE_CODE_X86_AMX:   // X86_AMX
1755af732203SDimitry Andric       ResultTy = Type::getX86_AMXTy(Context);
1756af732203SDimitry Andric       break;
17570b57cec5SDimitry Andric     case bitc::TYPE_CODE_TOKEN:     // TOKEN
17580b57cec5SDimitry Andric       ResultTy = Type::getTokenTy(Context);
17590b57cec5SDimitry Andric       break;
17600b57cec5SDimitry Andric     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1761af732203SDimitry Andric       if (Record.empty())
17620b57cec5SDimitry Andric         return error("Invalid record");
17630b57cec5SDimitry Andric 
17640b57cec5SDimitry Andric       uint64_t NumBits = Record[0];
17650b57cec5SDimitry Andric       if (NumBits < IntegerType::MIN_INT_BITS ||
17660b57cec5SDimitry Andric           NumBits > IntegerType::MAX_INT_BITS)
17670b57cec5SDimitry Andric         return error("Bitwidth for integer type out of range");
17680b57cec5SDimitry Andric       ResultTy = IntegerType::get(Context, NumBits);
17690b57cec5SDimitry Andric       break;
17700b57cec5SDimitry Andric     }
17710b57cec5SDimitry Andric     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
17720b57cec5SDimitry Andric                                     //          [pointee type, address space]
1773af732203SDimitry Andric       if (Record.empty())
17740b57cec5SDimitry Andric         return error("Invalid record");
17750b57cec5SDimitry Andric       unsigned AddressSpace = 0;
17760b57cec5SDimitry Andric       if (Record.size() == 2)
17770b57cec5SDimitry Andric         AddressSpace = Record[1];
17780b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[0]);
17790b57cec5SDimitry Andric       if (!ResultTy ||
17800b57cec5SDimitry Andric           !PointerType::isValidElementType(ResultTy))
17810b57cec5SDimitry Andric         return error("Invalid type");
17820b57cec5SDimitry Andric       ResultTy = PointerType::get(ResultTy, AddressSpace);
17830b57cec5SDimitry Andric       break;
17840b57cec5SDimitry Andric     }
1785*5f7ddb14SDimitry Andric     case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
1786*5f7ddb14SDimitry Andric       if (Record.size() != 1)
1787*5f7ddb14SDimitry Andric         return error("Invalid record");
1788*5f7ddb14SDimitry Andric       unsigned AddressSpace = Record[0];
1789*5f7ddb14SDimitry Andric       ResultTy = PointerType::get(Context, AddressSpace);
1790*5f7ddb14SDimitry Andric       break;
1791*5f7ddb14SDimitry Andric     }
17920b57cec5SDimitry Andric     case bitc::TYPE_CODE_FUNCTION_OLD: {
17935ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
17940b57cec5SDimitry Andric       // FUNCTION: [vararg, attrid, retty, paramty x N]
17950b57cec5SDimitry Andric       if (Record.size() < 3)
17960b57cec5SDimitry Andric         return error("Invalid record");
17970b57cec5SDimitry Andric       SmallVector<Type*, 8> ArgTys;
17980b57cec5SDimitry Andric       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
17990b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
18000b57cec5SDimitry Andric           ArgTys.push_back(T);
18010b57cec5SDimitry Andric         else
18020b57cec5SDimitry Andric           break;
18030b57cec5SDimitry Andric       }
18040b57cec5SDimitry Andric 
18050b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[2]);
18060b57cec5SDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-3)
18070b57cec5SDimitry Andric         return error("Invalid type");
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
18100b57cec5SDimitry Andric       break;
18110b57cec5SDimitry Andric     }
18120b57cec5SDimitry Andric     case bitc::TYPE_CODE_FUNCTION: {
18130b57cec5SDimitry Andric       // FUNCTION: [vararg, retty, paramty x N]
18140b57cec5SDimitry Andric       if (Record.size() < 2)
18150b57cec5SDimitry Andric         return error("Invalid record");
18160b57cec5SDimitry Andric       SmallVector<Type*, 8> ArgTys;
18170b57cec5SDimitry Andric       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
18180b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i])) {
18190b57cec5SDimitry Andric           if (!FunctionType::isValidArgumentType(T))
18200b57cec5SDimitry Andric             return error("Invalid function argument type");
18210b57cec5SDimitry Andric           ArgTys.push_back(T);
18220b57cec5SDimitry Andric         }
18230b57cec5SDimitry Andric         else
18240b57cec5SDimitry Andric           break;
18250b57cec5SDimitry Andric       }
18260b57cec5SDimitry Andric 
18270b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
18280b57cec5SDimitry Andric       if (!ResultTy || ArgTys.size() < Record.size()-2)
18290b57cec5SDimitry Andric         return error("Invalid type");
18300b57cec5SDimitry Andric 
18310b57cec5SDimitry Andric       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
18320b57cec5SDimitry Andric       break;
18330b57cec5SDimitry Andric     }
18340b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1835af732203SDimitry Andric       if (Record.empty())
18360b57cec5SDimitry Andric         return error("Invalid record");
18370b57cec5SDimitry Andric       SmallVector<Type*, 8> EltTys;
18380b57cec5SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
18390b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
18400b57cec5SDimitry Andric           EltTys.push_back(T);
18410b57cec5SDimitry Andric         else
18420b57cec5SDimitry Andric           break;
18430b57cec5SDimitry Andric       }
18440b57cec5SDimitry Andric       if (EltTys.size() != Record.size()-1)
18450b57cec5SDimitry Andric         return error("Invalid type");
18460b57cec5SDimitry Andric       ResultTy = StructType::get(Context, EltTys, Record[0]);
18470b57cec5SDimitry Andric       break;
18480b57cec5SDimitry Andric     }
18490b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
18500b57cec5SDimitry Andric       if (convertToString(Record, 0, TypeName))
18510b57cec5SDimitry Andric         return error("Invalid record");
18520b57cec5SDimitry Andric       continue;
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1855af732203SDimitry Andric       if (Record.empty())
18560b57cec5SDimitry Andric         return error("Invalid record");
18570b57cec5SDimitry Andric 
18580b57cec5SDimitry Andric       if (NumRecords >= TypeList.size())
18590b57cec5SDimitry Andric         return error("Invalid TYPE table");
18600b57cec5SDimitry Andric 
18610b57cec5SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
18620b57cec5SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
18630b57cec5SDimitry Andric       if (Res) {
18640b57cec5SDimitry Andric         Res->setName(TypeName);
18650b57cec5SDimitry Andric         TypeList[NumRecords] = nullptr;
18660b57cec5SDimitry Andric       } else  // Otherwise, create a new struct.
18670b57cec5SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
18680b57cec5SDimitry Andric       TypeName.clear();
18690b57cec5SDimitry Andric 
18700b57cec5SDimitry Andric       SmallVector<Type*, 8> EltTys;
18710b57cec5SDimitry Andric       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
18720b57cec5SDimitry Andric         if (Type *T = getTypeByID(Record[i]))
18730b57cec5SDimitry Andric           EltTys.push_back(T);
18740b57cec5SDimitry Andric         else
18750b57cec5SDimitry Andric           break;
18760b57cec5SDimitry Andric       }
18770b57cec5SDimitry Andric       if (EltTys.size() != Record.size()-1)
18780b57cec5SDimitry Andric         return error("Invalid record");
18790b57cec5SDimitry Andric       Res->setBody(EltTys, Record[0]);
18800b57cec5SDimitry Andric       ResultTy = Res;
18810b57cec5SDimitry Andric       break;
18820b57cec5SDimitry Andric     }
18830b57cec5SDimitry Andric     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
18840b57cec5SDimitry Andric       if (Record.size() != 1)
18850b57cec5SDimitry Andric         return error("Invalid record");
18860b57cec5SDimitry Andric 
18870b57cec5SDimitry Andric       if (NumRecords >= TypeList.size())
18880b57cec5SDimitry Andric         return error("Invalid TYPE table");
18890b57cec5SDimitry Andric 
18900b57cec5SDimitry Andric       // Check to see if this was forward referenced, if so fill in the temp.
18910b57cec5SDimitry Andric       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
18920b57cec5SDimitry Andric       if (Res) {
18930b57cec5SDimitry Andric         Res->setName(TypeName);
18940b57cec5SDimitry Andric         TypeList[NumRecords] = nullptr;
18950b57cec5SDimitry Andric       } else  // Otherwise, create a new struct with no body.
18960b57cec5SDimitry Andric         Res = createIdentifiedStructType(Context, TypeName);
18970b57cec5SDimitry Andric       TypeName.clear();
18980b57cec5SDimitry Andric       ResultTy = Res;
18990b57cec5SDimitry Andric       break;
19000b57cec5SDimitry Andric     }
19010b57cec5SDimitry Andric     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
19020b57cec5SDimitry Andric       if (Record.size() < 2)
19030b57cec5SDimitry Andric         return error("Invalid record");
19040b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
19050b57cec5SDimitry Andric       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
19060b57cec5SDimitry Andric         return error("Invalid type");
19070b57cec5SDimitry Andric       ResultTy = ArrayType::get(ResultTy, Record[0]);
19080b57cec5SDimitry Andric       break;
19090b57cec5SDimitry Andric     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty] or
19100b57cec5SDimitry Andric                                     //         [numelts, eltty, scalable]
19110b57cec5SDimitry Andric       if (Record.size() < 2)
19120b57cec5SDimitry Andric         return error("Invalid record");
19130b57cec5SDimitry Andric       if (Record[0] == 0)
19140b57cec5SDimitry Andric         return error("Invalid vector length");
19150b57cec5SDimitry Andric       ResultTy = getTypeByID(Record[1]);
19160b57cec5SDimitry Andric       if (!ResultTy || !StructType::isValidElementType(ResultTy))
19170b57cec5SDimitry Andric         return error("Invalid type");
19180b57cec5SDimitry Andric       bool Scalable = Record.size() > 2 ? Record[2] : false;
19190b57cec5SDimitry Andric       ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
19200b57cec5SDimitry Andric       break;
19210b57cec5SDimitry Andric     }
19220b57cec5SDimitry Andric 
19230b57cec5SDimitry Andric     if (NumRecords >= TypeList.size())
19240b57cec5SDimitry Andric       return error("Invalid TYPE table");
19250b57cec5SDimitry Andric     if (TypeList[NumRecords])
19260b57cec5SDimitry Andric       return error(
19270b57cec5SDimitry Andric           "Invalid TYPE table: Only named structs can be forward referenced");
19280b57cec5SDimitry Andric     assert(ResultTy && "Didn't read a type?");
19290b57cec5SDimitry Andric     TypeList[NumRecords++] = ResultTy;
19300b57cec5SDimitry Andric   }
19310b57cec5SDimitry Andric }
19320b57cec5SDimitry Andric 
parseOperandBundleTags()19330b57cec5SDimitry Andric Error BitcodeReader::parseOperandBundleTags() {
19340b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
19350b57cec5SDimitry Andric     return Err;
19360b57cec5SDimitry Andric 
19370b57cec5SDimitry Andric   if (!BundleTags.empty())
19380b57cec5SDimitry Andric     return error("Invalid multiple blocks");
19390b57cec5SDimitry Andric 
19400b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
19410b57cec5SDimitry Andric 
19420b57cec5SDimitry Andric   while (true) {
19430b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
19440b57cec5SDimitry Andric     if (!MaybeEntry)
19450b57cec5SDimitry Andric       return MaybeEntry.takeError();
19460b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
19470b57cec5SDimitry Andric 
19480b57cec5SDimitry Andric     switch (Entry.Kind) {
19490b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
19500b57cec5SDimitry Andric     case BitstreamEntry::Error:
19510b57cec5SDimitry Andric       return error("Malformed block");
19520b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
19530b57cec5SDimitry Andric       return Error::success();
19540b57cec5SDimitry Andric     case BitstreamEntry::Record:
19550b57cec5SDimitry Andric       // The interesting case.
19560b57cec5SDimitry Andric       break;
19570b57cec5SDimitry Andric     }
19580b57cec5SDimitry Andric 
19590b57cec5SDimitry Andric     // Tags are implicitly mapped to integers by their order.
19600b57cec5SDimitry Andric 
19610b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
19620b57cec5SDimitry Andric     if (!MaybeRecord)
19630b57cec5SDimitry Andric       return MaybeRecord.takeError();
19640b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
19650b57cec5SDimitry Andric       return error("Invalid record");
19660b57cec5SDimitry Andric 
19670b57cec5SDimitry Andric     // OPERAND_BUNDLE_TAG: [strchr x N]
19680b57cec5SDimitry Andric     BundleTags.emplace_back();
19690b57cec5SDimitry Andric     if (convertToString(Record, 0, BundleTags.back()))
19700b57cec5SDimitry Andric       return error("Invalid record");
19710b57cec5SDimitry Andric     Record.clear();
19720b57cec5SDimitry Andric   }
19730b57cec5SDimitry Andric }
19740b57cec5SDimitry Andric 
parseSyncScopeNames()19750b57cec5SDimitry Andric Error BitcodeReader::parseSyncScopeNames() {
19760b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
19770b57cec5SDimitry Andric     return Err;
19780b57cec5SDimitry Andric 
19790b57cec5SDimitry Andric   if (!SSIDs.empty())
19800b57cec5SDimitry Andric     return error("Invalid multiple synchronization scope names blocks");
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
19830b57cec5SDimitry Andric   while (true) {
19840b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
19850b57cec5SDimitry Andric     if (!MaybeEntry)
19860b57cec5SDimitry Andric       return MaybeEntry.takeError();
19870b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
19880b57cec5SDimitry Andric 
19890b57cec5SDimitry Andric     switch (Entry.Kind) {
19900b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
19910b57cec5SDimitry Andric     case BitstreamEntry::Error:
19920b57cec5SDimitry Andric       return error("Malformed block");
19930b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
19940b57cec5SDimitry Andric       if (SSIDs.empty())
19950b57cec5SDimitry Andric         return error("Invalid empty synchronization scope names block");
19960b57cec5SDimitry Andric       return Error::success();
19970b57cec5SDimitry Andric     case BitstreamEntry::Record:
19980b57cec5SDimitry Andric       // The interesting case.
19990b57cec5SDimitry Andric       break;
20000b57cec5SDimitry Andric     }
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric     // Synchronization scope names are implicitly mapped to synchronization
20030b57cec5SDimitry Andric     // scope IDs by their order.
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
20060b57cec5SDimitry Andric     if (!MaybeRecord)
20070b57cec5SDimitry Andric       return MaybeRecord.takeError();
20080b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
20090b57cec5SDimitry Andric       return error("Invalid record");
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric     SmallString<16> SSN;
20120b57cec5SDimitry Andric     if (convertToString(Record, 0, SSN))
20130b57cec5SDimitry Andric       return error("Invalid record");
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric     SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
20160b57cec5SDimitry Andric     Record.clear();
20170b57cec5SDimitry Andric   }
20180b57cec5SDimitry Andric }
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric /// Associate a value with its name from the given index in the provided record.
recordValue(SmallVectorImpl<uint64_t> & Record,unsigned NameIndex,Triple & TT)20210b57cec5SDimitry Andric Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
20220b57cec5SDimitry Andric                                              unsigned NameIndex, Triple &TT) {
20230b57cec5SDimitry Andric   SmallString<128> ValueName;
20240b57cec5SDimitry Andric   if (convertToString(Record, NameIndex, ValueName))
20250b57cec5SDimitry Andric     return error("Invalid record");
20260b57cec5SDimitry Andric   unsigned ValueID = Record[0];
20270b57cec5SDimitry Andric   if (ValueID >= ValueList.size() || !ValueList[ValueID])
20280b57cec5SDimitry Andric     return error("Invalid record");
20290b57cec5SDimitry Andric   Value *V = ValueList[ValueID];
20300b57cec5SDimitry Andric 
20310b57cec5SDimitry Andric   StringRef NameStr(ValueName.data(), ValueName.size());
20320b57cec5SDimitry Andric   if (NameStr.find_first_of(0) != StringRef::npos)
20330b57cec5SDimitry Andric     return error("Invalid value name");
20340b57cec5SDimitry Andric   V->setName(NameStr);
20350b57cec5SDimitry Andric   auto *GO = dyn_cast<GlobalObject>(V);
20360b57cec5SDimitry Andric   if (GO) {
20370b57cec5SDimitry Andric     if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
20380b57cec5SDimitry Andric       if (TT.supportsCOMDAT())
20390b57cec5SDimitry Andric         GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
20400b57cec5SDimitry Andric       else
20410b57cec5SDimitry Andric         GO->setComdat(nullptr);
20420b57cec5SDimitry Andric     }
20430b57cec5SDimitry Andric   }
20440b57cec5SDimitry Andric   return V;
20450b57cec5SDimitry Andric }
20460b57cec5SDimitry Andric 
20470b57cec5SDimitry Andric /// Helper to note and return the current location, and jump to the given
20480b57cec5SDimitry Andric /// offset.
jumpToValueSymbolTable(uint64_t Offset,BitstreamCursor & Stream)20490b57cec5SDimitry Andric static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
20500b57cec5SDimitry Andric                                                  BitstreamCursor &Stream) {
20510b57cec5SDimitry Andric   // Save the current parsing location so we can jump back at the end
20520b57cec5SDimitry Andric   // of the VST read.
20530b57cec5SDimitry Andric   uint64_t CurrentBit = Stream.GetCurrentBitNo();
20540b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
20550b57cec5SDimitry Andric     return std::move(JumpFailed);
20560b57cec5SDimitry Andric   Expected<BitstreamEntry> MaybeEntry = Stream.advance();
20570b57cec5SDimitry Andric   if (!MaybeEntry)
20580b57cec5SDimitry Andric     return MaybeEntry.takeError();
20590b57cec5SDimitry Andric   assert(MaybeEntry.get().Kind == BitstreamEntry::SubBlock);
20600b57cec5SDimitry Andric   assert(MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID);
20610b57cec5SDimitry Andric   return CurrentBit;
20620b57cec5SDimitry Andric }
20630b57cec5SDimitry Andric 
setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,Function * F,ArrayRef<uint64_t> Record)20640b57cec5SDimitry Andric void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
20650b57cec5SDimitry Andric                                             Function *F,
20660b57cec5SDimitry Andric                                             ArrayRef<uint64_t> Record) {
20670b57cec5SDimitry Andric   // Note that we subtract 1 here because the offset is relative to one word
20680b57cec5SDimitry Andric   // before the start of the identification or module block, which was
20690b57cec5SDimitry Andric   // historically always the start of the regular bitcode header.
20700b57cec5SDimitry Andric   uint64_t FuncWordOffset = Record[1] - 1;
20710b57cec5SDimitry Andric   uint64_t FuncBitOffset = FuncWordOffset * 32;
20720b57cec5SDimitry Andric   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
20730b57cec5SDimitry Andric   // Set the LastFunctionBlockBit to point to the last function block.
20740b57cec5SDimitry Andric   // Later when parsing is resumed after function materialization,
20750b57cec5SDimitry Andric   // we can simply skip that last function block.
20760b57cec5SDimitry Andric   if (FuncBitOffset > LastFunctionBlockBit)
20770b57cec5SDimitry Andric     LastFunctionBlockBit = FuncBitOffset;
20780b57cec5SDimitry Andric }
20790b57cec5SDimitry Andric 
20800b57cec5SDimitry Andric /// Read a new-style GlobalValue symbol table.
parseGlobalValueSymbolTable()20810b57cec5SDimitry Andric Error BitcodeReader::parseGlobalValueSymbolTable() {
20820b57cec5SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
20830b57cec5SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
20860b57cec5SDimitry Andric     return Err;
20870b57cec5SDimitry Andric 
20880b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
20890b57cec5SDimitry Andric   while (true) {
20900b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
20910b57cec5SDimitry Andric     if (!MaybeEntry)
20920b57cec5SDimitry Andric       return MaybeEntry.takeError();
20930b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
20940b57cec5SDimitry Andric 
20950b57cec5SDimitry Andric     switch (Entry.Kind) {
20960b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
20970b57cec5SDimitry Andric     case BitstreamEntry::Error:
20980b57cec5SDimitry Andric       return error("Malformed block");
20990b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
21000b57cec5SDimitry Andric       return Error::success();
21010b57cec5SDimitry Andric     case BitstreamEntry::Record:
21020b57cec5SDimitry Andric       break;
21030b57cec5SDimitry Andric     }
21040b57cec5SDimitry Andric 
21050b57cec5SDimitry Andric     Record.clear();
21060b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
21070b57cec5SDimitry Andric     if (!MaybeRecord)
21080b57cec5SDimitry Andric       return MaybeRecord.takeError();
21090b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
21100b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: // [valueid, offset]
21110b57cec5SDimitry Andric       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
21120b57cec5SDimitry Andric                               cast<Function>(ValueList[Record[0]]), Record);
21130b57cec5SDimitry Andric       break;
21140b57cec5SDimitry Andric     }
21150b57cec5SDimitry Andric   }
21160b57cec5SDimitry Andric }
21170b57cec5SDimitry Andric 
21180b57cec5SDimitry Andric /// Parse the value symbol table at either the current parsing location or
21190b57cec5SDimitry Andric /// at the given bit offset if provided.
parseValueSymbolTable(uint64_t Offset)21200b57cec5SDimitry Andric Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
21210b57cec5SDimitry Andric   uint64_t CurrentBit;
21220b57cec5SDimitry Andric   // Pass in the Offset to distinguish between calling for the module-level
21230b57cec5SDimitry Andric   // VST (where we want to jump to the VST offset) and the function-level
21240b57cec5SDimitry Andric   // VST (where we don't).
21250b57cec5SDimitry Andric   if (Offset > 0) {
21260b57cec5SDimitry Andric     Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
21270b57cec5SDimitry Andric     if (!MaybeCurrentBit)
21280b57cec5SDimitry Andric       return MaybeCurrentBit.takeError();
21290b57cec5SDimitry Andric     CurrentBit = MaybeCurrentBit.get();
21300b57cec5SDimitry Andric     // If this module uses a string table, read this as a module-level VST.
21310b57cec5SDimitry Andric     if (UseStrtab) {
21320b57cec5SDimitry Andric       if (Error Err = parseGlobalValueSymbolTable())
21330b57cec5SDimitry Andric         return Err;
21340b57cec5SDimitry Andric       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
21350b57cec5SDimitry Andric         return JumpFailed;
21360b57cec5SDimitry Andric       return Error::success();
21370b57cec5SDimitry Andric     }
21380b57cec5SDimitry Andric     // Otherwise, the VST will be in a similar format to a function-level VST,
21390b57cec5SDimitry Andric     // and will contain symbol names.
21400b57cec5SDimitry Andric   }
21410b57cec5SDimitry Andric 
21420b57cec5SDimitry Andric   // Compute the delta between the bitcode indices in the VST (the word offset
21430b57cec5SDimitry Andric   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
21440b57cec5SDimitry Andric   // expected by the lazy reader. The reader's EnterSubBlock expects to have
21450b57cec5SDimitry Andric   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
21460b57cec5SDimitry Andric   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
21470b57cec5SDimitry Andric   // just before entering the VST subblock because: 1) the EnterSubBlock
21480b57cec5SDimitry Andric   // changes the AbbrevID width; 2) the VST block is nested within the same
21490b57cec5SDimitry Andric   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
21500b57cec5SDimitry Andric   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
21510b57cec5SDimitry Andric   // jump to the FUNCTION_BLOCK using this offset later, we don't want
21520b57cec5SDimitry Andric   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
21530b57cec5SDimitry Andric   unsigned FuncBitcodeOffsetDelta =
21540b57cec5SDimitry Andric       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
21550b57cec5SDimitry Andric 
21560b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
21570b57cec5SDimitry Andric     return Err;
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
21600b57cec5SDimitry Andric 
21610b57cec5SDimitry Andric   Triple TT(TheModule->getTargetTriple());
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric   // Read all the records for this value table.
21640b57cec5SDimitry Andric   SmallString<128> ValueName;
21650b57cec5SDimitry Andric 
21660b57cec5SDimitry Andric   while (true) {
21670b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
21680b57cec5SDimitry Andric     if (!MaybeEntry)
21690b57cec5SDimitry Andric       return MaybeEntry.takeError();
21700b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
21710b57cec5SDimitry Andric 
21720b57cec5SDimitry Andric     switch (Entry.Kind) {
21730b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
21740b57cec5SDimitry Andric     case BitstreamEntry::Error:
21750b57cec5SDimitry Andric       return error("Malformed block");
21760b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
21770b57cec5SDimitry Andric       if (Offset > 0)
21780b57cec5SDimitry Andric         if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
21790b57cec5SDimitry Andric           return JumpFailed;
21800b57cec5SDimitry Andric       return Error::success();
21810b57cec5SDimitry Andric     case BitstreamEntry::Record:
21820b57cec5SDimitry Andric       // The interesting case.
21830b57cec5SDimitry Andric       break;
21840b57cec5SDimitry Andric     }
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric     // Read a record.
21870b57cec5SDimitry Andric     Record.clear();
21880b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
21890b57cec5SDimitry Andric     if (!MaybeRecord)
21900b57cec5SDimitry Andric       return MaybeRecord.takeError();
21910b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
21920b57cec5SDimitry Andric     default:  // Default behavior: unknown type.
21930b57cec5SDimitry Andric       break;
21940b57cec5SDimitry Andric     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
21950b57cec5SDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
21960b57cec5SDimitry Andric       if (Error Err = ValOrErr.takeError())
21970b57cec5SDimitry Andric         return Err;
21980b57cec5SDimitry Andric       ValOrErr.get();
21990b57cec5SDimitry Andric       break;
22000b57cec5SDimitry Andric     }
22010b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
22020b57cec5SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
22030b57cec5SDimitry Andric       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
22040b57cec5SDimitry Andric       if (Error Err = ValOrErr.takeError())
22050b57cec5SDimitry Andric         return Err;
22060b57cec5SDimitry Andric       Value *V = ValOrErr.get();
22070b57cec5SDimitry Andric 
22080b57cec5SDimitry Andric       // Ignore function offsets emitted for aliases of functions in older
22090b57cec5SDimitry Andric       // versions of LLVM.
22100b57cec5SDimitry Andric       if (auto *F = dyn_cast<Function>(V))
22110b57cec5SDimitry Andric         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
22120b57cec5SDimitry Andric       break;
22130b57cec5SDimitry Andric     }
22140b57cec5SDimitry Andric     case bitc::VST_CODE_BBENTRY: {
22150b57cec5SDimitry Andric       if (convertToString(Record, 1, ValueName))
22160b57cec5SDimitry Andric         return error("Invalid record");
22170b57cec5SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[0]);
22180b57cec5SDimitry Andric       if (!BB)
22190b57cec5SDimitry Andric         return error("Invalid record");
22200b57cec5SDimitry Andric 
22210b57cec5SDimitry Andric       BB->setName(StringRef(ValueName.data(), ValueName.size()));
22220b57cec5SDimitry Andric       ValueName.clear();
22230b57cec5SDimitry Andric       break;
22240b57cec5SDimitry Andric     }
22250b57cec5SDimitry Andric     }
22260b57cec5SDimitry Andric   }
22270b57cec5SDimitry Andric }
22280b57cec5SDimitry Andric 
22290b57cec5SDimitry Andric /// Decode a signed value stored with the sign bit in the LSB for dense VBR
22300b57cec5SDimitry Andric /// encoding.
decodeSignRotatedValue(uint64_t V)22310b57cec5SDimitry Andric uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
22320b57cec5SDimitry Andric   if ((V & 1) == 0)
22330b57cec5SDimitry Andric     return V >> 1;
22340b57cec5SDimitry Andric   if (V != 1)
22350b57cec5SDimitry Andric     return -(V >> 1);
22360b57cec5SDimitry Andric   // There is no such thing as -0 with integers.  "-0" really means MININT.
22370b57cec5SDimitry Andric   return 1ULL << 63;
22380b57cec5SDimitry Andric }
22390b57cec5SDimitry Andric 
22400b57cec5SDimitry Andric /// Resolve all of the initializers for global values and aliases that we can.
resolveGlobalAndIndirectSymbolInits()22410b57cec5SDimitry Andric Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
22420b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
22430b57cec5SDimitry Andric   std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
22440b57cec5SDimitry Andric       IndirectSymbolInitWorklist;
22450b57cec5SDimitry Andric   std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
22460b57cec5SDimitry Andric   std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
22470b57cec5SDimitry Andric   std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric   GlobalInitWorklist.swap(GlobalInits);
22500b57cec5SDimitry Andric   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
22510b57cec5SDimitry Andric   FunctionPrefixWorklist.swap(FunctionPrefixes);
22520b57cec5SDimitry Andric   FunctionPrologueWorklist.swap(FunctionPrologues);
22530b57cec5SDimitry Andric   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
22540b57cec5SDimitry Andric 
22550b57cec5SDimitry Andric   while (!GlobalInitWorklist.empty()) {
22560b57cec5SDimitry Andric     unsigned ValID = GlobalInitWorklist.back().second;
22570b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
22580b57cec5SDimitry Andric       // Not ready to resolve this yet, it requires something later in the file.
22590b57cec5SDimitry Andric       GlobalInits.push_back(GlobalInitWorklist.back());
22600b57cec5SDimitry Andric     } else {
22610b57cec5SDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
22620b57cec5SDimitry Andric         GlobalInitWorklist.back().first->setInitializer(C);
22630b57cec5SDimitry Andric       else
22640b57cec5SDimitry Andric         return error("Expected a constant");
22650b57cec5SDimitry Andric     }
22660b57cec5SDimitry Andric     GlobalInitWorklist.pop_back();
22670b57cec5SDimitry Andric   }
22680b57cec5SDimitry Andric 
22690b57cec5SDimitry Andric   while (!IndirectSymbolInitWorklist.empty()) {
22700b57cec5SDimitry Andric     unsigned ValID = IndirectSymbolInitWorklist.back().second;
22710b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
22720b57cec5SDimitry Andric       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
22730b57cec5SDimitry Andric     } else {
22740b57cec5SDimitry Andric       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
22750b57cec5SDimitry Andric       if (!C)
22760b57cec5SDimitry Andric         return error("Expected a constant");
22770b57cec5SDimitry Andric       GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
22780b57cec5SDimitry Andric       if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
22790b57cec5SDimitry Andric         return error("Alias and aliasee types don't match");
22800b57cec5SDimitry Andric       GIS->setIndirectSymbol(C);
22810b57cec5SDimitry Andric     }
22820b57cec5SDimitry Andric     IndirectSymbolInitWorklist.pop_back();
22830b57cec5SDimitry Andric   }
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric   while (!FunctionPrefixWorklist.empty()) {
22860b57cec5SDimitry Andric     unsigned ValID = FunctionPrefixWorklist.back().second;
22870b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
22880b57cec5SDimitry Andric       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
22890b57cec5SDimitry Andric     } else {
22900b57cec5SDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
22910b57cec5SDimitry Andric         FunctionPrefixWorklist.back().first->setPrefixData(C);
22920b57cec5SDimitry Andric       else
22930b57cec5SDimitry Andric         return error("Expected a constant");
22940b57cec5SDimitry Andric     }
22950b57cec5SDimitry Andric     FunctionPrefixWorklist.pop_back();
22960b57cec5SDimitry Andric   }
22970b57cec5SDimitry Andric 
22980b57cec5SDimitry Andric   while (!FunctionPrologueWorklist.empty()) {
22990b57cec5SDimitry Andric     unsigned ValID = FunctionPrologueWorklist.back().second;
23000b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
23010b57cec5SDimitry Andric       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
23020b57cec5SDimitry Andric     } else {
23030b57cec5SDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
23040b57cec5SDimitry Andric         FunctionPrologueWorklist.back().first->setPrologueData(C);
23050b57cec5SDimitry Andric       else
23060b57cec5SDimitry Andric         return error("Expected a constant");
23070b57cec5SDimitry Andric     }
23080b57cec5SDimitry Andric     FunctionPrologueWorklist.pop_back();
23090b57cec5SDimitry Andric   }
23100b57cec5SDimitry Andric 
23110b57cec5SDimitry Andric   while (!FunctionPersonalityFnWorklist.empty()) {
23120b57cec5SDimitry Andric     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
23130b57cec5SDimitry Andric     if (ValID >= ValueList.size()) {
23140b57cec5SDimitry Andric       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
23150b57cec5SDimitry Andric     } else {
23160b57cec5SDimitry Andric       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
23170b57cec5SDimitry Andric         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
23180b57cec5SDimitry Andric       else
23190b57cec5SDimitry Andric         return error("Expected a constant");
23200b57cec5SDimitry Andric     }
23210b57cec5SDimitry Andric     FunctionPersonalityFnWorklist.pop_back();
23220b57cec5SDimitry Andric   }
23230b57cec5SDimitry Andric 
23240b57cec5SDimitry Andric   return Error::success();
23250b57cec5SDimitry Andric }
23260b57cec5SDimitry Andric 
readWideAPInt(ArrayRef<uint64_t> Vals,unsigned TypeBits)23275ffd83dbSDimitry Andric APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
23280b57cec5SDimitry Andric   SmallVector<uint64_t, 8> Words(Vals.size());
23290b57cec5SDimitry Andric   transform(Vals, Words.begin(),
23300b57cec5SDimitry Andric                  BitcodeReader::decodeSignRotatedValue);
23310b57cec5SDimitry Andric 
23320b57cec5SDimitry Andric   return APInt(TypeBits, Words);
23330b57cec5SDimitry Andric }
23340b57cec5SDimitry Andric 
parseConstants()23350b57cec5SDimitry Andric Error BitcodeReader::parseConstants() {
23360b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
23370b57cec5SDimitry Andric     return Err;
23380b57cec5SDimitry Andric 
23390b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
23400b57cec5SDimitry Andric 
23410b57cec5SDimitry Andric   // Read all the records for this value table.
23420b57cec5SDimitry Andric   Type *CurTy = Type::getInt32Ty(Context);
23430b57cec5SDimitry Andric   unsigned NextCstNo = ValueList.size();
23440b57cec5SDimitry Andric 
23455ffd83dbSDimitry Andric   struct DelayedShufTy {
23465ffd83dbSDimitry Andric     VectorType *OpTy;
23475ffd83dbSDimitry Andric     VectorType *RTy;
23485ffd83dbSDimitry Andric     uint64_t Op0Idx;
23495ffd83dbSDimitry Andric     uint64_t Op1Idx;
23505ffd83dbSDimitry Andric     uint64_t Op2Idx;
23515ffd83dbSDimitry Andric     unsigned CstNo;
23525ffd83dbSDimitry Andric   };
23535ffd83dbSDimitry Andric   std::vector<DelayedShufTy> DelayedShuffles;
23540b57cec5SDimitry Andric   while (true) {
23550b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
23560b57cec5SDimitry Andric     if (!MaybeEntry)
23570b57cec5SDimitry Andric       return MaybeEntry.takeError();
23580b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
23590b57cec5SDimitry Andric 
23600b57cec5SDimitry Andric     switch (Entry.Kind) {
23610b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
23620b57cec5SDimitry Andric     case BitstreamEntry::Error:
23630b57cec5SDimitry Andric       return error("Malformed block");
23640b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
23655ffd83dbSDimitry Andric       // Once all the constants have been read, go through and resolve forward
23665ffd83dbSDimitry Andric       // references.
23675ffd83dbSDimitry Andric       //
23685ffd83dbSDimitry Andric       // We have to treat shuffles specially because they don't have three
23695ffd83dbSDimitry Andric       // operands anymore.  We need to convert the shuffle mask into an array,
23705ffd83dbSDimitry Andric       // and we can't convert a forward reference.
23715ffd83dbSDimitry Andric       for (auto &DelayedShuffle : DelayedShuffles) {
23725ffd83dbSDimitry Andric         VectorType *OpTy = DelayedShuffle.OpTy;
23735ffd83dbSDimitry Andric         VectorType *RTy = DelayedShuffle.RTy;
23745ffd83dbSDimitry Andric         uint64_t Op0Idx = DelayedShuffle.Op0Idx;
23755ffd83dbSDimitry Andric         uint64_t Op1Idx = DelayedShuffle.Op1Idx;
23765ffd83dbSDimitry Andric         uint64_t Op2Idx = DelayedShuffle.Op2Idx;
23775ffd83dbSDimitry Andric         uint64_t CstNo = DelayedShuffle.CstNo;
23785ffd83dbSDimitry Andric         Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, OpTy);
23795ffd83dbSDimitry Andric         Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy);
23805ffd83dbSDimitry Andric         Type *ShufTy =
23815ffd83dbSDimitry Andric             VectorType::get(Type::getInt32Ty(Context), RTy->getElementCount());
23825ffd83dbSDimitry Andric         Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, ShufTy);
23835ffd83dbSDimitry Andric         if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
23845ffd83dbSDimitry Andric           return error("Invalid shufflevector operands");
23855ffd83dbSDimitry Andric         SmallVector<int, 16> Mask;
23865ffd83dbSDimitry Andric         ShuffleVectorInst::getShuffleMask(Op2, Mask);
23875ffd83dbSDimitry Andric         Value *V = ConstantExpr::getShuffleVector(Op0, Op1, Mask);
2388*5f7ddb14SDimitry Andric         ValueList.assignValue(V, CstNo);
23895ffd83dbSDimitry Andric       }
23905ffd83dbSDimitry Andric 
23910b57cec5SDimitry Andric       if (NextCstNo != ValueList.size())
23920b57cec5SDimitry Andric         return error("Invalid constant reference");
23930b57cec5SDimitry Andric 
23940b57cec5SDimitry Andric       ValueList.resolveConstantForwardRefs();
23950b57cec5SDimitry Andric       return Error::success();
23960b57cec5SDimitry Andric     case BitstreamEntry::Record:
23970b57cec5SDimitry Andric       // The interesting case.
23980b57cec5SDimitry Andric       break;
23990b57cec5SDimitry Andric     }
24000b57cec5SDimitry Andric 
24010b57cec5SDimitry Andric     // Read a record.
24020b57cec5SDimitry Andric     Record.clear();
24030b57cec5SDimitry Andric     Type *VoidType = Type::getVoidTy(Context);
24040b57cec5SDimitry Andric     Value *V = nullptr;
24050b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
24060b57cec5SDimitry Andric     if (!MaybeBitCode)
24070b57cec5SDimitry Andric       return MaybeBitCode.takeError();
24080b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
24090b57cec5SDimitry Andric     default:  // Default behavior: unknown constant
24100b57cec5SDimitry Andric     case bitc::CST_CODE_UNDEF:     // UNDEF
24110b57cec5SDimitry Andric       V = UndefValue::get(CurTy);
24120b57cec5SDimitry Andric       break;
2413af732203SDimitry Andric     case bitc::CST_CODE_POISON:    // POISON
2414af732203SDimitry Andric       V = PoisonValue::get(CurTy);
2415af732203SDimitry Andric       break;
24160b57cec5SDimitry Andric     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
24170b57cec5SDimitry Andric       if (Record.empty())
24180b57cec5SDimitry Andric         return error("Invalid record");
24190b57cec5SDimitry Andric       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
24200b57cec5SDimitry Andric         return error("Invalid record");
24210b57cec5SDimitry Andric       if (TypeList[Record[0]] == VoidType)
24220b57cec5SDimitry Andric         return error("Invalid constant type");
2423*5f7ddb14SDimitry Andric       CurTy = TypeList[Record[0]];
24240b57cec5SDimitry Andric       continue;  // Skip the ValueList manipulation.
24250b57cec5SDimitry Andric     case bitc::CST_CODE_NULL:      // NULL
24268bcb0991SDimitry Andric       if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
24278bcb0991SDimitry Andric         return error("Invalid type for a constant null value");
24280b57cec5SDimitry Andric       V = Constant::getNullValue(CurTy);
24290b57cec5SDimitry Andric       break;
24300b57cec5SDimitry Andric     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
24310b57cec5SDimitry Andric       if (!CurTy->isIntegerTy() || Record.empty())
24320b57cec5SDimitry Andric         return error("Invalid record");
24330b57cec5SDimitry Andric       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
24340b57cec5SDimitry Andric       break;
24350b57cec5SDimitry Andric     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
24360b57cec5SDimitry Andric       if (!CurTy->isIntegerTy() || Record.empty())
24370b57cec5SDimitry Andric         return error("Invalid record");
24380b57cec5SDimitry Andric 
24390b57cec5SDimitry Andric       APInt VInt =
24400b57cec5SDimitry Andric           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
24410b57cec5SDimitry Andric       V = ConstantInt::get(Context, VInt);
24420b57cec5SDimitry Andric 
24430b57cec5SDimitry Andric       break;
24440b57cec5SDimitry Andric     }
24450b57cec5SDimitry Andric     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
24460b57cec5SDimitry Andric       if (Record.empty())
24470b57cec5SDimitry Andric         return error("Invalid record");
24480b57cec5SDimitry Andric       if (CurTy->isHalfTy())
24490b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
24500b57cec5SDimitry Andric                                              APInt(16, (uint16_t)Record[0])));
24515ffd83dbSDimitry Andric       else if (CurTy->isBFloatTy())
24525ffd83dbSDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
24535ffd83dbSDimitry Andric                                              APInt(16, (uint32_t)Record[0])));
24540b57cec5SDimitry Andric       else if (CurTy->isFloatTy())
24550b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
24560b57cec5SDimitry Andric                                              APInt(32, (uint32_t)Record[0])));
24570b57cec5SDimitry Andric       else if (CurTy->isDoubleTy())
24580b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
24590b57cec5SDimitry Andric                                              APInt(64, Record[0])));
24600b57cec5SDimitry Andric       else if (CurTy->isX86_FP80Ty()) {
24610b57cec5SDimitry Andric         // Bits are not stored the same way as a normal i80 APInt, compensate.
24620b57cec5SDimitry Andric         uint64_t Rearrange[2];
24630b57cec5SDimitry Andric         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
24640b57cec5SDimitry Andric         Rearrange[1] = Record[0] >> 48;
24650b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
24660b57cec5SDimitry Andric                                              APInt(80, Rearrange)));
24670b57cec5SDimitry Andric       } else if (CurTy->isFP128Ty())
24680b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
24690b57cec5SDimitry Andric                                              APInt(128, Record)));
24700b57cec5SDimitry Andric       else if (CurTy->isPPC_FP128Ty())
24710b57cec5SDimitry Andric         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
24720b57cec5SDimitry Andric                                              APInt(128, Record)));
24730b57cec5SDimitry Andric       else
24740b57cec5SDimitry Andric         V = UndefValue::get(CurTy);
24750b57cec5SDimitry Andric       break;
24760b57cec5SDimitry Andric     }
24770b57cec5SDimitry Andric 
24780b57cec5SDimitry Andric     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
24790b57cec5SDimitry Andric       if (Record.empty())
24800b57cec5SDimitry Andric         return error("Invalid record");
24810b57cec5SDimitry Andric 
24820b57cec5SDimitry Andric       unsigned Size = Record.size();
24830b57cec5SDimitry Andric       SmallVector<Constant*, 16> Elts;
24840b57cec5SDimitry Andric 
24850b57cec5SDimitry Andric       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
24860b57cec5SDimitry Andric         for (unsigned i = 0; i != Size; ++i)
24870b57cec5SDimitry Andric           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
24880b57cec5SDimitry Andric                                                      STy->getElementType(i)));
24890b57cec5SDimitry Andric         V = ConstantStruct::get(STy, Elts);
24900b57cec5SDimitry Andric       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
24910b57cec5SDimitry Andric         Type *EltTy = ATy->getElementType();
24920b57cec5SDimitry Andric         for (unsigned i = 0; i != Size; ++i)
24930b57cec5SDimitry Andric           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
24940b57cec5SDimitry Andric         V = ConstantArray::get(ATy, Elts);
24950b57cec5SDimitry Andric       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
24960b57cec5SDimitry Andric         Type *EltTy = VTy->getElementType();
24970b57cec5SDimitry Andric         for (unsigned i = 0; i != Size; ++i)
24980b57cec5SDimitry Andric           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
24990b57cec5SDimitry Andric         V = ConstantVector::get(Elts);
25000b57cec5SDimitry Andric       } else {
25010b57cec5SDimitry Andric         V = UndefValue::get(CurTy);
25020b57cec5SDimitry Andric       }
25030b57cec5SDimitry Andric       break;
25040b57cec5SDimitry Andric     }
25050b57cec5SDimitry Andric     case bitc::CST_CODE_STRING:    // STRING: [values]
25060b57cec5SDimitry Andric     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
25070b57cec5SDimitry Andric       if (Record.empty())
25080b57cec5SDimitry Andric         return error("Invalid record");
25090b57cec5SDimitry Andric 
25100b57cec5SDimitry Andric       SmallString<16> Elts(Record.begin(), Record.end());
25110b57cec5SDimitry Andric       V = ConstantDataArray::getString(Context, Elts,
25120b57cec5SDimitry Andric                                        BitCode == bitc::CST_CODE_CSTRING);
25130b57cec5SDimitry Andric       break;
25140b57cec5SDimitry Andric     }
25150b57cec5SDimitry Andric     case bitc::CST_CODE_DATA: {// DATA: [n x value]
25160b57cec5SDimitry Andric       if (Record.empty())
25170b57cec5SDimitry Andric         return error("Invalid record");
25180b57cec5SDimitry Andric 
25195ffd83dbSDimitry Andric       Type *EltTy;
25205ffd83dbSDimitry Andric       if (auto *Array = dyn_cast<ArrayType>(CurTy))
25215ffd83dbSDimitry Andric         EltTy = Array->getElementType();
25225ffd83dbSDimitry Andric       else
25235ffd83dbSDimitry Andric         EltTy = cast<VectorType>(CurTy)->getElementType();
25240b57cec5SDimitry Andric       if (EltTy->isIntegerTy(8)) {
25250b57cec5SDimitry Andric         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
25260b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
25270b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
25280b57cec5SDimitry Andric         else
25290b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
25300b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(16)) {
25310b57cec5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
25320b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
25330b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
25340b57cec5SDimitry Andric         else
25350b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
25360b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(32)) {
25370b57cec5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
25380b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
25390b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
25400b57cec5SDimitry Andric         else
25410b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
25420b57cec5SDimitry Andric       } else if (EltTy->isIntegerTy(64)) {
25430b57cec5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
25440b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
25450b57cec5SDimitry Andric           V = ConstantDataVector::get(Context, Elts);
25460b57cec5SDimitry Andric         else
25470b57cec5SDimitry Andric           V = ConstantDataArray::get(Context, Elts);
25480b57cec5SDimitry Andric       } else if (EltTy->isHalfTy()) {
25490b57cec5SDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
25500b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
25515ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
25520b57cec5SDimitry Andric         else
25535ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
25545ffd83dbSDimitry Andric       } else if (EltTy->isBFloatTy()) {
25555ffd83dbSDimitry Andric         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
25565ffd83dbSDimitry Andric         if (isa<VectorType>(CurTy))
25575ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
25585ffd83dbSDimitry Andric         else
25595ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
25600b57cec5SDimitry Andric       } else if (EltTy->isFloatTy()) {
25610b57cec5SDimitry Andric         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
25620b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
25635ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
25640b57cec5SDimitry Andric         else
25655ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
25660b57cec5SDimitry Andric       } else if (EltTy->isDoubleTy()) {
25670b57cec5SDimitry Andric         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
25680b57cec5SDimitry Andric         if (isa<VectorType>(CurTy))
25695ffd83dbSDimitry Andric           V = ConstantDataVector::getFP(EltTy, Elts);
25700b57cec5SDimitry Andric         else
25715ffd83dbSDimitry Andric           V = ConstantDataArray::getFP(EltTy, Elts);
25720b57cec5SDimitry Andric       } else {
25730b57cec5SDimitry Andric         return error("Invalid type for value");
25740b57cec5SDimitry Andric       }
25750b57cec5SDimitry Andric       break;
25760b57cec5SDimitry Andric     }
25770b57cec5SDimitry Andric     case bitc::CST_CODE_CE_UNOP: {  // CE_UNOP: [opcode, opval]
25780b57cec5SDimitry Andric       if (Record.size() < 2)
25790b57cec5SDimitry Andric         return error("Invalid record");
25800b57cec5SDimitry Andric       int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
25810b57cec5SDimitry Andric       if (Opc < 0) {
25820b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown unop.
25830b57cec5SDimitry Andric       } else {
25840b57cec5SDimitry Andric         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
25850b57cec5SDimitry Andric         unsigned Flags = 0;
25860b57cec5SDimitry Andric         V = ConstantExpr::get(Opc, LHS, Flags);
25870b57cec5SDimitry Andric       }
25880b57cec5SDimitry Andric       break;
25890b57cec5SDimitry Andric     }
25900b57cec5SDimitry Andric     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
25910b57cec5SDimitry Andric       if (Record.size() < 3)
25920b57cec5SDimitry Andric         return error("Invalid record");
25930b57cec5SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
25940b57cec5SDimitry Andric       if (Opc < 0) {
25950b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown binop.
25960b57cec5SDimitry Andric       } else {
25970b57cec5SDimitry Andric         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
25980b57cec5SDimitry Andric         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
25990b57cec5SDimitry Andric         unsigned Flags = 0;
26000b57cec5SDimitry Andric         if (Record.size() >= 4) {
26010b57cec5SDimitry Andric           if (Opc == Instruction::Add ||
26020b57cec5SDimitry Andric               Opc == Instruction::Sub ||
26030b57cec5SDimitry Andric               Opc == Instruction::Mul ||
26040b57cec5SDimitry Andric               Opc == Instruction::Shl) {
26050b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
26060b57cec5SDimitry Andric               Flags |= OverflowingBinaryOperator::NoSignedWrap;
26070b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
26080b57cec5SDimitry Andric               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
26090b57cec5SDimitry Andric           } else if (Opc == Instruction::SDiv ||
26100b57cec5SDimitry Andric                      Opc == Instruction::UDiv ||
26110b57cec5SDimitry Andric                      Opc == Instruction::LShr ||
26120b57cec5SDimitry Andric                      Opc == Instruction::AShr) {
26130b57cec5SDimitry Andric             if (Record[3] & (1 << bitc::PEO_EXACT))
26140b57cec5SDimitry Andric               Flags |= SDivOperator::IsExact;
26150b57cec5SDimitry Andric           }
26160b57cec5SDimitry Andric         }
26170b57cec5SDimitry Andric         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
26180b57cec5SDimitry Andric       }
26190b57cec5SDimitry Andric       break;
26200b57cec5SDimitry Andric     }
26210b57cec5SDimitry Andric     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
26220b57cec5SDimitry Andric       if (Record.size() < 3)
26230b57cec5SDimitry Andric         return error("Invalid record");
26240b57cec5SDimitry Andric       int Opc = getDecodedCastOpcode(Record[0]);
26250b57cec5SDimitry Andric       if (Opc < 0) {
26260b57cec5SDimitry Andric         V = UndefValue::get(CurTy);  // Unknown cast.
26270b57cec5SDimitry Andric       } else {
26280b57cec5SDimitry Andric         Type *OpTy = getTypeByID(Record[1]);
26290b57cec5SDimitry Andric         if (!OpTy)
26300b57cec5SDimitry Andric           return error("Invalid record");
26310b57cec5SDimitry Andric         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
26320b57cec5SDimitry Andric         V = UpgradeBitCastExpr(Opc, Op, CurTy);
26330b57cec5SDimitry Andric         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
26340b57cec5SDimitry Andric       }
26350b57cec5SDimitry Andric       break;
26360b57cec5SDimitry Andric     }
26370b57cec5SDimitry Andric     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
26380b57cec5SDimitry Andric     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
26390b57cec5SDimitry Andric     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
26400b57cec5SDimitry Andric                                                      // operands]
26410b57cec5SDimitry Andric       unsigned OpNum = 0;
26420b57cec5SDimitry Andric       Type *PointeeType = nullptr;
26430b57cec5SDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
26440b57cec5SDimitry Andric           Record.size() % 2)
26450b57cec5SDimitry Andric         PointeeType = getTypeByID(Record[OpNum++]);
26460b57cec5SDimitry Andric 
26470b57cec5SDimitry Andric       bool InBounds = false;
26480b57cec5SDimitry Andric       Optional<unsigned> InRangeIndex;
26490b57cec5SDimitry Andric       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
26500b57cec5SDimitry Andric         uint64_t Op = Record[OpNum++];
26510b57cec5SDimitry Andric         InBounds = Op & 1;
26520b57cec5SDimitry Andric         InRangeIndex = Op >> 1;
26530b57cec5SDimitry Andric       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
26540b57cec5SDimitry Andric         InBounds = true;
26550b57cec5SDimitry Andric 
26560b57cec5SDimitry Andric       SmallVector<Constant*, 16> Elts;
26570b57cec5SDimitry Andric       Type *Elt0FullTy = nullptr;
26580b57cec5SDimitry Andric       while (OpNum != Record.size()) {
26590b57cec5SDimitry Andric         if (!Elt0FullTy)
2660*5f7ddb14SDimitry Andric           Elt0FullTy = getTypeByID(Record[OpNum]);
26610b57cec5SDimitry Andric         Type *ElTy = getTypeByID(Record[OpNum++]);
26620b57cec5SDimitry Andric         if (!ElTy)
26630b57cec5SDimitry Andric           return error("Invalid record");
26640b57cec5SDimitry Andric         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
26650b57cec5SDimitry Andric       }
26660b57cec5SDimitry Andric 
26670b57cec5SDimitry Andric       if (Elts.size() < 1)
26680b57cec5SDimitry Andric         return error("Invalid gep with no operands");
26690b57cec5SDimitry Andric 
2670*5f7ddb14SDimitry Andric       PointerType *OrigPtrTy = cast<PointerType>(Elt0FullTy->getScalarType());
26710b57cec5SDimitry Andric       if (!PointeeType)
2672*5f7ddb14SDimitry Andric         PointeeType = OrigPtrTy->getElementType();
2673*5f7ddb14SDimitry Andric       else if (!OrigPtrTy->isOpaqueOrPointeeTypeMatches(PointeeType))
26740b57cec5SDimitry Andric         return error("Explicit gep operator type does not match pointee type "
26750b57cec5SDimitry Andric                      "of pointer operand");
26760b57cec5SDimitry Andric 
26770b57cec5SDimitry Andric       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
26780b57cec5SDimitry Andric       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
26790b57cec5SDimitry Andric                                          InBounds, InRangeIndex);
26800b57cec5SDimitry Andric       break;
26810b57cec5SDimitry Andric     }
26820b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
26830b57cec5SDimitry Andric       if (Record.size() < 3)
26840b57cec5SDimitry Andric         return error("Invalid record");
26850b57cec5SDimitry Andric 
26860b57cec5SDimitry Andric       Type *SelectorTy = Type::getInt1Ty(Context);
26870b57cec5SDimitry Andric 
26885ffd83dbSDimitry Andric       // The selector might be an i1, an <n x i1>, or a <vscale x n x i1>
26890b57cec5SDimitry Andric       // Get the type from the ValueList before getting a forward ref.
26900b57cec5SDimitry Andric       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
26910b57cec5SDimitry Andric         if (Value *V = ValueList[Record[0]])
26920b57cec5SDimitry Andric           if (SelectorTy != V->getType())
26935ffd83dbSDimitry Andric             SelectorTy = VectorType::get(SelectorTy,
26945ffd83dbSDimitry Andric                                          VTy->getElementCount());
26950b57cec5SDimitry Andric 
26960b57cec5SDimitry Andric       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
26970b57cec5SDimitry Andric                                                               SelectorTy),
26980b57cec5SDimitry Andric                                   ValueList.getConstantFwdRef(Record[1],CurTy),
26990b57cec5SDimitry Andric                                   ValueList.getConstantFwdRef(Record[2],CurTy));
27000b57cec5SDimitry Andric       break;
27010b57cec5SDimitry Andric     }
27020b57cec5SDimitry Andric     case bitc::CST_CODE_CE_EXTRACTELT
27030b57cec5SDimitry Andric         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
27040b57cec5SDimitry Andric       if (Record.size() < 3)
27050b57cec5SDimitry Andric         return error("Invalid record");
27060b57cec5SDimitry Andric       VectorType *OpTy =
27070b57cec5SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
27080b57cec5SDimitry Andric       if (!OpTy)
27090b57cec5SDimitry Andric         return error("Invalid record");
27100b57cec5SDimitry Andric       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
27110b57cec5SDimitry Andric       Constant *Op1 = nullptr;
27120b57cec5SDimitry Andric       if (Record.size() == 4) {
27130b57cec5SDimitry Andric         Type *IdxTy = getTypeByID(Record[2]);
27140b57cec5SDimitry Andric         if (!IdxTy)
27150b57cec5SDimitry Andric           return error("Invalid record");
27160b57cec5SDimitry Andric         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
27175ffd83dbSDimitry Andric       } else {
27185ffd83dbSDimitry Andric         // Deprecated, but still needed to read old bitcode files.
27190b57cec5SDimitry Andric         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
27205ffd83dbSDimitry Andric       }
27210b57cec5SDimitry Andric       if (!Op1)
27220b57cec5SDimitry Andric         return error("Invalid record");
27230b57cec5SDimitry Andric       V = ConstantExpr::getExtractElement(Op0, Op1);
27240b57cec5SDimitry Andric       break;
27250b57cec5SDimitry Andric     }
27260b57cec5SDimitry Andric     case bitc::CST_CODE_CE_INSERTELT
27270b57cec5SDimitry Andric         : { // CE_INSERTELT: [opval, opval, opty, opval]
27280b57cec5SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
27290b57cec5SDimitry Andric       if (Record.size() < 3 || !OpTy)
27300b57cec5SDimitry Andric         return error("Invalid record");
27310b57cec5SDimitry Andric       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
27320b57cec5SDimitry Andric       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
27330b57cec5SDimitry Andric                                                   OpTy->getElementType());
27340b57cec5SDimitry Andric       Constant *Op2 = nullptr;
27350b57cec5SDimitry Andric       if (Record.size() == 4) {
27360b57cec5SDimitry Andric         Type *IdxTy = getTypeByID(Record[2]);
27370b57cec5SDimitry Andric         if (!IdxTy)
27380b57cec5SDimitry Andric           return error("Invalid record");
27390b57cec5SDimitry Andric         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
27405ffd83dbSDimitry Andric       } else {
27415ffd83dbSDimitry Andric         // Deprecated, but still needed to read old bitcode files.
27420b57cec5SDimitry Andric         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
27435ffd83dbSDimitry Andric       }
27440b57cec5SDimitry Andric       if (!Op2)
27450b57cec5SDimitry Andric         return error("Invalid record");
27460b57cec5SDimitry Andric       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
27470b57cec5SDimitry Andric       break;
27480b57cec5SDimitry Andric     }
27490b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
27500b57cec5SDimitry Andric       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
27510b57cec5SDimitry Andric       if (Record.size() < 3 || !OpTy)
27520b57cec5SDimitry Andric         return error("Invalid record");
27535ffd83dbSDimitry Andric       DelayedShuffles.push_back(
2754*5f7ddb14SDimitry Andric           {OpTy, OpTy, Record[0], Record[1], Record[2], NextCstNo});
27555ffd83dbSDimitry Andric       ++NextCstNo;
27565ffd83dbSDimitry Andric       continue;
27570b57cec5SDimitry Andric     }
27580b57cec5SDimitry Andric     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
27590b57cec5SDimitry Andric       VectorType *RTy = dyn_cast<VectorType>(CurTy);
27600b57cec5SDimitry Andric       VectorType *OpTy =
27610b57cec5SDimitry Andric         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
27620b57cec5SDimitry Andric       if (Record.size() < 4 || !RTy || !OpTy)
27630b57cec5SDimitry Andric         return error("Invalid record");
27645ffd83dbSDimitry Andric       DelayedShuffles.push_back(
2765*5f7ddb14SDimitry Andric           {OpTy, RTy, Record[1], Record[2], Record[3], NextCstNo});
27665ffd83dbSDimitry Andric       ++NextCstNo;
27675ffd83dbSDimitry Andric       continue;
27680b57cec5SDimitry Andric     }
27690b57cec5SDimitry Andric     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
27700b57cec5SDimitry Andric       if (Record.size() < 4)
27710b57cec5SDimitry Andric         return error("Invalid record");
27720b57cec5SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
27730b57cec5SDimitry Andric       if (!OpTy)
27740b57cec5SDimitry Andric         return error("Invalid record");
27750b57cec5SDimitry Andric       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
27760b57cec5SDimitry Andric       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
27770b57cec5SDimitry Andric 
27780b57cec5SDimitry Andric       if (OpTy->isFPOrFPVectorTy())
27790b57cec5SDimitry Andric         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
27800b57cec5SDimitry Andric       else
27810b57cec5SDimitry Andric         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
27820b57cec5SDimitry Andric       break;
27830b57cec5SDimitry Andric     }
27840b57cec5SDimitry Andric     // This maintains backward compatibility, pre-asm dialect keywords.
27855ffd83dbSDimitry Andric     // Deprecated, but still needed to read old bitcode files.
27860b57cec5SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD: {
27870b57cec5SDimitry Andric       if (Record.size() < 2)
27880b57cec5SDimitry Andric         return error("Invalid record");
27890b57cec5SDimitry Andric       std::string AsmStr, ConstrStr;
27900b57cec5SDimitry Andric       bool HasSideEffects = Record[0] & 1;
27910b57cec5SDimitry Andric       bool IsAlignStack = Record[0] >> 1;
27920b57cec5SDimitry Andric       unsigned AsmStrSize = Record[1];
27930b57cec5SDimitry Andric       if (2+AsmStrSize >= Record.size())
27940b57cec5SDimitry Andric         return error("Invalid record");
27950b57cec5SDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
27960b57cec5SDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
27970b57cec5SDimitry Andric         return error("Invalid record");
27980b57cec5SDimitry Andric 
27990b57cec5SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
28000b57cec5SDimitry Andric         AsmStr += (char)Record[2+i];
28010b57cec5SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
28020b57cec5SDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
28030b57cec5SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
28040b57cec5SDimitry Andric       V = InlineAsm::get(
2805*5f7ddb14SDimitry Andric           cast<FunctionType>(cast<PointerType>(CurTy)->getElementType()),
2806*5f7ddb14SDimitry Andric           AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
28070b57cec5SDimitry Andric       break;
28080b57cec5SDimitry Andric     }
28090b57cec5SDimitry Andric     // This version adds support for the asm dialect keywords (e.g.,
28100b57cec5SDimitry Andric     // inteldialect).
2811*5f7ddb14SDimitry Andric     case bitc::CST_CODE_INLINEASM_OLD2: {
28120b57cec5SDimitry Andric       if (Record.size() < 2)
28130b57cec5SDimitry Andric         return error("Invalid record");
28140b57cec5SDimitry Andric       std::string AsmStr, ConstrStr;
28150b57cec5SDimitry Andric       bool HasSideEffects = Record[0] & 1;
28160b57cec5SDimitry Andric       bool IsAlignStack = (Record[0] >> 1) & 1;
28170b57cec5SDimitry Andric       unsigned AsmDialect = Record[0] >> 2;
28180b57cec5SDimitry Andric       unsigned AsmStrSize = Record[1];
28190b57cec5SDimitry Andric       if (2+AsmStrSize >= Record.size())
28200b57cec5SDimitry Andric         return error("Invalid record");
28210b57cec5SDimitry Andric       unsigned ConstStrSize = Record[2+AsmStrSize];
28220b57cec5SDimitry Andric       if (3+AsmStrSize+ConstStrSize > Record.size())
28230b57cec5SDimitry Andric         return error("Invalid record");
28240b57cec5SDimitry Andric 
28250b57cec5SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
28260b57cec5SDimitry Andric         AsmStr += (char)Record[2+i];
28270b57cec5SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
28280b57cec5SDimitry Andric         ConstrStr += (char)Record[3+AsmStrSize+i];
28290b57cec5SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
28300b57cec5SDimitry Andric       V = InlineAsm::get(
2831*5f7ddb14SDimitry Andric           cast<FunctionType>(cast<PointerType>(CurTy)->getElementType()),
2832*5f7ddb14SDimitry Andric           AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
28330b57cec5SDimitry Andric           InlineAsm::AsmDialect(AsmDialect));
28340b57cec5SDimitry Andric       break;
28350b57cec5SDimitry Andric     }
2836*5f7ddb14SDimitry Andric     // This version adds support for the unwind keyword.
2837*5f7ddb14SDimitry Andric     case bitc::CST_CODE_INLINEASM: {
2838*5f7ddb14SDimitry Andric       if (Record.size() < 2)
2839*5f7ddb14SDimitry Andric         return error("Invalid record");
2840*5f7ddb14SDimitry Andric       std::string AsmStr, ConstrStr;
2841*5f7ddb14SDimitry Andric       bool HasSideEffects = Record[0] & 1;
2842*5f7ddb14SDimitry Andric       bool IsAlignStack = (Record[0] >> 1) & 1;
2843*5f7ddb14SDimitry Andric       unsigned AsmDialect = (Record[0] >> 2) & 1;
2844*5f7ddb14SDimitry Andric       bool CanThrow = (Record[0] >> 3) & 1;
2845*5f7ddb14SDimitry Andric       unsigned AsmStrSize = Record[1];
2846*5f7ddb14SDimitry Andric       if (2 + AsmStrSize >= Record.size())
2847*5f7ddb14SDimitry Andric         return error("Invalid record");
2848*5f7ddb14SDimitry Andric       unsigned ConstStrSize = Record[2 + AsmStrSize];
2849*5f7ddb14SDimitry Andric       if (3 + AsmStrSize + ConstStrSize > Record.size())
2850*5f7ddb14SDimitry Andric         return error("Invalid record");
2851*5f7ddb14SDimitry Andric 
2852*5f7ddb14SDimitry Andric       for (unsigned i = 0; i != AsmStrSize; ++i)
2853*5f7ddb14SDimitry Andric         AsmStr += (char)Record[2 + i];
2854*5f7ddb14SDimitry Andric       for (unsigned i = 0; i != ConstStrSize; ++i)
2855*5f7ddb14SDimitry Andric         ConstrStr += (char)Record[3 + AsmStrSize + i];
2856*5f7ddb14SDimitry Andric       UpgradeInlineAsmString(&AsmStr);
2857*5f7ddb14SDimitry Andric       V = InlineAsm::get(
2858*5f7ddb14SDimitry Andric           cast<FunctionType>(cast<PointerType>(CurTy)->getElementType()),
2859*5f7ddb14SDimitry Andric           AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2860*5f7ddb14SDimitry Andric           InlineAsm::AsmDialect(AsmDialect), CanThrow);
2861*5f7ddb14SDimitry Andric       break;
2862*5f7ddb14SDimitry Andric     }
28630b57cec5SDimitry Andric     case bitc::CST_CODE_BLOCKADDRESS:{
28640b57cec5SDimitry Andric       if (Record.size() < 3)
28650b57cec5SDimitry Andric         return error("Invalid record");
28660b57cec5SDimitry Andric       Type *FnTy = getTypeByID(Record[0]);
28670b57cec5SDimitry Andric       if (!FnTy)
28680b57cec5SDimitry Andric         return error("Invalid record");
28690b57cec5SDimitry Andric       Function *Fn =
28700b57cec5SDimitry Andric         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
28710b57cec5SDimitry Andric       if (!Fn)
28720b57cec5SDimitry Andric         return error("Invalid record");
28730b57cec5SDimitry Andric 
28740b57cec5SDimitry Andric       // If the function is already parsed we can insert the block address right
28750b57cec5SDimitry Andric       // away.
28760b57cec5SDimitry Andric       BasicBlock *BB;
28770b57cec5SDimitry Andric       unsigned BBID = Record[2];
28780b57cec5SDimitry Andric       if (!BBID)
28790b57cec5SDimitry Andric         // Invalid reference to entry block.
28800b57cec5SDimitry Andric         return error("Invalid ID");
28810b57cec5SDimitry Andric       if (!Fn->empty()) {
28820b57cec5SDimitry Andric         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
28830b57cec5SDimitry Andric         for (size_t I = 0, E = BBID; I != E; ++I) {
28840b57cec5SDimitry Andric           if (BBI == BBE)
28850b57cec5SDimitry Andric             return error("Invalid ID");
28860b57cec5SDimitry Andric           ++BBI;
28870b57cec5SDimitry Andric         }
28880b57cec5SDimitry Andric         BB = &*BBI;
28890b57cec5SDimitry Andric       } else {
28900b57cec5SDimitry Andric         // Otherwise insert a placeholder and remember it so it can be inserted
28910b57cec5SDimitry Andric         // when the function is parsed.
28920b57cec5SDimitry Andric         auto &FwdBBs = BasicBlockFwdRefs[Fn];
28930b57cec5SDimitry Andric         if (FwdBBs.empty())
28940b57cec5SDimitry Andric           BasicBlockFwdRefQueue.push_back(Fn);
28950b57cec5SDimitry Andric         if (FwdBBs.size() < BBID + 1)
28960b57cec5SDimitry Andric           FwdBBs.resize(BBID + 1);
28970b57cec5SDimitry Andric         if (!FwdBBs[BBID])
28980b57cec5SDimitry Andric           FwdBBs[BBID] = BasicBlock::Create(Context);
28990b57cec5SDimitry Andric         BB = FwdBBs[BBID];
29000b57cec5SDimitry Andric       }
29010b57cec5SDimitry Andric       V = BlockAddress::get(Fn, BB);
29020b57cec5SDimitry Andric       break;
29030b57cec5SDimitry Andric     }
2904*5f7ddb14SDimitry Andric     case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
2905*5f7ddb14SDimitry Andric       if (Record.size() < 2)
2906*5f7ddb14SDimitry Andric         return error("Invalid record");
2907*5f7ddb14SDimitry Andric       Type *GVTy = getTypeByID(Record[0]);
2908*5f7ddb14SDimitry Andric       if (!GVTy)
2909*5f7ddb14SDimitry Andric         return error("Invalid record");
2910*5f7ddb14SDimitry Andric       GlobalValue *GV = dyn_cast_or_null<GlobalValue>(
2911*5f7ddb14SDimitry Andric           ValueList.getConstantFwdRef(Record[1], GVTy));
2912*5f7ddb14SDimitry Andric       if (!GV)
2913*5f7ddb14SDimitry Andric         return error("Invalid record");
2914*5f7ddb14SDimitry Andric 
2915*5f7ddb14SDimitry Andric       V = DSOLocalEquivalent::get(GV);
2916*5f7ddb14SDimitry Andric       break;
2917*5f7ddb14SDimitry Andric     }
29180b57cec5SDimitry Andric     }
29190b57cec5SDimitry Andric 
2920*5f7ddb14SDimitry Andric     ValueList.assignValue(V, NextCstNo);
29210b57cec5SDimitry Andric     ++NextCstNo;
29220b57cec5SDimitry Andric   }
29230b57cec5SDimitry Andric }
29240b57cec5SDimitry Andric 
parseUseLists()29250b57cec5SDimitry Andric Error BitcodeReader::parseUseLists() {
29260b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
29270b57cec5SDimitry Andric     return Err;
29280b57cec5SDimitry Andric 
29290b57cec5SDimitry Andric   // Read all the records.
29300b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
29310b57cec5SDimitry Andric 
29320b57cec5SDimitry Andric   while (true) {
29330b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
29340b57cec5SDimitry Andric     if (!MaybeEntry)
29350b57cec5SDimitry Andric       return MaybeEntry.takeError();
29360b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
29370b57cec5SDimitry Andric 
29380b57cec5SDimitry Andric     switch (Entry.Kind) {
29390b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
29400b57cec5SDimitry Andric     case BitstreamEntry::Error:
29410b57cec5SDimitry Andric       return error("Malformed block");
29420b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
29430b57cec5SDimitry Andric       return Error::success();
29440b57cec5SDimitry Andric     case BitstreamEntry::Record:
29450b57cec5SDimitry Andric       // The interesting case.
29460b57cec5SDimitry Andric       break;
29470b57cec5SDimitry Andric     }
29480b57cec5SDimitry Andric 
29490b57cec5SDimitry Andric     // Read a use list record.
29500b57cec5SDimitry Andric     Record.clear();
29510b57cec5SDimitry Andric     bool IsBB = false;
29520b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
29530b57cec5SDimitry Andric     if (!MaybeRecord)
29540b57cec5SDimitry Andric       return MaybeRecord.takeError();
29550b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
29560b57cec5SDimitry Andric     default:  // Default behavior: unknown type.
29570b57cec5SDimitry Andric       break;
29580b57cec5SDimitry Andric     case bitc::USELIST_CODE_BB:
29590b57cec5SDimitry Andric       IsBB = true;
29600b57cec5SDimitry Andric       LLVM_FALLTHROUGH;
29610b57cec5SDimitry Andric     case bitc::USELIST_CODE_DEFAULT: {
29620b57cec5SDimitry Andric       unsigned RecordLength = Record.size();
29630b57cec5SDimitry Andric       if (RecordLength < 3)
29640b57cec5SDimitry Andric         // Records should have at least an ID and two indexes.
29650b57cec5SDimitry Andric         return error("Invalid record");
2966af732203SDimitry Andric       unsigned ID = Record.pop_back_val();
29670b57cec5SDimitry Andric 
29680b57cec5SDimitry Andric       Value *V;
29690b57cec5SDimitry Andric       if (IsBB) {
29700b57cec5SDimitry Andric         assert(ID < FunctionBBs.size() && "Basic block not found");
29710b57cec5SDimitry Andric         V = FunctionBBs[ID];
29720b57cec5SDimitry Andric       } else
29730b57cec5SDimitry Andric         V = ValueList[ID];
29740b57cec5SDimitry Andric       unsigned NumUses = 0;
29750b57cec5SDimitry Andric       SmallDenseMap<const Use *, unsigned, 16> Order;
29760b57cec5SDimitry Andric       for (const Use &U : V->materialized_uses()) {
29770b57cec5SDimitry Andric         if (++NumUses > Record.size())
29780b57cec5SDimitry Andric           break;
29790b57cec5SDimitry Andric         Order[&U] = Record[NumUses - 1];
29800b57cec5SDimitry Andric       }
29810b57cec5SDimitry Andric       if (Order.size() != Record.size() || NumUses > Record.size())
29820b57cec5SDimitry Andric         // Mismatches can happen if the functions are being materialized lazily
29830b57cec5SDimitry Andric         // (out-of-order), or a value has been upgraded.
29840b57cec5SDimitry Andric         break;
29850b57cec5SDimitry Andric 
29860b57cec5SDimitry Andric       V->sortUseList([&](const Use &L, const Use &R) {
29870b57cec5SDimitry Andric         return Order.lookup(&L) < Order.lookup(&R);
29880b57cec5SDimitry Andric       });
29890b57cec5SDimitry Andric       break;
29900b57cec5SDimitry Andric     }
29910b57cec5SDimitry Andric     }
29920b57cec5SDimitry Andric   }
29930b57cec5SDimitry Andric }
29940b57cec5SDimitry Andric 
29950b57cec5SDimitry Andric /// When we see the block for metadata, remember where it is and then skip it.
29960b57cec5SDimitry Andric /// This lets us lazily deserialize the metadata.
rememberAndSkipMetadata()29970b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipMetadata() {
29980b57cec5SDimitry Andric   // Save the current stream state.
29990b57cec5SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
30000b57cec5SDimitry Andric   DeferredMetadataInfo.push_back(CurBit);
30010b57cec5SDimitry Andric 
30020b57cec5SDimitry Andric   // Skip over the block for now.
30030b57cec5SDimitry Andric   if (Error Err = Stream.SkipBlock())
30040b57cec5SDimitry Andric     return Err;
30050b57cec5SDimitry Andric   return Error::success();
30060b57cec5SDimitry Andric }
30070b57cec5SDimitry Andric 
materializeMetadata()30080b57cec5SDimitry Andric Error BitcodeReader::materializeMetadata() {
30090b57cec5SDimitry Andric   for (uint64_t BitPos : DeferredMetadataInfo) {
30100b57cec5SDimitry Andric     // Move the bit stream to the saved position.
30110b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(BitPos))
30120b57cec5SDimitry Andric       return JumpFailed;
30130b57cec5SDimitry Andric     if (Error Err = MDLoader->parseModuleMetadata())
30140b57cec5SDimitry Andric       return Err;
30150b57cec5SDimitry Andric   }
30160b57cec5SDimitry Andric 
30170b57cec5SDimitry Andric   // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3018af732203SDimitry Andric   // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3019af732203SDimitry Andric   // multiple times.
3020af732203SDimitry Andric   if (!TheModule->getNamedMetadata("llvm.linker.options")) {
30210b57cec5SDimitry Andric     if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
30220b57cec5SDimitry Andric       NamedMDNode *LinkerOpts =
30230b57cec5SDimitry Andric           TheModule->getOrInsertNamedMetadata("llvm.linker.options");
30240b57cec5SDimitry Andric       for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
30250b57cec5SDimitry Andric         LinkerOpts->addOperand(cast<MDNode>(MDOptions));
30260b57cec5SDimitry Andric     }
3027af732203SDimitry Andric   }
30280b57cec5SDimitry Andric 
30290b57cec5SDimitry Andric   DeferredMetadataInfo.clear();
30300b57cec5SDimitry Andric   return Error::success();
30310b57cec5SDimitry Andric }
30320b57cec5SDimitry Andric 
setStripDebugInfo()30330b57cec5SDimitry Andric void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric /// When we see the block for a function body, remember where it is and then
30360b57cec5SDimitry Andric /// skip it.  This lets us lazily deserialize the functions.
rememberAndSkipFunctionBody()30370b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBody() {
30380b57cec5SDimitry Andric   // Get the function we are talking about.
30390b57cec5SDimitry Andric   if (FunctionsWithBodies.empty())
30400b57cec5SDimitry Andric     return error("Insufficient function protos");
30410b57cec5SDimitry Andric 
30420b57cec5SDimitry Andric   Function *Fn = FunctionsWithBodies.back();
30430b57cec5SDimitry Andric   FunctionsWithBodies.pop_back();
30440b57cec5SDimitry Andric 
30450b57cec5SDimitry Andric   // Save the current stream state.
30460b57cec5SDimitry Andric   uint64_t CurBit = Stream.GetCurrentBitNo();
30470b57cec5SDimitry Andric   assert(
30480b57cec5SDimitry Andric       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
30490b57cec5SDimitry Andric       "Mismatch between VST and scanned function offsets");
30500b57cec5SDimitry Andric   DeferredFunctionInfo[Fn] = CurBit;
30510b57cec5SDimitry Andric 
30520b57cec5SDimitry Andric   // Skip over the function block for now.
30530b57cec5SDimitry Andric   if (Error Err = Stream.SkipBlock())
30540b57cec5SDimitry Andric     return Err;
30550b57cec5SDimitry Andric   return Error::success();
30560b57cec5SDimitry Andric }
30570b57cec5SDimitry Andric 
globalCleanup()30580b57cec5SDimitry Andric Error BitcodeReader::globalCleanup() {
30590b57cec5SDimitry Andric   // Patch the initializers for globals and aliases up.
30600b57cec5SDimitry Andric   if (Error Err = resolveGlobalAndIndirectSymbolInits())
30610b57cec5SDimitry Andric     return Err;
30620b57cec5SDimitry Andric   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
30630b57cec5SDimitry Andric     return error("Malformed global initializer set");
30640b57cec5SDimitry Andric 
30650b57cec5SDimitry Andric   // Look for intrinsic functions which need to be upgraded at some point
30665ffd83dbSDimitry Andric   // and functions that need to have their function attributes upgraded.
30670b57cec5SDimitry Andric   for (Function &F : *TheModule) {
30680b57cec5SDimitry Andric     MDLoader->upgradeDebugIntrinsics(F);
30690b57cec5SDimitry Andric     Function *NewFn;
30700b57cec5SDimitry Andric     if (UpgradeIntrinsicFunction(&F, NewFn))
30710b57cec5SDimitry Andric       UpgradedIntrinsics[&F] = NewFn;
30720b57cec5SDimitry Andric     else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
30730b57cec5SDimitry Andric       // Some types could be renamed during loading if several modules are
30740b57cec5SDimitry Andric       // loaded in the same LLVMContext (LTO scenario). In this case we should
30750b57cec5SDimitry Andric       // remangle intrinsics names as well.
30760b57cec5SDimitry Andric       RemangledIntrinsics[&F] = Remangled.getValue();
30775ffd83dbSDimitry Andric     // Look for functions that rely on old function attribute behavior.
30785ffd83dbSDimitry Andric     UpgradeFunctionAttributes(F);
30790b57cec5SDimitry Andric   }
30800b57cec5SDimitry Andric 
30810b57cec5SDimitry Andric   // Look for global variables which need to be renamed.
30820b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
30830b57cec5SDimitry Andric   for (GlobalVariable &GV : TheModule->globals())
30840b57cec5SDimitry Andric     if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
30850b57cec5SDimitry Andric       UpgradedVariables.emplace_back(&GV, Upgraded);
30860b57cec5SDimitry Andric   for (auto &Pair : UpgradedVariables) {
30870b57cec5SDimitry Andric     Pair.first->eraseFromParent();
30880b57cec5SDimitry Andric     TheModule->getGlobalList().push_back(Pair.second);
30890b57cec5SDimitry Andric   }
30900b57cec5SDimitry Andric 
30910b57cec5SDimitry Andric   // Force deallocation of memory for these vectors to favor the client that
30920b57cec5SDimitry Andric   // want lazy deserialization.
30930b57cec5SDimitry Andric   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
30940b57cec5SDimitry Andric   std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
30950b57cec5SDimitry Andric       IndirectSymbolInits);
30960b57cec5SDimitry Andric   return Error::success();
30970b57cec5SDimitry Andric }
30980b57cec5SDimitry Andric 
30990b57cec5SDimitry Andric /// Support for lazy parsing of function bodies. This is required if we
31000b57cec5SDimitry Andric /// either have an old bitcode file without a VST forward declaration record,
31010b57cec5SDimitry Andric /// or if we have an anonymous function being materialized, since anonymous
31020b57cec5SDimitry Andric /// functions do not have a name and are therefore not in the VST.
rememberAndSkipFunctionBodies()31030b57cec5SDimitry Andric Error BitcodeReader::rememberAndSkipFunctionBodies() {
31040b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
31050b57cec5SDimitry Andric     return JumpFailed;
31060b57cec5SDimitry Andric 
31070b57cec5SDimitry Andric   if (Stream.AtEndOfStream())
31080b57cec5SDimitry Andric     return error("Could not find function in stream");
31090b57cec5SDimitry Andric 
31100b57cec5SDimitry Andric   if (!SeenFirstFunctionBody)
31110b57cec5SDimitry Andric     return error("Trying to materialize functions before seeing function blocks");
31120b57cec5SDimitry Andric 
31130b57cec5SDimitry Andric   // An old bitcode file with the symbol table at the end would have
31140b57cec5SDimitry Andric   // finished the parse greedily.
31150b57cec5SDimitry Andric   assert(SeenValueSymbolTable);
31160b57cec5SDimitry Andric 
31170b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
31180b57cec5SDimitry Andric 
31190b57cec5SDimitry Andric   while (true) {
31200b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
31210b57cec5SDimitry Andric     if (!MaybeEntry)
31220b57cec5SDimitry Andric       return MaybeEntry.takeError();
31230b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
31240b57cec5SDimitry Andric 
31250b57cec5SDimitry Andric     switch (Entry.Kind) {
31260b57cec5SDimitry Andric     default:
31270b57cec5SDimitry Andric       return error("Expect SubBlock");
31280b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
31290b57cec5SDimitry Andric       switch (Entry.ID) {
31300b57cec5SDimitry Andric       default:
31310b57cec5SDimitry Andric         return error("Expect function block");
31320b57cec5SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
31330b57cec5SDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
31340b57cec5SDimitry Andric           return Err;
31350b57cec5SDimitry Andric         NextUnreadBit = Stream.GetCurrentBitNo();
31360b57cec5SDimitry Andric         return Error::success();
31370b57cec5SDimitry Andric       }
31380b57cec5SDimitry Andric     }
31390b57cec5SDimitry Andric   }
31400b57cec5SDimitry Andric }
31410b57cec5SDimitry Andric 
readBlockInfo()31420b57cec5SDimitry Andric bool BitcodeReaderBase::readBlockInfo() {
31430b57cec5SDimitry Andric   Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
31440b57cec5SDimitry Andric       Stream.ReadBlockInfoBlock();
31450b57cec5SDimitry Andric   if (!MaybeNewBlockInfo)
31460b57cec5SDimitry Andric     return true; // FIXME Handle the error.
31470b57cec5SDimitry Andric   Optional<BitstreamBlockInfo> NewBlockInfo =
31480b57cec5SDimitry Andric       std::move(MaybeNewBlockInfo.get());
31490b57cec5SDimitry Andric   if (!NewBlockInfo)
31500b57cec5SDimitry Andric     return true;
31510b57cec5SDimitry Andric   BlockInfo = std::move(*NewBlockInfo);
31520b57cec5SDimitry Andric   return false;
31530b57cec5SDimitry Andric }
31540b57cec5SDimitry Andric 
parseComdatRecord(ArrayRef<uint64_t> Record)31550b57cec5SDimitry Andric Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
31560b57cec5SDimitry Andric   // v1: [selection_kind, name]
31570b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, selection_kind]
31580b57cec5SDimitry Andric   StringRef Name;
31590b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
31600b57cec5SDimitry Andric 
31610b57cec5SDimitry Andric   if (Record.empty())
31620b57cec5SDimitry Andric     return error("Invalid record");
31630b57cec5SDimitry Andric   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
31640b57cec5SDimitry Andric   std::string OldFormatName;
31650b57cec5SDimitry Andric   if (!UseStrtab) {
31660b57cec5SDimitry Andric     if (Record.size() < 2)
31670b57cec5SDimitry Andric       return error("Invalid record");
31680b57cec5SDimitry Andric     unsigned ComdatNameSize = Record[1];
31690b57cec5SDimitry Andric     OldFormatName.reserve(ComdatNameSize);
31700b57cec5SDimitry Andric     for (unsigned i = 0; i != ComdatNameSize; ++i)
31710b57cec5SDimitry Andric       OldFormatName += (char)Record[2 + i];
31720b57cec5SDimitry Andric     Name = OldFormatName;
31730b57cec5SDimitry Andric   }
31740b57cec5SDimitry Andric   Comdat *C = TheModule->getOrInsertComdat(Name);
31750b57cec5SDimitry Andric   C->setSelectionKind(SK);
31760b57cec5SDimitry Andric   ComdatList.push_back(C);
31770b57cec5SDimitry Andric   return Error::success();
31780b57cec5SDimitry Andric }
31790b57cec5SDimitry Andric 
inferDSOLocal(GlobalValue * GV)31800b57cec5SDimitry Andric static void inferDSOLocal(GlobalValue *GV) {
31810b57cec5SDimitry Andric   // infer dso_local from linkage and visibility if it is not encoded.
31820b57cec5SDimitry Andric   if (GV->hasLocalLinkage() ||
31830b57cec5SDimitry Andric       (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
31840b57cec5SDimitry Andric     GV->setDSOLocal(true);
31850b57cec5SDimitry Andric }
31860b57cec5SDimitry Andric 
parseGlobalVarRecord(ArrayRef<uint64_t> Record)31870b57cec5SDimitry Andric Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
31880b57cec5SDimitry Andric   // v1: [pointer type, isconst, initid, linkage, alignment, section,
31890b57cec5SDimitry Andric   // visibility, threadlocal, unnamed_addr, externally_initialized,
31900b57cec5SDimitry Andric   // dllstorageclass, comdat, attributes, preemption specifier,
31910b57cec5SDimitry Andric   // partition strtab offset, partition strtab size] (name in VST)
31920b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
31930b57cec5SDimitry Andric   StringRef Name;
31940b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
31950b57cec5SDimitry Andric 
31960b57cec5SDimitry Andric   if (Record.size() < 6)
31970b57cec5SDimitry Andric     return error("Invalid record");
3198*5f7ddb14SDimitry Andric   Type *Ty = getTypeByID(Record[0]);
31990b57cec5SDimitry Andric   if (!Ty)
32000b57cec5SDimitry Andric     return error("Invalid record");
32010b57cec5SDimitry Andric   bool isConstant = Record[1] & 1;
32020b57cec5SDimitry Andric   bool explicitType = Record[1] & 2;
32030b57cec5SDimitry Andric   unsigned AddressSpace;
32040b57cec5SDimitry Andric   if (explicitType) {
32050b57cec5SDimitry Andric     AddressSpace = Record[1] >> 2;
32060b57cec5SDimitry Andric   } else {
32070b57cec5SDimitry Andric     if (!Ty->isPointerTy())
32080b57cec5SDimitry Andric       return error("Invalid type for value");
32090b57cec5SDimitry Andric     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3210*5f7ddb14SDimitry Andric     Ty = cast<PointerType>(Ty)->getElementType();
32110b57cec5SDimitry Andric   }
32120b57cec5SDimitry Andric 
32130b57cec5SDimitry Andric   uint64_t RawLinkage = Record[3];
32140b57cec5SDimitry Andric   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
32158bcb0991SDimitry Andric   MaybeAlign Alignment;
32160b57cec5SDimitry Andric   if (Error Err = parseAlignmentValue(Record[4], Alignment))
32170b57cec5SDimitry Andric     return Err;
32180b57cec5SDimitry Andric   std::string Section;
32190b57cec5SDimitry Andric   if (Record[5]) {
32200b57cec5SDimitry Andric     if (Record[5] - 1 >= SectionTable.size())
32210b57cec5SDimitry Andric       return error("Invalid ID");
32220b57cec5SDimitry Andric     Section = SectionTable[Record[5] - 1];
32230b57cec5SDimitry Andric   }
32240b57cec5SDimitry Andric   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
32250b57cec5SDimitry Andric   // Local linkage must have default visibility.
32265ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
32270b57cec5SDimitry Andric   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
32280b57cec5SDimitry Andric     Visibility = getDecodedVisibility(Record[6]);
32290b57cec5SDimitry Andric 
32300b57cec5SDimitry Andric   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
32310b57cec5SDimitry Andric   if (Record.size() > 7)
32320b57cec5SDimitry Andric     TLM = getDecodedThreadLocalMode(Record[7]);
32330b57cec5SDimitry Andric 
32340b57cec5SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
32350b57cec5SDimitry Andric   if (Record.size() > 8)
32360b57cec5SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
32370b57cec5SDimitry Andric 
32380b57cec5SDimitry Andric   bool ExternallyInitialized = false;
32390b57cec5SDimitry Andric   if (Record.size() > 9)
32400b57cec5SDimitry Andric     ExternallyInitialized = Record[9];
32410b57cec5SDimitry Andric 
32420b57cec5SDimitry Andric   GlobalVariable *NewGV =
32430b57cec5SDimitry Andric       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
32440b57cec5SDimitry Andric                          nullptr, TLM, AddressSpace, ExternallyInitialized);
32450b57cec5SDimitry Andric   NewGV->setAlignment(Alignment);
32460b57cec5SDimitry Andric   if (!Section.empty())
32470b57cec5SDimitry Andric     NewGV->setSection(Section);
32480b57cec5SDimitry Andric   NewGV->setVisibility(Visibility);
32490b57cec5SDimitry Andric   NewGV->setUnnamedAddr(UnnamedAddr);
32500b57cec5SDimitry Andric 
32510b57cec5SDimitry Andric   if (Record.size() > 10)
32520b57cec5SDimitry Andric     NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
32530b57cec5SDimitry Andric   else
32540b57cec5SDimitry Andric     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
32550b57cec5SDimitry Andric 
3256*5f7ddb14SDimitry Andric   ValueList.push_back(NewGV);
32570b57cec5SDimitry Andric 
32580b57cec5SDimitry Andric   // Remember which value to use for the global initializer.
32590b57cec5SDimitry Andric   if (unsigned InitID = Record[2])
32600b57cec5SDimitry Andric     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
32610b57cec5SDimitry Andric 
32620b57cec5SDimitry Andric   if (Record.size() > 11) {
32630b57cec5SDimitry Andric     if (unsigned ComdatID = Record[11]) {
32640b57cec5SDimitry Andric       if (ComdatID > ComdatList.size())
32650b57cec5SDimitry Andric         return error("Invalid global variable comdat ID");
32660b57cec5SDimitry Andric       NewGV->setComdat(ComdatList[ComdatID - 1]);
32670b57cec5SDimitry Andric     }
32680b57cec5SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
32690b57cec5SDimitry Andric     NewGV->setComdat(reinterpret_cast<Comdat *>(1));
32700b57cec5SDimitry Andric   }
32710b57cec5SDimitry Andric 
32720b57cec5SDimitry Andric   if (Record.size() > 12) {
32730b57cec5SDimitry Andric     auto AS = getAttributes(Record[12]).getFnAttributes();
32740b57cec5SDimitry Andric     NewGV->setAttributes(AS);
32750b57cec5SDimitry Andric   }
32760b57cec5SDimitry Andric 
32770b57cec5SDimitry Andric   if (Record.size() > 13) {
32780b57cec5SDimitry Andric     NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
32790b57cec5SDimitry Andric   }
32800b57cec5SDimitry Andric   inferDSOLocal(NewGV);
32810b57cec5SDimitry Andric 
32820b57cec5SDimitry Andric   // Check whether we have enough values to read a partition name.
32830b57cec5SDimitry Andric   if (Record.size() > 15)
32840b57cec5SDimitry Andric     NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
32850b57cec5SDimitry Andric 
32860b57cec5SDimitry Andric   return Error::success();
32870b57cec5SDimitry Andric }
32880b57cec5SDimitry Andric 
parseFunctionRecord(ArrayRef<uint64_t> Record)32890b57cec5SDimitry Andric Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
32900b57cec5SDimitry Andric   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
32910b57cec5SDimitry Andric   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
32920b57cec5SDimitry Andric   // prefixdata,  personalityfn, preemption specifier, addrspace] (name in VST)
32930b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
32940b57cec5SDimitry Andric   StringRef Name;
32950b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
32960b57cec5SDimitry Andric 
32970b57cec5SDimitry Andric   if (Record.size() < 8)
32980b57cec5SDimitry Andric     return error("Invalid record");
3299*5f7ddb14SDimitry Andric   Type *FTy = getTypeByID(Record[0]);
33000b57cec5SDimitry Andric   if (!FTy)
33010b57cec5SDimitry Andric     return error("Invalid record");
3302*5f7ddb14SDimitry Andric   if (auto *PTy = dyn_cast<PointerType>(FTy))
3303*5f7ddb14SDimitry Andric     FTy = PTy->getElementType();
33040b57cec5SDimitry Andric 
33050b57cec5SDimitry Andric   if (!isa<FunctionType>(FTy))
33060b57cec5SDimitry Andric     return error("Invalid type for value");
33070b57cec5SDimitry Andric   auto CC = static_cast<CallingConv::ID>(Record[1]);
33080b57cec5SDimitry Andric   if (CC & ~CallingConv::MaxID)
33090b57cec5SDimitry Andric     return error("Invalid calling convention ID");
33100b57cec5SDimitry Andric 
33110b57cec5SDimitry Andric   unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
33120b57cec5SDimitry Andric   if (Record.size() > 16)
33130b57cec5SDimitry Andric     AddrSpace = Record[16];
33140b57cec5SDimitry Andric 
33150b57cec5SDimitry Andric   Function *Func =
33160b57cec5SDimitry Andric       Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
33170b57cec5SDimitry Andric                        AddrSpace, Name, TheModule);
33180b57cec5SDimitry Andric 
3319*5f7ddb14SDimitry Andric   assert(Func->getFunctionType() == FTy &&
33200b57cec5SDimitry Andric          "Incorrect fully specified type provided for function");
3321*5f7ddb14SDimitry Andric   FunctionTypes[Func] = cast<FunctionType>(FTy);
33220b57cec5SDimitry Andric 
33230b57cec5SDimitry Andric   Func->setCallingConv(CC);
33240b57cec5SDimitry Andric   bool isProto = Record[2];
33250b57cec5SDimitry Andric   uint64_t RawLinkage = Record[3];
33260b57cec5SDimitry Andric   Func->setLinkage(getDecodedLinkage(RawLinkage));
33270b57cec5SDimitry Andric   Func->setAttributes(getAttributes(Record[4]));
33280b57cec5SDimitry Andric 
3329af732203SDimitry Andric   // Upgrade any old-style byval or sret without a type by propagating the
3330af732203SDimitry Andric   // argument's pointee type. There should be no opaque pointers where the byval
3331af732203SDimitry Andric   // type is implicit.
33320b57cec5SDimitry Andric   for (unsigned i = 0; i != Func->arg_size(); ++i) {
3333*5f7ddb14SDimitry Andric     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3334*5f7ddb14SDimitry Andric                                      Attribute::InAlloca}) {
3335af732203SDimitry Andric       if (!Func->hasParamAttribute(i, Kind))
33360b57cec5SDimitry Andric         continue;
33370b57cec5SDimitry Andric 
3338*5f7ddb14SDimitry Andric       if (Func->getParamAttribute(i, Kind).getValueAsType())
3339*5f7ddb14SDimitry Andric         continue;
3340*5f7ddb14SDimitry Andric 
3341af732203SDimitry Andric       Func->removeParamAttr(i, Kind);
3342af732203SDimitry Andric 
3343*5f7ddb14SDimitry Andric       Type *PTy = cast<FunctionType>(FTy)->getParamType(i);
3344*5f7ddb14SDimitry Andric       Type *PtrEltTy = cast<PointerType>(PTy)->getElementType();
3345*5f7ddb14SDimitry Andric       Attribute NewAttr;
3346*5f7ddb14SDimitry Andric       switch (Kind) {
3347*5f7ddb14SDimitry Andric       case Attribute::ByVal:
3348*5f7ddb14SDimitry Andric         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3349*5f7ddb14SDimitry Andric         break;
3350*5f7ddb14SDimitry Andric       case Attribute::StructRet:
3351*5f7ddb14SDimitry Andric         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3352*5f7ddb14SDimitry Andric         break;
3353*5f7ddb14SDimitry Andric       case Attribute::InAlloca:
3354*5f7ddb14SDimitry Andric         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3355*5f7ddb14SDimitry Andric         break;
3356*5f7ddb14SDimitry Andric       default:
3357*5f7ddb14SDimitry Andric         llvm_unreachable("not an upgraded type attribute");
3358*5f7ddb14SDimitry Andric       }
3359*5f7ddb14SDimitry Andric 
3360af732203SDimitry Andric       Func->addParamAttr(i, NewAttr);
3361af732203SDimitry Andric     }
33620b57cec5SDimitry Andric   }
33630b57cec5SDimitry Andric 
33648bcb0991SDimitry Andric   MaybeAlign Alignment;
33650b57cec5SDimitry Andric   if (Error Err = parseAlignmentValue(Record[5], Alignment))
33660b57cec5SDimitry Andric     return Err;
33670b57cec5SDimitry Andric   Func->setAlignment(Alignment);
33680b57cec5SDimitry Andric   if (Record[6]) {
33690b57cec5SDimitry Andric     if (Record[6] - 1 >= SectionTable.size())
33700b57cec5SDimitry Andric       return error("Invalid ID");
33710b57cec5SDimitry Andric     Func->setSection(SectionTable[Record[6] - 1]);
33720b57cec5SDimitry Andric   }
33730b57cec5SDimitry Andric   // Local linkage must have default visibility.
33745ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
33750b57cec5SDimitry Andric   if (!Func->hasLocalLinkage())
33760b57cec5SDimitry Andric     Func->setVisibility(getDecodedVisibility(Record[7]));
33770b57cec5SDimitry Andric   if (Record.size() > 8 && Record[8]) {
33780b57cec5SDimitry Andric     if (Record[8] - 1 >= GCTable.size())
33790b57cec5SDimitry Andric       return error("Invalid ID");
33800b57cec5SDimitry Andric     Func->setGC(GCTable[Record[8] - 1]);
33810b57cec5SDimitry Andric   }
33820b57cec5SDimitry Andric   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
33830b57cec5SDimitry Andric   if (Record.size() > 9)
33840b57cec5SDimitry Andric     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
33850b57cec5SDimitry Andric   Func->setUnnamedAddr(UnnamedAddr);
33860b57cec5SDimitry Andric   if (Record.size() > 10 && Record[10] != 0)
33870b57cec5SDimitry Andric     FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
33880b57cec5SDimitry Andric 
33890b57cec5SDimitry Andric   if (Record.size() > 11)
33900b57cec5SDimitry Andric     Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
33910b57cec5SDimitry Andric   else
33920b57cec5SDimitry Andric     upgradeDLLImportExportLinkage(Func, RawLinkage);
33930b57cec5SDimitry Andric 
33940b57cec5SDimitry Andric   if (Record.size() > 12) {
33950b57cec5SDimitry Andric     if (unsigned ComdatID = Record[12]) {
33960b57cec5SDimitry Andric       if (ComdatID > ComdatList.size())
33970b57cec5SDimitry Andric         return error("Invalid function comdat ID");
33980b57cec5SDimitry Andric       Func->setComdat(ComdatList[ComdatID - 1]);
33990b57cec5SDimitry Andric     }
34000b57cec5SDimitry Andric   } else if (hasImplicitComdat(RawLinkage)) {
34010b57cec5SDimitry Andric     Func->setComdat(reinterpret_cast<Comdat *>(1));
34020b57cec5SDimitry Andric   }
34030b57cec5SDimitry Andric 
34040b57cec5SDimitry Andric   if (Record.size() > 13 && Record[13] != 0)
34050b57cec5SDimitry Andric     FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
34060b57cec5SDimitry Andric 
34070b57cec5SDimitry Andric   if (Record.size() > 14 && Record[14] != 0)
34080b57cec5SDimitry Andric     FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
34090b57cec5SDimitry Andric 
34100b57cec5SDimitry Andric   if (Record.size() > 15) {
34110b57cec5SDimitry Andric     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
34120b57cec5SDimitry Andric   }
34130b57cec5SDimitry Andric   inferDSOLocal(Func);
34140b57cec5SDimitry Andric 
34150b57cec5SDimitry Andric   // Record[16] is the address space number.
34160b57cec5SDimitry Andric 
3417*5f7ddb14SDimitry Andric   // Check whether we have enough values to read a partition name. Also make
3418*5f7ddb14SDimitry Andric   // sure Strtab has enough values.
3419*5f7ddb14SDimitry Andric   if (Record.size() > 18 && Strtab.data() &&
3420*5f7ddb14SDimitry Andric       Record[17] + Record[18] <= Strtab.size()) {
34210b57cec5SDimitry Andric     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
3422*5f7ddb14SDimitry Andric   }
34230b57cec5SDimitry Andric 
3424*5f7ddb14SDimitry Andric   ValueList.push_back(Func);
34250b57cec5SDimitry Andric 
34260b57cec5SDimitry Andric   // If this is a function with a body, remember the prototype we are
34270b57cec5SDimitry Andric   // creating now, so that we can match up the body with them later.
34280b57cec5SDimitry Andric   if (!isProto) {
34290b57cec5SDimitry Andric     Func->setIsMaterializable(true);
34300b57cec5SDimitry Andric     FunctionsWithBodies.push_back(Func);
34310b57cec5SDimitry Andric     DeferredFunctionInfo[Func] = 0;
34320b57cec5SDimitry Andric   }
34330b57cec5SDimitry Andric   return Error::success();
34340b57cec5SDimitry Andric }
34350b57cec5SDimitry Andric 
parseGlobalIndirectSymbolRecord(unsigned BitCode,ArrayRef<uint64_t> Record)34360b57cec5SDimitry Andric Error BitcodeReader::parseGlobalIndirectSymbolRecord(
34370b57cec5SDimitry Andric     unsigned BitCode, ArrayRef<uint64_t> Record) {
34380b57cec5SDimitry Andric   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
34390b57cec5SDimitry Andric   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
34400b57cec5SDimitry Andric   // dllstorageclass, threadlocal, unnamed_addr,
34410b57cec5SDimitry Andric   // preemption specifier] (name in VST)
34420b57cec5SDimitry Andric   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
34430b57cec5SDimitry Andric   // visibility, dllstorageclass, threadlocal, unnamed_addr,
34440b57cec5SDimitry Andric   // preemption specifier] (name in VST)
34450b57cec5SDimitry Andric   // v2: [strtab_offset, strtab_size, v1]
34460b57cec5SDimitry Andric   StringRef Name;
34470b57cec5SDimitry Andric   std::tie(Name, Record) = readNameFromStrtab(Record);
34480b57cec5SDimitry Andric 
34490b57cec5SDimitry Andric   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
34500b57cec5SDimitry Andric   if (Record.size() < (3 + (unsigned)NewRecord))
34510b57cec5SDimitry Andric     return error("Invalid record");
34520b57cec5SDimitry Andric   unsigned OpNum = 0;
3453*5f7ddb14SDimitry Andric   Type *Ty = getTypeByID(Record[OpNum++]);
34540b57cec5SDimitry Andric   if (!Ty)
34550b57cec5SDimitry Andric     return error("Invalid record");
34560b57cec5SDimitry Andric 
34570b57cec5SDimitry Andric   unsigned AddrSpace;
34580b57cec5SDimitry Andric   if (!NewRecord) {
34590b57cec5SDimitry Andric     auto *PTy = dyn_cast<PointerType>(Ty);
34600b57cec5SDimitry Andric     if (!PTy)
34610b57cec5SDimitry Andric       return error("Invalid type for value");
3462*5f7ddb14SDimitry Andric     Ty = PTy->getElementType();
34630b57cec5SDimitry Andric     AddrSpace = PTy->getAddressSpace();
34640b57cec5SDimitry Andric   } else {
34650b57cec5SDimitry Andric     AddrSpace = Record[OpNum++];
34660b57cec5SDimitry Andric   }
34670b57cec5SDimitry Andric 
34680b57cec5SDimitry Andric   auto Val = Record[OpNum++];
34690b57cec5SDimitry Andric   auto Linkage = Record[OpNum++];
34700b57cec5SDimitry Andric   GlobalIndirectSymbol *NewGA;
34710b57cec5SDimitry Andric   if (BitCode == bitc::MODULE_CODE_ALIAS ||
34720b57cec5SDimitry Andric       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
34730b57cec5SDimitry Andric     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
34740b57cec5SDimitry Andric                                 TheModule);
34750b57cec5SDimitry Andric   else
34760b57cec5SDimitry Andric     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
34770b57cec5SDimitry Andric                                 nullptr, TheModule);
34780b57cec5SDimitry Andric 
34790b57cec5SDimitry Andric   // Local linkage must have default visibility.
34805ffd83dbSDimitry Andric   // auto-upgrade `hidden` and `protected` for old bitcode.
34810b57cec5SDimitry Andric   if (OpNum != Record.size()) {
34820b57cec5SDimitry Andric     auto VisInd = OpNum++;
34830b57cec5SDimitry Andric     if (!NewGA->hasLocalLinkage())
34840b57cec5SDimitry Andric       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
34850b57cec5SDimitry Andric   }
34860b57cec5SDimitry Andric   if (BitCode == bitc::MODULE_CODE_ALIAS ||
34870b57cec5SDimitry Andric       BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
34880b57cec5SDimitry Andric     if (OpNum != Record.size())
34890b57cec5SDimitry Andric       NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
34900b57cec5SDimitry Andric     else
34910b57cec5SDimitry Andric       upgradeDLLImportExportLinkage(NewGA, Linkage);
34920b57cec5SDimitry Andric     if (OpNum != Record.size())
34930b57cec5SDimitry Andric       NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
34940b57cec5SDimitry Andric     if (OpNum != Record.size())
34950b57cec5SDimitry Andric       NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
34960b57cec5SDimitry Andric   }
34970b57cec5SDimitry Andric   if (OpNum != Record.size())
34980b57cec5SDimitry Andric     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
34990b57cec5SDimitry Andric   inferDSOLocal(NewGA);
35000b57cec5SDimitry Andric 
35010b57cec5SDimitry Andric   // Check whether we have enough values to read a partition name.
35020b57cec5SDimitry Andric   if (OpNum + 1 < Record.size()) {
35030b57cec5SDimitry Andric     NewGA->setPartition(
35040b57cec5SDimitry Andric         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
35050b57cec5SDimitry Andric     OpNum += 2;
35060b57cec5SDimitry Andric   }
35070b57cec5SDimitry Andric 
3508*5f7ddb14SDimitry Andric   ValueList.push_back(NewGA);
35090b57cec5SDimitry Andric   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
35100b57cec5SDimitry Andric   return Error::success();
35110b57cec5SDimitry Andric }
35120b57cec5SDimitry Andric 
parseModule(uint64_t ResumeBit,bool ShouldLazyLoadMetadata,DataLayoutCallbackTy DataLayoutCallback)35130b57cec5SDimitry Andric Error BitcodeReader::parseModule(uint64_t ResumeBit,
35145ffd83dbSDimitry Andric                                  bool ShouldLazyLoadMetadata,
35155ffd83dbSDimitry Andric                                  DataLayoutCallbackTy DataLayoutCallback) {
35160b57cec5SDimitry Andric   if (ResumeBit) {
35170b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
35180b57cec5SDimitry Andric       return JumpFailed;
35190b57cec5SDimitry Andric   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
35200b57cec5SDimitry Andric     return Err;
35210b57cec5SDimitry Andric 
35220b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
35230b57cec5SDimitry Andric 
35245ffd83dbSDimitry Andric   // Parts of bitcode parsing depend on the datalayout.  Make sure we
35255ffd83dbSDimitry Andric   // finalize the datalayout before we run any of that code.
35265ffd83dbSDimitry Andric   bool ResolvedDataLayout = false;
35275ffd83dbSDimitry Andric   auto ResolveDataLayout = [&] {
35285ffd83dbSDimitry Andric     if (ResolvedDataLayout)
35295ffd83dbSDimitry Andric       return;
35305ffd83dbSDimitry Andric 
35315ffd83dbSDimitry Andric     // datalayout and triple can't be parsed after this point.
35325ffd83dbSDimitry Andric     ResolvedDataLayout = true;
35335ffd83dbSDimitry Andric 
35345ffd83dbSDimitry Andric     // Upgrade data layout string.
35355ffd83dbSDimitry Andric     std::string DL = llvm::UpgradeDataLayoutString(
35365ffd83dbSDimitry Andric         TheModule->getDataLayoutStr(), TheModule->getTargetTriple());
35375ffd83dbSDimitry Andric     TheModule->setDataLayout(DL);
35385ffd83dbSDimitry Andric 
35395ffd83dbSDimitry Andric     if (auto LayoutOverride =
35405ffd83dbSDimitry Andric             DataLayoutCallback(TheModule->getTargetTriple()))
35415ffd83dbSDimitry Andric       TheModule->setDataLayout(*LayoutOverride);
35425ffd83dbSDimitry Andric   };
35435ffd83dbSDimitry Andric 
35440b57cec5SDimitry Andric   // Read all the records for this module.
35450b57cec5SDimitry Andric   while (true) {
35460b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
35470b57cec5SDimitry Andric     if (!MaybeEntry)
35480b57cec5SDimitry Andric       return MaybeEntry.takeError();
35490b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
35500b57cec5SDimitry Andric 
35510b57cec5SDimitry Andric     switch (Entry.Kind) {
35520b57cec5SDimitry Andric     case BitstreamEntry::Error:
35530b57cec5SDimitry Andric       return error("Malformed block");
35540b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
35555ffd83dbSDimitry Andric       ResolveDataLayout();
35560b57cec5SDimitry Andric       return globalCleanup();
35570b57cec5SDimitry Andric 
35580b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
35590b57cec5SDimitry Andric       switch (Entry.ID) {
35600b57cec5SDimitry Andric       default:  // Skip unknown content.
35610b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
35620b57cec5SDimitry Andric           return Err;
35630b57cec5SDimitry Andric         break;
35640b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
35650b57cec5SDimitry Andric         if (readBlockInfo())
35660b57cec5SDimitry Andric           return error("Malformed block");
35670b57cec5SDimitry Andric         break;
35680b57cec5SDimitry Andric       case bitc::PARAMATTR_BLOCK_ID:
35690b57cec5SDimitry Andric         if (Error Err = parseAttributeBlock())
35700b57cec5SDimitry Andric           return Err;
35710b57cec5SDimitry Andric         break;
35720b57cec5SDimitry Andric       case bitc::PARAMATTR_GROUP_BLOCK_ID:
35730b57cec5SDimitry Andric         if (Error Err = parseAttributeGroupBlock())
35740b57cec5SDimitry Andric           return Err;
35750b57cec5SDimitry Andric         break;
35760b57cec5SDimitry Andric       case bitc::TYPE_BLOCK_ID_NEW:
35770b57cec5SDimitry Andric         if (Error Err = parseTypeTable())
35780b57cec5SDimitry Andric           return Err;
35790b57cec5SDimitry Andric         break;
35800b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
35810b57cec5SDimitry Andric         if (!SeenValueSymbolTable) {
35820b57cec5SDimitry Andric           // Either this is an old form VST without function index and an
35830b57cec5SDimitry Andric           // associated VST forward declaration record (which would have caused
35840b57cec5SDimitry Andric           // the VST to be jumped to and parsed before it was encountered
35850b57cec5SDimitry Andric           // normally in the stream), or there were no function blocks to
35860b57cec5SDimitry Andric           // trigger an earlier parsing of the VST.
35870b57cec5SDimitry Andric           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
35880b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable())
35890b57cec5SDimitry Andric             return Err;
35900b57cec5SDimitry Andric           SeenValueSymbolTable = true;
35910b57cec5SDimitry Andric         } else {
35920b57cec5SDimitry Andric           // We must have had a VST forward declaration record, which caused
35930b57cec5SDimitry Andric           // the parser to jump to and parse the VST earlier.
35940b57cec5SDimitry Andric           assert(VSTOffset > 0);
35950b57cec5SDimitry Andric           if (Error Err = Stream.SkipBlock())
35960b57cec5SDimitry Andric             return Err;
35970b57cec5SDimitry Andric         }
35980b57cec5SDimitry Andric         break;
35990b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
36000b57cec5SDimitry Andric         if (Error Err = parseConstants())
36010b57cec5SDimitry Andric           return Err;
36020b57cec5SDimitry Andric         if (Error Err = resolveGlobalAndIndirectSymbolInits())
36030b57cec5SDimitry Andric           return Err;
36040b57cec5SDimitry Andric         break;
36050b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
36060b57cec5SDimitry Andric         if (ShouldLazyLoadMetadata) {
36070b57cec5SDimitry Andric           if (Error Err = rememberAndSkipMetadata())
36080b57cec5SDimitry Andric             return Err;
36090b57cec5SDimitry Andric           break;
36100b57cec5SDimitry Andric         }
36110b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
36120b57cec5SDimitry Andric         if (Error Err = MDLoader->parseModuleMetadata())
36130b57cec5SDimitry Andric           return Err;
36140b57cec5SDimitry Andric         break;
36150b57cec5SDimitry Andric       case bitc::METADATA_KIND_BLOCK_ID:
36160b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataKinds())
36170b57cec5SDimitry Andric           return Err;
36180b57cec5SDimitry Andric         break;
36190b57cec5SDimitry Andric       case bitc::FUNCTION_BLOCK_ID:
36205ffd83dbSDimitry Andric         ResolveDataLayout();
36215ffd83dbSDimitry Andric 
36220b57cec5SDimitry Andric         // If this is the first function body we've seen, reverse the
36230b57cec5SDimitry Andric         // FunctionsWithBodies list.
36240b57cec5SDimitry Andric         if (!SeenFirstFunctionBody) {
36250b57cec5SDimitry Andric           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
36260b57cec5SDimitry Andric           if (Error Err = globalCleanup())
36270b57cec5SDimitry Andric             return Err;
36280b57cec5SDimitry Andric           SeenFirstFunctionBody = true;
36290b57cec5SDimitry Andric         }
36300b57cec5SDimitry Andric 
36310b57cec5SDimitry Andric         if (VSTOffset > 0) {
36320b57cec5SDimitry Andric           // If we have a VST forward declaration record, make sure we
36330b57cec5SDimitry Andric           // parse the VST now if we haven't already. It is needed to
36340b57cec5SDimitry Andric           // set up the DeferredFunctionInfo vector for lazy reading.
36350b57cec5SDimitry Andric           if (!SeenValueSymbolTable) {
36360b57cec5SDimitry Andric             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
36370b57cec5SDimitry Andric               return Err;
36380b57cec5SDimitry Andric             SeenValueSymbolTable = true;
36390b57cec5SDimitry Andric             // Fall through so that we record the NextUnreadBit below.
36400b57cec5SDimitry Andric             // This is necessary in case we have an anonymous function that
36410b57cec5SDimitry Andric             // is later materialized. Since it will not have a VST entry we
36420b57cec5SDimitry Andric             // need to fall back to the lazy parse to find its offset.
36430b57cec5SDimitry Andric           } else {
36440b57cec5SDimitry Andric             // If we have a VST forward declaration record, but have already
36450b57cec5SDimitry Andric             // parsed the VST (just above, when the first function body was
36460b57cec5SDimitry Andric             // encountered here), then we are resuming the parse after
36470b57cec5SDimitry Andric             // materializing functions. The ResumeBit points to the
36480b57cec5SDimitry Andric             // start of the last function block recorded in the
36490b57cec5SDimitry Andric             // DeferredFunctionInfo map. Skip it.
36500b57cec5SDimitry Andric             if (Error Err = Stream.SkipBlock())
36510b57cec5SDimitry Andric               return Err;
36520b57cec5SDimitry Andric             continue;
36530b57cec5SDimitry Andric           }
36540b57cec5SDimitry Andric         }
36550b57cec5SDimitry Andric 
36560b57cec5SDimitry Andric         // Support older bitcode files that did not have the function
36570b57cec5SDimitry Andric         // index in the VST, nor a VST forward declaration record, as
36580b57cec5SDimitry Andric         // well as anonymous functions that do not have VST entries.
36590b57cec5SDimitry Andric         // Build the DeferredFunctionInfo vector on the fly.
36600b57cec5SDimitry Andric         if (Error Err = rememberAndSkipFunctionBody())
36610b57cec5SDimitry Andric           return Err;
36620b57cec5SDimitry Andric 
36630b57cec5SDimitry Andric         // Suspend parsing when we reach the function bodies. Subsequent
36640b57cec5SDimitry Andric         // materialization calls will resume it when necessary. If the bitcode
36650b57cec5SDimitry Andric         // file is old, the symbol table will be at the end instead and will not
36660b57cec5SDimitry Andric         // have been seen yet. In this case, just finish the parse now.
36670b57cec5SDimitry Andric         if (SeenValueSymbolTable) {
36680b57cec5SDimitry Andric           NextUnreadBit = Stream.GetCurrentBitNo();
36690b57cec5SDimitry Andric           // After the VST has been parsed, we need to make sure intrinsic name
36700b57cec5SDimitry Andric           // are auto-upgraded.
36710b57cec5SDimitry Andric           return globalCleanup();
36720b57cec5SDimitry Andric         }
36730b57cec5SDimitry Andric         break;
36740b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
36750b57cec5SDimitry Andric         if (Error Err = parseUseLists())
36760b57cec5SDimitry Andric           return Err;
36770b57cec5SDimitry Andric         break;
36780b57cec5SDimitry Andric       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
36790b57cec5SDimitry Andric         if (Error Err = parseOperandBundleTags())
36800b57cec5SDimitry Andric           return Err;
36810b57cec5SDimitry Andric         break;
36820b57cec5SDimitry Andric       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
36830b57cec5SDimitry Andric         if (Error Err = parseSyncScopeNames())
36840b57cec5SDimitry Andric           return Err;
36850b57cec5SDimitry Andric         break;
36860b57cec5SDimitry Andric       }
36870b57cec5SDimitry Andric       continue;
36880b57cec5SDimitry Andric 
36890b57cec5SDimitry Andric     case BitstreamEntry::Record:
36900b57cec5SDimitry Andric       // The interesting case.
36910b57cec5SDimitry Andric       break;
36920b57cec5SDimitry Andric     }
36930b57cec5SDimitry Andric 
36940b57cec5SDimitry Andric     // Read a record.
36950b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
36960b57cec5SDimitry Andric     if (!MaybeBitCode)
36970b57cec5SDimitry Andric       return MaybeBitCode.takeError();
36980b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
36990b57cec5SDimitry Andric     default: break;  // Default behavior, ignore unknown content.
37000b57cec5SDimitry Andric     case bitc::MODULE_CODE_VERSION: {
37010b57cec5SDimitry Andric       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
37020b57cec5SDimitry Andric       if (!VersionOrErr)
37030b57cec5SDimitry Andric         return VersionOrErr.takeError();
37040b57cec5SDimitry Andric       UseRelativeIDs = *VersionOrErr >= 1;
37050b57cec5SDimitry Andric       break;
37060b57cec5SDimitry Andric     }
37070b57cec5SDimitry Andric     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
37085ffd83dbSDimitry Andric       if (ResolvedDataLayout)
37095ffd83dbSDimitry Andric         return error("target triple too late in module");
37100b57cec5SDimitry Andric       std::string S;
37110b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
37120b57cec5SDimitry Andric         return error("Invalid record");
37130b57cec5SDimitry Andric       TheModule->setTargetTriple(S);
37140b57cec5SDimitry Andric       break;
37150b57cec5SDimitry Andric     }
37160b57cec5SDimitry Andric     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
37175ffd83dbSDimitry Andric       if (ResolvedDataLayout)
37185ffd83dbSDimitry Andric         return error("datalayout too late in module");
37190b57cec5SDimitry Andric       std::string S;
37200b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
37210b57cec5SDimitry Andric         return error("Invalid record");
37220b57cec5SDimitry Andric       TheModule->setDataLayout(S);
37230b57cec5SDimitry Andric       break;
37240b57cec5SDimitry Andric     }
37250b57cec5SDimitry Andric     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
37260b57cec5SDimitry Andric       std::string S;
37270b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
37280b57cec5SDimitry Andric         return error("Invalid record");
37290b57cec5SDimitry Andric       TheModule->setModuleInlineAsm(S);
37300b57cec5SDimitry Andric       break;
37310b57cec5SDimitry Andric     }
37320b57cec5SDimitry Andric     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
37335ffd83dbSDimitry Andric       // Deprecated, but still needed to read old bitcode files.
37340b57cec5SDimitry Andric       std::string S;
37350b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
37360b57cec5SDimitry Andric         return error("Invalid record");
37370b57cec5SDimitry Andric       // Ignore value.
37380b57cec5SDimitry Andric       break;
37390b57cec5SDimitry Andric     }
37400b57cec5SDimitry Andric     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
37410b57cec5SDimitry Andric       std::string S;
37420b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
37430b57cec5SDimitry Andric         return error("Invalid record");
37440b57cec5SDimitry Andric       SectionTable.push_back(S);
37450b57cec5SDimitry Andric       break;
37460b57cec5SDimitry Andric     }
37470b57cec5SDimitry Andric     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
37480b57cec5SDimitry Andric       std::string S;
37490b57cec5SDimitry Andric       if (convertToString(Record, 0, S))
37500b57cec5SDimitry Andric         return error("Invalid record");
37510b57cec5SDimitry Andric       GCTable.push_back(S);
37520b57cec5SDimitry Andric       break;
37530b57cec5SDimitry Andric     }
37540b57cec5SDimitry Andric     case bitc::MODULE_CODE_COMDAT:
37550b57cec5SDimitry Andric       if (Error Err = parseComdatRecord(Record))
37560b57cec5SDimitry Andric         return Err;
37570b57cec5SDimitry Andric       break;
37580b57cec5SDimitry Andric     case bitc::MODULE_CODE_GLOBALVAR:
37590b57cec5SDimitry Andric       if (Error Err = parseGlobalVarRecord(Record))
37600b57cec5SDimitry Andric         return Err;
37610b57cec5SDimitry Andric       break;
37620b57cec5SDimitry Andric     case bitc::MODULE_CODE_FUNCTION:
37635ffd83dbSDimitry Andric       ResolveDataLayout();
37640b57cec5SDimitry Andric       if (Error Err = parseFunctionRecord(Record))
37650b57cec5SDimitry Andric         return Err;
37660b57cec5SDimitry Andric       break;
37670b57cec5SDimitry Andric     case bitc::MODULE_CODE_IFUNC:
37680b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS:
37690b57cec5SDimitry Andric     case bitc::MODULE_CODE_ALIAS_OLD:
37700b57cec5SDimitry Andric       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
37710b57cec5SDimitry Andric         return Err;
37720b57cec5SDimitry Andric       break;
37730b57cec5SDimitry Andric     /// MODULE_CODE_VSTOFFSET: [offset]
37740b57cec5SDimitry Andric     case bitc::MODULE_CODE_VSTOFFSET:
3775af732203SDimitry Andric       if (Record.empty())
37760b57cec5SDimitry Andric         return error("Invalid record");
37770b57cec5SDimitry Andric       // Note that we subtract 1 here because the offset is relative to one word
37780b57cec5SDimitry Andric       // before the start of the identification or module block, which was
37790b57cec5SDimitry Andric       // historically always the start of the regular bitcode header.
37800b57cec5SDimitry Andric       VSTOffset = Record[0] - 1;
37810b57cec5SDimitry Andric       break;
37820b57cec5SDimitry Andric     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
37830b57cec5SDimitry Andric     case bitc::MODULE_CODE_SOURCE_FILENAME:
37840b57cec5SDimitry Andric       SmallString<128> ValueName;
37850b57cec5SDimitry Andric       if (convertToString(Record, 0, ValueName))
37860b57cec5SDimitry Andric         return error("Invalid record");
37870b57cec5SDimitry Andric       TheModule->setSourceFileName(ValueName);
37880b57cec5SDimitry Andric       break;
37890b57cec5SDimitry Andric     }
37900b57cec5SDimitry Andric     Record.clear();
37910b57cec5SDimitry Andric   }
37920b57cec5SDimitry Andric }
37930b57cec5SDimitry Andric 
parseBitcodeInto(Module * M,bool ShouldLazyLoadMetadata,bool IsImporting,DataLayoutCallbackTy DataLayoutCallback)37940b57cec5SDimitry Andric Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
37955ffd83dbSDimitry Andric                                       bool IsImporting,
37965ffd83dbSDimitry Andric                                       DataLayoutCallbackTy DataLayoutCallback) {
37970b57cec5SDimitry Andric   TheModule = M;
37980b57cec5SDimitry Andric   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
37990b57cec5SDimitry Andric                             [&](unsigned ID) { return getTypeByID(ID); });
38005ffd83dbSDimitry Andric   return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback);
38010b57cec5SDimitry Andric }
38020b57cec5SDimitry Andric 
typeCheckLoadStoreInst(Type * ValType,Type * PtrType)38030b57cec5SDimitry Andric Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
38040b57cec5SDimitry Andric   if (!isa<PointerType>(PtrType))
38050b57cec5SDimitry Andric     return error("Load/Store operand is not a pointer type");
38060b57cec5SDimitry Andric 
3807*5f7ddb14SDimitry Andric   if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType))
38080b57cec5SDimitry Andric     return error("Explicit load/store type does not match pointee "
38090b57cec5SDimitry Andric                  "type of pointer operand");
3810*5f7ddb14SDimitry Andric   if (!PointerType::isLoadableOrStorableType(ValType))
38110b57cec5SDimitry Andric     return error("Cannot load/store from pointer");
38120b57cec5SDimitry Andric   return Error::success();
38130b57cec5SDimitry Andric }
38140b57cec5SDimitry Andric 
propagateAttributeTypes(CallBase * CB,ArrayRef<Type * > ArgsTys)3815*5f7ddb14SDimitry Andric void BitcodeReader::propagateAttributeTypes(CallBase *CB,
3816*5f7ddb14SDimitry Andric                                             ArrayRef<Type *> ArgsTys) {
38170b57cec5SDimitry Andric   for (unsigned i = 0; i != CB->arg_size(); ++i) {
3818*5f7ddb14SDimitry Andric     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3819*5f7ddb14SDimitry Andric                                      Attribute::InAlloca}) {
3820af732203SDimitry Andric       if (!CB->paramHasAttr(i, Kind))
38210b57cec5SDimitry Andric         continue;
38220b57cec5SDimitry Andric 
3823af732203SDimitry Andric       CB->removeParamAttr(i, Kind);
3824af732203SDimitry Andric 
3825*5f7ddb14SDimitry Andric       Type *PtrEltTy = cast<PointerType>(ArgsTys[i])->getElementType();
3826*5f7ddb14SDimitry Andric       Attribute NewAttr;
3827*5f7ddb14SDimitry Andric       switch (Kind) {
3828*5f7ddb14SDimitry Andric       case Attribute::ByVal:
3829*5f7ddb14SDimitry Andric         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3830*5f7ddb14SDimitry Andric         break;
3831*5f7ddb14SDimitry Andric       case Attribute::StructRet:
3832*5f7ddb14SDimitry Andric         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3833*5f7ddb14SDimitry Andric         break;
3834*5f7ddb14SDimitry Andric       case Attribute::InAlloca:
3835*5f7ddb14SDimitry Andric         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3836*5f7ddb14SDimitry Andric         break;
3837*5f7ddb14SDimitry Andric       default:
3838*5f7ddb14SDimitry Andric         llvm_unreachable("not an upgraded type attribute");
3839*5f7ddb14SDimitry Andric       }
3840*5f7ddb14SDimitry Andric 
3841af732203SDimitry Andric       CB->addParamAttr(i, NewAttr);
3842af732203SDimitry Andric     }
38430b57cec5SDimitry Andric   }
3844*5f7ddb14SDimitry Andric 
3845*5f7ddb14SDimitry Andric   switch (CB->getIntrinsicID()) {
3846*5f7ddb14SDimitry Andric   case Intrinsic::preserve_array_access_index:
3847*5f7ddb14SDimitry Andric   case Intrinsic::preserve_struct_access_index:
3848*5f7ddb14SDimitry Andric     if (!CB->getAttributes().getParamElementType(0)) {
3849*5f7ddb14SDimitry Andric       Type *ElTy = cast<PointerType>(ArgsTys[0])->getElementType();
3850*5f7ddb14SDimitry Andric       Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
3851*5f7ddb14SDimitry Andric       CB->addParamAttr(0, NewAttr);
3852*5f7ddb14SDimitry Andric     }
3853*5f7ddb14SDimitry Andric     break;
3854*5f7ddb14SDimitry Andric   default:
3855*5f7ddb14SDimitry Andric     break;
3856*5f7ddb14SDimitry Andric   }
38570b57cec5SDimitry Andric }
38580b57cec5SDimitry Andric 
38590b57cec5SDimitry Andric /// Lazily parse the specified function body block.
parseFunctionBody(Function * F)38600b57cec5SDimitry Andric Error BitcodeReader::parseFunctionBody(Function *F) {
38610b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
38620b57cec5SDimitry Andric     return Err;
38630b57cec5SDimitry Andric 
38640b57cec5SDimitry Andric   // Unexpected unresolved metadata when parsing function.
38650b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
38660b57cec5SDimitry Andric     return error("Invalid function metadata: incoming forward references");
38670b57cec5SDimitry Andric 
38680b57cec5SDimitry Andric   InstructionList.clear();
38690b57cec5SDimitry Andric   unsigned ModuleValueListSize = ValueList.size();
38700b57cec5SDimitry Andric   unsigned ModuleMDLoaderSize = MDLoader->size();
38710b57cec5SDimitry Andric 
38720b57cec5SDimitry Andric   // Add all the function arguments to the value table.
3873*5f7ddb14SDimitry Andric #ifndef NDEBUG
38740b57cec5SDimitry Andric   unsigned ArgNo = 0;
3875*5f7ddb14SDimitry Andric   FunctionType *FTy = FunctionTypes[F];
3876*5f7ddb14SDimitry Andric #endif
38770b57cec5SDimitry Andric   for (Argument &I : F->args()) {
3878*5f7ddb14SDimitry Andric     assert(I.getType() == FTy->getParamType(ArgNo++) &&
38790b57cec5SDimitry Andric            "Incorrect fully specified type for Function Argument");
3880*5f7ddb14SDimitry Andric     ValueList.push_back(&I);
38810b57cec5SDimitry Andric   }
38820b57cec5SDimitry Andric   unsigned NextValueNo = ValueList.size();
38830b57cec5SDimitry Andric   BasicBlock *CurBB = nullptr;
38840b57cec5SDimitry Andric   unsigned CurBBNo = 0;
38850b57cec5SDimitry Andric 
38860b57cec5SDimitry Andric   DebugLoc LastLoc;
38870b57cec5SDimitry Andric   auto getLastInstruction = [&]() -> Instruction * {
38880b57cec5SDimitry Andric     if (CurBB && !CurBB->empty())
38890b57cec5SDimitry Andric       return &CurBB->back();
38900b57cec5SDimitry Andric     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
38910b57cec5SDimitry Andric              !FunctionBBs[CurBBNo - 1]->empty())
38920b57cec5SDimitry Andric       return &FunctionBBs[CurBBNo - 1]->back();
38930b57cec5SDimitry Andric     return nullptr;
38940b57cec5SDimitry Andric   };
38950b57cec5SDimitry Andric 
38960b57cec5SDimitry Andric   std::vector<OperandBundleDef> OperandBundles;
38970b57cec5SDimitry Andric 
38980b57cec5SDimitry Andric   // Read all the records.
38990b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
39000b57cec5SDimitry Andric 
39010b57cec5SDimitry Andric   while (true) {
39020b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
39030b57cec5SDimitry Andric     if (!MaybeEntry)
39040b57cec5SDimitry Andric       return MaybeEntry.takeError();
39050b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
39060b57cec5SDimitry Andric 
39070b57cec5SDimitry Andric     switch (Entry.Kind) {
39080b57cec5SDimitry Andric     case BitstreamEntry::Error:
39090b57cec5SDimitry Andric       return error("Malformed block");
39100b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
39110b57cec5SDimitry Andric       goto OutOfRecordLoop;
39120b57cec5SDimitry Andric 
39130b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
39140b57cec5SDimitry Andric       switch (Entry.ID) {
39150b57cec5SDimitry Andric       default:  // Skip unknown content.
39160b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
39170b57cec5SDimitry Andric           return Err;
39180b57cec5SDimitry Andric         break;
39190b57cec5SDimitry Andric       case bitc::CONSTANTS_BLOCK_ID:
39200b57cec5SDimitry Andric         if (Error Err = parseConstants())
39210b57cec5SDimitry Andric           return Err;
39220b57cec5SDimitry Andric         NextValueNo = ValueList.size();
39230b57cec5SDimitry Andric         break;
39240b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
39250b57cec5SDimitry Andric         if (Error Err = parseValueSymbolTable())
39260b57cec5SDimitry Andric           return Err;
39270b57cec5SDimitry Andric         break;
39280b57cec5SDimitry Andric       case bitc::METADATA_ATTACHMENT_ID:
39290b57cec5SDimitry Andric         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
39300b57cec5SDimitry Andric           return Err;
39310b57cec5SDimitry Andric         break;
39320b57cec5SDimitry Andric       case bitc::METADATA_BLOCK_ID:
39330b57cec5SDimitry Andric         assert(DeferredMetadataInfo.empty() &&
39340b57cec5SDimitry Andric                "Must read all module-level metadata before function-level");
39350b57cec5SDimitry Andric         if (Error Err = MDLoader->parseFunctionMetadata())
39360b57cec5SDimitry Andric           return Err;
39370b57cec5SDimitry Andric         break;
39380b57cec5SDimitry Andric       case bitc::USELIST_BLOCK_ID:
39390b57cec5SDimitry Andric         if (Error Err = parseUseLists())
39400b57cec5SDimitry Andric           return Err;
39410b57cec5SDimitry Andric         break;
39420b57cec5SDimitry Andric       }
39430b57cec5SDimitry Andric       continue;
39440b57cec5SDimitry Andric 
39450b57cec5SDimitry Andric     case BitstreamEntry::Record:
39460b57cec5SDimitry Andric       // The interesting case.
39470b57cec5SDimitry Andric       break;
39480b57cec5SDimitry Andric     }
39490b57cec5SDimitry Andric 
39500b57cec5SDimitry Andric     // Read a record.
39510b57cec5SDimitry Andric     Record.clear();
39520b57cec5SDimitry Andric     Instruction *I = nullptr;
39530b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
39540b57cec5SDimitry Andric     if (!MaybeBitCode)
39550b57cec5SDimitry Andric       return MaybeBitCode.takeError();
39560b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
39570b57cec5SDimitry Andric     default: // Default behavior: reject
39580b57cec5SDimitry Andric       return error("Invalid value");
39590b57cec5SDimitry Andric     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3960af732203SDimitry Andric       if (Record.empty() || Record[0] == 0)
39610b57cec5SDimitry Andric         return error("Invalid record");
39620b57cec5SDimitry Andric       // Create all the basic blocks for the function.
39630b57cec5SDimitry Andric       FunctionBBs.resize(Record[0]);
39640b57cec5SDimitry Andric 
39650b57cec5SDimitry Andric       // See if anything took the address of blocks in this function.
39660b57cec5SDimitry Andric       auto BBFRI = BasicBlockFwdRefs.find(F);
39670b57cec5SDimitry Andric       if (BBFRI == BasicBlockFwdRefs.end()) {
39680b57cec5SDimitry Andric         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
39690b57cec5SDimitry Andric           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
39700b57cec5SDimitry Andric       } else {
39710b57cec5SDimitry Andric         auto &BBRefs = BBFRI->second;
39720b57cec5SDimitry Andric         // Check for invalid basic block references.
39730b57cec5SDimitry Andric         if (BBRefs.size() > FunctionBBs.size())
39740b57cec5SDimitry Andric           return error("Invalid ID");
39750b57cec5SDimitry Andric         assert(!BBRefs.empty() && "Unexpected empty array");
39760b57cec5SDimitry Andric         assert(!BBRefs.front() && "Invalid reference to entry block");
39770b57cec5SDimitry Andric         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
39780b57cec5SDimitry Andric              ++I)
39790b57cec5SDimitry Andric           if (I < RE && BBRefs[I]) {
39800b57cec5SDimitry Andric             BBRefs[I]->insertInto(F);
39810b57cec5SDimitry Andric             FunctionBBs[I] = BBRefs[I];
39820b57cec5SDimitry Andric           } else {
39830b57cec5SDimitry Andric             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
39840b57cec5SDimitry Andric           }
39850b57cec5SDimitry Andric 
39860b57cec5SDimitry Andric         // Erase from the table.
39870b57cec5SDimitry Andric         BasicBlockFwdRefs.erase(BBFRI);
39880b57cec5SDimitry Andric       }
39890b57cec5SDimitry Andric 
39900b57cec5SDimitry Andric       CurBB = FunctionBBs[0];
39910b57cec5SDimitry Andric       continue;
39920b57cec5SDimitry Andric     }
39930b57cec5SDimitry Andric 
39940b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
39950b57cec5SDimitry Andric       // This record indicates that the last instruction is at the same
39960b57cec5SDimitry Andric       // location as the previous instruction with a location.
39970b57cec5SDimitry Andric       I = getLastInstruction();
39980b57cec5SDimitry Andric 
39990b57cec5SDimitry Andric       if (!I)
40000b57cec5SDimitry Andric         return error("Invalid record");
40010b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
40020b57cec5SDimitry Andric       I = nullptr;
40030b57cec5SDimitry Andric       continue;
40040b57cec5SDimitry Andric 
40050b57cec5SDimitry Andric     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
40060b57cec5SDimitry Andric       I = getLastInstruction();
40070b57cec5SDimitry Andric       if (!I || Record.size() < 4)
40080b57cec5SDimitry Andric         return error("Invalid record");
40090b57cec5SDimitry Andric 
40100b57cec5SDimitry Andric       unsigned Line = Record[0], Col = Record[1];
40110b57cec5SDimitry Andric       unsigned ScopeID = Record[2], IAID = Record[3];
40120b57cec5SDimitry Andric       bool isImplicitCode = Record.size() == 5 && Record[4];
40130b57cec5SDimitry Andric 
40140b57cec5SDimitry Andric       MDNode *Scope = nullptr, *IA = nullptr;
40150b57cec5SDimitry Andric       if (ScopeID) {
40160b57cec5SDimitry Andric         Scope = dyn_cast_or_null<MDNode>(
40170b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
40180b57cec5SDimitry Andric         if (!Scope)
40190b57cec5SDimitry Andric           return error("Invalid record");
40200b57cec5SDimitry Andric       }
40210b57cec5SDimitry Andric       if (IAID) {
40220b57cec5SDimitry Andric         IA = dyn_cast_or_null<MDNode>(
40230b57cec5SDimitry Andric             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
40240b57cec5SDimitry Andric         if (!IA)
40250b57cec5SDimitry Andric           return error("Invalid record");
40260b57cec5SDimitry Andric       }
4027af732203SDimitry Andric       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4028af732203SDimitry Andric                                 isImplicitCode);
40290b57cec5SDimitry Andric       I->setDebugLoc(LastLoc);
40300b57cec5SDimitry Andric       I = nullptr;
40310b57cec5SDimitry Andric       continue;
40320b57cec5SDimitry Andric     }
40330b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
40340b57cec5SDimitry Andric       unsigned OpNum = 0;
40350b57cec5SDimitry Andric       Value *LHS;
40360b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
40370b57cec5SDimitry Andric           OpNum+1 > Record.size())
40380b57cec5SDimitry Andric         return error("Invalid record");
40390b57cec5SDimitry Andric 
40400b57cec5SDimitry Andric       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
40410b57cec5SDimitry Andric       if (Opc == -1)
40420b57cec5SDimitry Andric         return error("Invalid record");
40430b57cec5SDimitry Andric       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
40440b57cec5SDimitry Andric       InstructionList.push_back(I);
40450b57cec5SDimitry Andric       if (OpNum < Record.size()) {
40460b57cec5SDimitry Andric         if (isa<FPMathOperator>(I)) {
40470b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
40480b57cec5SDimitry Andric           if (FMF.any())
40490b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
40500b57cec5SDimitry Andric         }
40510b57cec5SDimitry Andric       }
40520b57cec5SDimitry Andric       break;
40530b57cec5SDimitry Andric     }
40540b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
40550b57cec5SDimitry Andric       unsigned OpNum = 0;
40560b57cec5SDimitry Andric       Value *LHS, *RHS;
40570b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
40580b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
40590b57cec5SDimitry Andric           OpNum+1 > Record.size())
40600b57cec5SDimitry Andric         return error("Invalid record");
40610b57cec5SDimitry Andric 
40620b57cec5SDimitry Andric       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
40630b57cec5SDimitry Andric       if (Opc == -1)
40640b57cec5SDimitry Andric         return error("Invalid record");
40650b57cec5SDimitry Andric       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
40660b57cec5SDimitry Andric       InstructionList.push_back(I);
40670b57cec5SDimitry Andric       if (OpNum < Record.size()) {
40680b57cec5SDimitry Andric         if (Opc == Instruction::Add ||
40690b57cec5SDimitry Andric             Opc == Instruction::Sub ||
40700b57cec5SDimitry Andric             Opc == Instruction::Mul ||
40710b57cec5SDimitry Andric             Opc == Instruction::Shl) {
40720b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
40730b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
40740b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
40750b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
40760b57cec5SDimitry Andric         } else if (Opc == Instruction::SDiv ||
40770b57cec5SDimitry Andric                    Opc == Instruction::UDiv ||
40780b57cec5SDimitry Andric                    Opc == Instruction::LShr ||
40790b57cec5SDimitry Andric                    Opc == Instruction::AShr) {
40800b57cec5SDimitry Andric           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
40810b57cec5SDimitry Andric             cast<BinaryOperator>(I)->setIsExact(true);
40820b57cec5SDimitry Andric         } else if (isa<FPMathOperator>(I)) {
40830b57cec5SDimitry Andric           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
40840b57cec5SDimitry Andric           if (FMF.any())
40850b57cec5SDimitry Andric             I->setFastMathFlags(FMF);
40860b57cec5SDimitry Andric         }
40870b57cec5SDimitry Andric 
40880b57cec5SDimitry Andric       }
40890b57cec5SDimitry Andric       break;
40900b57cec5SDimitry Andric     }
40910b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
40920b57cec5SDimitry Andric       unsigned OpNum = 0;
40930b57cec5SDimitry Andric       Value *Op;
40940b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
40950b57cec5SDimitry Andric           OpNum+2 != Record.size())
40960b57cec5SDimitry Andric         return error("Invalid record");
40970b57cec5SDimitry Andric 
4098*5f7ddb14SDimitry Andric       Type *ResTy = getTypeByID(Record[OpNum]);
40990b57cec5SDimitry Andric       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
41000b57cec5SDimitry Andric       if (Opc == -1 || !ResTy)
41010b57cec5SDimitry Andric         return error("Invalid record");
41020b57cec5SDimitry Andric       Instruction *Temp = nullptr;
41030b57cec5SDimitry Andric       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
41040b57cec5SDimitry Andric         if (Temp) {
41050b57cec5SDimitry Andric           InstructionList.push_back(Temp);
4106480093f4SDimitry Andric           assert(CurBB && "No current BB?");
41070b57cec5SDimitry Andric           CurBB->getInstList().push_back(Temp);
41080b57cec5SDimitry Andric         }
41090b57cec5SDimitry Andric       } else {
41100b57cec5SDimitry Andric         auto CastOp = (Instruction::CastOps)Opc;
41110b57cec5SDimitry Andric         if (!CastInst::castIsValid(CastOp, Op, ResTy))
41120b57cec5SDimitry Andric           return error("Invalid cast");
41130b57cec5SDimitry Andric         I = CastInst::Create(CastOp, Op, ResTy);
41140b57cec5SDimitry Andric       }
41150b57cec5SDimitry Andric       InstructionList.push_back(I);
41160b57cec5SDimitry Andric       break;
41170b57cec5SDimitry Andric     }
41180b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
41190b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP_OLD:
41200b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
41210b57cec5SDimitry Andric       unsigned OpNum = 0;
41220b57cec5SDimitry Andric 
41230b57cec5SDimitry Andric       Type *Ty;
41240b57cec5SDimitry Andric       bool InBounds;
41250b57cec5SDimitry Andric 
41260b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
41270b57cec5SDimitry Andric         InBounds = Record[OpNum++];
4128*5f7ddb14SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
41290b57cec5SDimitry Andric       } else {
41300b57cec5SDimitry Andric         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
41310b57cec5SDimitry Andric         Ty = nullptr;
41320b57cec5SDimitry Andric       }
41330b57cec5SDimitry Andric 
41340b57cec5SDimitry Andric       Value *BasePtr;
4135*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
41360b57cec5SDimitry Andric         return error("Invalid record");
41370b57cec5SDimitry Andric 
41380b57cec5SDimitry Andric       if (!Ty) {
4139*5f7ddb14SDimitry Andric         Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
4140*5f7ddb14SDimitry Andric                  ->getElementType();
4141*5f7ddb14SDimitry Andric       } else if (!cast<PointerType>(BasePtr->getType()->getScalarType())
4142*5f7ddb14SDimitry Andric                       ->isOpaqueOrPointeeTypeMatches(Ty)) {
41430b57cec5SDimitry Andric         return error(
41440b57cec5SDimitry Andric             "Explicit gep type does not match pointee type of pointer operand");
4145*5f7ddb14SDimitry Andric       }
41460b57cec5SDimitry Andric 
41470b57cec5SDimitry Andric       SmallVector<Value*, 16> GEPIdx;
41480b57cec5SDimitry Andric       while (OpNum != Record.size()) {
41490b57cec5SDimitry Andric         Value *Op;
41500b57cec5SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
41510b57cec5SDimitry Andric           return error("Invalid record");
41520b57cec5SDimitry Andric         GEPIdx.push_back(Op);
41530b57cec5SDimitry Andric       }
41540b57cec5SDimitry Andric 
41550b57cec5SDimitry Andric       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
41560b57cec5SDimitry Andric 
41570b57cec5SDimitry Andric       InstructionList.push_back(I);
41580b57cec5SDimitry Andric       if (InBounds)
41590b57cec5SDimitry Andric         cast<GetElementPtrInst>(I)->setIsInBounds(true);
41600b57cec5SDimitry Andric       break;
41610b57cec5SDimitry Andric     }
41620b57cec5SDimitry Andric 
41630b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
41640b57cec5SDimitry Andric                                        // EXTRACTVAL: [opty, opval, n x indices]
41650b57cec5SDimitry Andric       unsigned OpNum = 0;
41660b57cec5SDimitry Andric       Value *Agg;
4167*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
41680b57cec5SDimitry Andric         return error("Invalid record");
4169*5f7ddb14SDimitry Andric       Type *Ty = Agg->getType();
41700b57cec5SDimitry Andric 
41710b57cec5SDimitry Andric       unsigned RecSize = Record.size();
41720b57cec5SDimitry Andric       if (OpNum == RecSize)
41730b57cec5SDimitry Andric         return error("EXTRACTVAL: Invalid instruction with 0 indices");
41740b57cec5SDimitry Andric 
41750b57cec5SDimitry Andric       SmallVector<unsigned, 4> EXTRACTVALIdx;
41760b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
4177*5f7ddb14SDimitry Andric         bool IsArray = Ty->isArrayTy();
4178*5f7ddb14SDimitry Andric         bool IsStruct = Ty->isStructTy();
41790b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
41800b57cec5SDimitry Andric 
41810b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
41820b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid type");
41830b57cec5SDimitry Andric         if ((unsigned)Index != Index)
41840b57cec5SDimitry Andric           return error("Invalid value");
4185*5f7ddb14SDimitry Andric         if (IsStruct && Index >= Ty->getStructNumElements())
41860b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid struct index");
4187*5f7ddb14SDimitry Andric         if (IsArray && Index >= Ty->getArrayNumElements())
41880b57cec5SDimitry Andric           return error("EXTRACTVAL: Invalid array index");
41890b57cec5SDimitry Andric         EXTRACTVALIdx.push_back((unsigned)Index);
41900b57cec5SDimitry Andric 
41910b57cec5SDimitry Andric         if (IsStruct)
4192*5f7ddb14SDimitry Andric           Ty = Ty->getStructElementType(Index);
41930b57cec5SDimitry Andric         else
4194*5f7ddb14SDimitry Andric           Ty = Ty->getArrayElementType();
41950b57cec5SDimitry Andric       }
41960b57cec5SDimitry Andric 
41970b57cec5SDimitry Andric       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
41980b57cec5SDimitry Andric       InstructionList.push_back(I);
41990b57cec5SDimitry Andric       break;
42000b57cec5SDimitry Andric     }
42010b57cec5SDimitry Andric 
42020b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTVAL: {
42030b57cec5SDimitry Andric                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
42040b57cec5SDimitry Andric       unsigned OpNum = 0;
42050b57cec5SDimitry Andric       Value *Agg;
4206*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
42070b57cec5SDimitry Andric         return error("Invalid record");
42080b57cec5SDimitry Andric       Value *Val;
42090b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
42100b57cec5SDimitry Andric         return error("Invalid record");
42110b57cec5SDimitry Andric 
42120b57cec5SDimitry Andric       unsigned RecSize = Record.size();
42130b57cec5SDimitry Andric       if (OpNum == RecSize)
42140b57cec5SDimitry Andric         return error("INSERTVAL: Invalid instruction with 0 indices");
42150b57cec5SDimitry Andric 
42160b57cec5SDimitry Andric       SmallVector<unsigned, 4> INSERTVALIdx;
42170b57cec5SDimitry Andric       Type *CurTy = Agg->getType();
42180b57cec5SDimitry Andric       for (; OpNum != RecSize; ++OpNum) {
42190b57cec5SDimitry Andric         bool IsArray = CurTy->isArrayTy();
42200b57cec5SDimitry Andric         bool IsStruct = CurTy->isStructTy();
42210b57cec5SDimitry Andric         uint64_t Index = Record[OpNum];
42220b57cec5SDimitry Andric 
42230b57cec5SDimitry Andric         if (!IsStruct && !IsArray)
42240b57cec5SDimitry Andric           return error("INSERTVAL: Invalid type");
42250b57cec5SDimitry Andric         if ((unsigned)Index != Index)
42260b57cec5SDimitry Andric           return error("Invalid value");
42270b57cec5SDimitry Andric         if (IsStruct && Index >= CurTy->getStructNumElements())
42280b57cec5SDimitry Andric           return error("INSERTVAL: Invalid struct index");
42290b57cec5SDimitry Andric         if (IsArray && Index >= CurTy->getArrayNumElements())
42300b57cec5SDimitry Andric           return error("INSERTVAL: Invalid array index");
42310b57cec5SDimitry Andric 
42320b57cec5SDimitry Andric         INSERTVALIdx.push_back((unsigned)Index);
42330b57cec5SDimitry Andric         if (IsStruct)
42340b57cec5SDimitry Andric           CurTy = CurTy->getStructElementType(Index);
42350b57cec5SDimitry Andric         else
42360b57cec5SDimitry Andric           CurTy = CurTy->getArrayElementType();
42370b57cec5SDimitry Andric       }
42380b57cec5SDimitry Andric 
42390b57cec5SDimitry Andric       if (CurTy != Val->getType())
42400b57cec5SDimitry Andric         return error("Inserted value type doesn't match aggregate type");
42410b57cec5SDimitry Andric 
42420b57cec5SDimitry Andric       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
42430b57cec5SDimitry Andric       InstructionList.push_back(I);
42440b57cec5SDimitry Andric       break;
42450b57cec5SDimitry Andric     }
42460b57cec5SDimitry Andric 
42470b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
42480b57cec5SDimitry Andric       // obsolete form of select
42490b57cec5SDimitry Andric       // handles select i1 ... in old bitcode
42500b57cec5SDimitry Andric       unsigned OpNum = 0;
42510b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
4252*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
42530b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
42540b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
42550b57cec5SDimitry Andric         return error("Invalid record");
42560b57cec5SDimitry Andric 
42570b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
42580b57cec5SDimitry Andric       InstructionList.push_back(I);
42590b57cec5SDimitry Andric       break;
42600b57cec5SDimitry Andric     }
42610b57cec5SDimitry Andric 
42620b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
42630b57cec5SDimitry Andric       // new form of select
42640b57cec5SDimitry Andric       // handles select i1 or select [N x i1]
42650b57cec5SDimitry Andric       unsigned OpNum = 0;
42660b57cec5SDimitry Andric       Value *TrueVal, *FalseVal, *Cond;
4267*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
42680b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
42690b57cec5SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Cond))
42700b57cec5SDimitry Andric         return error("Invalid record");
42710b57cec5SDimitry Andric 
42720b57cec5SDimitry Andric       // select condition can be either i1 or [N x i1]
42730b57cec5SDimitry Andric       if (VectorType* vector_type =
42740b57cec5SDimitry Andric           dyn_cast<VectorType>(Cond->getType())) {
42750b57cec5SDimitry Andric         // expect <n x i1>
42760b57cec5SDimitry Andric         if (vector_type->getElementType() != Type::getInt1Ty(Context))
42770b57cec5SDimitry Andric           return error("Invalid type for value");
42780b57cec5SDimitry Andric       } else {
42790b57cec5SDimitry Andric         // expect i1
42800b57cec5SDimitry Andric         if (Cond->getType() != Type::getInt1Ty(Context))
42810b57cec5SDimitry Andric           return error("Invalid type for value");
42820b57cec5SDimitry Andric       }
42830b57cec5SDimitry Andric 
42840b57cec5SDimitry Andric       I = SelectInst::Create(Cond, TrueVal, FalseVal);
42850b57cec5SDimitry Andric       InstructionList.push_back(I);
42860b57cec5SDimitry Andric       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
42870b57cec5SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
42880b57cec5SDimitry Andric         if (FMF.any())
42890b57cec5SDimitry Andric           I->setFastMathFlags(FMF);
42900b57cec5SDimitry Andric       }
42910b57cec5SDimitry Andric       break;
42920b57cec5SDimitry Andric     }
42930b57cec5SDimitry Andric 
42940b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
42950b57cec5SDimitry Andric       unsigned OpNum = 0;
42960b57cec5SDimitry Andric       Value *Vec, *Idx;
4297*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
42980b57cec5SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx))
42990b57cec5SDimitry Andric         return error("Invalid record");
43000b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
43010b57cec5SDimitry Andric         return error("Invalid type for value");
43020b57cec5SDimitry Andric       I = ExtractElementInst::Create(Vec, Idx);
43030b57cec5SDimitry Andric       InstructionList.push_back(I);
43040b57cec5SDimitry Andric       break;
43050b57cec5SDimitry Andric     }
43060b57cec5SDimitry Andric 
43070b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
43080b57cec5SDimitry Andric       unsigned OpNum = 0;
43090b57cec5SDimitry Andric       Value *Vec, *Elt, *Idx;
4310*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
43110b57cec5SDimitry Andric         return error("Invalid record");
43120b57cec5SDimitry Andric       if (!Vec->getType()->isVectorTy())
43130b57cec5SDimitry Andric         return error("Invalid type for value");
43140b57cec5SDimitry Andric       if (popValue(Record, OpNum, NextValueNo,
43150b57cec5SDimitry Andric                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
43160b57cec5SDimitry Andric           getValueTypePair(Record, OpNum, NextValueNo, Idx))
43170b57cec5SDimitry Andric         return error("Invalid record");
43180b57cec5SDimitry Andric       I = InsertElementInst::Create(Vec, Elt, Idx);
43190b57cec5SDimitry Andric       InstructionList.push_back(I);
43200b57cec5SDimitry Andric       break;
43210b57cec5SDimitry Andric     }
43220b57cec5SDimitry Andric 
43230b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
43240b57cec5SDimitry Andric       unsigned OpNum = 0;
43250b57cec5SDimitry Andric       Value *Vec1, *Vec2, *Mask;
4326*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
43270b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
43280b57cec5SDimitry Andric         return error("Invalid record");
43290b57cec5SDimitry Andric 
43300b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
43310b57cec5SDimitry Andric         return error("Invalid record");
43320b57cec5SDimitry Andric       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
43330b57cec5SDimitry Andric         return error("Invalid type for value");
43345ffd83dbSDimitry Andric 
43350b57cec5SDimitry Andric       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
43360b57cec5SDimitry Andric       InstructionList.push_back(I);
43370b57cec5SDimitry Andric       break;
43380b57cec5SDimitry Andric     }
43390b57cec5SDimitry Andric 
43400b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
43410b57cec5SDimitry Andric       // Old form of ICmp/FCmp returning bool
43420b57cec5SDimitry Andric       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
43430b57cec5SDimitry Andric       // both legal on vectors but had different behaviour.
43440b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
43450b57cec5SDimitry Andric       // FCmp/ICmp returning bool or vector of bool
43460b57cec5SDimitry Andric 
43470b57cec5SDimitry Andric       unsigned OpNum = 0;
43480b57cec5SDimitry Andric       Value *LHS, *RHS;
43490b57cec5SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
43500b57cec5SDimitry Andric           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
43510b57cec5SDimitry Andric         return error("Invalid record");
43520b57cec5SDimitry Andric 
43530b57cec5SDimitry Andric       if (OpNum >= Record.size())
43540b57cec5SDimitry Andric         return error(
43550b57cec5SDimitry Andric             "Invalid record: operand number exceeded available operands");
43560b57cec5SDimitry Andric 
43570b57cec5SDimitry Andric       unsigned PredVal = Record[OpNum];
43580b57cec5SDimitry Andric       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
43590b57cec5SDimitry Andric       FastMathFlags FMF;
43600b57cec5SDimitry Andric       if (IsFP && Record.size() > OpNum+1)
43610b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[++OpNum]);
43620b57cec5SDimitry Andric 
43630b57cec5SDimitry Andric       if (OpNum+1 != Record.size())
43640b57cec5SDimitry Andric         return error("Invalid record");
43650b57cec5SDimitry Andric 
43660b57cec5SDimitry Andric       if (LHS->getType()->isFPOrFPVectorTy())
43670b57cec5SDimitry Andric         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
43680b57cec5SDimitry Andric       else
43690b57cec5SDimitry Andric         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
43700b57cec5SDimitry Andric 
43710b57cec5SDimitry Andric       if (FMF.any())
43720b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
43730b57cec5SDimitry Andric       InstructionList.push_back(I);
43740b57cec5SDimitry Andric       break;
43750b57cec5SDimitry Andric     }
43760b57cec5SDimitry Andric 
43770b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
43780b57cec5SDimitry Andric       {
43790b57cec5SDimitry Andric         unsigned Size = Record.size();
43800b57cec5SDimitry Andric         if (Size == 0) {
43810b57cec5SDimitry Andric           I = ReturnInst::Create(Context);
43820b57cec5SDimitry Andric           InstructionList.push_back(I);
43830b57cec5SDimitry Andric           break;
43840b57cec5SDimitry Andric         }
43850b57cec5SDimitry Andric 
43860b57cec5SDimitry Andric         unsigned OpNum = 0;
43870b57cec5SDimitry Andric         Value *Op = nullptr;
43880b57cec5SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
43890b57cec5SDimitry Andric           return error("Invalid record");
43900b57cec5SDimitry Andric         if (OpNum != Record.size())
43910b57cec5SDimitry Andric           return error("Invalid record");
43920b57cec5SDimitry Andric 
43930b57cec5SDimitry Andric         I = ReturnInst::Create(Context, Op);
43940b57cec5SDimitry Andric         InstructionList.push_back(I);
43950b57cec5SDimitry Andric         break;
43960b57cec5SDimitry Andric       }
43970b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
43980b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 3)
43990b57cec5SDimitry Andric         return error("Invalid record");
44000b57cec5SDimitry Andric       BasicBlock *TrueDest = getBasicBlock(Record[0]);
44010b57cec5SDimitry Andric       if (!TrueDest)
44020b57cec5SDimitry Andric         return error("Invalid record");
44030b57cec5SDimitry Andric 
44040b57cec5SDimitry Andric       if (Record.size() == 1) {
44050b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest);
44060b57cec5SDimitry Andric         InstructionList.push_back(I);
44070b57cec5SDimitry Andric       }
44080b57cec5SDimitry Andric       else {
44090b57cec5SDimitry Andric         BasicBlock *FalseDest = getBasicBlock(Record[1]);
44100b57cec5SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo,
44110b57cec5SDimitry Andric                                Type::getInt1Ty(Context));
44120b57cec5SDimitry Andric         if (!FalseDest || !Cond)
44130b57cec5SDimitry Andric           return error("Invalid record");
44140b57cec5SDimitry Andric         I = BranchInst::Create(TrueDest, FalseDest, Cond);
44150b57cec5SDimitry Andric         InstructionList.push_back(I);
44160b57cec5SDimitry Andric       }
44170b57cec5SDimitry Andric       break;
44180b57cec5SDimitry Andric     }
44190b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
44200b57cec5SDimitry Andric       if (Record.size() != 1 && Record.size() != 2)
44210b57cec5SDimitry Andric         return error("Invalid record");
44220b57cec5SDimitry Andric       unsigned Idx = 0;
44230b57cec5SDimitry Andric       Value *CleanupPad =
44240b57cec5SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
44250b57cec5SDimitry Andric       if (!CleanupPad)
44260b57cec5SDimitry Andric         return error("Invalid record");
44270b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
44280b57cec5SDimitry Andric       if (Record.size() == 2) {
44290b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
44300b57cec5SDimitry Andric         if (!UnwindDest)
44310b57cec5SDimitry Andric           return error("Invalid record");
44320b57cec5SDimitry Andric       }
44330b57cec5SDimitry Andric 
44340b57cec5SDimitry Andric       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
44350b57cec5SDimitry Andric       InstructionList.push_back(I);
44360b57cec5SDimitry Andric       break;
44370b57cec5SDimitry Andric     }
44380b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
44390b57cec5SDimitry Andric       if (Record.size() != 2)
44400b57cec5SDimitry Andric         return error("Invalid record");
44410b57cec5SDimitry Andric       unsigned Idx = 0;
44420b57cec5SDimitry Andric       Value *CatchPad =
44430b57cec5SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
44440b57cec5SDimitry Andric       if (!CatchPad)
44450b57cec5SDimitry Andric         return error("Invalid record");
44460b57cec5SDimitry Andric       BasicBlock *BB = getBasicBlock(Record[Idx++]);
44470b57cec5SDimitry Andric       if (!BB)
44480b57cec5SDimitry Andric         return error("Invalid record");
44490b57cec5SDimitry Andric 
44500b57cec5SDimitry Andric       I = CatchReturnInst::Create(CatchPad, BB);
44510b57cec5SDimitry Andric       InstructionList.push_back(I);
44520b57cec5SDimitry Andric       break;
44530b57cec5SDimitry Andric     }
44540b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
44550b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
44560b57cec5SDimitry Andric       if (Record.size() < 2)
44570b57cec5SDimitry Andric         return error("Invalid record");
44580b57cec5SDimitry Andric 
44590b57cec5SDimitry Andric       unsigned Idx = 0;
44600b57cec5SDimitry Andric 
44610b57cec5SDimitry Andric       Value *ParentPad =
44620b57cec5SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
44630b57cec5SDimitry Andric 
44640b57cec5SDimitry Andric       unsigned NumHandlers = Record[Idx++];
44650b57cec5SDimitry Andric 
44660b57cec5SDimitry Andric       SmallVector<BasicBlock *, 2> Handlers;
44670b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
44680b57cec5SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[Idx++]);
44690b57cec5SDimitry Andric         if (!BB)
44700b57cec5SDimitry Andric           return error("Invalid record");
44710b57cec5SDimitry Andric         Handlers.push_back(BB);
44720b57cec5SDimitry Andric       }
44730b57cec5SDimitry Andric 
44740b57cec5SDimitry Andric       BasicBlock *UnwindDest = nullptr;
44750b57cec5SDimitry Andric       if (Idx + 1 == Record.size()) {
44760b57cec5SDimitry Andric         UnwindDest = getBasicBlock(Record[Idx++]);
44770b57cec5SDimitry Andric         if (!UnwindDest)
44780b57cec5SDimitry Andric           return error("Invalid record");
44790b57cec5SDimitry Andric       }
44800b57cec5SDimitry Andric 
44810b57cec5SDimitry Andric       if (Record.size() != Idx)
44820b57cec5SDimitry Andric         return error("Invalid record");
44830b57cec5SDimitry Andric 
44840b57cec5SDimitry Andric       auto *CatchSwitch =
44850b57cec5SDimitry Andric           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
44860b57cec5SDimitry Andric       for (BasicBlock *Handler : Handlers)
44870b57cec5SDimitry Andric         CatchSwitch->addHandler(Handler);
44880b57cec5SDimitry Andric       I = CatchSwitch;
44890b57cec5SDimitry Andric       InstructionList.push_back(I);
44900b57cec5SDimitry Andric       break;
44910b57cec5SDimitry Andric     }
44920b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CATCHPAD:
44930b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
44940b57cec5SDimitry Andric       // We must have, at minimum, the outer scope and the number of arguments.
44950b57cec5SDimitry Andric       if (Record.size() < 2)
44960b57cec5SDimitry Andric         return error("Invalid record");
44970b57cec5SDimitry Andric 
44980b57cec5SDimitry Andric       unsigned Idx = 0;
44990b57cec5SDimitry Andric 
45000b57cec5SDimitry Andric       Value *ParentPad =
45010b57cec5SDimitry Andric           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
45020b57cec5SDimitry Andric 
45030b57cec5SDimitry Andric       unsigned NumArgOperands = Record[Idx++];
45040b57cec5SDimitry Andric 
45050b57cec5SDimitry Andric       SmallVector<Value *, 2> Args;
45060b57cec5SDimitry Andric       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
45070b57cec5SDimitry Andric         Value *Val;
45080b57cec5SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val))
45090b57cec5SDimitry Andric           return error("Invalid record");
45100b57cec5SDimitry Andric         Args.push_back(Val);
45110b57cec5SDimitry Andric       }
45120b57cec5SDimitry Andric 
45130b57cec5SDimitry Andric       if (Record.size() != Idx)
45140b57cec5SDimitry Andric         return error("Invalid record");
45150b57cec5SDimitry Andric 
45160b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
45170b57cec5SDimitry Andric         I = CleanupPadInst::Create(ParentPad, Args);
45180b57cec5SDimitry Andric       else
45190b57cec5SDimitry Andric         I = CatchPadInst::Create(ParentPad, Args);
45200b57cec5SDimitry Andric       InstructionList.push_back(I);
45210b57cec5SDimitry Andric       break;
45220b57cec5SDimitry Andric     }
45230b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
45240b57cec5SDimitry Andric       // Check magic
45250b57cec5SDimitry Andric       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
45260b57cec5SDimitry Andric         // "New" SwitchInst format with case ranges. The changes to write this
45270b57cec5SDimitry Andric         // format were reverted but we still recognize bitcode that uses it.
45280b57cec5SDimitry Andric         // Hopefully someday we will have support for case ranges and can use
45290b57cec5SDimitry Andric         // this format again.
45300b57cec5SDimitry Andric 
45310b57cec5SDimitry Andric         Type *OpTy = getTypeByID(Record[1]);
45320b57cec5SDimitry Andric         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
45330b57cec5SDimitry Andric 
45340b57cec5SDimitry Andric         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
45350b57cec5SDimitry Andric         BasicBlock *Default = getBasicBlock(Record[3]);
45360b57cec5SDimitry Andric         if (!OpTy || !Cond || !Default)
45370b57cec5SDimitry Andric           return error("Invalid record");
45380b57cec5SDimitry Andric 
45390b57cec5SDimitry Andric         unsigned NumCases = Record[4];
45400b57cec5SDimitry Andric 
45410b57cec5SDimitry Andric         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
45420b57cec5SDimitry Andric         InstructionList.push_back(SI);
45430b57cec5SDimitry Andric 
45440b57cec5SDimitry Andric         unsigned CurIdx = 5;
45450b57cec5SDimitry Andric         for (unsigned i = 0; i != NumCases; ++i) {
45460b57cec5SDimitry Andric           SmallVector<ConstantInt*, 1> CaseVals;
45470b57cec5SDimitry Andric           unsigned NumItems = Record[CurIdx++];
45480b57cec5SDimitry Andric           for (unsigned ci = 0; ci != NumItems; ++ci) {
45490b57cec5SDimitry Andric             bool isSingleNumber = Record[CurIdx++];
45500b57cec5SDimitry Andric 
45510b57cec5SDimitry Andric             APInt Low;
45520b57cec5SDimitry Andric             unsigned ActiveWords = 1;
45530b57cec5SDimitry Andric             if (ValueBitWidth > 64)
45540b57cec5SDimitry Andric               ActiveWords = Record[CurIdx++];
45550b57cec5SDimitry Andric             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
45560b57cec5SDimitry Andric                                 ValueBitWidth);
45570b57cec5SDimitry Andric             CurIdx += ActiveWords;
45580b57cec5SDimitry Andric 
45590b57cec5SDimitry Andric             if (!isSingleNumber) {
45600b57cec5SDimitry Andric               ActiveWords = 1;
45610b57cec5SDimitry Andric               if (ValueBitWidth > 64)
45620b57cec5SDimitry Andric                 ActiveWords = Record[CurIdx++];
45630b57cec5SDimitry Andric               APInt High = readWideAPInt(
45640b57cec5SDimitry Andric                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
45650b57cec5SDimitry Andric               CurIdx += ActiveWords;
45660b57cec5SDimitry Andric 
45670b57cec5SDimitry Andric               // FIXME: It is not clear whether values in the range should be
45680b57cec5SDimitry Andric               // compared as signed or unsigned values. The partially
45690b57cec5SDimitry Andric               // implemented changes that used this format in the past used
45700b57cec5SDimitry Andric               // unsigned comparisons.
45710b57cec5SDimitry Andric               for ( ; Low.ule(High); ++Low)
45720b57cec5SDimitry Andric                 CaseVals.push_back(ConstantInt::get(Context, Low));
45730b57cec5SDimitry Andric             } else
45740b57cec5SDimitry Andric               CaseVals.push_back(ConstantInt::get(Context, Low));
45750b57cec5SDimitry Andric           }
45760b57cec5SDimitry Andric           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
45770b57cec5SDimitry Andric           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
45780b57cec5SDimitry Andric                  cve = CaseVals.end(); cvi != cve; ++cvi)
45790b57cec5SDimitry Andric             SI->addCase(*cvi, DestBB);
45800b57cec5SDimitry Andric         }
45810b57cec5SDimitry Andric         I = SI;
45820b57cec5SDimitry Andric         break;
45830b57cec5SDimitry Andric       }
45840b57cec5SDimitry Andric 
45850b57cec5SDimitry Andric       // Old SwitchInst format without case ranges.
45860b57cec5SDimitry Andric 
45870b57cec5SDimitry Andric       if (Record.size() < 3 || (Record.size() & 1) == 0)
45880b57cec5SDimitry Andric         return error("Invalid record");
45890b57cec5SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
45900b57cec5SDimitry Andric       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
45910b57cec5SDimitry Andric       BasicBlock *Default = getBasicBlock(Record[2]);
45920b57cec5SDimitry Andric       if (!OpTy || !Cond || !Default)
45930b57cec5SDimitry Andric         return error("Invalid record");
45940b57cec5SDimitry Andric       unsigned NumCases = (Record.size()-3)/2;
45950b57cec5SDimitry Andric       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
45960b57cec5SDimitry Andric       InstructionList.push_back(SI);
45970b57cec5SDimitry Andric       for (unsigned i = 0, e = NumCases; i != e; ++i) {
45980b57cec5SDimitry Andric         ConstantInt *CaseVal =
45990b57cec5SDimitry Andric           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
46000b57cec5SDimitry Andric         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
46010b57cec5SDimitry Andric         if (!CaseVal || !DestBB) {
46020b57cec5SDimitry Andric           delete SI;
46030b57cec5SDimitry Andric           return error("Invalid record");
46040b57cec5SDimitry Andric         }
46050b57cec5SDimitry Andric         SI->addCase(CaseVal, DestBB);
46060b57cec5SDimitry Andric       }
46070b57cec5SDimitry Andric       I = SI;
46080b57cec5SDimitry Andric       break;
46090b57cec5SDimitry Andric     }
46100b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
46110b57cec5SDimitry Andric       if (Record.size() < 2)
46120b57cec5SDimitry Andric         return error("Invalid record");
46130b57cec5SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
46140b57cec5SDimitry Andric       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
46150b57cec5SDimitry Andric       if (!OpTy || !Address)
46160b57cec5SDimitry Andric         return error("Invalid record");
46170b57cec5SDimitry Andric       unsigned NumDests = Record.size()-2;
46180b57cec5SDimitry Andric       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
46190b57cec5SDimitry Andric       InstructionList.push_back(IBI);
46200b57cec5SDimitry Andric       for (unsigned i = 0, e = NumDests; i != e; ++i) {
46210b57cec5SDimitry Andric         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
46220b57cec5SDimitry Andric           IBI->addDestination(DestBB);
46230b57cec5SDimitry Andric         } else {
46240b57cec5SDimitry Andric           delete IBI;
46250b57cec5SDimitry Andric           return error("Invalid record");
46260b57cec5SDimitry Andric         }
46270b57cec5SDimitry Andric       }
46280b57cec5SDimitry Andric       I = IBI;
46290b57cec5SDimitry Andric       break;
46300b57cec5SDimitry Andric     }
46310b57cec5SDimitry Andric 
46320b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_INVOKE: {
46330b57cec5SDimitry Andric       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
46340b57cec5SDimitry Andric       if (Record.size() < 4)
46350b57cec5SDimitry Andric         return error("Invalid record");
46360b57cec5SDimitry Andric       unsigned OpNum = 0;
46370b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
46380b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
46390b57cec5SDimitry Andric       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
46400b57cec5SDimitry Andric       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
46410b57cec5SDimitry Andric 
46420b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
46430b57cec5SDimitry Andric       if ((CCInfo >> 13) & 1) {
4644*5f7ddb14SDimitry Andric         FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]));
4645*5f7ddb14SDimitry Andric         if (!FTy)
46460b57cec5SDimitry Andric           return error("Explicit invoke type is not a function type");
46470b57cec5SDimitry Andric       }
46480b57cec5SDimitry Andric 
46490b57cec5SDimitry Andric       Value *Callee;
4650*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
46510b57cec5SDimitry Andric         return error("Invalid record");
46520b57cec5SDimitry Andric 
46530b57cec5SDimitry Andric       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
46540b57cec5SDimitry Andric       if (!CalleeTy)
46550b57cec5SDimitry Andric         return error("Callee is not a pointer");
46560b57cec5SDimitry Andric       if (!FTy) {
4657*5f7ddb14SDimitry Andric         FTy = dyn_cast<FunctionType>(
4658*5f7ddb14SDimitry Andric             cast<PointerType>(Callee->getType())->getElementType());
4659*5f7ddb14SDimitry Andric         if (!FTy)
46600b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
4661*5f7ddb14SDimitry Andric       } else if (!CalleeTy->isOpaqueOrPointeeTypeMatches(FTy))
46620b57cec5SDimitry Andric         return error("Explicit invoke type does not match pointee type of "
46630b57cec5SDimitry Andric                      "callee operand");
46640b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
46650b57cec5SDimitry Andric         return error("Insufficient operands to call");
46660b57cec5SDimitry Andric 
46670b57cec5SDimitry Andric       SmallVector<Value*, 16> Ops;
4668*5f7ddb14SDimitry Andric       SmallVector<Type *, 16> ArgsTys;
46690b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
46700b57cec5SDimitry Andric         Ops.push_back(getValue(Record, OpNum, NextValueNo,
46710b57cec5SDimitry Andric                                FTy->getParamType(i)));
4672*5f7ddb14SDimitry Andric         ArgsTys.push_back(FTy->getParamType(i));
46730b57cec5SDimitry Andric         if (!Ops.back())
46740b57cec5SDimitry Andric           return error("Invalid record");
46750b57cec5SDimitry Andric       }
46760b57cec5SDimitry Andric 
46770b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
46780b57cec5SDimitry Andric         if (Record.size() != OpNum)
46790b57cec5SDimitry Andric           return error("Invalid record");
46800b57cec5SDimitry Andric       } else {
46810b57cec5SDimitry Andric         // Read type/value pairs for varargs params.
46820b57cec5SDimitry Andric         while (OpNum != Record.size()) {
46830b57cec5SDimitry Andric           Value *Op;
4684*5f7ddb14SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
46850b57cec5SDimitry Andric             return error("Invalid record");
46860b57cec5SDimitry Andric           Ops.push_back(Op);
4687*5f7ddb14SDimitry Andric           ArgsTys.push_back(Op->getType());
46880b57cec5SDimitry Andric         }
46890b57cec5SDimitry Andric       }
46900b57cec5SDimitry Andric 
46910b57cec5SDimitry Andric       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
46920b57cec5SDimitry Andric                              OperandBundles);
46930b57cec5SDimitry Andric       OperandBundles.clear();
46940b57cec5SDimitry Andric       InstructionList.push_back(I);
46950b57cec5SDimitry Andric       cast<InvokeInst>(I)->setCallingConv(
46960b57cec5SDimitry Andric           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
46970b57cec5SDimitry Andric       cast<InvokeInst>(I)->setAttributes(PAL);
4698*5f7ddb14SDimitry Andric       propagateAttributeTypes(cast<CallBase>(I), ArgsTys);
46990b57cec5SDimitry Andric 
47000b57cec5SDimitry Andric       break;
47010b57cec5SDimitry Andric     }
47020b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
47030b57cec5SDimitry Andric       unsigned Idx = 0;
47040b57cec5SDimitry Andric       Value *Val = nullptr;
47050b57cec5SDimitry Andric       if (getValueTypePair(Record, Idx, NextValueNo, Val))
47060b57cec5SDimitry Andric         return error("Invalid record");
47070b57cec5SDimitry Andric       I = ResumeInst::Create(Val);
47080b57cec5SDimitry Andric       InstructionList.push_back(I);
47090b57cec5SDimitry Andric       break;
47100b57cec5SDimitry Andric     }
47110b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALLBR: {
47120b57cec5SDimitry Andric       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
47130b57cec5SDimitry Andric       unsigned OpNum = 0;
47140b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
47150b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
47160b57cec5SDimitry Andric 
47170b57cec5SDimitry Andric       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
47180b57cec5SDimitry Andric       unsigned NumIndirectDests = Record[OpNum++];
47190b57cec5SDimitry Andric       SmallVector<BasicBlock *, 16> IndirectDests;
47200b57cec5SDimitry Andric       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
47210b57cec5SDimitry Andric         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
47220b57cec5SDimitry Andric 
47230b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
47240b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
4725*5f7ddb14SDimitry Andric         FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]));
4726*5f7ddb14SDimitry Andric         if (!FTy)
47270b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
47280b57cec5SDimitry Andric       }
47290b57cec5SDimitry Andric 
47300b57cec5SDimitry Andric       Value *Callee;
4731*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
47320b57cec5SDimitry Andric         return error("Invalid record");
47330b57cec5SDimitry Andric 
47340b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
47350b57cec5SDimitry Andric       if (!OpTy)
47360b57cec5SDimitry Andric         return error("Callee is not a pointer type");
47370b57cec5SDimitry Andric       if (!FTy) {
4738*5f7ddb14SDimitry Andric         FTy = dyn_cast<FunctionType>(
4739*5f7ddb14SDimitry Andric             cast<PointerType>(Callee->getType())->getElementType());
4740*5f7ddb14SDimitry Andric         if (!FTy)
47410b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
4742*5f7ddb14SDimitry Andric       } else if (cast<PointerType>(Callee->getType())->getElementType() != FTy)
47430b57cec5SDimitry Andric         return error("Explicit call type does not match pointee type of "
47440b57cec5SDimitry Andric                      "callee operand");
47450b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
47460b57cec5SDimitry Andric         return error("Insufficient operands to call");
47470b57cec5SDimitry Andric 
47480b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
47490b57cec5SDimitry Andric       // Read the fixed params.
47500b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
47510b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
47520b57cec5SDimitry Andric           Args.push_back(getBasicBlock(Record[OpNum]));
47530b57cec5SDimitry Andric         else
47540b57cec5SDimitry Andric           Args.push_back(getValue(Record, OpNum, NextValueNo,
47550b57cec5SDimitry Andric                                   FTy->getParamType(i)));
47560b57cec5SDimitry Andric         if (!Args.back())
47570b57cec5SDimitry Andric           return error("Invalid record");
47580b57cec5SDimitry Andric       }
47590b57cec5SDimitry Andric 
47600b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
47610b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
47620b57cec5SDimitry Andric         if (OpNum != Record.size())
47630b57cec5SDimitry Andric           return error("Invalid record");
47640b57cec5SDimitry Andric       } else {
47650b57cec5SDimitry Andric         while (OpNum != Record.size()) {
47660b57cec5SDimitry Andric           Value *Op;
47670b57cec5SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
47680b57cec5SDimitry Andric             return error("Invalid record");
47690b57cec5SDimitry Andric           Args.push_back(Op);
47700b57cec5SDimitry Andric         }
47710b57cec5SDimitry Andric       }
47720b57cec5SDimitry Andric 
47730b57cec5SDimitry Andric       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
47740b57cec5SDimitry Andric                              OperandBundles);
47750b57cec5SDimitry Andric       OperandBundles.clear();
47760b57cec5SDimitry Andric       InstructionList.push_back(I);
47770b57cec5SDimitry Andric       cast<CallBrInst>(I)->setCallingConv(
47780b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
47790b57cec5SDimitry Andric       cast<CallBrInst>(I)->setAttributes(PAL);
47800b57cec5SDimitry Andric       break;
47810b57cec5SDimitry Andric     }
47820b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
47830b57cec5SDimitry Andric       I = new UnreachableInst(Context);
47840b57cec5SDimitry Andric       InstructionList.push_back(I);
47850b57cec5SDimitry Andric       break;
47860b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4787af732203SDimitry Andric       if (Record.empty())
47880b57cec5SDimitry Andric         return error("Invalid record");
47898bcb0991SDimitry Andric       // The first record specifies the type.
4790*5f7ddb14SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
47910b57cec5SDimitry Andric       if (!Ty)
47920b57cec5SDimitry Andric         return error("Invalid record");
47930b57cec5SDimitry Andric 
47948bcb0991SDimitry Andric       // Phi arguments are pairs of records of [value, basic block].
47958bcb0991SDimitry Andric       // There is an optional final record for fast-math-flags if this phi has a
47968bcb0991SDimitry Andric       // floating-point type.
47978bcb0991SDimitry Andric       size_t NumArgs = (Record.size() - 1) / 2;
47988bcb0991SDimitry Andric       PHINode *PN = PHINode::Create(Ty, NumArgs);
4799480093f4SDimitry Andric       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN))
4800480093f4SDimitry Andric         return error("Invalid record");
48010b57cec5SDimitry Andric       InstructionList.push_back(PN);
48020b57cec5SDimitry Andric 
48038bcb0991SDimitry Andric       for (unsigned i = 0; i != NumArgs; i++) {
48040b57cec5SDimitry Andric         Value *V;
48050b57cec5SDimitry Andric         // With the new function encoding, it is possible that operands have
48060b57cec5SDimitry Andric         // negative IDs (for forward references).  Use a signed VBR
48070b57cec5SDimitry Andric         // representation to keep the encoding small.
48080b57cec5SDimitry Andric         if (UseRelativeIDs)
48098bcb0991SDimitry Andric           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty);
48100b57cec5SDimitry Andric         else
48118bcb0991SDimitry Andric           V = getValue(Record, i * 2 + 1, NextValueNo, Ty);
48128bcb0991SDimitry Andric         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
48130b57cec5SDimitry Andric         if (!V || !BB)
48140b57cec5SDimitry Andric           return error("Invalid record");
48150b57cec5SDimitry Andric         PN->addIncoming(V, BB);
48160b57cec5SDimitry Andric       }
48170b57cec5SDimitry Andric       I = PN;
48188bcb0991SDimitry Andric 
48198bcb0991SDimitry Andric       // If there are an even number of records, the final record must be FMF.
48208bcb0991SDimitry Andric       if (Record.size() % 2 == 0) {
48218bcb0991SDimitry Andric         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
48228bcb0991SDimitry Andric         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
48238bcb0991SDimitry Andric         if (FMF.any())
48248bcb0991SDimitry Andric           I->setFastMathFlags(FMF);
48258bcb0991SDimitry Andric       }
48268bcb0991SDimitry Andric 
48270b57cec5SDimitry Andric       break;
48280b57cec5SDimitry Andric     }
48290b57cec5SDimitry Andric 
48300b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD:
48310b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
48320b57cec5SDimitry Andric       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
48330b57cec5SDimitry Andric       unsigned Idx = 0;
48340b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
48350b57cec5SDimitry Andric         if (Record.size() < 3)
48360b57cec5SDimitry Andric           return error("Invalid record");
48370b57cec5SDimitry Andric       } else {
48380b57cec5SDimitry Andric         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
48390b57cec5SDimitry Andric         if (Record.size() < 4)
48400b57cec5SDimitry Andric           return error("Invalid record");
48410b57cec5SDimitry Andric       }
4842*5f7ddb14SDimitry Andric       Type *Ty = getTypeByID(Record[Idx++]);
48430b57cec5SDimitry Andric       if (!Ty)
48440b57cec5SDimitry Andric         return error("Invalid record");
48450b57cec5SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
48460b57cec5SDimitry Andric         Value *PersFn = nullptr;
48470b57cec5SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
48480b57cec5SDimitry Andric           return error("Invalid record");
48490b57cec5SDimitry Andric 
48500b57cec5SDimitry Andric         if (!F->hasPersonalityFn())
48510b57cec5SDimitry Andric           F->setPersonalityFn(cast<Constant>(PersFn));
48520b57cec5SDimitry Andric         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
48530b57cec5SDimitry Andric           return error("Personality function mismatch");
48540b57cec5SDimitry Andric       }
48550b57cec5SDimitry Andric 
48560b57cec5SDimitry Andric       bool IsCleanup = !!Record[Idx++];
48570b57cec5SDimitry Andric       unsigned NumClauses = Record[Idx++];
48580b57cec5SDimitry Andric       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
48590b57cec5SDimitry Andric       LP->setCleanup(IsCleanup);
48600b57cec5SDimitry Andric       for (unsigned J = 0; J != NumClauses; ++J) {
48610b57cec5SDimitry Andric         LandingPadInst::ClauseType CT =
48620b57cec5SDimitry Andric           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
48630b57cec5SDimitry Andric         Value *Val;
48640b57cec5SDimitry Andric 
48650b57cec5SDimitry Andric         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
48660b57cec5SDimitry Andric           delete LP;
48670b57cec5SDimitry Andric           return error("Invalid record");
48680b57cec5SDimitry Andric         }
48690b57cec5SDimitry Andric 
48700b57cec5SDimitry Andric         assert((CT != LandingPadInst::Catch ||
48710b57cec5SDimitry Andric                 !isa<ArrayType>(Val->getType())) &&
48720b57cec5SDimitry Andric                "Catch clause has a invalid type!");
48730b57cec5SDimitry Andric         assert((CT != LandingPadInst::Filter ||
48740b57cec5SDimitry Andric                 isa<ArrayType>(Val->getType())) &&
48750b57cec5SDimitry Andric                "Filter clause has invalid type!");
48760b57cec5SDimitry Andric         LP->addClause(cast<Constant>(Val));
48770b57cec5SDimitry Andric       }
48780b57cec5SDimitry Andric 
48790b57cec5SDimitry Andric       I = LP;
48800b57cec5SDimitry Andric       InstructionList.push_back(I);
48810b57cec5SDimitry Andric       break;
48820b57cec5SDimitry Andric     }
48830b57cec5SDimitry Andric 
48840b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
48850b57cec5SDimitry Andric       if (Record.size() != 4)
48860b57cec5SDimitry Andric         return error("Invalid record");
4887af732203SDimitry Andric       using APV = AllocaPackedValues;
4888af732203SDimitry Andric       const uint64_t Rec = Record[3];
4889af732203SDimitry Andric       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
4890af732203SDimitry Andric       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
4891*5f7ddb14SDimitry Andric       Type *Ty = getTypeByID(Record[0]);
4892af732203SDimitry Andric       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
48930b57cec5SDimitry Andric         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
48940b57cec5SDimitry Andric         if (!PTy)
48950b57cec5SDimitry Andric           return error("Old-style alloca with a non-pointer type");
4896*5f7ddb14SDimitry Andric         Ty = PTy->getElementType();
48970b57cec5SDimitry Andric       }
48980b57cec5SDimitry Andric       Type *OpTy = getTypeByID(Record[1]);
48990b57cec5SDimitry Andric       Value *Size = getFnValueByID(Record[2], OpTy);
49008bcb0991SDimitry Andric       MaybeAlign Align;
4901af732203SDimitry Andric       if (Error Err =
4902af732203SDimitry Andric               parseAlignmentValue(Bitfield::get<APV::Align>(Rec), Align)) {
49030b57cec5SDimitry Andric         return Err;
49040b57cec5SDimitry Andric       }
49050b57cec5SDimitry Andric       if (!Ty || !Size)
49060b57cec5SDimitry Andric         return error("Invalid record");
49070b57cec5SDimitry Andric 
49080b57cec5SDimitry Andric       // FIXME: Make this an optional field.
49090b57cec5SDimitry Andric       const DataLayout &DL = TheModule->getDataLayout();
49100b57cec5SDimitry Andric       unsigned AS = DL.getAllocaAddrSpace();
49110b57cec5SDimitry Andric 
49125ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
49135ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
49145ffd83dbSDimitry Andric         return error("alloca of unsized type");
49155ffd83dbSDimitry Andric       if (!Align)
49165ffd83dbSDimitry Andric         Align = DL.getPrefTypeAlign(Ty);
49175ffd83dbSDimitry Andric 
49185ffd83dbSDimitry Andric       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
49190b57cec5SDimitry Andric       AI->setUsedWithInAlloca(InAlloca);
49200b57cec5SDimitry Andric       AI->setSwiftError(SwiftError);
49210b57cec5SDimitry Andric       I = AI;
49220b57cec5SDimitry Andric       InstructionList.push_back(I);
49230b57cec5SDimitry Andric       break;
49240b57cec5SDimitry Andric     }
49250b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
49260b57cec5SDimitry Andric       unsigned OpNum = 0;
49270b57cec5SDimitry Andric       Value *Op;
4928*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
49290b57cec5SDimitry Andric           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
49300b57cec5SDimitry Andric         return error("Invalid record");
49310b57cec5SDimitry Andric 
49320b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
49330b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
49340b57cec5SDimitry Andric 
49350b57cec5SDimitry Andric       Type *Ty = nullptr;
49360b57cec5SDimitry Andric       if (OpNum + 3 == Record.size()) {
4937*5f7ddb14SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
4938*5f7ddb14SDimitry Andric       } else {
4939*5f7ddb14SDimitry Andric         Ty = cast<PointerType>(Op->getType())->getElementType();
4940*5f7ddb14SDimitry Andric       }
49410b57cec5SDimitry Andric 
49420b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
49430b57cec5SDimitry Andric         return Err;
49440b57cec5SDimitry Andric 
49458bcb0991SDimitry Andric       MaybeAlign Align;
49460b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
49470b57cec5SDimitry Andric         return Err;
49485ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
49495ffd83dbSDimitry Andric       if (!Align && !Ty->isSized(&Visited))
49505ffd83dbSDimitry Andric         return error("load of unsized type");
49515ffd83dbSDimitry Andric       if (!Align)
49525ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
49535ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
49540b57cec5SDimitry Andric       InstructionList.push_back(I);
49550b57cec5SDimitry Andric       break;
49560b57cec5SDimitry Andric     }
49570b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_LOADATOMIC: {
49580b57cec5SDimitry Andric        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
49590b57cec5SDimitry Andric       unsigned OpNum = 0;
49600b57cec5SDimitry Andric       Value *Op;
4961*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
49620b57cec5SDimitry Andric           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
49630b57cec5SDimitry Andric         return error("Invalid record");
49640b57cec5SDimitry Andric 
49650b57cec5SDimitry Andric       if (!isa<PointerType>(Op->getType()))
49660b57cec5SDimitry Andric         return error("Load operand is not a pointer type");
49670b57cec5SDimitry Andric 
49680b57cec5SDimitry Andric       Type *Ty = nullptr;
49690b57cec5SDimitry Andric       if (OpNum + 5 == Record.size()) {
4970*5f7ddb14SDimitry Andric         Ty = getTypeByID(Record[OpNum++]);
4971*5f7ddb14SDimitry Andric       } else {
4972*5f7ddb14SDimitry Andric         Ty = cast<PointerType>(Op->getType())->getElementType();
4973*5f7ddb14SDimitry Andric       }
49740b57cec5SDimitry Andric 
49750b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
49760b57cec5SDimitry Andric         return Err;
49770b57cec5SDimitry Andric 
49780b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
49790b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
49800b57cec5SDimitry Andric           Ordering == AtomicOrdering::Release ||
49810b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
49820b57cec5SDimitry Andric         return error("Invalid record");
49830b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
49840b57cec5SDimitry Andric         return error("Invalid record");
49850b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
49860b57cec5SDimitry Andric 
49878bcb0991SDimitry Andric       MaybeAlign Align;
49880b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
49890b57cec5SDimitry Andric         return Err;
49905ffd83dbSDimitry Andric       if (!Align)
49915ffd83dbSDimitry Andric         return error("Alignment missing from atomic load");
49925ffd83dbSDimitry Andric       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
49930b57cec5SDimitry Andric       InstructionList.push_back(I);
49940b57cec5SDimitry Andric       break;
49950b57cec5SDimitry Andric     }
49960b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE:
49970b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
49980b57cec5SDimitry Andric       unsigned OpNum = 0;
49990b57cec5SDimitry Andric       Value *Val, *Ptr;
5000*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
50010b57cec5SDimitry Andric           (BitCode == bitc::FUNC_CODE_INST_STORE
50020b57cec5SDimitry Andric                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
50030b57cec5SDimitry Andric                : popValue(Record, OpNum, NextValueNo,
5004*5f7ddb14SDimitry Andric                           cast<PointerType>(Ptr->getType())->getElementType(),
5005*5f7ddb14SDimitry Andric                           Val)) ||
50060b57cec5SDimitry Andric           OpNum + 2 != Record.size())
50070b57cec5SDimitry Andric         return error("Invalid record");
50080b57cec5SDimitry Andric 
50090b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
50100b57cec5SDimitry Andric         return Err;
50118bcb0991SDimitry Andric       MaybeAlign Align;
50120b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
50130b57cec5SDimitry Andric         return Err;
50145ffd83dbSDimitry Andric       SmallPtrSet<Type *, 4> Visited;
50155ffd83dbSDimitry Andric       if (!Align && !Val->getType()->isSized(&Visited))
50165ffd83dbSDimitry Andric         return error("store of unsized type");
50175ffd83dbSDimitry Andric       if (!Align)
50185ffd83dbSDimitry Andric         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
50195ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
50200b57cec5SDimitry Andric       InstructionList.push_back(I);
50210b57cec5SDimitry Andric       break;
50220b57cec5SDimitry Andric     }
50230b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC:
50240b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
50250b57cec5SDimitry Andric       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
50260b57cec5SDimitry Andric       unsigned OpNum = 0;
50270b57cec5SDimitry Andric       Value *Val, *Ptr;
5028*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
50290b57cec5SDimitry Andric           !isa<PointerType>(Ptr->getType()) ||
50300b57cec5SDimitry Andric           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
50310b57cec5SDimitry Andric                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
50320b57cec5SDimitry Andric                : popValue(Record, OpNum, NextValueNo,
5033*5f7ddb14SDimitry Andric                           cast<PointerType>(Ptr->getType())->getElementType(),
5034*5f7ddb14SDimitry Andric                           Val)) ||
50350b57cec5SDimitry Andric           OpNum + 4 != Record.size())
50360b57cec5SDimitry Andric         return error("Invalid record");
50370b57cec5SDimitry Andric 
50380b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
50390b57cec5SDimitry Andric         return Err;
50400b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
50410b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
50420b57cec5SDimitry Andric           Ordering == AtomicOrdering::Acquire ||
50430b57cec5SDimitry Andric           Ordering == AtomicOrdering::AcquireRelease)
50440b57cec5SDimitry Andric         return error("Invalid record");
50450b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
50460b57cec5SDimitry Andric       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
50470b57cec5SDimitry Andric         return error("Invalid record");
50480b57cec5SDimitry Andric 
50498bcb0991SDimitry Andric       MaybeAlign Align;
50500b57cec5SDimitry Andric       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
50510b57cec5SDimitry Andric         return Err;
50525ffd83dbSDimitry Andric       if (!Align)
50535ffd83dbSDimitry Andric         return error("Alignment missing from atomic store");
50545ffd83dbSDimitry Andric       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
50550b57cec5SDimitry Andric       InstructionList.push_back(I);
50560b57cec5SDimitry Andric       break;
50570b57cec5SDimitry Andric     }
5058af732203SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
5059af732203SDimitry Andric       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
5060af732203SDimitry Andric       // failure_ordering?, weak?]
5061af732203SDimitry Andric       const size_t NumRecords = Record.size();
50620b57cec5SDimitry Andric       unsigned OpNum = 0;
5063af732203SDimitry Andric       Value *Ptr = nullptr;
5064*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr))
50650b57cec5SDimitry Andric         return error("Invalid record");
50660b57cec5SDimitry Andric 
50670b57cec5SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
50680b57cec5SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
50690b57cec5SDimitry Andric 
5070af732203SDimitry Andric       Value *Cmp = nullptr;
5071af732203SDimitry Andric       if (popValue(Record, OpNum, NextValueNo,
5072*5f7ddb14SDimitry Andric                    cast<PointerType>(Ptr->getType())->getPointerElementType(),
5073*5f7ddb14SDimitry Andric                    Cmp))
50740b57cec5SDimitry Andric         return error("Invalid record");
5075af732203SDimitry Andric 
5076af732203SDimitry Andric       Value *New = nullptr;
50770b57cec5SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5078af732203SDimitry Andric           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
50790b57cec5SDimitry Andric         return error("Invalid record");
50800b57cec5SDimitry Andric 
5081af732203SDimitry Andric       const AtomicOrdering SuccessOrdering =
5082af732203SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
50830b57cec5SDimitry Andric       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
50840b57cec5SDimitry Andric           SuccessOrdering == AtomicOrdering::Unordered)
50850b57cec5SDimitry Andric         return error("Invalid record");
5086af732203SDimitry Andric 
5087af732203SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
50880b57cec5SDimitry Andric 
50890b57cec5SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
50900b57cec5SDimitry Andric         return Err;
50910b57cec5SDimitry Andric 
5092af732203SDimitry Andric       const AtomicOrdering FailureOrdering =
5093af732203SDimitry Andric           NumRecords < 7
5094af732203SDimitry Andric               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
5095af732203SDimitry Andric               : getDecodedOrdering(Record[OpNum + 3]);
5096af732203SDimitry Andric 
5097*5f7ddb14SDimitry Andric       if (FailureOrdering == AtomicOrdering::NotAtomic ||
5098*5f7ddb14SDimitry Andric           FailureOrdering == AtomicOrdering::Unordered)
5099*5f7ddb14SDimitry Andric         return error("Invalid record");
5100*5f7ddb14SDimitry Andric 
5101af732203SDimitry Andric       const Align Alignment(
51025ffd83dbSDimitry Andric           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5103af732203SDimitry Andric 
51045ffd83dbSDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
51055ffd83dbSDimitry Andric                                 FailureOrdering, SSID);
51060b57cec5SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
51070b57cec5SDimitry Andric 
5108af732203SDimitry Andric       if (NumRecords < 8) {
51090b57cec5SDimitry Andric         // Before weak cmpxchgs existed, the instruction simply returned the
51100b57cec5SDimitry Andric         // value loaded from memory, so bitcode files from that era will be
51110b57cec5SDimitry Andric         // expecting the first component of a modern cmpxchg.
51120b57cec5SDimitry Andric         CurBB->getInstList().push_back(I);
51130b57cec5SDimitry Andric         I = ExtractValueInst::Create(I, 0);
51140b57cec5SDimitry Andric       } else {
51150b57cec5SDimitry Andric         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
51160b57cec5SDimitry Andric       }
51170b57cec5SDimitry Andric 
51180b57cec5SDimitry Andric       InstructionList.push_back(I);
51190b57cec5SDimitry Andric       break;
51200b57cec5SDimitry Andric     }
5121af732203SDimitry Andric     case bitc::FUNC_CODE_INST_CMPXCHG: {
5122af732203SDimitry Andric       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
5123*5f7ddb14SDimitry Andric       // failure_ordering, weak, align?]
5124af732203SDimitry Andric       const size_t NumRecords = Record.size();
5125af732203SDimitry Andric       unsigned OpNum = 0;
5126af732203SDimitry Andric       Value *Ptr = nullptr;
5127*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr))
5128af732203SDimitry Andric         return error("Invalid record");
5129af732203SDimitry Andric 
5130af732203SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
5131af732203SDimitry Andric         return error("Cmpxchg operand is not a pointer type");
5132af732203SDimitry Andric 
5133af732203SDimitry Andric       Value *Cmp = nullptr;
5134*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp))
5135af732203SDimitry Andric         return error("Invalid record");
5136af732203SDimitry Andric 
5137af732203SDimitry Andric       Value *Val = nullptr;
5138*5f7ddb14SDimitry Andric       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), Val))
5139af732203SDimitry Andric         return error("Invalid record");
5140af732203SDimitry Andric 
5141*5f7ddb14SDimitry Andric       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
5142*5f7ddb14SDimitry Andric         return error("Invalid record");
5143*5f7ddb14SDimitry Andric 
5144*5f7ddb14SDimitry Andric       const bool IsVol = Record[OpNum];
5145*5f7ddb14SDimitry Andric 
5146af732203SDimitry Andric       const AtomicOrdering SuccessOrdering =
5147af732203SDimitry Andric           getDecodedOrdering(Record[OpNum + 1]);
5148*5f7ddb14SDimitry Andric       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
5149*5f7ddb14SDimitry Andric         return error("Invalid cmpxchg success ordering");
5150af732203SDimitry Andric 
5151af732203SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5152af732203SDimitry Andric 
5153af732203SDimitry Andric       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5154af732203SDimitry Andric         return Err;
5155af732203SDimitry Andric 
5156af732203SDimitry Andric       const AtomicOrdering FailureOrdering =
5157af732203SDimitry Andric           getDecodedOrdering(Record[OpNum + 3]);
5158*5f7ddb14SDimitry Andric       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
5159*5f7ddb14SDimitry Andric         return error("Invalid cmpxchg failure ordering");
5160af732203SDimitry Andric 
5161*5f7ddb14SDimitry Andric       const bool IsWeak = Record[OpNum + 4];
5162af732203SDimitry Andric 
5163*5f7ddb14SDimitry Andric       MaybeAlign Alignment;
5164*5f7ddb14SDimitry Andric 
5165*5f7ddb14SDimitry Andric       if (NumRecords == (OpNum + 6)) {
5166*5f7ddb14SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
5167*5f7ddb14SDimitry Andric           return Err;
5168*5f7ddb14SDimitry Andric       }
5169*5f7ddb14SDimitry Andric       if (!Alignment)
5170*5f7ddb14SDimitry Andric         Alignment =
5171*5f7ddb14SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5172*5f7ddb14SDimitry Andric 
5173*5f7ddb14SDimitry Andric       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
5174af732203SDimitry Andric                                 FailureOrdering, SSID);
5175*5f7ddb14SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
5176*5f7ddb14SDimitry Andric       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
5177af732203SDimitry Andric 
5178af732203SDimitry Andric       InstructionList.push_back(I);
5179af732203SDimitry Andric       break;
5180af732203SDimitry Andric     }
5181*5f7ddb14SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
51820b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_ATOMICRMW: {
5183*5f7ddb14SDimitry Andric       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
5184*5f7ddb14SDimitry Andric       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
5185*5f7ddb14SDimitry Andric       const size_t NumRecords = Record.size();
51860b57cec5SDimitry Andric       unsigned OpNum = 0;
5187*5f7ddb14SDimitry Andric 
5188*5f7ddb14SDimitry Andric       Value *Ptr = nullptr;
5189*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr))
51900b57cec5SDimitry Andric         return error("Invalid record");
5191*5f7ddb14SDimitry Andric 
5192*5f7ddb14SDimitry Andric       if (!isa<PointerType>(Ptr->getType()))
5193*5f7ddb14SDimitry Andric         return error("Invalid record");
5194*5f7ddb14SDimitry Andric 
5195*5f7ddb14SDimitry Andric       Value *Val = nullptr;
5196*5f7ddb14SDimitry Andric       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
5197*5f7ddb14SDimitry Andric         if (popValue(Record, OpNum, NextValueNo,
5198*5f7ddb14SDimitry Andric                      cast<PointerType>(Ptr->getType())->getPointerElementType(),
5199*5f7ddb14SDimitry Andric                      Val))
5200*5f7ddb14SDimitry Andric           return error("Invalid record");
5201*5f7ddb14SDimitry Andric       } else {
5202*5f7ddb14SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Val))
5203*5f7ddb14SDimitry Andric           return error("Invalid record");
5204*5f7ddb14SDimitry Andric       }
5205*5f7ddb14SDimitry Andric 
5206*5f7ddb14SDimitry Andric       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
5207*5f7ddb14SDimitry Andric         return error("Invalid record");
5208*5f7ddb14SDimitry Andric 
5209*5f7ddb14SDimitry Andric       const AtomicRMWInst::BinOp Operation =
5210*5f7ddb14SDimitry Andric           getDecodedRMWOperation(Record[OpNum]);
52110b57cec5SDimitry Andric       if (Operation < AtomicRMWInst::FIRST_BINOP ||
52120b57cec5SDimitry Andric           Operation > AtomicRMWInst::LAST_BINOP)
52130b57cec5SDimitry Andric         return error("Invalid record");
5214*5f7ddb14SDimitry Andric 
5215*5f7ddb14SDimitry Andric       const bool IsVol = Record[OpNum + 1];
5216*5f7ddb14SDimitry Andric 
5217*5f7ddb14SDimitry Andric       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
52180b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
52190b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered)
52200b57cec5SDimitry Andric         return error("Invalid record");
5221*5f7ddb14SDimitry Andric 
5222*5f7ddb14SDimitry Andric       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5223*5f7ddb14SDimitry Andric 
5224*5f7ddb14SDimitry Andric       MaybeAlign Alignment;
5225*5f7ddb14SDimitry Andric 
5226*5f7ddb14SDimitry Andric       if (NumRecords == (OpNum + 5)) {
5227*5f7ddb14SDimitry Andric         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
5228*5f7ddb14SDimitry Andric           return Err;
5229*5f7ddb14SDimitry Andric       }
5230*5f7ddb14SDimitry Andric 
5231*5f7ddb14SDimitry Andric       if (!Alignment)
5232*5f7ddb14SDimitry Andric         Alignment =
5233*5f7ddb14SDimitry Andric             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
5234*5f7ddb14SDimitry Andric 
5235*5f7ddb14SDimitry Andric       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
5236*5f7ddb14SDimitry Andric       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
5237*5f7ddb14SDimitry Andric 
52380b57cec5SDimitry Andric       InstructionList.push_back(I);
52390b57cec5SDimitry Andric       break;
52400b57cec5SDimitry Andric     }
52410b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
52420b57cec5SDimitry Andric       if (2 != Record.size())
52430b57cec5SDimitry Andric         return error("Invalid record");
52440b57cec5SDimitry Andric       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
52450b57cec5SDimitry Andric       if (Ordering == AtomicOrdering::NotAtomic ||
52460b57cec5SDimitry Andric           Ordering == AtomicOrdering::Unordered ||
52470b57cec5SDimitry Andric           Ordering == AtomicOrdering::Monotonic)
52480b57cec5SDimitry Andric         return error("Invalid record");
52490b57cec5SDimitry Andric       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
52500b57cec5SDimitry Andric       I = new FenceInst(Context, Ordering, SSID);
52510b57cec5SDimitry Andric       InstructionList.push_back(I);
52520b57cec5SDimitry Andric       break;
52530b57cec5SDimitry Andric     }
52540b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_CALL: {
52550b57cec5SDimitry Andric       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
52560b57cec5SDimitry Andric       if (Record.size() < 3)
52570b57cec5SDimitry Andric         return error("Invalid record");
52580b57cec5SDimitry Andric 
52590b57cec5SDimitry Andric       unsigned OpNum = 0;
52600b57cec5SDimitry Andric       AttributeList PAL = getAttributes(Record[OpNum++]);
52610b57cec5SDimitry Andric       unsigned CCInfo = Record[OpNum++];
52620b57cec5SDimitry Andric 
52630b57cec5SDimitry Andric       FastMathFlags FMF;
52640b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_FMF) & 1) {
52650b57cec5SDimitry Andric         FMF = getDecodedFastMathFlags(Record[OpNum++]);
52660b57cec5SDimitry Andric         if (!FMF.any())
52670b57cec5SDimitry Andric           return error("Fast math flags indicator set for call with no FMF");
52680b57cec5SDimitry Andric       }
52690b57cec5SDimitry Andric 
52700b57cec5SDimitry Andric       FunctionType *FTy = nullptr;
52710b57cec5SDimitry Andric       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5272*5f7ddb14SDimitry Andric         FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]));
5273*5f7ddb14SDimitry Andric         if (!FTy)
52740b57cec5SDimitry Andric           return error("Explicit call type is not a function type");
52750b57cec5SDimitry Andric       }
52760b57cec5SDimitry Andric 
52770b57cec5SDimitry Andric       Value *Callee;
5278*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
52790b57cec5SDimitry Andric         return error("Invalid record");
52800b57cec5SDimitry Andric 
52810b57cec5SDimitry Andric       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
52820b57cec5SDimitry Andric       if (!OpTy)
52830b57cec5SDimitry Andric         return error("Callee is not a pointer type");
52840b57cec5SDimitry Andric       if (!FTy) {
5285*5f7ddb14SDimitry Andric         FTy = dyn_cast<FunctionType>(
5286*5f7ddb14SDimitry Andric             cast<PointerType>(Callee->getType())->getElementType());
5287*5f7ddb14SDimitry Andric         if (!FTy)
52880b57cec5SDimitry Andric           return error("Callee is not of pointer to function type");
5289*5f7ddb14SDimitry Andric       } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
52900b57cec5SDimitry Andric         return error("Explicit call type does not match pointee type of "
52910b57cec5SDimitry Andric                      "callee operand");
52920b57cec5SDimitry Andric       if (Record.size() < FTy->getNumParams() + OpNum)
52930b57cec5SDimitry Andric         return error("Insufficient operands to call");
52940b57cec5SDimitry Andric 
52950b57cec5SDimitry Andric       SmallVector<Value*, 16> Args;
5296*5f7ddb14SDimitry Andric       SmallVector<Type *, 16> ArgsTys;
52970b57cec5SDimitry Andric       // Read the fixed params.
52980b57cec5SDimitry Andric       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
52990b57cec5SDimitry Andric         if (FTy->getParamType(i)->isLabelTy())
53000b57cec5SDimitry Andric           Args.push_back(getBasicBlock(Record[OpNum]));
53010b57cec5SDimitry Andric         else
53020b57cec5SDimitry Andric           Args.push_back(getValue(Record, OpNum, NextValueNo,
53030b57cec5SDimitry Andric                                   FTy->getParamType(i)));
5304*5f7ddb14SDimitry Andric         ArgsTys.push_back(FTy->getParamType(i));
53050b57cec5SDimitry Andric         if (!Args.back())
53060b57cec5SDimitry Andric           return error("Invalid record");
53070b57cec5SDimitry Andric       }
53080b57cec5SDimitry Andric 
53090b57cec5SDimitry Andric       // Read type/value pairs for varargs params.
53100b57cec5SDimitry Andric       if (!FTy->isVarArg()) {
53110b57cec5SDimitry Andric         if (OpNum != Record.size())
53120b57cec5SDimitry Andric           return error("Invalid record");
53130b57cec5SDimitry Andric       } else {
53140b57cec5SDimitry Andric         while (OpNum != Record.size()) {
53150b57cec5SDimitry Andric           Value *Op;
5316*5f7ddb14SDimitry Andric           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
53170b57cec5SDimitry Andric             return error("Invalid record");
53180b57cec5SDimitry Andric           Args.push_back(Op);
5319*5f7ddb14SDimitry Andric           ArgsTys.push_back(Op->getType());
53200b57cec5SDimitry Andric         }
53210b57cec5SDimitry Andric       }
53220b57cec5SDimitry Andric 
53230b57cec5SDimitry Andric       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
53240b57cec5SDimitry Andric       OperandBundles.clear();
53250b57cec5SDimitry Andric       InstructionList.push_back(I);
53260b57cec5SDimitry Andric       cast<CallInst>(I)->setCallingConv(
53270b57cec5SDimitry Andric           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
53280b57cec5SDimitry Andric       CallInst::TailCallKind TCK = CallInst::TCK_None;
53290b57cec5SDimitry Andric       if (CCInfo & 1 << bitc::CALL_TAIL)
53300b57cec5SDimitry Andric         TCK = CallInst::TCK_Tail;
53310b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
53320b57cec5SDimitry Andric         TCK = CallInst::TCK_MustTail;
53330b57cec5SDimitry Andric       if (CCInfo & (1 << bitc::CALL_NOTAIL))
53340b57cec5SDimitry Andric         TCK = CallInst::TCK_NoTail;
53350b57cec5SDimitry Andric       cast<CallInst>(I)->setTailCallKind(TCK);
53360b57cec5SDimitry Andric       cast<CallInst>(I)->setAttributes(PAL);
5337*5f7ddb14SDimitry Andric       propagateAttributeTypes(cast<CallBase>(I), ArgsTys);
53380b57cec5SDimitry Andric       if (FMF.any()) {
53390b57cec5SDimitry Andric         if (!isa<FPMathOperator>(I))
53400b57cec5SDimitry Andric           return error("Fast-math-flags specified for call without "
53410b57cec5SDimitry Andric                        "floating-point scalar or vector return type");
53420b57cec5SDimitry Andric         I->setFastMathFlags(FMF);
53430b57cec5SDimitry Andric       }
53440b57cec5SDimitry Andric       break;
53450b57cec5SDimitry Andric     }
53460b57cec5SDimitry Andric     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
53470b57cec5SDimitry Andric       if (Record.size() < 3)
53480b57cec5SDimitry Andric         return error("Invalid record");
53490b57cec5SDimitry Andric       Type *OpTy = getTypeByID(Record[0]);
53500b57cec5SDimitry Andric       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5351*5f7ddb14SDimitry Andric       Type *ResTy = getTypeByID(Record[2]);
53520b57cec5SDimitry Andric       if (!OpTy || !Op || !ResTy)
53530b57cec5SDimitry Andric         return error("Invalid record");
53540b57cec5SDimitry Andric       I = new VAArgInst(Op, ResTy);
53550b57cec5SDimitry Andric       InstructionList.push_back(I);
53560b57cec5SDimitry Andric       break;
53570b57cec5SDimitry Andric     }
53580b57cec5SDimitry Andric 
53590b57cec5SDimitry Andric     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
53600b57cec5SDimitry Andric       // A call or an invoke can be optionally prefixed with some variable
53610b57cec5SDimitry Andric       // number of operand bundle blocks.  These blocks are read into
53620b57cec5SDimitry Andric       // OperandBundles and consumed at the next call or invoke instruction.
53630b57cec5SDimitry Andric 
5364af732203SDimitry Andric       if (Record.empty() || Record[0] >= BundleTags.size())
53650b57cec5SDimitry Andric         return error("Invalid record");
53660b57cec5SDimitry Andric 
53670b57cec5SDimitry Andric       std::vector<Value *> Inputs;
53680b57cec5SDimitry Andric 
53690b57cec5SDimitry Andric       unsigned OpNum = 1;
53700b57cec5SDimitry Andric       while (OpNum != Record.size()) {
53710b57cec5SDimitry Andric         Value *Op;
53720b57cec5SDimitry Andric         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
53730b57cec5SDimitry Andric           return error("Invalid record");
53740b57cec5SDimitry Andric         Inputs.push_back(Op);
53750b57cec5SDimitry Andric       }
53760b57cec5SDimitry Andric 
53770b57cec5SDimitry Andric       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
53780b57cec5SDimitry Andric       continue;
53790b57cec5SDimitry Andric     }
5380480093f4SDimitry Andric 
5381480093f4SDimitry Andric     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
5382480093f4SDimitry Andric       unsigned OpNum = 0;
5383480093f4SDimitry Andric       Value *Op = nullptr;
5384*5f7ddb14SDimitry Andric       if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5385480093f4SDimitry Andric         return error("Invalid record");
5386480093f4SDimitry Andric       if (OpNum != Record.size())
5387480093f4SDimitry Andric         return error("Invalid record");
5388480093f4SDimitry Andric 
5389480093f4SDimitry Andric       I = new FreezeInst(Op);
5390480093f4SDimitry Andric       InstructionList.push_back(I);
5391480093f4SDimitry Andric       break;
5392480093f4SDimitry Andric     }
53930b57cec5SDimitry Andric     }
53940b57cec5SDimitry Andric 
53950b57cec5SDimitry Andric     // Add instruction to end of current BB.  If there is no current BB, reject
53960b57cec5SDimitry Andric     // this file.
53970b57cec5SDimitry Andric     if (!CurBB) {
53980b57cec5SDimitry Andric       I->deleteValue();
53990b57cec5SDimitry Andric       return error("Invalid instruction with no BB");
54000b57cec5SDimitry Andric     }
54010b57cec5SDimitry Andric     if (!OperandBundles.empty()) {
54020b57cec5SDimitry Andric       I->deleteValue();
54030b57cec5SDimitry Andric       return error("Operand bundles found with no consumer");
54040b57cec5SDimitry Andric     }
54050b57cec5SDimitry Andric     CurBB->getInstList().push_back(I);
54060b57cec5SDimitry Andric 
54070b57cec5SDimitry Andric     // If this was a terminator instruction, move to the next block.
54080b57cec5SDimitry Andric     if (I->isTerminator()) {
54090b57cec5SDimitry Andric       ++CurBBNo;
54100b57cec5SDimitry Andric       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
54110b57cec5SDimitry Andric     }
54120b57cec5SDimitry Andric 
54130b57cec5SDimitry Andric     // Non-void values get registered in the value table for future use.
5414*5f7ddb14SDimitry Andric     if (!I->getType()->isVoidTy())
5415*5f7ddb14SDimitry Andric       ValueList.assignValue(I, NextValueNo++);
54160b57cec5SDimitry Andric   }
54170b57cec5SDimitry Andric 
54180b57cec5SDimitry Andric OutOfRecordLoop:
54190b57cec5SDimitry Andric 
54200b57cec5SDimitry Andric   if (!OperandBundles.empty())
54210b57cec5SDimitry Andric     return error("Operand bundles found with no consumer");
54220b57cec5SDimitry Andric 
54230b57cec5SDimitry Andric   // Check the function list for unresolved values.
54240b57cec5SDimitry Andric   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
54250b57cec5SDimitry Andric     if (!A->getParent()) {
54260b57cec5SDimitry Andric       // We found at least one unresolved value.  Nuke them all to avoid leaks.
54270b57cec5SDimitry Andric       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
54280b57cec5SDimitry Andric         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
54290b57cec5SDimitry Andric           A->replaceAllUsesWith(UndefValue::get(A->getType()));
54300b57cec5SDimitry Andric           delete A;
54310b57cec5SDimitry Andric         }
54320b57cec5SDimitry Andric       }
54330b57cec5SDimitry Andric       return error("Never resolved value found in function");
54340b57cec5SDimitry Andric     }
54350b57cec5SDimitry Andric   }
54360b57cec5SDimitry Andric 
54370b57cec5SDimitry Andric   // Unexpected unresolved metadata about to be dropped.
54380b57cec5SDimitry Andric   if (MDLoader->hasFwdRefs())
54390b57cec5SDimitry Andric     return error("Invalid function metadata: outgoing forward refs");
54400b57cec5SDimitry Andric 
54410b57cec5SDimitry Andric   // Trim the value list down to the size it was before we parsed this function.
54420b57cec5SDimitry Andric   ValueList.shrinkTo(ModuleValueListSize);
54430b57cec5SDimitry Andric   MDLoader->shrinkTo(ModuleMDLoaderSize);
54440b57cec5SDimitry Andric   std::vector<BasicBlock*>().swap(FunctionBBs);
54450b57cec5SDimitry Andric   return Error::success();
54460b57cec5SDimitry Andric }
54470b57cec5SDimitry Andric 
54480b57cec5SDimitry Andric /// Find the function body in the bitcode stream
findFunctionInStream(Function * F,DenseMap<Function *,uint64_t>::iterator DeferredFunctionInfoIterator)54490b57cec5SDimitry Andric Error BitcodeReader::findFunctionInStream(
54500b57cec5SDimitry Andric     Function *F,
54510b57cec5SDimitry Andric     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
54520b57cec5SDimitry Andric   while (DeferredFunctionInfoIterator->second == 0) {
54530b57cec5SDimitry Andric     // This is the fallback handling for the old format bitcode that
54540b57cec5SDimitry Andric     // didn't contain the function index in the VST, or when we have
54550b57cec5SDimitry Andric     // an anonymous function which would not have a VST entry.
54560b57cec5SDimitry Andric     // Assert that we have one of those two cases.
54570b57cec5SDimitry Andric     assert(VSTOffset == 0 || !F->hasName());
54580b57cec5SDimitry Andric     // Parse the next body in the stream and set its position in the
54590b57cec5SDimitry Andric     // DeferredFunctionInfo map.
54600b57cec5SDimitry Andric     if (Error Err = rememberAndSkipFunctionBodies())
54610b57cec5SDimitry Andric       return Err;
54620b57cec5SDimitry Andric   }
54630b57cec5SDimitry Andric   return Error::success();
54640b57cec5SDimitry Andric }
54650b57cec5SDimitry Andric 
getDecodedSyncScopeID(unsigned Val)54660b57cec5SDimitry Andric SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
54670b57cec5SDimitry Andric   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
54680b57cec5SDimitry Andric     return SyncScope::ID(Val);
54690b57cec5SDimitry Andric   if (Val >= SSIDs.size())
54700b57cec5SDimitry Andric     return SyncScope::System; // Map unknown synchronization scopes to system.
54710b57cec5SDimitry Andric   return SSIDs[Val];
54720b57cec5SDimitry Andric }
54730b57cec5SDimitry Andric 
54740b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
54750b57cec5SDimitry Andric // GVMaterializer implementation
54760b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
54770b57cec5SDimitry Andric 
materialize(GlobalValue * GV)54780b57cec5SDimitry Andric Error BitcodeReader::materialize(GlobalValue *GV) {
54790b57cec5SDimitry Andric   Function *F = dyn_cast<Function>(GV);
54800b57cec5SDimitry Andric   // If it's not a function or is already material, ignore the request.
54810b57cec5SDimitry Andric   if (!F || !F->isMaterializable())
54820b57cec5SDimitry Andric     return Error::success();
54830b57cec5SDimitry Andric 
54840b57cec5SDimitry Andric   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
54850b57cec5SDimitry Andric   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
54860b57cec5SDimitry Andric   // If its position is recorded as 0, its body is somewhere in the stream
54870b57cec5SDimitry Andric   // but we haven't seen it yet.
54880b57cec5SDimitry Andric   if (DFII->second == 0)
54890b57cec5SDimitry Andric     if (Error Err = findFunctionInStream(F, DFII))
54900b57cec5SDimitry Andric       return Err;
54910b57cec5SDimitry Andric 
54920b57cec5SDimitry Andric   // Materialize metadata before parsing any function bodies.
54930b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
54940b57cec5SDimitry Andric     return Err;
54950b57cec5SDimitry Andric 
54960b57cec5SDimitry Andric   // Move the bit stream to the saved position of the deferred function body.
54970b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
54980b57cec5SDimitry Andric     return JumpFailed;
54990b57cec5SDimitry Andric   if (Error Err = parseFunctionBody(F))
55000b57cec5SDimitry Andric     return Err;
55010b57cec5SDimitry Andric   F->setIsMaterializable(false);
55020b57cec5SDimitry Andric 
55030b57cec5SDimitry Andric   if (StripDebugInfo)
55040b57cec5SDimitry Andric     stripDebugInfo(*F);
55050b57cec5SDimitry Andric 
55060b57cec5SDimitry Andric   // Upgrade any old intrinsic calls in the function.
55070b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
55080b57cec5SDimitry Andric     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
55090b57cec5SDimitry Andric          UI != UE;) {
55100b57cec5SDimitry Andric       User *U = *UI;
55110b57cec5SDimitry Andric       ++UI;
55120b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
55130b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
55140b57cec5SDimitry Andric     }
55150b57cec5SDimitry Andric   }
55160b57cec5SDimitry Andric 
55170b57cec5SDimitry Andric   // Update calls to the remangled intrinsics
55180b57cec5SDimitry Andric   for (auto &I : RemangledIntrinsics)
55190b57cec5SDimitry Andric     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
55200b57cec5SDimitry Andric          UI != UE;)
55210b57cec5SDimitry Andric       // Don't expect any other users than call sites
55225ffd83dbSDimitry Andric       cast<CallBase>(*UI++)->setCalledFunction(I.second);
55230b57cec5SDimitry Andric 
55240b57cec5SDimitry Andric   // Finish fn->subprogram upgrade for materialized functions.
55250b57cec5SDimitry Andric   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
55260b57cec5SDimitry Andric     F->setSubprogram(SP);
55270b57cec5SDimitry Andric 
55280b57cec5SDimitry Andric   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
55290b57cec5SDimitry Andric   if (!MDLoader->isStrippingTBAA()) {
55300b57cec5SDimitry Andric     for (auto &I : instructions(F)) {
55310b57cec5SDimitry Andric       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
55320b57cec5SDimitry Andric       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
55330b57cec5SDimitry Andric         continue;
55340b57cec5SDimitry Andric       MDLoader->setStripTBAA(true);
55350b57cec5SDimitry Andric       stripTBAA(F->getParent());
55360b57cec5SDimitry Andric     }
55370b57cec5SDimitry Andric   }
55380b57cec5SDimitry Andric 
5539af732203SDimitry Andric   for (auto &I : instructions(F)) {
5540*5f7ddb14SDimitry Andric     // "Upgrade" older incorrect branch weights by dropping them.
5541af732203SDimitry Andric     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
5542af732203SDimitry Andric       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
5543af732203SDimitry Andric         MDString *MDS = cast<MDString>(MD->getOperand(0));
5544af732203SDimitry Andric         StringRef ProfName = MDS->getString();
5545af732203SDimitry Andric         // Check consistency of !prof branch_weights metadata.
5546af732203SDimitry Andric         if (!ProfName.equals("branch_weights"))
5547af732203SDimitry Andric           continue;
5548af732203SDimitry Andric         unsigned ExpectedNumOperands = 0;
5549af732203SDimitry Andric         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
5550af732203SDimitry Andric           ExpectedNumOperands = BI->getNumSuccessors();
5551af732203SDimitry Andric         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
5552af732203SDimitry Andric           ExpectedNumOperands = SI->getNumSuccessors();
5553af732203SDimitry Andric         else if (isa<CallInst>(&I))
5554af732203SDimitry Andric           ExpectedNumOperands = 1;
5555af732203SDimitry Andric         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
5556af732203SDimitry Andric           ExpectedNumOperands = IBI->getNumDestinations();
5557af732203SDimitry Andric         else if (isa<SelectInst>(&I))
5558af732203SDimitry Andric           ExpectedNumOperands = 2;
5559af732203SDimitry Andric         else
5560af732203SDimitry Andric           continue; // ignore and continue.
5561af732203SDimitry Andric 
5562af732203SDimitry Andric         // If branch weight doesn't match, just strip branch weight.
5563af732203SDimitry Andric         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
5564af732203SDimitry Andric           I.setMetadata(LLVMContext::MD_prof, nullptr);
5565af732203SDimitry Andric       }
5566af732203SDimitry Andric     }
5567*5f7ddb14SDimitry Andric 
5568*5f7ddb14SDimitry Andric     // Remove incompatible attributes on function calls.
5569*5f7ddb14SDimitry Andric     if (auto *CI = dyn_cast<CallBase>(&I)) {
5570*5f7ddb14SDimitry Andric       CI->removeAttributes(AttributeList::ReturnIndex,
5571*5f7ddb14SDimitry Andric                            AttributeFuncs::typeIncompatible(
5572*5f7ddb14SDimitry Andric                                CI->getFunctionType()->getReturnType()));
5573*5f7ddb14SDimitry Andric 
5574*5f7ddb14SDimitry Andric       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
5575*5f7ddb14SDimitry Andric         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
5576*5f7ddb14SDimitry Andric                                         CI->getArgOperand(ArgNo)->getType()));
5577*5f7ddb14SDimitry Andric     }
5578af732203SDimitry Andric   }
5579af732203SDimitry Andric 
55805ffd83dbSDimitry Andric   // Look for functions that rely on old function attribute behavior.
55815ffd83dbSDimitry Andric   UpgradeFunctionAttributes(*F);
55825ffd83dbSDimitry Andric 
55830b57cec5SDimitry Andric   // Bring in any functions that this function forward-referenced via
55840b57cec5SDimitry Andric   // blockaddresses.
55850b57cec5SDimitry Andric   return materializeForwardReferencedFunctions();
55860b57cec5SDimitry Andric }
55870b57cec5SDimitry Andric 
materializeModule()55880b57cec5SDimitry Andric Error BitcodeReader::materializeModule() {
55890b57cec5SDimitry Andric   if (Error Err = materializeMetadata())
55900b57cec5SDimitry Andric     return Err;
55910b57cec5SDimitry Andric 
55920b57cec5SDimitry Andric   // Promise to materialize all forward references.
55930b57cec5SDimitry Andric   WillMaterializeAllForwardRefs = true;
55940b57cec5SDimitry Andric 
55950b57cec5SDimitry Andric   // Iterate over the module, deserializing any functions that are still on
55960b57cec5SDimitry Andric   // disk.
55970b57cec5SDimitry Andric   for (Function &F : *TheModule) {
55980b57cec5SDimitry Andric     if (Error Err = materialize(&F))
55990b57cec5SDimitry Andric       return Err;
56000b57cec5SDimitry Andric   }
56010b57cec5SDimitry Andric   // At this point, if there are any function bodies, parse the rest of
56020b57cec5SDimitry Andric   // the bits in the module past the last function block we have recorded
56030b57cec5SDimitry Andric   // through either lazy scanning or the VST.
56040b57cec5SDimitry Andric   if (LastFunctionBlockBit || NextUnreadBit)
56050b57cec5SDimitry Andric     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
56060b57cec5SDimitry Andric                                     ? LastFunctionBlockBit
56070b57cec5SDimitry Andric                                     : NextUnreadBit))
56080b57cec5SDimitry Andric       return Err;
56090b57cec5SDimitry Andric 
56100b57cec5SDimitry Andric   // Check that all block address forward references got resolved (as we
56110b57cec5SDimitry Andric   // promised above).
56120b57cec5SDimitry Andric   if (!BasicBlockFwdRefs.empty())
56130b57cec5SDimitry Andric     return error("Never resolved function from blockaddress");
56140b57cec5SDimitry Andric 
56150b57cec5SDimitry Andric   // Upgrade any intrinsic calls that slipped through (should not happen!) and
56160b57cec5SDimitry Andric   // delete the old functions to clean up. We can't do this unless the entire
56170b57cec5SDimitry Andric   // module is materialized because there could always be another function body
56180b57cec5SDimitry Andric   // with calls to the old function.
56190b57cec5SDimitry Andric   for (auto &I : UpgradedIntrinsics) {
56200b57cec5SDimitry Andric     for (auto *U : I.first->users()) {
56210b57cec5SDimitry Andric       if (CallInst *CI = dyn_cast<CallInst>(U))
56220b57cec5SDimitry Andric         UpgradeIntrinsicCall(CI, I.second);
56230b57cec5SDimitry Andric     }
56240b57cec5SDimitry Andric     if (!I.first->use_empty())
56250b57cec5SDimitry Andric       I.first->replaceAllUsesWith(I.second);
56260b57cec5SDimitry Andric     I.first->eraseFromParent();
56270b57cec5SDimitry Andric   }
56280b57cec5SDimitry Andric   UpgradedIntrinsics.clear();
56290b57cec5SDimitry Andric   // Do the same for remangled intrinsics
56300b57cec5SDimitry Andric   for (auto &I : RemangledIntrinsics) {
56310b57cec5SDimitry Andric     I.first->replaceAllUsesWith(I.second);
56320b57cec5SDimitry Andric     I.first->eraseFromParent();
56330b57cec5SDimitry Andric   }
56340b57cec5SDimitry Andric   RemangledIntrinsics.clear();
56350b57cec5SDimitry Andric 
56360b57cec5SDimitry Andric   UpgradeDebugInfo(*TheModule);
56370b57cec5SDimitry Andric 
56380b57cec5SDimitry Andric   UpgradeModuleFlags(*TheModule);
56390b57cec5SDimitry Andric 
56408bcb0991SDimitry Andric   UpgradeARCRuntime(*TheModule);
56410b57cec5SDimitry Andric 
56420b57cec5SDimitry Andric   return Error::success();
56430b57cec5SDimitry Andric }
56440b57cec5SDimitry Andric 
getIdentifiedStructTypes() const56450b57cec5SDimitry Andric std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
56460b57cec5SDimitry Andric   return IdentifiedStructTypes;
56470b57cec5SDimitry Andric }
56480b57cec5SDimitry Andric 
ModuleSummaryIndexBitcodeReader(BitstreamCursor Cursor,StringRef Strtab,ModuleSummaryIndex & TheIndex,StringRef ModulePath,unsigned ModuleId)56490b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
56500b57cec5SDimitry Andric     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
56510b57cec5SDimitry Andric     StringRef ModulePath, unsigned ModuleId)
56520b57cec5SDimitry Andric     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
56530b57cec5SDimitry Andric       ModulePath(ModulePath), ModuleId(ModuleId) {}
56540b57cec5SDimitry Andric 
addThisModule()56550b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::addThisModule() {
56560b57cec5SDimitry Andric   TheIndex.addModule(ModulePath, ModuleId);
56570b57cec5SDimitry Andric }
56580b57cec5SDimitry Andric 
56590b57cec5SDimitry Andric ModuleSummaryIndex::ModuleInfo *
getThisModule()56600b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getThisModule() {
56610b57cec5SDimitry Andric   return TheIndex.getModule(ModulePath);
56620b57cec5SDimitry Andric }
56630b57cec5SDimitry Andric 
56640b57cec5SDimitry Andric std::pair<ValueInfo, GlobalValue::GUID>
getValueInfoFromValueId(unsigned ValueId)56650b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
56660b57cec5SDimitry Andric   auto VGI = ValueIdToValueInfoMap[ValueId];
56670b57cec5SDimitry Andric   assert(VGI.first);
56680b57cec5SDimitry Andric   return VGI;
56690b57cec5SDimitry Andric }
56700b57cec5SDimitry Andric 
setValueGUID(uint64_t ValueID,StringRef ValueName,GlobalValue::LinkageTypes Linkage,StringRef SourceFileName)56710b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::setValueGUID(
56720b57cec5SDimitry Andric     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
56730b57cec5SDimitry Andric     StringRef SourceFileName) {
56740b57cec5SDimitry Andric   std::string GlobalId =
56750b57cec5SDimitry Andric       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
56760b57cec5SDimitry Andric   auto ValueGUID = GlobalValue::getGUID(GlobalId);
56770b57cec5SDimitry Andric   auto OriginalNameID = ValueGUID;
56780b57cec5SDimitry Andric   if (GlobalValue::isLocalLinkage(Linkage))
56790b57cec5SDimitry Andric     OriginalNameID = GlobalValue::getGUID(ValueName);
56800b57cec5SDimitry Andric   if (PrintSummaryGUIDs)
56810b57cec5SDimitry Andric     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
56820b57cec5SDimitry Andric            << ValueName << "\n";
56830b57cec5SDimitry Andric 
56840b57cec5SDimitry Andric   // UseStrtab is false for legacy summary formats and value names are
56850b57cec5SDimitry Andric   // created on stack. In that case we save the name in a string saver in
56860b57cec5SDimitry Andric   // the index so that the value name can be recorded.
56870b57cec5SDimitry Andric   ValueIdToValueInfoMap[ValueID] = std::make_pair(
56880b57cec5SDimitry Andric       TheIndex.getOrInsertValueInfo(
56890b57cec5SDimitry Andric           ValueGUID,
56900b57cec5SDimitry Andric           UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
56910b57cec5SDimitry Andric       OriginalNameID);
56920b57cec5SDimitry Andric }
56930b57cec5SDimitry Andric 
56940b57cec5SDimitry Andric // Specialized value symbol table parser used when reading module index
56950b57cec5SDimitry Andric // blocks where we don't actually create global values. The parsed information
56960b57cec5SDimitry Andric // is saved in the bitcode reader for use when later parsing summaries.
parseValueSymbolTable(uint64_t Offset,DenseMap<unsigned,GlobalValue::LinkageTypes> & ValueIdToLinkageMap)56970b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
56980b57cec5SDimitry Andric     uint64_t Offset,
56990b57cec5SDimitry Andric     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
57000b57cec5SDimitry Andric   // With a strtab the VST is not required to parse the summary.
57010b57cec5SDimitry Andric   if (UseStrtab)
57020b57cec5SDimitry Andric     return Error::success();
57030b57cec5SDimitry Andric 
57040b57cec5SDimitry Andric   assert(Offset > 0 && "Expected non-zero VST offset");
57050b57cec5SDimitry Andric   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
57060b57cec5SDimitry Andric   if (!MaybeCurrentBit)
57070b57cec5SDimitry Andric     return MaybeCurrentBit.takeError();
57080b57cec5SDimitry Andric   uint64_t CurrentBit = MaybeCurrentBit.get();
57090b57cec5SDimitry Andric 
57100b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
57110b57cec5SDimitry Andric     return Err;
57120b57cec5SDimitry Andric 
57130b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
57140b57cec5SDimitry Andric 
57150b57cec5SDimitry Andric   // Read all the records for this value table.
57160b57cec5SDimitry Andric   SmallString<128> ValueName;
57170b57cec5SDimitry Andric 
57180b57cec5SDimitry Andric   while (true) {
57190b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
57200b57cec5SDimitry Andric     if (!MaybeEntry)
57210b57cec5SDimitry Andric       return MaybeEntry.takeError();
57220b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
57230b57cec5SDimitry Andric 
57240b57cec5SDimitry Andric     switch (Entry.Kind) {
57250b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
57260b57cec5SDimitry Andric     case BitstreamEntry::Error:
57270b57cec5SDimitry Andric       return error("Malformed block");
57280b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
57290b57cec5SDimitry Andric       // Done parsing VST, jump back to wherever we came from.
57300b57cec5SDimitry Andric       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
57310b57cec5SDimitry Andric         return JumpFailed;
57320b57cec5SDimitry Andric       return Error::success();
57330b57cec5SDimitry Andric     case BitstreamEntry::Record:
57340b57cec5SDimitry Andric       // The interesting case.
57350b57cec5SDimitry Andric       break;
57360b57cec5SDimitry Andric     }
57370b57cec5SDimitry Andric 
57380b57cec5SDimitry Andric     // Read a record.
57390b57cec5SDimitry Andric     Record.clear();
57400b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
57410b57cec5SDimitry Andric     if (!MaybeRecord)
57420b57cec5SDimitry Andric       return MaybeRecord.takeError();
57430b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
57440b57cec5SDimitry Andric     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
57450b57cec5SDimitry Andric       break;
57460b57cec5SDimitry Andric     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
57470b57cec5SDimitry Andric       if (convertToString(Record, 1, ValueName))
57480b57cec5SDimitry Andric         return error("Invalid record");
57490b57cec5SDimitry Andric       unsigned ValueID = Record[0];
57500b57cec5SDimitry Andric       assert(!SourceFileName.empty());
57510b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
57520b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
57530b57cec5SDimitry Andric              "No linkage found for VST entry?");
57540b57cec5SDimitry Andric       auto Linkage = VLI->second;
57550b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
57560b57cec5SDimitry Andric       ValueName.clear();
57570b57cec5SDimitry Andric       break;
57580b57cec5SDimitry Andric     }
57590b57cec5SDimitry Andric     case bitc::VST_CODE_FNENTRY: {
57600b57cec5SDimitry Andric       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
57610b57cec5SDimitry Andric       if (convertToString(Record, 2, ValueName))
57620b57cec5SDimitry Andric         return error("Invalid record");
57630b57cec5SDimitry Andric       unsigned ValueID = Record[0];
57640b57cec5SDimitry Andric       assert(!SourceFileName.empty());
57650b57cec5SDimitry Andric       auto VLI = ValueIdToLinkageMap.find(ValueID);
57660b57cec5SDimitry Andric       assert(VLI != ValueIdToLinkageMap.end() &&
57670b57cec5SDimitry Andric              "No linkage found for VST entry?");
57680b57cec5SDimitry Andric       auto Linkage = VLI->second;
57690b57cec5SDimitry Andric       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
57700b57cec5SDimitry Andric       ValueName.clear();
57710b57cec5SDimitry Andric       break;
57720b57cec5SDimitry Andric     }
57730b57cec5SDimitry Andric     case bitc::VST_CODE_COMBINED_ENTRY: {
57740b57cec5SDimitry Andric       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
57750b57cec5SDimitry Andric       unsigned ValueID = Record[0];
57760b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
57770b57cec5SDimitry Andric       // The "original name", which is the second value of the pair will be
57780b57cec5SDimitry Andric       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
57790b57cec5SDimitry Andric       ValueIdToValueInfoMap[ValueID] =
57800b57cec5SDimitry Andric           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
57810b57cec5SDimitry Andric       break;
57820b57cec5SDimitry Andric     }
57830b57cec5SDimitry Andric     }
57840b57cec5SDimitry Andric   }
57850b57cec5SDimitry Andric }
57860b57cec5SDimitry Andric 
57870b57cec5SDimitry Andric // Parse just the blocks needed for building the index out of the module.
57880b57cec5SDimitry Andric // At the end of this routine the module Index is populated with a map
57890b57cec5SDimitry Andric // from global value id to GlobalValueSummary objects.
parseModule()57900b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModule() {
57910b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
57920b57cec5SDimitry Andric     return Err;
57930b57cec5SDimitry Andric 
57940b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
57950b57cec5SDimitry Andric   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
57960b57cec5SDimitry Andric   unsigned ValueId = 0;
57970b57cec5SDimitry Andric 
57980b57cec5SDimitry Andric   // Read the index for this module.
57990b57cec5SDimitry Andric   while (true) {
58000b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
58010b57cec5SDimitry Andric     if (!MaybeEntry)
58020b57cec5SDimitry Andric       return MaybeEntry.takeError();
58030b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
58040b57cec5SDimitry Andric 
58050b57cec5SDimitry Andric     switch (Entry.Kind) {
58060b57cec5SDimitry Andric     case BitstreamEntry::Error:
58070b57cec5SDimitry Andric       return error("Malformed block");
58080b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
58090b57cec5SDimitry Andric       return Error::success();
58100b57cec5SDimitry Andric 
58110b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
58120b57cec5SDimitry Andric       switch (Entry.ID) {
58130b57cec5SDimitry Andric       default: // Skip unknown content.
58140b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
58150b57cec5SDimitry Andric           return Err;
58160b57cec5SDimitry Andric         break;
58170b57cec5SDimitry Andric       case bitc::BLOCKINFO_BLOCK_ID:
58180b57cec5SDimitry Andric         // Need to parse these to get abbrev ids (e.g. for VST)
58190b57cec5SDimitry Andric         if (readBlockInfo())
58200b57cec5SDimitry Andric           return error("Malformed block");
58210b57cec5SDimitry Andric         break;
58220b57cec5SDimitry Andric       case bitc::VALUE_SYMTAB_BLOCK_ID:
58230b57cec5SDimitry Andric         // Should have been parsed earlier via VSTOffset, unless there
58240b57cec5SDimitry Andric         // is no summary section.
58250b57cec5SDimitry Andric         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
58260b57cec5SDimitry Andric                 !SeenGlobalValSummary) &&
58270b57cec5SDimitry Andric                "Expected early VST parse via VSTOffset record");
58280b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
58290b57cec5SDimitry Andric           return Err;
58300b57cec5SDimitry Andric         break;
58310b57cec5SDimitry Andric       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
58320b57cec5SDimitry Andric       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
58330b57cec5SDimitry Andric         // Add the module if it is a per-module index (has a source file name).
58340b57cec5SDimitry Andric         if (!SourceFileName.empty())
58350b57cec5SDimitry Andric           addThisModule();
58360b57cec5SDimitry Andric         assert(!SeenValueSymbolTable &&
58370b57cec5SDimitry Andric                "Already read VST when parsing summary block?");
58380b57cec5SDimitry Andric         // We might not have a VST if there were no values in the
58390b57cec5SDimitry Andric         // summary. An empty summary block generated when we are
58400b57cec5SDimitry Andric         // performing ThinLTO compiles so we don't later invoke
58410b57cec5SDimitry Andric         // the regular LTO process on them.
58420b57cec5SDimitry Andric         if (VSTOffset > 0) {
58430b57cec5SDimitry Andric           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
58440b57cec5SDimitry Andric             return Err;
58450b57cec5SDimitry Andric           SeenValueSymbolTable = true;
58460b57cec5SDimitry Andric         }
58470b57cec5SDimitry Andric         SeenGlobalValSummary = true;
58480b57cec5SDimitry Andric         if (Error Err = parseEntireSummary(Entry.ID))
58490b57cec5SDimitry Andric           return Err;
58500b57cec5SDimitry Andric         break;
58510b57cec5SDimitry Andric       case bitc::MODULE_STRTAB_BLOCK_ID:
58520b57cec5SDimitry Andric         if (Error Err = parseModuleStringTable())
58530b57cec5SDimitry Andric           return Err;
58540b57cec5SDimitry Andric         break;
58550b57cec5SDimitry Andric       }
58560b57cec5SDimitry Andric       continue;
58570b57cec5SDimitry Andric 
58580b57cec5SDimitry Andric     case BitstreamEntry::Record: {
58590b57cec5SDimitry Andric         Record.clear();
58600b57cec5SDimitry Andric         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
58610b57cec5SDimitry Andric         if (!MaybeBitCode)
58620b57cec5SDimitry Andric           return MaybeBitCode.takeError();
58630b57cec5SDimitry Andric         switch (MaybeBitCode.get()) {
58640b57cec5SDimitry Andric         default:
58650b57cec5SDimitry Andric           break; // Default behavior, ignore unknown content.
58660b57cec5SDimitry Andric         case bitc::MODULE_CODE_VERSION: {
58670b57cec5SDimitry Andric           if (Error Err = parseVersionRecord(Record).takeError())
58680b57cec5SDimitry Andric             return Err;
58690b57cec5SDimitry Andric           break;
58700b57cec5SDimitry Andric         }
58710b57cec5SDimitry Andric         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
58720b57cec5SDimitry Andric         case bitc::MODULE_CODE_SOURCE_FILENAME: {
58730b57cec5SDimitry Andric           SmallString<128> ValueName;
58740b57cec5SDimitry Andric           if (convertToString(Record, 0, ValueName))
58750b57cec5SDimitry Andric             return error("Invalid record");
58760b57cec5SDimitry Andric           SourceFileName = ValueName.c_str();
58770b57cec5SDimitry Andric           break;
58780b57cec5SDimitry Andric         }
58790b57cec5SDimitry Andric         /// MODULE_CODE_HASH: [5*i32]
58800b57cec5SDimitry Andric         case bitc::MODULE_CODE_HASH: {
58810b57cec5SDimitry Andric           if (Record.size() != 5)
58820b57cec5SDimitry Andric             return error("Invalid hash length " + Twine(Record.size()).str());
58830b57cec5SDimitry Andric           auto &Hash = getThisModule()->second.second;
58840b57cec5SDimitry Andric           int Pos = 0;
58850b57cec5SDimitry Andric           for (auto &Val : Record) {
58860b57cec5SDimitry Andric             assert(!(Val >> 32) && "Unexpected high bits set");
58870b57cec5SDimitry Andric             Hash[Pos++] = Val;
58880b57cec5SDimitry Andric           }
58890b57cec5SDimitry Andric           break;
58900b57cec5SDimitry Andric         }
58910b57cec5SDimitry Andric         /// MODULE_CODE_VSTOFFSET: [offset]
58920b57cec5SDimitry Andric         case bitc::MODULE_CODE_VSTOFFSET:
5893af732203SDimitry Andric           if (Record.empty())
58940b57cec5SDimitry Andric             return error("Invalid record");
58950b57cec5SDimitry Andric           // Note that we subtract 1 here because the offset is relative to one
58960b57cec5SDimitry Andric           // word before the start of the identification or module block, which
58970b57cec5SDimitry Andric           // was historically always the start of the regular bitcode header.
58980b57cec5SDimitry Andric           VSTOffset = Record[0] - 1;
58990b57cec5SDimitry Andric           break;
59000b57cec5SDimitry Andric         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
59010b57cec5SDimitry Andric         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
59020b57cec5SDimitry Andric         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
59030b57cec5SDimitry Andric         // v2: [strtab offset, strtab size, v1]
59040b57cec5SDimitry Andric         case bitc::MODULE_CODE_GLOBALVAR:
59050b57cec5SDimitry Andric         case bitc::MODULE_CODE_FUNCTION:
59060b57cec5SDimitry Andric         case bitc::MODULE_CODE_ALIAS: {
59070b57cec5SDimitry Andric           StringRef Name;
59080b57cec5SDimitry Andric           ArrayRef<uint64_t> GVRecord;
59090b57cec5SDimitry Andric           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
59100b57cec5SDimitry Andric           if (GVRecord.size() <= 3)
59110b57cec5SDimitry Andric             return error("Invalid record");
59120b57cec5SDimitry Andric           uint64_t RawLinkage = GVRecord[3];
59130b57cec5SDimitry Andric           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
59140b57cec5SDimitry Andric           if (!UseStrtab) {
59150b57cec5SDimitry Andric             ValueIdToLinkageMap[ValueId++] = Linkage;
59160b57cec5SDimitry Andric             break;
59170b57cec5SDimitry Andric           }
59180b57cec5SDimitry Andric 
59190b57cec5SDimitry Andric           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
59200b57cec5SDimitry Andric           break;
59210b57cec5SDimitry Andric         }
59220b57cec5SDimitry Andric         }
59230b57cec5SDimitry Andric       }
59240b57cec5SDimitry Andric       continue;
59250b57cec5SDimitry Andric     }
59260b57cec5SDimitry Andric   }
59270b57cec5SDimitry Andric }
59280b57cec5SDimitry Andric 
59290b57cec5SDimitry Andric std::vector<ValueInfo>
makeRefList(ArrayRef<uint64_t> Record)59300b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
59310b57cec5SDimitry Andric   std::vector<ValueInfo> Ret;
59320b57cec5SDimitry Andric   Ret.reserve(Record.size());
59330b57cec5SDimitry Andric   for (uint64_t RefValueId : Record)
59340b57cec5SDimitry Andric     Ret.push_back(getValueInfoFromValueId(RefValueId).first);
59350b57cec5SDimitry Andric   return Ret;
59360b57cec5SDimitry Andric }
59370b57cec5SDimitry Andric 
59380b57cec5SDimitry Andric std::vector<FunctionSummary::EdgeTy>
makeCallList(ArrayRef<uint64_t> Record,bool IsOldProfileFormat,bool HasProfile,bool HasRelBF)59390b57cec5SDimitry Andric ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
59400b57cec5SDimitry Andric                                               bool IsOldProfileFormat,
59410b57cec5SDimitry Andric                                               bool HasProfile, bool HasRelBF) {
59420b57cec5SDimitry Andric   std::vector<FunctionSummary::EdgeTy> Ret;
59430b57cec5SDimitry Andric   Ret.reserve(Record.size());
59440b57cec5SDimitry Andric   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
59450b57cec5SDimitry Andric     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
59460b57cec5SDimitry Andric     uint64_t RelBF = 0;
59470b57cec5SDimitry Andric     ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
59480b57cec5SDimitry Andric     if (IsOldProfileFormat) {
59490b57cec5SDimitry Andric       I += 1; // Skip old callsitecount field
59500b57cec5SDimitry Andric       if (HasProfile)
59510b57cec5SDimitry Andric         I += 1; // Skip old profilecount field
59520b57cec5SDimitry Andric     } else if (HasProfile)
59530b57cec5SDimitry Andric       Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
59540b57cec5SDimitry Andric     else if (HasRelBF)
59550b57cec5SDimitry Andric       RelBF = Record[++I];
59560b57cec5SDimitry Andric     Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
59570b57cec5SDimitry Andric   }
59580b57cec5SDimitry Andric   return Ret;
59590b57cec5SDimitry Andric }
59600b57cec5SDimitry Andric 
59610b57cec5SDimitry Andric static void
parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record,size_t & Slot,WholeProgramDevirtResolution & Wpd)59620b57cec5SDimitry Andric parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
59630b57cec5SDimitry Andric                                        WholeProgramDevirtResolution &Wpd) {
59640b57cec5SDimitry Andric   uint64_t ArgNum = Record[Slot++];
59650b57cec5SDimitry Andric   WholeProgramDevirtResolution::ByArg &B =
59660b57cec5SDimitry Andric       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
59670b57cec5SDimitry Andric   Slot += ArgNum;
59680b57cec5SDimitry Andric 
59690b57cec5SDimitry Andric   B.TheKind =
59700b57cec5SDimitry Andric       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
59710b57cec5SDimitry Andric   B.Info = Record[Slot++];
59720b57cec5SDimitry Andric   B.Byte = Record[Slot++];
59730b57cec5SDimitry Andric   B.Bit = Record[Slot++];
59740b57cec5SDimitry Andric }
59750b57cec5SDimitry Andric 
parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,StringRef Strtab,size_t & Slot,TypeIdSummary & TypeId)59760b57cec5SDimitry Andric static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
59770b57cec5SDimitry Andric                                               StringRef Strtab, size_t &Slot,
59780b57cec5SDimitry Andric                                               TypeIdSummary &TypeId) {
59790b57cec5SDimitry Andric   uint64_t Id = Record[Slot++];
59800b57cec5SDimitry Andric   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
59810b57cec5SDimitry Andric 
59820b57cec5SDimitry Andric   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
59830b57cec5SDimitry Andric   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
59840b57cec5SDimitry Andric                         static_cast<size_t>(Record[Slot + 1])};
59850b57cec5SDimitry Andric   Slot += 2;
59860b57cec5SDimitry Andric 
59870b57cec5SDimitry Andric   uint64_t ResByArgNum = Record[Slot++];
59880b57cec5SDimitry Andric   for (uint64_t I = 0; I != ResByArgNum; ++I)
59890b57cec5SDimitry Andric     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
59900b57cec5SDimitry Andric }
59910b57cec5SDimitry Andric 
parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,StringRef Strtab,ModuleSummaryIndex & TheIndex)59920b57cec5SDimitry Andric static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
59930b57cec5SDimitry Andric                                      StringRef Strtab,
59940b57cec5SDimitry Andric                                      ModuleSummaryIndex &TheIndex) {
59950b57cec5SDimitry Andric   size_t Slot = 0;
59960b57cec5SDimitry Andric   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
59970b57cec5SDimitry Andric       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
59980b57cec5SDimitry Andric   Slot += 2;
59990b57cec5SDimitry Andric 
60000b57cec5SDimitry Andric   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
60010b57cec5SDimitry Andric   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
60020b57cec5SDimitry Andric   TypeId.TTRes.AlignLog2 = Record[Slot++];
60030b57cec5SDimitry Andric   TypeId.TTRes.SizeM1 = Record[Slot++];
60040b57cec5SDimitry Andric   TypeId.TTRes.BitMask = Record[Slot++];
60050b57cec5SDimitry Andric   TypeId.TTRes.InlineBits = Record[Slot++];
60060b57cec5SDimitry Andric 
60070b57cec5SDimitry Andric   while (Slot < Record.size())
60080b57cec5SDimitry Andric     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
60090b57cec5SDimitry Andric }
60100b57cec5SDimitry Andric 
6011af732203SDimitry Andric std::vector<FunctionSummary::ParamAccess>
parseParamAccesses(ArrayRef<uint64_t> Record)6012af732203SDimitry Andric ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
60135ffd83dbSDimitry Andric   auto ReadRange = [&]() {
60145ffd83dbSDimitry Andric     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
60155ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
60165ffd83dbSDimitry Andric     Record = Record.drop_front();
60175ffd83dbSDimitry Andric     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
60185ffd83dbSDimitry Andric                 BitcodeReader::decodeSignRotatedValue(Record.front()));
60195ffd83dbSDimitry Andric     Record = Record.drop_front();
60205ffd83dbSDimitry Andric     ConstantRange Range{Lower, Upper};
60215ffd83dbSDimitry Andric     assert(!Range.isFullSet());
60225ffd83dbSDimitry Andric     assert(!Range.isUpperSignWrapped());
60235ffd83dbSDimitry Andric     return Range;
60245ffd83dbSDimitry Andric   };
60255ffd83dbSDimitry Andric 
60265ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
60275ffd83dbSDimitry Andric   while (!Record.empty()) {
60285ffd83dbSDimitry Andric     PendingParamAccesses.emplace_back();
60295ffd83dbSDimitry Andric     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
60305ffd83dbSDimitry Andric     ParamAccess.ParamNo = Record.front();
60315ffd83dbSDimitry Andric     Record = Record.drop_front();
60325ffd83dbSDimitry Andric     ParamAccess.Use = ReadRange();
60335ffd83dbSDimitry Andric     ParamAccess.Calls.resize(Record.front());
60345ffd83dbSDimitry Andric     Record = Record.drop_front();
60355ffd83dbSDimitry Andric     for (auto &Call : ParamAccess.Calls) {
60365ffd83dbSDimitry Andric       Call.ParamNo = Record.front();
60375ffd83dbSDimitry Andric       Record = Record.drop_front();
6038af732203SDimitry Andric       Call.Callee = getValueInfoFromValueId(Record.front()).first;
60395ffd83dbSDimitry Andric       Record = Record.drop_front();
60405ffd83dbSDimitry Andric       Call.Offsets = ReadRange();
60415ffd83dbSDimitry Andric     }
60425ffd83dbSDimitry Andric   }
60435ffd83dbSDimitry Andric   return PendingParamAccesses;
60445ffd83dbSDimitry Andric }
60455ffd83dbSDimitry Andric 
parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record,size_t & Slot,TypeIdCompatibleVtableInfo & TypeId)60460b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
60470b57cec5SDimitry Andric     ArrayRef<uint64_t> Record, size_t &Slot,
60480b57cec5SDimitry Andric     TypeIdCompatibleVtableInfo &TypeId) {
60490b57cec5SDimitry Andric   uint64_t Offset = Record[Slot++];
60500b57cec5SDimitry Andric   ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first;
60510b57cec5SDimitry Andric   TypeId.push_back({Offset, Callee});
60520b57cec5SDimitry Andric }
60530b57cec5SDimitry Andric 
parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record)60540b57cec5SDimitry Andric void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
60550b57cec5SDimitry Andric     ArrayRef<uint64_t> Record) {
60560b57cec5SDimitry Andric   size_t Slot = 0;
60570b57cec5SDimitry Andric   TypeIdCompatibleVtableInfo &TypeId =
60580b57cec5SDimitry Andric       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
60590b57cec5SDimitry Andric           {Strtab.data() + Record[Slot],
60600b57cec5SDimitry Andric            static_cast<size_t>(Record[Slot + 1])});
60610b57cec5SDimitry Andric   Slot += 2;
60620b57cec5SDimitry Andric 
60630b57cec5SDimitry Andric   while (Slot < Record.size())
60640b57cec5SDimitry Andric     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
60650b57cec5SDimitry Andric }
60660b57cec5SDimitry Andric 
setSpecialRefs(std::vector<ValueInfo> & Refs,unsigned ROCnt,unsigned WOCnt)60670b57cec5SDimitry Andric static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
60680b57cec5SDimitry Andric                            unsigned WOCnt) {
60690b57cec5SDimitry Andric   // Readonly and writeonly refs are in the end of the refs list.
60700b57cec5SDimitry Andric   assert(ROCnt + WOCnt <= Refs.size());
60710b57cec5SDimitry Andric   unsigned FirstWORef = Refs.size() - WOCnt;
60720b57cec5SDimitry Andric   unsigned RefNo = FirstWORef - ROCnt;
60730b57cec5SDimitry Andric   for (; RefNo < FirstWORef; ++RefNo)
60740b57cec5SDimitry Andric     Refs[RefNo].setReadOnly();
60750b57cec5SDimitry Andric   for (; RefNo < Refs.size(); ++RefNo)
60760b57cec5SDimitry Andric     Refs[RefNo].setWriteOnly();
60770b57cec5SDimitry Andric }
60780b57cec5SDimitry Andric 
60790b57cec5SDimitry Andric // Eagerly parse the entire summary block. This populates the GlobalValueSummary
60800b57cec5SDimitry Andric // objects in the index.
parseEntireSummary(unsigned ID)60810b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
60820b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
60830b57cec5SDimitry Andric     return Err;
60840b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
60850b57cec5SDimitry Andric 
60860b57cec5SDimitry Andric   // Parse version
60870b57cec5SDimitry Andric   {
60880b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
60890b57cec5SDimitry Andric     if (!MaybeEntry)
60900b57cec5SDimitry Andric       return MaybeEntry.takeError();
60910b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
60920b57cec5SDimitry Andric 
60930b57cec5SDimitry Andric     if (Entry.Kind != BitstreamEntry::Record)
60940b57cec5SDimitry Andric       return error("Invalid Summary Block: record for version expected");
60950b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
60960b57cec5SDimitry Andric     if (!MaybeRecord)
60970b57cec5SDimitry Andric       return MaybeRecord.takeError();
60980b57cec5SDimitry Andric     if (MaybeRecord.get() != bitc::FS_VERSION)
60990b57cec5SDimitry Andric       return error("Invalid Summary Block: version expected");
61000b57cec5SDimitry Andric   }
61010b57cec5SDimitry Andric   const uint64_t Version = Record[0];
61020b57cec5SDimitry Andric   const bool IsOldProfileFormat = Version == 1;
6103480093f4SDimitry Andric   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
61040b57cec5SDimitry Andric     return error("Invalid summary version " + Twine(Version) +
6105480093f4SDimitry Andric                  ". Version should be in the range [1-" +
6106480093f4SDimitry Andric                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
6107480093f4SDimitry Andric                  "].");
61080b57cec5SDimitry Andric   Record.clear();
61090b57cec5SDimitry Andric 
61100b57cec5SDimitry Andric   // Keep around the last seen summary to be used when we see an optional
61110b57cec5SDimitry Andric   // "OriginalName" attachement.
61120b57cec5SDimitry Andric   GlobalValueSummary *LastSeenSummary = nullptr;
61130b57cec5SDimitry Andric   GlobalValue::GUID LastSeenGUID = 0;
61140b57cec5SDimitry Andric 
61150b57cec5SDimitry Andric   // We can expect to see any number of type ID information records before
61160b57cec5SDimitry Andric   // each function summary records; these variables store the information
61170b57cec5SDimitry Andric   // collected so far so that it can be used to create the summary object.
61180b57cec5SDimitry Andric   std::vector<GlobalValue::GUID> PendingTypeTests;
61190b57cec5SDimitry Andric   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
61200b57cec5SDimitry Andric       PendingTypeCheckedLoadVCalls;
61210b57cec5SDimitry Andric   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
61220b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls;
61235ffd83dbSDimitry Andric   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
61240b57cec5SDimitry Andric 
61250b57cec5SDimitry Andric   while (true) {
61260b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
61270b57cec5SDimitry Andric     if (!MaybeEntry)
61280b57cec5SDimitry Andric       return MaybeEntry.takeError();
61290b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
61300b57cec5SDimitry Andric 
61310b57cec5SDimitry Andric     switch (Entry.Kind) {
61320b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
61330b57cec5SDimitry Andric     case BitstreamEntry::Error:
61340b57cec5SDimitry Andric       return error("Malformed block");
61350b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
61360b57cec5SDimitry Andric       return Error::success();
61370b57cec5SDimitry Andric     case BitstreamEntry::Record:
61380b57cec5SDimitry Andric       // The interesting case.
61390b57cec5SDimitry Andric       break;
61400b57cec5SDimitry Andric     }
61410b57cec5SDimitry Andric 
61420b57cec5SDimitry Andric     // Read a record. The record format depends on whether this
61430b57cec5SDimitry Andric     // is a per-module index or a combined index file. In the per-module
61440b57cec5SDimitry Andric     // case the records contain the associated value's ID for correlation
61450b57cec5SDimitry Andric     // with VST entries. In the combined index the correlation is done
61460b57cec5SDimitry Andric     // via the bitcode offset of the summary records (which were saved
61470b57cec5SDimitry Andric     // in the combined index VST entries). The records also contain
61480b57cec5SDimitry Andric     // information used for ThinLTO renaming and importing.
61490b57cec5SDimitry Andric     Record.clear();
61500b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
61510b57cec5SDimitry Andric     if (!MaybeBitCode)
61520b57cec5SDimitry Andric       return MaybeBitCode.takeError();
61530b57cec5SDimitry Andric     switch (unsigned BitCode = MaybeBitCode.get()) {
61540b57cec5SDimitry Andric     default: // Default behavior: ignore.
61550b57cec5SDimitry Andric       break;
61560b57cec5SDimitry Andric     case bitc::FS_FLAGS: {  // [flags]
61575ffd83dbSDimitry Andric       TheIndex.setFlags(Record[0]);
61580b57cec5SDimitry Andric       break;
61590b57cec5SDimitry Andric     }
61600b57cec5SDimitry Andric     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
61610b57cec5SDimitry Andric       uint64_t ValueID = Record[0];
61620b57cec5SDimitry Andric       GlobalValue::GUID RefGUID = Record[1];
61630b57cec5SDimitry Andric       ValueIdToValueInfoMap[ValueID] =
61640b57cec5SDimitry Andric           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
61650b57cec5SDimitry Andric       break;
61660b57cec5SDimitry Andric     }
61670b57cec5SDimitry Andric     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
61680b57cec5SDimitry Andric     //                numrefs x valueid, n x (valueid)]
61690b57cec5SDimitry Andric     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
61700b57cec5SDimitry Andric     //                        numrefs x valueid,
61710b57cec5SDimitry Andric     //                        n x (valueid, hotness)]
61720b57cec5SDimitry Andric     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
61730b57cec5SDimitry Andric     //                      numrefs x valueid,
61740b57cec5SDimitry Andric     //                      n x (valueid, relblockfreq)]
61750b57cec5SDimitry Andric     case bitc::FS_PERMODULE:
61760b57cec5SDimitry Andric     case bitc::FS_PERMODULE_RELBF:
61770b57cec5SDimitry Andric     case bitc::FS_PERMODULE_PROFILE: {
61780b57cec5SDimitry Andric       unsigned ValueID = Record[0];
61790b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
61800b57cec5SDimitry Andric       unsigned InstCount = Record[2];
61810b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
61820b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
61830b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
61840b57cec5SDimitry Andric       int RefListStartIndex = 4;
61850b57cec5SDimitry Andric       if (Version >= 4) {
61860b57cec5SDimitry Andric         RawFunFlags = Record[3];
61870b57cec5SDimitry Andric         NumRefs = Record[4];
61880b57cec5SDimitry Andric         RefListStartIndex = 5;
61890b57cec5SDimitry Andric         if (Version >= 5) {
61900b57cec5SDimitry Andric           NumRORefs = Record[5];
61910b57cec5SDimitry Andric           RefListStartIndex = 6;
61920b57cec5SDimitry Andric           if (Version >= 7) {
61930b57cec5SDimitry Andric             NumWORefs = Record[6];
61940b57cec5SDimitry Andric             RefListStartIndex = 7;
61950b57cec5SDimitry Andric           }
61960b57cec5SDimitry Andric         }
61970b57cec5SDimitry Andric       }
61980b57cec5SDimitry Andric 
61990b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
62000b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
62010b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
62020b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
62030b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
62040b57cec5SDimitry Andric       // ownership.
62050b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
62060b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
62070b57cec5SDimitry Andric              "Record size inconsistent with number of references");
62080b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
62090b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
62100b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
62110b57cec5SDimitry Andric       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
62120b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
62130b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
62140b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, HasRelBF);
62150b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
62168bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
62170b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
62180b57cec5SDimitry Andric           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
62190b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
62200b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
62210b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
62225ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
62235ffd83dbSDimitry Andric           std::move(PendingParamAccesses));
62240b57cec5SDimitry Andric       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
62250b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
62260b57cec5SDimitry Andric       FS->setOriginalName(VIAndOriginalGUID.second);
62270b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
62280b57cec5SDimitry Andric       break;
62290b57cec5SDimitry Andric     }
62300b57cec5SDimitry Andric     // FS_ALIAS: [valueid, flags, valueid]
62310b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
62320b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
62330b57cec5SDimitry Andric     case bitc::FS_ALIAS: {
62340b57cec5SDimitry Andric       unsigned ValueID = Record[0];
62350b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
62360b57cec5SDimitry Andric       unsigned AliaseeID = Record[2];
62370b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
62388bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
62390b57cec5SDimitry Andric       // The module path string ref set in the summary must be owned by the
62400b57cec5SDimitry Andric       // index's module string table. Since we don't have a module path
62410b57cec5SDimitry Andric       // string table section in the per-module index, we create a single
62420b57cec5SDimitry Andric       // module path string table entry with an empty (0) ID to take
62430b57cec5SDimitry Andric       // ownership.
62440b57cec5SDimitry Andric       AS->setModulePath(getThisModule()->first());
62450b57cec5SDimitry Andric 
62460b57cec5SDimitry Andric       auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
62470b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
62480b57cec5SDimitry Andric       if (!AliaseeInModule)
62490b57cec5SDimitry Andric         return error("Alias expects aliasee summary to be parsed");
62500b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
62510b57cec5SDimitry Andric 
62520b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
62530b57cec5SDimitry Andric       AS->setOriginalName(GUID.second);
62540b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
62550b57cec5SDimitry Andric       break;
62560b57cec5SDimitry Andric     }
62570b57cec5SDimitry Andric     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
62580b57cec5SDimitry Andric     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
62590b57cec5SDimitry Andric       unsigned ValueID = Record[0];
62600b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
62610b57cec5SDimitry Andric       unsigned RefArrayStart = 2;
62620b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
62635ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
62645ffd83dbSDimitry Andric                                       /* Constant */ false,
62655ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
62660b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
62670b57cec5SDimitry Andric       if (Version >= 5) {
62680b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[2]);
62690b57cec5SDimitry Andric         RefArrayStart = 3;
62700b57cec5SDimitry Andric       }
62710b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
62720b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
62730b57cec5SDimitry Andric       auto FS =
62748bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
62750b57cec5SDimitry Andric       FS->setModulePath(getThisModule()->first());
62760b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
62770b57cec5SDimitry Andric       FS->setOriginalName(GUID.second);
62780b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
62790b57cec5SDimitry Andric       break;
62800b57cec5SDimitry Andric     }
62810b57cec5SDimitry Andric     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
62820b57cec5SDimitry Andric     //                        numrefs, numrefs x valueid,
62830b57cec5SDimitry Andric     //                        n x (valueid, offset)]
62840b57cec5SDimitry Andric     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
62850b57cec5SDimitry Andric       unsigned ValueID = Record[0];
62860b57cec5SDimitry Andric       uint64_t RawFlags = Record[1];
62870b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
62880b57cec5SDimitry Andric       unsigned NumRefs = Record[3];
62890b57cec5SDimitry Andric       unsigned RefListStartIndex = 4;
62900b57cec5SDimitry Andric       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
62910b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
62920b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
62930b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
62940b57cec5SDimitry Andric       VTableFuncList VTableFuncs;
62950b57cec5SDimitry Andric       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
62960b57cec5SDimitry Andric         ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
62970b57cec5SDimitry Andric         uint64_t Offset = Record[++I];
62980b57cec5SDimitry Andric         VTableFuncs.push_back({Callee, Offset});
62990b57cec5SDimitry Andric       }
63000b57cec5SDimitry Andric       auto VS =
63018bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
63020b57cec5SDimitry Andric       VS->setModulePath(getThisModule()->first());
63030b57cec5SDimitry Andric       VS->setVTableFuncs(VTableFuncs);
63040b57cec5SDimitry Andric       auto GUID = getValueInfoFromValueId(ValueID);
63050b57cec5SDimitry Andric       VS->setOriginalName(GUID.second);
63060b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(GUID.first, std::move(VS));
63070b57cec5SDimitry Andric       break;
63080b57cec5SDimitry Andric     }
63090b57cec5SDimitry Andric     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
63100b57cec5SDimitry Andric     //               numrefs x valueid, n x (valueid)]
63110b57cec5SDimitry Andric     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
63120b57cec5SDimitry Andric     //                       numrefs x valueid, n x (valueid, hotness)]
63130b57cec5SDimitry Andric     case bitc::FS_COMBINED:
63140b57cec5SDimitry Andric     case bitc::FS_COMBINED_PROFILE: {
63150b57cec5SDimitry Andric       unsigned ValueID = Record[0];
63160b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
63170b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
63180b57cec5SDimitry Andric       unsigned InstCount = Record[3];
63190b57cec5SDimitry Andric       uint64_t RawFunFlags = 0;
63200b57cec5SDimitry Andric       uint64_t EntryCount = 0;
63210b57cec5SDimitry Andric       unsigned NumRefs = Record[4];
63220b57cec5SDimitry Andric       unsigned NumRORefs = 0, NumWORefs = 0;
63230b57cec5SDimitry Andric       int RefListStartIndex = 5;
63240b57cec5SDimitry Andric 
63250b57cec5SDimitry Andric       if (Version >= 4) {
63260b57cec5SDimitry Andric         RawFunFlags = Record[4];
63270b57cec5SDimitry Andric         RefListStartIndex = 6;
63280b57cec5SDimitry Andric         size_t NumRefsIndex = 5;
63290b57cec5SDimitry Andric         if (Version >= 5) {
63300b57cec5SDimitry Andric           unsigned NumRORefsOffset = 1;
63310b57cec5SDimitry Andric           RefListStartIndex = 7;
63320b57cec5SDimitry Andric           if (Version >= 6) {
63330b57cec5SDimitry Andric             NumRefsIndex = 6;
63340b57cec5SDimitry Andric             EntryCount = Record[5];
63350b57cec5SDimitry Andric             RefListStartIndex = 8;
63360b57cec5SDimitry Andric             if (Version >= 7) {
63370b57cec5SDimitry Andric               RefListStartIndex = 9;
63380b57cec5SDimitry Andric               NumWORefs = Record[8];
63390b57cec5SDimitry Andric               NumRORefsOffset = 2;
63400b57cec5SDimitry Andric             }
63410b57cec5SDimitry Andric           }
63420b57cec5SDimitry Andric           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
63430b57cec5SDimitry Andric         }
63440b57cec5SDimitry Andric         NumRefs = Record[NumRefsIndex];
63450b57cec5SDimitry Andric       }
63460b57cec5SDimitry Andric 
63470b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
63480b57cec5SDimitry Andric       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
63490b57cec5SDimitry Andric       assert(Record.size() >= RefListStartIndex + NumRefs &&
63500b57cec5SDimitry Andric              "Record size inconsistent with number of references");
63510b57cec5SDimitry Andric       std::vector<ValueInfo> Refs = makeRefList(
63520b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
63530b57cec5SDimitry Andric       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
63540b57cec5SDimitry Andric       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
63550b57cec5SDimitry Andric           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
63560b57cec5SDimitry Andric           IsOldProfileFormat, HasProfile, false);
63570b57cec5SDimitry Andric       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
63580b57cec5SDimitry Andric       setSpecialRefs(Refs, NumRORefs, NumWORefs);
63598bcb0991SDimitry Andric       auto FS = std::make_unique<FunctionSummary>(
63600b57cec5SDimitry Andric           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
63610b57cec5SDimitry Andric           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
63620b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeVCalls),
63630b57cec5SDimitry Andric           std::move(PendingTypeCheckedLoadVCalls),
63640b57cec5SDimitry Andric           std::move(PendingTypeTestAssumeConstVCalls),
63655ffd83dbSDimitry Andric           std::move(PendingTypeCheckedLoadConstVCalls),
63665ffd83dbSDimitry Andric           std::move(PendingParamAccesses));
63670b57cec5SDimitry Andric       LastSeenSummary = FS.get();
63680b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
63690b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
63700b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
63710b57cec5SDimitry Andric       break;
63720b57cec5SDimitry Andric     }
63730b57cec5SDimitry Andric     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
63740b57cec5SDimitry Andric     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
63750b57cec5SDimitry Andric     // they expect all aliasee summaries to be available.
63760b57cec5SDimitry Andric     case bitc::FS_COMBINED_ALIAS: {
63770b57cec5SDimitry Andric       unsigned ValueID = Record[0];
63780b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
63790b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
63800b57cec5SDimitry Andric       unsigned AliaseeValueId = Record[3];
63810b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
63828bcb0991SDimitry Andric       auto AS = std::make_unique<AliasSummary>(Flags);
63830b57cec5SDimitry Andric       LastSeenSummary = AS.get();
63840b57cec5SDimitry Andric       AS->setModulePath(ModuleIdMap[ModuleId]);
63850b57cec5SDimitry Andric 
63860b57cec5SDimitry Andric       auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
63870b57cec5SDimitry Andric       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
63880b57cec5SDimitry Andric       AS->setAliasee(AliaseeVI, AliaseeInModule);
63890b57cec5SDimitry Andric 
63900b57cec5SDimitry Andric       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
63910b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
63920b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(AS));
63930b57cec5SDimitry Andric       break;
63940b57cec5SDimitry Andric     }
63950b57cec5SDimitry Andric     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
63960b57cec5SDimitry Andric     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
63970b57cec5SDimitry Andric       unsigned ValueID = Record[0];
63980b57cec5SDimitry Andric       uint64_t ModuleId = Record[1];
63990b57cec5SDimitry Andric       uint64_t RawFlags = Record[2];
64000b57cec5SDimitry Andric       unsigned RefArrayStart = 3;
64010b57cec5SDimitry Andric       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
64025ffd83dbSDimitry Andric                                       /* WriteOnly */ false,
64035ffd83dbSDimitry Andric                                       /* Constant */ false,
64045ffd83dbSDimitry Andric                                       GlobalObject::VCallVisibilityPublic);
64050b57cec5SDimitry Andric       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
64060b57cec5SDimitry Andric       if (Version >= 5) {
64070b57cec5SDimitry Andric         GVF = getDecodedGVarFlags(Record[3]);
64080b57cec5SDimitry Andric         RefArrayStart = 4;
64090b57cec5SDimitry Andric       }
64100b57cec5SDimitry Andric       std::vector<ValueInfo> Refs =
64110b57cec5SDimitry Andric           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
64120b57cec5SDimitry Andric       auto FS =
64138bcb0991SDimitry Andric           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
64140b57cec5SDimitry Andric       LastSeenSummary = FS.get();
64150b57cec5SDimitry Andric       FS->setModulePath(ModuleIdMap[ModuleId]);
64160b57cec5SDimitry Andric       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
64170b57cec5SDimitry Andric       LastSeenGUID = VI.getGUID();
64180b57cec5SDimitry Andric       TheIndex.addGlobalValueSummary(VI, std::move(FS));
64190b57cec5SDimitry Andric       break;
64200b57cec5SDimitry Andric     }
64210b57cec5SDimitry Andric     // FS_COMBINED_ORIGINAL_NAME: [original_name]
64220b57cec5SDimitry Andric     case bitc::FS_COMBINED_ORIGINAL_NAME: {
64230b57cec5SDimitry Andric       uint64_t OriginalName = Record[0];
64240b57cec5SDimitry Andric       if (!LastSeenSummary)
64250b57cec5SDimitry Andric         return error("Name attachment that does not follow a combined record");
64260b57cec5SDimitry Andric       LastSeenSummary->setOriginalName(OriginalName);
64270b57cec5SDimitry Andric       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
64280b57cec5SDimitry Andric       // Reset the LastSeenSummary
64290b57cec5SDimitry Andric       LastSeenSummary = nullptr;
64300b57cec5SDimitry Andric       LastSeenGUID = 0;
64310b57cec5SDimitry Andric       break;
64320b57cec5SDimitry Andric     }
64330b57cec5SDimitry Andric     case bitc::FS_TYPE_TESTS:
64340b57cec5SDimitry Andric       assert(PendingTypeTests.empty());
6435af732203SDimitry Andric       llvm::append_range(PendingTypeTests, Record);
64360b57cec5SDimitry Andric       break;
64370b57cec5SDimitry Andric 
64380b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
64390b57cec5SDimitry Andric       assert(PendingTypeTestAssumeVCalls.empty());
64400b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
64410b57cec5SDimitry Andric         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
64420b57cec5SDimitry Andric       break;
64430b57cec5SDimitry Andric 
64440b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
64450b57cec5SDimitry Andric       assert(PendingTypeCheckedLoadVCalls.empty());
64460b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
64470b57cec5SDimitry Andric         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
64480b57cec5SDimitry Andric       break;
64490b57cec5SDimitry Andric 
64500b57cec5SDimitry Andric     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
64510b57cec5SDimitry Andric       PendingTypeTestAssumeConstVCalls.push_back(
64520b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
64530b57cec5SDimitry Andric       break;
64540b57cec5SDimitry Andric 
64550b57cec5SDimitry Andric     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
64560b57cec5SDimitry Andric       PendingTypeCheckedLoadConstVCalls.push_back(
64570b57cec5SDimitry Andric           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
64580b57cec5SDimitry Andric       break;
64590b57cec5SDimitry Andric 
64600b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DEFS: {
64610b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
64620b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
64630b57cec5SDimitry Andric         CfiFunctionDefs.insert(
64640b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
64650b57cec5SDimitry Andric       break;
64660b57cec5SDimitry Andric     }
64670b57cec5SDimitry Andric 
64680b57cec5SDimitry Andric     case bitc::FS_CFI_FUNCTION_DECLS: {
64690b57cec5SDimitry Andric       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
64700b57cec5SDimitry Andric       for (unsigned I = 0; I != Record.size(); I += 2)
64710b57cec5SDimitry Andric         CfiFunctionDecls.insert(
64720b57cec5SDimitry Andric             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
64730b57cec5SDimitry Andric       break;
64740b57cec5SDimitry Andric     }
64750b57cec5SDimitry Andric 
64760b57cec5SDimitry Andric     case bitc::FS_TYPE_ID:
64770b57cec5SDimitry Andric       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
64780b57cec5SDimitry Andric       break;
64790b57cec5SDimitry Andric 
64800b57cec5SDimitry Andric     case bitc::FS_TYPE_ID_METADATA:
64810b57cec5SDimitry Andric       parseTypeIdCompatibleVtableSummaryRecord(Record);
64820b57cec5SDimitry Andric       break;
64835ffd83dbSDimitry Andric 
64845ffd83dbSDimitry Andric     case bitc::FS_BLOCK_COUNT:
64855ffd83dbSDimitry Andric       TheIndex.addBlockCount(Record[0]);
64865ffd83dbSDimitry Andric       break;
64875ffd83dbSDimitry Andric 
64885ffd83dbSDimitry Andric     case bitc::FS_PARAM_ACCESS: {
64895ffd83dbSDimitry Andric       PendingParamAccesses = parseParamAccesses(Record);
64905ffd83dbSDimitry Andric       break;
64915ffd83dbSDimitry Andric     }
64920b57cec5SDimitry Andric     }
64930b57cec5SDimitry Andric   }
64940b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
64950b57cec5SDimitry Andric }
64960b57cec5SDimitry Andric 
64970b57cec5SDimitry Andric // Parse the  module string table block into the Index.
64980b57cec5SDimitry Andric // This populates the ModulePathStringTable map in the index.
parseModuleStringTable()64990b57cec5SDimitry Andric Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
65000b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
65010b57cec5SDimitry Andric     return Err;
65020b57cec5SDimitry Andric 
65030b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
65040b57cec5SDimitry Andric 
65050b57cec5SDimitry Andric   SmallString<128> ModulePath;
65060b57cec5SDimitry Andric   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
65070b57cec5SDimitry Andric 
65080b57cec5SDimitry Andric   while (true) {
65090b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
65100b57cec5SDimitry Andric     if (!MaybeEntry)
65110b57cec5SDimitry Andric       return MaybeEntry.takeError();
65120b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
65130b57cec5SDimitry Andric 
65140b57cec5SDimitry Andric     switch (Entry.Kind) {
65150b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
65160b57cec5SDimitry Andric     case BitstreamEntry::Error:
65170b57cec5SDimitry Andric       return error("Malformed block");
65180b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
65190b57cec5SDimitry Andric       return Error::success();
65200b57cec5SDimitry Andric     case BitstreamEntry::Record:
65210b57cec5SDimitry Andric       // The interesting case.
65220b57cec5SDimitry Andric       break;
65230b57cec5SDimitry Andric     }
65240b57cec5SDimitry Andric 
65250b57cec5SDimitry Andric     Record.clear();
65260b57cec5SDimitry Andric     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
65270b57cec5SDimitry Andric     if (!MaybeRecord)
65280b57cec5SDimitry Andric       return MaybeRecord.takeError();
65290b57cec5SDimitry Andric     switch (MaybeRecord.get()) {
65300b57cec5SDimitry Andric     default: // Default behavior: ignore.
65310b57cec5SDimitry Andric       break;
65320b57cec5SDimitry Andric     case bitc::MST_CODE_ENTRY: {
65330b57cec5SDimitry Andric       // MST_ENTRY: [modid, namechar x N]
65340b57cec5SDimitry Andric       uint64_t ModuleId = Record[0];
65350b57cec5SDimitry Andric 
65360b57cec5SDimitry Andric       if (convertToString(Record, 1, ModulePath))
65370b57cec5SDimitry Andric         return error("Invalid record");
65380b57cec5SDimitry Andric 
65390b57cec5SDimitry Andric       LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
65400b57cec5SDimitry Andric       ModuleIdMap[ModuleId] = LastSeenModule->first();
65410b57cec5SDimitry Andric 
65420b57cec5SDimitry Andric       ModulePath.clear();
65430b57cec5SDimitry Andric       break;
65440b57cec5SDimitry Andric     }
65450b57cec5SDimitry Andric     /// MST_CODE_HASH: [5*i32]
65460b57cec5SDimitry Andric     case bitc::MST_CODE_HASH: {
65470b57cec5SDimitry Andric       if (Record.size() != 5)
65480b57cec5SDimitry Andric         return error("Invalid hash length " + Twine(Record.size()).str());
65490b57cec5SDimitry Andric       if (!LastSeenModule)
65500b57cec5SDimitry Andric         return error("Invalid hash that does not follow a module path");
65510b57cec5SDimitry Andric       int Pos = 0;
65520b57cec5SDimitry Andric       for (auto &Val : Record) {
65530b57cec5SDimitry Andric         assert(!(Val >> 32) && "Unexpected high bits set");
65540b57cec5SDimitry Andric         LastSeenModule->second.second[Pos++] = Val;
65550b57cec5SDimitry Andric       }
65560b57cec5SDimitry Andric       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
65570b57cec5SDimitry Andric       LastSeenModule = nullptr;
65580b57cec5SDimitry Andric       break;
65590b57cec5SDimitry Andric     }
65600b57cec5SDimitry Andric     }
65610b57cec5SDimitry Andric   }
65620b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
65630b57cec5SDimitry Andric }
65640b57cec5SDimitry Andric 
65650b57cec5SDimitry Andric namespace {
65660b57cec5SDimitry Andric 
65670b57cec5SDimitry Andric // FIXME: This class is only here to support the transition to llvm::Error. It
65680b57cec5SDimitry Andric // will be removed once this transition is complete. Clients should prefer to
65690b57cec5SDimitry Andric // deal with the Error value directly, rather than converting to error_code.
65700b57cec5SDimitry Andric class BitcodeErrorCategoryType : public std::error_category {
name() const65710b57cec5SDimitry Andric   const char *name() const noexcept override {
65720b57cec5SDimitry Andric     return "llvm.bitcode";
65730b57cec5SDimitry Andric   }
65740b57cec5SDimitry Andric 
message(int IE) const65750b57cec5SDimitry Andric   std::string message(int IE) const override {
65760b57cec5SDimitry Andric     BitcodeError E = static_cast<BitcodeError>(IE);
65770b57cec5SDimitry Andric     switch (E) {
65780b57cec5SDimitry Andric     case BitcodeError::CorruptedBitcode:
65790b57cec5SDimitry Andric       return "Corrupted bitcode";
65800b57cec5SDimitry Andric     }
65810b57cec5SDimitry Andric     llvm_unreachable("Unknown error type!");
65820b57cec5SDimitry Andric   }
65830b57cec5SDimitry Andric };
65840b57cec5SDimitry Andric 
65850b57cec5SDimitry Andric } // end anonymous namespace
65860b57cec5SDimitry Andric 
65870b57cec5SDimitry Andric static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
65880b57cec5SDimitry Andric 
BitcodeErrorCategory()65890b57cec5SDimitry Andric const std::error_category &llvm::BitcodeErrorCategory() {
65900b57cec5SDimitry Andric   return *ErrorCategory;
65910b57cec5SDimitry Andric }
65920b57cec5SDimitry Andric 
readBlobInRecord(BitstreamCursor & Stream,unsigned Block,unsigned RecordID)65930b57cec5SDimitry Andric static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
65940b57cec5SDimitry Andric                                             unsigned Block, unsigned RecordID) {
65950b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(Block))
65960b57cec5SDimitry Andric     return std::move(Err);
65970b57cec5SDimitry Andric 
65980b57cec5SDimitry Andric   StringRef Strtab;
65990b57cec5SDimitry Andric   while (true) {
66000b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
66010b57cec5SDimitry Andric     if (!MaybeEntry)
66020b57cec5SDimitry Andric       return MaybeEntry.takeError();
66030b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
66040b57cec5SDimitry Andric 
66050b57cec5SDimitry Andric     switch (Entry.Kind) {
66060b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
66070b57cec5SDimitry Andric       return Strtab;
66080b57cec5SDimitry Andric 
66090b57cec5SDimitry Andric     case BitstreamEntry::Error:
66100b57cec5SDimitry Andric       return error("Malformed block");
66110b57cec5SDimitry Andric 
66120b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
66130b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
66140b57cec5SDimitry Andric         return std::move(Err);
66150b57cec5SDimitry Andric       break;
66160b57cec5SDimitry Andric 
66170b57cec5SDimitry Andric     case BitstreamEntry::Record:
66180b57cec5SDimitry Andric       StringRef Blob;
66190b57cec5SDimitry Andric       SmallVector<uint64_t, 1> Record;
66200b57cec5SDimitry Andric       Expected<unsigned> MaybeRecord =
66210b57cec5SDimitry Andric           Stream.readRecord(Entry.ID, Record, &Blob);
66220b57cec5SDimitry Andric       if (!MaybeRecord)
66230b57cec5SDimitry Andric         return MaybeRecord.takeError();
66240b57cec5SDimitry Andric       if (MaybeRecord.get() == RecordID)
66250b57cec5SDimitry Andric         Strtab = Blob;
66260b57cec5SDimitry Andric       break;
66270b57cec5SDimitry Andric     }
66280b57cec5SDimitry Andric   }
66290b57cec5SDimitry Andric }
66300b57cec5SDimitry Andric 
66310b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
66320b57cec5SDimitry Andric // External interface
66330b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
66340b57cec5SDimitry Andric 
66350b57cec5SDimitry Andric Expected<std::vector<BitcodeModule>>
getBitcodeModuleList(MemoryBufferRef Buffer)66360b57cec5SDimitry Andric llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
66370b57cec5SDimitry Andric   auto FOrErr = getBitcodeFileContents(Buffer);
66380b57cec5SDimitry Andric   if (!FOrErr)
66390b57cec5SDimitry Andric     return FOrErr.takeError();
66400b57cec5SDimitry Andric   return std::move(FOrErr->Mods);
66410b57cec5SDimitry Andric }
66420b57cec5SDimitry Andric 
66430b57cec5SDimitry Andric Expected<BitcodeFileContents>
getBitcodeFileContents(MemoryBufferRef Buffer)66440b57cec5SDimitry Andric llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
66450b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
66460b57cec5SDimitry Andric   if (!StreamOrErr)
66470b57cec5SDimitry Andric     return StreamOrErr.takeError();
66480b57cec5SDimitry Andric   BitstreamCursor &Stream = *StreamOrErr;
66490b57cec5SDimitry Andric 
66500b57cec5SDimitry Andric   BitcodeFileContents F;
66510b57cec5SDimitry Andric   while (true) {
66520b57cec5SDimitry Andric     uint64_t BCBegin = Stream.getCurrentByteNo();
66530b57cec5SDimitry Andric 
66540b57cec5SDimitry Andric     // We may be consuming bitcode from a client that leaves garbage at the end
66550b57cec5SDimitry Andric     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
66560b57cec5SDimitry Andric     // the end that there cannot possibly be another module, stop looking.
66570b57cec5SDimitry Andric     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
66580b57cec5SDimitry Andric       return F;
66590b57cec5SDimitry Andric 
66600b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
66610b57cec5SDimitry Andric     if (!MaybeEntry)
66620b57cec5SDimitry Andric       return MaybeEntry.takeError();
66630b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
66640b57cec5SDimitry Andric 
66650b57cec5SDimitry Andric     switch (Entry.Kind) {
66660b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
66670b57cec5SDimitry Andric     case BitstreamEntry::Error:
66680b57cec5SDimitry Andric       return error("Malformed block");
66690b57cec5SDimitry Andric 
66700b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: {
66710b57cec5SDimitry Andric       uint64_t IdentificationBit = -1ull;
66720b57cec5SDimitry Andric       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
66730b57cec5SDimitry Andric         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
66740b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
66750b57cec5SDimitry Andric           return std::move(Err);
66760b57cec5SDimitry Andric 
66770b57cec5SDimitry Andric         {
66780b57cec5SDimitry Andric           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
66790b57cec5SDimitry Andric           if (!MaybeEntry)
66800b57cec5SDimitry Andric             return MaybeEntry.takeError();
66810b57cec5SDimitry Andric           Entry = MaybeEntry.get();
66820b57cec5SDimitry Andric         }
66830b57cec5SDimitry Andric 
66840b57cec5SDimitry Andric         if (Entry.Kind != BitstreamEntry::SubBlock ||
66850b57cec5SDimitry Andric             Entry.ID != bitc::MODULE_BLOCK_ID)
66860b57cec5SDimitry Andric           return error("Malformed block");
66870b57cec5SDimitry Andric       }
66880b57cec5SDimitry Andric 
66890b57cec5SDimitry Andric       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
66900b57cec5SDimitry Andric         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
66910b57cec5SDimitry Andric         if (Error Err = Stream.SkipBlock())
66920b57cec5SDimitry Andric           return std::move(Err);
66930b57cec5SDimitry Andric 
66940b57cec5SDimitry Andric         F.Mods.push_back({Stream.getBitcodeBytes().slice(
66950b57cec5SDimitry Andric                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
66960b57cec5SDimitry Andric                           Buffer.getBufferIdentifier(), IdentificationBit,
66970b57cec5SDimitry Andric                           ModuleBit});
66980b57cec5SDimitry Andric         continue;
66990b57cec5SDimitry Andric       }
67000b57cec5SDimitry Andric 
67010b57cec5SDimitry Andric       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
67020b57cec5SDimitry Andric         Expected<StringRef> Strtab =
67030b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
67040b57cec5SDimitry Andric         if (!Strtab)
67050b57cec5SDimitry Andric           return Strtab.takeError();
67060b57cec5SDimitry Andric         // This string table is used by every preceding bitcode module that does
67070b57cec5SDimitry Andric         // not have its own string table. A bitcode file may have multiple
67080b57cec5SDimitry Andric         // string tables if it was created by binary concatenation, for example
67090b57cec5SDimitry Andric         // with "llvm-cat -b".
67100b57cec5SDimitry Andric         for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
67110b57cec5SDimitry Andric           if (!I->Strtab.empty())
67120b57cec5SDimitry Andric             break;
67130b57cec5SDimitry Andric           I->Strtab = *Strtab;
67140b57cec5SDimitry Andric         }
67150b57cec5SDimitry Andric         // Similarly, the string table is used by every preceding symbol table;
67160b57cec5SDimitry Andric         // normally there will be just one unless the bitcode file was created
67170b57cec5SDimitry Andric         // by binary concatenation.
67180b57cec5SDimitry Andric         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
67190b57cec5SDimitry Andric           F.StrtabForSymtab = *Strtab;
67200b57cec5SDimitry Andric         continue;
67210b57cec5SDimitry Andric       }
67220b57cec5SDimitry Andric 
67230b57cec5SDimitry Andric       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
67240b57cec5SDimitry Andric         Expected<StringRef> SymtabOrErr =
67250b57cec5SDimitry Andric             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
67260b57cec5SDimitry Andric         if (!SymtabOrErr)
67270b57cec5SDimitry Andric           return SymtabOrErr.takeError();
67280b57cec5SDimitry Andric 
67290b57cec5SDimitry Andric         // We can expect the bitcode file to have multiple symbol tables if it
67300b57cec5SDimitry Andric         // was created by binary concatenation. In that case we silently
67310b57cec5SDimitry Andric         // ignore any subsequent symbol tables, which is fine because this is a
67320b57cec5SDimitry Andric         // low level function. The client is expected to notice that the number
67330b57cec5SDimitry Andric         // of modules in the symbol table does not match the number of modules
67340b57cec5SDimitry Andric         // in the input file and regenerate the symbol table.
67350b57cec5SDimitry Andric         if (F.Symtab.empty())
67360b57cec5SDimitry Andric           F.Symtab = *SymtabOrErr;
67370b57cec5SDimitry Andric         continue;
67380b57cec5SDimitry Andric       }
67390b57cec5SDimitry Andric 
67400b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
67410b57cec5SDimitry Andric         return std::move(Err);
67420b57cec5SDimitry Andric       continue;
67430b57cec5SDimitry Andric     }
67440b57cec5SDimitry Andric     case BitstreamEntry::Record:
67450b57cec5SDimitry Andric       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
67460b57cec5SDimitry Andric         continue;
67470b57cec5SDimitry Andric       else
67480b57cec5SDimitry Andric         return StreamFailed.takeError();
67490b57cec5SDimitry Andric     }
67500b57cec5SDimitry Andric   }
67510b57cec5SDimitry Andric }
67520b57cec5SDimitry Andric 
67530b57cec5SDimitry Andric /// Get a lazy one-at-time loading module from bitcode.
67540b57cec5SDimitry Andric ///
67550b57cec5SDimitry Andric /// This isn't always used in a lazy context.  In particular, it's also used by
67560b57cec5SDimitry Andric /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
67570b57cec5SDimitry Andric /// in forward-referenced functions from block address references.
67580b57cec5SDimitry Andric ///
67590b57cec5SDimitry Andric /// \param[in] MaterializeAll Set to \c true if we should materialize
67600b57cec5SDimitry Andric /// everything.
67610b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
getModuleImpl(LLVMContext & Context,bool MaterializeAll,bool ShouldLazyLoadMetadata,bool IsImporting,DataLayoutCallbackTy DataLayoutCallback)67620b57cec5SDimitry Andric BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
67635ffd83dbSDimitry Andric                              bool ShouldLazyLoadMetadata, bool IsImporting,
67645ffd83dbSDimitry Andric                              DataLayoutCallbackTy DataLayoutCallback) {
67650b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
67660b57cec5SDimitry Andric 
67670b57cec5SDimitry Andric   std::string ProducerIdentification;
67680b57cec5SDimitry Andric   if (IdentificationBit != -1ull) {
67690b57cec5SDimitry Andric     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
67700b57cec5SDimitry Andric       return std::move(JumpFailed);
67710b57cec5SDimitry Andric     Expected<std::string> ProducerIdentificationOrErr =
67720b57cec5SDimitry Andric         readIdentificationBlock(Stream);
67730b57cec5SDimitry Andric     if (!ProducerIdentificationOrErr)
67740b57cec5SDimitry Andric       return ProducerIdentificationOrErr.takeError();
67750b57cec5SDimitry Andric 
67760b57cec5SDimitry Andric     ProducerIdentification = *ProducerIdentificationOrErr;
67770b57cec5SDimitry Andric   }
67780b57cec5SDimitry Andric 
67790b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
67800b57cec5SDimitry Andric     return std::move(JumpFailed);
67810b57cec5SDimitry Andric   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
67820b57cec5SDimitry Andric                               Context);
67830b57cec5SDimitry Andric 
67840b57cec5SDimitry Andric   std::unique_ptr<Module> M =
67858bcb0991SDimitry Andric       std::make_unique<Module>(ModuleIdentifier, Context);
67860b57cec5SDimitry Andric   M->setMaterializer(R);
67870b57cec5SDimitry Andric 
67880b57cec5SDimitry Andric   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
67895ffd83dbSDimitry Andric   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
67905ffd83dbSDimitry Andric                                       IsImporting, DataLayoutCallback))
67910b57cec5SDimitry Andric     return std::move(Err);
67920b57cec5SDimitry Andric 
67930b57cec5SDimitry Andric   if (MaterializeAll) {
67940b57cec5SDimitry Andric     // Read in the entire module, and destroy the BitcodeReader.
67950b57cec5SDimitry Andric     if (Error Err = M->materializeAll())
67960b57cec5SDimitry Andric       return std::move(Err);
67970b57cec5SDimitry Andric   } else {
67980b57cec5SDimitry Andric     // Resolve forward references from blockaddresses.
67990b57cec5SDimitry Andric     if (Error Err = R->materializeForwardReferencedFunctions())
68000b57cec5SDimitry Andric       return std::move(Err);
68010b57cec5SDimitry Andric   }
68020b57cec5SDimitry Andric   return std::move(M);
68030b57cec5SDimitry Andric }
68040b57cec5SDimitry Andric 
68050b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
getLazyModule(LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting)68060b57cec5SDimitry Andric BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
68070b57cec5SDimitry Andric                              bool IsImporting) {
68085ffd83dbSDimitry Andric   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
68095ffd83dbSDimitry Andric                        [](StringRef) { return None; });
68100b57cec5SDimitry Andric }
68110b57cec5SDimitry Andric 
68120b57cec5SDimitry Andric // Parse the specified bitcode buffer and merge the index into CombinedIndex.
68130b57cec5SDimitry Andric // We don't use ModuleIdentifier here because the client may need to control the
68140b57cec5SDimitry Andric // module path used in the combined summary (e.g. when reading summaries for
68150b57cec5SDimitry Andric // regular LTO modules).
readSummary(ModuleSummaryIndex & CombinedIndex,StringRef ModulePath,uint64_t ModuleId)68160b57cec5SDimitry Andric Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
68170b57cec5SDimitry Andric                                  StringRef ModulePath, uint64_t ModuleId) {
68180b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
68190b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
68200b57cec5SDimitry Andric     return JumpFailed;
68210b57cec5SDimitry Andric 
68220b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
68230b57cec5SDimitry Andric                                     ModulePath, ModuleId);
68240b57cec5SDimitry Andric   return R.parseModule();
68250b57cec5SDimitry Andric }
68260b57cec5SDimitry Andric 
68270b57cec5SDimitry Andric // Parse the specified bitcode buffer, returning the function info index.
getSummary()68280b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
68290b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
68300b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
68310b57cec5SDimitry Andric     return std::move(JumpFailed);
68320b57cec5SDimitry Andric 
68338bcb0991SDimitry Andric   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
68340b57cec5SDimitry Andric   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
68350b57cec5SDimitry Andric                                     ModuleIdentifier, 0);
68360b57cec5SDimitry Andric 
68370b57cec5SDimitry Andric   if (Error Err = R.parseModule())
68380b57cec5SDimitry Andric     return std::move(Err);
68390b57cec5SDimitry Andric 
68400b57cec5SDimitry Andric   return std::move(Index);
68410b57cec5SDimitry Andric }
68420b57cec5SDimitry Andric 
getEnableSplitLTOUnitFlag(BitstreamCursor & Stream,unsigned ID)68430b57cec5SDimitry Andric static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
68440b57cec5SDimitry Andric                                                 unsigned ID) {
68450b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(ID))
68460b57cec5SDimitry Andric     return std::move(Err);
68470b57cec5SDimitry Andric   SmallVector<uint64_t, 64> Record;
68480b57cec5SDimitry Andric 
68490b57cec5SDimitry Andric   while (true) {
68500b57cec5SDimitry Andric     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
68510b57cec5SDimitry Andric     if (!MaybeEntry)
68520b57cec5SDimitry Andric       return MaybeEntry.takeError();
68530b57cec5SDimitry Andric     BitstreamEntry Entry = MaybeEntry.get();
68540b57cec5SDimitry Andric 
68550b57cec5SDimitry Andric     switch (Entry.Kind) {
68560b57cec5SDimitry Andric     case BitstreamEntry::SubBlock: // Handled for us already.
68570b57cec5SDimitry Andric     case BitstreamEntry::Error:
68580b57cec5SDimitry Andric       return error("Malformed block");
68590b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
68600b57cec5SDimitry Andric       // If no flags record found, conservatively return true to mimic
68610b57cec5SDimitry Andric       // behavior before this flag was added.
68620b57cec5SDimitry Andric       return true;
68630b57cec5SDimitry Andric     case BitstreamEntry::Record:
68640b57cec5SDimitry Andric       // The interesting case.
68650b57cec5SDimitry Andric       break;
68660b57cec5SDimitry Andric     }
68670b57cec5SDimitry Andric 
68680b57cec5SDimitry Andric     // Look for the FS_FLAGS record.
68690b57cec5SDimitry Andric     Record.clear();
68700b57cec5SDimitry Andric     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
68710b57cec5SDimitry Andric     if (!MaybeBitCode)
68720b57cec5SDimitry Andric       return MaybeBitCode.takeError();
68730b57cec5SDimitry Andric     switch (MaybeBitCode.get()) {
68740b57cec5SDimitry Andric     default: // Default behavior: ignore.
68750b57cec5SDimitry Andric       break;
68760b57cec5SDimitry Andric     case bitc::FS_FLAGS: { // [flags]
68770b57cec5SDimitry Andric       uint64_t Flags = Record[0];
68780b57cec5SDimitry Andric       // Scan flags.
6879*5f7ddb14SDimitry Andric       assert(Flags <= 0x7f && "Unexpected bits in flag");
68800b57cec5SDimitry Andric 
68810b57cec5SDimitry Andric       return Flags & 0x8;
68820b57cec5SDimitry Andric     }
68830b57cec5SDimitry Andric     }
68840b57cec5SDimitry Andric   }
68850b57cec5SDimitry Andric   llvm_unreachable("Exit infinite loop");
68860b57cec5SDimitry Andric }
68870b57cec5SDimitry Andric 
68880b57cec5SDimitry Andric // Check if the given bitcode buffer contains a global value summary block.
getLTOInfo()68890b57cec5SDimitry Andric Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
68900b57cec5SDimitry Andric   BitstreamCursor Stream(Buffer);
68910b57cec5SDimitry Andric   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
68920b57cec5SDimitry Andric     return std::move(JumpFailed);
68930b57cec5SDimitry Andric 
68940b57cec5SDimitry Andric   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
68950b57cec5SDimitry Andric     return std::move(Err);
68960b57cec5SDimitry Andric 
68970b57cec5SDimitry Andric   while (true) {
68980b57cec5SDimitry Andric     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
68990b57cec5SDimitry Andric     if (!MaybeEntry)
69000b57cec5SDimitry Andric       return MaybeEntry.takeError();
69010b57cec5SDimitry Andric     llvm::BitstreamEntry Entry = MaybeEntry.get();
69020b57cec5SDimitry Andric 
69030b57cec5SDimitry Andric     switch (Entry.Kind) {
69040b57cec5SDimitry Andric     case BitstreamEntry::Error:
69050b57cec5SDimitry Andric       return error("Malformed block");
69060b57cec5SDimitry Andric     case BitstreamEntry::EndBlock:
69070b57cec5SDimitry Andric       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
69080b57cec5SDimitry Andric                             /*EnableSplitLTOUnit=*/false};
69090b57cec5SDimitry Andric 
69100b57cec5SDimitry Andric     case BitstreamEntry::SubBlock:
69110b57cec5SDimitry Andric       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
69120b57cec5SDimitry Andric         Expected<bool> EnableSplitLTOUnit =
69130b57cec5SDimitry Andric             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
69140b57cec5SDimitry Andric         if (!EnableSplitLTOUnit)
69150b57cec5SDimitry Andric           return EnableSplitLTOUnit.takeError();
69160b57cec5SDimitry Andric         return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
69170b57cec5SDimitry Andric                               *EnableSplitLTOUnit};
69180b57cec5SDimitry Andric       }
69190b57cec5SDimitry Andric 
69200b57cec5SDimitry Andric       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
69210b57cec5SDimitry Andric         Expected<bool> EnableSplitLTOUnit =
69220b57cec5SDimitry Andric             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
69230b57cec5SDimitry Andric         if (!EnableSplitLTOUnit)
69240b57cec5SDimitry Andric           return EnableSplitLTOUnit.takeError();
69250b57cec5SDimitry Andric         return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
69260b57cec5SDimitry Andric                               *EnableSplitLTOUnit};
69270b57cec5SDimitry Andric       }
69280b57cec5SDimitry Andric 
69290b57cec5SDimitry Andric       // Ignore other sub-blocks.
69300b57cec5SDimitry Andric       if (Error Err = Stream.SkipBlock())
69310b57cec5SDimitry Andric         return std::move(Err);
69320b57cec5SDimitry Andric       continue;
69330b57cec5SDimitry Andric 
69340b57cec5SDimitry Andric     case BitstreamEntry::Record:
69350b57cec5SDimitry Andric       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
69360b57cec5SDimitry Andric         continue;
69370b57cec5SDimitry Andric       else
69380b57cec5SDimitry Andric         return StreamFailed.takeError();
69390b57cec5SDimitry Andric     }
69400b57cec5SDimitry Andric   }
69410b57cec5SDimitry Andric }
69420b57cec5SDimitry Andric 
getSingleModule(MemoryBufferRef Buffer)69430b57cec5SDimitry Andric static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
69440b57cec5SDimitry Andric   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
69450b57cec5SDimitry Andric   if (!MsOrErr)
69460b57cec5SDimitry Andric     return MsOrErr.takeError();
69470b57cec5SDimitry Andric 
69480b57cec5SDimitry Andric   if (MsOrErr->size() != 1)
69490b57cec5SDimitry Andric     return error("Expected a single module");
69500b57cec5SDimitry Andric 
69510b57cec5SDimitry Andric   return (*MsOrErr)[0];
69520b57cec5SDimitry Andric }
69530b57cec5SDimitry Andric 
69540b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
getLazyBitcodeModule(MemoryBufferRef Buffer,LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting)69550b57cec5SDimitry Andric llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
69560b57cec5SDimitry Andric                            bool ShouldLazyLoadMetadata, bool IsImporting) {
69570b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
69580b57cec5SDimitry Andric   if (!BM)
69590b57cec5SDimitry Andric     return BM.takeError();
69600b57cec5SDimitry Andric 
69610b57cec5SDimitry Andric   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
69620b57cec5SDimitry Andric }
69630b57cec5SDimitry Andric 
getOwningLazyBitcodeModule(std::unique_ptr<MemoryBuffer> && Buffer,LLVMContext & Context,bool ShouldLazyLoadMetadata,bool IsImporting)69640b57cec5SDimitry Andric Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
69650b57cec5SDimitry Andric     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
69660b57cec5SDimitry Andric     bool ShouldLazyLoadMetadata, bool IsImporting) {
69670b57cec5SDimitry Andric   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
69680b57cec5SDimitry Andric                                      IsImporting);
69690b57cec5SDimitry Andric   if (MOrErr)
69700b57cec5SDimitry Andric     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
69710b57cec5SDimitry Andric   return MOrErr;
69720b57cec5SDimitry Andric }
69730b57cec5SDimitry Andric 
69740b57cec5SDimitry Andric Expected<std::unique_ptr<Module>>
parseModule(LLVMContext & Context,DataLayoutCallbackTy DataLayoutCallback)69755ffd83dbSDimitry Andric BitcodeModule::parseModule(LLVMContext &Context,
69765ffd83dbSDimitry Andric                            DataLayoutCallbackTy DataLayoutCallback) {
69775ffd83dbSDimitry Andric   return getModuleImpl(Context, true, false, false, DataLayoutCallback);
69780b57cec5SDimitry Andric   // TODO: Restore the use-lists to the in-memory state when the bitcode was
69790b57cec5SDimitry Andric   // written.  We must defer until the Module has been fully materialized.
69800b57cec5SDimitry Andric }
69810b57cec5SDimitry Andric 
69825ffd83dbSDimitry Andric Expected<std::unique_ptr<Module>>
parseBitcodeFile(MemoryBufferRef Buffer,LLVMContext & Context,DataLayoutCallbackTy DataLayoutCallback)69835ffd83dbSDimitry Andric llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
69845ffd83dbSDimitry Andric                        DataLayoutCallbackTy DataLayoutCallback) {
69850b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
69860b57cec5SDimitry Andric   if (!BM)
69870b57cec5SDimitry Andric     return BM.takeError();
69880b57cec5SDimitry Andric 
69895ffd83dbSDimitry Andric   return BM->parseModule(Context, DataLayoutCallback);
69900b57cec5SDimitry Andric }
69910b57cec5SDimitry Andric 
getBitcodeTargetTriple(MemoryBufferRef Buffer)69920b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
69930b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
69940b57cec5SDimitry Andric   if (!StreamOrErr)
69950b57cec5SDimitry Andric     return StreamOrErr.takeError();
69960b57cec5SDimitry Andric 
69970b57cec5SDimitry Andric   return readTriple(*StreamOrErr);
69980b57cec5SDimitry Andric }
69990b57cec5SDimitry Andric 
isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)70000b57cec5SDimitry Andric Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
70010b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
70020b57cec5SDimitry Andric   if (!StreamOrErr)
70030b57cec5SDimitry Andric     return StreamOrErr.takeError();
70040b57cec5SDimitry Andric 
70050b57cec5SDimitry Andric   return hasObjCCategory(*StreamOrErr);
70060b57cec5SDimitry Andric }
70070b57cec5SDimitry Andric 
getBitcodeProducerString(MemoryBufferRef Buffer)70080b57cec5SDimitry Andric Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
70090b57cec5SDimitry Andric   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
70100b57cec5SDimitry Andric   if (!StreamOrErr)
70110b57cec5SDimitry Andric     return StreamOrErr.takeError();
70120b57cec5SDimitry Andric 
70130b57cec5SDimitry Andric   return readIdentificationCode(*StreamOrErr);
70140b57cec5SDimitry Andric }
70150b57cec5SDimitry Andric 
readModuleSummaryIndex(MemoryBufferRef Buffer,ModuleSummaryIndex & CombinedIndex,uint64_t ModuleId)70160b57cec5SDimitry Andric Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
70170b57cec5SDimitry Andric                                    ModuleSummaryIndex &CombinedIndex,
70180b57cec5SDimitry Andric                                    uint64_t ModuleId) {
70190b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
70200b57cec5SDimitry Andric   if (!BM)
70210b57cec5SDimitry Andric     return BM.takeError();
70220b57cec5SDimitry Andric 
70230b57cec5SDimitry Andric   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
70240b57cec5SDimitry Andric }
70250b57cec5SDimitry Andric 
70260b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
getModuleSummaryIndex(MemoryBufferRef Buffer)70270b57cec5SDimitry Andric llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
70280b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
70290b57cec5SDimitry Andric   if (!BM)
70300b57cec5SDimitry Andric     return BM.takeError();
70310b57cec5SDimitry Andric 
70320b57cec5SDimitry Andric   return BM->getSummary();
70330b57cec5SDimitry Andric }
70340b57cec5SDimitry Andric 
getBitcodeLTOInfo(MemoryBufferRef Buffer)70350b57cec5SDimitry Andric Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
70360b57cec5SDimitry Andric   Expected<BitcodeModule> BM = getSingleModule(Buffer);
70370b57cec5SDimitry Andric   if (!BM)
70380b57cec5SDimitry Andric     return BM.takeError();
70390b57cec5SDimitry Andric 
70400b57cec5SDimitry Andric   return BM->getLTOInfo();
70410b57cec5SDimitry Andric }
70420b57cec5SDimitry Andric 
70430b57cec5SDimitry Andric Expected<std::unique_ptr<ModuleSummaryIndex>>
getModuleSummaryIndexForFile(StringRef Path,bool IgnoreEmptyThinLTOIndexFile)70440b57cec5SDimitry Andric llvm::getModuleSummaryIndexForFile(StringRef Path,
70450b57cec5SDimitry Andric                                    bool IgnoreEmptyThinLTOIndexFile) {
70460b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
70470b57cec5SDimitry Andric       MemoryBuffer::getFileOrSTDIN(Path);
70480b57cec5SDimitry Andric   if (!FileOrErr)
70490b57cec5SDimitry Andric     return errorCodeToError(FileOrErr.getError());
70500b57cec5SDimitry Andric   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
70510b57cec5SDimitry Andric     return nullptr;
70520b57cec5SDimitry Andric   return getModuleSummaryIndex(**FileOrErr);
70530b57cec5SDimitry Andric }
7054