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