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