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