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_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
1811       if (Record.size() != 1)
1812         return error("Invalid record");
1813       unsigned AddressSpace = Record[0];
1814       ResultTy = PointerType::get(Context, AddressSpace);
1815       break;
1816     }
1817     case bitc::TYPE_CODE_FUNCTION_OLD: {
1818       // Deprecated, but still needed to read old bitcode files.
1819       // FUNCTION: [vararg, attrid, retty, paramty x N]
1820       if (Record.size() < 3)
1821         return error("Invalid record");
1822       SmallVector<Type*, 8> ArgTys;
1823       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1824         if (Type *T = getTypeByID(Record[i]))
1825           ArgTys.push_back(T);
1826         else
1827           break;
1828       }
1829 
1830       ResultTy = getTypeByID(Record[2]);
1831       if (!ResultTy || ArgTys.size() < Record.size()-3)
1832         return error("Invalid type");
1833 
1834       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1835       break;
1836     }
1837     case bitc::TYPE_CODE_FUNCTION: {
1838       // FUNCTION: [vararg, retty, paramty x N]
1839       if (Record.size() < 2)
1840         return error("Invalid record");
1841       SmallVector<Type*, 8> ArgTys;
1842       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1843         if (Type *T = getTypeByID(Record[i])) {
1844           if (!FunctionType::isValidArgumentType(T))
1845             return error("Invalid function argument type");
1846           ArgTys.push_back(T);
1847         }
1848         else
1849           break;
1850       }
1851 
1852       ResultTy = getTypeByID(Record[1]);
1853       if (!ResultTy || ArgTys.size() < Record.size()-2)
1854         return error("Invalid type");
1855 
1856       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1857       break;
1858     }
1859     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1860       if (Record.empty())
1861         return error("Invalid record");
1862       SmallVector<Type*, 8> EltTys;
1863       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1864         if (Type *T = getTypeByID(Record[i]))
1865           EltTys.push_back(T);
1866         else
1867           break;
1868       }
1869       if (EltTys.size() != Record.size()-1)
1870         return error("Invalid type");
1871       ResultTy = StructType::get(Context, EltTys, Record[0]);
1872       break;
1873     }
1874     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
1875       if (convertToString(Record, 0, TypeName))
1876         return error("Invalid record");
1877       continue;
1878 
1879     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1880       if (Record.empty())
1881         return error("Invalid record");
1882 
1883       if (NumRecords >= TypeList.size())
1884         return error("Invalid TYPE table");
1885 
1886       // Check to see if this was forward referenced, if so fill in the temp.
1887       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1888       if (Res) {
1889         Res->setName(TypeName);
1890         TypeList[NumRecords] = nullptr;
1891       } else  // Otherwise, create a new struct.
1892         Res = createIdentifiedStructType(Context, TypeName);
1893       TypeName.clear();
1894 
1895       SmallVector<Type*, 8> EltTys;
1896       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1897         if (Type *T = getTypeByID(Record[i]))
1898           EltTys.push_back(T);
1899         else
1900           break;
1901       }
1902       if (EltTys.size() != Record.size()-1)
1903         return error("Invalid record");
1904       Res->setBody(EltTys, Record[0]);
1905       ResultTy = Res;
1906       break;
1907     }
1908     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
1909       if (Record.size() != 1)
1910         return error("Invalid record");
1911 
1912       if (NumRecords >= TypeList.size())
1913         return error("Invalid TYPE table");
1914 
1915       // Check to see if this was forward referenced, if so fill in the temp.
1916       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1917       if (Res) {
1918         Res->setName(TypeName);
1919         TypeList[NumRecords] = nullptr;
1920       } else  // Otherwise, create a new struct with no body.
1921         Res = createIdentifiedStructType(Context, TypeName);
1922       TypeName.clear();
1923       ResultTy = Res;
1924       break;
1925     }
1926     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1927       if (Record.size() < 2)
1928         return error("Invalid record");
1929       ResultTy = getTypeByID(Record[1]);
1930       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1931         return error("Invalid type");
1932       ResultTy = ArrayType::get(ResultTy, Record[0]);
1933       break;
1934     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty] or
1935                                     //         [numelts, eltty, scalable]
1936       if (Record.size() < 2)
1937         return error("Invalid record");
1938       if (Record[0] == 0)
1939         return error("Invalid vector length");
1940       ResultTy = getTypeByID(Record[1]);
1941       if (!ResultTy || !StructType::isValidElementType(ResultTy))
1942         return error("Invalid type");
1943       bool Scalable = Record.size() > 2 ? Record[2] : false;
1944       ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
1945       break;
1946     }
1947 
1948     if (NumRecords >= TypeList.size())
1949       return error("Invalid TYPE table");
1950     if (TypeList[NumRecords])
1951       return error(
1952           "Invalid TYPE table: Only named structs can be forward referenced");
1953     assert(ResultTy && "Didn't read a type?");
1954     TypeList[NumRecords++] = ResultTy;
1955   }
1956 }
1957 
1958 Error BitcodeReader::parseOperandBundleTags() {
1959   if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1960     return Err;
1961 
1962   if (!BundleTags.empty())
1963     return error("Invalid multiple blocks");
1964 
1965   SmallVector<uint64_t, 64> Record;
1966 
1967   while (true) {
1968     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1969     if (!MaybeEntry)
1970       return MaybeEntry.takeError();
1971     BitstreamEntry Entry = MaybeEntry.get();
1972 
1973     switch (Entry.Kind) {
1974     case BitstreamEntry::SubBlock: // Handled for us already.
1975     case BitstreamEntry::Error:
1976       return error("Malformed block");
1977     case BitstreamEntry::EndBlock:
1978       return Error::success();
1979     case BitstreamEntry::Record:
1980       // The interesting case.
1981       break;
1982     }
1983 
1984     // Tags are implicitly mapped to integers by their order.
1985 
1986     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1987     if (!MaybeRecord)
1988       return MaybeRecord.takeError();
1989     if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
1990       return error("Invalid record");
1991 
1992     // OPERAND_BUNDLE_TAG: [strchr x N]
1993     BundleTags.emplace_back();
1994     if (convertToString(Record, 0, BundleTags.back()))
1995       return error("Invalid record");
1996     Record.clear();
1997   }
1998 }
1999 
2000 Error BitcodeReader::parseSyncScopeNames() {
2001   if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2002     return Err;
2003 
2004   if (!SSIDs.empty())
2005     return error("Invalid multiple synchronization scope names blocks");
2006 
2007   SmallVector<uint64_t, 64> Record;
2008   while (true) {
2009     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2010     if (!MaybeEntry)
2011       return MaybeEntry.takeError();
2012     BitstreamEntry Entry = MaybeEntry.get();
2013 
2014     switch (Entry.Kind) {
2015     case BitstreamEntry::SubBlock: // Handled for us already.
2016     case BitstreamEntry::Error:
2017       return error("Malformed block");
2018     case BitstreamEntry::EndBlock:
2019       if (SSIDs.empty())
2020         return error("Invalid empty synchronization scope names block");
2021       return Error::success();
2022     case BitstreamEntry::Record:
2023       // The interesting case.
2024       break;
2025     }
2026 
2027     // Synchronization scope names are implicitly mapped to synchronization
2028     // scope IDs by their order.
2029 
2030     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2031     if (!MaybeRecord)
2032       return MaybeRecord.takeError();
2033     if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2034       return error("Invalid record");
2035 
2036     SmallString<16> SSN;
2037     if (convertToString(Record, 0, SSN))
2038       return error("Invalid record");
2039 
2040     SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2041     Record.clear();
2042   }
2043 }
2044 
2045 /// Associate a value with its name from the given index in the provided record.
2046 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2047                                              unsigned NameIndex, Triple &TT) {
2048   SmallString<128> ValueName;
2049   if (convertToString(Record, NameIndex, ValueName))
2050     return error("Invalid record");
2051   unsigned ValueID = Record[0];
2052   if (ValueID >= ValueList.size() || !ValueList[ValueID])
2053     return error("Invalid record");
2054   Value *V = ValueList[ValueID];
2055 
2056   StringRef NameStr(ValueName.data(), ValueName.size());
2057   if (NameStr.find_first_of(0) != StringRef::npos)
2058     return error("Invalid value name");
2059   V->setName(NameStr);
2060   auto *GO = dyn_cast<GlobalObject>(V);
2061   if (GO) {
2062     if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
2063       if (TT.supportsCOMDAT())
2064         GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2065       else
2066         GO->setComdat(nullptr);
2067     }
2068   }
2069   return V;
2070 }
2071 
2072 /// Helper to note and return the current location, and jump to the given
2073 /// offset.
2074 static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
2075                                                  BitstreamCursor &Stream) {
2076   // Save the current parsing location so we can jump back at the end
2077   // of the VST read.
2078   uint64_t CurrentBit = Stream.GetCurrentBitNo();
2079   if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2080     return std::move(JumpFailed);
2081   Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2082   if (!MaybeEntry)
2083     return MaybeEntry.takeError();
2084   assert(MaybeEntry.get().Kind == BitstreamEntry::SubBlock);
2085   assert(MaybeEntry.get().ID == bitc::VALUE_SYMTAB_BLOCK_ID);
2086   return CurrentBit;
2087 }
2088 
2089 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2090                                             Function *F,
2091                                             ArrayRef<uint64_t> Record) {
2092   // Note that we subtract 1 here because the offset is relative to one word
2093   // before the start of the identification or module block, which was
2094   // historically always the start of the regular bitcode header.
2095   uint64_t FuncWordOffset = Record[1] - 1;
2096   uint64_t FuncBitOffset = FuncWordOffset * 32;
2097   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2098   // Set the LastFunctionBlockBit to point to the last function block.
2099   // Later when parsing is resumed after function materialization,
2100   // we can simply skip that last function block.
2101   if (FuncBitOffset > LastFunctionBlockBit)
2102     LastFunctionBlockBit = FuncBitOffset;
2103 }
2104 
2105 /// Read a new-style GlobalValue symbol table.
2106 Error BitcodeReader::parseGlobalValueSymbolTable() {
2107   unsigned FuncBitcodeOffsetDelta =
2108       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2109 
2110   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2111     return Err;
2112 
2113   SmallVector<uint64_t, 64> Record;
2114   while (true) {
2115     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2116     if (!MaybeEntry)
2117       return MaybeEntry.takeError();
2118     BitstreamEntry Entry = MaybeEntry.get();
2119 
2120     switch (Entry.Kind) {
2121     case BitstreamEntry::SubBlock:
2122     case BitstreamEntry::Error:
2123       return error("Malformed block");
2124     case BitstreamEntry::EndBlock:
2125       return Error::success();
2126     case BitstreamEntry::Record:
2127       break;
2128     }
2129 
2130     Record.clear();
2131     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2132     if (!MaybeRecord)
2133       return MaybeRecord.takeError();
2134     switch (MaybeRecord.get()) {
2135     case bitc::VST_CODE_FNENTRY: // [valueid, offset]
2136       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2137                               cast<Function>(ValueList[Record[0]]), Record);
2138       break;
2139     }
2140   }
2141 }
2142 
2143 /// Parse the value symbol table at either the current parsing location or
2144 /// at the given bit offset if provided.
2145 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
2146   uint64_t CurrentBit;
2147   // Pass in the Offset to distinguish between calling for the module-level
2148   // VST (where we want to jump to the VST offset) and the function-level
2149   // VST (where we don't).
2150   if (Offset > 0) {
2151     Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2152     if (!MaybeCurrentBit)
2153       return MaybeCurrentBit.takeError();
2154     CurrentBit = MaybeCurrentBit.get();
2155     // If this module uses a string table, read this as a module-level VST.
2156     if (UseStrtab) {
2157       if (Error Err = parseGlobalValueSymbolTable())
2158         return Err;
2159       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2160         return JumpFailed;
2161       return Error::success();
2162     }
2163     // Otherwise, the VST will be in a similar format to a function-level VST,
2164     // and will contain symbol names.
2165   }
2166 
2167   // Compute the delta between the bitcode indices in the VST (the word offset
2168   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2169   // expected by the lazy reader. The reader's EnterSubBlock expects to have
2170   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2171   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2172   // just before entering the VST subblock because: 1) the EnterSubBlock
2173   // changes the AbbrevID width; 2) the VST block is nested within the same
2174   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2175   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2176   // jump to the FUNCTION_BLOCK using this offset later, we don't want
2177   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2178   unsigned FuncBitcodeOffsetDelta =
2179       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2180 
2181   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2182     return Err;
2183 
2184   SmallVector<uint64_t, 64> Record;
2185 
2186   Triple TT(TheModule->getTargetTriple());
2187 
2188   // Read all the records for this value table.
2189   SmallString<128> ValueName;
2190 
2191   while (true) {
2192     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2193     if (!MaybeEntry)
2194       return MaybeEntry.takeError();
2195     BitstreamEntry Entry = MaybeEntry.get();
2196 
2197     switch (Entry.Kind) {
2198     case BitstreamEntry::SubBlock: // Handled for us already.
2199     case BitstreamEntry::Error:
2200       return error("Malformed block");
2201     case BitstreamEntry::EndBlock:
2202       if (Offset > 0)
2203         if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2204           return JumpFailed;
2205       return Error::success();
2206     case BitstreamEntry::Record:
2207       // The interesting case.
2208       break;
2209     }
2210 
2211     // Read a record.
2212     Record.clear();
2213     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2214     if (!MaybeRecord)
2215       return MaybeRecord.takeError();
2216     switch (MaybeRecord.get()) {
2217     default:  // Default behavior: unknown type.
2218       break;
2219     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
2220       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2221       if (Error Err = ValOrErr.takeError())
2222         return Err;
2223       ValOrErr.get();
2224       break;
2225     }
2226     case bitc::VST_CODE_FNENTRY: {
2227       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2228       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2229       if (Error Err = ValOrErr.takeError())
2230         return Err;
2231       Value *V = ValOrErr.get();
2232 
2233       // Ignore function offsets emitted for aliases of functions in older
2234       // versions of LLVM.
2235       if (auto *F = dyn_cast<Function>(V))
2236         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2237       break;
2238     }
2239     case bitc::VST_CODE_BBENTRY: {
2240       if (convertToString(Record, 1, ValueName))
2241         return error("Invalid record");
2242       BasicBlock *BB = getBasicBlock(Record[0]);
2243       if (!BB)
2244         return error("Invalid record");
2245 
2246       BB->setName(StringRef(ValueName.data(), ValueName.size()));
2247       ValueName.clear();
2248       break;
2249     }
2250     }
2251   }
2252 }
2253 
2254 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2255 /// encoding.
2256 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2257   if ((V & 1) == 0)
2258     return V >> 1;
2259   if (V != 1)
2260     return -(V >> 1);
2261   // There is no such thing as -0 with integers.  "-0" really means MININT.
2262   return 1ULL << 63;
2263 }
2264 
2265 /// Resolve all of the initializers for global values and aliases that we can.
2266 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2267   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2268   std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>
2269       IndirectSymbolInitWorklist;
2270   std::vector<std::pair<Function *, unsigned>> FunctionPrefixWorklist;
2271   std::vector<std::pair<Function *, unsigned>> FunctionPrologueWorklist;
2272   std::vector<std::pair<Function *, unsigned>> FunctionPersonalityFnWorklist;
2273 
2274   GlobalInitWorklist.swap(GlobalInits);
2275   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2276   FunctionPrefixWorklist.swap(FunctionPrefixes);
2277   FunctionPrologueWorklist.swap(FunctionPrologues);
2278   FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
2279 
2280   while (!GlobalInitWorklist.empty()) {
2281     unsigned ValID = GlobalInitWorklist.back().second;
2282     if (ValID >= ValueList.size()) {
2283       // Not ready to resolve this yet, it requires something later in the file.
2284       GlobalInits.push_back(GlobalInitWorklist.back());
2285     } else {
2286       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2287         GlobalInitWorklist.back().first->setInitializer(C);
2288       else
2289         return error("Expected a constant");
2290     }
2291     GlobalInitWorklist.pop_back();
2292   }
2293 
2294   while (!IndirectSymbolInitWorklist.empty()) {
2295     unsigned ValID = IndirectSymbolInitWorklist.back().second;
2296     if (ValID >= ValueList.size()) {
2297       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2298     } else {
2299       Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2300       if (!C)
2301         return error("Expected a constant");
2302       GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2303       if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
2304         return error("Alias and aliasee types don't match");
2305       GIS->setIndirectSymbol(C);
2306     }
2307     IndirectSymbolInitWorklist.pop_back();
2308   }
2309 
2310   while (!FunctionPrefixWorklist.empty()) {
2311     unsigned ValID = FunctionPrefixWorklist.back().second;
2312     if (ValID >= ValueList.size()) {
2313       FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2314     } else {
2315       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2316         FunctionPrefixWorklist.back().first->setPrefixData(C);
2317       else
2318         return error("Expected a constant");
2319     }
2320     FunctionPrefixWorklist.pop_back();
2321   }
2322 
2323   while (!FunctionPrologueWorklist.empty()) {
2324     unsigned ValID = FunctionPrologueWorklist.back().second;
2325     if (ValID >= ValueList.size()) {
2326       FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2327     } else {
2328       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2329         FunctionPrologueWorklist.back().first->setPrologueData(C);
2330       else
2331         return error("Expected a constant");
2332     }
2333     FunctionPrologueWorklist.pop_back();
2334   }
2335 
2336   while (!FunctionPersonalityFnWorklist.empty()) {
2337     unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2338     if (ValID >= ValueList.size()) {
2339       FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2340     } else {
2341       if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2342         FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2343       else
2344         return error("Expected a constant");
2345     }
2346     FunctionPersonalityFnWorklist.pop_back();
2347   }
2348 
2349   return Error::success();
2350 }
2351 
2352 APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2353   SmallVector<uint64_t, 8> Words(Vals.size());
2354   transform(Vals, Words.begin(),
2355                  BitcodeReader::decodeSignRotatedValue);
2356 
2357   return APInt(TypeBits, Words);
2358 }
2359 
2360 Error BitcodeReader::parseConstants() {
2361   if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2362     return Err;
2363 
2364   SmallVector<uint64_t, 64> Record;
2365 
2366   // Read all the records for this value table.
2367   Type *CurTy = Type::getInt32Ty(Context);
2368   Type *CurFullTy = Type::getInt32Ty(Context);
2369   unsigned NextCstNo = ValueList.size();
2370 
2371   struct DelayedShufTy {
2372     VectorType *OpTy;
2373     VectorType *RTy;
2374     Type *CurFullTy;
2375     uint64_t Op0Idx;
2376     uint64_t Op1Idx;
2377     uint64_t Op2Idx;
2378     unsigned CstNo;
2379   };
2380   std::vector<DelayedShufTy> DelayedShuffles;
2381   while (true) {
2382     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2383     if (!MaybeEntry)
2384       return MaybeEntry.takeError();
2385     BitstreamEntry Entry = MaybeEntry.get();
2386 
2387     switch (Entry.Kind) {
2388     case BitstreamEntry::SubBlock: // Handled for us already.
2389     case BitstreamEntry::Error:
2390       return error("Malformed block");
2391     case BitstreamEntry::EndBlock:
2392       // Once all the constants have been read, go through and resolve forward
2393       // references.
2394       //
2395       // We have to treat shuffles specially because they don't have three
2396       // operands anymore.  We need to convert the shuffle mask into an array,
2397       // and we can't convert a forward reference.
2398       for (auto &DelayedShuffle : DelayedShuffles) {
2399         VectorType *OpTy = DelayedShuffle.OpTy;
2400         VectorType *RTy = DelayedShuffle.RTy;
2401         uint64_t Op0Idx = DelayedShuffle.Op0Idx;
2402         uint64_t Op1Idx = DelayedShuffle.Op1Idx;
2403         uint64_t Op2Idx = DelayedShuffle.Op2Idx;
2404         uint64_t CstNo = DelayedShuffle.CstNo;
2405         Constant *Op0 = ValueList.getConstantFwdRef(Op0Idx, OpTy);
2406         Constant *Op1 = ValueList.getConstantFwdRef(Op1Idx, OpTy);
2407         Type *ShufTy =
2408             VectorType::get(Type::getInt32Ty(Context), RTy->getElementCount());
2409         Constant *Op2 = ValueList.getConstantFwdRef(Op2Idx, ShufTy);
2410         if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
2411           return error("Invalid shufflevector operands");
2412         SmallVector<int, 16> Mask;
2413         ShuffleVectorInst::getShuffleMask(Op2, Mask);
2414         Value *V = ConstantExpr::getShuffleVector(Op0, Op1, Mask);
2415         ValueList.assignValue(V, CstNo, DelayedShuffle.CurFullTy);
2416       }
2417 
2418       if (NextCstNo != ValueList.size())
2419         return error("Invalid constant reference");
2420 
2421       ValueList.resolveConstantForwardRefs();
2422       return Error::success();
2423     case BitstreamEntry::Record:
2424       // The interesting case.
2425       break;
2426     }
2427 
2428     // Read a record.
2429     Record.clear();
2430     Type *VoidType = Type::getVoidTy(Context);
2431     Value *V = nullptr;
2432     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2433     if (!MaybeBitCode)
2434       return MaybeBitCode.takeError();
2435     switch (unsigned BitCode = MaybeBitCode.get()) {
2436     default:  // Default behavior: unknown constant
2437     case bitc::CST_CODE_UNDEF:     // UNDEF
2438       V = UndefValue::get(CurTy);
2439       break;
2440     case bitc::CST_CODE_POISON:    // POISON
2441       V = PoisonValue::get(CurTy);
2442       break;
2443     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
2444       if (Record.empty())
2445         return error("Invalid record");
2446       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2447         return error("Invalid record");
2448       if (TypeList[Record[0]] == VoidType)
2449         return error("Invalid constant type");
2450       CurFullTy = TypeList[Record[0]];
2451       CurTy = flattenPointerTypes(CurFullTy);
2452       continue;  // Skip the ValueList manipulation.
2453     case bitc::CST_CODE_NULL:      // NULL
2454       if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
2455         return error("Invalid type for a constant null value");
2456       V = Constant::getNullValue(CurTy);
2457       break;
2458     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
2459       if (!CurTy->isIntegerTy() || Record.empty())
2460         return error("Invalid record");
2461       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
2462       break;
2463     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2464       if (!CurTy->isIntegerTy() || Record.empty())
2465         return error("Invalid record");
2466 
2467       APInt VInt =
2468           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2469       V = ConstantInt::get(Context, VInt);
2470 
2471       break;
2472     }
2473     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
2474       if (Record.empty())
2475         return error("Invalid record");
2476       if (CurTy->isHalfTy())
2477         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2478                                              APInt(16, (uint16_t)Record[0])));
2479       else if (CurTy->isBFloatTy())
2480         V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
2481                                              APInt(16, (uint32_t)Record[0])));
2482       else if (CurTy->isFloatTy())
2483         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2484                                              APInt(32, (uint32_t)Record[0])));
2485       else if (CurTy->isDoubleTy())
2486         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2487                                              APInt(64, Record[0])));
2488       else if (CurTy->isX86_FP80Ty()) {
2489         // Bits are not stored the same way as a normal i80 APInt, compensate.
2490         uint64_t Rearrange[2];
2491         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2492         Rearrange[1] = Record[0] >> 48;
2493         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2494                                              APInt(80, Rearrange)));
2495       } else if (CurTy->isFP128Ty())
2496         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2497                                              APInt(128, Record)));
2498       else if (CurTy->isPPC_FP128Ty())
2499         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2500                                              APInt(128, Record)));
2501       else
2502         V = UndefValue::get(CurTy);
2503       break;
2504     }
2505 
2506     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2507       if (Record.empty())
2508         return error("Invalid record");
2509 
2510       unsigned Size = Record.size();
2511       SmallVector<Constant*, 16> Elts;
2512 
2513       if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2514         for (unsigned i = 0; i != Size; ++i)
2515           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2516                                                      STy->getElementType(i)));
2517         V = ConstantStruct::get(STy, Elts);
2518       } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2519         Type *EltTy = ATy->getElementType();
2520         for (unsigned i = 0; i != Size; ++i)
2521           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2522         V = ConstantArray::get(ATy, Elts);
2523       } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2524         Type *EltTy = VTy->getElementType();
2525         for (unsigned i = 0; i != Size; ++i)
2526           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2527         V = ConstantVector::get(Elts);
2528       } else {
2529         V = UndefValue::get(CurTy);
2530       }
2531       break;
2532     }
2533     case bitc::CST_CODE_STRING:    // STRING: [values]
2534     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2535       if (Record.empty())
2536         return error("Invalid record");
2537 
2538       SmallString<16> Elts(Record.begin(), Record.end());
2539       V = ConstantDataArray::getString(Context, Elts,
2540                                        BitCode == bitc::CST_CODE_CSTRING);
2541       break;
2542     }
2543     case bitc::CST_CODE_DATA: {// DATA: [n x value]
2544       if (Record.empty())
2545         return error("Invalid record");
2546 
2547       Type *EltTy;
2548       if (auto *Array = dyn_cast<ArrayType>(CurTy))
2549         EltTy = Array->getElementType();
2550       else
2551         EltTy = cast<VectorType>(CurTy)->getElementType();
2552       if (EltTy->isIntegerTy(8)) {
2553         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2554         if (isa<VectorType>(CurTy))
2555           V = ConstantDataVector::get(Context, Elts);
2556         else
2557           V = ConstantDataArray::get(Context, Elts);
2558       } else if (EltTy->isIntegerTy(16)) {
2559         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2560         if (isa<VectorType>(CurTy))
2561           V = ConstantDataVector::get(Context, Elts);
2562         else
2563           V = ConstantDataArray::get(Context, Elts);
2564       } else if (EltTy->isIntegerTy(32)) {
2565         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2566         if (isa<VectorType>(CurTy))
2567           V = ConstantDataVector::get(Context, Elts);
2568         else
2569           V = ConstantDataArray::get(Context, Elts);
2570       } else if (EltTy->isIntegerTy(64)) {
2571         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2572         if (isa<VectorType>(CurTy))
2573           V = ConstantDataVector::get(Context, Elts);
2574         else
2575           V = ConstantDataArray::get(Context, Elts);
2576       } else if (EltTy->isHalfTy()) {
2577         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2578         if (isa<VectorType>(CurTy))
2579           V = ConstantDataVector::getFP(EltTy, Elts);
2580         else
2581           V = ConstantDataArray::getFP(EltTy, Elts);
2582       } else if (EltTy->isBFloatTy()) {
2583         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2584         if (isa<VectorType>(CurTy))
2585           V = ConstantDataVector::getFP(EltTy, Elts);
2586         else
2587           V = ConstantDataArray::getFP(EltTy, Elts);
2588       } else if (EltTy->isFloatTy()) {
2589         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2590         if (isa<VectorType>(CurTy))
2591           V = ConstantDataVector::getFP(EltTy, Elts);
2592         else
2593           V = ConstantDataArray::getFP(EltTy, Elts);
2594       } else if (EltTy->isDoubleTy()) {
2595         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2596         if (isa<VectorType>(CurTy))
2597           V = ConstantDataVector::getFP(EltTy, Elts);
2598         else
2599           V = ConstantDataArray::getFP(EltTy, Elts);
2600       } else {
2601         return error("Invalid type for value");
2602       }
2603       break;
2604     }
2605     case bitc::CST_CODE_CE_UNOP: {  // CE_UNOP: [opcode, opval]
2606       if (Record.size() < 2)
2607         return error("Invalid record");
2608       int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
2609       if (Opc < 0) {
2610         V = UndefValue::get(CurTy);  // Unknown unop.
2611       } else {
2612         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2613         unsigned Flags = 0;
2614         V = ConstantExpr::get(Opc, LHS, Flags);
2615       }
2616       break;
2617     }
2618     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
2619       if (Record.size() < 3)
2620         return error("Invalid record");
2621       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2622       if (Opc < 0) {
2623         V = UndefValue::get(CurTy);  // Unknown binop.
2624       } else {
2625         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2626         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2627         unsigned Flags = 0;
2628         if (Record.size() >= 4) {
2629           if (Opc == Instruction::Add ||
2630               Opc == Instruction::Sub ||
2631               Opc == Instruction::Mul ||
2632               Opc == Instruction::Shl) {
2633             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2634               Flags |= OverflowingBinaryOperator::NoSignedWrap;
2635             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2636               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2637           } else if (Opc == Instruction::SDiv ||
2638                      Opc == Instruction::UDiv ||
2639                      Opc == Instruction::LShr ||
2640                      Opc == Instruction::AShr) {
2641             if (Record[3] & (1 << bitc::PEO_EXACT))
2642               Flags |= SDivOperator::IsExact;
2643           }
2644         }
2645         V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2646       }
2647       break;
2648     }
2649     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
2650       if (Record.size() < 3)
2651         return error("Invalid record");
2652       int Opc = getDecodedCastOpcode(Record[0]);
2653       if (Opc < 0) {
2654         V = UndefValue::get(CurTy);  // Unknown cast.
2655       } else {
2656         Type *OpTy = getTypeByID(Record[1]);
2657         if (!OpTy)
2658           return error("Invalid record");
2659         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2660         V = UpgradeBitCastExpr(Opc, Op, CurTy);
2661         if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2662       }
2663       break;
2664     }
2665     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2666     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2667     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2668                                                      // operands]
2669       unsigned OpNum = 0;
2670       Type *PointeeType = nullptr;
2671       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
2672           Record.size() % 2)
2673         PointeeType = getTypeByID(Record[OpNum++]);
2674 
2675       bool InBounds = false;
2676       Optional<unsigned> InRangeIndex;
2677       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
2678         uint64_t Op = Record[OpNum++];
2679         InBounds = Op & 1;
2680         InRangeIndex = Op >> 1;
2681       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2682         InBounds = true;
2683 
2684       SmallVector<Constant*, 16> Elts;
2685       Type *Elt0FullTy = nullptr;
2686       while (OpNum != Record.size()) {
2687         if (!Elt0FullTy)
2688           Elt0FullTy = getFullyStructuredTypeByID(Record[OpNum]);
2689         Type *ElTy = getTypeByID(Record[OpNum++]);
2690         if (!ElTy)
2691           return error("Invalid record");
2692         Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2693       }
2694 
2695       if (Elts.size() < 1)
2696         return error("Invalid gep with no operands");
2697 
2698       Type *ImplicitPointeeType =
2699           getPointerElementFlatType(Elt0FullTy->getScalarType());
2700       if (!PointeeType)
2701         PointeeType = ImplicitPointeeType;
2702       else if (PointeeType != ImplicitPointeeType)
2703         return error("Explicit gep operator type does not match pointee type "
2704                      "of pointer operand");
2705 
2706       ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2707       V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2708                                          InBounds, InRangeIndex);
2709       break;
2710     }
2711     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
2712       if (Record.size() < 3)
2713         return error("Invalid record");
2714 
2715       Type *SelectorTy = Type::getInt1Ty(Context);
2716 
2717       // The selector might be an i1, an <n x i1>, or a <vscale x n x i1>
2718       // Get the type from the ValueList before getting a forward ref.
2719       if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2720         if (Value *V = ValueList[Record[0]])
2721           if (SelectorTy != V->getType())
2722             SelectorTy = VectorType::get(SelectorTy,
2723                                          VTy->getElementCount());
2724 
2725       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2726                                                               SelectorTy),
2727                                   ValueList.getConstantFwdRef(Record[1],CurTy),
2728                                   ValueList.getConstantFwdRef(Record[2],CurTy));
2729       break;
2730     }
2731     case bitc::CST_CODE_CE_EXTRACTELT
2732         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2733       if (Record.size() < 3)
2734         return error("Invalid record");
2735       VectorType *OpTy =
2736         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2737       if (!OpTy)
2738         return error("Invalid record");
2739       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2740       Constant *Op1 = nullptr;
2741       if (Record.size() == 4) {
2742         Type *IdxTy = getTypeByID(Record[2]);
2743         if (!IdxTy)
2744           return error("Invalid record");
2745         Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2746       } else {
2747         // Deprecated, but still needed to read old bitcode files.
2748         Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2749       }
2750       if (!Op1)
2751         return error("Invalid record");
2752       V = ConstantExpr::getExtractElement(Op0, Op1);
2753       break;
2754     }
2755     case bitc::CST_CODE_CE_INSERTELT
2756         : { // CE_INSERTELT: [opval, opval, opty, opval]
2757       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2758       if (Record.size() < 3 || !OpTy)
2759         return error("Invalid record");
2760       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2761       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2762                                                   OpTy->getElementType());
2763       Constant *Op2 = nullptr;
2764       if (Record.size() == 4) {
2765         Type *IdxTy = getTypeByID(Record[2]);
2766         if (!IdxTy)
2767           return error("Invalid record");
2768         Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2769       } else {
2770         // Deprecated, but still needed to read old bitcode files.
2771         Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2772       }
2773       if (!Op2)
2774         return error("Invalid record");
2775       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2776       break;
2777     }
2778     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2779       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2780       if (Record.size() < 3 || !OpTy)
2781         return error("Invalid record");
2782       DelayedShuffles.push_back(
2783           {OpTy, OpTy, CurFullTy, Record[0], Record[1], Record[2], NextCstNo});
2784       ++NextCstNo;
2785       continue;
2786     }
2787     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2788       VectorType *RTy = dyn_cast<VectorType>(CurTy);
2789       VectorType *OpTy =
2790         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2791       if (Record.size() < 4 || !RTy || !OpTy)
2792         return error("Invalid record");
2793       DelayedShuffles.push_back(
2794           {OpTy, RTy, CurFullTy, Record[1], Record[2], Record[3], NextCstNo});
2795       ++NextCstNo;
2796       continue;
2797     }
2798     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
2799       if (Record.size() < 4)
2800         return error("Invalid record");
2801       Type *OpTy = getTypeByID(Record[0]);
2802       if (!OpTy)
2803         return error("Invalid record");
2804       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2805       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2806 
2807       if (OpTy->isFPOrFPVectorTy())
2808         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2809       else
2810         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2811       break;
2812     }
2813     // This maintains backward compatibility, pre-asm dialect keywords.
2814     // Deprecated, but still needed to read old bitcode files.
2815     case bitc::CST_CODE_INLINEASM_OLD: {
2816       if (Record.size() < 2)
2817         return error("Invalid record");
2818       std::string AsmStr, ConstrStr;
2819       bool HasSideEffects = Record[0] & 1;
2820       bool IsAlignStack = Record[0] >> 1;
2821       unsigned AsmStrSize = Record[1];
2822       if (2+AsmStrSize >= Record.size())
2823         return error("Invalid record");
2824       unsigned ConstStrSize = Record[2+AsmStrSize];
2825       if (3+AsmStrSize+ConstStrSize > Record.size())
2826         return error("Invalid record");
2827 
2828       for (unsigned i = 0; i != AsmStrSize; ++i)
2829         AsmStr += (char)Record[2+i];
2830       for (unsigned i = 0; i != ConstStrSize; ++i)
2831         ConstrStr += (char)Record[3+AsmStrSize+i];
2832       UpgradeInlineAsmString(&AsmStr);
2833       V = InlineAsm::get(
2834           cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr,
2835           ConstrStr, HasSideEffects, IsAlignStack);
2836       break;
2837     }
2838     // This version adds support for the asm dialect keywords (e.g.,
2839     // inteldialect).
2840     case bitc::CST_CODE_INLINEASM_OLD2: {
2841       if (Record.size() < 2)
2842         return error("Invalid record");
2843       std::string AsmStr, ConstrStr;
2844       bool HasSideEffects = Record[0] & 1;
2845       bool IsAlignStack = (Record[0] >> 1) & 1;
2846       unsigned AsmDialect = Record[0] >> 2;
2847       unsigned AsmStrSize = Record[1];
2848       if (2+AsmStrSize >= Record.size())
2849         return error("Invalid record");
2850       unsigned ConstStrSize = Record[2+AsmStrSize];
2851       if (3+AsmStrSize+ConstStrSize > Record.size())
2852         return error("Invalid record");
2853 
2854       for (unsigned i = 0; i != AsmStrSize; ++i)
2855         AsmStr += (char)Record[2+i];
2856       for (unsigned i = 0; i != ConstStrSize; ++i)
2857         ConstrStr += (char)Record[3+AsmStrSize+i];
2858       UpgradeInlineAsmString(&AsmStr);
2859       V = InlineAsm::get(
2860           cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr,
2861           ConstrStr, HasSideEffects, IsAlignStack,
2862           InlineAsm::AsmDialect(AsmDialect));
2863       break;
2864     }
2865     // This version adds support for the unwind keyword.
2866     case bitc::CST_CODE_INLINEASM: {
2867       if (Record.size() < 2)
2868         return error("Invalid record");
2869       std::string AsmStr, ConstrStr;
2870       bool HasSideEffects = Record[0] & 1;
2871       bool IsAlignStack = (Record[0] >> 1) & 1;
2872       unsigned AsmDialect = (Record[0] >> 2) & 1;
2873       bool CanThrow = (Record[0] >> 3) & 1;
2874       unsigned AsmStrSize = Record[1];
2875       if (2 + AsmStrSize >= Record.size())
2876         return error("Invalid record");
2877       unsigned ConstStrSize = Record[2 + AsmStrSize];
2878       if (3 + AsmStrSize + ConstStrSize > Record.size())
2879         return error("Invalid record");
2880 
2881       for (unsigned i = 0; i != AsmStrSize; ++i)
2882         AsmStr += (char)Record[2 + i];
2883       for (unsigned i = 0; i != ConstStrSize; ++i)
2884         ConstrStr += (char)Record[3 + AsmStrSize + i];
2885       UpgradeInlineAsmString(&AsmStr);
2886       V = InlineAsm::get(
2887           cast<FunctionType>(getPointerElementFlatType(CurFullTy)), AsmStr,
2888           ConstrStr, HasSideEffects, IsAlignStack,
2889           InlineAsm::AsmDialect(AsmDialect), CanThrow);
2890       break;
2891     }
2892     case bitc::CST_CODE_BLOCKADDRESS:{
2893       if (Record.size() < 3)
2894         return error("Invalid record");
2895       Type *FnTy = getTypeByID(Record[0]);
2896       if (!FnTy)
2897         return error("Invalid record");
2898       Function *Fn =
2899         dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2900       if (!Fn)
2901         return error("Invalid record");
2902 
2903       // If the function is already parsed we can insert the block address right
2904       // away.
2905       BasicBlock *BB;
2906       unsigned BBID = Record[2];
2907       if (!BBID)
2908         // Invalid reference to entry block.
2909         return error("Invalid ID");
2910       if (!Fn->empty()) {
2911         Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2912         for (size_t I = 0, E = BBID; I != E; ++I) {
2913           if (BBI == BBE)
2914             return error("Invalid ID");
2915           ++BBI;
2916         }
2917         BB = &*BBI;
2918       } else {
2919         // Otherwise insert a placeholder and remember it so it can be inserted
2920         // when the function is parsed.
2921         auto &FwdBBs = BasicBlockFwdRefs[Fn];
2922         if (FwdBBs.empty())
2923           BasicBlockFwdRefQueue.push_back(Fn);
2924         if (FwdBBs.size() < BBID + 1)
2925           FwdBBs.resize(BBID + 1);
2926         if (!FwdBBs[BBID])
2927           FwdBBs[BBID] = BasicBlock::Create(Context);
2928         BB = FwdBBs[BBID];
2929       }
2930       V = BlockAddress::get(Fn, BB);
2931       break;
2932     }
2933     case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
2934       if (Record.size() < 2)
2935         return error("Invalid record");
2936       Type *GVTy = getTypeByID(Record[0]);
2937       if (!GVTy)
2938         return error("Invalid record");
2939       GlobalValue *GV = dyn_cast_or_null<GlobalValue>(
2940           ValueList.getConstantFwdRef(Record[1], GVTy));
2941       if (!GV)
2942         return error("Invalid record");
2943 
2944       V = DSOLocalEquivalent::get(GV);
2945       break;
2946     }
2947     }
2948 
2949     assert(V->getType() == flattenPointerTypes(CurFullTy) &&
2950            "Incorrect fully structured type provided for Constant");
2951     ValueList.assignValue(V, NextCstNo, CurFullTy);
2952     ++NextCstNo;
2953   }
2954 }
2955 
2956 Error BitcodeReader::parseUseLists() {
2957   if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
2958     return Err;
2959 
2960   // Read all the records.
2961   SmallVector<uint64_t, 64> Record;
2962 
2963   while (true) {
2964     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2965     if (!MaybeEntry)
2966       return MaybeEntry.takeError();
2967     BitstreamEntry Entry = MaybeEntry.get();
2968 
2969     switch (Entry.Kind) {
2970     case BitstreamEntry::SubBlock: // Handled for us already.
2971     case BitstreamEntry::Error:
2972       return error("Malformed block");
2973     case BitstreamEntry::EndBlock:
2974       return Error::success();
2975     case BitstreamEntry::Record:
2976       // The interesting case.
2977       break;
2978     }
2979 
2980     // Read a use list record.
2981     Record.clear();
2982     bool IsBB = false;
2983     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2984     if (!MaybeRecord)
2985       return MaybeRecord.takeError();
2986     switch (MaybeRecord.get()) {
2987     default:  // Default behavior: unknown type.
2988       break;
2989     case bitc::USELIST_CODE_BB:
2990       IsBB = true;
2991       LLVM_FALLTHROUGH;
2992     case bitc::USELIST_CODE_DEFAULT: {
2993       unsigned RecordLength = Record.size();
2994       if (RecordLength < 3)
2995         // Records should have at least an ID and two indexes.
2996         return error("Invalid record");
2997       unsigned ID = Record.pop_back_val();
2998 
2999       Value *V;
3000       if (IsBB) {
3001         assert(ID < FunctionBBs.size() && "Basic block not found");
3002         V = FunctionBBs[ID];
3003       } else
3004         V = ValueList[ID];
3005       unsigned NumUses = 0;
3006       SmallDenseMap<const Use *, unsigned, 16> Order;
3007       for (const Use &U : V->materialized_uses()) {
3008         if (++NumUses > Record.size())
3009           break;
3010         Order[&U] = Record[NumUses - 1];
3011       }
3012       if (Order.size() != Record.size() || NumUses > Record.size())
3013         // Mismatches can happen if the functions are being materialized lazily
3014         // (out-of-order), or a value has been upgraded.
3015         break;
3016 
3017       V->sortUseList([&](const Use &L, const Use &R) {
3018         return Order.lookup(&L) < Order.lookup(&R);
3019       });
3020       break;
3021     }
3022     }
3023   }
3024 }
3025 
3026 /// When we see the block for metadata, remember where it is and then skip it.
3027 /// This lets us lazily deserialize the metadata.
3028 Error BitcodeReader::rememberAndSkipMetadata() {
3029   // Save the current stream state.
3030   uint64_t CurBit = Stream.GetCurrentBitNo();
3031   DeferredMetadataInfo.push_back(CurBit);
3032 
3033   // Skip over the block for now.
3034   if (Error Err = Stream.SkipBlock())
3035     return Err;
3036   return Error::success();
3037 }
3038 
3039 Error BitcodeReader::materializeMetadata() {
3040   for (uint64_t BitPos : DeferredMetadataInfo) {
3041     // Move the bit stream to the saved position.
3042     if (Error JumpFailed = Stream.JumpToBit(BitPos))
3043       return JumpFailed;
3044     if (Error Err = MDLoader->parseModuleMetadata())
3045       return Err;
3046   }
3047 
3048   // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3049   // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3050   // multiple times.
3051   if (!TheModule->getNamedMetadata("llvm.linker.options")) {
3052     if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
3053       NamedMDNode *LinkerOpts =
3054           TheModule->getOrInsertNamedMetadata("llvm.linker.options");
3055       for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3056         LinkerOpts->addOperand(cast<MDNode>(MDOptions));
3057     }
3058   }
3059 
3060   DeferredMetadataInfo.clear();
3061   return Error::success();
3062 }
3063 
3064 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3065 
3066 /// When we see the block for a function body, remember where it is and then
3067 /// skip it.  This lets us lazily deserialize the functions.
3068 Error BitcodeReader::rememberAndSkipFunctionBody() {
3069   // Get the function we are talking about.
3070   if (FunctionsWithBodies.empty())
3071     return error("Insufficient function protos");
3072 
3073   Function *Fn = FunctionsWithBodies.back();
3074   FunctionsWithBodies.pop_back();
3075 
3076   // Save the current stream state.
3077   uint64_t CurBit = Stream.GetCurrentBitNo();
3078   assert(
3079       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3080       "Mismatch between VST and scanned function offsets");
3081   DeferredFunctionInfo[Fn] = CurBit;
3082 
3083   // Skip over the function block for now.
3084   if (Error Err = Stream.SkipBlock())
3085     return Err;
3086   return Error::success();
3087 }
3088 
3089 Error BitcodeReader::globalCleanup() {
3090   // Patch the initializers for globals and aliases up.
3091   if (Error Err = resolveGlobalAndIndirectSymbolInits())
3092     return Err;
3093   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3094     return error("Malformed global initializer set");
3095 
3096   // Look for intrinsic functions which need to be upgraded at some point
3097   // and functions that need to have their function attributes upgraded.
3098   for (Function &F : *TheModule) {
3099     MDLoader->upgradeDebugIntrinsics(F);
3100     Function *NewFn;
3101     if (UpgradeIntrinsicFunction(&F, NewFn))
3102       UpgradedIntrinsics[&F] = NewFn;
3103     else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3104       // Some types could be renamed during loading if several modules are
3105       // loaded in the same LLVMContext (LTO scenario). In this case we should
3106       // remangle intrinsics names as well.
3107       RemangledIntrinsics[&F] = Remangled.getValue();
3108     // Look for functions that rely on old function attribute behavior.
3109     UpgradeFunctionAttributes(F);
3110   }
3111 
3112   // Look for global variables which need to be renamed.
3113   std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3114   for (GlobalVariable &GV : TheModule->globals())
3115     if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
3116       UpgradedVariables.emplace_back(&GV, Upgraded);
3117   for (auto &Pair : UpgradedVariables) {
3118     Pair.first->eraseFromParent();
3119     TheModule->getGlobalList().push_back(Pair.second);
3120   }
3121 
3122   // Force deallocation of memory for these vectors to favor the client that
3123   // want lazy deserialization.
3124   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3125   std::vector<std::pair<GlobalIndirectSymbol *, unsigned>>().swap(
3126       IndirectSymbolInits);
3127   return Error::success();
3128 }
3129 
3130 /// Support for lazy parsing of function bodies. This is required if we
3131 /// either have an old bitcode file without a VST forward declaration record,
3132 /// or if we have an anonymous function being materialized, since anonymous
3133 /// functions do not have a name and are therefore not in the VST.
3134 Error BitcodeReader::rememberAndSkipFunctionBodies() {
3135   if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3136     return JumpFailed;
3137 
3138   if (Stream.AtEndOfStream())
3139     return error("Could not find function in stream");
3140 
3141   if (!SeenFirstFunctionBody)
3142     return error("Trying to materialize functions before seeing function blocks");
3143 
3144   // An old bitcode file with the symbol table at the end would have
3145   // finished the parse greedily.
3146   assert(SeenValueSymbolTable);
3147 
3148   SmallVector<uint64_t, 64> Record;
3149 
3150   while (true) {
3151     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3152     if (!MaybeEntry)
3153       return MaybeEntry.takeError();
3154     llvm::BitstreamEntry Entry = MaybeEntry.get();
3155 
3156     switch (Entry.Kind) {
3157     default:
3158       return error("Expect SubBlock");
3159     case BitstreamEntry::SubBlock:
3160       switch (Entry.ID) {
3161       default:
3162         return error("Expect function block");
3163       case bitc::FUNCTION_BLOCK_ID:
3164         if (Error Err = rememberAndSkipFunctionBody())
3165           return Err;
3166         NextUnreadBit = Stream.GetCurrentBitNo();
3167         return Error::success();
3168       }
3169     }
3170   }
3171 }
3172 
3173 bool BitcodeReaderBase::readBlockInfo() {
3174   Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
3175       Stream.ReadBlockInfoBlock();
3176   if (!MaybeNewBlockInfo)
3177     return true; // FIXME Handle the error.
3178   Optional<BitstreamBlockInfo> NewBlockInfo =
3179       std::move(MaybeNewBlockInfo.get());
3180   if (!NewBlockInfo)
3181     return true;
3182   BlockInfo = std::move(*NewBlockInfo);
3183   return false;
3184 }
3185 
3186 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
3187   // v1: [selection_kind, name]
3188   // v2: [strtab_offset, strtab_size, selection_kind]
3189   StringRef Name;
3190   std::tie(Name, Record) = readNameFromStrtab(Record);
3191 
3192   if (Record.empty())
3193     return error("Invalid record");
3194   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3195   std::string OldFormatName;
3196   if (!UseStrtab) {
3197     if (Record.size() < 2)
3198       return error("Invalid record");
3199     unsigned ComdatNameSize = Record[1];
3200     OldFormatName.reserve(ComdatNameSize);
3201     for (unsigned i = 0; i != ComdatNameSize; ++i)
3202       OldFormatName += (char)Record[2 + i];
3203     Name = OldFormatName;
3204   }
3205   Comdat *C = TheModule->getOrInsertComdat(Name);
3206   C->setSelectionKind(SK);
3207   ComdatList.push_back(C);
3208   return Error::success();
3209 }
3210 
3211 static void inferDSOLocal(GlobalValue *GV) {
3212   // infer dso_local from linkage and visibility if it is not encoded.
3213   if (GV->hasLocalLinkage() ||
3214       (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
3215     GV->setDSOLocal(true);
3216 }
3217 
3218 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
3219   // v1: [pointer type, isconst, initid, linkage, alignment, section,
3220   // visibility, threadlocal, unnamed_addr, externally_initialized,
3221   // dllstorageclass, comdat, attributes, preemption specifier,
3222   // partition strtab offset, partition strtab size] (name in VST)
3223   // v2: [strtab_offset, strtab_size, v1]
3224   StringRef Name;
3225   std::tie(Name, Record) = readNameFromStrtab(Record);
3226 
3227   if (Record.size() < 6)
3228     return error("Invalid record");
3229   Type *FullTy = getFullyStructuredTypeByID(Record[0]);
3230   Type *Ty = flattenPointerTypes(FullTy);
3231   if (!Ty)
3232     return error("Invalid record");
3233   bool isConstant = Record[1] & 1;
3234   bool explicitType = Record[1] & 2;
3235   unsigned AddressSpace;
3236   if (explicitType) {
3237     AddressSpace = Record[1] >> 2;
3238   } else {
3239     if (!Ty->isPointerTy())
3240       return error("Invalid type for value");
3241     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3242     std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
3243   }
3244 
3245   uint64_t RawLinkage = Record[3];
3246   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3247   MaybeAlign Alignment;
3248   if (Error Err = parseAlignmentValue(Record[4], Alignment))
3249     return Err;
3250   std::string Section;
3251   if (Record[5]) {
3252     if (Record[5] - 1 >= SectionTable.size())
3253       return error("Invalid ID");
3254     Section = SectionTable[Record[5] - 1];
3255   }
3256   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3257   // Local linkage must have default visibility.
3258   // auto-upgrade `hidden` and `protected` for old bitcode.
3259   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3260     Visibility = getDecodedVisibility(Record[6]);
3261 
3262   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3263   if (Record.size() > 7)
3264     TLM = getDecodedThreadLocalMode(Record[7]);
3265 
3266   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3267   if (Record.size() > 8)
3268     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3269 
3270   bool ExternallyInitialized = false;
3271   if (Record.size() > 9)
3272     ExternallyInitialized = Record[9];
3273 
3274   GlobalVariable *NewGV =
3275       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
3276                          nullptr, TLM, AddressSpace, ExternallyInitialized);
3277   NewGV->setAlignment(Alignment);
3278   if (!Section.empty())
3279     NewGV->setSection(Section);
3280   NewGV->setVisibility(Visibility);
3281   NewGV->setUnnamedAddr(UnnamedAddr);
3282 
3283   if (Record.size() > 10)
3284     NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3285   else
3286     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3287 
3288   FullTy = PointerType::get(FullTy, AddressSpace);
3289   assert(NewGV->getType() == flattenPointerTypes(FullTy) &&
3290          "Incorrect fully specified type for GlobalVariable");
3291   ValueList.push_back(NewGV, FullTy);
3292 
3293   // Remember which value to use for the global initializer.
3294   if (unsigned InitID = Record[2])
3295     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
3296 
3297   if (Record.size() > 11) {
3298     if (unsigned ComdatID = Record[11]) {
3299       if (ComdatID > ComdatList.size())
3300         return error("Invalid global variable comdat ID");
3301       NewGV->setComdat(ComdatList[ComdatID - 1]);
3302     }
3303   } else if (hasImplicitComdat(RawLinkage)) {
3304     NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3305   }
3306 
3307   if (Record.size() > 12) {
3308     auto AS = getAttributes(Record[12]).getFnAttributes();
3309     NewGV->setAttributes(AS);
3310   }
3311 
3312   if (Record.size() > 13) {
3313     NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
3314   }
3315   inferDSOLocal(NewGV);
3316 
3317   // Check whether we have enough values to read a partition name.
3318   if (Record.size() > 15)
3319     NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
3320 
3321   return Error::success();
3322 }
3323 
3324 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
3325   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3326   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3327   // prefixdata,  personalityfn, preemption specifier, addrspace] (name in VST)
3328   // v2: [strtab_offset, strtab_size, v1]
3329   StringRef Name;
3330   std::tie(Name, Record) = readNameFromStrtab(Record);
3331 
3332   if (Record.size() < 8)
3333     return error("Invalid record");
3334   Type *FullFTy = getFullyStructuredTypeByID(Record[0]);
3335   Type *FTy = flattenPointerTypes(FullFTy);
3336   if (!FTy)
3337     return error("Invalid record");
3338   if (isa<PointerType>(FTy))
3339     std::tie(FullFTy, FTy) = getPointerElementTypes(FullFTy);
3340 
3341   if (!isa<FunctionType>(FTy))
3342     return error("Invalid type for value");
3343   auto CC = static_cast<CallingConv::ID>(Record[1]);
3344   if (CC & ~CallingConv::MaxID)
3345     return error("Invalid calling convention ID");
3346 
3347   unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3348   if (Record.size() > 16)
3349     AddrSpace = Record[16];
3350 
3351   Function *Func =
3352       Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
3353                        AddrSpace, Name, TheModule);
3354 
3355   assert(Func->getFunctionType() == flattenPointerTypes(FullFTy) &&
3356          "Incorrect fully specified type provided for function");
3357   FunctionTypes[Func] = cast<FunctionType>(FullFTy);
3358 
3359   Func->setCallingConv(CC);
3360   bool isProto = Record[2];
3361   uint64_t RawLinkage = Record[3];
3362   Func->setLinkage(getDecodedLinkage(RawLinkage));
3363   Func->setAttributes(getAttributes(Record[4]));
3364 
3365   // Upgrade any old-style byval or sret without a type by propagating the
3366   // argument's pointee type. There should be no opaque pointers where the byval
3367   // type is implicit.
3368   for (unsigned i = 0; i != Func->arg_size(); ++i) {
3369     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3370                                      Attribute::InAlloca}) {
3371       if (!Func->hasParamAttribute(i, Kind))
3372         continue;
3373 
3374       Func->removeParamAttr(i, Kind);
3375 
3376       Type *PTy = cast<FunctionType>(FullFTy)->getParamType(i);
3377       Type *PtrEltTy = getPointerElementFlatType(PTy);
3378       Attribute NewAttr;
3379       switch (Kind) {
3380       case Attribute::ByVal:
3381         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3382         break;
3383       case Attribute::StructRet:
3384         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3385         break;
3386       case Attribute::InAlloca:
3387         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3388         break;
3389       default:
3390         llvm_unreachable("not an upgraded type attribute");
3391       }
3392 
3393       Func->addParamAttr(i, NewAttr);
3394     }
3395   }
3396 
3397   MaybeAlign Alignment;
3398   if (Error Err = parseAlignmentValue(Record[5], Alignment))
3399     return Err;
3400   Func->setAlignment(Alignment);
3401   if (Record[6]) {
3402     if (Record[6] - 1 >= SectionTable.size())
3403       return error("Invalid ID");
3404     Func->setSection(SectionTable[Record[6] - 1]);
3405   }
3406   // Local linkage must have default visibility.
3407   // auto-upgrade `hidden` and `protected` for old bitcode.
3408   if (!Func->hasLocalLinkage())
3409     Func->setVisibility(getDecodedVisibility(Record[7]));
3410   if (Record.size() > 8 && Record[8]) {
3411     if (Record[8] - 1 >= GCTable.size())
3412       return error("Invalid ID");
3413     Func->setGC(GCTable[Record[8] - 1]);
3414   }
3415   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3416   if (Record.size() > 9)
3417     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3418   Func->setUnnamedAddr(UnnamedAddr);
3419   if (Record.size() > 10 && Record[10] != 0)
3420     FunctionPrologues.push_back(std::make_pair(Func, Record[10] - 1));
3421 
3422   if (Record.size() > 11)
3423     Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3424   else
3425     upgradeDLLImportExportLinkage(Func, RawLinkage);
3426 
3427   if (Record.size() > 12) {
3428     if (unsigned ComdatID = Record[12]) {
3429       if (ComdatID > ComdatList.size())
3430         return error("Invalid function comdat ID");
3431       Func->setComdat(ComdatList[ComdatID - 1]);
3432     }
3433   } else if (hasImplicitComdat(RawLinkage)) {
3434     Func->setComdat(reinterpret_cast<Comdat *>(1));
3435   }
3436 
3437   if (Record.size() > 13 && Record[13] != 0)
3438     FunctionPrefixes.push_back(std::make_pair(Func, Record[13] - 1));
3439 
3440   if (Record.size() > 14 && Record[14] != 0)
3441     FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3442 
3443   if (Record.size() > 15) {
3444     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3445   }
3446   inferDSOLocal(Func);
3447 
3448   // Record[16] is the address space number.
3449 
3450   // Check whether we have enough values to read a partition name.
3451   if (Record.size() > 18)
3452     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
3453 
3454   Type *FullTy = PointerType::get(FullFTy, AddrSpace);
3455   assert(Func->getType() == flattenPointerTypes(FullTy) &&
3456          "Incorrect fully specified type provided for Function");
3457   ValueList.push_back(Func, FullTy);
3458 
3459   // If this is a function with a body, remember the prototype we are
3460   // creating now, so that we can match up the body with them later.
3461   if (!isProto) {
3462     Func->setIsMaterializable(true);
3463     FunctionsWithBodies.push_back(Func);
3464     DeferredFunctionInfo[Func] = 0;
3465   }
3466   return Error::success();
3467 }
3468 
3469 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3470     unsigned BitCode, ArrayRef<uint64_t> Record) {
3471   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3472   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3473   // dllstorageclass, threadlocal, unnamed_addr,
3474   // preemption specifier] (name in VST)
3475   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3476   // visibility, dllstorageclass, threadlocal, unnamed_addr,
3477   // preemption specifier] (name in VST)
3478   // v2: [strtab_offset, strtab_size, v1]
3479   StringRef Name;
3480   std::tie(Name, Record) = readNameFromStrtab(Record);
3481 
3482   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3483   if (Record.size() < (3 + (unsigned)NewRecord))
3484     return error("Invalid record");
3485   unsigned OpNum = 0;
3486   Type *FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
3487   Type *Ty = flattenPointerTypes(FullTy);
3488   if (!Ty)
3489     return error("Invalid record");
3490 
3491   unsigned AddrSpace;
3492   if (!NewRecord) {
3493     auto *PTy = dyn_cast<PointerType>(Ty);
3494     if (!PTy)
3495       return error("Invalid type for value");
3496     std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
3497     AddrSpace = PTy->getAddressSpace();
3498   } else {
3499     AddrSpace = Record[OpNum++];
3500   }
3501 
3502   auto Val = Record[OpNum++];
3503   auto Linkage = Record[OpNum++];
3504   GlobalIndirectSymbol *NewGA;
3505   if (BitCode == bitc::MODULE_CODE_ALIAS ||
3506       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3507     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3508                                 TheModule);
3509   else
3510     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3511                                 nullptr, TheModule);
3512 
3513   assert(NewGA->getValueType() == flattenPointerTypes(FullTy) &&
3514          "Incorrect fully structured type provided for GlobalIndirectSymbol");
3515   // Local linkage must have default visibility.
3516   // auto-upgrade `hidden` and `protected` for old bitcode.
3517   if (OpNum != Record.size()) {
3518     auto VisInd = OpNum++;
3519     if (!NewGA->hasLocalLinkage())
3520       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3521   }
3522   if (BitCode == bitc::MODULE_CODE_ALIAS ||
3523       BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
3524     if (OpNum != Record.size())
3525       NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3526     else
3527       upgradeDLLImportExportLinkage(NewGA, Linkage);
3528     if (OpNum != Record.size())
3529       NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3530     if (OpNum != Record.size())
3531       NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3532   }
3533   if (OpNum != Record.size())
3534     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3535   inferDSOLocal(NewGA);
3536 
3537   // Check whether we have enough values to read a partition name.
3538   if (OpNum + 1 < Record.size()) {
3539     NewGA->setPartition(
3540         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
3541     OpNum += 2;
3542   }
3543 
3544   FullTy = PointerType::get(FullTy, AddrSpace);
3545   assert(NewGA->getType() == flattenPointerTypes(FullTy) &&
3546          "Incorrect fully structured type provided for GlobalIndirectSymbol");
3547   ValueList.push_back(NewGA, FullTy);
3548   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3549   return Error::success();
3550 }
3551 
3552 Error BitcodeReader::parseModule(uint64_t ResumeBit,
3553                                  bool ShouldLazyLoadMetadata,
3554                                  DataLayoutCallbackTy DataLayoutCallback) {
3555   if (ResumeBit) {
3556     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
3557       return JumpFailed;
3558   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3559     return Err;
3560 
3561   SmallVector<uint64_t, 64> Record;
3562 
3563   // Parts of bitcode parsing depend on the datalayout.  Make sure we
3564   // finalize the datalayout before we run any of that code.
3565   bool ResolvedDataLayout = false;
3566   auto ResolveDataLayout = [&] {
3567     if (ResolvedDataLayout)
3568       return;
3569 
3570     // datalayout and triple can't be parsed after this point.
3571     ResolvedDataLayout = true;
3572 
3573     // Upgrade data layout string.
3574     std::string DL = llvm::UpgradeDataLayoutString(
3575         TheModule->getDataLayoutStr(), TheModule->getTargetTriple());
3576     TheModule->setDataLayout(DL);
3577 
3578     if (auto LayoutOverride =
3579             DataLayoutCallback(TheModule->getTargetTriple()))
3580       TheModule->setDataLayout(*LayoutOverride);
3581   };
3582 
3583   // Read all the records for this module.
3584   while (true) {
3585     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3586     if (!MaybeEntry)
3587       return MaybeEntry.takeError();
3588     llvm::BitstreamEntry Entry = MaybeEntry.get();
3589 
3590     switch (Entry.Kind) {
3591     case BitstreamEntry::Error:
3592       return error("Malformed block");
3593     case BitstreamEntry::EndBlock:
3594       ResolveDataLayout();
3595       return globalCleanup();
3596 
3597     case BitstreamEntry::SubBlock:
3598       switch (Entry.ID) {
3599       default:  // Skip unknown content.
3600         if (Error Err = Stream.SkipBlock())
3601           return Err;
3602         break;
3603       case bitc::BLOCKINFO_BLOCK_ID:
3604         if (readBlockInfo())
3605           return error("Malformed block");
3606         break;
3607       case bitc::PARAMATTR_BLOCK_ID:
3608         if (Error Err = parseAttributeBlock())
3609           return Err;
3610         break;
3611       case bitc::PARAMATTR_GROUP_BLOCK_ID:
3612         if (Error Err = parseAttributeGroupBlock())
3613           return Err;
3614         break;
3615       case bitc::TYPE_BLOCK_ID_NEW:
3616         if (Error Err = parseTypeTable())
3617           return Err;
3618         break;
3619       case bitc::VALUE_SYMTAB_BLOCK_ID:
3620         if (!SeenValueSymbolTable) {
3621           // Either this is an old form VST without function index and an
3622           // associated VST forward declaration record (which would have caused
3623           // the VST to be jumped to and parsed before it was encountered
3624           // normally in the stream), or there were no function blocks to
3625           // trigger an earlier parsing of the VST.
3626           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3627           if (Error Err = parseValueSymbolTable())
3628             return Err;
3629           SeenValueSymbolTable = true;
3630         } else {
3631           // We must have had a VST forward declaration record, which caused
3632           // the parser to jump to and parse the VST earlier.
3633           assert(VSTOffset > 0);
3634           if (Error Err = Stream.SkipBlock())
3635             return Err;
3636         }
3637         break;
3638       case bitc::CONSTANTS_BLOCK_ID:
3639         if (Error Err = parseConstants())
3640           return Err;
3641         if (Error Err = resolveGlobalAndIndirectSymbolInits())
3642           return Err;
3643         break;
3644       case bitc::METADATA_BLOCK_ID:
3645         if (ShouldLazyLoadMetadata) {
3646           if (Error Err = rememberAndSkipMetadata())
3647             return Err;
3648           break;
3649         }
3650         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3651         if (Error Err = MDLoader->parseModuleMetadata())
3652           return Err;
3653         break;
3654       case bitc::METADATA_KIND_BLOCK_ID:
3655         if (Error Err = MDLoader->parseMetadataKinds())
3656           return Err;
3657         break;
3658       case bitc::FUNCTION_BLOCK_ID:
3659         ResolveDataLayout();
3660 
3661         // If this is the first function body we've seen, reverse the
3662         // FunctionsWithBodies list.
3663         if (!SeenFirstFunctionBody) {
3664           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3665           if (Error Err = globalCleanup())
3666             return Err;
3667           SeenFirstFunctionBody = true;
3668         }
3669 
3670         if (VSTOffset > 0) {
3671           // If we have a VST forward declaration record, make sure we
3672           // parse the VST now if we haven't already. It is needed to
3673           // set up the DeferredFunctionInfo vector for lazy reading.
3674           if (!SeenValueSymbolTable) {
3675             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3676               return Err;
3677             SeenValueSymbolTable = true;
3678             // Fall through so that we record the NextUnreadBit below.
3679             // This is necessary in case we have an anonymous function that
3680             // is later materialized. Since it will not have a VST entry we
3681             // need to fall back to the lazy parse to find its offset.
3682           } else {
3683             // If we have a VST forward declaration record, but have already
3684             // parsed the VST (just above, when the first function body was
3685             // encountered here), then we are resuming the parse after
3686             // materializing functions. The ResumeBit points to the
3687             // start of the last function block recorded in the
3688             // DeferredFunctionInfo map. Skip it.
3689             if (Error Err = Stream.SkipBlock())
3690               return Err;
3691             continue;
3692           }
3693         }
3694 
3695         // Support older bitcode files that did not have the function
3696         // index in the VST, nor a VST forward declaration record, as
3697         // well as anonymous functions that do not have VST entries.
3698         // Build the DeferredFunctionInfo vector on the fly.
3699         if (Error Err = rememberAndSkipFunctionBody())
3700           return Err;
3701 
3702         // Suspend parsing when we reach the function bodies. Subsequent
3703         // materialization calls will resume it when necessary. If the bitcode
3704         // file is old, the symbol table will be at the end instead and will not
3705         // have been seen yet. In this case, just finish the parse now.
3706         if (SeenValueSymbolTable) {
3707           NextUnreadBit = Stream.GetCurrentBitNo();
3708           // After the VST has been parsed, we need to make sure intrinsic name
3709           // are auto-upgraded.
3710           return globalCleanup();
3711         }
3712         break;
3713       case bitc::USELIST_BLOCK_ID:
3714         if (Error Err = parseUseLists())
3715           return Err;
3716         break;
3717       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3718         if (Error Err = parseOperandBundleTags())
3719           return Err;
3720         break;
3721       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3722         if (Error Err = parseSyncScopeNames())
3723           return Err;
3724         break;
3725       }
3726       continue;
3727 
3728     case BitstreamEntry::Record:
3729       // The interesting case.
3730       break;
3731     }
3732 
3733     // Read a record.
3734     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3735     if (!MaybeBitCode)
3736       return MaybeBitCode.takeError();
3737     switch (unsigned BitCode = MaybeBitCode.get()) {
3738     default: break;  // Default behavior, ignore unknown content.
3739     case bitc::MODULE_CODE_VERSION: {
3740       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3741       if (!VersionOrErr)
3742         return VersionOrErr.takeError();
3743       UseRelativeIDs = *VersionOrErr >= 1;
3744       break;
3745     }
3746     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3747       if (ResolvedDataLayout)
3748         return error("target triple too late in module");
3749       std::string S;
3750       if (convertToString(Record, 0, S))
3751         return error("Invalid record");
3752       TheModule->setTargetTriple(S);
3753       break;
3754     }
3755     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3756       if (ResolvedDataLayout)
3757         return error("datalayout too late in module");
3758       std::string S;
3759       if (convertToString(Record, 0, S))
3760         return error("Invalid record");
3761       TheModule->setDataLayout(S);
3762       break;
3763     }
3764     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3765       std::string S;
3766       if (convertToString(Record, 0, S))
3767         return error("Invalid record");
3768       TheModule->setModuleInlineAsm(S);
3769       break;
3770     }
3771     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3772       // Deprecated, but still needed to read old bitcode files.
3773       std::string S;
3774       if (convertToString(Record, 0, S))
3775         return error("Invalid record");
3776       // Ignore value.
3777       break;
3778     }
3779     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3780       std::string S;
3781       if (convertToString(Record, 0, S))
3782         return error("Invalid record");
3783       SectionTable.push_back(S);
3784       break;
3785     }
3786     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3787       std::string S;
3788       if (convertToString(Record, 0, S))
3789         return error("Invalid record");
3790       GCTable.push_back(S);
3791       break;
3792     }
3793     case bitc::MODULE_CODE_COMDAT:
3794       if (Error Err = parseComdatRecord(Record))
3795         return Err;
3796       break;
3797     case bitc::MODULE_CODE_GLOBALVAR:
3798       if (Error Err = parseGlobalVarRecord(Record))
3799         return Err;
3800       break;
3801     case bitc::MODULE_CODE_FUNCTION:
3802       ResolveDataLayout();
3803       if (Error Err = parseFunctionRecord(Record))
3804         return Err;
3805       break;
3806     case bitc::MODULE_CODE_IFUNC:
3807     case bitc::MODULE_CODE_ALIAS:
3808     case bitc::MODULE_CODE_ALIAS_OLD:
3809       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
3810         return Err;
3811       break;
3812     /// MODULE_CODE_VSTOFFSET: [offset]
3813     case bitc::MODULE_CODE_VSTOFFSET:
3814       if (Record.empty())
3815         return error("Invalid record");
3816       // Note that we subtract 1 here because the offset is relative to one word
3817       // before the start of the identification or module block, which was
3818       // historically always the start of the regular bitcode header.
3819       VSTOffset = Record[0] - 1;
3820       break;
3821     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3822     case bitc::MODULE_CODE_SOURCE_FILENAME:
3823       SmallString<128> ValueName;
3824       if (convertToString(Record, 0, ValueName))
3825         return error("Invalid record");
3826       TheModule->setSourceFileName(ValueName);
3827       break;
3828     }
3829     Record.clear();
3830   }
3831 }
3832 
3833 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3834                                       bool IsImporting,
3835                                       DataLayoutCallbackTy DataLayoutCallback) {
3836   TheModule = M;
3837   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3838                             [&](unsigned ID) { return getTypeByID(ID); });
3839   return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback);
3840 }
3841 
3842 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3843   if (!isa<PointerType>(PtrType))
3844     return error("Load/Store operand is not a pointer type");
3845   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3846 
3847   if (ValType && ValType != ElemType)
3848     return error("Explicit load/store type does not match pointee "
3849                  "type of pointer operand");
3850   if (!PointerType::isLoadableOrStorableType(ElemType))
3851     return error("Cannot load/store from pointer");
3852   return Error::success();
3853 }
3854 
3855 void BitcodeReader::propagateByValSRetTypes(CallBase *CB,
3856                                             ArrayRef<Type *> ArgsFullTys) {
3857   for (unsigned i = 0; i != CB->arg_size(); ++i) {
3858     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3859                                      Attribute::InAlloca}) {
3860       if (!CB->paramHasAttr(i, Kind))
3861         continue;
3862 
3863       CB->removeParamAttr(i, Kind);
3864 
3865       Type *PtrEltTy = getPointerElementFlatType(ArgsFullTys[i]);
3866       Attribute NewAttr;
3867       switch (Kind) {
3868       case Attribute::ByVal:
3869         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3870         break;
3871       case Attribute::StructRet:
3872         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3873         break;
3874       case Attribute::InAlloca:
3875         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3876         break;
3877       default:
3878         llvm_unreachable("not an upgraded type attribute");
3879       }
3880 
3881       CB->addParamAttr(i, NewAttr);
3882     }
3883   }
3884 }
3885 
3886 /// Lazily parse the specified function body block.
3887 Error BitcodeReader::parseFunctionBody(Function *F) {
3888   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3889     return Err;
3890 
3891   // Unexpected unresolved metadata when parsing function.
3892   if (MDLoader->hasFwdRefs())
3893     return error("Invalid function metadata: incoming forward references");
3894 
3895   InstructionList.clear();
3896   unsigned ModuleValueListSize = ValueList.size();
3897   unsigned ModuleMDLoaderSize = MDLoader->size();
3898 
3899   // Add all the function arguments to the value table.
3900   unsigned ArgNo = 0;
3901   FunctionType *FullFTy = FunctionTypes[F];
3902   for (Argument &I : F->args()) {
3903     assert(I.getType() == flattenPointerTypes(FullFTy->getParamType(ArgNo)) &&
3904            "Incorrect fully specified type for Function Argument");
3905     ValueList.push_back(&I, FullFTy->getParamType(ArgNo++));
3906   }
3907   unsigned NextValueNo = ValueList.size();
3908   BasicBlock *CurBB = nullptr;
3909   unsigned CurBBNo = 0;
3910 
3911   DebugLoc LastLoc;
3912   auto getLastInstruction = [&]() -> Instruction * {
3913     if (CurBB && !CurBB->empty())
3914       return &CurBB->back();
3915     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3916              !FunctionBBs[CurBBNo - 1]->empty())
3917       return &FunctionBBs[CurBBNo - 1]->back();
3918     return nullptr;
3919   };
3920 
3921   std::vector<OperandBundleDef> OperandBundles;
3922 
3923   // Read all the records.
3924   SmallVector<uint64_t, 64> Record;
3925 
3926   while (true) {
3927     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3928     if (!MaybeEntry)
3929       return MaybeEntry.takeError();
3930     llvm::BitstreamEntry Entry = MaybeEntry.get();
3931 
3932     switch (Entry.Kind) {
3933     case BitstreamEntry::Error:
3934       return error("Malformed block");
3935     case BitstreamEntry::EndBlock:
3936       goto OutOfRecordLoop;
3937 
3938     case BitstreamEntry::SubBlock:
3939       switch (Entry.ID) {
3940       default:  // Skip unknown content.
3941         if (Error Err = Stream.SkipBlock())
3942           return Err;
3943         break;
3944       case bitc::CONSTANTS_BLOCK_ID:
3945         if (Error Err = parseConstants())
3946           return Err;
3947         NextValueNo = ValueList.size();
3948         break;
3949       case bitc::VALUE_SYMTAB_BLOCK_ID:
3950         if (Error Err = parseValueSymbolTable())
3951           return Err;
3952         break;
3953       case bitc::METADATA_ATTACHMENT_ID:
3954         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3955           return Err;
3956         break;
3957       case bitc::METADATA_BLOCK_ID:
3958         assert(DeferredMetadataInfo.empty() &&
3959                "Must read all module-level metadata before function-level");
3960         if (Error Err = MDLoader->parseFunctionMetadata())
3961           return Err;
3962         break;
3963       case bitc::USELIST_BLOCK_ID:
3964         if (Error Err = parseUseLists())
3965           return Err;
3966         break;
3967       }
3968       continue;
3969 
3970     case BitstreamEntry::Record:
3971       // The interesting case.
3972       break;
3973     }
3974 
3975     // Read a record.
3976     Record.clear();
3977     Instruction *I = nullptr;
3978     Type *FullTy = nullptr;
3979     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3980     if (!MaybeBitCode)
3981       return MaybeBitCode.takeError();
3982     switch (unsigned BitCode = MaybeBitCode.get()) {
3983     default: // Default behavior: reject
3984       return error("Invalid value");
3985     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
3986       if (Record.empty() || Record[0] == 0)
3987         return error("Invalid record");
3988       // Create all the basic blocks for the function.
3989       FunctionBBs.resize(Record[0]);
3990 
3991       // See if anything took the address of blocks in this function.
3992       auto BBFRI = BasicBlockFwdRefs.find(F);
3993       if (BBFRI == BasicBlockFwdRefs.end()) {
3994         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3995           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3996       } else {
3997         auto &BBRefs = BBFRI->second;
3998         // Check for invalid basic block references.
3999         if (BBRefs.size() > FunctionBBs.size())
4000           return error("Invalid ID");
4001         assert(!BBRefs.empty() && "Unexpected empty array");
4002         assert(!BBRefs.front() && "Invalid reference to entry block");
4003         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4004              ++I)
4005           if (I < RE && BBRefs[I]) {
4006             BBRefs[I]->insertInto(F);
4007             FunctionBBs[I] = BBRefs[I];
4008           } else {
4009             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4010           }
4011 
4012         // Erase from the table.
4013         BasicBlockFwdRefs.erase(BBFRI);
4014       }
4015 
4016       CurBB = FunctionBBs[0];
4017       continue;
4018     }
4019 
4020     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4021       // This record indicates that the last instruction is at the same
4022       // location as the previous instruction with a location.
4023       I = getLastInstruction();
4024 
4025       if (!I)
4026         return error("Invalid record");
4027       I->setDebugLoc(LastLoc);
4028       I = nullptr;
4029       continue;
4030 
4031     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
4032       I = getLastInstruction();
4033       if (!I || Record.size() < 4)
4034         return error("Invalid record");
4035 
4036       unsigned Line = Record[0], Col = Record[1];
4037       unsigned ScopeID = Record[2], IAID = Record[3];
4038       bool isImplicitCode = Record.size() == 5 && Record[4];
4039 
4040       MDNode *Scope = nullptr, *IA = nullptr;
4041       if (ScopeID) {
4042         Scope = dyn_cast_or_null<MDNode>(
4043             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
4044         if (!Scope)
4045           return error("Invalid record");
4046       }
4047       if (IAID) {
4048         IA = dyn_cast_or_null<MDNode>(
4049             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
4050         if (!IA)
4051           return error("Invalid record");
4052       }
4053       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4054                                 isImplicitCode);
4055       I->setDebugLoc(LastLoc);
4056       I = nullptr;
4057       continue;
4058     }
4059     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
4060       unsigned OpNum = 0;
4061       Value *LHS;
4062       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4063           OpNum+1 > Record.size())
4064         return error("Invalid record");
4065 
4066       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
4067       if (Opc == -1)
4068         return error("Invalid record");
4069       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
4070       InstructionList.push_back(I);
4071       if (OpNum < Record.size()) {
4072         if (isa<FPMathOperator>(I)) {
4073           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4074           if (FMF.any())
4075             I->setFastMathFlags(FMF);
4076         }
4077       }
4078       break;
4079     }
4080     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4081       unsigned OpNum = 0;
4082       Value *LHS, *RHS;
4083       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4084           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4085           OpNum+1 > Record.size())
4086         return error("Invalid record");
4087 
4088       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4089       if (Opc == -1)
4090         return error("Invalid record");
4091       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4092       InstructionList.push_back(I);
4093       if (OpNum < Record.size()) {
4094         if (Opc == Instruction::Add ||
4095             Opc == Instruction::Sub ||
4096             Opc == Instruction::Mul ||
4097             Opc == Instruction::Shl) {
4098           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4099             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4100           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4101             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4102         } else if (Opc == Instruction::SDiv ||
4103                    Opc == Instruction::UDiv ||
4104                    Opc == Instruction::LShr ||
4105                    Opc == Instruction::AShr) {
4106           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4107             cast<BinaryOperator>(I)->setIsExact(true);
4108         } else if (isa<FPMathOperator>(I)) {
4109           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4110           if (FMF.any())
4111             I->setFastMathFlags(FMF);
4112         }
4113 
4114       }
4115       break;
4116     }
4117     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4118       unsigned OpNum = 0;
4119       Value *Op;
4120       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4121           OpNum+2 != Record.size())
4122         return error("Invalid record");
4123 
4124       FullTy = getFullyStructuredTypeByID(Record[OpNum]);
4125       Type *ResTy = flattenPointerTypes(FullTy);
4126       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4127       if (Opc == -1 || !ResTy)
4128         return error("Invalid record");
4129       Instruction *Temp = nullptr;
4130       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4131         if (Temp) {
4132           InstructionList.push_back(Temp);
4133           assert(CurBB && "No current BB?");
4134           CurBB->getInstList().push_back(Temp);
4135         }
4136       } else {
4137         auto CastOp = (Instruction::CastOps)Opc;
4138         if (!CastInst::castIsValid(CastOp, Op, ResTy))
4139           return error("Invalid cast");
4140         I = CastInst::Create(CastOp, Op, ResTy);
4141       }
4142       InstructionList.push_back(I);
4143       break;
4144     }
4145     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4146     case bitc::FUNC_CODE_INST_GEP_OLD:
4147     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4148       unsigned OpNum = 0;
4149 
4150       Type *Ty;
4151       bool InBounds;
4152 
4153       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4154         InBounds = Record[OpNum++];
4155         FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
4156         Ty = flattenPointerTypes(FullTy);
4157       } else {
4158         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4159         Ty = nullptr;
4160       }
4161 
4162       Value *BasePtr;
4163       Type *FullBaseTy = nullptr;
4164       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, &FullBaseTy))
4165         return error("Invalid record");
4166 
4167       if (!Ty) {
4168         std::tie(FullTy, Ty) =
4169             getPointerElementTypes(FullBaseTy->getScalarType());
4170       } else if (Ty != getPointerElementFlatType(FullBaseTy->getScalarType()))
4171         return error(
4172             "Explicit gep type does not match pointee type of pointer operand");
4173 
4174       SmallVector<Value*, 16> GEPIdx;
4175       while (OpNum != Record.size()) {
4176         Value *Op;
4177         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4178           return error("Invalid record");
4179         GEPIdx.push_back(Op);
4180       }
4181 
4182       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4183       FullTy = GetElementPtrInst::getGEPReturnType(FullTy, I, GEPIdx);
4184 
4185       InstructionList.push_back(I);
4186       if (InBounds)
4187         cast<GetElementPtrInst>(I)->setIsInBounds(true);
4188       break;
4189     }
4190 
4191     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4192                                        // EXTRACTVAL: [opty, opval, n x indices]
4193       unsigned OpNum = 0;
4194       Value *Agg;
4195       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy))
4196         return error("Invalid record");
4197 
4198       unsigned RecSize = Record.size();
4199       if (OpNum == RecSize)
4200         return error("EXTRACTVAL: Invalid instruction with 0 indices");
4201 
4202       SmallVector<unsigned, 4> EXTRACTVALIdx;
4203       for (; OpNum != RecSize; ++OpNum) {
4204         bool IsArray = FullTy->isArrayTy();
4205         bool IsStruct = FullTy->isStructTy();
4206         uint64_t Index = Record[OpNum];
4207 
4208         if (!IsStruct && !IsArray)
4209           return error("EXTRACTVAL: Invalid type");
4210         if ((unsigned)Index != Index)
4211           return error("Invalid value");
4212         if (IsStruct && Index >= FullTy->getStructNumElements())
4213           return error("EXTRACTVAL: Invalid struct index");
4214         if (IsArray && Index >= FullTy->getArrayNumElements())
4215           return error("EXTRACTVAL: Invalid array index");
4216         EXTRACTVALIdx.push_back((unsigned)Index);
4217 
4218         if (IsStruct)
4219           FullTy = FullTy->getStructElementType(Index);
4220         else
4221           FullTy = FullTy->getArrayElementType();
4222       }
4223 
4224       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4225       InstructionList.push_back(I);
4226       break;
4227     }
4228 
4229     case bitc::FUNC_CODE_INST_INSERTVAL: {
4230                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
4231       unsigned OpNum = 0;
4232       Value *Agg;
4233       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, &FullTy))
4234         return error("Invalid record");
4235       Value *Val;
4236       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4237         return error("Invalid record");
4238 
4239       unsigned RecSize = Record.size();
4240       if (OpNum == RecSize)
4241         return error("INSERTVAL: Invalid instruction with 0 indices");
4242 
4243       SmallVector<unsigned, 4> INSERTVALIdx;
4244       Type *CurTy = Agg->getType();
4245       for (; OpNum != RecSize; ++OpNum) {
4246         bool IsArray = CurTy->isArrayTy();
4247         bool IsStruct = CurTy->isStructTy();
4248         uint64_t Index = Record[OpNum];
4249 
4250         if (!IsStruct && !IsArray)
4251           return error("INSERTVAL: Invalid type");
4252         if ((unsigned)Index != Index)
4253           return error("Invalid value");
4254         if (IsStruct && Index >= CurTy->getStructNumElements())
4255           return error("INSERTVAL: Invalid struct index");
4256         if (IsArray && Index >= CurTy->getArrayNumElements())
4257           return error("INSERTVAL: Invalid array index");
4258 
4259         INSERTVALIdx.push_back((unsigned)Index);
4260         if (IsStruct)
4261           CurTy = CurTy->getStructElementType(Index);
4262         else
4263           CurTy = CurTy->getArrayElementType();
4264       }
4265 
4266       if (CurTy != Val->getType())
4267         return error("Inserted value type doesn't match aggregate type");
4268 
4269       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4270       InstructionList.push_back(I);
4271       break;
4272     }
4273 
4274     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4275       // obsolete form of select
4276       // handles select i1 ... in old bitcode
4277       unsigned OpNum = 0;
4278       Value *TrueVal, *FalseVal, *Cond;
4279       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) ||
4280           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4281           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4282         return error("Invalid record");
4283 
4284       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4285       InstructionList.push_back(I);
4286       break;
4287     }
4288 
4289     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4290       // new form of select
4291       // handles select i1 or select [N x i1]
4292       unsigned OpNum = 0;
4293       Value *TrueVal, *FalseVal, *Cond;
4294       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, &FullTy) ||
4295           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4296           getValueTypePair(Record, OpNum, NextValueNo, Cond))
4297         return error("Invalid record");
4298 
4299       // select condition can be either i1 or [N x i1]
4300       if (VectorType* vector_type =
4301           dyn_cast<VectorType>(Cond->getType())) {
4302         // expect <n x i1>
4303         if (vector_type->getElementType() != Type::getInt1Ty(Context))
4304           return error("Invalid type for value");
4305       } else {
4306         // expect i1
4307         if (Cond->getType() != Type::getInt1Ty(Context))
4308           return error("Invalid type for value");
4309       }
4310 
4311       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4312       InstructionList.push_back(I);
4313       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
4314         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4315         if (FMF.any())
4316           I->setFastMathFlags(FMF);
4317       }
4318       break;
4319     }
4320 
4321     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4322       unsigned OpNum = 0;
4323       Value *Vec, *Idx;
4324       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy) ||
4325           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4326         return error("Invalid record");
4327       if (!Vec->getType()->isVectorTy())
4328         return error("Invalid type for value");
4329       I = ExtractElementInst::Create(Vec, Idx);
4330       FullTy = cast<VectorType>(FullTy)->getElementType();
4331       InstructionList.push_back(I);
4332       break;
4333     }
4334 
4335     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4336       unsigned OpNum = 0;
4337       Value *Vec, *Elt, *Idx;
4338       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, &FullTy))
4339         return error("Invalid record");
4340       if (!Vec->getType()->isVectorTy())
4341         return error("Invalid type for value");
4342       if (popValue(Record, OpNum, NextValueNo,
4343                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4344           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4345         return error("Invalid record");
4346       I = InsertElementInst::Create(Vec, Elt, Idx);
4347       InstructionList.push_back(I);
4348       break;
4349     }
4350 
4351     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4352       unsigned OpNum = 0;
4353       Value *Vec1, *Vec2, *Mask;
4354       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, &FullTy) ||
4355           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4356         return error("Invalid record");
4357 
4358       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4359         return error("Invalid record");
4360       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4361         return error("Invalid type for value");
4362 
4363       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4364       FullTy =
4365           VectorType::get(cast<VectorType>(FullTy)->getElementType(),
4366                           cast<VectorType>(Mask->getType())->getElementCount());
4367       InstructionList.push_back(I);
4368       break;
4369     }
4370 
4371     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
4372       // Old form of ICmp/FCmp returning bool
4373       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4374       // both legal on vectors but had different behaviour.
4375     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4376       // FCmp/ICmp returning bool or vector of bool
4377 
4378       unsigned OpNum = 0;
4379       Value *LHS, *RHS;
4380       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4381           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4382         return error("Invalid record");
4383 
4384       if (OpNum >= Record.size())
4385         return error(
4386             "Invalid record: operand number exceeded available operands");
4387 
4388       unsigned PredVal = Record[OpNum];
4389       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4390       FastMathFlags FMF;
4391       if (IsFP && Record.size() > OpNum+1)
4392         FMF = getDecodedFastMathFlags(Record[++OpNum]);
4393 
4394       if (OpNum+1 != Record.size())
4395         return error("Invalid record");
4396 
4397       if (LHS->getType()->isFPOrFPVectorTy())
4398         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4399       else
4400         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4401 
4402       if (FMF.any())
4403         I->setFastMathFlags(FMF);
4404       InstructionList.push_back(I);
4405       break;
4406     }
4407 
4408     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4409       {
4410         unsigned Size = Record.size();
4411         if (Size == 0) {
4412           I = ReturnInst::Create(Context);
4413           InstructionList.push_back(I);
4414           break;
4415         }
4416 
4417         unsigned OpNum = 0;
4418         Value *Op = nullptr;
4419         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4420           return error("Invalid record");
4421         if (OpNum != Record.size())
4422           return error("Invalid record");
4423 
4424         I = ReturnInst::Create(Context, Op);
4425         InstructionList.push_back(I);
4426         break;
4427       }
4428     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4429       if (Record.size() != 1 && Record.size() != 3)
4430         return error("Invalid record");
4431       BasicBlock *TrueDest = getBasicBlock(Record[0]);
4432       if (!TrueDest)
4433         return error("Invalid record");
4434 
4435       if (Record.size() == 1) {
4436         I = BranchInst::Create(TrueDest);
4437         InstructionList.push_back(I);
4438       }
4439       else {
4440         BasicBlock *FalseDest = getBasicBlock(Record[1]);
4441         Value *Cond = getValue(Record, 2, NextValueNo,
4442                                Type::getInt1Ty(Context));
4443         if (!FalseDest || !Cond)
4444           return error("Invalid record");
4445         I = BranchInst::Create(TrueDest, FalseDest, Cond);
4446         InstructionList.push_back(I);
4447       }
4448       break;
4449     }
4450     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4451       if (Record.size() != 1 && Record.size() != 2)
4452         return error("Invalid record");
4453       unsigned Idx = 0;
4454       Value *CleanupPad =
4455           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4456       if (!CleanupPad)
4457         return error("Invalid record");
4458       BasicBlock *UnwindDest = nullptr;
4459       if (Record.size() == 2) {
4460         UnwindDest = getBasicBlock(Record[Idx++]);
4461         if (!UnwindDest)
4462           return error("Invalid record");
4463       }
4464 
4465       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4466       InstructionList.push_back(I);
4467       break;
4468     }
4469     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4470       if (Record.size() != 2)
4471         return error("Invalid record");
4472       unsigned Idx = 0;
4473       Value *CatchPad =
4474           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4475       if (!CatchPad)
4476         return error("Invalid record");
4477       BasicBlock *BB = getBasicBlock(Record[Idx++]);
4478       if (!BB)
4479         return error("Invalid record");
4480 
4481       I = CatchReturnInst::Create(CatchPad, BB);
4482       InstructionList.push_back(I);
4483       break;
4484     }
4485     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4486       // We must have, at minimum, the outer scope and the number of arguments.
4487       if (Record.size() < 2)
4488         return error("Invalid record");
4489 
4490       unsigned Idx = 0;
4491 
4492       Value *ParentPad =
4493           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4494 
4495       unsigned NumHandlers = Record[Idx++];
4496 
4497       SmallVector<BasicBlock *, 2> Handlers;
4498       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4499         BasicBlock *BB = getBasicBlock(Record[Idx++]);
4500         if (!BB)
4501           return error("Invalid record");
4502         Handlers.push_back(BB);
4503       }
4504 
4505       BasicBlock *UnwindDest = nullptr;
4506       if (Idx + 1 == Record.size()) {
4507         UnwindDest = getBasicBlock(Record[Idx++]);
4508         if (!UnwindDest)
4509           return error("Invalid record");
4510       }
4511 
4512       if (Record.size() != Idx)
4513         return error("Invalid record");
4514 
4515       auto *CatchSwitch =
4516           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4517       for (BasicBlock *Handler : Handlers)
4518         CatchSwitch->addHandler(Handler);
4519       I = CatchSwitch;
4520       InstructionList.push_back(I);
4521       break;
4522     }
4523     case bitc::FUNC_CODE_INST_CATCHPAD:
4524     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4525       // We must have, at minimum, the outer scope and the number of arguments.
4526       if (Record.size() < 2)
4527         return error("Invalid record");
4528 
4529       unsigned Idx = 0;
4530 
4531       Value *ParentPad =
4532           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4533 
4534       unsigned NumArgOperands = Record[Idx++];
4535 
4536       SmallVector<Value *, 2> Args;
4537       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4538         Value *Val;
4539         if (getValueTypePair(Record, Idx, NextValueNo, Val))
4540           return error("Invalid record");
4541         Args.push_back(Val);
4542       }
4543 
4544       if (Record.size() != Idx)
4545         return error("Invalid record");
4546 
4547       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4548         I = CleanupPadInst::Create(ParentPad, Args);
4549       else
4550         I = CatchPadInst::Create(ParentPad, Args);
4551       InstructionList.push_back(I);
4552       break;
4553     }
4554     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4555       // Check magic
4556       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4557         // "New" SwitchInst format with case ranges. The changes to write this
4558         // format were reverted but we still recognize bitcode that uses it.
4559         // Hopefully someday we will have support for case ranges and can use
4560         // this format again.
4561 
4562         Type *OpTy = getTypeByID(Record[1]);
4563         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4564 
4565         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4566         BasicBlock *Default = getBasicBlock(Record[3]);
4567         if (!OpTy || !Cond || !Default)
4568           return error("Invalid record");
4569 
4570         unsigned NumCases = Record[4];
4571 
4572         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4573         InstructionList.push_back(SI);
4574 
4575         unsigned CurIdx = 5;
4576         for (unsigned i = 0; i != NumCases; ++i) {
4577           SmallVector<ConstantInt*, 1> CaseVals;
4578           unsigned NumItems = Record[CurIdx++];
4579           for (unsigned ci = 0; ci != NumItems; ++ci) {
4580             bool isSingleNumber = Record[CurIdx++];
4581 
4582             APInt Low;
4583             unsigned ActiveWords = 1;
4584             if (ValueBitWidth > 64)
4585               ActiveWords = Record[CurIdx++];
4586             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4587                                 ValueBitWidth);
4588             CurIdx += ActiveWords;
4589 
4590             if (!isSingleNumber) {
4591               ActiveWords = 1;
4592               if (ValueBitWidth > 64)
4593                 ActiveWords = Record[CurIdx++];
4594               APInt High = readWideAPInt(
4595                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4596               CurIdx += ActiveWords;
4597 
4598               // FIXME: It is not clear whether values in the range should be
4599               // compared as signed or unsigned values. The partially
4600               // implemented changes that used this format in the past used
4601               // unsigned comparisons.
4602               for ( ; Low.ule(High); ++Low)
4603                 CaseVals.push_back(ConstantInt::get(Context, Low));
4604             } else
4605               CaseVals.push_back(ConstantInt::get(Context, Low));
4606           }
4607           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4608           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4609                  cve = CaseVals.end(); cvi != cve; ++cvi)
4610             SI->addCase(*cvi, DestBB);
4611         }
4612         I = SI;
4613         break;
4614       }
4615 
4616       // Old SwitchInst format without case ranges.
4617 
4618       if (Record.size() < 3 || (Record.size() & 1) == 0)
4619         return error("Invalid record");
4620       Type *OpTy = getTypeByID(Record[0]);
4621       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4622       BasicBlock *Default = getBasicBlock(Record[2]);
4623       if (!OpTy || !Cond || !Default)
4624         return error("Invalid record");
4625       unsigned NumCases = (Record.size()-3)/2;
4626       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4627       InstructionList.push_back(SI);
4628       for (unsigned i = 0, e = NumCases; i != e; ++i) {
4629         ConstantInt *CaseVal =
4630           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4631         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4632         if (!CaseVal || !DestBB) {
4633           delete SI;
4634           return error("Invalid record");
4635         }
4636         SI->addCase(CaseVal, DestBB);
4637       }
4638       I = SI;
4639       break;
4640     }
4641     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4642       if (Record.size() < 2)
4643         return error("Invalid record");
4644       Type *OpTy = getTypeByID(Record[0]);
4645       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4646       if (!OpTy || !Address)
4647         return error("Invalid record");
4648       unsigned NumDests = Record.size()-2;
4649       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4650       InstructionList.push_back(IBI);
4651       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4652         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4653           IBI->addDestination(DestBB);
4654         } else {
4655           delete IBI;
4656           return error("Invalid record");
4657         }
4658       }
4659       I = IBI;
4660       break;
4661     }
4662 
4663     case bitc::FUNC_CODE_INST_INVOKE: {
4664       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4665       if (Record.size() < 4)
4666         return error("Invalid record");
4667       unsigned OpNum = 0;
4668       AttributeList PAL = getAttributes(Record[OpNum++]);
4669       unsigned CCInfo = Record[OpNum++];
4670       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4671       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4672 
4673       FunctionType *FTy = nullptr;
4674       FunctionType *FullFTy = nullptr;
4675       if ((CCInfo >> 13) & 1) {
4676         FullFTy =
4677             dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
4678         if (!FullFTy)
4679           return error("Explicit invoke type is not a function type");
4680         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4681       }
4682 
4683       Value *Callee;
4684       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
4685         return error("Invalid record");
4686 
4687       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4688       if (!CalleeTy)
4689         return error("Callee is not a pointer");
4690       if (!FTy) {
4691         FullFTy =
4692             dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
4693         if (!FullFTy)
4694           return error("Callee is not of pointer to function type");
4695         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4696       } else if (getPointerElementFlatType(FullTy) != FTy)
4697         return error("Explicit invoke type does not match pointee type of "
4698                      "callee operand");
4699       if (Record.size() < FTy->getNumParams() + OpNum)
4700         return error("Insufficient operands to call");
4701 
4702       SmallVector<Value*, 16> Ops;
4703       SmallVector<Type *, 16> ArgsFullTys;
4704       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4705         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4706                                FTy->getParamType(i)));
4707         ArgsFullTys.push_back(FullFTy->getParamType(i));
4708         if (!Ops.back())
4709           return error("Invalid record");
4710       }
4711 
4712       if (!FTy->isVarArg()) {
4713         if (Record.size() != OpNum)
4714           return error("Invalid record");
4715       } else {
4716         // Read type/value pairs for varargs params.
4717         while (OpNum != Record.size()) {
4718           Value *Op;
4719           Type *FullTy;
4720           if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy))
4721             return error("Invalid record");
4722           Ops.push_back(Op);
4723           ArgsFullTys.push_back(FullTy);
4724         }
4725       }
4726 
4727       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
4728                              OperandBundles);
4729       FullTy = FullFTy->getReturnType();
4730       OperandBundles.clear();
4731       InstructionList.push_back(I);
4732       cast<InvokeInst>(I)->setCallingConv(
4733           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4734       cast<InvokeInst>(I)->setAttributes(PAL);
4735       propagateByValSRetTypes(cast<CallBase>(I), ArgsFullTys);
4736 
4737       break;
4738     }
4739     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4740       unsigned Idx = 0;
4741       Value *Val = nullptr;
4742       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4743         return error("Invalid record");
4744       I = ResumeInst::Create(Val);
4745       InstructionList.push_back(I);
4746       break;
4747     }
4748     case bitc::FUNC_CODE_INST_CALLBR: {
4749       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
4750       unsigned OpNum = 0;
4751       AttributeList PAL = getAttributes(Record[OpNum++]);
4752       unsigned CCInfo = Record[OpNum++];
4753 
4754       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
4755       unsigned NumIndirectDests = Record[OpNum++];
4756       SmallVector<BasicBlock *, 16> IndirectDests;
4757       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
4758         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
4759 
4760       FunctionType *FTy = nullptr;
4761       FunctionType *FullFTy = nullptr;
4762       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
4763         FullFTy =
4764             dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
4765         if (!FullFTy)
4766           return error("Explicit call type is not a function type");
4767         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4768       }
4769 
4770       Value *Callee;
4771       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
4772         return error("Invalid record");
4773 
4774       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4775       if (!OpTy)
4776         return error("Callee is not a pointer type");
4777       if (!FTy) {
4778         FullFTy =
4779             dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
4780         if (!FullFTy)
4781           return error("Callee is not of pointer to function type");
4782         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
4783       } else if (getPointerElementFlatType(FullTy) != FTy)
4784         return error("Explicit call type does not match pointee type of "
4785                      "callee operand");
4786       if (Record.size() < FTy->getNumParams() + OpNum)
4787         return error("Insufficient operands to call");
4788 
4789       SmallVector<Value*, 16> Args;
4790       // Read the fixed params.
4791       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4792         if (FTy->getParamType(i)->isLabelTy())
4793           Args.push_back(getBasicBlock(Record[OpNum]));
4794         else
4795           Args.push_back(getValue(Record, OpNum, NextValueNo,
4796                                   FTy->getParamType(i)));
4797         if (!Args.back())
4798           return error("Invalid record");
4799       }
4800 
4801       // Read type/value pairs for varargs params.
4802       if (!FTy->isVarArg()) {
4803         if (OpNum != Record.size())
4804           return error("Invalid record");
4805       } else {
4806         while (OpNum != Record.size()) {
4807           Value *Op;
4808           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4809             return error("Invalid record");
4810           Args.push_back(Op);
4811         }
4812       }
4813 
4814       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
4815                              OperandBundles);
4816       FullTy = FullFTy->getReturnType();
4817       OperandBundles.clear();
4818       InstructionList.push_back(I);
4819       cast<CallBrInst>(I)->setCallingConv(
4820           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4821       cast<CallBrInst>(I)->setAttributes(PAL);
4822       break;
4823     }
4824     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4825       I = new UnreachableInst(Context);
4826       InstructionList.push_back(I);
4827       break;
4828     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4829       if (Record.empty())
4830         return error("Invalid record");
4831       // The first record specifies the type.
4832       FullTy = getFullyStructuredTypeByID(Record[0]);
4833       Type *Ty = flattenPointerTypes(FullTy);
4834       if (!Ty)
4835         return error("Invalid record");
4836 
4837       // Phi arguments are pairs of records of [value, basic block].
4838       // There is an optional final record for fast-math-flags if this phi has a
4839       // floating-point type.
4840       size_t NumArgs = (Record.size() - 1) / 2;
4841       PHINode *PN = PHINode::Create(Ty, NumArgs);
4842       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN))
4843         return error("Invalid record");
4844       InstructionList.push_back(PN);
4845 
4846       for (unsigned i = 0; i != NumArgs; i++) {
4847         Value *V;
4848         // With the new function encoding, it is possible that operands have
4849         // negative IDs (for forward references).  Use a signed VBR
4850         // representation to keep the encoding small.
4851         if (UseRelativeIDs)
4852           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty);
4853         else
4854           V = getValue(Record, i * 2 + 1, NextValueNo, Ty);
4855         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
4856         if (!V || !BB)
4857           return error("Invalid record");
4858         PN->addIncoming(V, BB);
4859       }
4860       I = PN;
4861 
4862       // If there are an even number of records, the final record must be FMF.
4863       if (Record.size() % 2 == 0) {
4864         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
4865         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
4866         if (FMF.any())
4867           I->setFastMathFlags(FMF);
4868       }
4869 
4870       break;
4871     }
4872 
4873     case bitc::FUNC_CODE_INST_LANDINGPAD:
4874     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4875       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4876       unsigned Idx = 0;
4877       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4878         if (Record.size() < 3)
4879           return error("Invalid record");
4880       } else {
4881         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4882         if (Record.size() < 4)
4883           return error("Invalid record");
4884       }
4885       FullTy = getFullyStructuredTypeByID(Record[Idx++]);
4886       Type *Ty = flattenPointerTypes(FullTy);
4887       if (!Ty)
4888         return error("Invalid record");
4889       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4890         Value *PersFn = nullptr;
4891         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4892           return error("Invalid record");
4893 
4894         if (!F->hasPersonalityFn())
4895           F->setPersonalityFn(cast<Constant>(PersFn));
4896         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4897           return error("Personality function mismatch");
4898       }
4899 
4900       bool IsCleanup = !!Record[Idx++];
4901       unsigned NumClauses = Record[Idx++];
4902       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4903       LP->setCleanup(IsCleanup);
4904       for (unsigned J = 0; J != NumClauses; ++J) {
4905         LandingPadInst::ClauseType CT =
4906           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4907         Value *Val;
4908 
4909         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4910           delete LP;
4911           return error("Invalid record");
4912         }
4913 
4914         assert((CT != LandingPadInst::Catch ||
4915                 !isa<ArrayType>(Val->getType())) &&
4916                "Catch clause has a invalid type!");
4917         assert((CT != LandingPadInst::Filter ||
4918                 isa<ArrayType>(Val->getType())) &&
4919                "Filter clause has invalid type!");
4920         LP->addClause(cast<Constant>(Val));
4921       }
4922 
4923       I = LP;
4924       InstructionList.push_back(I);
4925       break;
4926     }
4927 
4928     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4929       if (Record.size() != 4)
4930         return error("Invalid record");
4931       using APV = AllocaPackedValues;
4932       const uint64_t Rec = Record[3];
4933       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
4934       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
4935       FullTy = getFullyStructuredTypeByID(Record[0]);
4936       Type *Ty = flattenPointerTypes(FullTy);
4937       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
4938         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4939         if (!PTy)
4940           return error("Old-style alloca with a non-pointer type");
4941         std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
4942       }
4943       Type *OpTy = getTypeByID(Record[1]);
4944       Value *Size = getFnValueByID(Record[2], OpTy);
4945       MaybeAlign Align;
4946       if (Error Err =
4947               parseAlignmentValue(Bitfield::get<APV::Align>(Rec), Align)) {
4948         return Err;
4949       }
4950       if (!Ty || !Size)
4951         return error("Invalid record");
4952 
4953       // FIXME: Make this an optional field.
4954       const DataLayout &DL = TheModule->getDataLayout();
4955       unsigned AS = DL.getAllocaAddrSpace();
4956 
4957       SmallPtrSet<Type *, 4> Visited;
4958       if (!Align && !Ty->isSized(&Visited))
4959         return error("alloca of unsized type");
4960       if (!Align)
4961         Align = DL.getPrefTypeAlign(Ty);
4962 
4963       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
4964       AI->setUsedWithInAlloca(InAlloca);
4965       AI->setSwiftError(SwiftError);
4966       I = AI;
4967       FullTy = PointerType::get(FullTy, AS);
4968       InstructionList.push_back(I);
4969       break;
4970     }
4971     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4972       unsigned OpNum = 0;
4973       Value *Op;
4974       if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) ||
4975           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4976         return error("Invalid record");
4977 
4978       if (!isa<PointerType>(Op->getType()))
4979         return error("Load operand is not a pointer type");
4980 
4981       Type *Ty = nullptr;
4982       if (OpNum + 3 == Record.size()) {
4983         FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
4984         Ty = flattenPointerTypes(FullTy);
4985       } else
4986         std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
4987 
4988       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4989         return Err;
4990 
4991       MaybeAlign Align;
4992       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4993         return Err;
4994       SmallPtrSet<Type *, 4> Visited;
4995       if (!Align && !Ty->isSized(&Visited))
4996         return error("load of unsized type");
4997       if (!Align)
4998         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
4999       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
5000       InstructionList.push_back(I);
5001       break;
5002     }
5003     case bitc::FUNC_CODE_INST_LOADATOMIC: {
5004        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
5005       unsigned OpNum = 0;
5006       Value *Op;
5007       if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy) ||
5008           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
5009         return error("Invalid record");
5010 
5011       if (!isa<PointerType>(Op->getType()))
5012         return error("Load operand is not a pointer type");
5013 
5014       Type *Ty = nullptr;
5015       if (OpNum + 5 == Record.size()) {
5016         FullTy = getFullyStructuredTypeByID(Record[OpNum++]);
5017         Ty = flattenPointerTypes(FullTy);
5018       } else
5019         std::tie(FullTy, Ty) = getPointerElementTypes(FullTy);
5020 
5021       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5022         return Err;
5023 
5024       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5025       if (Ordering == AtomicOrdering::NotAtomic ||
5026           Ordering == AtomicOrdering::Release ||
5027           Ordering == AtomicOrdering::AcquireRelease)
5028         return error("Invalid record");
5029       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5030         return error("Invalid record");
5031       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5032 
5033       MaybeAlign Align;
5034       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5035         return Err;
5036       if (!Align)
5037         return error("Alignment missing from atomic load");
5038       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
5039       InstructionList.push_back(I);
5040       break;
5041     }
5042     case bitc::FUNC_CODE_INST_STORE:
5043     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5044       unsigned OpNum = 0;
5045       Value *Val, *Ptr;
5046       Type *FullTy;
5047       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) ||
5048           (BitCode == bitc::FUNC_CODE_INST_STORE
5049                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5050                : popValue(Record, OpNum, NextValueNo,
5051                           getPointerElementFlatType(FullTy), Val)) ||
5052           OpNum + 2 != Record.size())
5053         return error("Invalid record");
5054 
5055       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5056         return Err;
5057       MaybeAlign Align;
5058       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5059         return Err;
5060       SmallPtrSet<Type *, 4> Visited;
5061       if (!Align && !Val->getType()->isSized(&Visited))
5062         return error("store of unsized type");
5063       if (!Align)
5064         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
5065       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
5066       InstructionList.push_back(I);
5067       break;
5068     }
5069     case bitc::FUNC_CODE_INST_STOREATOMIC:
5070     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5071       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
5072       unsigned OpNum = 0;
5073       Value *Val, *Ptr;
5074       Type *FullTy;
5075       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy) ||
5076           !isa<PointerType>(Ptr->getType()) ||
5077           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
5078                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
5079                : popValue(Record, OpNum, NextValueNo,
5080                           getPointerElementFlatType(FullTy), Val)) ||
5081           OpNum + 4 != Record.size())
5082         return error("Invalid record");
5083 
5084       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5085         return Err;
5086       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5087       if (Ordering == AtomicOrdering::NotAtomic ||
5088           Ordering == AtomicOrdering::Acquire ||
5089           Ordering == AtomicOrdering::AcquireRelease)
5090         return error("Invalid record");
5091       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5092       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5093         return error("Invalid record");
5094 
5095       MaybeAlign Align;
5096       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5097         return Err;
5098       if (!Align)
5099         return error("Alignment missing from atomic store");
5100       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
5101       InstructionList.push_back(I);
5102       break;
5103     }
5104     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
5105       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
5106       // failure_ordering?, weak?]
5107       const size_t NumRecords = Record.size();
5108       unsigned OpNum = 0;
5109       Value *Ptr = nullptr;
5110       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy))
5111         return error("Invalid record");
5112 
5113       if (!isa<PointerType>(Ptr->getType()))
5114         return error("Cmpxchg operand is not a pointer type");
5115 
5116       Value *Cmp = nullptr;
5117       if (popValue(Record, OpNum, NextValueNo,
5118                    getPointerElementFlatType(FullTy), Cmp))
5119         return error("Invalid record");
5120 
5121       FullTy = cast<PointerType>(FullTy)->getElementType();
5122 
5123       Value *New = nullptr;
5124       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5125           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
5126         return error("Invalid record");
5127 
5128       const AtomicOrdering SuccessOrdering =
5129           getDecodedOrdering(Record[OpNum + 1]);
5130       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5131           SuccessOrdering == AtomicOrdering::Unordered)
5132         return error("Invalid record");
5133 
5134       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5135 
5136       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5137         return Err;
5138 
5139       const AtomicOrdering FailureOrdering =
5140           NumRecords < 7
5141               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
5142               : getDecodedOrdering(Record[OpNum + 3]);
5143 
5144       const Align Alignment(
5145           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5146 
5147       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
5148                                 FailureOrdering, SSID);
5149       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5150       FullTy = StructType::get(Context, {FullTy, Type::getInt1Ty(Context)});
5151 
5152       if (NumRecords < 8) {
5153         // Before weak cmpxchgs existed, the instruction simply returned the
5154         // value loaded from memory, so bitcode files from that era will be
5155         // expecting the first component of a modern cmpxchg.
5156         CurBB->getInstList().push_back(I);
5157         I = ExtractValueInst::Create(I, 0);
5158         FullTy = cast<StructType>(FullTy)->getElementType(0);
5159       } else {
5160         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
5161       }
5162 
5163       InstructionList.push_back(I);
5164       break;
5165     }
5166     case bitc::FUNC_CODE_INST_CMPXCHG: {
5167       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
5168       // failure_ordering, weak, align?]
5169       const size_t NumRecords = Record.size();
5170       unsigned OpNum = 0;
5171       Value *Ptr = nullptr;
5172       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy))
5173         return error("Invalid record");
5174 
5175       if (!isa<PointerType>(Ptr->getType()))
5176         return error("Cmpxchg operand is not a pointer type");
5177 
5178       Value *Cmp = nullptr;
5179       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, &FullTy))
5180         return error("Invalid record");
5181 
5182       Value *Val = nullptr;
5183       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), Val))
5184         return error("Invalid record");
5185 
5186       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
5187         return error("Invalid record");
5188 
5189       const bool IsVol = Record[OpNum];
5190 
5191       const AtomicOrdering SuccessOrdering =
5192           getDecodedOrdering(Record[OpNum + 1]);
5193       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5194           SuccessOrdering == AtomicOrdering::Unordered)
5195         return error("Invalid record");
5196 
5197       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5198 
5199       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5200         return Err;
5201 
5202       const AtomicOrdering FailureOrdering =
5203           getDecodedOrdering(Record[OpNum + 3]);
5204 
5205       const bool IsWeak = Record[OpNum + 4];
5206 
5207       MaybeAlign Alignment;
5208 
5209       if (NumRecords == (OpNum + 6)) {
5210         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
5211           return Err;
5212       }
5213       if (!Alignment)
5214         Alignment =
5215             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5216 
5217       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
5218                                 FailureOrdering, SSID);
5219       FullTy = StructType::get(Context, {FullTy, Type::getInt1Ty(Context)});
5220       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
5221       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
5222 
5223       InstructionList.push_back(I);
5224       break;
5225     }
5226     case bitc::FUNC_CODE_INST_ATOMICRMW: {
5227       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, ssid, align?]
5228       const size_t NumRecords = Record.size();
5229       unsigned OpNum = 0;
5230 
5231       Value *Ptr = nullptr;
5232       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, &FullTy))
5233         return error("Invalid record");
5234 
5235       if (!isa<PointerType>(Ptr->getType()))
5236         return error("Invalid record");
5237 
5238       Value *Val = nullptr;
5239       if (popValue(Record, OpNum, NextValueNo,
5240                    getPointerElementFlatType(FullTy), Val))
5241         return error("Invalid record");
5242 
5243       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
5244         return error("Invalid record");
5245 
5246       const AtomicRMWInst::BinOp Operation =
5247           getDecodedRMWOperation(Record[OpNum]);
5248       if (Operation < AtomicRMWInst::FIRST_BINOP ||
5249           Operation > AtomicRMWInst::LAST_BINOP)
5250         return error("Invalid record");
5251 
5252       const bool IsVol = Record[OpNum + 1];
5253 
5254       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5255       if (Ordering == AtomicOrdering::NotAtomic ||
5256           Ordering == AtomicOrdering::Unordered)
5257         return error("Invalid record");
5258 
5259       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5260 
5261       MaybeAlign Alignment;
5262 
5263       if (NumRecords == (OpNum + 5)) {
5264         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
5265           return Err;
5266       }
5267 
5268       if (!Alignment)
5269         Alignment =
5270             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
5271 
5272       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
5273       FullTy = getPointerElementFlatType(FullTy);
5274       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
5275 
5276       InstructionList.push_back(I);
5277       break;
5278     }
5279     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
5280       if (2 != Record.size())
5281         return error("Invalid record");
5282       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5283       if (Ordering == AtomicOrdering::NotAtomic ||
5284           Ordering == AtomicOrdering::Unordered ||
5285           Ordering == AtomicOrdering::Monotonic)
5286         return error("Invalid record");
5287       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
5288       I = new FenceInst(Context, Ordering, SSID);
5289       InstructionList.push_back(I);
5290       break;
5291     }
5292     case bitc::FUNC_CODE_INST_CALL: {
5293       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5294       if (Record.size() < 3)
5295         return error("Invalid record");
5296 
5297       unsigned OpNum = 0;
5298       AttributeList PAL = getAttributes(Record[OpNum++]);
5299       unsigned CCInfo = Record[OpNum++];
5300 
5301       FastMathFlags FMF;
5302       if ((CCInfo >> bitc::CALL_FMF) & 1) {
5303         FMF = getDecodedFastMathFlags(Record[OpNum++]);
5304         if (!FMF.any())
5305           return error("Fast math flags indicator set for call with no FMF");
5306       }
5307 
5308       FunctionType *FTy = nullptr;
5309       FunctionType *FullFTy = nullptr;
5310       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5311         FullFTy =
5312             dyn_cast<FunctionType>(getFullyStructuredTypeByID(Record[OpNum++]));
5313         if (!FullFTy)
5314           return error("Explicit call type is not a function type");
5315         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
5316       }
5317 
5318       Value *Callee;
5319       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, &FullTy))
5320         return error("Invalid record");
5321 
5322       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5323       if (!OpTy)
5324         return error("Callee is not a pointer type");
5325       if (!FTy) {
5326         FullFTy =
5327             dyn_cast<FunctionType>(cast<PointerType>(FullTy)->getElementType());
5328         if (!FullFTy)
5329           return error("Callee is not of pointer to function type");
5330         FTy = cast<FunctionType>(flattenPointerTypes(FullFTy));
5331       } else if (getPointerElementFlatType(FullTy) != FTy)
5332         return error("Explicit call type does not match pointee type of "
5333                      "callee operand");
5334       if (Record.size() < FTy->getNumParams() + OpNum)
5335         return error("Insufficient operands to call");
5336 
5337       SmallVector<Value*, 16> Args;
5338       SmallVector<Type*, 16> ArgsFullTys;
5339       // Read the fixed params.
5340       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5341         if (FTy->getParamType(i)->isLabelTy())
5342           Args.push_back(getBasicBlock(Record[OpNum]));
5343         else
5344           Args.push_back(getValue(Record, OpNum, NextValueNo,
5345                                   FTy->getParamType(i)));
5346         ArgsFullTys.push_back(FullFTy->getParamType(i));
5347         if (!Args.back())
5348           return error("Invalid record");
5349       }
5350 
5351       // Read type/value pairs for varargs params.
5352       if (!FTy->isVarArg()) {
5353         if (OpNum != Record.size())
5354           return error("Invalid record");
5355       } else {
5356         while (OpNum != Record.size()) {
5357           Value *Op;
5358           Type *FullTy;
5359           if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy))
5360             return error("Invalid record");
5361           Args.push_back(Op);
5362           ArgsFullTys.push_back(FullTy);
5363         }
5364       }
5365 
5366       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5367       FullTy = FullFTy->getReturnType();
5368       OperandBundles.clear();
5369       InstructionList.push_back(I);
5370       cast<CallInst>(I)->setCallingConv(
5371           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5372       CallInst::TailCallKind TCK = CallInst::TCK_None;
5373       if (CCInfo & 1 << bitc::CALL_TAIL)
5374         TCK = CallInst::TCK_Tail;
5375       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5376         TCK = CallInst::TCK_MustTail;
5377       if (CCInfo & (1 << bitc::CALL_NOTAIL))
5378         TCK = CallInst::TCK_NoTail;
5379       cast<CallInst>(I)->setTailCallKind(TCK);
5380       cast<CallInst>(I)->setAttributes(PAL);
5381       propagateByValSRetTypes(cast<CallBase>(I), ArgsFullTys);
5382       if (FMF.any()) {
5383         if (!isa<FPMathOperator>(I))
5384           return error("Fast-math-flags specified for call without "
5385                        "floating-point scalar or vector return type");
5386         I->setFastMathFlags(FMF);
5387       }
5388       break;
5389     }
5390     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5391       if (Record.size() < 3)
5392         return error("Invalid record");
5393       Type *OpTy = getTypeByID(Record[0]);
5394       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5395       FullTy = getFullyStructuredTypeByID(Record[2]);
5396       Type *ResTy = flattenPointerTypes(FullTy);
5397       if (!OpTy || !Op || !ResTy)
5398         return error("Invalid record");
5399       I = new VAArgInst(Op, ResTy);
5400       InstructionList.push_back(I);
5401       break;
5402     }
5403 
5404     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5405       // A call or an invoke can be optionally prefixed with some variable
5406       // number of operand bundle blocks.  These blocks are read into
5407       // OperandBundles and consumed at the next call or invoke instruction.
5408 
5409       if (Record.empty() || Record[0] >= BundleTags.size())
5410         return error("Invalid record");
5411 
5412       std::vector<Value *> Inputs;
5413 
5414       unsigned OpNum = 1;
5415       while (OpNum != Record.size()) {
5416         Value *Op;
5417         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5418           return error("Invalid record");
5419         Inputs.push_back(Op);
5420       }
5421 
5422       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5423       continue;
5424     }
5425 
5426     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
5427       unsigned OpNum = 0;
5428       Value *Op = nullptr;
5429       if (getValueTypePair(Record, OpNum, NextValueNo, Op, &FullTy))
5430         return error("Invalid record");
5431       if (OpNum != Record.size())
5432         return error("Invalid record");
5433 
5434       I = new FreezeInst(Op);
5435       InstructionList.push_back(I);
5436       break;
5437     }
5438     }
5439 
5440     // Add instruction to end of current BB.  If there is no current BB, reject
5441     // this file.
5442     if (!CurBB) {
5443       I->deleteValue();
5444       return error("Invalid instruction with no BB");
5445     }
5446     if (!OperandBundles.empty()) {
5447       I->deleteValue();
5448       return error("Operand bundles found with no consumer");
5449     }
5450     CurBB->getInstList().push_back(I);
5451 
5452     // If this was a terminator instruction, move to the next block.
5453     if (I->isTerminator()) {
5454       ++CurBBNo;
5455       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5456     }
5457 
5458     // Non-void values get registered in the value table for future use.
5459     if (!I->getType()->isVoidTy()) {
5460       if (!FullTy) {
5461         FullTy = I->getType();
5462         assert(
5463             !FullTy->isPointerTy() && !isa<StructType>(FullTy) &&
5464             !isa<ArrayType>(FullTy) &&
5465             (!isa<VectorType>(FullTy) ||
5466              cast<VectorType>(FullTy)->getElementType()->isFloatingPointTy() ||
5467              cast<VectorType>(FullTy)->getElementType()->isIntegerTy()) &&
5468             "Structured types must be assigned with corresponding non-opaque "
5469             "pointer type");
5470       }
5471 
5472       assert(I->getType() == flattenPointerTypes(FullTy) &&
5473              "Incorrect fully structured type provided for Instruction");
5474       ValueList.assignValue(I, NextValueNo++, FullTy);
5475     }
5476   }
5477 
5478 OutOfRecordLoop:
5479 
5480   if (!OperandBundles.empty())
5481     return error("Operand bundles found with no consumer");
5482 
5483   // Check the function list for unresolved values.
5484   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5485     if (!A->getParent()) {
5486       // We found at least one unresolved value.  Nuke them all to avoid leaks.
5487       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5488         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5489           A->replaceAllUsesWith(UndefValue::get(A->getType()));
5490           delete A;
5491         }
5492       }
5493       return error("Never resolved value found in function");
5494     }
5495   }
5496 
5497   // Unexpected unresolved metadata about to be dropped.
5498   if (MDLoader->hasFwdRefs())
5499     return error("Invalid function metadata: outgoing forward refs");
5500 
5501   // Trim the value list down to the size it was before we parsed this function.
5502   ValueList.shrinkTo(ModuleValueListSize);
5503   MDLoader->shrinkTo(ModuleMDLoaderSize);
5504   std::vector<BasicBlock*>().swap(FunctionBBs);
5505   return Error::success();
5506 }
5507 
5508 /// Find the function body in the bitcode stream
5509 Error BitcodeReader::findFunctionInStream(
5510     Function *F,
5511     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5512   while (DeferredFunctionInfoIterator->second == 0) {
5513     // This is the fallback handling for the old format bitcode that
5514     // didn't contain the function index in the VST, or when we have
5515     // an anonymous function which would not have a VST entry.
5516     // Assert that we have one of those two cases.
5517     assert(VSTOffset == 0 || !F->hasName());
5518     // Parse the next body in the stream and set its position in the
5519     // DeferredFunctionInfo map.
5520     if (Error Err = rememberAndSkipFunctionBodies())
5521       return Err;
5522   }
5523   return Error::success();
5524 }
5525 
5526 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
5527   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
5528     return SyncScope::ID(Val);
5529   if (Val >= SSIDs.size())
5530     return SyncScope::System; // Map unknown synchronization scopes to system.
5531   return SSIDs[Val];
5532 }
5533 
5534 //===----------------------------------------------------------------------===//
5535 // GVMaterializer implementation
5536 //===----------------------------------------------------------------------===//
5537 
5538 Error BitcodeReader::materialize(GlobalValue *GV) {
5539   Function *F = dyn_cast<Function>(GV);
5540   // If it's not a function or is already material, ignore the request.
5541   if (!F || !F->isMaterializable())
5542     return Error::success();
5543 
5544   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5545   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5546   // If its position is recorded as 0, its body is somewhere in the stream
5547   // but we haven't seen it yet.
5548   if (DFII->second == 0)
5549     if (Error Err = findFunctionInStream(F, DFII))
5550       return Err;
5551 
5552   // Materialize metadata before parsing any function bodies.
5553   if (Error Err = materializeMetadata())
5554     return Err;
5555 
5556   // Move the bit stream to the saved position of the deferred function body.
5557   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
5558     return JumpFailed;
5559   if (Error Err = parseFunctionBody(F))
5560     return Err;
5561   F->setIsMaterializable(false);
5562 
5563   if (StripDebugInfo)
5564     stripDebugInfo(*F);
5565 
5566   // Upgrade any old intrinsic calls in the function.
5567   for (auto &I : UpgradedIntrinsics) {
5568     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5569          UI != UE;) {
5570       User *U = *UI;
5571       ++UI;
5572       if (CallInst *CI = dyn_cast<CallInst>(U))
5573         UpgradeIntrinsicCall(CI, I.second);
5574     }
5575   }
5576 
5577   // Update calls to the remangled intrinsics
5578   for (auto &I : RemangledIntrinsics)
5579     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5580          UI != UE;)
5581       // Don't expect any other users than call sites
5582       cast<CallBase>(*UI++)->setCalledFunction(I.second);
5583 
5584   // Finish fn->subprogram upgrade for materialized functions.
5585   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
5586     F->setSubprogram(SP);
5587 
5588   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
5589   if (!MDLoader->isStrippingTBAA()) {
5590     for (auto &I : instructions(F)) {
5591       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
5592       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
5593         continue;
5594       MDLoader->setStripTBAA(true);
5595       stripTBAA(F->getParent());
5596     }
5597   }
5598 
5599   for (auto &I : instructions(F)) {
5600     // "Upgrade" older incorrect branch weights by dropping them.
5601     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
5602       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
5603         MDString *MDS = cast<MDString>(MD->getOperand(0));
5604         StringRef ProfName = MDS->getString();
5605         // Check consistency of !prof branch_weights metadata.
5606         if (!ProfName.equals("branch_weights"))
5607           continue;
5608         unsigned ExpectedNumOperands = 0;
5609         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
5610           ExpectedNumOperands = BI->getNumSuccessors();
5611         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
5612           ExpectedNumOperands = SI->getNumSuccessors();
5613         else if (isa<CallInst>(&I))
5614           ExpectedNumOperands = 1;
5615         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
5616           ExpectedNumOperands = IBI->getNumDestinations();
5617         else if (isa<SelectInst>(&I))
5618           ExpectedNumOperands = 2;
5619         else
5620           continue; // ignore and continue.
5621 
5622         // If branch weight doesn't match, just strip branch weight.
5623         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
5624           I.setMetadata(LLVMContext::MD_prof, nullptr);
5625       }
5626     }
5627 
5628     // Remove align from return attribute on CallInst.
5629     if (auto *CI = dyn_cast<CallInst>(&I)) {
5630       if (CI->getFunctionType()->getReturnType()->isVoidTy())
5631         CI->removeAttribute(0, Attribute::Alignment);
5632     }
5633   }
5634 
5635   // Look for functions that rely on old function attribute behavior.
5636   UpgradeFunctionAttributes(*F);
5637 
5638   // Bring in any functions that this function forward-referenced via
5639   // blockaddresses.
5640   return materializeForwardReferencedFunctions();
5641 }
5642 
5643 Error BitcodeReader::materializeModule() {
5644   if (Error Err = materializeMetadata())
5645     return Err;
5646 
5647   // Promise to materialize all forward references.
5648   WillMaterializeAllForwardRefs = true;
5649 
5650   // Iterate over the module, deserializing any functions that are still on
5651   // disk.
5652   for (Function &F : *TheModule) {
5653     if (Error Err = materialize(&F))
5654       return Err;
5655   }
5656   // At this point, if there are any function bodies, parse the rest of
5657   // the bits in the module past the last function block we have recorded
5658   // through either lazy scanning or the VST.
5659   if (LastFunctionBlockBit || NextUnreadBit)
5660     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
5661                                     ? LastFunctionBlockBit
5662                                     : NextUnreadBit))
5663       return Err;
5664 
5665   // Check that all block address forward references got resolved (as we
5666   // promised above).
5667   if (!BasicBlockFwdRefs.empty())
5668     return error("Never resolved function from blockaddress");
5669 
5670   // Upgrade any intrinsic calls that slipped through (should not happen!) and
5671   // delete the old functions to clean up. We can't do this unless the entire
5672   // module is materialized because there could always be another function body
5673   // with calls to the old function.
5674   for (auto &I : UpgradedIntrinsics) {
5675     for (auto *U : I.first->users()) {
5676       if (CallInst *CI = dyn_cast<CallInst>(U))
5677         UpgradeIntrinsicCall(CI, I.second);
5678     }
5679     if (!I.first->use_empty())
5680       I.first->replaceAllUsesWith(I.second);
5681     I.first->eraseFromParent();
5682   }
5683   UpgradedIntrinsics.clear();
5684   // Do the same for remangled intrinsics
5685   for (auto &I : RemangledIntrinsics) {
5686     I.first->replaceAllUsesWith(I.second);
5687     I.first->eraseFromParent();
5688   }
5689   RemangledIntrinsics.clear();
5690 
5691   UpgradeDebugInfo(*TheModule);
5692 
5693   UpgradeModuleFlags(*TheModule);
5694 
5695   UpgradeARCRuntime(*TheModule);
5696 
5697   return Error::success();
5698 }
5699 
5700 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5701   return IdentifiedStructTypes;
5702 }
5703 
5704 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
5705     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
5706     StringRef ModulePath, unsigned ModuleId)
5707     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
5708       ModulePath(ModulePath), ModuleId(ModuleId) {}
5709 
5710 void ModuleSummaryIndexBitcodeReader::addThisModule() {
5711   TheIndex.addModule(ModulePath, ModuleId);
5712 }
5713 
5714 ModuleSummaryIndex::ModuleInfo *
5715 ModuleSummaryIndexBitcodeReader::getThisModule() {
5716   return TheIndex.getModule(ModulePath);
5717 }
5718 
5719 std::pair<ValueInfo, GlobalValue::GUID>
5720 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
5721   auto VGI = ValueIdToValueInfoMap[ValueId];
5722   assert(VGI.first);
5723   return VGI;
5724 }
5725 
5726 void ModuleSummaryIndexBitcodeReader::setValueGUID(
5727     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
5728     StringRef SourceFileName) {
5729   std::string GlobalId =
5730       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
5731   auto ValueGUID = GlobalValue::getGUID(GlobalId);
5732   auto OriginalNameID = ValueGUID;
5733   if (GlobalValue::isLocalLinkage(Linkage))
5734     OriginalNameID = GlobalValue::getGUID(ValueName);
5735   if (PrintSummaryGUIDs)
5736     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
5737            << ValueName << "\n";
5738 
5739   // UseStrtab is false for legacy summary formats and value names are
5740   // created on stack. In that case we save the name in a string saver in
5741   // the index so that the value name can be recorded.
5742   ValueIdToValueInfoMap[ValueID] = std::make_pair(
5743       TheIndex.getOrInsertValueInfo(
5744           ValueGUID,
5745           UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
5746       OriginalNameID);
5747 }
5748 
5749 // Specialized value symbol table parser used when reading module index
5750 // blocks where we don't actually create global values. The parsed information
5751 // is saved in the bitcode reader for use when later parsing summaries.
5752 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
5753     uint64_t Offset,
5754     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5755   // With a strtab the VST is not required to parse the summary.
5756   if (UseStrtab)
5757     return Error::success();
5758 
5759   assert(Offset > 0 && "Expected non-zero VST offset");
5760   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
5761   if (!MaybeCurrentBit)
5762     return MaybeCurrentBit.takeError();
5763   uint64_t CurrentBit = MaybeCurrentBit.get();
5764 
5765   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5766     return Err;
5767 
5768   SmallVector<uint64_t, 64> Record;
5769 
5770   // Read all the records for this value table.
5771   SmallString<128> ValueName;
5772 
5773   while (true) {
5774     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
5775     if (!MaybeEntry)
5776       return MaybeEntry.takeError();
5777     BitstreamEntry Entry = MaybeEntry.get();
5778 
5779     switch (Entry.Kind) {
5780     case BitstreamEntry::SubBlock: // Handled for us already.
5781     case BitstreamEntry::Error:
5782       return error("Malformed block");
5783     case BitstreamEntry::EndBlock:
5784       // Done parsing VST, jump back to wherever we came from.
5785       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
5786         return JumpFailed;
5787       return Error::success();
5788     case BitstreamEntry::Record:
5789       // The interesting case.
5790       break;
5791     }
5792 
5793     // Read a record.
5794     Record.clear();
5795     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
5796     if (!MaybeRecord)
5797       return MaybeRecord.takeError();
5798     switch (MaybeRecord.get()) {
5799     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5800       break;
5801     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5802       if (convertToString(Record, 1, ValueName))
5803         return error("Invalid record");
5804       unsigned ValueID = Record[0];
5805       assert(!SourceFileName.empty());
5806       auto VLI = ValueIdToLinkageMap.find(ValueID);
5807       assert(VLI != ValueIdToLinkageMap.end() &&
5808              "No linkage found for VST entry?");
5809       auto Linkage = VLI->second;
5810       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5811       ValueName.clear();
5812       break;
5813     }
5814     case bitc::VST_CODE_FNENTRY: {
5815       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
5816       if (convertToString(Record, 2, ValueName))
5817         return error("Invalid record");
5818       unsigned ValueID = Record[0];
5819       assert(!SourceFileName.empty());
5820       auto VLI = ValueIdToLinkageMap.find(ValueID);
5821       assert(VLI != ValueIdToLinkageMap.end() &&
5822              "No linkage found for VST entry?");
5823       auto Linkage = VLI->second;
5824       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
5825       ValueName.clear();
5826       break;
5827     }
5828     case bitc::VST_CODE_COMBINED_ENTRY: {
5829       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5830       unsigned ValueID = Record[0];
5831       GlobalValue::GUID RefGUID = Record[1];
5832       // The "original name", which is the second value of the pair will be
5833       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
5834       ValueIdToValueInfoMap[ValueID] =
5835           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
5836       break;
5837     }
5838     }
5839   }
5840 }
5841 
5842 // Parse just the blocks needed for building the index out of the module.
5843 // At the end of this routine the module Index is populated with a map
5844 // from global value id to GlobalValueSummary objects.
5845 Error ModuleSummaryIndexBitcodeReader::parseModule() {
5846   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5847     return Err;
5848 
5849   SmallVector<uint64_t, 64> Record;
5850   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5851   unsigned ValueId = 0;
5852 
5853   // Read the index for this module.
5854   while (true) {
5855     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
5856     if (!MaybeEntry)
5857       return MaybeEntry.takeError();
5858     llvm::BitstreamEntry Entry = MaybeEntry.get();
5859 
5860     switch (Entry.Kind) {
5861     case BitstreamEntry::Error:
5862       return error("Malformed block");
5863     case BitstreamEntry::EndBlock:
5864       return Error::success();
5865 
5866     case BitstreamEntry::SubBlock:
5867       switch (Entry.ID) {
5868       default: // Skip unknown content.
5869         if (Error Err = Stream.SkipBlock())
5870           return Err;
5871         break;
5872       case bitc::BLOCKINFO_BLOCK_ID:
5873         // Need to parse these to get abbrev ids (e.g. for VST)
5874         if (readBlockInfo())
5875           return error("Malformed block");
5876         break;
5877       case bitc::VALUE_SYMTAB_BLOCK_ID:
5878         // Should have been parsed earlier via VSTOffset, unless there
5879         // is no summary section.
5880         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5881                 !SeenGlobalValSummary) &&
5882                "Expected early VST parse via VSTOffset record");
5883         if (Error Err = Stream.SkipBlock())
5884           return Err;
5885         break;
5886       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5887       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
5888         // Add the module if it is a per-module index (has a source file name).
5889         if (!SourceFileName.empty())
5890           addThisModule();
5891         assert(!SeenValueSymbolTable &&
5892                "Already read VST when parsing summary block?");
5893         // We might not have a VST if there were no values in the
5894         // summary. An empty summary block generated when we are
5895         // performing ThinLTO compiles so we don't later invoke
5896         // the regular LTO process on them.
5897         if (VSTOffset > 0) {
5898           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5899             return Err;
5900           SeenValueSymbolTable = true;
5901         }
5902         SeenGlobalValSummary = true;
5903         if (Error Err = parseEntireSummary(Entry.ID))
5904           return Err;
5905         break;
5906       case bitc::MODULE_STRTAB_BLOCK_ID:
5907         if (Error Err = parseModuleStringTable())
5908           return Err;
5909         break;
5910       }
5911       continue;
5912 
5913     case BitstreamEntry::Record: {
5914         Record.clear();
5915         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
5916         if (!MaybeBitCode)
5917           return MaybeBitCode.takeError();
5918         switch (MaybeBitCode.get()) {
5919         default:
5920           break; // Default behavior, ignore unknown content.
5921         case bitc::MODULE_CODE_VERSION: {
5922           if (Error Err = parseVersionRecord(Record).takeError())
5923             return Err;
5924           break;
5925         }
5926         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
5927         case bitc::MODULE_CODE_SOURCE_FILENAME: {
5928           SmallString<128> ValueName;
5929           if (convertToString(Record, 0, ValueName))
5930             return error("Invalid record");
5931           SourceFileName = ValueName.c_str();
5932           break;
5933         }
5934         /// MODULE_CODE_HASH: [5*i32]
5935         case bitc::MODULE_CODE_HASH: {
5936           if (Record.size() != 5)
5937             return error("Invalid hash length " + Twine(Record.size()).str());
5938           auto &Hash = getThisModule()->second.second;
5939           int Pos = 0;
5940           for (auto &Val : Record) {
5941             assert(!(Val >> 32) && "Unexpected high bits set");
5942             Hash[Pos++] = Val;
5943           }
5944           break;
5945         }
5946         /// MODULE_CODE_VSTOFFSET: [offset]
5947         case bitc::MODULE_CODE_VSTOFFSET:
5948           if (Record.empty())
5949             return error("Invalid record");
5950           // Note that we subtract 1 here because the offset is relative to one
5951           // word before the start of the identification or module block, which
5952           // was historically always the start of the regular bitcode header.
5953           VSTOffset = Record[0] - 1;
5954           break;
5955         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
5956         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
5957         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
5958         // v2: [strtab offset, strtab size, v1]
5959         case bitc::MODULE_CODE_GLOBALVAR:
5960         case bitc::MODULE_CODE_FUNCTION:
5961         case bitc::MODULE_CODE_ALIAS: {
5962           StringRef Name;
5963           ArrayRef<uint64_t> GVRecord;
5964           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
5965           if (GVRecord.size() <= 3)
5966             return error("Invalid record");
5967           uint64_t RawLinkage = GVRecord[3];
5968           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5969           if (!UseStrtab) {
5970             ValueIdToLinkageMap[ValueId++] = Linkage;
5971             break;
5972           }
5973 
5974           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
5975           break;
5976         }
5977         }
5978       }
5979       continue;
5980     }
5981   }
5982 }
5983 
5984 std::vector<ValueInfo>
5985 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
5986   std::vector<ValueInfo> Ret;
5987   Ret.reserve(Record.size());
5988   for (uint64_t RefValueId : Record)
5989     Ret.push_back(getValueInfoFromValueId(RefValueId).first);
5990   return Ret;
5991 }
5992 
5993 std::vector<FunctionSummary::EdgeTy>
5994 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
5995                                               bool IsOldProfileFormat,
5996                                               bool HasProfile, bool HasRelBF) {
5997   std::vector<FunctionSummary::EdgeTy> Ret;
5998   Ret.reserve(Record.size());
5999   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
6000     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
6001     uint64_t RelBF = 0;
6002     ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6003     if (IsOldProfileFormat) {
6004       I += 1; // Skip old callsitecount field
6005       if (HasProfile)
6006         I += 1; // Skip old profilecount field
6007     } else if (HasProfile)
6008       Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
6009     else if (HasRelBF)
6010       RelBF = Record[++I];
6011     Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
6012   }
6013   return Ret;
6014 }
6015 
6016 static void
6017 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
6018                                        WholeProgramDevirtResolution &Wpd) {
6019   uint64_t ArgNum = Record[Slot++];
6020   WholeProgramDevirtResolution::ByArg &B =
6021       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
6022   Slot += ArgNum;
6023 
6024   B.TheKind =
6025       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
6026   B.Info = Record[Slot++];
6027   B.Byte = Record[Slot++];
6028   B.Bit = Record[Slot++];
6029 }
6030 
6031 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
6032                                               StringRef Strtab, size_t &Slot,
6033                                               TypeIdSummary &TypeId) {
6034   uint64_t Id = Record[Slot++];
6035   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
6036 
6037   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
6038   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
6039                         static_cast<size_t>(Record[Slot + 1])};
6040   Slot += 2;
6041 
6042   uint64_t ResByArgNum = Record[Slot++];
6043   for (uint64_t I = 0; I != ResByArgNum; ++I)
6044     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
6045 }
6046 
6047 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
6048                                      StringRef Strtab,
6049                                      ModuleSummaryIndex &TheIndex) {
6050   size_t Slot = 0;
6051   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
6052       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
6053   Slot += 2;
6054 
6055   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
6056   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
6057   TypeId.TTRes.AlignLog2 = Record[Slot++];
6058   TypeId.TTRes.SizeM1 = Record[Slot++];
6059   TypeId.TTRes.BitMask = Record[Slot++];
6060   TypeId.TTRes.InlineBits = Record[Slot++];
6061 
6062   while (Slot < Record.size())
6063     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
6064 }
6065 
6066 std::vector<FunctionSummary::ParamAccess>
6067 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
6068   auto ReadRange = [&]() {
6069     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
6070                 BitcodeReader::decodeSignRotatedValue(Record.front()));
6071     Record = Record.drop_front();
6072     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
6073                 BitcodeReader::decodeSignRotatedValue(Record.front()));
6074     Record = Record.drop_front();
6075     ConstantRange Range{Lower, Upper};
6076     assert(!Range.isFullSet());
6077     assert(!Range.isUpperSignWrapped());
6078     return Range;
6079   };
6080 
6081   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6082   while (!Record.empty()) {
6083     PendingParamAccesses.emplace_back();
6084     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
6085     ParamAccess.ParamNo = Record.front();
6086     Record = Record.drop_front();
6087     ParamAccess.Use = ReadRange();
6088     ParamAccess.Calls.resize(Record.front());
6089     Record = Record.drop_front();
6090     for (auto &Call : ParamAccess.Calls) {
6091       Call.ParamNo = Record.front();
6092       Record = Record.drop_front();
6093       Call.Callee = getValueInfoFromValueId(Record.front()).first;
6094       Record = Record.drop_front();
6095       Call.Offsets = ReadRange();
6096     }
6097   }
6098   return PendingParamAccesses;
6099 }
6100 
6101 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
6102     ArrayRef<uint64_t> Record, size_t &Slot,
6103     TypeIdCompatibleVtableInfo &TypeId) {
6104   uint64_t Offset = Record[Slot++];
6105   ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first;
6106   TypeId.push_back({Offset, Callee});
6107 }
6108 
6109 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
6110     ArrayRef<uint64_t> Record) {
6111   size_t Slot = 0;
6112   TypeIdCompatibleVtableInfo &TypeId =
6113       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
6114           {Strtab.data() + Record[Slot],
6115            static_cast<size_t>(Record[Slot + 1])});
6116   Slot += 2;
6117 
6118   while (Slot < Record.size())
6119     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
6120 }
6121 
6122 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
6123                            unsigned WOCnt) {
6124   // Readonly and writeonly refs are in the end of the refs list.
6125   assert(ROCnt + WOCnt <= Refs.size());
6126   unsigned FirstWORef = Refs.size() - WOCnt;
6127   unsigned RefNo = FirstWORef - ROCnt;
6128   for (; RefNo < FirstWORef; ++RefNo)
6129     Refs[RefNo].setReadOnly();
6130   for (; RefNo < Refs.size(); ++RefNo)
6131     Refs[RefNo].setWriteOnly();
6132 }
6133 
6134 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
6135 // objects in the index.
6136 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
6137   if (Error Err = Stream.EnterSubBlock(ID))
6138     return Err;
6139   SmallVector<uint64_t, 64> Record;
6140 
6141   // Parse version
6142   {
6143     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6144     if (!MaybeEntry)
6145       return MaybeEntry.takeError();
6146     BitstreamEntry Entry = MaybeEntry.get();
6147 
6148     if (Entry.Kind != BitstreamEntry::Record)
6149       return error("Invalid Summary Block: record for version expected");
6150     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6151     if (!MaybeRecord)
6152       return MaybeRecord.takeError();
6153     if (MaybeRecord.get() != bitc::FS_VERSION)
6154       return error("Invalid Summary Block: version expected");
6155   }
6156   const uint64_t Version = Record[0];
6157   const bool IsOldProfileFormat = Version == 1;
6158   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
6159     return error("Invalid summary version " + Twine(Version) +
6160                  ". Version should be in the range [1-" +
6161                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
6162                  "].");
6163   Record.clear();
6164 
6165   // Keep around the last seen summary to be used when we see an optional
6166   // "OriginalName" attachement.
6167   GlobalValueSummary *LastSeenSummary = nullptr;
6168   GlobalValue::GUID LastSeenGUID = 0;
6169 
6170   // We can expect to see any number of type ID information records before
6171   // each function summary records; these variables store the information
6172   // collected so far so that it can be used to create the summary object.
6173   std::vector<GlobalValue::GUID> PendingTypeTests;
6174   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
6175       PendingTypeCheckedLoadVCalls;
6176   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
6177       PendingTypeCheckedLoadConstVCalls;
6178   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6179 
6180   while (true) {
6181     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6182     if (!MaybeEntry)
6183       return MaybeEntry.takeError();
6184     BitstreamEntry Entry = MaybeEntry.get();
6185 
6186     switch (Entry.Kind) {
6187     case BitstreamEntry::SubBlock: // Handled for us already.
6188     case BitstreamEntry::Error:
6189       return error("Malformed block");
6190     case BitstreamEntry::EndBlock:
6191       return Error::success();
6192     case BitstreamEntry::Record:
6193       // The interesting case.
6194       break;
6195     }
6196 
6197     // Read a record. The record format depends on whether this
6198     // is a per-module index or a combined index file. In the per-module
6199     // case the records contain the associated value's ID for correlation
6200     // with VST entries. In the combined index the correlation is done
6201     // via the bitcode offset of the summary records (which were saved
6202     // in the combined index VST entries). The records also contain
6203     // information used for ThinLTO renaming and importing.
6204     Record.clear();
6205     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6206     if (!MaybeBitCode)
6207       return MaybeBitCode.takeError();
6208     switch (unsigned BitCode = MaybeBitCode.get()) {
6209     default: // Default behavior: ignore.
6210       break;
6211     case bitc::FS_FLAGS: {  // [flags]
6212       TheIndex.setFlags(Record[0]);
6213       break;
6214     }
6215     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
6216       uint64_t ValueID = Record[0];
6217       GlobalValue::GUID RefGUID = Record[1];
6218       ValueIdToValueInfoMap[ValueID] =
6219           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
6220       break;
6221     }
6222     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
6223     //                numrefs x valueid, n x (valueid)]
6224     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
6225     //                        numrefs x valueid,
6226     //                        n x (valueid, hotness)]
6227     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
6228     //                      numrefs x valueid,
6229     //                      n x (valueid, relblockfreq)]
6230     case bitc::FS_PERMODULE:
6231     case bitc::FS_PERMODULE_RELBF:
6232     case bitc::FS_PERMODULE_PROFILE: {
6233       unsigned ValueID = Record[0];
6234       uint64_t RawFlags = Record[1];
6235       unsigned InstCount = Record[2];
6236       uint64_t RawFunFlags = 0;
6237       unsigned NumRefs = Record[3];
6238       unsigned NumRORefs = 0, NumWORefs = 0;
6239       int RefListStartIndex = 4;
6240       if (Version >= 4) {
6241         RawFunFlags = Record[3];
6242         NumRefs = Record[4];
6243         RefListStartIndex = 5;
6244         if (Version >= 5) {
6245           NumRORefs = Record[5];
6246           RefListStartIndex = 6;
6247           if (Version >= 7) {
6248             NumWORefs = Record[6];
6249             RefListStartIndex = 7;
6250           }
6251         }
6252       }
6253 
6254       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6255       // The module path string ref set in the summary must be owned by the
6256       // index's module string table. Since we don't have a module path
6257       // string table section in the per-module index, we create a single
6258       // module path string table entry with an empty (0) ID to take
6259       // ownership.
6260       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6261       assert(Record.size() >= RefListStartIndex + NumRefs &&
6262              "Record size inconsistent with number of references");
6263       std::vector<ValueInfo> Refs = makeRefList(
6264           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6265       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6266       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
6267       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
6268           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6269           IsOldProfileFormat, HasProfile, HasRelBF);
6270       setSpecialRefs(Refs, NumRORefs, NumWORefs);
6271       auto FS = std::make_unique<FunctionSummary>(
6272           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
6273           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
6274           std::move(PendingTypeTestAssumeVCalls),
6275           std::move(PendingTypeCheckedLoadVCalls),
6276           std::move(PendingTypeTestAssumeConstVCalls),
6277           std::move(PendingTypeCheckedLoadConstVCalls),
6278           std::move(PendingParamAccesses));
6279       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
6280       FS->setModulePath(getThisModule()->first());
6281       FS->setOriginalName(VIAndOriginalGUID.second);
6282       TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
6283       break;
6284     }
6285     // FS_ALIAS: [valueid, flags, valueid]
6286     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6287     // they expect all aliasee summaries to be available.
6288     case bitc::FS_ALIAS: {
6289       unsigned ValueID = Record[0];
6290       uint64_t RawFlags = Record[1];
6291       unsigned AliaseeID = Record[2];
6292       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6293       auto AS = std::make_unique<AliasSummary>(Flags);
6294       // The module path string ref set in the summary must be owned by the
6295       // index's module string table. Since we don't have a module path
6296       // string table section in the per-module index, we create a single
6297       // module path string table entry with an empty (0) ID to take
6298       // ownership.
6299       AS->setModulePath(getThisModule()->first());
6300 
6301       auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
6302       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
6303       if (!AliaseeInModule)
6304         return error("Alias expects aliasee summary to be parsed");
6305       AS->setAliasee(AliaseeVI, AliaseeInModule);
6306 
6307       auto GUID = getValueInfoFromValueId(ValueID);
6308       AS->setOriginalName(GUID.second);
6309       TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
6310       break;
6311     }
6312     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
6313     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6314       unsigned ValueID = Record[0];
6315       uint64_t RawFlags = Record[1];
6316       unsigned RefArrayStart = 2;
6317       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6318                                       /* WriteOnly */ false,
6319                                       /* Constant */ false,
6320                                       GlobalObject::VCallVisibilityPublic);
6321       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6322       if (Version >= 5) {
6323         GVF = getDecodedGVarFlags(Record[2]);
6324         RefArrayStart = 3;
6325       }
6326       std::vector<ValueInfo> Refs =
6327           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6328       auto FS =
6329           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6330       FS->setModulePath(getThisModule()->first());
6331       auto GUID = getValueInfoFromValueId(ValueID);
6332       FS->setOriginalName(GUID.second);
6333       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
6334       break;
6335     }
6336     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
6337     //                        numrefs, numrefs x valueid,
6338     //                        n x (valueid, offset)]
6339     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
6340       unsigned ValueID = Record[0];
6341       uint64_t RawFlags = Record[1];
6342       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
6343       unsigned NumRefs = Record[3];
6344       unsigned RefListStartIndex = 4;
6345       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
6346       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6347       std::vector<ValueInfo> Refs = makeRefList(
6348           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6349       VTableFuncList VTableFuncs;
6350       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
6351         ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6352         uint64_t Offset = Record[++I];
6353         VTableFuncs.push_back({Callee, Offset});
6354       }
6355       auto VS =
6356           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6357       VS->setModulePath(getThisModule()->first());
6358       VS->setVTableFuncs(VTableFuncs);
6359       auto GUID = getValueInfoFromValueId(ValueID);
6360       VS->setOriginalName(GUID.second);
6361       TheIndex.addGlobalValueSummary(GUID.first, std::move(VS));
6362       break;
6363     }
6364     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
6365     //               numrefs x valueid, n x (valueid)]
6366     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
6367     //                       numrefs x valueid, n x (valueid, hotness)]
6368     case bitc::FS_COMBINED:
6369     case bitc::FS_COMBINED_PROFILE: {
6370       unsigned ValueID = Record[0];
6371       uint64_t ModuleId = Record[1];
6372       uint64_t RawFlags = Record[2];
6373       unsigned InstCount = Record[3];
6374       uint64_t RawFunFlags = 0;
6375       uint64_t EntryCount = 0;
6376       unsigned NumRefs = Record[4];
6377       unsigned NumRORefs = 0, NumWORefs = 0;
6378       int RefListStartIndex = 5;
6379 
6380       if (Version >= 4) {
6381         RawFunFlags = Record[4];
6382         RefListStartIndex = 6;
6383         size_t NumRefsIndex = 5;
6384         if (Version >= 5) {
6385           unsigned NumRORefsOffset = 1;
6386           RefListStartIndex = 7;
6387           if (Version >= 6) {
6388             NumRefsIndex = 6;
6389             EntryCount = Record[5];
6390             RefListStartIndex = 8;
6391             if (Version >= 7) {
6392               RefListStartIndex = 9;
6393               NumWORefs = Record[8];
6394               NumRORefsOffset = 2;
6395             }
6396           }
6397           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
6398         }
6399         NumRefs = Record[NumRefsIndex];
6400       }
6401 
6402       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6403       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6404       assert(Record.size() >= RefListStartIndex + NumRefs &&
6405              "Record size inconsistent with number of references");
6406       std::vector<ValueInfo> Refs = makeRefList(
6407           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6408       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6409       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
6410           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6411           IsOldProfileFormat, HasProfile, false);
6412       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6413       setSpecialRefs(Refs, NumRORefs, NumWORefs);
6414       auto FS = std::make_unique<FunctionSummary>(
6415           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
6416           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
6417           std::move(PendingTypeTestAssumeVCalls),
6418           std::move(PendingTypeCheckedLoadVCalls),
6419           std::move(PendingTypeTestAssumeConstVCalls),
6420           std::move(PendingTypeCheckedLoadConstVCalls),
6421           std::move(PendingParamAccesses));
6422       LastSeenSummary = FS.get();
6423       LastSeenGUID = VI.getGUID();
6424       FS->setModulePath(ModuleIdMap[ModuleId]);
6425       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6426       break;
6427     }
6428     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6429     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6430     // they expect all aliasee summaries to be available.
6431     case bitc::FS_COMBINED_ALIAS: {
6432       unsigned ValueID = Record[0];
6433       uint64_t ModuleId = Record[1];
6434       uint64_t RawFlags = Record[2];
6435       unsigned AliaseeValueId = Record[3];
6436       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6437       auto AS = std::make_unique<AliasSummary>(Flags);
6438       LastSeenSummary = AS.get();
6439       AS->setModulePath(ModuleIdMap[ModuleId]);
6440 
6441       auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
6442       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
6443       AS->setAliasee(AliaseeVI, AliaseeInModule);
6444 
6445       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6446       LastSeenGUID = VI.getGUID();
6447       TheIndex.addGlobalValueSummary(VI, std::move(AS));
6448       break;
6449     }
6450     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6451     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6452       unsigned ValueID = Record[0];
6453       uint64_t ModuleId = Record[1];
6454       uint64_t RawFlags = Record[2];
6455       unsigned RefArrayStart = 3;
6456       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6457                                       /* WriteOnly */ false,
6458                                       /* Constant */ false,
6459                                       GlobalObject::VCallVisibilityPublic);
6460       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6461       if (Version >= 5) {
6462         GVF = getDecodedGVarFlags(Record[3]);
6463         RefArrayStart = 4;
6464       }
6465       std::vector<ValueInfo> Refs =
6466           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6467       auto FS =
6468           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6469       LastSeenSummary = FS.get();
6470       FS->setModulePath(ModuleIdMap[ModuleId]);
6471       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6472       LastSeenGUID = VI.getGUID();
6473       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6474       break;
6475     }
6476     // FS_COMBINED_ORIGINAL_NAME: [original_name]
6477     case bitc::FS_COMBINED_ORIGINAL_NAME: {
6478       uint64_t OriginalName = Record[0];
6479       if (!LastSeenSummary)
6480         return error("Name attachment that does not follow a combined record");
6481       LastSeenSummary->setOriginalName(OriginalName);
6482       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
6483       // Reset the LastSeenSummary
6484       LastSeenSummary = nullptr;
6485       LastSeenGUID = 0;
6486       break;
6487     }
6488     case bitc::FS_TYPE_TESTS:
6489       assert(PendingTypeTests.empty());
6490       llvm::append_range(PendingTypeTests, Record);
6491       break;
6492 
6493     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
6494       assert(PendingTypeTestAssumeVCalls.empty());
6495       for (unsigned I = 0; I != Record.size(); I += 2)
6496         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
6497       break;
6498 
6499     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
6500       assert(PendingTypeCheckedLoadVCalls.empty());
6501       for (unsigned I = 0; I != Record.size(); I += 2)
6502         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
6503       break;
6504 
6505     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
6506       PendingTypeTestAssumeConstVCalls.push_back(
6507           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6508       break;
6509 
6510     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
6511       PendingTypeCheckedLoadConstVCalls.push_back(
6512           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6513       break;
6514 
6515     case bitc::FS_CFI_FUNCTION_DEFS: {
6516       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
6517       for (unsigned I = 0; I != Record.size(); I += 2)
6518         CfiFunctionDefs.insert(
6519             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6520       break;
6521     }
6522 
6523     case bitc::FS_CFI_FUNCTION_DECLS: {
6524       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
6525       for (unsigned I = 0; I != Record.size(); I += 2)
6526         CfiFunctionDecls.insert(
6527             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6528       break;
6529     }
6530 
6531     case bitc::FS_TYPE_ID:
6532       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
6533       break;
6534 
6535     case bitc::FS_TYPE_ID_METADATA:
6536       parseTypeIdCompatibleVtableSummaryRecord(Record);
6537       break;
6538 
6539     case bitc::FS_BLOCK_COUNT:
6540       TheIndex.addBlockCount(Record[0]);
6541       break;
6542 
6543     case bitc::FS_PARAM_ACCESS: {
6544       PendingParamAccesses = parseParamAccesses(Record);
6545       break;
6546     }
6547     }
6548   }
6549   llvm_unreachable("Exit infinite loop");
6550 }
6551 
6552 // Parse the  module string table block into the Index.
6553 // This populates the ModulePathStringTable map in the index.
6554 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6555   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6556     return Err;
6557 
6558   SmallVector<uint64_t, 64> Record;
6559 
6560   SmallString<128> ModulePath;
6561   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
6562 
6563   while (true) {
6564     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6565     if (!MaybeEntry)
6566       return MaybeEntry.takeError();
6567     BitstreamEntry Entry = MaybeEntry.get();
6568 
6569     switch (Entry.Kind) {
6570     case BitstreamEntry::SubBlock: // Handled for us already.
6571     case BitstreamEntry::Error:
6572       return error("Malformed block");
6573     case BitstreamEntry::EndBlock:
6574       return Error::success();
6575     case BitstreamEntry::Record:
6576       // The interesting case.
6577       break;
6578     }
6579 
6580     Record.clear();
6581     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6582     if (!MaybeRecord)
6583       return MaybeRecord.takeError();
6584     switch (MaybeRecord.get()) {
6585     default: // Default behavior: ignore.
6586       break;
6587     case bitc::MST_CODE_ENTRY: {
6588       // MST_ENTRY: [modid, namechar x N]
6589       uint64_t ModuleId = Record[0];
6590 
6591       if (convertToString(Record, 1, ModulePath))
6592         return error("Invalid record");
6593 
6594       LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
6595       ModuleIdMap[ModuleId] = LastSeenModule->first();
6596 
6597       ModulePath.clear();
6598       break;
6599     }
6600     /// MST_CODE_HASH: [5*i32]
6601     case bitc::MST_CODE_HASH: {
6602       if (Record.size() != 5)
6603         return error("Invalid hash length " + Twine(Record.size()).str());
6604       if (!LastSeenModule)
6605         return error("Invalid hash that does not follow a module path");
6606       int Pos = 0;
6607       for (auto &Val : Record) {
6608         assert(!(Val >> 32) && "Unexpected high bits set");
6609         LastSeenModule->second.second[Pos++] = Val;
6610       }
6611       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
6612       LastSeenModule = nullptr;
6613       break;
6614     }
6615     }
6616   }
6617   llvm_unreachable("Exit infinite loop");
6618 }
6619 
6620 namespace {
6621 
6622 // FIXME: This class is only here to support the transition to llvm::Error. It
6623 // will be removed once this transition is complete. Clients should prefer to
6624 // deal with the Error value directly, rather than converting to error_code.
6625 class BitcodeErrorCategoryType : public std::error_category {
6626   const char *name() const noexcept override {
6627     return "llvm.bitcode";
6628   }
6629 
6630   std::string message(int IE) const override {
6631     BitcodeError E = static_cast<BitcodeError>(IE);
6632     switch (E) {
6633     case BitcodeError::CorruptedBitcode:
6634       return "Corrupted bitcode";
6635     }
6636     llvm_unreachable("Unknown error type!");
6637   }
6638 };
6639 
6640 } // end anonymous namespace
6641 
6642 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6643 
6644 const std::error_category &llvm::BitcodeErrorCategory() {
6645   return *ErrorCategory;
6646 }
6647 
6648 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
6649                                             unsigned Block, unsigned RecordID) {
6650   if (Error Err = Stream.EnterSubBlock(Block))
6651     return std::move(Err);
6652 
6653   StringRef Strtab;
6654   while (true) {
6655     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6656     if (!MaybeEntry)
6657       return MaybeEntry.takeError();
6658     llvm::BitstreamEntry Entry = MaybeEntry.get();
6659 
6660     switch (Entry.Kind) {
6661     case BitstreamEntry::EndBlock:
6662       return Strtab;
6663 
6664     case BitstreamEntry::Error:
6665       return error("Malformed block");
6666 
6667     case BitstreamEntry::SubBlock:
6668       if (Error Err = Stream.SkipBlock())
6669         return std::move(Err);
6670       break;
6671 
6672     case BitstreamEntry::Record:
6673       StringRef Blob;
6674       SmallVector<uint64_t, 1> Record;
6675       Expected<unsigned> MaybeRecord =
6676           Stream.readRecord(Entry.ID, Record, &Blob);
6677       if (!MaybeRecord)
6678         return MaybeRecord.takeError();
6679       if (MaybeRecord.get() == RecordID)
6680         Strtab = Blob;
6681       break;
6682     }
6683   }
6684 }
6685 
6686 //===----------------------------------------------------------------------===//
6687 // External interface
6688 //===----------------------------------------------------------------------===//
6689 
6690 Expected<std::vector<BitcodeModule>>
6691 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
6692   auto FOrErr = getBitcodeFileContents(Buffer);
6693   if (!FOrErr)
6694     return FOrErr.takeError();
6695   return std::move(FOrErr->Mods);
6696 }
6697 
6698 Expected<BitcodeFileContents>
6699 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
6700   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
6701   if (!StreamOrErr)
6702     return StreamOrErr.takeError();
6703   BitstreamCursor &Stream = *StreamOrErr;
6704 
6705   BitcodeFileContents F;
6706   while (true) {
6707     uint64_t BCBegin = Stream.getCurrentByteNo();
6708 
6709     // We may be consuming bitcode from a client that leaves garbage at the end
6710     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
6711     // the end that there cannot possibly be another module, stop looking.
6712     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
6713       return F;
6714 
6715     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6716     if (!MaybeEntry)
6717       return MaybeEntry.takeError();
6718     llvm::BitstreamEntry Entry = MaybeEntry.get();
6719 
6720     switch (Entry.Kind) {
6721     case BitstreamEntry::EndBlock:
6722     case BitstreamEntry::Error:
6723       return error("Malformed block");
6724 
6725     case BitstreamEntry::SubBlock: {
6726       uint64_t IdentificationBit = -1ull;
6727       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
6728         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6729         if (Error Err = Stream.SkipBlock())
6730           return std::move(Err);
6731 
6732         {
6733           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6734           if (!MaybeEntry)
6735             return MaybeEntry.takeError();
6736           Entry = MaybeEntry.get();
6737         }
6738 
6739         if (Entry.Kind != BitstreamEntry::SubBlock ||
6740             Entry.ID != bitc::MODULE_BLOCK_ID)
6741           return error("Malformed block");
6742       }
6743 
6744       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
6745         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
6746         if (Error Err = Stream.SkipBlock())
6747           return std::move(Err);
6748 
6749         F.Mods.push_back({Stream.getBitcodeBytes().slice(
6750                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
6751                           Buffer.getBufferIdentifier(), IdentificationBit,
6752                           ModuleBit});
6753         continue;
6754       }
6755 
6756       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
6757         Expected<StringRef> Strtab =
6758             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
6759         if (!Strtab)
6760           return Strtab.takeError();
6761         // This string table is used by every preceding bitcode module that does
6762         // not have its own string table. A bitcode file may have multiple
6763         // string tables if it was created by binary concatenation, for example
6764         // with "llvm-cat -b".
6765         for (auto I = F.Mods.rbegin(), E = F.Mods.rend(); I != E; ++I) {
6766           if (!I->Strtab.empty())
6767             break;
6768           I->Strtab = *Strtab;
6769         }
6770         // Similarly, the string table is used by every preceding symbol table;
6771         // normally there will be just one unless the bitcode file was created
6772         // by binary concatenation.
6773         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
6774           F.StrtabForSymtab = *Strtab;
6775         continue;
6776       }
6777 
6778       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
6779         Expected<StringRef> SymtabOrErr =
6780             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
6781         if (!SymtabOrErr)
6782           return SymtabOrErr.takeError();
6783 
6784         // We can expect the bitcode file to have multiple symbol tables if it
6785         // was created by binary concatenation. In that case we silently
6786         // ignore any subsequent symbol tables, which is fine because this is a
6787         // low level function. The client is expected to notice that the number
6788         // of modules in the symbol table does not match the number of modules
6789         // in the input file and regenerate the symbol table.
6790         if (F.Symtab.empty())
6791           F.Symtab = *SymtabOrErr;
6792         continue;
6793       }
6794 
6795       if (Error Err = Stream.SkipBlock())
6796         return std::move(Err);
6797       continue;
6798     }
6799     case BitstreamEntry::Record:
6800       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
6801         continue;
6802       else
6803         return StreamFailed.takeError();
6804     }
6805   }
6806 }
6807 
6808 /// Get a lazy one-at-time loading module from bitcode.
6809 ///
6810 /// This isn't always used in a lazy context.  In particular, it's also used by
6811 /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
6812 /// in forward-referenced functions from block address references.
6813 ///
6814 /// \param[in] MaterializeAll Set to \c true if we should materialize
6815 /// everything.
6816 Expected<std::unique_ptr<Module>>
6817 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
6818                              bool ShouldLazyLoadMetadata, bool IsImporting,
6819                              DataLayoutCallbackTy DataLayoutCallback) {
6820   BitstreamCursor Stream(Buffer);
6821 
6822   std::string ProducerIdentification;
6823   if (IdentificationBit != -1ull) {
6824     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
6825       return std::move(JumpFailed);
6826     Expected<std::string> ProducerIdentificationOrErr =
6827         readIdentificationBlock(Stream);
6828     if (!ProducerIdentificationOrErr)
6829       return ProducerIdentificationOrErr.takeError();
6830 
6831     ProducerIdentification = *ProducerIdentificationOrErr;
6832   }
6833 
6834   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6835     return std::move(JumpFailed);
6836   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
6837                               Context);
6838 
6839   std::unique_ptr<Module> M =
6840       std::make_unique<Module>(ModuleIdentifier, Context);
6841   M->setMaterializer(R);
6842 
6843   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6844   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
6845                                       IsImporting, DataLayoutCallback))
6846     return std::move(Err);
6847 
6848   if (MaterializeAll) {
6849     // Read in the entire module, and destroy the BitcodeReader.
6850     if (Error Err = M->materializeAll())
6851       return std::move(Err);
6852   } else {
6853     // Resolve forward references from blockaddresses.
6854     if (Error Err = R->materializeForwardReferencedFunctions())
6855       return std::move(Err);
6856   }
6857   return std::move(M);
6858 }
6859 
6860 Expected<std::unique_ptr<Module>>
6861 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
6862                              bool IsImporting) {
6863   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
6864                        [](StringRef) { return None; });
6865 }
6866 
6867 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
6868 // We don't use ModuleIdentifier here because the client may need to control the
6869 // module path used in the combined summary (e.g. when reading summaries for
6870 // regular LTO modules).
6871 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
6872                                  StringRef ModulePath, uint64_t ModuleId) {
6873   BitstreamCursor Stream(Buffer);
6874   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6875     return JumpFailed;
6876 
6877   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
6878                                     ModulePath, ModuleId);
6879   return R.parseModule();
6880 }
6881 
6882 // Parse the specified bitcode buffer, returning the function info index.
6883 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
6884   BitstreamCursor Stream(Buffer);
6885   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6886     return std::move(JumpFailed);
6887 
6888   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
6889   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
6890                                     ModuleIdentifier, 0);
6891 
6892   if (Error Err = R.parseModule())
6893     return std::move(Err);
6894 
6895   return std::move(Index);
6896 }
6897 
6898 static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
6899                                                 unsigned ID) {
6900   if (Error Err = Stream.EnterSubBlock(ID))
6901     return std::move(Err);
6902   SmallVector<uint64_t, 64> Record;
6903 
6904   while (true) {
6905     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6906     if (!MaybeEntry)
6907       return MaybeEntry.takeError();
6908     BitstreamEntry Entry = MaybeEntry.get();
6909 
6910     switch (Entry.Kind) {
6911     case BitstreamEntry::SubBlock: // Handled for us already.
6912     case BitstreamEntry::Error:
6913       return error("Malformed block");
6914     case BitstreamEntry::EndBlock:
6915       // If no flags record found, conservatively return true to mimic
6916       // behavior before this flag was added.
6917       return true;
6918     case BitstreamEntry::Record:
6919       // The interesting case.
6920       break;
6921     }
6922 
6923     // Look for the FS_FLAGS record.
6924     Record.clear();
6925     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6926     if (!MaybeBitCode)
6927       return MaybeBitCode.takeError();
6928     switch (MaybeBitCode.get()) {
6929     default: // Default behavior: ignore.
6930       break;
6931     case bitc::FS_FLAGS: { // [flags]
6932       uint64_t Flags = Record[0];
6933       // Scan flags.
6934       assert(Flags <= 0x7f && "Unexpected bits in flag");
6935 
6936       return Flags & 0x8;
6937     }
6938     }
6939   }
6940   llvm_unreachable("Exit infinite loop");
6941 }
6942 
6943 // Check if the given bitcode buffer contains a global value summary block.
6944 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
6945   BitstreamCursor Stream(Buffer);
6946   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
6947     return std::move(JumpFailed);
6948 
6949   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6950     return std::move(Err);
6951 
6952   while (true) {
6953     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6954     if (!MaybeEntry)
6955       return MaybeEntry.takeError();
6956     llvm::BitstreamEntry Entry = MaybeEntry.get();
6957 
6958     switch (Entry.Kind) {
6959     case BitstreamEntry::Error:
6960       return error("Malformed block");
6961     case BitstreamEntry::EndBlock:
6962       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
6963                             /*EnableSplitLTOUnit=*/false};
6964 
6965     case BitstreamEntry::SubBlock:
6966       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
6967         Expected<bool> EnableSplitLTOUnit =
6968             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
6969         if (!EnableSplitLTOUnit)
6970           return EnableSplitLTOUnit.takeError();
6971         return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
6972                               *EnableSplitLTOUnit};
6973       }
6974 
6975       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
6976         Expected<bool> EnableSplitLTOUnit =
6977             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
6978         if (!EnableSplitLTOUnit)
6979           return EnableSplitLTOUnit.takeError();
6980         return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
6981                               *EnableSplitLTOUnit};
6982       }
6983 
6984       // Ignore other sub-blocks.
6985       if (Error Err = Stream.SkipBlock())
6986         return std::move(Err);
6987       continue;
6988 
6989     case BitstreamEntry::Record:
6990       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
6991         continue;
6992       else
6993         return StreamFailed.takeError();
6994     }
6995   }
6996 }
6997 
6998 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
6999   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
7000   if (!MsOrErr)
7001     return MsOrErr.takeError();
7002 
7003   if (MsOrErr->size() != 1)
7004     return error("Expected a single module");
7005 
7006   return (*MsOrErr)[0];
7007 }
7008 
7009 Expected<std::unique_ptr<Module>>
7010 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
7011                            bool ShouldLazyLoadMetadata, bool IsImporting) {
7012   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7013   if (!BM)
7014     return BM.takeError();
7015 
7016   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
7017 }
7018 
7019 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
7020     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
7021     bool ShouldLazyLoadMetadata, bool IsImporting) {
7022   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
7023                                      IsImporting);
7024   if (MOrErr)
7025     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
7026   return MOrErr;
7027 }
7028 
7029 Expected<std::unique_ptr<Module>>
7030 BitcodeModule::parseModule(LLVMContext &Context,
7031                            DataLayoutCallbackTy DataLayoutCallback) {
7032   return getModuleImpl(Context, true, false, false, DataLayoutCallback);
7033   // TODO: Restore the use-lists to the in-memory state when the bitcode was
7034   // written.  We must defer until the Module has been fully materialized.
7035 }
7036 
7037 Expected<std::unique_ptr<Module>>
7038 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
7039                        DataLayoutCallbackTy DataLayoutCallback) {
7040   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7041   if (!BM)
7042     return BM.takeError();
7043 
7044   return BM->parseModule(Context, DataLayoutCallback);
7045 }
7046 
7047 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
7048   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7049   if (!StreamOrErr)
7050     return StreamOrErr.takeError();
7051 
7052   return readTriple(*StreamOrErr);
7053 }
7054 
7055 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
7056   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7057   if (!StreamOrErr)
7058     return StreamOrErr.takeError();
7059 
7060   return hasObjCCategory(*StreamOrErr);
7061 }
7062 
7063 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
7064   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7065   if (!StreamOrErr)
7066     return StreamOrErr.takeError();
7067 
7068   return readIdentificationCode(*StreamOrErr);
7069 }
7070 
7071 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
7072                                    ModuleSummaryIndex &CombinedIndex,
7073                                    uint64_t ModuleId) {
7074   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7075   if (!BM)
7076     return BM.takeError();
7077 
7078   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
7079 }
7080 
7081 Expected<std::unique_ptr<ModuleSummaryIndex>>
7082 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
7083   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7084   if (!BM)
7085     return BM.takeError();
7086 
7087   return BM->getSummary();
7088 }
7089 
7090 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
7091   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7092   if (!BM)
7093     return BM.takeError();
7094 
7095   return BM->getLTOInfo();
7096 }
7097 
7098 Expected<std::unique_ptr<ModuleSummaryIndex>>
7099 llvm::getModuleSummaryIndexForFile(StringRef Path,
7100                                    bool IgnoreEmptyThinLTOIndexFile) {
7101   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
7102       MemoryBuffer::getFileOrSTDIN(Path);
7103   if (!FileOrErr)
7104     return errorCodeToError(FileOrErr.getError());
7105   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
7106     return nullptr;
7107   return getModuleSummaryIndex(**FileOrErr);
7108 }
7109