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