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