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