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