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