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