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