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