xref: /llvm-project/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (revision 7a258c6a3778b78935422a9ed0b6822fae123f32)
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   if (Func->getCallingConv() == CallingConv::X86_INTR &&
3605       !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {
3606     unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
3607     Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
3608     if (!ByValTy)
3609       return error("Missing param element type for x86_intrcc upgrade");
3610     Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
3611     Func->addParamAttr(0, NewAttr);
3612   }
3613 
3614   MaybeAlign Alignment;
3615   if (Error Err = parseAlignmentValue(Record[5], Alignment))
3616     return Err;
3617   Func->setAlignment(Alignment);
3618   if (Record[6]) {
3619     if (Record[6] - 1 >= SectionTable.size())
3620       return error("Invalid ID");
3621     Func->setSection(SectionTable[Record[6] - 1]);
3622   }
3623   // Local linkage must have default visibility.
3624   // auto-upgrade `hidden` and `protected` for old bitcode.
3625   if (!Func->hasLocalLinkage())
3626     Func->setVisibility(getDecodedVisibility(Record[7]));
3627   if (Record.size() > 8 && Record[8]) {
3628     if (Record[8] - 1 >= GCTable.size())
3629       return error("Invalid ID");
3630     Func->setGC(GCTable[Record[8] - 1]);
3631   }
3632   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3633   if (Record.size() > 9)
3634     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3635   Func->setUnnamedAddr(UnnamedAddr);
3636 
3637   FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
3638   if (Record.size() > 10)
3639     OperandInfo.Prologue = Record[10];
3640 
3641   if (Record.size() > 11)
3642     Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3643   else
3644     upgradeDLLImportExportLinkage(Func, RawLinkage);
3645 
3646   if (Record.size() > 12) {
3647     if (unsigned ComdatID = Record[12]) {
3648       if (ComdatID > ComdatList.size())
3649         return error("Invalid function comdat ID");
3650       Func->setComdat(ComdatList[ComdatID - 1]);
3651     }
3652   } else if (hasImplicitComdat(RawLinkage)) {
3653     ImplicitComdatObjects.insert(Func);
3654   }
3655 
3656   if (Record.size() > 13)
3657     OperandInfo.Prefix = Record[13];
3658 
3659   if (Record.size() > 14)
3660     OperandInfo.PersonalityFn = Record[14];
3661 
3662   if (Record.size() > 15) {
3663     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3664   }
3665   inferDSOLocal(Func);
3666 
3667   // Record[16] is the address space number.
3668 
3669   // Check whether we have enough values to read a partition name. Also make
3670   // sure Strtab has enough values.
3671   if (Record.size() > 18 && Strtab.data() &&
3672       Record[17] + Record[18] <= Strtab.size()) {
3673     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
3674   }
3675 
3676   ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
3677 
3678   if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
3679     FunctionOperands.push_back(OperandInfo);
3680 
3681   // If this is a function with a body, remember the prototype we are
3682   // creating now, so that we can match up the body with them later.
3683   if (!isProto) {
3684     Func->setIsMaterializable(true);
3685     FunctionsWithBodies.push_back(Func);
3686     DeferredFunctionInfo[Func] = 0;
3687   }
3688   return Error::success();
3689 }
3690 
3691 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3692     unsigned BitCode, ArrayRef<uint64_t> Record) {
3693   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3694   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3695   // dllstorageclass, threadlocal, unnamed_addr,
3696   // preemption specifier] (name in VST)
3697   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3698   // visibility, dllstorageclass, threadlocal, unnamed_addr,
3699   // preemption specifier] (name in VST)
3700   // v2: [strtab_offset, strtab_size, v1]
3701   StringRef Name;
3702   std::tie(Name, Record) = readNameFromStrtab(Record);
3703 
3704   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3705   if (Record.size() < (3 + (unsigned)NewRecord))
3706     return error("Invalid record");
3707   unsigned OpNum = 0;
3708   unsigned TypeID = Record[OpNum++];
3709   Type *Ty = getTypeByID(TypeID);
3710   if (!Ty)
3711     return error("Invalid record");
3712 
3713   unsigned AddrSpace;
3714   if (!NewRecord) {
3715     auto *PTy = dyn_cast<PointerType>(Ty);
3716     if (!PTy)
3717       return error("Invalid type for value");
3718     AddrSpace = PTy->getAddressSpace();
3719     TypeID = getContainedTypeID(TypeID);
3720     Ty = getTypeByID(TypeID);
3721     if (!Ty)
3722       return error("Missing element type for old-style indirect symbol");
3723   } else {
3724     AddrSpace = Record[OpNum++];
3725   }
3726 
3727   auto Val = Record[OpNum++];
3728   auto Linkage = Record[OpNum++];
3729   GlobalValue *NewGA;
3730   if (BitCode == bitc::MODULE_CODE_ALIAS ||
3731       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3732     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3733                                 TheModule);
3734   else
3735     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
3736                                 nullptr, TheModule);
3737 
3738   // Local linkage must have default visibility.
3739   // auto-upgrade `hidden` and `protected` for old bitcode.
3740   if (OpNum != Record.size()) {
3741     auto VisInd = OpNum++;
3742     if (!NewGA->hasLocalLinkage())
3743       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3744   }
3745   if (BitCode == bitc::MODULE_CODE_ALIAS ||
3746       BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
3747     if (OpNum != Record.size())
3748       NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3749     else
3750       upgradeDLLImportExportLinkage(NewGA, Linkage);
3751     if (OpNum != Record.size())
3752       NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3753     if (OpNum != Record.size())
3754       NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3755   }
3756   if (OpNum != Record.size())
3757     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
3758   inferDSOLocal(NewGA);
3759 
3760   // Check whether we have enough values to read a partition name.
3761   if (OpNum + 1 < Record.size()) {
3762     NewGA->setPartition(
3763         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
3764     OpNum += 2;
3765   }
3766 
3767   ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
3768   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3769   return Error::success();
3770 }
3771 
3772 Error BitcodeReader::parseModule(uint64_t ResumeBit,
3773                                  bool ShouldLazyLoadMetadata,
3774                                  DataLayoutCallbackTy DataLayoutCallback) {
3775   if (ResumeBit) {
3776     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
3777       return JumpFailed;
3778   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3779     return Err;
3780 
3781   SmallVector<uint64_t, 64> Record;
3782 
3783   // Parts of bitcode parsing depend on the datalayout.  Make sure we
3784   // finalize the datalayout before we run any of that code.
3785   bool ResolvedDataLayout = false;
3786   auto ResolveDataLayout = [&] {
3787     if (ResolvedDataLayout)
3788       return;
3789 
3790     // datalayout and triple can't be parsed after this point.
3791     ResolvedDataLayout = true;
3792 
3793     // Upgrade data layout string.
3794     std::string DL = llvm::UpgradeDataLayoutString(
3795         TheModule->getDataLayoutStr(), TheModule->getTargetTriple());
3796     TheModule->setDataLayout(DL);
3797 
3798     if (auto LayoutOverride =
3799             DataLayoutCallback(TheModule->getTargetTriple()))
3800       TheModule->setDataLayout(*LayoutOverride);
3801   };
3802 
3803   // Read all the records for this module.
3804   while (true) {
3805     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3806     if (!MaybeEntry)
3807       return MaybeEntry.takeError();
3808     llvm::BitstreamEntry Entry = MaybeEntry.get();
3809 
3810     switch (Entry.Kind) {
3811     case BitstreamEntry::Error:
3812       return error("Malformed block");
3813     case BitstreamEntry::EndBlock:
3814       ResolveDataLayout();
3815       return globalCleanup();
3816 
3817     case BitstreamEntry::SubBlock:
3818       switch (Entry.ID) {
3819       default:  // Skip unknown content.
3820         if (Error Err = Stream.SkipBlock())
3821           return Err;
3822         break;
3823       case bitc::BLOCKINFO_BLOCK_ID:
3824         if (Error Err = readBlockInfo())
3825           return Err;
3826         break;
3827       case bitc::PARAMATTR_BLOCK_ID:
3828         if (Error Err = parseAttributeBlock())
3829           return Err;
3830         break;
3831       case bitc::PARAMATTR_GROUP_BLOCK_ID:
3832         if (Error Err = parseAttributeGroupBlock())
3833           return Err;
3834         break;
3835       case bitc::TYPE_BLOCK_ID_NEW:
3836         if (Error Err = parseTypeTable())
3837           return Err;
3838         break;
3839       case bitc::VALUE_SYMTAB_BLOCK_ID:
3840         if (!SeenValueSymbolTable) {
3841           // Either this is an old form VST without function index and an
3842           // associated VST forward declaration record (which would have caused
3843           // the VST to be jumped to and parsed before it was encountered
3844           // normally in the stream), or there were no function blocks to
3845           // trigger an earlier parsing of the VST.
3846           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3847           if (Error Err = parseValueSymbolTable())
3848             return Err;
3849           SeenValueSymbolTable = true;
3850         } else {
3851           // We must have had a VST forward declaration record, which caused
3852           // the parser to jump to and parse the VST earlier.
3853           assert(VSTOffset > 0);
3854           if (Error Err = Stream.SkipBlock())
3855             return Err;
3856         }
3857         break;
3858       case bitc::CONSTANTS_BLOCK_ID:
3859         if (Error Err = parseConstants())
3860           return Err;
3861         if (Error Err = resolveGlobalAndIndirectSymbolInits())
3862           return Err;
3863         break;
3864       case bitc::METADATA_BLOCK_ID:
3865         if (ShouldLazyLoadMetadata) {
3866           if (Error Err = rememberAndSkipMetadata())
3867             return Err;
3868           break;
3869         }
3870         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3871         if (Error Err = MDLoader->parseModuleMetadata())
3872           return Err;
3873         break;
3874       case bitc::METADATA_KIND_BLOCK_ID:
3875         if (Error Err = MDLoader->parseMetadataKinds())
3876           return Err;
3877         break;
3878       case bitc::FUNCTION_BLOCK_ID:
3879         ResolveDataLayout();
3880 
3881         // If this is the first function body we've seen, reverse the
3882         // FunctionsWithBodies list.
3883         if (!SeenFirstFunctionBody) {
3884           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3885           if (Error Err = globalCleanup())
3886             return Err;
3887           SeenFirstFunctionBody = true;
3888         }
3889 
3890         if (VSTOffset > 0) {
3891           // If we have a VST forward declaration record, make sure we
3892           // parse the VST now if we haven't already. It is needed to
3893           // set up the DeferredFunctionInfo vector for lazy reading.
3894           if (!SeenValueSymbolTable) {
3895             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
3896               return Err;
3897             SeenValueSymbolTable = true;
3898             // Fall through so that we record the NextUnreadBit below.
3899             // This is necessary in case we have an anonymous function that
3900             // is later materialized. Since it will not have a VST entry we
3901             // need to fall back to the lazy parse to find its offset.
3902           } else {
3903             // If we have a VST forward declaration record, but have already
3904             // parsed the VST (just above, when the first function body was
3905             // encountered here), then we are resuming the parse after
3906             // materializing functions. The ResumeBit points to the
3907             // start of the last function block recorded in the
3908             // DeferredFunctionInfo map. Skip it.
3909             if (Error Err = Stream.SkipBlock())
3910               return Err;
3911             continue;
3912           }
3913         }
3914 
3915         // Support older bitcode files that did not have the function
3916         // index in the VST, nor a VST forward declaration record, as
3917         // well as anonymous functions that do not have VST entries.
3918         // Build the DeferredFunctionInfo vector on the fly.
3919         if (Error Err = rememberAndSkipFunctionBody())
3920           return Err;
3921 
3922         // Suspend parsing when we reach the function bodies. Subsequent
3923         // materialization calls will resume it when necessary. If the bitcode
3924         // file is old, the symbol table will be at the end instead and will not
3925         // have been seen yet. In this case, just finish the parse now.
3926         if (SeenValueSymbolTable) {
3927           NextUnreadBit = Stream.GetCurrentBitNo();
3928           // After the VST has been parsed, we need to make sure intrinsic name
3929           // are auto-upgraded.
3930           return globalCleanup();
3931         }
3932         break;
3933       case bitc::USELIST_BLOCK_ID:
3934         if (Error Err = parseUseLists())
3935           return Err;
3936         break;
3937       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3938         if (Error Err = parseOperandBundleTags())
3939           return Err;
3940         break;
3941       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
3942         if (Error Err = parseSyncScopeNames())
3943           return Err;
3944         break;
3945       }
3946       continue;
3947 
3948     case BitstreamEntry::Record:
3949       // The interesting case.
3950       break;
3951     }
3952 
3953     // Read a record.
3954     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3955     if (!MaybeBitCode)
3956       return MaybeBitCode.takeError();
3957     switch (unsigned BitCode = MaybeBitCode.get()) {
3958     default: break;  // Default behavior, ignore unknown content.
3959     case bitc::MODULE_CODE_VERSION: {
3960       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
3961       if (!VersionOrErr)
3962         return VersionOrErr.takeError();
3963       UseRelativeIDs = *VersionOrErr >= 1;
3964       break;
3965     }
3966     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3967       if (ResolvedDataLayout)
3968         return error("target triple too late in module");
3969       std::string S;
3970       if (convertToString(Record, 0, S))
3971         return error("Invalid record");
3972       TheModule->setTargetTriple(S);
3973       break;
3974     }
3975     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3976       if (ResolvedDataLayout)
3977         return error("datalayout too late in module");
3978       std::string S;
3979       if (convertToString(Record, 0, S))
3980         return error("Invalid record");
3981       Expected<DataLayout> MaybeDL = DataLayout::parse(S);
3982       if (!MaybeDL)
3983         return MaybeDL.takeError();
3984       TheModule->setDataLayout(MaybeDL.get());
3985       break;
3986     }
3987     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3988       std::string S;
3989       if (convertToString(Record, 0, S))
3990         return error("Invalid record");
3991       TheModule->setModuleInlineAsm(S);
3992       break;
3993     }
3994     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3995       // Deprecated, but still needed to read old bitcode files.
3996       std::string S;
3997       if (convertToString(Record, 0, S))
3998         return error("Invalid record");
3999       // Ignore value.
4000       break;
4001     }
4002     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
4003       std::string S;
4004       if (convertToString(Record, 0, S))
4005         return error("Invalid record");
4006       SectionTable.push_back(S);
4007       break;
4008     }
4009     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
4010       std::string S;
4011       if (convertToString(Record, 0, S))
4012         return error("Invalid record");
4013       GCTable.push_back(S);
4014       break;
4015     }
4016     case bitc::MODULE_CODE_COMDAT:
4017       if (Error Err = parseComdatRecord(Record))
4018         return Err;
4019       break;
4020     // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
4021     // written by ThinLinkBitcodeWriter. See
4022     // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
4023     // record
4024     // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4025     case bitc::MODULE_CODE_GLOBALVAR:
4026       if (Error Err = parseGlobalVarRecord(Record))
4027         return Err;
4028       break;
4029     case bitc::MODULE_CODE_FUNCTION:
4030       ResolveDataLayout();
4031       if (Error Err = parseFunctionRecord(Record))
4032         return Err;
4033       break;
4034     case bitc::MODULE_CODE_IFUNC:
4035     case bitc::MODULE_CODE_ALIAS:
4036     case bitc::MODULE_CODE_ALIAS_OLD:
4037       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4038         return Err;
4039       break;
4040     /// MODULE_CODE_VSTOFFSET: [offset]
4041     case bitc::MODULE_CODE_VSTOFFSET:
4042       if (Record.empty())
4043         return error("Invalid record");
4044       // Note that we subtract 1 here because the offset is relative to one word
4045       // before the start of the identification or module block, which was
4046       // historically always the start of the regular bitcode header.
4047       VSTOffset = Record[0] - 1;
4048       break;
4049     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4050     case bitc::MODULE_CODE_SOURCE_FILENAME:
4051       SmallString<128> ValueName;
4052       if (convertToString(Record, 0, ValueName))
4053         return error("Invalid record");
4054       TheModule->setSourceFileName(ValueName);
4055       break;
4056     }
4057     Record.clear();
4058   }
4059 }
4060 
4061 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
4062                                       bool IsImporting,
4063                                       DataLayoutCallbackTy DataLayoutCallback) {
4064   TheModule = M;
4065   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
4066                             [&](unsigned ID) { return getTypeByID(ID); });
4067   return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback);
4068 }
4069 
4070 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4071   if (!isa<PointerType>(PtrType))
4072     return error("Load/Store operand is not a pointer type");
4073 
4074   if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType))
4075     return error("Explicit load/store type does not match pointee "
4076                  "type of pointer operand");
4077   if (!PointerType::isLoadableOrStorableType(ValType))
4078     return error("Cannot load/store from pointer");
4079   return Error::success();
4080 }
4081 
4082 void BitcodeReader::propagateAttributeTypes(CallBase *CB,
4083                                             ArrayRef<unsigned> ArgTyIDs) {
4084   for (unsigned i = 0; i != CB->arg_size(); ++i) {
4085     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4086                                      Attribute::InAlloca}) {
4087       if (!CB->paramHasAttr(i, Kind) ||
4088           CB->getParamAttr(i, Kind).getValueAsType())
4089         continue;
4090 
4091       CB->removeParamAttr(i, Kind);
4092 
4093       Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4094       Attribute NewAttr;
4095       switch (Kind) {
4096       case Attribute::ByVal:
4097         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4098         break;
4099       case Attribute::StructRet:
4100         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4101         break;
4102       case Attribute::InAlloca:
4103         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4104         break;
4105       default:
4106         llvm_unreachable("not an upgraded type attribute");
4107       }
4108 
4109       CB->addParamAttr(i, NewAttr);
4110     }
4111   }
4112 
4113   if (CB->isInlineAsm()) {
4114     const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
4115     unsigned ArgNo = 0;
4116     for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4117       if (!CI.hasArg())
4118         continue;
4119 
4120       if (CI.isIndirect && !CB->getParamElementType(ArgNo)) {
4121         Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4122         CB->addParamAttr(
4123             ArgNo, Attribute::get(Context, Attribute::ElementType, ElemTy));
4124       }
4125 
4126       ArgNo++;
4127     }
4128   }
4129 
4130   switch (CB->getIntrinsicID()) {
4131   case Intrinsic::preserve_array_access_index:
4132   case Intrinsic::preserve_struct_access_index:
4133     if (!CB->getParamElementType(0)) {
4134       Type *ElTy = getPtrElementTypeByID(ArgTyIDs[0]);
4135       Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
4136       CB->addParamAttr(0, NewAttr);
4137     }
4138     break;
4139   default:
4140     break;
4141   }
4142 }
4143 
4144 /// Lazily parse the specified function body block.
4145 Error BitcodeReader::parseFunctionBody(Function *F) {
4146   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4147     return Err;
4148 
4149   // Unexpected unresolved metadata when parsing function.
4150   if (MDLoader->hasFwdRefs())
4151     return error("Invalid function metadata: incoming forward references");
4152 
4153   InstructionList.clear();
4154   unsigned ModuleValueListSize = ValueList.size();
4155   unsigned ModuleMDLoaderSize = MDLoader->size();
4156 
4157   // Add all the function arguments to the value table.
4158   unsigned ArgNo = 0;
4159   unsigned FTyID = FunctionTypeIDs[F];
4160   for (Argument &I : F->args()) {
4161     unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4162     assert(I.getType() == getTypeByID(ArgTyID) &&
4163            "Incorrect fully specified type for Function Argument");
4164     ValueList.push_back(&I, ArgTyID);
4165     ++ArgNo;
4166   }
4167   unsigned NextValueNo = ValueList.size();
4168   BasicBlock *CurBB = nullptr;
4169   unsigned CurBBNo = 0;
4170 
4171   DebugLoc LastLoc;
4172   auto getLastInstruction = [&]() -> Instruction * {
4173     if (CurBB && !CurBB->empty())
4174       return &CurBB->back();
4175     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4176              !FunctionBBs[CurBBNo - 1]->empty())
4177       return &FunctionBBs[CurBBNo - 1]->back();
4178     return nullptr;
4179   };
4180 
4181   std::vector<OperandBundleDef> OperandBundles;
4182 
4183   // Read all the records.
4184   SmallVector<uint64_t, 64> Record;
4185 
4186   while (true) {
4187     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4188     if (!MaybeEntry)
4189       return MaybeEntry.takeError();
4190     llvm::BitstreamEntry Entry = MaybeEntry.get();
4191 
4192     switch (Entry.Kind) {
4193     case BitstreamEntry::Error:
4194       return error("Malformed block");
4195     case BitstreamEntry::EndBlock:
4196       goto OutOfRecordLoop;
4197 
4198     case BitstreamEntry::SubBlock:
4199       switch (Entry.ID) {
4200       default:  // Skip unknown content.
4201         if (Error Err = Stream.SkipBlock())
4202           return Err;
4203         break;
4204       case bitc::CONSTANTS_BLOCK_ID:
4205         if (Error Err = parseConstants())
4206           return Err;
4207         NextValueNo = ValueList.size();
4208         break;
4209       case bitc::VALUE_SYMTAB_BLOCK_ID:
4210         if (Error Err = parseValueSymbolTable())
4211           return Err;
4212         break;
4213       case bitc::METADATA_ATTACHMENT_ID:
4214         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
4215           return Err;
4216         break;
4217       case bitc::METADATA_BLOCK_ID:
4218         assert(DeferredMetadataInfo.empty() &&
4219                "Must read all module-level metadata before function-level");
4220         if (Error Err = MDLoader->parseFunctionMetadata())
4221           return Err;
4222         break;
4223       case bitc::USELIST_BLOCK_ID:
4224         if (Error Err = parseUseLists())
4225           return Err;
4226         break;
4227       }
4228       continue;
4229 
4230     case BitstreamEntry::Record:
4231       // The interesting case.
4232       break;
4233     }
4234 
4235     // Read a record.
4236     Record.clear();
4237     Instruction *I = nullptr;
4238     unsigned ResTypeID = InvalidTypeID;
4239     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4240     if (!MaybeBitCode)
4241       return MaybeBitCode.takeError();
4242     switch (unsigned BitCode = MaybeBitCode.get()) {
4243     default: // Default behavior: reject
4244       return error("Invalid value");
4245     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4246       if (Record.empty() || Record[0] == 0)
4247         return error("Invalid record");
4248       // Create all the basic blocks for the function.
4249       FunctionBBs.resize(Record[0]);
4250 
4251       // See if anything took the address of blocks in this function.
4252       auto BBFRI = BasicBlockFwdRefs.find(F);
4253       if (BBFRI == BasicBlockFwdRefs.end()) {
4254         for (BasicBlock *&BB : FunctionBBs)
4255           BB = BasicBlock::Create(Context, "", F);
4256       } else {
4257         auto &BBRefs = BBFRI->second;
4258         // Check for invalid basic block references.
4259         if (BBRefs.size() > FunctionBBs.size())
4260           return error("Invalid ID");
4261         assert(!BBRefs.empty() && "Unexpected empty array");
4262         assert(!BBRefs.front() && "Invalid reference to entry block");
4263         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4264              ++I)
4265           if (I < RE && BBRefs[I]) {
4266             BBRefs[I]->insertInto(F);
4267             FunctionBBs[I] = BBRefs[I];
4268           } else {
4269             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4270           }
4271 
4272         // Erase from the table.
4273         BasicBlockFwdRefs.erase(BBFRI);
4274       }
4275 
4276       CurBB = FunctionBBs[0];
4277       continue;
4278     }
4279 
4280     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4281       // This record indicates that the last instruction is at the same
4282       // location as the previous instruction with a location.
4283       I = getLastInstruction();
4284 
4285       if (!I)
4286         return error("Invalid record");
4287       I->setDebugLoc(LastLoc);
4288       I = nullptr;
4289       continue;
4290 
4291     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
4292       I = getLastInstruction();
4293       if (!I || Record.size() < 4)
4294         return error("Invalid record");
4295 
4296       unsigned Line = Record[0], Col = Record[1];
4297       unsigned ScopeID = Record[2], IAID = Record[3];
4298       bool isImplicitCode = Record.size() == 5 && Record[4];
4299 
4300       MDNode *Scope = nullptr, *IA = nullptr;
4301       if (ScopeID) {
4302         Scope = dyn_cast_or_null<MDNode>(
4303             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
4304         if (!Scope)
4305           return error("Invalid record");
4306       }
4307       if (IAID) {
4308         IA = dyn_cast_or_null<MDNode>(
4309             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
4310         if (!IA)
4311           return error("Invalid record");
4312       }
4313       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4314                                 isImplicitCode);
4315       I->setDebugLoc(LastLoc);
4316       I = nullptr;
4317       continue;
4318     }
4319     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
4320       unsigned OpNum = 0;
4321       Value *LHS;
4322       unsigned TypeID;
4323       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID) ||
4324           OpNum+1 > Record.size())
4325         return error("Invalid record");
4326 
4327       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
4328       if (Opc == -1)
4329         return error("Invalid record");
4330       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
4331       ResTypeID = TypeID;
4332       InstructionList.push_back(I);
4333       if (OpNum < Record.size()) {
4334         if (isa<FPMathOperator>(I)) {
4335           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4336           if (FMF.any())
4337             I->setFastMathFlags(FMF);
4338         }
4339       }
4340       break;
4341     }
4342     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4343       unsigned OpNum = 0;
4344       Value *LHS, *RHS;
4345       unsigned TypeID;
4346       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID) ||
4347           popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS) ||
4348           OpNum+1 > Record.size())
4349         return error("Invalid record");
4350 
4351       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4352       if (Opc == -1)
4353         return error("Invalid record");
4354       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4355       ResTypeID = TypeID;
4356       InstructionList.push_back(I);
4357       if (OpNum < Record.size()) {
4358         if (Opc == Instruction::Add ||
4359             Opc == Instruction::Sub ||
4360             Opc == Instruction::Mul ||
4361             Opc == Instruction::Shl) {
4362           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4363             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4364           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4365             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4366         } else if (Opc == Instruction::SDiv ||
4367                    Opc == Instruction::UDiv ||
4368                    Opc == Instruction::LShr ||
4369                    Opc == Instruction::AShr) {
4370           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4371             cast<BinaryOperator>(I)->setIsExact(true);
4372         } else if (isa<FPMathOperator>(I)) {
4373           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4374           if (FMF.any())
4375             I->setFastMathFlags(FMF);
4376         }
4377 
4378       }
4379       break;
4380     }
4381     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4382       unsigned OpNum = 0;
4383       Value *Op;
4384       unsigned OpTypeID;
4385       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID) ||
4386           OpNum+2 != Record.size())
4387         return error("Invalid record");
4388 
4389       ResTypeID = Record[OpNum];
4390       Type *ResTy = getTypeByID(ResTypeID);
4391       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4392       if (Opc == -1 || !ResTy)
4393         return error("Invalid record");
4394       Instruction *Temp = nullptr;
4395       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4396         if (Temp) {
4397           InstructionList.push_back(Temp);
4398           assert(CurBB && "No current BB?");
4399           CurBB->getInstList().push_back(Temp);
4400         }
4401       } else {
4402         auto CastOp = (Instruction::CastOps)Opc;
4403         if (!CastInst::castIsValid(CastOp, Op, ResTy))
4404           return error("Invalid cast");
4405         I = CastInst::Create(CastOp, Op, ResTy);
4406       }
4407       InstructionList.push_back(I);
4408       break;
4409     }
4410     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4411     case bitc::FUNC_CODE_INST_GEP_OLD:
4412     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4413       unsigned OpNum = 0;
4414 
4415       unsigned TyID;
4416       Type *Ty;
4417       bool InBounds;
4418 
4419       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4420         InBounds = Record[OpNum++];
4421         TyID = Record[OpNum++];
4422         Ty = getTypeByID(TyID);
4423       } else {
4424         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4425         TyID = InvalidTypeID;
4426         Ty = nullptr;
4427       }
4428 
4429       Value *BasePtr;
4430       unsigned BasePtrTypeID;
4431       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID))
4432         return error("Invalid record");
4433 
4434       if (!Ty) {
4435         TyID = getContainedTypeID(BasePtrTypeID);
4436         if (BasePtr->getType()->isVectorTy())
4437           TyID = getContainedTypeID(TyID);
4438         Ty = getTypeByID(TyID);
4439       } else if (!cast<PointerType>(BasePtr->getType()->getScalarType())
4440                       ->isOpaqueOrPointeeTypeMatches(Ty)) {
4441         return error(
4442             "Explicit gep type does not match pointee type of pointer operand");
4443       }
4444 
4445       SmallVector<Value*, 16> GEPIdx;
4446       while (OpNum != Record.size()) {
4447         Value *Op;
4448         unsigned OpTypeID;
4449         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))
4450           return error("Invalid record");
4451         GEPIdx.push_back(Op);
4452       }
4453 
4454       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4455 
4456       ResTypeID = TyID;
4457       auto GTI = std::next(gep_type_begin(I));
4458       for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
4459         unsigned SubType = 0;
4460         if (GTI.isStruct()) {
4461           ConstantInt *IdxC =
4462               Idx->getType()->isVectorTy()
4463                   ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
4464                   : cast<ConstantInt>(Idx);
4465           SubType = IdxC->getZExtValue();
4466         }
4467         ResTypeID = getContainedTypeID(ResTypeID, SubType);
4468         ++GTI;
4469       }
4470 
4471       // At this point ResTypeID is the result element type. We need a pointer
4472       // or vector of pointer to it.
4473       ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
4474       if (I->getType()->isVectorTy())
4475         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
4476 
4477       InstructionList.push_back(I);
4478       if (InBounds)
4479         cast<GetElementPtrInst>(I)->setIsInBounds(true);
4480       break;
4481     }
4482 
4483     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4484                                        // EXTRACTVAL: [opty, opval, n x indices]
4485       unsigned OpNum = 0;
4486       Value *Agg;
4487       unsigned AggTypeID;
4488       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID))
4489         return error("Invalid record");
4490       Type *Ty = Agg->getType();
4491 
4492       unsigned RecSize = Record.size();
4493       if (OpNum == RecSize)
4494         return error("EXTRACTVAL: Invalid instruction with 0 indices");
4495 
4496       SmallVector<unsigned, 4> EXTRACTVALIdx;
4497       ResTypeID = AggTypeID;
4498       for (; OpNum != RecSize; ++OpNum) {
4499         bool IsArray = Ty->isArrayTy();
4500         bool IsStruct = Ty->isStructTy();
4501         uint64_t Index = Record[OpNum];
4502 
4503         if (!IsStruct && !IsArray)
4504           return error("EXTRACTVAL: Invalid type");
4505         if ((unsigned)Index != Index)
4506           return error("Invalid value");
4507         if (IsStruct && Index >= Ty->getStructNumElements())
4508           return error("EXTRACTVAL: Invalid struct index");
4509         if (IsArray && Index >= Ty->getArrayNumElements())
4510           return error("EXTRACTVAL: Invalid array index");
4511         EXTRACTVALIdx.push_back((unsigned)Index);
4512 
4513         if (IsStruct) {
4514           Ty = Ty->getStructElementType(Index);
4515           ResTypeID = getContainedTypeID(ResTypeID, Index);
4516         } else {
4517           Ty = Ty->getArrayElementType();
4518           ResTypeID = getContainedTypeID(ResTypeID);
4519         }
4520       }
4521 
4522       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4523       InstructionList.push_back(I);
4524       break;
4525     }
4526 
4527     case bitc::FUNC_CODE_INST_INSERTVAL: {
4528                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
4529       unsigned OpNum = 0;
4530       Value *Agg;
4531       unsigned AggTypeID;
4532       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID))
4533         return error("Invalid record");
4534       Value *Val;
4535       unsigned ValTypeID;
4536       if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID))
4537         return error("Invalid record");
4538 
4539       unsigned RecSize = Record.size();
4540       if (OpNum == RecSize)
4541         return error("INSERTVAL: Invalid instruction with 0 indices");
4542 
4543       SmallVector<unsigned, 4> INSERTVALIdx;
4544       Type *CurTy = Agg->getType();
4545       for (; OpNum != RecSize; ++OpNum) {
4546         bool IsArray = CurTy->isArrayTy();
4547         bool IsStruct = CurTy->isStructTy();
4548         uint64_t Index = Record[OpNum];
4549 
4550         if (!IsStruct && !IsArray)
4551           return error("INSERTVAL: Invalid type");
4552         if ((unsigned)Index != Index)
4553           return error("Invalid value");
4554         if (IsStruct && Index >= CurTy->getStructNumElements())
4555           return error("INSERTVAL: Invalid struct index");
4556         if (IsArray && Index >= CurTy->getArrayNumElements())
4557           return error("INSERTVAL: Invalid array index");
4558 
4559         INSERTVALIdx.push_back((unsigned)Index);
4560         if (IsStruct)
4561           CurTy = CurTy->getStructElementType(Index);
4562         else
4563           CurTy = CurTy->getArrayElementType();
4564       }
4565 
4566       if (CurTy != Val->getType())
4567         return error("Inserted value type doesn't match aggregate type");
4568 
4569       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4570       ResTypeID = AggTypeID;
4571       InstructionList.push_back(I);
4572       break;
4573     }
4574 
4575     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4576       // obsolete form of select
4577       // handles select i1 ... in old bitcode
4578       unsigned OpNum = 0;
4579       Value *TrueVal, *FalseVal, *Cond;
4580       unsigned TypeID;
4581       Type *CondType = Type::getInt1Ty(Context);
4582       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID) ||
4583           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
4584                    FalseVal) ||
4585           popValue(Record, OpNum, NextValueNo, CondType,
4586                    getVirtualTypeID(CondType), Cond))
4587         return error("Invalid record");
4588 
4589       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4590       ResTypeID = TypeID;
4591       InstructionList.push_back(I);
4592       break;
4593     }
4594 
4595     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4596       // new form of select
4597       // handles select i1 or select [N x i1]
4598       unsigned OpNum = 0;
4599       Value *TrueVal, *FalseVal, *Cond;
4600       unsigned ValTypeID, CondTypeID;
4601       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID) ||
4602           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
4603                    FalseVal) ||
4604           getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID))
4605         return error("Invalid record");
4606 
4607       // select condition can be either i1 or [N x i1]
4608       if (VectorType* vector_type =
4609           dyn_cast<VectorType>(Cond->getType())) {
4610         // expect <n x i1>
4611         if (vector_type->getElementType() != Type::getInt1Ty(Context))
4612           return error("Invalid type for value");
4613       } else {
4614         // expect i1
4615         if (Cond->getType() != Type::getInt1Ty(Context))
4616           return error("Invalid type for value");
4617       }
4618 
4619       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4620       ResTypeID = ValTypeID;
4621       InstructionList.push_back(I);
4622       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
4623         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4624         if (FMF.any())
4625           I->setFastMathFlags(FMF);
4626       }
4627       break;
4628     }
4629 
4630     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4631       unsigned OpNum = 0;
4632       Value *Vec, *Idx;
4633       unsigned VecTypeID, IdxTypeID;
4634       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID) ||
4635           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID))
4636         return error("Invalid record");
4637       if (!Vec->getType()->isVectorTy())
4638         return error("Invalid type for value");
4639       I = ExtractElementInst::Create(Vec, Idx);
4640       ResTypeID = getContainedTypeID(VecTypeID);
4641       InstructionList.push_back(I);
4642       break;
4643     }
4644 
4645     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4646       unsigned OpNum = 0;
4647       Value *Vec, *Elt, *Idx;
4648       unsigned VecTypeID, IdxTypeID;
4649       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID))
4650         return error("Invalid record");
4651       if (!Vec->getType()->isVectorTy())
4652         return error("Invalid type for value");
4653       if (popValue(Record, OpNum, NextValueNo,
4654                    cast<VectorType>(Vec->getType())->getElementType(),
4655                    getContainedTypeID(VecTypeID), Elt) ||
4656           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID))
4657         return error("Invalid record");
4658       I = InsertElementInst::Create(Vec, Elt, Idx);
4659       ResTypeID = VecTypeID;
4660       InstructionList.push_back(I);
4661       break;
4662     }
4663 
4664     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4665       unsigned OpNum = 0;
4666       Value *Vec1, *Vec2, *Mask;
4667       unsigned Vec1TypeID;
4668       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID) ||
4669           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
4670                    Vec2))
4671         return error("Invalid record");
4672 
4673       unsigned MaskTypeID;
4674       if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID))
4675         return error("Invalid record");
4676       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4677         return error("Invalid type for value");
4678 
4679       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4680       ResTypeID =
4681           getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
4682       InstructionList.push_back(I);
4683       break;
4684     }
4685 
4686     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
4687       // Old form of ICmp/FCmp returning bool
4688       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4689       // both legal on vectors but had different behaviour.
4690     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4691       // FCmp/ICmp returning bool or vector of bool
4692 
4693       unsigned OpNum = 0;
4694       Value *LHS, *RHS;
4695       unsigned LHSTypeID;
4696       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID) ||
4697           popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS))
4698         return error("Invalid record");
4699 
4700       if (OpNum >= Record.size())
4701         return error(
4702             "Invalid record: operand number exceeded available operands");
4703 
4704       unsigned PredVal = Record[OpNum];
4705       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4706       FastMathFlags FMF;
4707       if (IsFP && Record.size() > OpNum+1)
4708         FMF = getDecodedFastMathFlags(Record[++OpNum]);
4709 
4710       if (OpNum+1 != Record.size())
4711         return error("Invalid record");
4712 
4713       if (LHS->getType()->isFPOrFPVectorTy())
4714         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4715       else
4716         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4717 
4718       ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
4719       if (LHS->getType()->isVectorTy())
4720         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
4721 
4722       if (FMF.any())
4723         I->setFastMathFlags(FMF);
4724       InstructionList.push_back(I);
4725       break;
4726     }
4727 
4728     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4729       {
4730         unsigned Size = Record.size();
4731         if (Size == 0) {
4732           I = ReturnInst::Create(Context);
4733           InstructionList.push_back(I);
4734           break;
4735         }
4736 
4737         unsigned OpNum = 0;
4738         Value *Op = nullptr;
4739         unsigned OpTypeID;
4740         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))
4741           return error("Invalid record");
4742         if (OpNum != Record.size())
4743           return error("Invalid record");
4744 
4745         I = ReturnInst::Create(Context, Op);
4746         InstructionList.push_back(I);
4747         break;
4748       }
4749     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4750       if (Record.size() != 1 && Record.size() != 3)
4751         return error("Invalid record");
4752       BasicBlock *TrueDest = getBasicBlock(Record[0]);
4753       if (!TrueDest)
4754         return error("Invalid record");
4755 
4756       if (Record.size() == 1) {
4757         I = BranchInst::Create(TrueDest);
4758         InstructionList.push_back(I);
4759       }
4760       else {
4761         BasicBlock *FalseDest = getBasicBlock(Record[1]);
4762         Type *CondType = Type::getInt1Ty(Context);
4763         Value *Cond = getValue(Record, 2, NextValueNo, CondType,
4764                                getVirtualTypeID(CondType));
4765         if (!FalseDest || !Cond)
4766           return error("Invalid record");
4767         I = BranchInst::Create(TrueDest, FalseDest, Cond);
4768         InstructionList.push_back(I);
4769       }
4770       break;
4771     }
4772     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4773       if (Record.size() != 1 && Record.size() != 2)
4774         return error("Invalid record");
4775       unsigned Idx = 0;
4776       Type *TokenTy = Type::getTokenTy(Context);
4777       Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
4778                                    getVirtualTypeID(TokenTy));
4779       if (!CleanupPad)
4780         return error("Invalid record");
4781       BasicBlock *UnwindDest = nullptr;
4782       if (Record.size() == 2) {
4783         UnwindDest = getBasicBlock(Record[Idx++]);
4784         if (!UnwindDest)
4785           return error("Invalid record");
4786       }
4787 
4788       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4789       InstructionList.push_back(I);
4790       break;
4791     }
4792     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4793       if (Record.size() != 2)
4794         return error("Invalid record");
4795       unsigned Idx = 0;
4796       Type *TokenTy = Type::getTokenTy(Context);
4797       Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
4798                                  getVirtualTypeID(TokenTy));
4799       if (!CatchPad)
4800         return error("Invalid record");
4801       BasicBlock *BB = getBasicBlock(Record[Idx++]);
4802       if (!BB)
4803         return error("Invalid record");
4804 
4805       I = CatchReturnInst::Create(CatchPad, BB);
4806       InstructionList.push_back(I);
4807       break;
4808     }
4809     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4810       // We must have, at minimum, the outer scope and the number of arguments.
4811       if (Record.size() < 2)
4812         return error("Invalid record");
4813 
4814       unsigned Idx = 0;
4815 
4816       Type *TokenTy = Type::getTokenTy(Context);
4817       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
4818                                   getVirtualTypeID(TokenTy));
4819 
4820       unsigned NumHandlers = Record[Idx++];
4821 
4822       SmallVector<BasicBlock *, 2> Handlers;
4823       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4824         BasicBlock *BB = getBasicBlock(Record[Idx++]);
4825         if (!BB)
4826           return error("Invalid record");
4827         Handlers.push_back(BB);
4828       }
4829 
4830       BasicBlock *UnwindDest = nullptr;
4831       if (Idx + 1 == Record.size()) {
4832         UnwindDest = getBasicBlock(Record[Idx++]);
4833         if (!UnwindDest)
4834           return error("Invalid record");
4835       }
4836 
4837       if (Record.size() != Idx)
4838         return error("Invalid record");
4839 
4840       auto *CatchSwitch =
4841           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4842       for (BasicBlock *Handler : Handlers)
4843         CatchSwitch->addHandler(Handler);
4844       I = CatchSwitch;
4845       ResTypeID = getVirtualTypeID(I->getType());
4846       InstructionList.push_back(I);
4847       break;
4848     }
4849     case bitc::FUNC_CODE_INST_CATCHPAD:
4850     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4851       // We must have, at minimum, the outer scope and the number of arguments.
4852       if (Record.size() < 2)
4853         return error("Invalid record");
4854 
4855       unsigned Idx = 0;
4856 
4857       Type *TokenTy = Type::getTokenTy(Context);
4858       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
4859                                   getVirtualTypeID(TokenTy));
4860 
4861       unsigned NumArgOperands = Record[Idx++];
4862 
4863       SmallVector<Value *, 2> Args;
4864       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4865         Value *Val;
4866         unsigned ValTypeID;
4867         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID))
4868           return error("Invalid record");
4869         Args.push_back(Val);
4870       }
4871 
4872       if (Record.size() != Idx)
4873         return error("Invalid record");
4874 
4875       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4876         I = CleanupPadInst::Create(ParentPad, Args);
4877       else
4878         I = CatchPadInst::Create(ParentPad, Args);
4879       ResTypeID = getVirtualTypeID(I->getType());
4880       InstructionList.push_back(I);
4881       break;
4882     }
4883     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4884       // Check magic
4885       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4886         // "New" SwitchInst format with case ranges. The changes to write this
4887         // format were reverted but we still recognize bitcode that uses it.
4888         // Hopefully someday we will have support for case ranges and can use
4889         // this format again.
4890 
4891         unsigned OpTyID = Record[1];
4892         Type *OpTy = getTypeByID(OpTyID);
4893         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4894 
4895         Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID);
4896         BasicBlock *Default = getBasicBlock(Record[3]);
4897         if (!OpTy || !Cond || !Default)
4898           return error("Invalid record");
4899 
4900         unsigned NumCases = Record[4];
4901 
4902         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4903         InstructionList.push_back(SI);
4904 
4905         unsigned CurIdx = 5;
4906         for (unsigned i = 0; i != NumCases; ++i) {
4907           SmallVector<ConstantInt*, 1> CaseVals;
4908           unsigned NumItems = Record[CurIdx++];
4909           for (unsigned ci = 0; ci != NumItems; ++ci) {
4910             bool isSingleNumber = Record[CurIdx++];
4911 
4912             APInt Low;
4913             unsigned ActiveWords = 1;
4914             if (ValueBitWidth > 64)
4915               ActiveWords = Record[CurIdx++];
4916             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4917                                 ValueBitWidth);
4918             CurIdx += ActiveWords;
4919 
4920             if (!isSingleNumber) {
4921               ActiveWords = 1;
4922               if (ValueBitWidth > 64)
4923                 ActiveWords = Record[CurIdx++];
4924               APInt High = readWideAPInt(
4925                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4926               CurIdx += ActiveWords;
4927 
4928               // FIXME: It is not clear whether values in the range should be
4929               // compared as signed or unsigned values. The partially
4930               // implemented changes that used this format in the past used
4931               // unsigned comparisons.
4932               for ( ; Low.ule(High); ++Low)
4933                 CaseVals.push_back(ConstantInt::get(Context, Low));
4934             } else
4935               CaseVals.push_back(ConstantInt::get(Context, Low));
4936           }
4937           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4938           for (ConstantInt *Cst : CaseVals)
4939             SI->addCase(Cst, DestBB);
4940         }
4941         I = SI;
4942         break;
4943       }
4944 
4945       // Old SwitchInst format without case ranges.
4946 
4947       if (Record.size() < 3 || (Record.size() & 1) == 0)
4948         return error("Invalid record");
4949       unsigned OpTyID = Record[0];
4950       Type *OpTy = getTypeByID(OpTyID);
4951       Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID);
4952       BasicBlock *Default = getBasicBlock(Record[2]);
4953       if (!OpTy || !Cond || !Default)
4954         return error("Invalid record");
4955       unsigned NumCases = (Record.size()-3)/2;
4956       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4957       InstructionList.push_back(SI);
4958       for (unsigned i = 0, e = NumCases; i != e; ++i) {
4959         ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
4960             getFnValueByID(Record[3+i*2], OpTy, OpTyID));
4961         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4962         if (!CaseVal || !DestBB) {
4963           delete SI;
4964           return error("Invalid record");
4965         }
4966         SI->addCase(CaseVal, DestBB);
4967       }
4968       I = SI;
4969       break;
4970     }
4971     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4972       if (Record.size() < 2)
4973         return error("Invalid record");
4974       unsigned OpTyID = Record[0];
4975       Type *OpTy = getTypeByID(OpTyID);
4976       Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID);
4977       if (!OpTy || !Address)
4978         return error("Invalid record");
4979       unsigned NumDests = Record.size()-2;
4980       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4981       InstructionList.push_back(IBI);
4982       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4983         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4984           IBI->addDestination(DestBB);
4985         } else {
4986           delete IBI;
4987           return error("Invalid record");
4988         }
4989       }
4990       I = IBI;
4991       break;
4992     }
4993 
4994     case bitc::FUNC_CODE_INST_INVOKE: {
4995       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4996       if (Record.size() < 4)
4997         return error("Invalid record");
4998       unsigned OpNum = 0;
4999       AttributeList PAL = getAttributes(Record[OpNum++]);
5000       unsigned CCInfo = Record[OpNum++];
5001       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5002       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5003 
5004       unsigned FTyID = InvalidTypeID;
5005       FunctionType *FTy = nullptr;
5006       if ((CCInfo >> 13) & 1) {
5007         FTyID = Record[OpNum++];
5008         FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5009         if (!FTy)
5010           return error("Explicit invoke type is not a function type");
5011       }
5012 
5013       Value *Callee;
5014       unsigned CalleeTypeID;
5015       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID))
5016         return error("Invalid record");
5017 
5018       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5019       if (!CalleeTy)
5020         return error("Callee is not a pointer");
5021       if (!FTy) {
5022         FTyID = getContainedTypeID(CalleeTypeID);
5023         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5024         if (!FTy)
5025           return error("Callee is not of pointer to function type");
5026       } else if (!CalleeTy->isOpaqueOrPointeeTypeMatches(FTy))
5027         return error("Explicit invoke type does not match pointee type of "
5028                      "callee operand");
5029       if (Record.size() < FTy->getNumParams() + OpNum)
5030         return error("Insufficient operands to call");
5031 
5032       SmallVector<Value*, 16> Ops;
5033       SmallVector<unsigned, 16> ArgTyIDs;
5034       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5035         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5036         Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5037                                ArgTyID));
5038         ArgTyIDs.push_back(ArgTyID);
5039         if (!Ops.back())
5040           return error("Invalid record");
5041       }
5042 
5043       if (!FTy->isVarArg()) {
5044         if (Record.size() != OpNum)
5045           return error("Invalid record");
5046       } else {
5047         // Read type/value pairs for varargs params.
5048         while (OpNum != Record.size()) {
5049           Value *Op;
5050           unsigned OpTypeID;
5051           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))
5052             return error("Invalid record");
5053           Ops.push_back(Op);
5054           ArgTyIDs.push_back(OpTypeID);
5055         }
5056       }
5057 
5058       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
5059                              OperandBundles);
5060       ResTypeID = getContainedTypeID(FTyID);
5061       OperandBundles.clear();
5062       InstructionList.push_back(I);
5063       cast<InvokeInst>(I)->setCallingConv(
5064           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5065       cast<InvokeInst>(I)->setAttributes(PAL);
5066       propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs);
5067 
5068       break;
5069     }
5070     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5071       unsigned Idx = 0;
5072       Value *Val = nullptr;
5073       unsigned ValTypeID;
5074       if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID))
5075         return error("Invalid record");
5076       I = ResumeInst::Create(Val);
5077       InstructionList.push_back(I);
5078       break;
5079     }
5080     case bitc::FUNC_CODE_INST_CALLBR: {
5081       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
5082       unsigned OpNum = 0;
5083       AttributeList PAL = getAttributes(Record[OpNum++]);
5084       unsigned CCInfo = Record[OpNum++];
5085 
5086       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5087       unsigned NumIndirectDests = Record[OpNum++];
5088       SmallVector<BasicBlock *, 16> IndirectDests;
5089       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
5090         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
5091 
5092       unsigned FTyID = InvalidTypeID;
5093       FunctionType *FTy = nullptr;
5094       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5095         FTyID = Record[OpNum++];
5096         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5097         if (!FTy)
5098           return error("Explicit call type is not a function type");
5099       }
5100 
5101       Value *Callee;
5102       unsigned CalleeTypeID;
5103       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID))
5104         return error("Invalid record");
5105 
5106       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5107       if (!OpTy)
5108         return error("Callee is not a pointer type");
5109       if (!FTy) {
5110         FTyID = getContainedTypeID(CalleeTypeID);
5111         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5112         if (!FTy)
5113           return error("Callee is not of pointer to function type");
5114       } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
5115         return error("Explicit call type does not match pointee type of "
5116                      "callee operand");
5117       if (Record.size() < FTy->getNumParams() + OpNum)
5118         return error("Insufficient operands to call");
5119 
5120       SmallVector<Value*, 16> Args;
5121       SmallVector<unsigned, 16> ArgTyIDs;
5122       // Read the fixed params.
5123       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5124         Value *Arg;
5125         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5126         if (FTy->getParamType(i)->isLabelTy())
5127           Arg = getBasicBlock(Record[OpNum]);
5128         else
5129           Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5130                          ArgTyID);
5131         if (!Arg)
5132           return error("Invalid record");
5133         Args.push_back(Arg);
5134         ArgTyIDs.push_back(ArgTyID);
5135       }
5136 
5137       // Read type/value pairs for varargs params.
5138       if (!FTy->isVarArg()) {
5139         if (OpNum != Record.size())
5140           return error("Invalid record");
5141       } else {
5142         while (OpNum != Record.size()) {
5143           Value *Op;
5144           unsigned OpTypeID;
5145           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))
5146             return error("Invalid record");
5147           Args.push_back(Op);
5148           ArgTyIDs.push_back(OpTypeID);
5149         }
5150       }
5151 
5152       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
5153                              OperandBundles);
5154       ResTypeID = getContainedTypeID(FTyID);
5155       OperandBundles.clear();
5156       InstructionList.push_back(I);
5157       cast<CallBrInst>(I)->setCallingConv(
5158           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5159       cast<CallBrInst>(I)->setAttributes(PAL);
5160       propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs);
5161       break;
5162     }
5163     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
5164       I = new UnreachableInst(Context);
5165       InstructionList.push_back(I);
5166       break;
5167     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5168       if (Record.empty())
5169         return error("Invalid record");
5170       // The first record specifies the type.
5171       unsigned TyID = Record[0];
5172       Type *Ty = getTypeByID(TyID);
5173       if (!Ty)
5174         return error("Invalid record");
5175 
5176       // Phi arguments are pairs of records of [value, basic block].
5177       // There is an optional final record for fast-math-flags if this phi has a
5178       // floating-point type.
5179       size_t NumArgs = (Record.size() - 1) / 2;
5180       PHINode *PN = PHINode::Create(Ty, NumArgs);
5181       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN))
5182         return error("Invalid record");
5183       InstructionList.push_back(PN);
5184 
5185       for (unsigned i = 0; i != NumArgs; i++) {
5186         Value *V;
5187         // With the new function encoding, it is possible that operands have
5188         // negative IDs (for forward references).  Use a signed VBR
5189         // representation to keep the encoding small.
5190         if (UseRelativeIDs)
5191           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID);
5192         else
5193           V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID);
5194         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
5195         if (!V || !BB)
5196           return error("Invalid record");
5197         PN->addIncoming(V, BB);
5198       }
5199       I = PN;
5200       ResTypeID = TyID;
5201 
5202       // If there are an even number of records, the final record must be FMF.
5203       if (Record.size() % 2 == 0) {
5204         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
5205         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
5206         if (FMF.any())
5207           I->setFastMathFlags(FMF);
5208       }
5209 
5210       break;
5211     }
5212 
5213     case bitc::FUNC_CODE_INST_LANDINGPAD:
5214     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
5215       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5216       unsigned Idx = 0;
5217       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5218         if (Record.size() < 3)
5219           return error("Invalid record");
5220       } else {
5221         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5222         if (Record.size() < 4)
5223           return error("Invalid record");
5224       }
5225       ResTypeID = Record[Idx++];
5226       Type *Ty = getTypeByID(ResTypeID);
5227       if (!Ty)
5228         return error("Invalid record");
5229       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5230         Value *PersFn = nullptr;
5231         unsigned PersFnTypeID;
5232         if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID))
5233           return error("Invalid record");
5234 
5235         if (!F->hasPersonalityFn())
5236           F->setPersonalityFn(cast<Constant>(PersFn));
5237         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5238           return error("Personality function mismatch");
5239       }
5240 
5241       bool IsCleanup = !!Record[Idx++];
5242       unsigned NumClauses = Record[Idx++];
5243       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
5244       LP->setCleanup(IsCleanup);
5245       for (unsigned J = 0; J != NumClauses; ++J) {
5246         LandingPadInst::ClauseType CT =
5247           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5248         Value *Val;
5249         unsigned ValTypeID;
5250 
5251         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID)) {
5252           delete LP;
5253           return error("Invalid record");
5254         }
5255 
5256         assert((CT != LandingPadInst::Catch ||
5257                 !isa<ArrayType>(Val->getType())) &&
5258                "Catch clause has a invalid type!");
5259         assert((CT != LandingPadInst::Filter ||
5260                 isa<ArrayType>(Val->getType())) &&
5261                "Filter clause has invalid type!");
5262         LP->addClause(cast<Constant>(Val));
5263       }
5264 
5265       I = LP;
5266       InstructionList.push_back(I);
5267       break;
5268     }
5269 
5270     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5271       if (Record.size() != 4)
5272         return error("Invalid record");
5273       using APV = AllocaPackedValues;
5274       const uint64_t Rec = Record[3];
5275       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
5276       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
5277       unsigned TyID = Record[0];
5278       Type *Ty = getTypeByID(TyID);
5279       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
5280         TyID = getContainedTypeID(TyID);
5281         Ty = getTypeByID(TyID);
5282         if (!Ty)
5283           return error("Missing element type for old-style alloca");
5284       }
5285       unsigned OpTyID = Record[1];
5286       Type *OpTy = getTypeByID(OpTyID);
5287       Value *Size = getFnValueByID(Record[2], OpTy, OpTyID);
5288       MaybeAlign Align;
5289       uint64_t AlignExp =
5290           Bitfield::get<APV::AlignLower>(Rec) |
5291           (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
5292       if (Error Err = parseAlignmentValue(AlignExp, Align)) {
5293         return Err;
5294       }
5295       if (!Ty || !Size)
5296         return error("Invalid record");
5297 
5298       // FIXME: Make this an optional field.
5299       const DataLayout &DL = TheModule->getDataLayout();
5300       unsigned AS = DL.getAllocaAddrSpace();
5301 
5302       SmallPtrSet<Type *, 4> Visited;
5303       if (!Align && !Ty->isSized(&Visited))
5304         return error("alloca of unsized type");
5305       if (!Align)
5306         Align = DL.getPrefTypeAlign(Ty);
5307 
5308       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
5309       AI->setUsedWithInAlloca(InAlloca);
5310       AI->setSwiftError(SwiftError);
5311       I = AI;
5312       ResTypeID = getVirtualTypeID(AI->getType(), TyID);
5313       InstructionList.push_back(I);
5314       break;
5315     }
5316     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
5317       unsigned OpNum = 0;
5318       Value *Op;
5319       unsigned OpTypeID;
5320       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID) ||
5321           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
5322         return error("Invalid record");
5323 
5324       if (!isa<PointerType>(Op->getType()))
5325         return error("Load operand is not a pointer type");
5326 
5327       Type *Ty = nullptr;
5328       if (OpNum + 3 == Record.size()) {
5329         ResTypeID = Record[OpNum++];
5330         Ty = getTypeByID(ResTypeID);
5331       } else {
5332         ResTypeID = getContainedTypeID(OpTypeID);
5333         Ty = getTypeByID(ResTypeID);
5334         if (!Ty)
5335           return error("Missing element type for old-style load");
5336       }
5337 
5338       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5339         return Err;
5340 
5341       MaybeAlign Align;
5342       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5343         return Err;
5344       SmallPtrSet<Type *, 4> Visited;
5345       if (!Align && !Ty->isSized(&Visited))
5346         return error("load of unsized type");
5347       if (!Align)
5348         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
5349       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
5350       InstructionList.push_back(I);
5351       break;
5352     }
5353     case bitc::FUNC_CODE_INST_LOADATOMIC: {
5354        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
5355       unsigned OpNum = 0;
5356       Value *Op;
5357       unsigned OpTypeID;
5358       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID) ||
5359           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
5360         return error("Invalid record");
5361 
5362       if (!isa<PointerType>(Op->getType()))
5363         return error("Load operand is not a pointer type");
5364 
5365       Type *Ty = nullptr;
5366       if (OpNum + 5 == Record.size()) {
5367         ResTypeID = Record[OpNum++];
5368         Ty = getTypeByID(ResTypeID);
5369       } else {
5370         ResTypeID = getContainedTypeID(OpTypeID);
5371         Ty = getTypeByID(ResTypeID);
5372         if (!Ty)
5373           return error("Missing element type for old style atomic load");
5374       }
5375 
5376       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
5377         return Err;
5378 
5379       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5380       if (Ordering == AtomicOrdering::NotAtomic ||
5381           Ordering == AtomicOrdering::Release ||
5382           Ordering == AtomicOrdering::AcquireRelease)
5383         return error("Invalid record");
5384       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5385         return error("Invalid record");
5386       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5387 
5388       MaybeAlign Align;
5389       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5390         return Err;
5391       if (!Align)
5392         return error("Alignment missing from atomic load");
5393       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
5394       InstructionList.push_back(I);
5395       break;
5396     }
5397     case bitc::FUNC_CODE_INST_STORE:
5398     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
5399       unsigned OpNum = 0;
5400       Value *Val, *Ptr;
5401       unsigned PtrTypeID, ValTypeID;
5402       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))
5403         return error("Invalid record");
5404 
5405       if (BitCode == bitc::FUNC_CODE_INST_STORE) {
5406         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID))
5407           return error("Invalid record");
5408       } else {
5409         ValTypeID = getContainedTypeID(PtrTypeID);
5410         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
5411                      ValTypeID, Val))
5412           return error("Invalid record");
5413       }
5414 
5415       if (OpNum + 2 != Record.size())
5416         return error("Invalid record");
5417 
5418       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5419         return Err;
5420       MaybeAlign Align;
5421       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5422         return Err;
5423       SmallPtrSet<Type *, 4> Visited;
5424       if (!Align && !Val->getType()->isSized(&Visited))
5425         return error("store of unsized type");
5426       if (!Align)
5427         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
5428       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
5429       InstructionList.push_back(I);
5430       break;
5431     }
5432     case bitc::FUNC_CODE_INST_STOREATOMIC:
5433     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
5434       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
5435       unsigned OpNum = 0;
5436       Value *Val, *Ptr;
5437       unsigned PtrTypeID, ValTypeID;
5438       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID) ||
5439           !isa<PointerType>(Ptr->getType()))
5440         return error("Invalid record");
5441       if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
5442         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID))
5443           return error("Invalid record");
5444       } else {
5445         ValTypeID = getContainedTypeID(PtrTypeID);
5446         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
5447                      ValTypeID, Val))
5448           return error("Invalid record");
5449       }
5450 
5451       if (OpNum + 4 != Record.size())
5452         return error("Invalid record");
5453 
5454       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
5455         return Err;
5456       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5457       if (Ordering == AtomicOrdering::NotAtomic ||
5458           Ordering == AtomicOrdering::Acquire ||
5459           Ordering == AtomicOrdering::AcquireRelease)
5460         return error("Invalid record");
5461       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5462       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
5463         return error("Invalid record");
5464 
5465       MaybeAlign Align;
5466       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
5467         return Err;
5468       if (!Align)
5469         return error("Alignment missing from atomic store");
5470       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
5471       InstructionList.push_back(I);
5472       break;
5473     }
5474     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
5475       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
5476       // failure_ordering?, weak?]
5477       const size_t NumRecords = Record.size();
5478       unsigned OpNum = 0;
5479       Value *Ptr = nullptr;
5480       unsigned PtrTypeID;
5481       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))
5482         return error("Invalid record");
5483 
5484       if (!isa<PointerType>(Ptr->getType()))
5485         return error("Cmpxchg operand is not a pointer type");
5486 
5487       Value *Cmp = nullptr;
5488       unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
5489       if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
5490                    CmpTypeID, Cmp))
5491         return error("Invalid record");
5492 
5493       Value *New = nullptr;
5494       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
5495                    New) ||
5496           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
5497         return error("Invalid record");
5498 
5499       const AtomicOrdering SuccessOrdering =
5500           getDecodedOrdering(Record[OpNum + 1]);
5501       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
5502           SuccessOrdering == AtomicOrdering::Unordered)
5503         return error("Invalid record");
5504 
5505       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5506 
5507       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5508         return Err;
5509 
5510       const AtomicOrdering FailureOrdering =
5511           NumRecords < 7
5512               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
5513               : getDecodedOrdering(Record[OpNum + 3]);
5514 
5515       if (FailureOrdering == AtomicOrdering::NotAtomic ||
5516           FailureOrdering == AtomicOrdering::Unordered)
5517         return error("Invalid record");
5518 
5519       const Align Alignment(
5520           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5521 
5522       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
5523                                 FailureOrdering, SSID);
5524       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
5525 
5526       if (NumRecords < 8) {
5527         // Before weak cmpxchgs existed, the instruction simply returned the
5528         // value loaded from memory, so bitcode files from that era will be
5529         // expecting the first component of a modern cmpxchg.
5530         CurBB->getInstList().push_back(I);
5531         I = ExtractValueInst::Create(I, 0);
5532         ResTypeID = CmpTypeID;
5533       } else {
5534         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
5535         unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
5536         ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
5537       }
5538 
5539       InstructionList.push_back(I);
5540       break;
5541     }
5542     case bitc::FUNC_CODE_INST_CMPXCHG: {
5543       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
5544       // failure_ordering, weak, align?]
5545       const size_t NumRecords = Record.size();
5546       unsigned OpNum = 0;
5547       Value *Ptr = nullptr;
5548       unsigned PtrTypeID;
5549       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))
5550         return error("Invalid record");
5551 
5552       if (!isa<PointerType>(Ptr->getType()))
5553         return error("Cmpxchg operand is not a pointer type");
5554 
5555       Value *Cmp = nullptr;
5556       unsigned CmpTypeID;
5557       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID))
5558         return error("Invalid record");
5559 
5560       Value *Val = nullptr;
5561       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val))
5562         return error("Invalid record");
5563 
5564       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
5565         return error("Invalid record");
5566 
5567       const bool IsVol = Record[OpNum];
5568 
5569       const AtomicOrdering SuccessOrdering =
5570           getDecodedOrdering(Record[OpNum + 1]);
5571       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
5572         return error("Invalid cmpxchg success ordering");
5573 
5574       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
5575 
5576       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
5577         return Err;
5578 
5579       const AtomicOrdering FailureOrdering =
5580           getDecodedOrdering(Record[OpNum + 3]);
5581       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
5582         return error("Invalid cmpxchg failure ordering");
5583 
5584       const bool IsWeak = Record[OpNum + 4];
5585 
5586       MaybeAlign Alignment;
5587 
5588       if (NumRecords == (OpNum + 6)) {
5589         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
5590           return Err;
5591       }
5592       if (!Alignment)
5593         Alignment =
5594             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
5595 
5596       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
5597                                 FailureOrdering, SSID);
5598       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
5599       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
5600 
5601       unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
5602       ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
5603 
5604       InstructionList.push_back(I);
5605       break;
5606     }
5607     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
5608     case bitc::FUNC_CODE_INST_ATOMICRMW: {
5609       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
5610       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
5611       const size_t NumRecords = Record.size();
5612       unsigned OpNum = 0;
5613 
5614       Value *Ptr = nullptr;
5615       unsigned PtrTypeID;
5616       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID))
5617         return error("Invalid record");
5618 
5619       if (!isa<PointerType>(Ptr->getType()))
5620         return error("Invalid record");
5621 
5622       Value *Val = nullptr;
5623       unsigned ValTypeID = InvalidTypeID;
5624       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
5625         ValTypeID = getContainedTypeID(PtrTypeID);
5626         if (popValue(Record, OpNum, NextValueNo,
5627                      getTypeByID(ValTypeID), ValTypeID, Val))
5628           return error("Invalid record");
5629       } else {
5630         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID))
5631           return error("Invalid record");
5632       }
5633 
5634       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
5635         return error("Invalid record");
5636 
5637       const AtomicRMWInst::BinOp Operation =
5638           getDecodedRMWOperation(Record[OpNum]);
5639       if (Operation < AtomicRMWInst::FIRST_BINOP ||
5640           Operation > AtomicRMWInst::LAST_BINOP)
5641         return error("Invalid record");
5642 
5643       const bool IsVol = Record[OpNum + 1];
5644 
5645       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5646       if (Ordering == AtomicOrdering::NotAtomic ||
5647           Ordering == AtomicOrdering::Unordered)
5648         return error("Invalid record");
5649 
5650       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
5651 
5652       MaybeAlign Alignment;
5653 
5654       if (NumRecords == (OpNum + 5)) {
5655         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
5656           return Err;
5657       }
5658 
5659       if (!Alignment)
5660         Alignment =
5661             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
5662 
5663       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
5664       ResTypeID = ValTypeID;
5665       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
5666 
5667       InstructionList.push_back(I);
5668       break;
5669     }
5670     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
5671       if (2 != Record.size())
5672         return error("Invalid record");
5673       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5674       if (Ordering == AtomicOrdering::NotAtomic ||
5675           Ordering == AtomicOrdering::Unordered ||
5676           Ordering == AtomicOrdering::Monotonic)
5677         return error("Invalid record");
5678       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
5679       I = new FenceInst(Context, Ordering, SSID);
5680       InstructionList.push_back(I);
5681       break;
5682     }
5683     case bitc::FUNC_CODE_INST_CALL: {
5684       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5685       if (Record.size() < 3)
5686         return error("Invalid record");
5687 
5688       unsigned OpNum = 0;
5689       AttributeList PAL = getAttributes(Record[OpNum++]);
5690       unsigned CCInfo = Record[OpNum++];
5691 
5692       FastMathFlags FMF;
5693       if ((CCInfo >> bitc::CALL_FMF) & 1) {
5694         FMF = getDecodedFastMathFlags(Record[OpNum++]);
5695         if (!FMF.any())
5696           return error("Fast math flags indicator set for call with no FMF");
5697       }
5698 
5699       unsigned FTyID = InvalidTypeID;
5700       FunctionType *FTy = nullptr;
5701       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5702         FTyID = Record[OpNum++];
5703         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5704         if (!FTy)
5705           return error("Explicit call type is not a function type");
5706       }
5707 
5708       Value *Callee;
5709       unsigned CalleeTypeID;
5710       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID))
5711         return error("Invalid record");
5712 
5713       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5714       if (!OpTy)
5715         return error("Callee is not a pointer type");
5716       if (!FTy) {
5717         FTyID = getContainedTypeID(CalleeTypeID);
5718         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5719         if (!FTy)
5720           return error("Callee is not of pointer to function type");
5721       } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
5722         return error("Explicit call type does not match pointee type of "
5723                      "callee operand");
5724       if (Record.size() < FTy->getNumParams() + OpNum)
5725         return error("Insufficient operands to call");
5726 
5727       SmallVector<Value*, 16> Args;
5728       SmallVector<unsigned, 16> ArgTyIDs;
5729       // Read the fixed params.
5730       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5731         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5732         if (FTy->getParamType(i)->isLabelTy())
5733           Args.push_back(getBasicBlock(Record[OpNum]));
5734         else
5735           Args.push_back(getValue(Record, OpNum, NextValueNo,
5736                                   FTy->getParamType(i), ArgTyID));
5737         ArgTyIDs.push_back(ArgTyID);
5738         if (!Args.back())
5739           return error("Invalid record");
5740       }
5741 
5742       // Read type/value pairs for varargs params.
5743       if (!FTy->isVarArg()) {
5744         if (OpNum != Record.size())
5745           return error("Invalid record");
5746       } else {
5747         while (OpNum != Record.size()) {
5748           Value *Op;
5749           unsigned OpTypeID;
5750           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))
5751             return error("Invalid record");
5752           Args.push_back(Op);
5753           ArgTyIDs.push_back(OpTypeID);
5754         }
5755       }
5756 
5757       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5758       ResTypeID = getContainedTypeID(FTyID);
5759       OperandBundles.clear();
5760       InstructionList.push_back(I);
5761       cast<CallInst>(I)->setCallingConv(
5762           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5763       CallInst::TailCallKind TCK = CallInst::TCK_None;
5764       if (CCInfo & 1 << bitc::CALL_TAIL)
5765         TCK = CallInst::TCK_Tail;
5766       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5767         TCK = CallInst::TCK_MustTail;
5768       if (CCInfo & (1 << bitc::CALL_NOTAIL))
5769         TCK = CallInst::TCK_NoTail;
5770       cast<CallInst>(I)->setTailCallKind(TCK);
5771       cast<CallInst>(I)->setAttributes(PAL);
5772       propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs);
5773       if (FMF.any()) {
5774         if (!isa<FPMathOperator>(I))
5775           return error("Fast-math-flags specified for call without "
5776                        "floating-point scalar or vector return type");
5777         I->setFastMathFlags(FMF);
5778       }
5779       break;
5780     }
5781     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5782       if (Record.size() < 3)
5783         return error("Invalid record");
5784       unsigned OpTyID = Record[0];
5785       Type *OpTy = getTypeByID(OpTyID);
5786       Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID);
5787       ResTypeID = Record[2];
5788       Type *ResTy = getTypeByID(ResTypeID);
5789       if (!OpTy || !Op || !ResTy)
5790         return error("Invalid record");
5791       I = new VAArgInst(Op, ResTy);
5792       InstructionList.push_back(I);
5793       break;
5794     }
5795 
5796     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5797       // A call or an invoke can be optionally prefixed with some variable
5798       // number of operand bundle blocks.  These blocks are read into
5799       // OperandBundles and consumed at the next call or invoke instruction.
5800 
5801       if (Record.empty() || Record[0] >= BundleTags.size())
5802         return error("Invalid record");
5803 
5804       std::vector<Value *> Inputs;
5805 
5806       unsigned OpNum = 1;
5807       while (OpNum != Record.size()) {
5808         Value *Op;
5809         unsigned OpTypeID;
5810         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))
5811           return error("Invalid record");
5812         Inputs.push_back(Op);
5813       }
5814 
5815       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5816       continue;
5817     }
5818 
5819     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
5820       unsigned OpNum = 0;
5821       Value *Op = nullptr;
5822       unsigned OpTypeID;
5823       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID))
5824         return error("Invalid record");
5825       if (OpNum != Record.size())
5826         return error("Invalid record");
5827 
5828       I = new FreezeInst(Op);
5829       ResTypeID = OpTypeID;
5830       InstructionList.push_back(I);
5831       break;
5832     }
5833     }
5834 
5835     // Add instruction to end of current BB.  If there is no current BB, reject
5836     // this file.
5837     if (!CurBB) {
5838       I->deleteValue();
5839       return error("Invalid instruction with no BB");
5840     }
5841     if (!OperandBundles.empty()) {
5842       I->deleteValue();
5843       return error("Operand bundles found with no consumer");
5844     }
5845     CurBB->getInstList().push_back(I);
5846 
5847     // If this was a terminator instruction, move to the next block.
5848     if (I->isTerminator()) {
5849       ++CurBBNo;
5850       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5851     }
5852 
5853     // Non-void values get registered in the value table for future use.
5854     if (!I->getType()->isVoidTy()) {
5855       assert(I->getType() == getTypeByID(ResTypeID) &&
5856              "Incorrect result type ID");
5857       ValueList.assignValue(NextValueNo++, I, ResTypeID);
5858     }
5859   }
5860 
5861 OutOfRecordLoop:
5862 
5863   if (!OperandBundles.empty())
5864     return error("Operand bundles found with no consumer");
5865 
5866   // Check the function list for unresolved values.
5867   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5868     if (!A->getParent()) {
5869       // We found at least one unresolved value.  Nuke them all to avoid leaks.
5870       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5871         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5872           A->replaceAllUsesWith(UndefValue::get(A->getType()));
5873           delete A;
5874         }
5875       }
5876       return error("Never resolved value found in function");
5877     }
5878   }
5879 
5880   // Unexpected unresolved metadata about to be dropped.
5881   if (MDLoader->hasFwdRefs())
5882     return error("Invalid function metadata: outgoing forward refs");
5883 
5884   // Trim the value list down to the size it was before we parsed this function.
5885   ValueList.shrinkTo(ModuleValueListSize);
5886   MDLoader->shrinkTo(ModuleMDLoaderSize);
5887   std::vector<BasicBlock*>().swap(FunctionBBs);
5888   return Error::success();
5889 }
5890 
5891 /// Find the function body in the bitcode stream
5892 Error BitcodeReader::findFunctionInStream(
5893     Function *F,
5894     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5895   while (DeferredFunctionInfoIterator->second == 0) {
5896     // This is the fallback handling for the old format bitcode that
5897     // didn't contain the function index in the VST, or when we have
5898     // an anonymous function which would not have a VST entry.
5899     // Assert that we have one of those two cases.
5900     assert(VSTOffset == 0 || !F->hasName());
5901     // Parse the next body in the stream and set its position in the
5902     // DeferredFunctionInfo map.
5903     if (Error Err = rememberAndSkipFunctionBodies())
5904       return Err;
5905   }
5906   return Error::success();
5907 }
5908 
5909 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
5910   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
5911     return SyncScope::ID(Val);
5912   if (Val >= SSIDs.size())
5913     return SyncScope::System; // Map unknown synchronization scopes to system.
5914   return SSIDs[Val];
5915 }
5916 
5917 //===----------------------------------------------------------------------===//
5918 // GVMaterializer implementation
5919 //===----------------------------------------------------------------------===//
5920 
5921 Error BitcodeReader::materialize(GlobalValue *GV) {
5922   Function *F = dyn_cast<Function>(GV);
5923   // If it's not a function or is already material, ignore the request.
5924   if (!F || !F->isMaterializable())
5925     return Error::success();
5926 
5927   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5928   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5929   // If its position is recorded as 0, its body is somewhere in the stream
5930   // but we haven't seen it yet.
5931   if (DFII->second == 0)
5932     if (Error Err = findFunctionInStream(F, DFII))
5933       return Err;
5934 
5935   // Materialize metadata before parsing any function bodies.
5936   if (Error Err = materializeMetadata())
5937     return Err;
5938 
5939   // Move the bit stream to the saved position of the deferred function body.
5940   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
5941     return JumpFailed;
5942   if (Error Err = parseFunctionBody(F))
5943     return Err;
5944   F->setIsMaterializable(false);
5945 
5946   if (StripDebugInfo)
5947     stripDebugInfo(*F);
5948 
5949   // Upgrade any old intrinsic calls in the function.
5950   for (auto &I : UpgradedIntrinsics) {
5951     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
5952       if (CallInst *CI = dyn_cast<CallInst>(U))
5953         UpgradeIntrinsicCall(CI, I.second);
5954   }
5955 
5956   // Update calls to the remangled intrinsics
5957   for (auto &I : RemangledIntrinsics)
5958     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
5959       // Don't expect any other users than call sites
5960       cast<CallBase>(U)->setCalledFunction(I.second);
5961 
5962   // Finish fn->subprogram upgrade for materialized functions.
5963   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
5964     F->setSubprogram(SP);
5965 
5966   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
5967   if (!MDLoader->isStrippingTBAA()) {
5968     for (auto &I : instructions(F)) {
5969       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
5970       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
5971         continue;
5972       MDLoader->setStripTBAA(true);
5973       stripTBAA(F->getParent());
5974     }
5975   }
5976 
5977   for (auto &I : instructions(F)) {
5978     // "Upgrade" older incorrect branch weights by dropping them.
5979     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
5980       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
5981         MDString *MDS = cast<MDString>(MD->getOperand(0));
5982         StringRef ProfName = MDS->getString();
5983         // Check consistency of !prof branch_weights metadata.
5984         if (!ProfName.equals("branch_weights"))
5985           continue;
5986         unsigned ExpectedNumOperands = 0;
5987         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
5988           ExpectedNumOperands = BI->getNumSuccessors();
5989         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
5990           ExpectedNumOperands = SI->getNumSuccessors();
5991         else if (isa<CallInst>(&I))
5992           ExpectedNumOperands = 1;
5993         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
5994           ExpectedNumOperands = IBI->getNumDestinations();
5995         else if (isa<SelectInst>(&I))
5996           ExpectedNumOperands = 2;
5997         else
5998           continue; // ignore and continue.
5999 
6000         // If branch weight doesn't match, just strip branch weight.
6001         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
6002           I.setMetadata(LLVMContext::MD_prof, nullptr);
6003       }
6004     }
6005 
6006     // Remove incompatible attributes on function calls.
6007     if (auto *CI = dyn_cast<CallBase>(&I)) {
6008       CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
6009           CI->getFunctionType()->getReturnType()));
6010 
6011       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
6012         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
6013                                         CI->getArgOperand(ArgNo)->getType()));
6014     }
6015   }
6016 
6017   // Look for functions that rely on old function attribute behavior.
6018   UpgradeFunctionAttributes(*F);
6019 
6020   // Bring in any functions that this function forward-referenced via
6021   // blockaddresses.
6022   return materializeForwardReferencedFunctions();
6023 }
6024 
6025 Error BitcodeReader::materializeModule() {
6026   if (Error Err = materializeMetadata())
6027     return Err;
6028 
6029   // Promise to materialize all forward references.
6030   WillMaterializeAllForwardRefs = true;
6031 
6032   // Iterate over the module, deserializing any functions that are still on
6033   // disk.
6034   for (Function &F : *TheModule) {
6035     if (Error Err = materialize(&F))
6036       return Err;
6037   }
6038   // At this point, if there are any function bodies, parse the rest of
6039   // the bits in the module past the last function block we have recorded
6040   // through either lazy scanning or the VST.
6041   if (LastFunctionBlockBit || NextUnreadBit)
6042     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
6043                                     ? LastFunctionBlockBit
6044                                     : NextUnreadBit))
6045       return Err;
6046 
6047   // Check that all block address forward references got resolved (as we
6048   // promised above).
6049   if (!BasicBlockFwdRefs.empty())
6050     return error("Never resolved function from blockaddress");
6051 
6052   // Upgrade any intrinsic calls that slipped through (should not happen!) and
6053   // delete the old functions to clean up. We can't do this unless the entire
6054   // module is materialized because there could always be another function body
6055   // with calls to the old function.
6056   for (auto &I : UpgradedIntrinsics) {
6057     for (auto *U : I.first->users()) {
6058       if (CallInst *CI = dyn_cast<CallInst>(U))
6059         UpgradeIntrinsicCall(CI, I.second);
6060     }
6061     if (!I.first->use_empty())
6062       I.first->replaceAllUsesWith(I.second);
6063     I.first->eraseFromParent();
6064   }
6065   UpgradedIntrinsics.clear();
6066   // Do the same for remangled intrinsics
6067   for (auto &I : RemangledIntrinsics) {
6068     I.first->replaceAllUsesWith(I.second);
6069     I.first->eraseFromParent();
6070   }
6071   RemangledIntrinsics.clear();
6072 
6073   UpgradeDebugInfo(*TheModule);
6074 
6075   UpgradeModuleFlags(*TheModule);
6076 
6077   UpgradeARCRuntime(*TheModule);
6078 
6079   return Error::success();
6080 }
6081 
6082 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
6083   return IdentifiedStructTypes;
6084 }
6085 
6086 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
6087     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
6088     StringRef ModulePath, unsigned ModuleId)
6089     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
6090       ModulePath(ModulePath), ModuleId(ModuleId) {}
6091 
6092 void ModuleSummaryIndexBitcodeReader::addThisModule() {
6093   TheIndex.addModule(ModulePath, ModuleId);
6094 }
6095 
6096 ModuleSummaryIndex::ModuleInfo *
6097 ModuleSummaryIndexBitcodeReader::getThisModule() {
6098   return TheIndex.getModule(ModulePath);
6099 }
6100 
6101 std::pair<ValueInfo, GlobalValue::GUID>
6102 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
6103   auto VGI = ValueIdToValueInfoMap[ValueId];
6104   assert(VGI.first);
6105   return VGI;
6106 }
6107 
6108 void ModuleSummaryIndexBitcodeReader::setValueGUID(
6109     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
6110     StringRef SourceFileName) {
6111   std::string GlobalId =
6112       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
6113   auto ValueGUID = GlobalValue::getGUID(GlobalId);
6114   auto OriginalNameID = ValueGUID;
6115   if (GlobalValue::isLocalLinkage(Linkage))
6116     OriginalNameID = GlobalValue::getGUID(ValueName);
6117   if (PrintSummaryGUIDs)
6118     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
6119            << ValueName << "\n";
6120 
6121   // UseStrtab is false for legacy summary formats and value names are
6122   // created on stack. In that case we save the name in a string saver in
6123   // the index so that the value name can be recorded.
6124   ValueIdToValueInfoMap[ValueID] = std::make_pair(
6125       TheIndex.getOrInsertValueInfo(
6126           ValueGUID,
6127           UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
6128       OriginalNameID);
6129 }
6130 
6131 // Specialized value symbol table parser used when reading module index
6132 // blocks where we don't actually create global values. The parsed information
6133 // is saved in the bitcode reader for use when later parsing summaries.
6134 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
6135     uint64_t Offset,
6136     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
6137   // With a strtab the VST is not required to parse the summary.
6138   if (UseStrtab)
6139     return Error::success();
6140 
6141   assert(Offset > 0 && "Expected non-zero VST offset");
6142   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
6143   if (!MaybeCurrentBit)
6144     return MaybeCurrentBit.takeError();
6145   uint64_t CurrentBit = MaybeCurrentBit.get();
6146 
6147   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
6148     return Err;
6149 
6150   SmallVector<uint64_t, 64> Record;
6151 
6152   // Read all the records for this value table.
6153   SmallString<128> ValueName;
6154 
6155   while (true) {
6156     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6157     if (!MaybeEntry)
6158       return MaybeEntry.takeError();
6159     BitstreamEntry Entry = MaybeEntry.get();
6160 
6161     switch (Entry.Kind) {
6162     case BitstreamEntry::SubBlock: // Handled for us already.
6163     case BitstreamEntry::Error:
6164       return error("Malformed block");
6165     case BitstreamEntry::EndBlock:
6166       // Done parsing VST, jump back to wherever we came from.
6167       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
6168         return JumpFailed;
6169       return Error::success();
6170     case BitstreamEntry::Record:
6171       // The interesting case.
6172       break;
6173     }
6174 
6175     // Read a record.
6176     Record.clear();
6177     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6178     if (!MaybeRecord)
6179       return MaybeRecord.takeError();
6180     switch (MaybeRecord.get()) {
6181     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
6182       break;
6183     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
6184       if (convertToString(Record, 1, ValueName))
6185         return error("Invalid record");
6186       unsigned ValueID = Record[0];
6187       assert(!SourceFileName.empty());
6188       auto VLI = ValueIdToLinkageMap.find(ValueID);
6189       assert(VLI != ValueIdToLinkageMap.end() &&
6190              "No linkage found for VST entry?");
6191       auto Linkage = VLI->second;
6192       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
6193       ValueName.clear();
6194       break;
6195     }
6196     case bitc::VST_CODE_FNENTRY: {
6197       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
6198       if (convertToString(Record, 2, ValueName))
6199         return error("Invalid record");
6200       unsigned ValueID = Record[0];
6201       assert(!SourceFileName.empty());
6202       auto VLI = ValueIdToLinkageMap.find(ValueID);
6203       assert(VLI != ValueIdToLinkageMap.end() &&
6204              "No linkage found for VST entry?");
6205       auto Linkage = VLI->second;
6206       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
6207       ValueName.clear();
6208       break;
6209     }
6210     case bitc::VST_CODE_COMBINED_ENTRY: {
6211       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
6212       unsigned ValueID = Record[0];
6213       GlobalValue::GUID RefGUID = Record[1];
6214       // The "original name", which is the second value of the pair will be
6215       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
6216       ValueIdToValueInfoMap[ValueID] =
6217           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
6218       break;
6219     }
6220     }
6221   }
6222 }
6223 
6224 // Parse just the blocks needed for building the index out of the module.
6225 // At the end of this routine the module Index is populated with a map
6226 // from global value id to GlobalValueSummary objects.
6227 Error ModuleSummaryIndexBitcodeReader::parseModule() {
6228   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6229     return Err;
6230 
6231   SmallVector<uint64_t, 64> Record;
6232   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
6233   unsigned ValueId = 0;
6234 
6235   // Read the index for this module.
6236   while (true) {
6237     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6238     if (!MaybeEntry)
6239       return MaybeEntry.takeError();
6240     llvm::BitstreamEntry Entry = MaybeEntry.get();
6241 
6242     switch (Entry.Kind) {
6243     case BitstreamEntry::Error:
6244       return error("Malformed block");
6245     case BitstreamEntry::EndBlock:
6246       return Error::success();
6247 
6248     case BitstreamEntry::SubBlock:
6249       switch (Entry.ID) {
6250       default: // Skip unknown content.
6251         if (Error Err = Stream.SkipBlock())
6252           return Err;
6253         break;
6254       case bitc::BLOCKINFO_BLOCK_ID:
6255         // Need to parse these to get abbrev ids (e.g. for VST)
6256         if (Error Err = readBlockInfo())
6257           return Err;
6258         break;
6259       case bitc::VALUE_SYMTAB_BLOCK_ID:
6260         // Should have been parsed earlier via VSTOffset, unless there
6261         // is no summary section.
6262         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
6263                 !SeenGlobalValSummary) &&
6264                "Expected early VST parse via VSTOffset record");
6265         if (Error Err = Stream.SkipBlock())
6266           return Err;
6267         break;
6268       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
6269       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
6270         // Add the module if it is a per-module index (has a source file name).
6271         if (!SourceFileName.empty())
6272           addThisModule();
6273         assert(!SeenValueSymbolTable &&
6274                "Already read VST when parsing summary block?");
6275         // We might not have a VST if there were no values in the
6276         // summary. An empty summary block generated when we are
6277         // performing ThinLTO compiles so we don't later invoke
6278         // the regular LTO process on them.
6279         if (VSTOffset > 0) {
6280           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
6281             return Err;
6282           SeenValueSymbolTable = true;
6283         }
6284         SeenGlobalValSummary = true;
6285         if (Error Err = parseEntireSummary(Entry.ID))
6286           return Err;
6287         break;
6288       case bitc::MODULE_STRTAB_BLOCK_ID:
6289         if (Error Err = parseModuleStringTable())
6290           return Err;
6291         break;
6292       }
6293       continue;
6294 
6295     case BitstreamEntry::Record: {
6296         Record.clear();
6297         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6298         if (!MaybeBitCode)
6299           return MaybeBitCode.takeError();
6300         switch (MaybeBitCode.get()) {
6301         default:
6302           break; // Default behavior, ignore unknown content.
6303         case bitc::MODULE_CODE_VERSION: {
6304           if (Error Err = parseVersionRecord(Record).takeError())
6305             return Err;
6306           break;
6307         }
6308         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
6309         case bitc::MODULE_CODE_SOURCE_FILENAME: {
6310           SmallString<128> ValueName;
6311           if (convertToString(Record, 0, ValueName))
6312             return error("Invalid record");
6313           SourceFileName = ValueName.c_str();
6314           break;
6315         }
6316         /// MODULE_CODE_HASH: [5*i32]
6317         case bitc::MODULE_CODE_HASH: {
6318           if (Record.size() != 5)
6319             return error("Invalid hash length " + Twine(Record.size()).str());
6320           auto &Hash = getThisModule()->second.second;
6321           int Pos = 0;
6322           for (auto &Val : Record) {
6323             assert(!(Val >> 32) && "Unexpected high bits set");
6324             Hash[Pos++] = Val;
6325           }
6326           break;
6327         }
6328         /// MODULE_CODE_VSTOFFSET: [offset]
6329         case bitc::MODULE_CODE_VSTOFFSET:
6330           if (Record.empty())
6331             return error("Invalid record");
6332           // Note that we subtract 1 here because the offset is relative to one
6333           // word before the start of the identification or module block, which
6334           // was historically always the start of the regular bitcode header.
6335           VSTOffset = Record[0] - 1;
6336           break;
6337         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
6338         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
6339         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
6340         // v2: [strtab offset, strtab size, v1]
6341         case bitc::MODULE_CODE_GLOBALVAR:
6342         case bitc::MODULE_CODE_FUNCTION:
6343         case bitc::MODULE_CODE_ALIAS: {
6344           StringRef Name;
6345           ArrayRef<uint64_t> GVRecord;
6346           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
6347           if (GVRecord.size() <= 3)
6348             return error("Invalid record");
6349           uint64_t RawLinkage = GVRecord[3];
6350           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
6351           if (!UseStrtab) {
6352             ValueIdToLinkageMap[ValueId++] = Linkage;
6353             break;
6354           }
6355 
6356           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
6357           break;
6358         }
6359         }
6360       }
6361       continue;
6362     }
6363   }
6364 }
6365 
6366 std::vector<ValueInfo>
6367 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
6368   std::vector<ValueInfo> Ret;
6369   Ret.reserve(Record.size());
6370   for (uint64_t RefValueId : Record)
6371     Ret.push_back(getValueInfoFromValueId(RefValueId).first);
6372   return Ret;
6373 }
6374 
6375 std::vector<FunctionSummary::EdgeTy>
6376 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
6377                                               bool IsOldProfileFormat,
6378                                               bool HasProfile, bool HasRelBF) {
6379   std::vector<FunctionSummary::EdgeTy> Ret;
6380   Ret.reserve(Record.size());
6381   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
6382     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
6383     uint64_t RelBF = 0;
6384     ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6385     if (IsOldProfileFormat) {
6386       I += 1; // Skip old callsitecount field
6387       if (HasProfile)
6388         I += 1; // Skip old profilecount field
6389     } else if (HasProfile)
6390       Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
6391     else if (HasRelBF)
6392       RelBF = Record[++I];
6393     Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
6394   }
6395   return Ret;
6396 }
6397 
6398 static void
6399 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
6400                                        WholeProgramDevirtResolution &Wpd) {
6401   uint64_t ArgNum = Record[Slot++];
6402   WholeProgramDevirtResolution::ByArg &B =
6403       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
6404   Slot += ArgNum;
6405 
6406   B.TheKind =
6407       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
6408   B.Info = Record[Slot++];
6409   B.Byte = Record[Slot++];
6410   B.Bit = Record[Slot++];
6411 }
6412 
6413 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
6414                                               StringRef Strtab, size_t &Slot,
6415                                               TypeIdSummary &TypeId) {
6416   uint64_t Id = Record[Slot++];
6417   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
6418 
6419   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
6420   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
6421                         static_cast<size_t>(Record[Slot + 1])};
6422   Slot += 2;
6423 
6424   uint64_t ResByArgNum = Record[Slot++];
6425   for (uint64_t I = 0; I != ResByArgNum; ++I)
6426     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
6427 }
6428 
6429 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
6430                                      StringRef Strtab,
6431                                      ModuleSummaryIndex &TheIndex) {
6432   size_t Slot = 0;
6433   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
6434       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
6435   Slot += 2;
6436 
6437   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
6438   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
6439   TypeId.TTRes.AlignLog2 = Record[Slot++];
6440   TypeId.TTRes.SizeM1 = Record[Slot++];
6441   TypeId.TTRes.BitMask = Record[Slot++];
6442   TypeId.TTRes.InlineBits = Record[Slot++];
6443 
6444   while (Slot < Record.size())
6445     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
6446 }
6447 
6448 std::vector<FunctionSummary::ParamAccess>
6449 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
6450   auto ReadRange = [&]() {
6451     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
6452                 BitcodeReader::decodeSignRotatedValue(Record.front()));
6453     Record = Record.drop_front();
6454     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
6455                 BitcodeReader::decodeSignRotatedValue(Record.front()));
6456     Record = Record.drop_front();
6457     ConstantRange Range{Lower, Upper};
6458     assert(!Range.isFullSet());
6459     assert(!Range.isUpperSignWrapped());
6460     return Range;
6461   };
6462 
6463   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6464   while (!Record.empty()) {
6465     PendingParamAccesses.emplace_back();
6466     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
6467     ParamAccess.ParamNo = Record.front();
6468     Record = Record.drop_front();
6469     ParamAccess.Use = ReadRange();
6470     ParamAccess.Calls.resize(Record.front());
6471     Record = Record.drop_front();
6472     for (auto &Call : ParamAccess.Calls) {
6473       Call.ParamNo = Record.front();
6474       Record = Record.drop_front();
6475       Call.Callee = getValueInfoFromValueId(Record.front()).first;
6476       Record = Record.drop_front();
6477       Call.Offsets = ReadRange();
6478     }
6479   }
6480   return PendingParamAccesses;
6481 }
6482 
6483 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
6484     ArrayRef<uint64_t> Record, size_t &Slot,
6485     TypeIdCompatibleVtableInfo &TypeId) {
6486   uint64_t Offset = Record[Slot++];
6487   ValueInfo Callee = getValueInfoFromValueId(Record[Slot++]).first;
6488   TypeId.push_back({Offset, Callee});
6489 }
6490 
6491 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
6492     ArrayRef<uint64_t> Record) {
6493   size_t Slot = 0;
6494   TypeIdCompatibleVtableInfo &TypeId =
6495       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
6496           {Strtab.data() + Record[Slot],
6497            static_cast<size_t>(Record[Slot + 1])});
6498   Slot += 2;
6499 
6500   while (Slot < Record.size())
6501     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
6502 }
6503 
6504 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
6505                            unsigned WOCnt) {
6506   // Readonly and writeonly refs are in the end of the refs list.
6507   assert(ROCnt + WOCnt <= Refs.size());
6508   unsigned FirstWORef = Refs.size() - WOCnt;
6509   unsigned RefNo = FirstWORef - ROCnt;
6510   for (; RefNo < FirstWORef; ++RefNo)
6511     Refs[RefNo].setReadOnly();
6512   for (; RefNo < Refs.size(); ++RefNo)
6513     Refs[RefNo].setWriteOnly();
6514 }
6515 
6516 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
6517 // objects in the index.
6518 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
6519   if (Error Err = Stream.EnterSubBlock(ID))
6520     return Err;
6521   SmallVector<uint64_t, 64> Record;
6522 
6523   // Parse version
6524   {
6525     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6526     if (!MaybeEntry)
6527       return MaybeEntry.takeError();
6528     BitstreamEntry Entry = MaybeEntry.get();
6529 
6530     if (Entry.Kind != BitstreamEntry::Record)
6531       return error("Invalid Summary Block: record for version expected");
6532     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6533     if (!MaybeRecord)
6534       return MaybeRecord.takeError();
6535     if (MaybeRecord.get() != bitc::FS_VERSION)
6536       return error("Invalid Summary Block: version expected");
6537   }
6538   const uint64_t Version = Record[0];
6539   const bool IsOldProfileFormat = Version == 1;
6540   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
6541     return error("Invalid summary version " + Twine(Version) +
6542                  ". Version should be in the range [1-" +
6543                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
6544                  "].");
6545   Record.clear();
6546 
6547   // Keep around the last seen summary to be used when we see an optional
6548   // "OriginalName" attachement.
6549   GlobalValueSummary *LastSeenSummary = nullptr;
6550   GlobalValue::GUID LastSeenGUID = 0;
6551 
6552   // We can expect to see any number of type ID information records before
6553   // each function summary records; these variables store the information
6554   // collected so far so that it can be used to create the summary object.
6555   std::vector<GlobalValue::GUID> PendingTypeTests;
6556   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
6557       PendingTypeCheckedLoadVCalls;
6558   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
6559       PendingTypeCheckedLoadConstVCalls;
6560   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
6561 
6562   while (true) {
6563     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6564     if (!MaybeEntry)
6565       return MaybeEntry.takeError();
6566     BitstreamEntry Entry = MaybeEntry.get();
6567 
6568     switch (Entry.Kind) {
6569     case BitstreamEntry::SubBlock: // Handled for us already.
6570     case BitstreamEntry::Error:
6571       return error("Malformed block");
6572     case BitstreamEntry::EndBlock:
6573       return Error::success();
6574     case BitstreamEntry::Record:
6575       // The interesting case.
6576       break;
6577     }
6578 
6579     // Read a record. The record format depends on whether this
6580     // is a per-module index or a combined index file. In the per-module
6581     // case the records contain the associated value's ID for correlation
6582     // with VST entries. In the combined index the correlation is done
6583     // via the bitcode offset of the summary records (which were saved
6584     // in the combined index VST entries). The records also contain
6585     // information used for ThinLTO renaming and importing.
6586     Record.clear();
6587     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6588     if (!MaybeBitCode)
6589       return MaybeBitCode.takeError();
6590     switch (unsigned BitCode = MaybeBitCode.get()) {
6591     default: // Default behavior: ignore.
6592       break;
6593     case bitc::FS_FLAGS: {  // [flags]
6594       TheIndex.setFlags(Record[0]);
6595       break;
6596     }
6597     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
6598       uint64_t ValueID = Record[0];
6599       GlobalValue::GUID RefGUID = Record[1];
6600       ValueIdToValueInfoMap[ValueID] =
6601           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
6602       break;
6603     }
6604     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
6605     //                numrefs x valueid, n x (valueid)]
6606     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
6607     //                        numrefs x valueid,
6608     //                        n x (valueid, hotness)]
6609     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
6610     //                      numrefs x valueid,
6611     //                      n x (valueid, relblockfreq)]
6612     case bitc::FS_PERMODULE:
6613     case bitc::FS_PERMODULE_RELBF:
6614     case bitc::FS_PERMODULE_PROFILE: {
6615       unsigned ValueID = Record[0];
6616       uint64_t RawFlags = Record[1];
6617       unsigned InstCount = Record[2];
6618       uint64_t RawFunFlags = 0;
6619       unsigned NumRefs = Record[3];
6620       unsigned NumRORefs = 0, NumWORefs = 0;
6621       int RefListStartIndex = 4;
6622       if (Version >= 4) {
6623         RawFunFlags = Record[3];
6624         NumRefs = Record[4];
6625         RefListStartIndex = 5;
6626         if (Version >= 5) {
6627           NumRORefs = Record[5];
6628           RefListStartIndex = 6;
6629           if (Version >= 7) {
6630             NumWORefs = Record[6];
6631             RefListStartIndex = 7;
6632           }
6633         }
6634       }
6635 
6636       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6637       // The module path string ref set in the summary must be owned by the
6638       // index's module string table. Since we don't have a module path
6639       // string table section in the per-module index, we create a single
6640       // module path string table entry with an empty (0) ID to take
6641       // ownership.
6642       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6643       assert(Record.size() >= RefListStartIndex + NumRefs &&
6644              "Record size inconsistent with number of references");
6645       std::vector<ValueInfo> Refs = makeRefList(
6646           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6647       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
6648       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
6649       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
6650           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6651           IsOldProfileFormat, HasProfile, HasRelBF);
6652       setSpecialRefs(Refs, NumRORefs, NumWORefs);
6653       auto FS = std::make_unique<FunctionSummary>(
6654           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
6655           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
6656           std::move(PendingTypeTestAssumeVCalls),
6657           std::move(PendingTypeCheckedLoadVCalls),
6658           std::move(PendingTypeTestAssumeConstVCalls),
6659           std::move(PendingTypeCheckedLoadConstVCalls),
6660           std::move(PendingParamAccesses));
6661       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
6662       FS->setModulePath(getThisModule()->first());
6663       FS->setOriginalName(VIAndOriginalGUID.second);
6664       TheIndex.addGlobalValueSummary(VIAndOriginalGUID.first, std::move(FS));
6665       break;
6666     }
6667     // FS_ALIAS: [valueid, flags, valueid]
6668     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
6669     // they expect all aliasee summaries to be available.
6670     case bitc::FS_ALIAS: {
6671       unsigned ValueID = Record[0];
6672       uint64_t RawFlags = Record[1];
6673       unsigned AliaseeID = Record[2];
6674       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6675       auto AS = std::make_unique<AliasSummary>(Flags);
6676       // The module path string ref set in the summary must be owned by the
6677       // index's module string table. Since we don't have a module path
6678       // string table section in the per-module index, we create a single
6679       // module path string table entry with an empty (0) ID to take
6680       // ownership.
6681       AS->setModulePath(getThisModule()->first());
6682 
6683       auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first;
6684       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
6685       if (!AliaseeInModule)
6686         return error("Alias expects aliasee summary to be parsed");
6687       AS->setAliasee(AliaseeVI, AliaseeInModule);
6688 
6689       auto GUID = getValueInfoFromValueId(ValueID);
6690       AS->setOriginalName(GUID.second);
6691       TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
6692       break;
6693     }
6694     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
6695     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
6696       unsigned ValueID = Record[0];
6697       uint64_t RawFlags = Record[1];
6698       unsigned RefArrayStart = 2;
6699       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6700                                       /* WriteOnly */ false,
6701                                       /* Constant */ false,
6702                                       GlobalObject::VCallVisibilityPublic);
6703       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6704       if (Version >= 5) {
6705         GVF = getDecodedGVarFlags(Record[2]);
6706         RefArrayStart = 3;
6707       }
6708       std::vector<ValueInfo> Refs =
6709           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6710       auto FS =
6711           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6712       FS->setModulePath(getThisModule()->first());
6713       auto GUID = getValueInfoFromValueId(ValueID);
6714       FS->setOriginalName(GUID.second);
6715       TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
6716       break;
6717     }
6718     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
6719     //                        numrefs, numrefs x valueid,
6720     //                        n x (valueid, offset)]
6721     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
6722       unsigned ValueID = Record[0];
6723       uint64_t RawFlags = Record[1];
6724       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
6725       unsigned NumRefs = Record[3];
6726       unsigned RefListStartIndex = 4;
6727       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
6728       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6729       std::vector<ValueInfo> Refs = makeRefList(
6730           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6731       VTableFuncList VTableFuncs;
6732       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
6733         ValueInfo Callee = getValueInfoFromValueId(Record[I]).first;
6734         uint64_t Offset = Record[++I];
6735         VTableFuncs.push_back({Callee, Offset});
6736       }
6737       auto VS =
6738           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6739       VS->setModulePath(getThisModule()->first());
6740       VS->setVTableFuncs(VTableFuncs);
6741       auto GUID = getValueInfoFromValueId(ValueID);
6742       VS->setOriginalName(GUID.second);
6743       TheIndex.addGlobalValueSummary(GUID.first, std::move(VS));
6744       break;
6745     }
6746     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
6747     //               numrefs x valueid, n x (valueid)]
6748     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
6749     //                       numrefs x valueid, n x (valueid, hotness)]
6750     case bitc::FS_COMBINED:
6751     case bitc::FS_COMBINED_PROFILE: {
6752       unsigned ValueID = Record[0];
6753       uint64_t ModuleId = Record[1];
6754       uint64_t RawFlags = Record[2];
6755       unsigned InstCount = Record[3];
6756       uint64_t RawFunFlags = 0;
6757       uint64_t EntryCount = 0;
6758       unsigned NumRefs = Record[4];
6759       unsigned NumRORefs = 0, NumWORefs = 0;
6760       int RefListStartIndex = 5;
6761 
6762       if (Version >= 4) {
6763         RawFunFlags = Record[4];
6764         RefListStartIndex = 6;
6765         size_t NumRefsIndex = 5;
6766         if (Version >= 5) {
6767           unsigned NumRORefsOffset = 1;
6768           RefListStartIndex = 7;
6769           if (Version >= 6) {
6770             NumRefsIndex = 6;
6771             EntryCount = Record[5];
6772             RefListStartIndex = 8;
6773             if (Version >= 7) {
6774               RefListStartIndex = 9;
6775               NumWORefs = Record[8];
6776               NumRORefsOffset = 2;
6777             }
6778           }
6779           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
6780         }
6781         NumRefs = Record[NumRefsIndex];
6782       }
6783 
6784       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6785       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
6786       assert(Record.size() >= RefListStartIndex + NumRefs &&
6787              "Record size inconsistent with number of references");
6788       std::vector<ValueInfo> Refs = makeRefList(
6789           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
6790       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
6791       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
6792           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
6793           IsOldProfileFormat, HasProfile, false);
6794       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6795       setSpecialRefs(Refs, NumRORefs, NumWORefs);
6796       auto FS = std::make_unique<FunctionSummary>(
6797           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
6798           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
6799           std::move(PendingTypeTestAssumeVCalls),
6800           std::move(PendingTypeCheckedLoadVCalls),
6801           std::move(PendingTypeTestAssumeConstVCalls),
6802           std::move(PendingTypeCheckedLoadConstVCalls),
6803           std::move(PendingParamAccesses));
6804       LastSeenSummary = FS.get();
6805       LastSeenGUID = VI.getGUID();
6806       FS->setModulePath(ModuleIdMap[ModuleId]);
6807       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6808       break;
6809     }
6810     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
6811     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
6812     // they expect all aliasee summaries to be available.
6813     case bitc::FS_COMBINED_ALIAS: {
6814       unsigned ValueID = Record[0];
6815       uint64_t ModuleId = Record[1];
6816       uint64_t RawFlags = Record[2];
6817       unsigned AliaseeValueId = Record[3];
6818       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6819       auto AS = std::make_unique<AliasSummary>(Flags);
6820       LastSeenSummary = AS.get();
6821       AS->setModulePath(ModuleIdMap[ModuleId]);
6822 
6823       auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first;
6824       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
6825       AS->setAliasee(AliaseeVI, AliaseeInModule);
6826 
6827       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6828       LastSeenGUID = VI.getGUID();
6829       TheIndex.addGlobalValueSummary(VI, std::move(AS));
6830       break;
6831     }
6832     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
6833     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
6834       unsigned ValueID = Record[0];
6835       uint64_t ModuleId = Record[1];
6836       uint64_t RawFlags = Record[2];
6837       unsigned RefArrayStart = 3;
6838       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
6839                                       /* WriteOnly */ false,
6840                                       /* Constant */ false,
6841                                       GlobalObject::VCallVisibilityPublic);
6842       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
6843       if (Version >= 5) {
6844         GVF = getDecodedGVarFlags(Record[3]);
6845         RefArrayStart = 4;
6846       }
6847       std::vector<ValueInfo> Refs =
6848           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
6849       auto FS =
6850           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
6851       LastSeenSummary = FS.get();
6852       FS->setModulePath(ModuleIdMap[ModuleId]);
6853       ValueInfo VI = getValueInfoFromValueId(ValueID).first;
6854       LastSeenGUID = VI.getGUID();
6855       TheIndex.addGlobalValueSummary(VI, std::move(FS));
6856       break;
6857     }
6858     // FS_COMBINED_ORIGINAL_NAME: [original_name]
6859     case bitc::FS_COMBINED_ORIGINAL_NAME: {
6860       uint64_t OriginalName = Record[0];
6861       if (!LastSeenSummary)
6862         return error("Name attachment that does not follow a combined record");
6863       LastSeenSummary->setOriginalName(OriginalName);
6864       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
6865       // Reset the LastSeenSummary
6866       LastSeenSummary = nullptr;
6867       LastSeenGUID = 0;
6868       break;
6869     }
6870     case bitc::FS_TYPE_TESTS:
6871       assert(PendingTypeTests.empty());
6872       llvm::append_range(PendingTypeTests, Record);
6873       break;
6874 
6875     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
6876       assert(PendingTypeTestAssumeVCalls.empty());
6877       for (unsigned I = 0; I != Record.size(); I += 2)
6878         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
6879       break;
6880 
6881     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
6882       assert(PendingTypeCheckedLoadVCalls.empty());
6883       for (unsigned I = 0; I != Record.size(); I += 2)
6884         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
6885       break;
6886 
6887     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
6888       PendingTypeTestAssumeConstVCalls.push_back(
6889           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6890       break;
6891 
6892     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
6893       PendingTypeCheckedLoadConstVCalls.push_back(
6894           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
6895       break;
6896 
6897     case bitc::FS_CFI_FUNCTION_DEFS: {
6898       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
6899       for (unsigned I = 0; I != Record.size(); I += 2)
6900         CfiFunctionDefs.insert(
6901             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6902       break;
6903     }
6904 
6905     case bitc::FS_CFI_FUNCTION_DECLS: {
6906       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
6907       for (unsigned I = 0; I != Record.size(); I += 2)
6908         CfiFunctionDecls.insert(
6909             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
6910       break;
6911     }
6912 
6913     case bitc::FS_TYPE_ID:
6914       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
6915       break;
6916 
6917     case bitc::FS_TYPE_ID_METADATA:
6918       parseTypeIdCompatibleVtableSummaryRecord(Record);
6919       break;
6920 
6921     case bitc::FS_BLOCK_COUNT:
6922       TheIndex.addBlockCount(Record[0]);
6923       break;
6924 
6925     case bitc::FS_PARAM_ACCESS: {
6926       PendingParamAccesses = parseParamAccesses(Record);
6927       break;
6928     }
6929     }
6930   }
6931   llvm_unreachable("Exit infinite loop");
6932 }
6933 
6934 // Parse the  module string table block into the Index.
6935 // This populates the ModulePathStringTable map in the index.
6936 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
6937   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
6938     return Err;
6939 
6940   SmallVector<uint64_t, 64> Record;
6941 
6942   SmallString<128> ModulePath;
6943   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
6944 
6945   while (true) {
6946     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6947     if (!MaybeEntry)
6948       return MaybeEntry.takeError();
6949     BitstreamEntry Entry = MaybeEntry.get();
6950 
6951     switch (Entry.Kind) {
6952     case BitstreamEntry::SubBlock: // Handled for us already.
6953     case BitstreamEntry::Error:
6954       return error("Malformed block");
6955     case BitstreamEntry::EndBlock:
6956       return Error::success();
6957     case BitstreamEntry::Record:
6958       // The interesting case.
6959       break;
6960     }
6961 
6962     Record.clear();
6963     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6964     if (!MaybeRecord)
6965       return MaybeRecord.takeError();
6966     switch (MaybeRecord.get()) {
6967     default: // Default behavior: ignore.
6968       break;
6969     case bitc::MST_CODE_ENTRY: {
6970       // MST_ENTRY: [modid, namechar x N]
6971       uint64_t ModuleId = Record[0];
6972 
6973       if (convertToString(Record, 1, ModulePath))
6974         return error("Invalid record");
6975 
6976       LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
6977       ModuleIdMap[ModuleId] = LastSeenModule->first();
6978 
6979       ModulePath.clear();
6980       break;
6981     }
6982     /// MST_CODE_HASH: [5*i32]
6983     case bitc::MST_CODE_HASH: {
6984       if (Record.size() != 5)
6985         return error("Invalid hash length " + Twine(Record.size()).str());
6986       if (!LastSeenModule)
6987         return error("Invalid hash that does not follow a module path");
6988       int Pos = 0;
6989       for (auto &Val : Record) {
6990         assert(!(Val >> 32) && "Unexpected high bits set");
6991         LastSeenModule->second.second[Pos++] = Val;
6992       }
6993       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
6994       LastSeenModule = nullptr;
6995       break;
6996     }
6997     }
6998   }
6999   llvm_unreachable("Exit infinite loop");
7000 }
7001 
7002 namespace {
7003 
7004 // FIXME: This class is only here to support the transition to llvm::Error. It
7005 // will be removed once this transition is complete. Clients should prefer to
7006 // deal with the Error value directly, rather than converting to error_code.
7007 class BitcodeErrorCategoryType : public std::error_category {
7008   const char *name() const noexcept override {
7009     return "llvm.bitcode";
7010   }
7011 
7012   std::string message(int IE) const override {
7013     BitcodeError E = static_cast<BitcodeError>(IE);
7014     switch (E) {
7015     case BitcodeError::CorruptedBitcode:
7016       return "Corrupted bitcode";
7017     }
7018     llvm_unreachable("Unknown error type!");
7019   }
7020 };
7021 
7022 } // end anonymous namespace
7023 
7024 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
7025 
7026 const std::error_category &llvm::BitcodeErrorCategory() {
7027   return *ErrorCategory;
7028 }
7029 
7030 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
7031                                             unsigned Block, unsigned RecordID) {
7032   if (Error Err = Stream.EnterSubBlock(Block))
7033     return std::move(Err);
7034 
7035   StringRef Strtab;
7036   while (true) {
7037     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7038     if (!MaybeEntry)
7039       return MaybeEntry.takeError();
7040     llvm::BitstreamEntry Entry = MaybeEntry.get();
7041 
7042     switch (Entry.Kind) {
7043     case BitstreamEntry::EndBlock:
7044       return Strtab;
7045 
7046     case BitstreamEntry::Error:
7047       return error("Malformed block");
7048 
7049     case BitstreamEntry::SubBlock:
7050       if (Error Err = Stream.SkipBlock())
7051         return std::move(Err);
7052       break;
7053 
7054     case BitstreamEntry::Record:
7055       StringRef Blob;
7056       SmallVector<uint64_t, 1> Record;
7057       Expected<unsigned> MaybeRecord =
7058           Stream.readRecord(Entry.ID, Record, &Blob);
7059       if (!MaybeRecord)
7060         return MaybeRecord.takeError();
7061       if (MaybeRecord.get() == RecordID)
7062         Strtab = Blob;
7063       break;
7064     }
7065   }
7066 }
7067 
7068 //===----------------------------------------------------------------------===//
7069 // External interface
7070 //===----------------------------------------------------------------------===//
7071 
7072 Expected<std::vector<BitcodeModule>>
7073 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
7074   auto FOrErr = getBitcodeFileContents(Buffer);
7075   if (!FOrErr)
7076     return FOrErr.takeError();
7077   return std::move(FOrErr->Mods);
7078 }
7079 
7080 Expected<BitcodeFileContents>
7081 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
7082   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7083   if (!StreamOrErr)
7084     return StreamOrErr.takeError();
7085   BitstreamCursor &Stream = *StreamOrErr;
7086 
7087   BitcodeFileContents F;
7088   while (true) {
7089     uint64_t BCBegin = Stream.getCurrentByteNo();
7090 
7091     // We may be consuming bitcode from a client that leaves garbage at the end
7092     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
7093     // the end that there cannot possibly be another module, stop looking.
7094     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
7095       return F;
7096 
7097     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7098     if (!MaybeEntry)
7099       return MaybeEntry.takeError();
7100     llvm::BitstreamEntry Entry = MaybeEntry.get();
7101 
7102     switch (Entry.Kind) {
7103     case BitstreamEntry::EndBlock:
7104     case BitstreamEntry::Error:
7105       return error("Malformed block");
7106 
7107     case BitstreamEntry::SubBlock: {
7108       uint64_t IdentificationBit = -1ull;
7109       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
7110         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
7111         if (Error Err = Stream.SkipBlock())
7112           return std::move(Err);
7113 
7114         {
7115           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7116           if (!MaybeEntry)
7117             return MaybeEntry.takeError();
7118           Entry = MaybeEntry.get();
7119         }
7120 
7121         if (Entry.Kind != BitstreamEntry::SubBlock ||
7122             Entry.ID != bitc::MODULE_BLOCK_ID)
7123           return error("Malformed block");
7124       }
7125 
7126       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
7127         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
7128         if (Error Err = Stream.SkipBlock())
7129           return std::move(Err);
7130 
7131         F.Mods.push_back({Stream.getBitcodeBytes().slice(
7132                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
7133                           Buffer.getBufferIdentifier(), IdentificationBit,
7134                           ModuleBit});
7135         continue;
7136       }
7137 
7138       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
7139         Expected<StringRef> Strtab =
7140             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
7141         if (!Strtab)
7142           return Strtab.takeError();
7143         // This string table is used by every preceding bitcode module that does
7144         // not have its own string table. A bitcode file may have multiple
7145         // string tables if it was created by binary concatenation, for example
7146         // with "llvm-cat -b".
7147         for (BitcodeModule &I : llvm::reverse(F.Mods)) {
7148           if (!I.Strtab.empty())
7149             break;
7150           I.Strtab = *Strtab;
7151         }
7152         // Similarly, the string table is used by every preceding symbol table;
7153         // normally there will be just one unless the bitcode file was created
7154         // by binary concatenation.
7155         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
7156           F.StrtabForSymtab = *Strtab;
7157         continue;
7158       }
7159 
7160       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
7161         Expected<StringRef> SymtabOrErr =
7162             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
7163         if (!SymtabOrErr)
7164           return SymtabOrErr.takeError();
7165 
7166         // We can expect the bitcode file to have multiple symbol tables if it
7167         // was created by binary concatenation. In that case we silently
7168         // ignore any subsequent symbol tables, which is fine because this is a
7169         // low level function. The client is expected to notice that the number
7170         // of modules in the symbol table does not match the number of modules
7171         // in the input file and regenerate the symbol table.
7172         if (F.Symtab.empty())
7173           F.Symtab = *SymtabOrErr;
7174         continue;
7175       }
7176 
7177       if (Error Err = Stream.SkipBlock())
7178         return std::move(Err);
7179       continue;
7180     }
7181     case BitstreamEntry::Record:
7182       if (Error E = Stream.skipRecord(Entry.ID).takeError())
7183         return std::move(E);
7184       continue;
7185     }
7186   }
7187 }
7188 
7189 /// Get a lazy one-at-time loading module from bitcode.
7190 ///
7191 /// This isn't always used in a lazy context.  In particular, it's also used by
7192 /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
7193 /// in forward-referenced functions from block address references.
7194 ///
7195 /// \param[in] MaterializeAll Set to \c true if we should materialize
7196 /// everything.
7197 Expected<std::unique_ptr<Module>>
7198 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
7199                              bool ShouldLazyLoadMetadata, bool IsImporting,
7200                              DataLayoutCallbackTy DataLayoutCallback) {
7201   BitstreamCursor Stream(Buffer);
7202 
7203   std::string ProducerIdentification;
7204   if (IdentificationBit != -1ull) {
7205     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
7206       return std::move(JumpFailed);
7207     if (Error E =
7208             readIdentificationBlock(Stream).moveInto(ProducerIdentification))
7209       return std::move(E);
7210   }
7211 
7212   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7213     return std::move(JumpFailed);
7214   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
7215                               Context);
7216 
7217   std::unique_ptr<Module> M =
7218       std::make_unique<Module>(ModuleIdentifier, Context);
7219   M->setMaterializer(R);
7220 
7221   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
7222   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
7223                                       IsImporting, DataLayoutCallback))
7224     return std::move(Err);
7225 
7226   if (MaterializeAll) {
7227     // Read in the entire module, and destroy the BitcodeReader.
7228     if (Error Err = M->materializeAll())
7229       return std::move(Err);
7230   } else {
7231     // Resolve forward references from blockaddresses.
7232     if (Error Err = R->materializeForwardReferencedFunctions())
7233       return std::move(Err);
7234   }
7235   return std::move(M);
7236 }
7237 
7238 Expected<std::unique_ptr<Module>>
7239 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
7240                              bool IsImporting) {
7241   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
7242                        [](StringRef) { return None; });
7243 }
7244 
7245 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
7246 // We don't use ModuleIdentifier here because the client may need to control the
7247 // module path used in the combined summary (e.g. when reading summaries for
7248 // regular LTO modules).
7249 Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
7250                                  StringRef ModulePath, uint64_t ModuleId) {
7251   BitstreamCursor Stream(Buffer);
7252   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7253     return JumpFailed;
7254 
7255   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
7256                                     ModulePath, ModuleId);
7257   return R.parseModule();
7258 }
7259 
7260 // Parse the specified bitcode buffer, returning the function info index.
7261 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
7262   BitstreamCursor Stream(Buffer);
7263   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7264     return std::move(JumpFailed);
7265 
7266   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
7267   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
7268                                     ModuleIdentifier, 0);
7269 
7270   if (Error Err = R.parseModule())
7271     return std::move(Err);
7272 
7273   return std::move(Index);
7274 }
7275 
7276 static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
7277                                                 unsigned ID) {
7278   if (Error Err = Stream.EnterSubBlock(ID))
7279     return std::move(Err);
7280   SmallVector<uint64_t, 64> Record;
7281 
7282   while (true) {
7283     BitstreamEntry Entry;
7284     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
7285       return std::move(E);
7286 
7287     switch (Entry.Kind) {
7288     case BitstreamEntry::SubBlock: // Handled for us already.
7289     case BitstreamEntry::Error:
7290       return error("Malformed block");
7291     case BitstreamEntry::EndBlock:
7292       // If no flags record found, conservatively return true to mimic
7293       // behavior before this flag was added.
7294       return true;
7295     case BitstreamEntry::Record:
7296       // The interesting case.
7297       break;
7298     }
7299 
7300     // Look for the FS_FLAGS record.
7301     Record.clear();
7302     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7303     if (!MaybeBitCode)
7304       return MaybeBitCode.takeError();
7305     switch (MaybeBitCode.get()) {
7306     default: // Default behavior: ignore.
7307       break;
7308     case bitc::FS_FLAGS: { // [flags]
7309       uint64_t Flags = Record[0];
7310       // Scan flags.
7311       assert(Flags <= 0x7f && "Unexpected bits in flag");
7312 
7313       return Flags & 0x8;
7314     }
7315     }
7316   }
7317   llvm_unreachable("Exit infinite loop");
7318 }
7319 
7320 // Check if the given bitcode buffer contains a global value summary block.
7321 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
7322   BitstreamCursor Stream(Buffer);
7323   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
7324     return std::move(JumpFailed);
7325 
7326   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
7327     return std::move(Err);
7328 
7329   while (true) {
7330     llvm::BitstreamEntry Entry;
7331     if (Error E = Stream.advance().moveInto(Entry))
7332       return std::move(E);
7333 
7334     switch (Entry.Kind) {
7335     case BitstreamEntry::Error:
7336       return error("Malformed block");
7337     case BitstreamEntry::EndBlock:
7338       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
7339                             /*EnableSplitLTOUnit=*/false};
7340 
7341     case BitstreamEntry::SubBlock:
7342       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
7343         Expected<bool> EnableSplitLTOUnit =
7344             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
7345         if (!EnableSplitLTOUnit)
7346           return EnableSplitLTOUnit.takeError();
7347         return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
7348                               *EnableSplitLTOUnit};
7349       }
7350 
7351       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
7352         Expected<bool> EnableSplitLTOUnit =
7353             getEnableSplitLTOUnitFlag(Stream, Entry.ID);
7354         if (!EnableSplitLTOUnit)
7355           return EnableSplitLTOUnit.takeError();
7356         return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
7357                               *EnableSplitLTOUnit};
7358       }
7359 
7360       // Ignore other sub-blocks.
7361       if (Error Err = Stream.SkipBlock())
7362         return std::move(Err);
7363       continue;
7364 
7365     case BitstreamEntry::Record:
7366       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
7367         continue;
7368       else
7369         return StreamFailed.takeError();
7370     }
7371   }
7372 }
7373 
7374 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
7375   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
7376   if (!MsOrErr)
7377     return MsOrErr.takeError();
7378 
7379   if (MsOrErr->size() != 1)
7380     return error("Expected a single module");
7381 
7382   return (*MsOrErr)[0];
7383 }
7384 
7385 Expected<std::unique_ptr<Module>>
7386 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
7387                            bool ShouldLazyLoadMetadata, bool IsImporting) {
7388   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7389   if (!BM)
7390     return BM.takeError();
7391 
7392   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
7393 }
7394 
7395 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
7396     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
7397     bool ShouldLazyLoadMetadata, bool IsImporting) {
7398   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
7399                                      IsImporting);
7400   if (MOrErr)
7401     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
7402   return MOrErr;
7403 }
7404 
7405 Expected<std::unique_ptr<Module>>
7406 BitcodeModule::parseModule(LLVMContext &Context,
7407                            DataLayoutCallbackTy DataLayoutCallback) {
7408   return getModuleImpl(Context, true, false, false, DataLayoutCallback);
7409   // TODO: Restore the use-lists to the in-memory state when the bitcode was
7410   // written.  We must defer until the Module has been fully materialized.
7411 }
7412 
7413 Expected<std::unique_ptr<Module>>
7414 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
7415                        DataLayoutCallbackTy DataLayoutCallback) {
7416   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7417   if (!BM)
7418     return BM.takeError();
7419 
7420   return BM->parseModule(Context, DataLayoutCallback);
7421 }
7422 
7423 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
7424   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7425   if (!StreamOrErr)
7426     return StreamOrErr.takeError();
7427 
7428   return readTriple(*StreamOrErr);
7429 }
7430 
7431 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
7432   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7433   if (!StreamOrErr)
7434     return StreamOrErr.takeError();
7435 
7436   return hasObjCCategory(*StreamOrErr);
7437 }
7438 
7439 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
7440   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7441   if (!StreamOrErr)
7442     return StreamOrErr.takeError();
7443 
7444   return readIdentificationCode(*StreamOrErr);
7445 }
7446 
7447 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
7448                                    ModuleSummaryIndex &CombinedIndex,
7449                                    uint64_t ModuleId) {
7450   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7451   if (!BM)
7452     return BM.takeError();
7453 
7454   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
7455 }
7456 
7457 Expected<std::unique_ptr<ModuleSummaryIndex>>
7458 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
7459   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7460   if (!BM)
7461     return BM.takeError();
7462 
7463   return BM->getSummary();
7464 }
7465 
7466 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
7467   Expected<BitcodeModule> BM = getSingleModule(Buffer);
7468   if (!BM)
7469     return BM.takeError();
7470 
7471   return BM->getLTOInfo();
7472 }
7473 
7474 Expected<std::unique_ptr<ModuleSummaryIndex>>
7475 llvm::getModuleSummaryIndexForFile(StringRef Path,
7476                                    bool IgnoreEmptyThinLTOIndexFile) {
7477   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
7478       MemoryBuffer::getFileOrSTDIN(Path);
7479   if (!FileOrErr)
7480     return errorCodeToError(FileOrErr.getError());
7481   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
7482     return nullptr;
7483   return getModuleSummaryIndex(**FileOrErr);
7484 }
7485