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