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