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