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