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