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