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