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