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