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