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