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