xref: /llvm-project/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (revision cda82d39f3f25d8f6d1c1a105a59001339e54bb2)
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)
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       // FIXME: Make this an optional field.
5325       const DataLayout &DL = TheModule->getDataLayout();
5326       unsigned AS = DL.getAllocaAddrSpace();
5327 
5328       SmallPtrSet<Type *, 4> Visited;
5329       if (!Align && !Ty->isSized(&Visited))
5330         return error("alloca of unsized type");
5331       if (!Align)
5332         Align = DL.getPrefTypeAlign(Ty);
5333 
5334       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
5335       AI->setUsedWithInAlloca(InAlloca);
5336       AI->setSwiftError(SwiftError);
5337       I = AI;
5338       ResTypeID = getVirtualTypeID(AI->getType(), TyID);
5339       InstructionList.push_back(I);
5340       break;
5341     }
5342     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
5343       unsigned OpNum = 0;
5344       Value *Op;
5345       unsigned OpTypeID;
5346       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID) ||
5347           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
5348         return error("Invalid record");
5349 
5350       if (!isa<PointerType>(Op->getType()))
5351         return error("Load operand is not a pointer type");
5352 
5353       Type *Ty = nullptr;
5354       if (OpNum + 3 == Record.size()) {
5355         ResTypeID = Record[OpNum++];
5356         Ty = getTypeByID(ResTypeID);
5357       } else {
5358         ResTypeID = getContainedTypeID(OpTypeID);
5359         Ty = getTypeByID(ResTypeID);
5360         if (!Ty)
5361           return error("Missing element type for old-style load");
5362       }
5363 
5364       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5365         return Err;
5366 
5367       MaybeAlign Align;
5368       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5369         return Err;
5370       SmallPtrSet<Type *, 4> Visited;
5371       if (!Align && !Ty->isSized(&Visited))
5372         return error("load of unsized type");
5373       if (!Align)
5374         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
5375       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
5376       InstructionList.push_back(I);
5377       break;
5378     }
5379     case bitc::FUNC_CODE_INST_LOADATOMIC: {
5380        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
5381       unsigned OpNum = 0;
5382       Value *Op;
5383       unsigned OpTypeID;
5384       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID) ||
5385           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
5386         return error("Invalid record");
5387 
5388       if (!isa<PointerType>(Op->getType()))
5389         return error("Load operand is not a pointer type");
5390 
5391       Type *Ty = nullptr;
5392       if (OpNum + 5 == Record.size()) {
5393         ResTypeID = Record[OpNum++];
5394         Ty = getTypeByID(ResTypeID);
5395       } else {
5396         ResTypeID = getContainedTypeID(OpTypeID);
5397         Ty = getTypeByID(ResTypeID);
5398         if (!Ty)
5399           return error("Missing element type for old style atomic load");
5400       }
5401 
5402       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5403         return Err;
5404 
5405       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5406       if (Ordering == AtomicOrdering::NotAtomic ||
5407           Ordering == AtomicOrdering::Release ||
5408           Ordering == AtomicOrdering::AcquireRelease)
5409         return error("Invalid record");
5410       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5411         return error("Invalid record");
5412       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5413 
5414       MaybeAlign Align;
5415       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5416         return Err;
5417       if (!Align)
5418         return error("Alignment missing from atomic load");
5419       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
5420       InstructionList.push_back(I);
5421       break;
5422     }
5423     case bitc::FUNC_CODE_INST_STORE:
5424     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5425       unsigned OpNum = 0;
5426       Value *Val, *Ptr;
5427       unsigned PtrTypeID, ValTypeID;
5428       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))
5429         return error("Invalid record");
5430 
5431       if (BitCode == bitc::FUNC_CODE_INST_STORE) {
5432         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID))
5433           return error("Invalid record");
5434       } else {
5435         ValTypeID = getContainedTypeID(PtrTypeID);
5436         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
5437                      ValTypeID, Val))
5438           return error("Invalid record");
5439       }
5440 
5441       if (OpNum + 2 != Record.size())
5442         return error("Invalid record");
5443 
5444       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5445         return Err;
5446       MaybeAlign Align;
5447       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5448         return Err;
5449       SmallPtrSet<Type *, 4> Visited;
5450       if (!Align && !Val->getType()->isSized(&Visited))
5451         return error("store of unsized type");
5452       if (!Align)
5453         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
5454       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
5455       InstructionList.push_back(I);
5456       break;
5457     }
5458     case bitc::FUNC_CODE_INST_STOREATOMIC:
5459     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5460       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
5461       unsigned OpNum = 0;
5462       Value *Val, *Ptr;
5463       unsigned PtrTypeID, ValTypeID;
5464       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID) ||
5465           !isa<PointerType>(Ptr->getType()))
5466         return error("Invalid record");
5467       if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
5468         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID))
5469           return error("Invalid record");
5470       } else {
5471         ValTypeID = getContainedTypeID(PtrTypeID);
5472         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
5473                      ValTypeID, Val))
5474           return error("Invalid record");
5475       }
5476 
5477       if (OpNum + 4 != Record.size())
5478         return error("Invalid record");
5479 
5480       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5481         return Err;
5482       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5483       if (Ordering == AtomicOrdering::NotAtomic ||
5484           Ordering == AtomicOrdering::Acquire ||
5485           Ordering == AtomicOrdering::AcquireRelease)
5486         return error("Invalid record");
5487       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5488       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5489         return error("Invalid record");
5490 
5491       MaybeAlign Align;
5492       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5493         return Err;
5494       if (!Align)
5495         return error("Alignment missing from atomic store");
5496       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
5497       InstructionList.push_back(I);
5498       break;
5499     }
5500     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
5501       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
5502       // failure_ordering?, weak?]
5503       const size_t NumRecords = Record.size();
5504       unsigned OpNum = 0;
5505       Value *Ptr = nullptr;
5506       unsigned PtrTypeID;
5507       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))
5508         return error("Invalid record");
5509 
5510       if (!isa<PointerType>(Ptr->getType()))
5511         return error("Cmpxchg operand is not a pointer type");
5512 
5513       Value *Cmp = nullptr;
5514       unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
5515       if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
5516                    CmpTypeID, Cmp))
5517         return error("Invalid record");
5518 
5519       Value *New = nullptr;
5520       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
5521                    New) ||
5522           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
5523         return error("Invalid record");
5524 
5525       const AtomicOrdering SuccessOrdering =
5526           getDecodedOrdering(Record[OpNum + 1]);
5527       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5528           SuccessOrdering == AtomicOrdering::Unordered)
5529         return error("Invalid record");
5530 
5531       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5532 
5533       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5534         return Err;
5535 
5536       const AtomicOrdering FailureOrdering =
5537           NumRecords < 7
5538               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
5539               : getDecodedOrdering(Record[OpNum + 3]);
5540 
5541       if (FailureOrdering == AtomicOrdering::NotAtomic ||
5542           FailureOrdering == AtomicOrdering::Unordered)
5543         return error("Invalid record");
5544 
5545       const Align Alignment(
5546           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5547 
5548       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
5549                                 FailureOrdering, SSID);
5550       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5551 
5552       if (NumRecords < 8) {
5553         // Before weak cmpxchgs existed, the instruction simply returned the
5554         // value loaded from memory, so bitcode files from that era will be
5555         // expecting the first component of a modern cmpxchg.
5556         CurBB->getInstList().push_back(I);
5557         I = ExtractValueInst::Create(I, 0);
5558         ResTypeID = CmpTypeID;
5559       } else {
5560         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
5561         unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
5562         ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
5563       }
5564 
5565       InstructionList.push_back(I);
5566       break;
5567     }
5568     case bitc::FUNC_CODE_INST_CMPXCHG: {
5569       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
5570       // failure_ordering, weak, align?]
5571       const size_t NumRecords = Record.size();
5572       unsigned OpNum = 0;
5573       Value *Ptr = nullptr;
5574       unsigned PtrTypeID;
5575       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))
5576         return error("Invalid record");
5577 
5578       if (!isa<PointerType>(Ptr->getType()))
5579         return error("Cmpxchg operand is not a pointer type");
5580 
5581       Value *Cmp = nullptr;
5582       unsigned CmpTypeID;
5583       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID))
5584         return error("Invalid record");
5585 
5586       Value *Val = nullptr;
5587       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val))
5588         return error("Invalid record");
5589 
5590       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
5591         return error("Invalid record");
5592 
5593       const bool IsVol = Record[OpNum];
5594 
5595       const AtomicOrdering SuccessOrdering =
5596           getDecodedOrdering(Record[OpNum + 1]);
5597       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
5598         return error("Invalid cmpxchg success ordering");
5599 
5600       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5601 
5602       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5603         return Err;
5604 
5605       const AtomicOrdering FailureOrdering =
5606           getDecodedOrdering(Record[OpNum + 3]);
5607       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
5608         return error("Invalid cmpxchg failure ordering");
5609 
5610       const bool IsWeak = Record[OpNum + 4];
5611 
5612       MaybeAlign Alignment;
5613 
5614       if (NumRecords == (OpNum + 6)) {
5615         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
5616           return Err;
5617       }
5618       if (!Alignment)
5619         Alignment =
5620             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5621 
5622       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
5623                                 FailureOrdering, SSID);
5624       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
5625       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
5626 
5627       unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
5628       ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
5629 
5630       InstructionList.push_back(I);
5631       break;
5632     }
5633     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
5634     case bitc::FUNC_CODE_INST_ATOMICRMW: {
5635       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
5636       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
5637       const size_t NumRecords = Record.size();
5638       unsigned OpNum = 0;
5639 
5640       Value *Ptr = nullptr;
5641       unsigned PtrTypeID;
5642       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))
5643         return error("Invalid record");
5644 
5645       if (!isa<PointerType>(Ptr->getType()))
5646         return error("Invalid record");
5647 
5648       Value *Val = nullptr;
5649       unsigned ValTypeID = InvalidTypeID;
5650       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
5651         ValTypeID = getContainedTypeID(PtrTypeID);
5652         if (popValue(Record, OpNum, NextValueNo,
5653                      getTypeByID(ValTypeID), ValTypeID, Val))
5654           return error("Invalid record");
5655       } else {
5656         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID))
5657           return error("Invalid record");
5658       }
5659 
5660       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
5661         return error("Invalid record");
5662 
5663       const AtomicRMWInst::BinOp Operation =
5664           getDecodedRMWOperation(Record[OpNum]);
5665       if (Operation < AtomicRMWInst::FIRST_BINOP ||
5666           Operation > AtomicRMWInst::LAST_BINOP)
5667         return error("Invalid record");
5668 
5669       const bool IsVol = Record[OpNum + 1];
5670 
5671       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5672       if (Ordering == AtomicOrdering::NotAtomic ||
5673           Ordering == AtomicOrdering::Unordered)
5674         return error("Invalid record");
5675 
5676       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5677 
5678       MaybeAlign Alignment;
5679 
5680       if (NumRecords == (OpNum + 5)) {
5681         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
5682           return Err;
5683       }
5684 
5685       if (!Alignment)
5686         Alignment =
5687             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
5688 
5689       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
5690       ResTypeID = ValTypeID;
5691       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
5692 
5693       InstructionList.push_back(I);
5694       break;
5695     }
5696     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
5697       if (2 != Record.size())
5698         return error("Invalid record");
5699       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5700       if (Ordering == AtomicOrdering::NotAtomic ||
5701           Ordering == AtomicOrdering::Unordered ||
5702           Ordering == AtomicOrdering::Monotonic)
5703         return error("Invalid record");
5704       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
5705       I = new FenceInst(Context, Ordering, SSID);
5706       InstructionList.push_back(I);
5707       break;
5708     }
5709     case bitc::FUNC_CODE_INST_CALL: {
5710       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5711       if (Record.size() < 3)
5712         return error("Invalid record");
5713 
5714       unsigned OpNum = 0;
5715       AttributeList PAL = getAttributes(Record[OpNum++]);
5716       unsigned CCInfo = Record[OpNum++];
5717 
5718       FastMathFlags FMF;
5719       if ((CCInfo >> bitc::CALL_FMF) & 1) {
5720         FMF = getDecodedFastMathFlags(Record[OpNum++]);
5721         if (!FMF.any())
5722           return error("Fast math flags indicator set for call with no FMF");
5723       }
5724 
5725       unsigned FTyID = InvalidTypeID;
5726       FunctionType *FTy = nullptr;
5727       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5728         FTyID = Record[OpNum++];
5729         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5730         if (!FTy)
5731           return error("Explicit call type is not a function type");
5732       }
5733 
5734       Value *Callee;
5735       unsigned CalleeTypeID;
5736       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID))
5737         return error("Invalid record");
5738 
5739       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5740       if (!OpTy)
5741         return error("Callee is not a pointer type");
5742       if (!FTy) {
5743         FTyID = getContainedTypeID(CalleeTypeID);
5744         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5745         if (!FTy)
5746           return error("Callee is not of pointer to function type");
5747       } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
5748         return error("Explicit call type does not match pointee type of "
5749                      "callee operand");
5750       if (Record.size() < FTy->getNumParams() + OpNum)
5751         return error("Insufficient operands to call");
5752 
5753       SmallVector<Value*, 16> Args;
5754       SmallVector<unsigned, 16> ArgTyIDs;
5755       // Read the fixed params.
5756       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5757         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5758         if (FTy->getParamType(i)->isLabelTy())
5759           Args.push_back(getBasicBlock(Record[OpNum]));
5760         else
5761           Args.push_back(getValue(Record, OpNum, NextValueNo,
5762                                   FTy->getParamType(i), ArgTyID));
5763         ArgTyIDs.push_back(ArgTyID);
5764         if (!Args.back())
5765           return error("Invalid record");
5766       }
5767 
5768       // Read type/value pairs for varargs params.
5769       if (!FTy->isVarArg()) {
5770         if (OpNum != Record.size())
5771           return error("Invalid record");
5772       } else {
5773         while (OpNum != Record.size()) {
5774           Value *Op;
5775           unsigned OpTypeID;
5776           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))
5777             return error("Invalid record");
5778           Args.push_back(Op);
5779           ArgTyIDs.push_back(OpTypeID);
5780         }
5781       }
5782 
5783       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5784       ResTypeID = getContainedTypeID(FTyID);
5785       OperandBundles.clear();
5786       InstructionList.push_back(I);
5787       cast<CallInst>(I)->setCallingConv(
5788           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5789       CallInst::TailCallKind TCK = CallInst::TCK_None;
5790       if (CCInfo & 1 << bitc::CALL_TAIL)
5791         TCK = CallInst::TCK_Tail;
5792       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5793         TCK = CallInst::TCK_MustTail;
5794       if (CCInfo & (1 << bitc::CALL_NOTAIL))
5795         TCK = CallInst::TCK_NoTail;
5796       cast<CallInst>(I)->setTailCallKind(TCK);
5797       cast<CallInst>(I)->setAttributes(PAL);
5798       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
5799         I->deleteValue();
5800         return Err;
5801       }
5802       if (FMF.any()) {
5803         if (!isa<FPMathOperator>(I))
5804           return error("Fast-math-flags specified for call without "
5805                        "floating-point scalar or vector return type");
5806         I->setFastMathFlags(FMF);
5807       }
5808       break;
5809     }
5810     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5811       if (Record.size() < 3)
5812         return error("Invalid record");
5813       unsigned OpTyID = Record[0];
5814       Type *OpTy = getTypeByID(OpTyID);
5815       Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID);
5816       ResTypeID = Record[2];
5817       Type *ResTy = getTypeByID(ResTypeID);
5818       if (!OpTy || !Op || !ResTy)
5819         return error("Invalid record");
5820       I = new VAArgInst(Op, ResTy);
5821       InstructionList.push_back(I);
5822       break;
5823     }
5824 
5825     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5826       // A call or an invoke can be optionally prefixed with some variable
5827       // number of operand bundle blocks.  These blocks are read into
5828       // OperandBundles and consumed at the next call or invoke instruction.
5829 
5830       if (Record.empty() || Record[0] >= BundleTags.size())
5831         return error("Invalid record");
5832 
5833       std::vector<Value *> Inputs;
5834 
5835       unsigned OpNum = 1;
5836       while (OpNum != Record.size()) {
5837         Value *Op;
5838         unsigned OpTypeID;
5839         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))
5840           return error("Invalid record");
5841         Inputs.push_back(Op);
5842       }
5843 
5844       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5845       continue;
5846     }
5847 
5848     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
5849       unsigned OpNum = 0;
5850       Value *Op = nullptr;
5851       unsigned OpTypeID;
5852       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))
5853         return error("Invalid record");
5854       if (OpNum != Record.size())
5855         return error("Invalid record");
5856 
5857       I = new FreezeInst(Op);
5858       ResTypeID = OpTypeID;
5859       InstructionList.push_back(I);
5860       break;
5861     }
5862     }
5863 
5864     // Add instruction to end of current BB.  If there is no current BB, reject
5865     // this file.
5866     if (!CurBB) {
5867       I->deleteValue();
5868       return error("Invalid instruction with no BB");
5869     }
5870     if (!OperandBundles.empty()) {
5871       I->deleteValue();
5872       return error("Operand bundles found with no consumer");
5873     }
5874     CurBB->getInstList().push_back(I);
5875 
5876     // If this was a terminator instruction, move to the next block.
5877     if (I->isTerminator()) {
5878       ++CurBBNo;
5879       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5880     }
5881 
5882     // Non-void values get registered in the value table for future use.
5883     if (!I->getType()->isVoidTy()) {
5884       assert(I->getType() == getTypeByID(ResTypeID) &&
5885              "Incorrect result type ID");
5886       if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
5887         return Err;
5888     }
5889   }
5890 
5891 OutOfRecordLoop:
5892 
5893   if (!OperandBundles.empty())
5894     return error("Operand bundles found with no consumer");
5895 
5896   // Check the function list for unresolved values.
5897   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5898     if (!A->getParent()) {
5899       // We found at least one unresolved value.  Nuke them all to avoid leaks.
5900       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5901         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5902           A->replaceAllUsesWith(UndefValue::get(A->getType()));
5903           delete A;
5904         }
5905       }
5906       return error("Never resolved value found in function");
5907     }
5908   }
5909 
5910   // Unexpected unresolved metadata about to be dropped.
5911   if (MDLoader->hasFwdRefs())
5912     return error("Invalid function metadata: outgoing forward refs");
5913 
5914   // Trim the value list down to the size it was before we parsed this function.
5915   ValueList.shrinkTo(ModuleValueListSize);
5916   MDLoader->shrinkTo(ModuleMDLoaderSize);
5917   std::vector<BasicBlock*>().swap(FunctionBBs);
5918   return Error::success();
5919 }
5920 
5921 /// Find the function body in the bitcode stream
5922 Error BitcodeReader::findFunctionInStream(
5923     Function *F,
5924     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5925   while (DeferredFunctionInfoIterator->second == 0) {
5926     // This is the fallback handling for the old format bitcode that
5927     // didn't contain the function index in the VST, or when we have
5928     // an anonymous function which would not have a VST entry.
5929     // Assert that we have one of those two cases.
5930     assert(VSTOffset == 0 || !F->hasName());
5931     // Parse the next body in the stream and set its position in the
5932     // DeferredFunctionInfo map.
5933     if (Error Err = rememberAndSkipFunctionBodies())
5934       return Err;
5935   }
5936   return Error::success();
5937 }
5938 
5939 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
5940   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
5941     return SyncScope::ID(Val);
5942   if (Val >= SSIDs.size())
5943     return SyncScope::System; // Map unknown synchronization scopes to system.
5944   return SSIDs[Val];
5945 }
5946 
5947 //===----------------------------------------------------------------------===//
5948 // GVMaterializer implementation
5949 //===----------------------------------------------------------------------===//
5950 
5951 Error BitcodeReader::materialize(GlobalValue *GV) {
5952   Function *F = dyn_cast<Function>(GV);
5953   // If it's not a function or is already material, ignore the request.
5954   if (!F || !F->isMaterializable())
5955     return Error::success();
5956 
5957   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5958   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5959   // If its position is recorded as 0, its body is somewhere in the stream
5960   // but we haven't seen it yet.
5961   if (DFII->second == 0)
5962     if (Error Err = findFunctionInStream(F, DFII))
5963       return Err;
5964 
5965   // Materialize metadata before parsing any function bodies.
5966   if (Error Err = materializeMetadata())
5967     return Err;
5968 
5969   // Move the bit stream to the saved position of the deferred function body.
5970   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
5971     return JumpFailed;
5972   if (Error Err = parseFunctionBody(F))
5973     return Err;
5974   F->setIsMaterializable(false);
5975 
5976   if (StripDebugInfo)
5977     stripDebugInfo(*F);
5978 
5979   // Upgrade any old intrinsic calls in the function.
5980   for (auto &I : UpgradedIntrinsics) {
5981     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
5982       if (CallInst *CI = dyn_cast<CallInst>(U))
5983         UpgradeIntrinsicCall(CI, I.second);
5984   }
5985 
5986   // Update calls to the remangled intrinsics
5987   for (auto &I : RemangledIntrinsics)
5988     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
5989       // Don't expect any other users than call sites
5990       cast<CallBase>(U)->setCalledFunction(I.second);
5991 
5992   // Finish fn->subprogram upgrade for materialized functions.
5993   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
5994     F->setSubprogram(SP);
5995 
5996   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
5997   if (!MDLoader->isStrippingTBAA()) {
5998     for (auto &I : instructions(F)) {
5999       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
6000       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
6001         continue;
6002       MDLoader->setStripTBAA(true);
6003       stripTBAA(F->getParent());
6004     }
6005   }
6006 
6007   for (auto &I : instructions(F)) {
6008     // "Upgrade" older incorrect branch weights by dropping them.
6009     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
6010       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
6011         MDString *MDS = cast<MDString>(MD->getOperand(0));
6012         StringRef ProfName = MDS->getString();
6013         // Check consistency of !prof branch_weights metadata.
6014         if (!ProfName.equals("branch_weights"))
6015           continue;
6016         unsigned ExpectedNumOperands = 0;
6017         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
6018           ExpectedNumOperands = BI->getNumSuccessors();
6019         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
6020           ExpectedNumOperands = SI->getNumSuccessors();
6021         else if (isa<CallInst>(&I))
6022           ExpectedNumOperands = 1;
6023         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
6024           ExpectedNumOperands = IBI->getNumDestinations();
6025         else if (isa<SelectInst>(&I))
6026           ExpectedNumOperands = 2;
6027         else
6028           continue; // ignore and continue.
6029 
6030         // If branch weight doesn't match, just strip branch weight.
6031         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
6032           I.setMetadata(LLVMContext::MD_prof, nullptr);
6033       }
6034     }
6035 
6036     // Remove incompatible attributes on function calls.
6037     if (auto *CI = dyn_cast<CallBase>(&I)) {
6038       CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
6039           CI->getFunctionType()->getReturnType()));
6040 
6041       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
6042         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
6043                                         CI->getArgOperand(ArgNo)->getType()));
6044     }
6045   }
6046 
6047   // Look for functions that rely on old function attribute behavior.
6048   UpgradeFunctionAttributes(*F);
6049 
6050   // Bring in any functions that this function forward-referenced via
6051   // blockaddresses.
6052   return materializeForwardReferencedFunctions();
6053 }
6054 
6055 Error BitcodeReader::materializeModule() {
6056   if (Error Err = materializeMetadata())
6057     return Err;
6058 
6059   // Promise to materialize all forward references.
6060   WillMaterializeAllForwardRefs = true;
6061 
6062   // Iterate over the module, deserializing any functions that are still on
6063   // disk.
6064   for (Function &F : *TheModule) {
6065     if (Error Err = materialize(&F))
6066       return Err;
6067   }
6068   // At this point, if there are any function bodies, parse the rest of
6069   // the bits in the module past the last function block we have recorded
6070   // through either lazy scanning or the VST.
6071   if (LastFunctionBlockBit || NextUnreadBit)
6072     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
6073                                     ? LastFunctionBlockBit
6074                                     : NextUnreadBit))
6075       return Err;
6076 
6077   // Check that all block address forward references got resolved (as we
6078   // promised above).
6079   if (!BasicBlockFwdRefs.empty())
6080     return error("Never resolved function from blockaddress");
6081 
6082   // Upgrade any intrinsic calls that slipped through (should not happen!) and
6083   // delete the old functions to clean up. We can't do this unless the entire
6084   // module is materialized because there could always be another function body
6085   // with calls to the old function.
6086   for (auto &I : UpgradedIntrinsics) {
6087     for (auto *U : I.first->users()) {
6088       if (CallInst *CI = dyn_cast<CallInst>(U))
6089         UpgradeIntrinsicCall(CI, I.second);
6090     }
6091     if (!I.first->use_empty())
6092       I.first->replaceAllUsesWith(I.second);
6093     I.first->eraseFromParent();
6094   }
6095   UpgradedIntrinsics.clear();
6096   // Do the same for remangled intrinsics
6097   for (auto &I : RemangledIntrinsics) {
6098     I.first->replaceAllUsesWith(I.second);
6099     I.first->eraseFromParent();
6100   }
6101   RemangledIntrinsics.clear();
6102 
6103   UpgradeDebugInfo(*TheModule);
6104 
6105   UpgradeModuleFlags(*TheModule);
6106 
6107   UpgradeARCRuntime(*TheModule);
6108 
6109   return Error::success();
6110 }
6111 
6112 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
6113   return IdentifiedStructTypes;
6114 }
6115 
6116 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
6117     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
6118     StringRef ModulePath, unsigned ModuleId)
6119     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
6120       ModulePath(ModulePath), ModuleId(ModuleId) {}
6121 
6122 void ModuleSummaryIndexBitcodeReader::addThisModule() {
6123   TheIndex.addModule(ModulePath, ModuleId);
6124 }
6125 
6126 ModuleSummaryIndex::ModuleInfo *
6127 ModuleSummaryIndexBitcodeReader::getThisModule() {
6128   return TheIndex.getModule(ModulePath);
6129 }
6130 
6131 std::pair<ValueInfo, GlobalValue::GUID>
6132 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
6133   auto VGI = ValueIdToValueInfoMap[ValueId];
6134   assert(VGI.first);
6135   return VGI;
6136 }
6137 
6138 void ModuleSummaryIndexBitcodeReader::setValueGUID(
6139     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
6140     StringRef SourceFileName) {
6141   std::string GlobalId =
6142       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
6143   auto ValueGUID = GlobalValue::getGUID(GlobalId);
6144   auto OriginalNameID = ValueGUID;
6145   if (GlobalValue::isLocalLinkage(Linkage))
6146     OriginalNameID = GlobalValue::getGUID(ValueName);
6147   if (PrintSummaryGUIDs)
6148     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
6149            << ValueName << "\n";
6150 
6151   // UseStrtab is false for legacy summary formats and value names are
6152   // created on stack. In that case we save the name in a string saver in
6153   // the index so that the value name can be recorded.
6154   ValueIdToValueInfoMap[ValueID] = std::make_pair(
6155       TheIndex.getOrInsertValueInfo(
6156           ValueGUID,
6157           UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
6158       OriginalNameID);
6159 }
6160 
6161 // Specialized value symbol table parser used when reading module index
6162 // blocks where we don't actually create global values. The parsed information
6163 // is saved in the bitcode reader for use when later parsing summaries.
6164 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
6165     uint64_t Offset,
6166     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
6167   // With a strtab the VST is not required to parse the summary.
6168   if (UseStrtab)
6169     return Error::success();
6170 
6171   assert(Offset > 0 && "Expected non-zero VST offset");
6172   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
6173   if (!MaybeCurrentBit)
6174     return MaybeCurrentBit.takeError();
6175   uint64_t CurrentBit = MaybeCurrentBit.get();
6176 
6177   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
6178     return Err;
6179 
6180   SmallVector<uint64_t, 64> Record;
6181 
6182   // Read all the records for this value table.
6183   SmallString<128> ValueName;
6184 
6185   while (true) {
6186     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6187     if (!MaybeEntry)
6188       return MaybeEntry.takeError();
6189     BitstreamEntry Entry = MaybeEntry.get();
6190 
6191     switch (Entry.Kind) {
6192     case BitstreamEntry::SubBlock: // Handled for us already.
6193     case BitstreamEntry::Error:
6194       return error("Malformed block");
6195     case BitstreamEntry::EndBlock:
6196       // Done parsing VST, jump back to wherever we came from.
6197       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
6198         return JumpFailed;
6199       return Error::success();
6200     case BitstreamEntry::Record:
6201       // The interesting case.
6202       break;
6203     }
6204 
6205     // Read a record.
6206     Record.clear();
6207     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6208     if (!MaybeRecord)
6209       return MaybeRecord.takeError();
6210     switch (MaybeRecord.get()) {
6211     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
6212       break;
6213     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
6214       if (convertToString(Record, 1, ValueName))
6215         return error("Invalid record");
6216       unsigned ValueID = Record[0];
6217       assert(!SourceFileName.empty());
6218       auto VLI = ValueIdToLinkageMap.find(ValueID);
6219       assert(VLI != ValueIdToLinkageMap.end() &&
6220              "No linkage found for VST entry?");
6221       auto Linkage = VLI->second;
6222       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
6223       ValueName.clear();
6224       break;
6225     }
6226     case bitc::VST_CODE_FNENTRY: {
6227       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
6228       if (convertToString(Record, 2, ValueName))
6229         return error("Invalid record");
6230       unsigned ValueID = Record[0];
6231       assert(!SourceFileName.empty());
6232       auto VLI = ValueIdToLinkageMap.find(ValueID);
6233       assert(VLI != ValueIdToLinkageMap.end() &&
6234              "No linkage found for VST entry?");
6235       auto Linkage = VLI->second;
6236       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
6237       ValueName.clear();
6238       break;
6239     }
6240     case bitc::VST_CODE_COMBINED_ENTRY: {
6241       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
6242       unsigned ValueID = Record[0];
6243       GlobalValue::GUID RefGUID = Record[1];
6244       // The "original name", which is the second value of the pair will be
6245       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
6246       ValueIdToValueInfoMap[ValueID] =
6247           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
6248       break;
6249     }
6250     }
6251   }
6252 }
6253 
6254 // Parse just the blocks needed for building the index out of the module.
6255 // At the end of this routine the module Index is populated with a map
6256 // from global value id to GlobalValueSummary objects.
6257 Error ModuleSummaryIndexBitcodeReader::parseModule() {
6258   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6259     return Err;
6260 
6261   SmallVector<uint64_t, 64> Record;
6262   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
6263   unsigned ValueId = 0;
6264 
6265   // Read the index for this module.
6266   while (true) {
6267     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6268     if (!MaybeEntry)
6269       return MaybeEntry.takeError();
6270     llvm::BitstreamEntry Entry = MaybeEntry.get();
6271 
6272     switch (Entry.Kind) {
6273     case BitstreamEntry::Error:
6274       return error("Malformed block");
6275     case BitstreamEntry::EndBlock:
6276       return Error::success();
6277 
6278     case BitstreamEntry::SubBlock:
6279       switch (Entry.ID) {
6280       default: // Skip unknown content.
6281         if (Error Err = Stream.SkipBlock())
6282           return Err;
6283         break;
6284       case bitc::BLOCKINFO_BLOCK_ID:
6285         // Need to parse these to get abbrev ids (e.g. for VST)
6286         if (Error Err = readBlockInfo())
6287           return Err;
6288         break;
6289       case bitc::VALUE_SYMTAB_BLOCK_ID:
6290         // Should have been parsed earlier via VSTOffset, unless there
6291         // is no summary section.
6292         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
6293                 !SeenGlobalValSummary) &&
6294                "Expected early VST parse via VSTOffset record");
6295         if (Error Err = Stream.SkipBlock())
6296           return Err;
6297         break;
6298       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
6299       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
6300         // Add the module if it is a per-module index (has a source file name).
6301         if (!SourceFileName.empty())
6302           addThisModule();
6303         assert(!SeenValueSymbolTable &&
6304                "Already read VST when parsing summary block?");
6305         // We might not have a VST if there were no values in the
6306         // summary. An empty summary block generated when we are
6307         // performing ThinLTO compiles so we don't later invoke
6308         // the regular LTO process on them.
6309         if (VSTOffset > 0) {
6310           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
6311             return Err;
6312           SeenValueSymbolTable = true;
6313         }
6314         SeenGlobalValSummary = true;
6315         if (Error Err = parseEntireSummary(Entry.ID))
6316           return Err;
6317         break;
6318       case bitc::MODULE_STRTAB_BLOCK_ID:
6319         if (Error Err = parseModuleStringTable())
6320           return Err;
6321         break;
6322       }
6323       continue;
6324 
6325     case BitstreamEntry::Record: {
6326         Record.clear();
6327         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6328         if (!MaybeBitCode)
6329           return MaybeBitCode.takeError();
6330         switch (MaybeBitCode.get()) {
6331         default:
6332           break; // Default behavior, ignore unknown content.
6333         case bitc::MODULE_CODE_VERSION: {
6334           if (Error Err = parseVersionRecord(Record).takeError())
6335             return Err;
6336           break;
6337         }
6338         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
6339         case bitc::MODULE_CODE_SOURCE_FILENAME: {
6340           SmallString<128> ValueName;
6341           if (convertToString(Record, 0, ValueName))
6342             return error("Invalid record");
6343           SourceFileName = ValueName.c_str();
6344           break;
6345         }
6346         /// MODULE_CODE_HASH: [5*i32]
6347         case bitc::MODULE_CODE_HASH: {
6348           if (Record.size() != 5)
6349             return error("Invalid hash length " + Twine(Record.size()).str());
6350           auto &Hash = getThisModule()->second.second;
6351           int Pos = 0;
6352           for (auto &Val : Record) {
6353             assert(!(Val >> 32) && "Unexpected high bits set");
6354             Hash[Pos++] = Val;
6355           }
6356           break;
6357         }
6358         /// MODULE_CODE_VSTOFFSET: [offset]
6359         case bitc::MODULE_CODE_VSTOFFSET:
6360           if (Record.empty())
6361             return error("Invalid record");
6362           // Note that we subtract 1 here because the offset is relative to one
6363           // word before the start of the identification or module block, which
6364           // was historically always the start of the regular bitcode header.
6365           VSTOffset = Record[0] - 1;
6366           break;
6367         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
6368         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
6369         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
6370         // v2: [strtab offset, strtab size, v1]
6371         case bitc::MODULE_CODE_GLOBALVAR:
6372         case bitc::MODULE_CODE_FUNCTION:
6373         case bitc::MODULE_CODE_ALIAS: {
6374           StringRef Name;
6375           ArrayRef<uint64_t> GVRecord;
6376           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
6377           if (GVRecord.size() <= 3)
6378             return error("Invalid record");
6379           uint64_t RawLinkage = GVRecord[3];
6380           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6381           if (!UseStrtab) {
6382             ValueIdToLinkageMap[ValueId++] = Linkage;
6383             break;
6384           }
6385 
6386           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
6387           break;
6388         }
6389         }
6390       }
6391       continue;
6392     }
6393   }
6394 }
6395 
6396 std::vector<ValueInfo>
6397 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
6398   std::vector<ValueInfo> Ret;
6399   Ret.reserve(Record.size());
6400   for (uint64_t RefValueId : Record)
6401     Ret.push_back(getValueInfoFromValueId(RefValueId).first);
6402   return Ret;
6403 }
6404 
6405 std::vector<FunctionSummary::EdgeTy>
6406 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
6407                                               bool IsOldProfileFormat,
6408                                               bool HasProfile, bool HasRelBF) {
6409   std::vector<FunctionSummary::EdgeTy> Ret;
6410   Ret.reserve(Record.size());
6411   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
6412     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
6413     uint64_t RelBF = 0;
6414     ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6415     if (IsOldProfileFormat) {
6416       I += 1; // Skip old callsitecount field
6417       if (HasProfile)
6418         I += 1; // Skip old profilecount field
6419     } else if (HasProfile)
6420       Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
6421     else if (HasRelBF)
6422       RelBF = Record[++I];
6423     Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
6424   }
6425   return Ret;
6426 }
6427 
6428 static void
6429 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
6430                                        WholeProgramDevirtResolution &Wpd) {
6431   uint64_t ArgNum = Record[Slot++];
6432   WholeProgramDevirtResolution::ByArg &B =
6433       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
6434   Slot += ArgNum;
6435 
6436   B.TheKind =
6437       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
6438   B.Info = Record[Slot++];
6439   B.Byte = Record[Slot++];
6440   B.Bit = Record[Slot++];
6441 }
6442 
6443 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
6444                                               StringRef Strtab, size_t &Slot,
6445                                               TypeIdSummary &TypeId) {
6446   uint64_t Id = Record[Slot++];
6447   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
6448 
6449   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
6450   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
6451                         static_cast<size_t>(Record[Slot + 1])};
6452   Slot += 2;
6453 
6454   uint64_t ResByArgNum = Record[Slot++];
6455   for (uint64_t I = 0; I != ResByArgNum; ++I)
6456     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
6457 }
6458 
6459 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
6460                                      StringRef Strtab,
6461                                      ModuleSummaryIndex &TheIndex) {
6462   size_t Slot = 0;
6463   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
6464       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
6465   Slot += 2;
6466 
6467   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
6468   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
6469   TypeId.TTRes.AlignLog2 = Record[Slot++];
6470   TypeId.TTRes.SizeM1 = Record[Slot++];
6471   TypeId.TTRes.BitMask = Record[Slot++];
6472   TypeId.TTRes.InlineBits = Record[Slot++];
6473 
6474   while (Slot < Record.size())
6475     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
6476 }
6477 
6478 std::vector<FunctionSummary::ParamAccess>
6479 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
6480   auto ReadRange = [&]() {
6481     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
6482                 BitcodeReader::decodeSignRotatedValue(Record.front()));
6483     Record = Record.drop_front();
6484     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
6485                 BitcodeReader::decodeSignRotatedValue(Record.front()));
6486     Record = Record.drop_front();
6487     ConstantRange Range{Lower, Upper};
6488     assert(!Range.isFullSet());
6489     assert(!Range.isUpperSignWrapped());
6490     return Range;
6491   };
6492 
6493   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6494   while (!Record.empty()) {
6495     PendingParamAccesses.emplace_back();
6496     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
6497     ParamAccess.ParamNo = Record.front();
6498     Record = Record.drop_front();
6499     ParamAccess.Use = ReadRange();
6500     ParamAccess.Calls.resize(Record.front());
6501     Record = Record.drop_front();
6502     for (auto &Call : ParamAccess.Calls) {
6503       Call.ParamNo = Record.front();
6504       Record = Record.drop_front();
6505       Call.Callee = getValueInfoFromValueId(Record.front()).first;
6506       Record = Record.drop_front();
6507       Call.Offsets = ReadRange();
6508     }
6509   }
6510   return PendingParamAccesses;
6511 }
6512 
6513 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
6514     ArrayRef<uint64_t> Record, size_t &Slot,
6515     TypeIdCompatibleVtableInfo &TypeId) {
6516   uint64_t Offset = Record[Slot++];
6517   ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first;
6518   TypeId.push_back({Offset, Callee});
6519 }
6520 
6521 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
6522     ArrayRef<uint64_t> Record) {
6523   size_t Slot = 0;
6524   TypeIdCompatibleVtableInfo &TypeId =
6525       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
6526           {Strtab.data() + Record[Slot],
6527            static_cast<size_t>(Record[Slot + 1])});
6528   Slot += 2;
6529 
6530   while (Slot < Record.size())
6531     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
6532 }
6533 
6534 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
6535                            unsigned WOCnt) {
6536   // Readonly and writeonly refs are in the end of the refs list.
6537   assert(ROCnt + WOCnt <= Refs.size());
6538   unsigned FirstWORef = Refs.size() - WOCnt;
6539   unsigned RefNo = FirstWORef - ROCnt;
6540   for (; RefNo < FirstWORef; ++RefNo)
6541     Refs[RefNo].setReadOnly();
6542   for (; RefNo < Refs.size(); ++RefNo)
6543     Refs[RefNo].setWriteOnly();
6544 }
6545 
6546 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
6547 // objects in the index.
6548 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
6549   if (Error Err = Stream.EnterSubBlock(ID))
6550     return Err;
6551   SmallVector<uint64_t, 64> Record;
6552 
6553   // Parse version
6554   {
6555     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6556     if (!MaybeEntry)
6557       return MaybeEntry.takeError();
6558     BitstreamEntry Entry = MaybeEntry.get();
6559 
6560     if (Entry.Kind != BitstreamEntry::Record)
6561       return error("Invalid Summary Block: record for version expected");
6562     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6563     if (!MaybeRecord)
6564       return MaybeRecord.takeError();
6565     if (MaybeRecord.get() != bitc::FS_VERSION)
6566       return error("Invalid Summary Block: version expected");
6567   }
6568   const uint64_t Version = Record[0];
6569   const bool IsOldProfileFormat = Version == 1;
6570   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
6571     return error("Invalid summary version " + Twine(Version) +
6572                  ". Version should be in the range [1-" +
6573                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
6574                  "].");
6575   Record.clear();
6576 
6577   // Keep around the last seen summary to be used when we see an optional
6578   // "OriginalName" attachement.
6579   GlobalValueSummary *LastSeenSummary = nullptr;
6580   GlobalValue::GUID LastSeenGUID = 0;
6581 
6582   // We can expect to see any number of type ID information records before
6583   // each function summary records; these variables store the information
6584   // collected so far so that it can be used to create the summary object.
6585   std::vector<GlobalValue::GUID> PendingTypeTests;
6586   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
6587       PendingTypeCheckedLoadVCalls;
6588   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
6589       PendingTypeCheckedLoadConstVCalls;
6590   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6591 
6592   while (true) {
6593     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6594     if (!MaybeEntry)
6595       return MaybeEntry.takeError();
6596     BitstreamEntry Entry = MaybeEntry.get();
6597 
6598     switch (Entry.Kind) {
6599     case BitstreamEntry::SubBlock: // Handled for us already.
6600     case BitstreamEntry::Error:
6601       return error("Malformed block");
6602     case BitstreamEntry::EndBlock:
6603       return Error::success();
6604     case BitstreamEntry::Record:
6605       // The interesting case.
6606       break;
6607     }
6608 
6609     // Read a record. The record format depends on whether this
6610     // is a per-module index or a combined index file. In the per-module
6611     // case the records contain the associated value's ID for correlation
6612     // with VST entries. In the combined index the correlation is done
6613     // via the bitcode offset of the summary records (which were saved
6614     // in the combined index VST entries). The records also contain
6615     // information used for ThinLTO renaming and importing.
6616     Record.clear();
6617     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6618     if (!MaybeBitCode)
6619       return MaybeBitCode.takeError();
6620     switch (unsigned BitCode = MaybeBitCode.get()) {
6621     default: // Default behavior: ignore.
6622       break;
6623     case bitc::FS_FLAGS: {  // [flags]
6624       TheIndex.setFlags(Record[0]);
6625       break;
6626     }
6627     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
6628       uint64_t ValueID = Record[0];
6629       GlobalValue::GUID RefGUID = Record[1];
6630       ValueIdToValueInfoMap[ValueID] =
6631           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
6632       break;
6633     }
6634     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
6635     //                numrefs x valueid, n x (valueid)]
6636     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
6637     //                        numrefs x valueid,
6638     //                        n x (valueid, hotness)]
6639     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
6640     //                      numrefs x valueid,
6641     //                      n x (valueid, relblockfreq)]
6642     case bitc::FS_PERMODULE:
6643     case bitc::FS_PERMODULE_RELBF:
6644     case bitc::FS_PERMODULE_PROFILE: {
6645       unsigned ValueID = Record[0];
6646       uint64_t RawFlags = Record[1];
6647       unsigned InstCount = Record[2];
6648       uint64_t RawFunFlags = 0;
6649       unsigned NumRefs = Record[3];
6650       unsigned NumRORefs = 0, NumWORefs = 0;
6651       int RefListStartIndex = 4;
6652       if (Version >= 4) {
6653         RawFunFlags = Record[3];
6654         NumRefs = Record[4];
6655         RefListStartIndex = 5;
6656         if (Version >= 5) {
6657           NumRORefs = Record[5];
6658           RefListStartIndex = 6;
6659           if (Version >= 7) {
6660             NumWORefs = Record[6];
6661             RefListStartIndex = 7;
6662           }
6663         }
6664       }
6665 
6666       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6667       // The module path string ref set in the summary must be owned by the
6668       // index's module string table. Since we don't have a module path
6669       // string table section in the per-module index, we create a single
6670       // module path string table entry with an empty (0) ID to take
6671       // ownership.
6672       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6673       assert(Record.size() >= RefListStartIndex + NumRefs &&
6674              "Record size inconsistent with number of references");
6675       std::vector<ValueInfo> Refs = makeRefList(
6676           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6677       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6678       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
6679       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
6680           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6681           IsOldProfileFormat, HasProfile, HasRelBF);
6682       setSpecialRefs(Refs, NumRORefs, NumWORefs);
6683       auto FS = std::make_unique<FunctionSummary>(
6684           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
6685           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
6686           std::move(PendingTypeTestAssumeVCalls),
6687           std::move(PendingTypeCheckedLoadVCalls),
6688           std::move(PendingTypeTestAssumeConstVCalls),
6689           std::move(PendingTypeCheckedLoadConstVCalls),
6690           std::move(PendingParamAccesses));
6691       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
6692       FS->setModulePath(getThisModule()->first());
6693       FS->setOriginalName(VIAndOriginalGUID.second);
6694       TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
6695       break;
6696     }
6697     // FS_ALIAS: [valueid, flags, valueid]
6698     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6699     // they expect all aliasee summaries to be available.
6700     case bitc::FS_ALIAS: {
6701       unsigned ValueID = Record[0];
6702       uint64_t RawFlags = Record[1];
6703       unsigned AliaseeID = Record[2];
6704       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6705       auto AS = std::make_unique<AliasSummary>(Flags);
6706       // The module path string ref set in the summary must be owned by the
6707       // index's module string table. Since we don't have a module path
6708       // string table section in the per-module index, we create a single
6709       // module path string table entry with an empty (0) ID to take
6710       // ownership.
6711       AS->setModulePath(getThisModule()->first());
6712 
6713       auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
6714       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
6715       if (!AliaseeInModule)
6716         return error("Alias expects aliasee summary to be parsed");
6717       AS->setAliasee(AliaseeVI, AliaseeInModule);
6718 
6719       auto GUID = getValueInfoFromValueId(ValueID);
6720       AS->setOriginalName(GUID.second);
6721       TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
6722       break;
6723     }
6724     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
6725     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6726       unsigned ValueID = Record[0];
6727       uint64_t RawFlags = Record[1];
6728       unsigned RefArrayStart = 2;
6729       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6730                                       /* WriteOnly */ false,
6731                                       /* Constant */ false,
6732                                       GlobalObject::VCallVisibilityPublic);
6733       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6734       if (Version >= 5) {
6735         GVF = getDecodedGVarFlags(Record[2]);
6736         RefArrayStart = 3;
6737       }
6738       std::vector<ValueInfo> Refs =
6739           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6740       auto FS =
6741           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6742       FS->setModulePath(getThisModule()->first());
6743       auto GUID = getValueInfoFromValueId(ValueID);
6744       FS->setOriginalName(GUID.second);
6745       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
6746       break;
6747     }
6748     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
6749     //                        numrefs, numrefs x valueid,
6750     //                        n x (valueid, offset)]
6751     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
6752       unsigned ValueID = Record[0];
6753       uint64_t RawFlags = Record[1];
6754       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
6755       unsigned NumRefs = Record[3];
6756       unsigned RefListStartIndex = 4;
6757       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
6758       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6759       std::vector<ValueInfo> Refs = makeRefList(
6760           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6761       VTableFuncList VTableFuncs;
6762       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
6763         ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6764         uint64_t Offset = Record[++I];
6765         VTableFuncs.push_back({Callee, Offset});
6766       }
6767       auto VS =
6768           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6769       VS->setModulePath(getThisModule()->first());
6770       VS->setVTableFuncs(VTableFuncs);
6771       auto GUID = getValueInfoFromValueId(ValueID);
6772       VS->setOriginalName(GUID.second);
6773       TheIndex.addGlobalValueSummary(GUID.first, std::move(VS));
6774       break;
6775     }
6776     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
6777     //               numrefs x valueid, n x (valueid)]
6778     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
6779     //                       numrefs x valueid, n x (valueid, hotness)]
6780     case bitc::FS_COMBINED:
6781     case bitc::FS_COMBINED_PROFILE: {
6782       unsigned ValueID = Record[0];
6783       uint64_t ModuleId = Record[1];
6784       uint64_t RawFlags = Record[2];
6785       unsigned InstCount = Record[3];
6786       uint64_t RawFunFlags = 0;
6787       uint64_t EntryCount = 0;
6788       unsigned NumRefs = Record[4];
6789       unsigned NumRORefs = 0, NumWORefs = 0;
6790       int RefListStartIndex = 5;
6791 
6792       if (Version >= 4) {
6793         RawFunFlags = Record[4];
6794         RefListStartIndex = 6;
6795         size_t NumRefsIndex = 5;
6796         if (Version >= 5) {
6797           unsigned NumRORefsOffset = 1;
6798           RefListStartIndex = 7;
6799           if (Version >= 6) {
6800             NumRefsIndex = 6;
6801             EntryCount = Record[5];
6802             RefListStartIndex = 8;
6803             if (Version >= 7) {
6804               RefListStartIndex = 9;
6805               NumWORefs = Record[8];
6806               NumRORefsOffset = 2;
6807             }
6808           }
6809           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
6810         }
6811         NumRefs = Record[NumRefsIndex];
6812       }
6813 
6814       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6815       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6816       assert(Record.size() >= RefListStartIndex + NumRefs &&
6817              "Record size inconsistent with number of references");
6818       std::vector<ValueInfo> Refs = makeRefList(
6819           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6820       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6821       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
6822           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6823           IsOldProfileFormat, HasProfile, false);
6824       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6825       setSpecialRefs(Refs, NumRORefs, NumWORefs);
6826       auto FS = std::make_unique<FunctionSummary>(
6827           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
6828           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
6829           std::move(PendingTypeTestAssumeVCalls),
6830           std::move(PendingTypeCheckedLoadVCalls),
6831           std::move(PendingTypeTestAssumeConstVCalls),
6832           std::move(PendingTypeCheckedLoadConstVCalls),
6833           std::move(PendingParamAccesses));
6834       LastSeenSummary = FS.get();
6835       LastSeenGUID = VI.getGUID();
6836       FS->setModulePath(ModuleIdMap[ModuleId]);
6837       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6838       break;
6839     }
6840     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6841     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6842     // they expect all aliasee summaries to be available.
6843     case bitc::FS_COMBINED_ALIAS: {
6844       unsigned ValueID = Record[0];
6845       uint64_t ModuleId = Record[1];
6846       uint64_t RawFlags = Record[2];
6847       unsigned AliaseeValueId = Record[3];
6848       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6849       auto AS = std::make_unique<AliasSummary>(Flags);
6850       LastSeenSummary = AS.get();
6851       AS->setModulePath(ModuleIdMap[ModuleId]);
6852 
6853       auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
6854       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
6855       AS->setAliasee(AliaseeVI, AliaseeInModule);
6856 
6857       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6858       LastSeenGUID = VI.getGUID();
6859       TheIndex.addGlobalValueSummary(VI, std::move(AS));
6860       break;
6861     }
6862     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6863     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6864       unsigned ValueID = Record[0];
6865       uint64_t ModuleId = Record[1];
6866       uint64_t RawFlags = Record[2];
6867       unsigned RefArrayStart = 3;
6868       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6869                                       /* WriteOnly */ false,
6870                                       /* Constant */ false,
6871                                       GlobalObject::VCallVisibilityPublic);
6872       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6873       if (Version >= 5) {
6874         GVF = getDecodedGVarFlags(Record[3]);
6875         RefArrayStart = 4;
6876       }
6877       std::vector<ValueInfo> Refs =
6878           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6879       auto FS =
6880           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6881       LastSeenSummary = FS.get();
6882       FS->setModulePath(ModuleIdMap[ModuleId]);
6883       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6884       LastSeenGUID = VI.getGUID();
6885       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6886       break;
6887     }
6888     // FS_COMBINED_ORIGINAL_NAME: [original_name]
6889     case bitc::FS_COMBINED_ORIGINAL_NAME: {
6890       uint64_t OriginalName = Record[0];
6891       if (!LastSeenSummary)
6892         return error("Name attachment that does not follow a combined record");
6893       LastSeenSummary->setOriginalName(OriginalName);
6894       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
6895       // Reset the LastSeenSummary
6896       LastSeenSummary = nullptr;
6897       LastSeenGUID = 0;
6898       break;
6899     }
6900     case bitc::FS_TYPE_TESTS:
6901       assert(PendingTypeTests.empty());
6902       llvm::append_range(PendingTypeTests, Record);
6903       break;
6904 
6905     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
6906       assert(PendingTypeTestAssumeVCalls.empty());
6907       for (unsigned I = 0; I != Record.size(); I += 2)
6908         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
6909       break;
6910 
6911     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
6912       assert(PendingTypeCheckedLoadVCalls.empty());
6913       for (unsigned I = 0; I != Record.size(); I += 2)
6914         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
6915       break;
6916 
6917     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
6918       PendingTypeTestAssumeConstVCalls.push_back(
6919           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6920       break;
6921 
6922     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
6923       PendingTypeCheckedLoadConstVCalls.push_back(
6924           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6925       break;
6926 
6927     case bitc::FS_CFI_FUNCTION_DEFS: {
6928       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
6929       for (unsigned I = 0; I != Record.size(); I += 2)
6930         CfiFunctionDefs.insert(
6931             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6932       break;
6933     }
6934 
6935     case bitc::FS_CFI_FUNCTION_DECLS: {
6936       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
6937       for (unsigned I = 0; I != Record.size(); I += 2)
6938         CfiFunctionDecls.insert(
6939             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6940       break;
6941     }
6942 
6943     case bitc::FS_TYPE_ID:
6944       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
6945       break;
6946 
6947     case bitc::FS_TYPE_ID_METADATA:
6948       parseTypeIdCompatibleVtableSummaryRecord(Record);
6949       break;
6950 
6951     case bitc::FS_BLOCK_COUNT:
6952       TheIndex.addBlockCount(Record[0]);
6953       break;
6954 
6955     case bitc::FS_PARAM_ACCESS: {
6956       PendingParamAccesses = parseParamAccesses(Record);
6957       break;
6958     }
6959     }
6960   }
6961   llvm_unreachable("Exit infinite loop");
6962 }
6963 
6964 // Parse the  module string table block into the Index.
6965 // This populates the ModulePathStringTable map in the index.
6966 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6967   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6968     return Err;
6969 
6970   SmallVector<uint64_t, 64> Record;
6971 
6972   SmallString<128> ModulePath;
6973   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
6974 
6975   while (true) {
6976     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6977     if (!MaybeEntry)
6978       return MaybeEntry.takeError();
6979     BitstreamEntry Entry = MaybeEntry.get();
6980 
6981     switch (Entry.Kind) {
6982     case BitstreamEntry::SubBlock: // Handled for us already.
6983     case BitstreamEntry::Error:
6984       return error("Malformed block");
6985     case BitstreamEntry::EndBlock:
6986       return Error::success();
6987     case BitstreamEntry::Record:
6988       // The interesting case.
6989       break;
6990     }
6991 
6992     Record.clear();
6993     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6994     if (!MaybeRecord)
6995       return MaybeRecord.takeError();
6996     switch (MaybeRecord.get()) {
6997     default: // Default behavior: ignore.
6998       break;
6999     case bitc::MST_CODE_ENTRY: {
7000       // MST_ENTRY: [modid, namechar x N]
7001       uint64_t ModuleId = Record[0];
7002 
7003       if (convertToString(Record, 1, ModulePath))
7004         return error("Invalid record");
7005 
7006       LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
7007       ModuleIdMap[ModuleId] = LastSeenModule->first();
7008 
7009       ModulePath.clear();
7010       break;
7011     }
7012     /// MST_CODE_HASH: [5*i32]
7013     case bitc::MST_CODE_HASH: {
7014       if (Record.size() != 5)
7015         return error("Invalid hash length " + Twine(Record.size()).str());
7016       if (!LastSeenModule)
7017         return error("Invalid hash that does not follow a module path");
7018       int Pos = 0;
7019       for (auto &Val : Record) {
7020         assert(!(Val >> 32) && "Unexpected high bits set");
7021         LastSeenModule->second.second[Pos++] = Val;
7022       }
7023       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
7024       LastSeenModule = nullptr;
7025       break;
7026     }
7027     }
7028   }
7029   llvm_unreachable("Exit infinite loop");
7030 }
7031 
7032 namespace {
7033 
7034 // FIXME: This class is only here to support the transition to llvm::Error. It
7035 // will be removed once this transition is complete. Clients should prefer to
7036 // deal with the Error value directly, rather than converting to error_code.
7037 class BitcodeErrorCategoryType : public std::error_category {
7038   const char *name() const noexcept override {
7039     return "llvm.bitcode";
7040   }
7041 
7042   std::string message(int IE) const override {
7043     BitcodeError E = static_cast<BitcodeError>(IE);
7044     switch (E) {
7045     case BitcodeError::CorruptedBitcode:
7046       return "Corrupted bitcode";
7047     }
7048     llvm_unreachable("Unknown error type!");
7049   }
7050 };
7051 
7052 } // end anonymous namespace
7053 
7054 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
7055 
7056 const std::error_category &llvm::BitcodeErrorCategory() {
7057   return *ErrorCategory;
7058 }
7059 
7060 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
7061                                             unsigned Block, unsigned RecordID) {
7062   if (Error Err = Stream.EnterSubBlock(Block))
7063     return std::move(Err);
7064 
7065   StringRef Strtab;
7066   while (true) {
7067     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7068     if (!MaybeEntry)
7069       return MaybeEntry.takeError();
7070     llvm::BitstreamEntry Entry = MaybeEntry.get();
7071 
7072     switch (Entry.Kind) {
7073     case BitstreamEntry::EndBlock:
7074       return Strtab;
7075 
7076     case BitstreamEntry::Error:
7077       return error("Malformed block");
7078 
7079     case BitstreamEntry::SubBlock:
7080       if (Error Err = Stream.SkipBlock())
7081         return std::move(Err);
7082       break;
7083 
7084     case BitstreamEntry::Record:
7085       StringRef Blob;
7086       SmallVector<uint64_t, 1> Record;
7087       Expected<unsigned> MaybeRecord =
7088           Stream.readRecord(Entry.ID, Record, &Blob);
7089       if (!MaybeRecord)
7090         return MaybeRecord.takeError();
7091       if (MaybeRecord.get() == RecordID)
7092         Strtab = Blob;
7093       break;
7094     }
7095   }
7096 }
7097 
7098 //===----------------------------------------------------------------------===//
7099 // External interface
7100 //===----------------------------------------------------------------------===//
7101 
7102 Expected<std::vector<BitcodeModule>>
7103 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
7104   auto FOrErr = getBitcodeFileContents(Buffer);
7105   if (!FOrErr)
7106     return FOrErr.takeError();
7107   return std::move(FOrErr->Mods);
7108 }
7109 
7110 Expected<BitcodeFileContents>
7111 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
7112   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7113   if (!StreamOrErr)
7114     return StreamOrErr.takeError();
7115   BitstreamCursor &Stream = *StreamOrErr;
7116 
7117   BitcodeFileContents F;
7118   while (true) {
7119     uint64_t BCBegin = Stream.getCurrentByteNo();
7120 
7121     // We may be consuming bitcode from a client that leaves garbage at the end
7122     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
7123     // the end that there cannot possibly be another module, stop looking.
7124     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
7125       return F;
7126 
7127     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7128     if (!MaybeEntry)
7129       return MaybeEntry.takeError();
7130     llvm::BitstreamEntry Entry = MaybeEntry.get();
7131 
7132     switch (Entry.Kind) {
7133     case BitstreamEntry::EndBlock:
7134     case BitstreamEntry::Error:
7135       return error("Malformed block");
7136 
7137     case BitstreamEntry::SubBlock: {
7138       uint64_t IdentificationBit = -1ull;
7139       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
7140         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
7141         if (Error Err = Stream.SkipBlock())
7142           return std::move(Err);
7143 
7144         {
7145           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7146           if (!MaybeEntry)
7147             return MaybeEntry.takeError();
7148           Entry = MaybeEntry.get();
7149         }
7150 
7151         if (Entry.Kind != BitstreamEntry::SubBlock ||
7152             Entry.ID != bitc::MODULE_BLOCK_ID)
7153           return error("Malformed block");
7154       }
7155 
7156       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
7157         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
7158         if (Error Err = Stream.SkipBlock())
7159           return std::move(Err);
7160 
7161         F.Mods.push_back({Stream.getBitcodeBytes().slice(
7162                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
7163                           Buffer.getBufferIdentifier(), IdentificationBit,
7164                           ModuleBit});
7165         continue;
7166       }
7167 
7168       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
7169         Expected<StringRef> Strtab =
7170             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
7171         if (!Strtab)
7172           return Strtab.takeError();
7173         // This string table is used by every preceding bitcode module that does
7174         // not have its own string table. A bitcode file may have multiple
7175         // string tables if it was created by binary concatenation, for example
7176         // with "llvm-cat -b".
7177         for (BitcodeModule &I : llvm::reverse(F.Mods)) {
7178           if (!I.Strtab.empty())
7179             break;
7180           I.Strtab = *Strtab;
7181         }
7182         // Similarly, the string table is used by every preceding symbol table;
7183         // normally there will be just one unless the bitcode file was created
7184         // by binary concatenation.
7185         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
7186           F.StrtabForSymtab = *Strtab;
7187         continue;
7188       }
7189 
7190       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
7191         Expected<StringRef> SymtabOrErr =
7192             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
7193         if (!SymtabOrErr)
7194           return SymtabOrErr.takeError();
7195 
7196         // We can expect the bitcode file to have multiple symbol tables if it
7197         // was created by binary concatenation. In that case we silently
7198         // ignore any subsequent symbol tables, which is fine because this is a
7199         // low level function. The client is expected to notice that the number
7200         // of modules in the symbol table does not match the number of modules
7201         // in the input file and regenerate the symbol table.
7202         if (F.Symtab.empty())
7203           F.Symtab = *SymtabOrErr;
7204         continue;
7205       }
7206 
7207       if (Error Err = Stream.SkipBlock())
7208         return std::move(Err);
7209       continue;
7210     }
7211     case BitstreamEntry::Record:
7212       if (Error E = Stream.skipRecord(Entry.ID).takeError())
7213         return std::move(E);
7214       continue;
7215     }
7216   }
7217 }
7218 
7219 /// Get a lazy one-at-time loading module from bitcode.
7220 ///
7221 /// This isn't always used in a lazy context.  In particular, it's also used by
7222 /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
7223 /// in forward-referenced functions from block address references.
7224 ///
7225 /// \param[in] MaterializeAll Set to \c true if we should materialize
7226 /// everything.
7227 Expected<std::unique_ptr<Module>>
7228 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
7229                              bool ShouldLazyLoadMetadata, bool IsImporting,
7230                              DataLayoutCallbackTy DataLayoutCallback) {
7231   BitstreamCursor Stream(Buffer);
7232 
7233   std::string ProducerIdentification;
7234   if (IdentificationBit != -1ull) {
7235     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
7236       return std::move(JumpFailed);
7237     if (Error E =
7238             readIdentificationBlock(Stream).moveInto(ProducerIdentification))
7239       return std::move(E);
7240   }
7241 
7242   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7243     return std::move(JumpFailed);
7244   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
7245                               Context);
7246 
7247   std::unique_ptr<Module> M =
7248       std::make_unique<Module>(ModuleIdentifier, Context);
7249   M->setMaterializer(R);
7250 
7251   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
7252   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
7253                                       IsImporting, DataLayoutCallback))
7254     return std::move(Err);
7255 
7256   if (MaterializeAll) {
7257     // Read in the entire module, and destroy the BitcodeReader.
7258     if (Error Err = M->materializeAll())
7259       return std::move(Err);
7260   } else {
7261     // Resolve forward references from blockaddresses.
7262     if (Error Err = R->materializeForwardReferencedFunctions())
7263       return std::move(Err);
7264   }
7265   return std::move(M);
7266 }
7267 
7268 Expected<std::unique_ptr<Module>>
7269 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
7270                              bool IsImporting) {
7271   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
7272                        [](StringRef) { return None; });
7273 }
7274 
7275 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
7276 // We don't use ModuleIdentifier here because the client may need to control the
7277 // module path used in the combined summary (e.g. when reading summaries for
7278 // regular LTO modules).
7279 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
7280                                  StringRef ModulePath, uint64_t ModuleId) {
7281   BitstreamCursor Stream(Buffer);
7282   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7283     return JumpFailed;
7284 
7285   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
7286                                     ModulePath, ModuleId);
7287   return R.parseModule();
7288 }
7289 
7290 // Parse the specified bitcode buffer, returning the function info index.
7291 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
7292   BitstreamCursor Stream(Buffer);
7293   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7294     return std::move(JumpFailed);
7295 
7296   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
7297   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
7298                                     ModuleIdentifier, 0);
7299 
7300   if (Error Err = R.parseModule())
7301     return std::move(Err);
7302 
7303   return std::move(Index);
7304 }
7305 
7306 static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
7307                                                 unsigned ID) {
7308   if (Error Err = Stream.EnterSubBlock(ID))
7309     return std::move(Err);
7310   SmallVector<uint64_t, 64> Record;
7311 
7312   while (true) {
7313     BitstreamEntry Entry;
7314     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
7315       return std::move(E);
7316 
7317     switch (Entry.Kind) {
7318     case BitstreamEntry::SubBlock: // Handled for us already.
7319     case BitstreamEntry::Error:
7320       return error("Malformed block");
7321     case BitstreamEntry::EndBlock:
7322       // If no flags record found, conservatively return true to mimic
7323       // behavior before this flag was added.
7324       return true;
7325     case BitstreamEntry::Record:
7326       // The interesting case.
7327       break;
7328     }
7329 
7330     // Look for the FS_FLAGS record.
7331     Record.clear();
7332     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7333     if (!MaybeBitCode)
7334       return MaybeBitCode.takeError();
7335     switch (MaybeBitCode.get()) {
7336     default: // Default behavior: ignore.
7337       break;
7338     case bitc::FS_FLAGS: { // [flags]
7339       uint64_t Flags = Record[0];
7340       // Scan flags.
7341       assert(Flags <= 0x7f && "Unexpected bits in flag");
7342 
7343       return Flags & 0x8;
7344     }
7345     }
7346   }
7347   llvm_unreachable("Exit infinite loop");
7348 }
7349 
7350 // Check if the given bitcode buffer contains a global value summary block.
7351 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
7352   BitstreamCursor Stream(Buffer);
7353   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7354     return std::move(JumpFailed);
7355 
7356   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
7357     return std::move(Err);
7358 
7359   while (true) {
7360     llvm::BitstreamEntry Entry;
7361     if (Error E = Stream.advance().moveInto(Entry))
7362       return std::move(E);
7363 
7364     switch (Entry.Kind) {
7365     case BitstreamEntry::Error:
7366       return error("Malformed block");
7367     case BitstreamEntry::EndBlock:
7368       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
7369                             /*EnableSplitLTOUnit=*/false};
7370 
7371     case BitstreamEntry::SubBlock:
7372       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
7373         Expected<bool> EnableSplitLTOUnit =
7374             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
7375         if (!EnableSplitLTOUnit)
7376           return EnableSplitLTOUnit.takeError();
7377         return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
7378                               *EnableSplitLTOUnit};
7379       }
7380 
7381       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
7382         Expected<bool> EnableSplitLTOUnit =
7383             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
7384         if (!EnableSplitLTOUnit)
7385           return EnableSplitLTOUnit.takeError();
7386         return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
7387                               *EnableSplitLTOUnit};
7388       }
7389 
7390       // Ignore other sub-blocks.
7391       if (Error Err = Stream.SkipBlock())
7392         return std::move(Err);
7393       continue;
7394 
7395     case BitstreamEntry::Record:
7396       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
7397         continue;
7398       else
7399         return StreamFailed.takeError();
7400     }
7401   }
7402 }
7403 
7404 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
7405   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
7406   if (!MsOrErr)
7407     return MsOrErr.takeError();
7408 
7409   if (MsOrErr->size() != 1)
7410     return error("Expected a single module");
7411 
7412   return (*MsOrErr)[0];
7413 }
7414 
7415 Expected<std::unique_ptr<Module>>
7416 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
7417                            bool ShouldLazyLoadMetadata, bool IsImporting) {
7418   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7419   if (!BM)
7420     return BM.takeError();
7421 
7422   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
7423 }
7424 
7425 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
7426     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
7427     bool ShouldLazyLoadMetadata, bool IsImporting) {
7428   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
7429                                      IsImporting);
7430   if (MOrErr)
7431     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
7432   return MOrErr;
7433 }
7434 
7435 Expected<std::unique_ptr<Module>>
7436 BitcodeModule::parseModule(LLVMContext &Context,
7437                            DataLayoutCallbackTy DataLayoutCallback) {
7438   return getModuleImpl(Context, true, false, false, DataLayoutCallback);
7439   // TODO: Restore the use-lists to the in-memory state when the bitcode was
7440   // written.  We must defer until the Module has been fully materialized.
7441 }
7442 
7443 Expected<std::unique_ptr<Module>>
7444 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
7445                        DataLayoutCallbackTy DataLayoutCallback) {
7446   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7447   if (!BM)
7448     return BM.takeError();
7449 
7450   return BM->parseModule(Context, DataLayoutCallback);
7451 }
7452 
7453 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
7454   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7455   if (!StreamOrErr)
7456     return StreamOrErr.takeError();
7457 
7458   return readTriple(*StreamOrErr);
7459 }
7460 
7461 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
7462   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7463   if (!StreamOrErr)
7464     return StreamOrErr.takeError();
7465 
7466   return hasObjCCategory(*StreamOrErr);
7467 }
7468 
7469 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
7470   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7471   if (!StreamOrErr)
7472     return StreamOrErr.takeError();
7473 
7474   return readIdentificationCode(*StreamOrErr);
7475 }
7476 
7477 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
7478                                    ModuleSummaryIndex &CombinedIndex,
7479                                    uint64_t ModuleId) {
7480   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7481   if (!BM)
7482     return BM.takeError();
7483 
7484   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
7485 }
7486 
7487 Expected<std::unique_ptr<ModuleSummaryIndex>>
7488 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
7489   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7490   if (!BM)
7491     return BM.takeError();
7492 
7493   return BM->getSummary();
7494 }
7495 
7496 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
7497   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7498   if (!BM)
7499     return BM.takeError();
7500 
7501   return BM->getLTOInfo();
7502 }
7503 
7504 Expected<std::unique_ptr<ModuleSummaryIndex>>
7505 llvm::getModuleSummaryIndexForFile(StringRef Path,
7506                                    bool IgnoreEmptyThinLTOIndexFile) {
7507   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
7508       MemoryBuffer::getFileOrSTDIN(Path);
7509   if (!FileOrErr)
7510     return errorCodeToError(FileOrErr.getError());
7511   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
7512     return nullptr;
7513   return getModuleSummaryIndex(**FileOrErr);
7514 }
7515