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