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