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