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