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