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