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