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