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