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