OSDN Git Service

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