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