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