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