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