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