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