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