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