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