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