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