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