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