2e670d584ecc0c4cbf6c6c83b76afc3260523f86
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.cpp
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 using namespace llvm;
39
40 namespace {
41 enum {
42   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
43 };
44
45 class BitcodeReaderValueList {
46   std::vector<WeakVH> ValuePtrs;
47
48   /// As we resolve forward-referenced constants, we add information about them
49   /// to this vector.  This allows us to resolve them in bulk instead of
50   /// resolving each reference at a time.  See the code in
51   /// ResolveConstantForwardRefs for more information about this.
52   ///
53   /// The key of this vector is the placeholder constant, the value is the slot
54   /// number that holds the resolved value.
55   typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
56   ResolveConstantsTy ResolveConstants;
57   LLVMContext &Context;
58 public:
59   BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
60   ~BitcodeReaderValueList() {
61     assert(ResolveConstants.empty() && "Constants not resolved?");
62   }
63
64   // vector compatibility methods
65   unsigned size() const { return ValuePtrs.size(); }
66   void resize(unsigned N) { ValuePtrs.resize(N); }
67   void push_back(Value *V) { ValuePtrs.emplace_back(V); }
68
69   void clear() {
70     assert(ResolveConstants.empty() && "Constants not resolved?");
71     ValuePtrs.clear();
72   }
73
74   Value *operator[](unsigned i) const {
75     assert(i < ValuePtrs.size());
76     return ValuePtrs[i];
77   }
78
79   Value *back() const { return ValuePtrs.back(); }
80     void pop_back() { ValuePtrs.pop_back(); }
81   bool empty() const { return ValuePtrs.empty(); }
82   void shrinkTo(unsigned N) {
83     assert(N <= size() && "Invalid shrinkTo request!");
84     ValuePtrs.resize(N);
85   }
86
87   Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
88   Value *getValueFwdRef(unsigned Idx, Type *Ty);
89
90   void assignValue(Value *V, unsigned Idx);
91
92   /// Once all constants are read, this method bulk resolves any forward
93   /// references.
94   void resolveConstantForwardRefs();
95 };
96
97 class BitcodeReaderMetadataList {
98   unsigned NumFwdRefs;
99   bool AnyFwdRefs;
100   unsigned MinFwdRef;
101   unsigned MaxFwdRef;
102   std::vector<TrackingMDRef> MetadataPtrs;
103
104   LLVMContext &Context;
105 public:
106   BitcodeReaderMetadataList(LLVMContext &C)
107       : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
108
109   // vector compatibility methods
110   unsigned size() const { return MetadataPtrs.size(); }
111   void resize(unsigned N) { MetadataPtrs.resize(N); }
112   void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
113   void clear() { MetadataPtrs.clear(); }
114   Metadata *back() const { return MetadataPtrs.back(); }
115   void pop_back() { MetadataPtrs.pop_back(); }
116   bool empty() const { return MetadataPtrs.empty(); }
117
118   Metadata *operator[](unsigned i) const {
119     assert(i < MetadataPtrs.size());
120     return MetadataPtrs[i];
121   }
122
123   void shrinkTo(unsigned N) {
124     assert(N <= size() && "Invalid shrinkTo request!");
125     MetadataPtrs.resize(N);
126   }
127
128   Metadata *getValueFwdRef(unsigned Idx);
129   void assignValue(Metadata *MD, unsigned Idx);
130   void tryToResolveCycles();
131 };
132
133 class BitcodeReader : public GVMaterializer {
134   LLVMContext &Context;
135   Module *TheModule = nullptr;
136   std::unique_ptr<MemoryBuffer> Buffer;
137   std::unique_ptr<BitstreamReader> StreamFile;
138   BitstreamCursor Stream;
139   // Next offset to start scanning for lazy parsing of function bodies.
140   uint64_t NextUnreadBit = 0;
141   // Last function offset found in the VST.
142   uint64_t LastFunctionBlockBit = 0;
143   bool SeenValueSymbolTable = false;
144   uint64_t VSTOffset = 0;
145   // Contains an arbitrary and optional string identifying the bitcode producer
146   std::string ProducerIdentification;
147   // Number of module level metadata records specified by the
148   // MODULE_CODE_METADATA_VALUES record.
149   unsigned NumModuleMDs = 0;
150   // Support older bitcode without the MODULE_CODE_METADATA_VALUES record.
151   bool SeenModuleValuesRecord = false;
152
153   std::vector<Type*> TypeList;
154   BitcodeReaderValueList ValueList;
155   BitcodeReaderMetadataList MetadataList;
156   std::vector<Comdat *> ComdatList;
157   SmallVector<Instruction *, 64> InstructionList;
158
159   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
160   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
161   std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
162   std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
163   std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
164
165   SmallVector<Instruction*, 64> InstsWithTBAATag;
166
167   /// The set of attributes by index.  Index zero in the file is for null, and
168   /// is thus not represented here.  As such all indices are off by one.
169   std::vector<AttributeSet> MAttributes;
170
171   /// The set of attribute groups.
172   std::map<unsigned, AttributeSet> MAttributeGroups;
173
174   /// While parsing a function body, this is a list of the basic blocks for the
175   /// function.
176   std::vector<BasicBlock*> FunctionBBs;
177
178   // When reading the module header, this list is populated with functions that
179   // have bodies later in the file.
180   std::vector<Function*> FunctionsWithBodies;
181
182   // When intrinsic functions are encountered which require upgrading they are
183   // stored here with their replacement function.
184   typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
185   UpgradedIntrinsicMap UpgradedIntrinsics;
186
187   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
188   DenseMap<unsigned, unsigned> MDKindMap;
189
190   // Several operations happen after the module header has been read, but
191   // before function bodies are processed. This keeps track of whether
192   // we've done this yet.
193   bool SeenFirstFunctionBody = false;
194
195   /// When function bodies are initially scanned, this map contains info about
196   /// where to find deferred function body in the stream.
197   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
198
199   /// When Metadata block is initially scanned when parsing the module, we may
200   /// choose to defer parsing of the metadata. This vector contains info about
201   /// which Metadata blocks are deferred.
202   std::vector<uint64_t> DeferredMetadataInfo;
203
204   /// These are basic blocks forward-referenced by block addresses.  They are
205   /// inserted lazily into functions when they're loaded.  The basic block ID is
206   /// its index into the vector.
207   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
208   std::deque<Function *> BasicBlockFwdRefQueue;
209
210   /// Indicates that we are using a new encoding for instruction operands where
211   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
212   /// instruction number, for a more compact encoding.  Some instruction
213   /// operands are not relative to the instruction ID: basic block numbers, and
214   /// types. Once the old style function blocks have been phased out, we would
215   /// not need this flag.
216   bool UseRelativeIDs = false;
217
218   /// True if all functions will be materialized, negating the need to process
219   /// (e.g.) blockaddress forward references.
220   bool WillMaterializeAllForwardRefs = false;
221
222   /// True if any Metadata block has been materialized.
223   bool IsMetadataMaterialized = false;
224
225   bool StripDebugInfo = false;
226
227   /// Functions that need to be matched with subprograms when upgrading old
228   /// metadata.
229   SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
230
231   std::vector<std::string> BundleTags;
232
233 public:
234   std::error_code error(BitcodeError E, const Twine &Message);
235   std::error_code error(BitcodeError E);
236   std::error_code error(const Twine &Message);
237
238   BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
239   BitcodeReader(LLVMContext &Context);
240   ~BitcodeReader() override { freeState(); }
241
242   std::error_code materializeForwardReferencedFunctions();
243
244   void freeState();
245
246   void releaseBuffer();
247
248   std::error_code materialize(GlobalValue *GV) override;
249   std::error_code materializeModule() override;
250   std::vector<StructType *> getIdentifiedStructTypes() const override;
251
252   /// \brief Main interface to parsing a bitcode buffer.
253   /// \returns true if an error occurred.
254   std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
255                                    Module *M,
256                                    bool ShouldLazyLoadMetadata = false);
257
258   /// \brief Cheap mechanism to just extract module triple
259   /// \returns true if an error occurred.
260   ErrorOr<std::string> parseTriple();
261
262   /// Cheap mechanism to just extract the identification block out of bitcode.
263   ErrorOr<std::string> parseIdentificationBlock();
264
265   static uint64_t decodeSignRotatedValue(uint64_t V);
266
267   /// Materialize any deferred Metadata block.
268   std::error_code materializeMetadata() override;
269
270   void setStripDebugInfo() override;
271
272   /// Save the mapping between the metadata values and the corresponding
273   /// value id that were recorded in the MetadataList during parsing. If
274   /// OnlyTempMD is true, then only record those entries that are still
275   /// temporary metadata. This interface is used when metadata linking is
276   /// performed as a postpass, such as during function importing.
277   void saveMetadataList(DenseMap<const Metadata *, unsigned> &MetadataToIDs,
278                         bool OnlyTempMD) override;
279
280 private:
281   /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
282   // ProducerIdentification data member, and do some basic enforcement on the
283   // "epoch" encoded in the bitcode.
284   std::error_code parseBitcodeVersion();
285
286   std::vector<StructType *> IdentifiedStructTypes;
287   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
288   StructType *createIdentifiedStructType(LLVMContext &Context);
289
290   Type *getTypeByID(unsigned ID);
291   Value *getFnValueByID(unsigned ID, Type *Ty) {
292     if (Ty && Ty->isMetadataTy())
293       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
294     return ValueList.getValueFwdRef(ID, Ty);
295   }
296   Metadata *getFnMetadataByID(unsigned ID) {
297     return MetadataList.getValueFwdRef(ID);
298   }
299   BasicBlock *getBasicBlock(unsigned ID) const {
300     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
301     return FunctionBBs[ID];
302   }
303   AttributeSet getAttributes(unsigned i) const {
304     if (i-1 < MAttributes.size())
305       return MAttributes[i-1];
306     return AttributeSet();
307   }
308
309   /// Read a value/type pair out of the specified record from slot 'Slot'.
310   /// Increment Slot past the number of slots used in the record. Return true on
311   /// failure.
312   bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
313                         unsigned InstNum, Value *&ResVal) {
314     if (Slot == Record.size()) return true;
315     unsigned ValNo = (unsigned)Record[Slot++];
316     // Adjust the ValNo, if it was encoded relative to the InstNum.
317     if (UseRelativeIDs)
318       ValNo = InstNum - ValNo;
319     if (ValNo < InstNum) {
320       // If this is not a forward reference, just return the value we already
321       // have.
322       ResVal = getFnValueByID(ValNo, nullptr);
323       return ResVal == nullptr;
324     }
325     if (Slot == Record.size())
326       return true;
327
328     unsigned TypeNo = (unsigned)Record[Slot++];
329     ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
330     return ResVal == nullptr;
331   }
332
333   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
334   /// past the number of slots used by the value in the record. Return true if
335   /// there is an error.
336   bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
337                 unsigned InstNum, Type *Ty, Value *&ResVal) {
338     if (getValue(Record, Slot, InstNum, Ty, ResVal))
339       return true;
340     // All values currently take a single record slot.
341     ++Slot;
342     return false;
343   }
344
345   /// Like popValue, but does not increment the Slot number.
346   bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
347                 unsigned InstNum, Type *Ty, Value *&ResVal) {
348     ResVal = getValue(Record, Slot, InstNum, Ty);
349     return ResVal == nullptr;
350   }
351
352   /// Version of getValue that returns ResVal directly, or 0 if there is an
353   /// error.
354   Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
355                   unsigned InstNum, Type *Ty) {
356     if (Slot == Record.size()) return nullptr;
357     unsigned ValNo = (unsigned)Record[Slot];
358     // Adjust the ValNo, if it was encoded relative to the InstNum.
359     if (UseRelativeIDs)
360       ValNo = InstNum - ValNo;
361     return getFnValueByID(ValNo, Ty);
362   }
363
364   /// Like getValue, but decodes signed VBRs.
365   Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
366                         unsigned InstNum, Type *Ty) {
367     if (Slot == Record.size()) return nullptr;
368     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
369     // Adjust the ValNo, if it was encoded relative to the InstNum.
370     if (UseRelativeIDs)
371       ValNo = InstNum - ValNo;
372     return getFnValueByID(ValNo, Ty);
373   }
374
375   /// Converts alignment exponent (i.e. power of two (or zero)) to the
376   /// corresponding alignment to use. If alignment is too large, returns
377   /// a corresponding error code.
378   std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
379   std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
380   std::error_code parseModule(uint64_t ResumeBit,
381                               bool ShouldLazyLoadMetadata = false);
382   std::error_code parseAttributeBlock();
383   std::error_code parseAttributeGroupBlock();
384   std::error_code parseTypeTable();
385   std::error_code parseTypeTableBody();
386   std::error_code parseOperandBundleTags();
387
388   ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
389                                unsigned NameIndex, Triple &TT);
390   std::error_code parseValueSymbolTable(uint64_t Offset = 0);
391   std::error_code parseConstants();
392   std::error_code rememberAndSkipFunctionBodies();
393   std::error_code rememberAndSkipFunctionBody();
394   /// Save the positions of the Metadata blocks and skip parsing the blocks.
395   std::error_code rememberAndSkipMetadata();
396   std::error_code parseFunctionBody(Function *F);
397   std::error_code globalCleanup();
398   std::error_code resolveGlobalAndAliasInits();
399   std::error_code parseMetadata(bool ModuleLevel = false);
400   std::error_code parseMetadataKinds();
401   std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
402   std::error_code parseMetadataAttachment(Function &F);
403   ErrorOr<std::string> parseModuleTriple();
404   std::error_code parseUseLists();
405   std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
406   std::error_code initStreamFromBuffer();
407   std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
408   std::error_code findFunctionInStream(
409       Function *F,
410       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
411 };
412
413 /// Class to manage reading and parsing function summary index bitcode
414 /// files/sections.
415 class FunctionIndexBitcodeReader {
416   DiagnosticHandlerFunction DiagnosticHandler;
417
418   /// Eventually points to the function index built during parsing.
419   FunctionInfoIndex *TheIndex = nullptr;
420
421   std::unique_ptr<MemoryBuffer> Buffer;
422   std::unique_ptr<BitstreamReader> StreamFile;
423   BitstreamCursor Stream;
424
425   /// \brief Used to indicate whether we are doing lazy parsing of summary data.
426   ///
427   /// If false, the summary section is fully parsed into the index during
428   /// the initial parse. Otherwise, if true, the caller is expected to
429   /// invoke \a readFunctionSummary for each summary needed, and the summary
430   /// section is thus parsed lazily.
431   bool IsLazy = false;
432
433   /// Used to indicate whether caller only wants to check for the presence
434   /// of the function summary bitcode section. All blocks are skipped,
435   /// but the SeenFuncSummary boolean is set.
436   bool CheckFuncSummaryPresenceOnly = false;
437
438   /// Indicates whether we have encountered a function summary section
439   /// yet during parsing, used when checking if file contains function
440   /// summary section.
441   bool SeenFuncSummary = false;
442
443   /// \brief Map populated during function summary section parsing, and
444   /// consumed during ValueSymbolTable parsing.
445   ///
446   /// Used to correlate summary records with VST entries. For the per-module
447   /// index this maps the ValueID to the parsed function summary, and
448   /// for the combined index this maps the summary record's bitcode
449   /// offset to the function summary (since in the combined index the
450   /// VST records do not hold value IDs but rather hold the function
451   /// summary record offset).
452   DenseMap<uint64_t, std::unique_ptr<FunctionSummary>> SummaryMap;
453
454   /// Map populated during module path string table parsing, from the
455   /// module ID to a string reference owned by the index's module
456   /// path string table, used to correlate with combined index function
457   /// summary records.
458   DenseMap<uint64_t, StringRef> ModuleIdMap;
459
460 public:
461   std::error_code error(BitcodeError E, const Twine &Message);
462   std::error_code error(BitcodeError E);
463   std::error_code error(const Twine &Message);
464
465   FunctionIndexBitcodeReader(MemoryBuffer *Buffer,
466                              DiagnosticHandlerFunction DiagnosticHandler,
467                              bool IsLazy = false,
468                              bool CheckFuncSummaryPresenceOnly = false);
469   FunctionIndexBitcodeReader(DiagnosticHandlerFunction DiagnosticHandler,
470                              bool IsLazy = false,
471                              bool CheckFuncSummaryPresenceOnly = false);
472   ~FunctionIndexBitcodeReader() { freeState(); }
473
474   void freeState();
475
476   void releaseBuffer();
477
478   /// Check if the parser has encountered a function summary section.
479   bool foundFuncSummary() { return SeenFuncSummary; }
480
481   /// \brief Main interface to parsing a bitcode buffer.
482   /// \returns true if an error occurred.
483   std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
484                                         FunctionInfoIndex *I);
485
486   /// \brief Interface for parsing a function summary lazily.
487   std::error_code parseFunctionSummary(std::unique_ptr<DataStreamer> Streamer,
488                                        FunctionInfoIndex *I,
489                                        size_t FunctionSummaryOffset);
490
491 private:
492   std::error_code parseModule();
493   std::error_code parseValueSymbolTable();
494   std::error_code parseEntireSummary();
495   std::error_code parseModuleStringTable();
496   std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
497   std::error_code initStreamFromBuffer();
498   std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
499 };
500 } // namespace
501
502 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
503                                              DiagnosticSeverity Severity,
504                                              const Twine &Msg)
505     : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
506
507 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
508
509 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
510                              std::error_code EC, const Twine &Message) {
511   BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
512   DiagnosticHandler(DI);
513   return EC;
514 }
515
516 static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
517                              std::error_code EC) {
518   return error(DiagnosticHandler, EC, EC.message());
519 }
520
521 static std::error_code error(LLVMContext &Context, std::error_code EC,
522                              const Twine &Message) {
523   return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
524                Message);
525 }
526
527 static std::error_code error(LLVMContext &Context, std::error_code EC) {
528   return error(Context, EC, EC.message());
529 }
530
531 static std::error_code error(LLVMContext &Context, const Twine &Message) {
532   return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
533                Message);
534 }
535
536 std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
537   if (!ProducerIdentification.empty()) {
538     return ::error(Context, make_error_code(E),
539                    Message + " (Producer: '" + ProducerIdentification +
540                        "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
541   }
542   return ::error(Context, make_error_code(E), Message);
543 }
544
545 std::error_code BitcodeReader::error(const Twine &Message) {
546   if (!ProducerIdentification.empty()) {
547     return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
548                    Message + " (Producer: '" + ProducerIdentification +
549                        "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
550   }
551   return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
552                  Message);
553 }
554
555 std::error_code BitcodeReader::error(BitcodeError E) {
556   return ::error(Context, make_error_code(E));
557 }
558
559 BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
560     : Context(Context), Buffer(Buffer), ValueList(Context),
561       MetadataList(Context) {}
562
563 BitcodeReader::BitcodeReader(LLVMContext &Context)
564     : Context(Context), Buffer(nullptr), ValueList(Context),
565       MetadataList(Context) {}
566
567 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
568   if (WillMaterializeAllForwardRefs)
569     return std::error_code();
570
571   // Prevent recursion.
572   WillMaterializeAllForwardRefs = true;
573
574   while (!BasicBlockFwdRefQueue.empty()) {
575     Function *F = BasicBlockFwdRefQueue.front();
576     BasicBlockFwdRefQueue.pop_front();
577     assert(F && "Expected valid function");
578     if (!BasicBlockFwdRefs.count(F))
579       // Already materialized.
580       continue;
581
582     // Check for a function that isn't materializable to prevent an infinite
583     // loop.  When parsing a blockaddress stored in a global variable, there
584     // isn't a trivial way to check if a function will have a body without a
585     // linear search through FunctionsWithBodies, so just check it here.
586     if (!F->isMaterializable())
587       return error("Never resolved function from blockaddress");
588
589     // Try to materialize F.
590     if (std::error_code EC = materialize(F))
591       return EC;
592   }
593   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
594
595   // Reset state.
596   WillMaterializeAllForwardRefs = false;
597   return std::error_code();
598 }
599
600 void BitcodeReader::freeState() {
601   Buffer = nullptr;
602   std::vector<Type*>().swap(TypeList);
603   ValueList.clear();
604   MetadataList.clear();
605   std::vector<Comdat *>().swap(ComdatList);
606
607   std::vector<AttributeSet>().swap(MAttributes);
608   std::vector<BasicBlock*>().swap(FunctionBBs);
609   std::vector<Function*>().swap(FunctionsWithBodies);
610   DeferredFunctionInfo.clear();
611   DeferredMetadataInfo.clear();
612   MDKindMap.clear();
613
614   assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
615   BasicBlockFwdRefQueue.clear();
616 }
617
618 //===----------------------------------------------------------------------===//
619 //  Helper functions to implement forward reference resolution, etc.
620 //===----------------------------------------------------------------------===//
621
622 /// Convert a string from a record into an std::string, return true on failure.
623 template <typename StrTy>
624 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
625                             StrTy &Result) {
626   if (Idx > Record.size())
627     return true;
628
629   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
630     Result += (char)Record[i];
631   return false;
632 }
633
634 static bool hasImplicitComdat(size_t Val) {
635   switch (Val) {
636   default:
637     return false;
638   case 1:  // Old WeakAnyLinkage
639   case 4:  // Old LinkOnceAnyLinkage
640   case 10: // Old WeakODRLinkage
641   case 11: // Old LinkOnceODRLinkage
642     return true;
643   }
644 }
645
646 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
647   switch (Val) {
648   default: // Map unknown/new linkages to external
649   case 0:
650     return GlobalValue::ExternalLinkage;
651   case 2:
652     return GlobalValue::AppendingLinkage;
653   case 3:
654     return GlobalValue::InternalLinkage;
655   case 5:
656     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
657   case 6:
658     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
659   case 7:
660     return GlobalValue::ExternalWeakLinkage;
661   case 8:
662     return GlobalValue::CommonLinkage;
663   case 9:
664     return GlobalValue::PrivateLinkage;
665   case 12:
666     return GlobalValue::AvailableExternallyLinkage;
667   case 13:
668     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
669   case 14:
670     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
671   case 15:
672     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
673   case 1: // Old value with implicit comdat.
674   case 16:
675     return GlobalValue::WeakAnyLinkage;
676   case 10: // Old value with implicit comdat.
677   case 17:
678     return GlobalValue::WeakODRLinkage;
679   case 4: // Old value with implicit comdat.
680   case 18:
681     return GlobalValue::LinkOnceAnyLinkage;
682   case 11: // Old value with implicit comdat.
683   case 19:
684     return GlobalValue::LinkOnceODRLinkage;
685   }
686 }
687
688 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
689   switch (Val) {
690   default: // Map unknown visibilities to default.
691   case 0: return GlobalValue::DefaultVisibility;
692   case 1: return GlobalValue::HiddenVisibility;
693   case 2: return GlobalValue::ProtectedVisibility;
694   }
695 }
696
697 static GlobalValue::DLLStorageClassTypes
698 getDecodedDLLStorageClass(unsigned Val) {
699   switch (Val) {
700   default: // Map unknown values to default.
701   case 0: return GlobalValue::DefaultStorageClass;
702   case 1: return GlobalValue::DLLImportStorageClass;
703   case 2: return GlobalValue::DLLExportStorageClass;
704   }
705 }
706
707 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
708   switch (Val) {
709     case 0: return GlobalVariable::NotThreadLocal;
710     default: // Map unknown non-zero value to general dynamic.
711     case 1: return GlobalVariable::GeneralDynamicTLSModel;
712     case 2: return GlobalVariable::LocalDynamicTLSModel;
713     case 3: return GlobalVariable::InitialExecTLSModel;
714     case 4: return GlobalVariable::LocalExecTLSModel;
715   }
716 }
717
718 static int getDecodedCastOpcode(unsigned Val) {
719   switch (Val) {
720   default: return -1;
721   case bitc::CAST_TRUNC   : return Instruction::Trunc;
722   case bitc::CAST_ZEXT    : return Instruction::ZExt;
723   case bitc::CAST_SEXT    : return Instruction::SExt;
724   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
725   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
726   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
727   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
728   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
729   case bitc::CAST_FPEXT   : return Instruction::FPExt;
730   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
731   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
732   case bitc::CAST_BITCAST : return Instruction::BitCast;
733   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
734   }
735 }
736
737 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
738   bool IsFP = Ty->isFPOrFPVectorTy();
739   // BinOps are only valid for int/fp or vector of int/fp types
740   if (!IsFP && !Ty->isIntOrIntVectorTy())
741     return -1;
742
743   switch (Val) {
744   default:
745     return -1;
746   case bitc::BINOP_ADD:
747     return IsFP ? Instruction::FAdd : Instruction::Add;
748   case bitc::BINOP_SUB:
749     return IsFP ? Instruction::FSub : Instruction::Sub;
750   case bitc::BINOP_MUL:
751     return IsFP ? Instruction::FMul : Instruction::Mul;
752   case bitc::BINOP_UDIV:
753     return IsFP ? -1 : Instruction::UDiv;
754   case bitc::BINOP_SDIV:
755     return IsFP ? Instruction::FDiv : Instruction::SDiv;
756   case bitc::BINOP_UREM:
757     return IsFP ? -1 : Instruction::URem;
758   case bitc::BINOP_SREM:
759     return IsFP ? Instruction::FRem : Instruction::SRem;
760   case bitc::BINOP_SHL:
761     return IsFP ? -1 : Instruction::Shl;
762   case bitc::BINOP_LSHR:
763     return IsFP ? -1 : Instruction::LShr;
764   case bitc::BINOP_ASHR:
765     return IsFP ? -1 : Instruction::AShr;
766   case bitc::BINOP_AND:
767     return IsFP ? -1 : Instruction::And;
768   case bitc::BINOP_OR:
769     return IsFP ? -1 : Instruction::Or;
770   case bitc::BINOP_XOR:
771     return IsFP ? -1 : Instruction::Xor;
772   }
773 }
774
775 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
776   switch (Val) {
777   default: return AtomicRMWInst::BAD_BINOP;
778   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
779   case bitc::RMW_ADD: return AtomicRMWInst::Add;
780   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
781   case bitc::RMW_AND: return AtomicRMWInst::And;
782   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
783   case bitc::RMW_OR: return AtomicRMWInst::Or;
784   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
785   case bitc::RMW_MAX: return AtomicRMWInst::Max;
786   case bitc::RMW_MIN: return AtomicRMWInst::Min;
787   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
788   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
789   }
790 }
791
792 static AtomicOrdering getDecodedOrdering(unsigned Val) {
793   switch (Val) {
794   case bitc::ORDERING_NOTATOMIC: return NotAtomic;
795   case bitc::ORDERING_UNORDERED: return Unordered;
796   case bitc::ORDERING_MONOTONIC: return Monotonic;
797   case bitc::ORDERING_ACQUIRE: return Acquire;
798   case bitc::ORDERING_RELEASE: return Release;
799   case bitc::ORDERING_ACQREL: return AcquireRelease;
800   default: // Map unknown orderings to sequentially-consistent.
801   case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
802   }
803 }
804
805 static SynchronizationScope getDecodedSynchScope(unsigned Val) {
806   switch (Val) {
807   case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
808   default: // Map unknown scopes to cross-thread.
809   case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
810   }
811 }
812
813 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
814   switch (Val) {
815   default: // Map unknown selection kinds to any.
816   case bitc::COMDAT_SELECTION_KIND_ANY:
817     return Comdat::Any;
818   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
819     return Comdat::ExactMatch;
820   case bitc::COMDAT_SELECTION_KIND_LARGEST:
821     return Comdat::Largest;
822   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
823     return Comdat::NoDuplicates;
824   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
825     return Comdat::SameSize;
826   }
827 }
828
829 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
830   FastMathFlags FMF;
831   if (0 != (Val & FastMathFlags::UnsafeAlgebra))
832     FMF.setUnsafeAlgebra();
833   if (0 != (Val & FastMathFlags::NoNaNs))
834     FMF.setNoNaNs();
835   if (0 != (Val & FastMathFlags::NoInfs))
836     FMF.setNoInfs();
837   if (0 != (Val & FastMathFlags::NoSignedZeros))
838     FMF.setNoSignedZeros();
839   if (0 != (Val & FastMathFlags::AllowReciprocal))
840     FMF.setAllowReciprocal();
841   return FMF;
842 }
843
844 static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
845   switch (Val) {
846   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
847   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
848   }
849 }
850
851 namespace llvm {
852 namespace {
853 /// \brief A class for maintaining the slot number definition
854 /// as a placeholder for the actual definition for forward constants defs.
855 class ConstantPlaceHolder : public ConstantExpr {
856   void operator=(const ConstantPlaceHolder &) = delete;
857
858 public:
859   // allocate space for exactly one operand
860   void *operator new(size_t s) { return User::operator new(s, 1); }
861   explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
862       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
863     Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
864   }
865
866   /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
867   static bool classof(const Value *V) {
868     return isa<ConstantExpr>(V) &&
869            cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
870   }
871
872   /// Provide fast operand accessors
873   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
874 };
875 }
876
877 // FIXME: can we inherit this from ConstantExpr?
878 template <>
879 struct OperandTraits<ConstantPlaceHolder> :
880   public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
881 };
882 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
883 }
884
885 void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
886   if (Idx == size()) {
887     push_back(V);
888     return;
889   }
890
891   if (Idx >= size())
892     resize(Idx+1);
893
894   WeakVH &OldV = ValuePtrs[Idx];
895   if (!OldV) {
896     OldV = V;
897     return;
898   }
899
900   // Handle constants and non-constants (e.g. instrs) differently for
901   // efficiency.
902   if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
903     ResolveConstants.push_back(std::make_pair(PHC, Idx));
904     OldV = V;
905   } else {
906     // If there was a forward reference to this value, replace it.
907     Value *PrevVal = OldV;
908     OldV->replaceAllUsesWith(V);
909     delete PrevVal;
910   }
911
912   return;
913 }
914
915
916 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
917                                                     Type *Ty) {
918   if (Idx >= size())
919     resize(Idx + 1);
920
921   if (Value *V = ValuePtrs[Idx]) {
922     if (Ty != V->getType())
923       report_fatal_error("Type mismatch in constant table!");
924     return cast<Constant>(V);
925   }
926
927   // Create and return a placeholder, which will later be RAUW'd.
928   Constant *C = new ConstantPlaceHolder(Ty, Context);
929   ValuePtrs[Idx] = C;
930   return C;
931 }
932
933 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
934   // Bail out for a clearly invalid value. This would make us call resize(0)
935   if (Idx == UINT_MAX)
936     return nullptr;
937
938   if (Idx >= size())
939     resize(Idx + 1);
940
941   if (Value *V = ValuePtrs[Idx]) {
942     // If the types don't match, it's invalid.
943     if (Ty && Ty != V->getType())
944       return nullptr;
945     return V;
946   }
947
948   // No type specified, must be invalid reference.
949   if (!Ty) return nullptr;
950
951   // Create and return a placeholder, which will later be RAUW'd.
952   Value *V = new Argument(Ty);
953   ValuePtrs[Idx] = V;
954   return V;
955 }
956
957 /// Once all constants are read, this method bulk resolves any forward
958 /// references.  The idea behind this is that we sometimes get constants (such
959 /// as large arrays) which reference *many* forward ref constants.  Replacing
960 /// each of these causes a lot of thrashing when building/reuniquing the
961 /// constant.  Instead of doing this, we look at all the uses and rewrite all
962 /// the place holders at once for any constant that uses a placeholder.
963 void BitcodeReaderValueList::resolveConstantForwardRefs() {
964   // Sort the values by-pointer so that they are efficient to look up with a
965   // binary search.
966   std::sort(ResolveConstants.begin(), ResolveConstants.end());
967
968   SmallVector<Constant*, 64> NewOps;
969
970   while (!ResolveConstants.empty()) {
971     Value *RealVal = operator[](ResolveConstants.back().second);
972     Constant *Placeholder = ResolveConstants.back().first;
973     ResolveConstants.pop_back();
974
975     // Loop over all users of the placeholder, updating them to reference the
976     // new value.  If they reference more than one placeholder, update them all
977     // at once.
978     while (!Placeholder->use_empty()) {
979       auto UI = Placeholder->user_begin();
980       User *U = *UI;
981
982       // If the using object isn't uniqued, just update the operands.  This
983       // handles instructions and initializers for global variables.
984       if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
985         UI.getUse().set(RealVal);
986         continue;
987       }
988
989       // Otherwise, we have a constant that uses the placeholder.  Replace that
990       // constant with a new constant that has *all* placeholder uses updated.
991       Constant *UserC = cast<Constant>(U);
992       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
993            I != E; ++I) {
994         Value *NewOp;
995         if (!isa<ConstantPlaceHolder>(*I)) {
996           // Not a placeholder reference.
997           NewOp = *I;
998         } else if (*I == Placeholder) {
999           // Common case is that it just references this one placeholder.
1000           NewOp = RealVal;
1001         } else {
1002           // Otherwise, look up the placeholder in ResolveConstants.
1003           ResolveConstantsTy::iterator It =
1004             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
1005                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
1006                                                             0));
1007           assert(It != ResolveConstants.end() && It->first == *I);
1008           NewOp = operator[](It->second);
1009         }
1010
1011         NewOps.push_back(cast<Constant>(NewOp));
1012       }
1013
1014       // Make the new constant.
1015       Constant *NewC;
1016       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
1017         NewC = ConstantArray::get(UserCA->getType(), NewOps);
1018       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
1019         NewC = ConstantStruct::get(UserCS->getType(), NewOps);
1020       } else if (isa<ConstantVector>(UserC)) {
1021         NewC = ConstantVector::get(NewOps);
1022       } else {
1023         assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
1024         NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
1025       }
1026
1027       UserC->replaceAllUsesWith(NewC);
1028       UserC->destroyConstant();
1029       NewOps.clear();
1030     }
1031
1032     // Update all ValueHandles, they should be the only users at this point.
1033     Placeholder->replaceAllUsesWith(RealVal);
1034     delete Placeholder;
1035   }
1036 }
1037
1038 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
1039   if (Idx == size()) {
1040     push_back(MD);
1041     return;
1042   }
1043
1044   if (Idx >= size())
1045     resize(Idx+1);
1046
1047   TrackingMDRef &OldMD = MetadataPtrs[Idx];
1048   if (!OldMD) {
1049     OldMD.reset(MD);
1050     return;
1051   }
1052
1053   // If there was a forward reference to this value, replace it.
1054   TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
1055   PrevMD->replaceAllUsesWith(MD);
1056   --NumFwdRefs;
1057 }
1058
1059 Metadata *BitcodeReaderMetadataList::getValueFwdRef(unsigned Idx) {
1060   if (Idx >= size())
1061     resize(Idx + 1);
1062
1063   if (Metadata *MD = MetadataPtrs[Idx])
1064     return MD;
1065
1066   // Track forward refs to be resolved later.
1067   if (AnyFwdRefs) {
1068     MinFwdRef = std::min(MinFwdRef, Idx);
1069     MaxFwdRef = std::max(MaxFwdRef, Idx);
1070   } else {
1071     AnyFwdRefs = true;
1072     MinFwdRef = MaxFwdRef = Idx;
1073   }
1074   ++NumFwdRefs;
1075
1076   // Create and return a placeholder, which will later be RAUW'd.
1077   Metadata *MD = MDNode::getTemporary(Context, None).release();
1078   MetadataPtrs[Idx].reset(MD);
1079   return MD;
1080 }
1081
1082 void BitcodeReaderMetadataList::tryToResolveCycles() {
1083   if (!AnyFwdRefs)
1084     // Nothing to do.
1085     return;
1086
1087   if (NumFwdRefs)
1088     // Still forward references... can't resolve cycles.
1089     return;
1090
1091   // Resolve any cycles.
1092   for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1093     auto &MD = MetadataPtrs[I];
1094     auto *N = dyn_cast_or_null<MDNode>(MD);
1095     if (!N)
1096       continue;
1097
1098     assert(!N->isTemporary() && "Unexpected forward reference");
1099     N->resolveCycles();
1100   }
1101
1102   // Make sure we return early again until there's another forward ref.
1103   AnyFwdRefs = false;
1104 }
1105
1106 Type *BitcodeReader::getTypeByID(unsigned ID) {
1107   // The type table size is always specified correctly.
1108   if (ID >= TypeList.size())
1109     return nullptr;
1110
1111   if (Type *Ty = TypeList[ID])
1112     return Ty;
1113
1114   // If we have a forward reference, the only possible case is when it is to a
1115   // named struct.  Just create a placeholder for now.
1116   return TypeList[ID] = createIdentifiedStructType(Context);
1117 }
1118
1119 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1120                                                       StringRef Name) {
1121   auto *Ret = StructType::create(Context, Name);
1122   IdentifiedStructTypes.push_back(Ret);
1123   return Ret;
1124 }
1125
1126 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1127   auto *Ret = StructType::create(Context);
1128   IdentifiedStructTypes.push_back(Ret);
1129   return Ret;
1130 }
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_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_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 ? 0 : 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 ronstant 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       unsigned Size = Record.size();
2658
2659       if (EltTy->isIntegerTy(8)) {
2660         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2661         if (isa<VectorType>(CurTy))
2662           V = ConstantDataVector::get(Context, Elts);
2663         else
2664           V = ConstantDataArray::get(Context, Elts);
2665       } else if (EltTy->isIntegerTy(16)) {
2666         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2667         if (isa<VectorType>(CurTy))
2668           V = ConstantDataVector::get(Context, Elts);
2669         else
2670           V = ConstantDataArray::get(Context, Elts);
2671       } else if (EltTy->isIntegerTy(32)) {
2672         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2673         if (isa<VectorType>(CurTy))
2674           V = ConstantDataVector::get(Context, Elts);
2675         else
2676           V = ConstantDataArray::get(Context, Elts);
2677       } else if (EltTy->isIntegerTy(64)) {
2678         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2679         if (isa<VectorType>(CurTy))
2680           V = ConstantDataVector::get(Context, Elts);
2681         else
2682           V = ConstantDataArray::get(Context, Elts);
2683       } else if (EltTy->isFloatTy()) {
2684         SmallVector<float, 16> Elts(Size);
2685         std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
2686         if (isa<VectorType>(CurTy))
2687           V = ConstantDataVector::get(Context, Elts);
2688         else
2689           V = ConstantDataArray::get(Context, Elts);
2690       } else if (EltTy->isDoubleTy()) {
2691         SmallVector<double, 16> Elts(Size);
2692         std::transform(Record.begin(), Record.end(), Elts.begin(),
2693                        BitsToDouble);
2694         if (isa<VectorType>(CurTy))
2695           V = ConstantDataVector::get(Context, Elts);
2696         else
2697           V = ConstantDataArray::get(Context, Elts);
2698       } else {
2699         return error("Invalid type for value");
2700       }
2701       break;
2702     }
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     // Save all values if !OnlyTempMD, otherwise just the temporary metadata.
3075     if (!OnlyTempMD || (N && N->isTemporary())) {
3076       // Will call this after materializing each function, in order to
3077       // handle remapping of the function's instructions/metadata.
3078       // See if we already have an entry in that case.
3079       if (OnlyTempMD && MetadataToIDs.count(MD)) {
3080         assert(MetadataToIDs[MD] == ID && "Inconsistent metadata value id");
3081         continue;
3082       }
3083       MetadataToIDs[MD] = ID;
3084     }
3085   }
3086 }
3087
3088 /// When we see the block for a function body, remember where it is and then
3089 /// skip it.  This lets us lazily deserialize the functions.
3090 std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
3091   // Get the function we are talking about.
3092   if (FunctionsWithBodies.empty())
3093     return error("Insufficient function protos");
3094
3095   Function *Fn = FunctionsWithBodies.back();
3096   FunctionsWithBodies.pop_back();
3097
3098   // Save the current stream state.
3099   uint64_t CurBit = Stream.GetCurrentBitNo();
3100   assert(
3101       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3102       "Mismatch between VST and scanned function offsets");
3103   DeferredFunctionInfo[Fn] = CurBit;
3104
3105   // Skip over the function block for now.
3106   if (Stream.SkipBlock())
3107     return error("Invalid record");
3108   return std::error_code();
3109 }
3110
3111 std::error_code BitcodeReader::globalCleanup() {
3112   // Patch the initializers for globals and aliases up.
3113   resolveGlobalAndAliasInits();
3114   if (!GlobalInits.empty() || !AliasInits.empty())
3115     return error("Malformed global initializer set");
3116
3117   // Look for intrinsic functions which need to be upgraded at some point
3118   for (Function &F : *TheModule) {
3119     Function *NewFn;
3120     if (UpgradeIntrinsicFunction(&F, NewFn))
3121       UpgradedIntrinsics[&F] = NewFn;
3122   }
3123
3124   // Look for global variables which need to be renamed.
3125   for (GlobalVariable &GV : TheModule->globals())
3126     UpgradeGlobalVariable(&GV);
3127
3128   // Force deallocation of memory for these vectors to favor the client that
3129   // want lazy deserialization.
3130   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3131   std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
3132   return std::error_code();
3133 }
3134
3135 /// Support for lazy parsing of function bodies. This is required if we
3136 /// either have an old bitcode file without a VST forward declaration record,
3137 /// or if we have an anonymous function being materialized, since anonymous
3138 /// functions do not have a name and are therefore not in the VST.
3139 std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3140   Stream.JumpToBit(NextUnreadBit);
3141
3142   if (Stream.AtEndOfStream())
3143     return error("Could not find function in stream");
3144
3145   if (!SeenFirstFunctionBody)
3146     return error("Trying to materialize functions before seeing function blocks");
3147
3148   // An old bitcode file with the symbol table at the end would have
3149   // finished the parse greedily.
3150   assert(SeenValueSymbolTable);
3151
3152   SmallVector<uint64_t, 64> Record;
3153
3154   while (1) {
3155     BitstreamEntry Entry = Stream.advance();
3156     switch (Entry.Kind) {
3157     default:
3158       return error("Expect SubBlock");
3159     case BitstreamEntry::SubBlock:
3160       switch (Entry.ID) {
3161       default:
3162         return error("Expect function block");
3163       case bitc::FUNCTION_BLOCK_ID:
3164         if (std::error_code EC = rememberAndSkipFunctionBody())
3165           return EC;
3166         NextUnreadBit = Stream.GetCurrentBitNo();
3167         return std::error_code();
3168       }
3169     }
3170   }
3171 }
3172
3173 std::error_code BitcodeReader::parseBitcodeVersion() {
3174   if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3175     return error("Invalid record");
3176
3177   // Read all the records.
3178   SmallVector<uint64_t, 64> Record;
3179   while (1) {
3180     BitstreamEntry Entry = Stream.advance();
3181
3182     switch (Entry.Kind) {
3183     default:
3184     case BitstreamEntry::Error:
3185       return error("Malformed block");
3186     case BitstreamEntry::EndBlock:
3187       return std::error_code();
3188     case BitstreamEntry::Record:
3189       // The interesting case.
3190       break;
3191     }
3192
3193     // Read a record.
3194     Record.clear();
3195     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3196     switch (BitCode) {
3197     default: // Default behavior: reject
3198       return error("Invalid value");
3199     case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION:      [strchr x
3200                                              // N]
3201       convertToString(Record, 0, ProducerIdentification);
3202       break;
3203     }
3204     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH:      [epoch#]
3205       unsigned epoch = (unsigned)Record[0];
3206       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
3207         return error(
3208           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3209           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
3210       }
3211     }
3212     }
3213   }
3214 }
3215
3216 std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
3217                                            bool ShouldLazyLoadMetadata) {
3218   if (ResumeBit)
3219     Stream.JumpToBit(ResumeBit);
3220   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3221     return error("Invalid record");
3222
3223   SmallVector<uint64_t, 64> Record;
3224   std::vector<std::string> SectionTable;
3225   std::vector<std::string> GCTable;
3226
3227   // Read all the records for this module.
3228   while (1) {
3229     BitstreamEntry Entry = Stream.advance();
3230
3231     switch (Entry.Kind) {
3232     case BitstreamEntry::Error:
3233       return error("Malformed block");
3234     case BitstreamEntry::EndBlock:
3235       return globalCleanup();
3236
3237     case BitstreamEntry::SubBlock:
3238       switch (Entry.ID) {
3239       default:  // Skip unknown content.
3240         if (Stream.SkipBlock())
3241           return error("Invalid record");
3242         break;
3243       case bitc::BLOCKINFO_BLOCK_ID:
3244         if (Stream.ReadBlockInfoBlock())
3245           return error("Malformed block");
3246         break;
3247       case bitc::PARAMATTR_BLOCK_ID:
3248         if (std::error_code EC = parseAttributeBlock())
3249           return EC;
3250         break;
3251       case bitc::PARAMATTR_GROUP_BLOCK_ID:
3252         if (std::error_code EC = parseAttributeGroupBlock())
3253           return EC;
3254         break;
3255       case bitc::TYPE_BLOCK_ID_NEW:
3256         if (std::error_code EC = parseTypeTable())
3257           return EC;
3258         break;
3259       case bitc::VALUE_SYMTAB_BLOCK_ID:
3260         if (!SeenValueSymbolTable) {
3261           // Either this is an old form VST without function index and an
3262           // associated VST forward declaration record (which would have caused
3263           // the VST to be jumped to and parsed before it was encountered
3264           // normally in the stream), or there were no function blocks to
3265           // trigger an earlier parsing of the VST.
3266           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3267           if (std::error_code EC = parseValueSymbolTable())
3268             return EC;
3269           SeenValueSymbolTable = true;
3270         } else {
3271           // We must have had a VST forward declaration record, which caused
3272           // the parser to jump to and parse the VST earlier.
3273           assert(VSTOffset > 0);
3274           if (Stream.SkipBlock())
3275             return error("Invalid record");
3276         }
3277         break;
3278       case bitc::CONSTANTS_BLOCK_ID:
3279         if (std::error_code EC = parseConstants())
3280           return EC;
3281         if (std::error_code EC = resolveGlobalAndAliasInits())
3282           return EC;
3283         break;
3284       case bitc::METADATA_BLOCK_ID:
3285         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3286           if (std::error_code EC = rememberAndSkipMetadata())
3287             return EC;
3288           break;
3289         }
3290         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
3291         if (std::error_code EC = parseMetadata(true))
3292           return EC;
3293         break;
3294       case bitc::METADATA_KIND_BLOCK_ID:
3295         if (std::error_code EC = parseMetadataKinds())
3296           return EC;
3297         break;
3298       case bitc::FUNCTION_BLOCK_ID:
3299         // If this is the first function body we've seen, reverse the
3300         // FunctionsWithBodies list.
3301         if (!SeenFirstFunctionBody) {
3302           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
3303           if (std::error_code EC = globalCleanup())
3304             return EC;
3305           SeenFirstFunctionBody = true;
3306         }
3307
3308         if (VSTOffset > 0) {
3309           // If we have a VST forward declaration record, make sure we
3310           // parse the VST now if we haven't already. It is needed to
3311           // set up the DeferredFunctionInfo vector for lazy reading.
3312           if (!SeenValueSymbolTable) {
3313             if (std::error_code EC =
3314                     BitcodeReader::parseValueSymbolTable(VSTOffset))
3315               return EC;
3316             SeenValueSymbolTable = true;
3317             // Fall through so that we record the NextUnreadBit below.
3318             // This is necessary in case we have an anonymous function that
3319             // is later materialized. Since it will not have a VST entry we
3320             // need to fall back to the lazy parse to find its offset.
3321           } else {
3322             // If we have a VST forward declaration record, but have already
3323             // parsed the VST (just above, when the first function body was
3324             // encountered here), then we are resuming the parse after
3325             // materializing functions. The ResumeBit points to the
3326             // start of the last function block recorded in the
3327             // DeferredFunctionInfo map. Skip it.
3328             if (Stream.SkipBlock())
3329               return error("Invalid record");
3330             continue;
3331           }
3332         }
3333
3334         // Support older bitcode files that did not have the function
3335         // index in the VST, nor a VST forward declaration record, as
3336         // well as anonymous functions that do not have VST entries.
3337         // Build the DeferredFunctionInfo vector on the fly.
3338         if (std::error_code EC = rememberAndSkipFunctionBody())
3339           return EC;
3340
3341         // Suspend parsing when we reach the function bodies. Subsequent
3342         // materialization calls will resume it when necessary. If the bitcode
3343         // file is old, the symbol table will be at the end instead and will not
3344         // have been seen yet. In this case, just finish the parse now.
3345         if (SeenValueSymbolTable) {
3346           NextUnreadBit = Stream.GetCurrentBitNo();
3347           return std::error_code();
3348         }
3349         break;
3350       case bitc::USELIST_BLOCK_ID:
3351         if (std::error_code EC = parseUseLists())
3352           return EC;
3353         break;
3354       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3355         if (std::error_code EC = parseOperandBundleTags())
3356           return EC;
3357         break;
3358       }
3359       continue;
3360
3361     case BitstreamEntry::Record:
3362       // The interesting case.
3363       break;
3364     }
3365
3366
3367     // Read a record.
3368     auto BitCode = Stream.readRecord(Entry.ID, Record);
3369     switch (BitCode) {
3370     default: break;  // Default behavior, ignore unknown content.
3371     case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
3372       if (Record.size() < 1)
3373         return error("Invalid record");
3374       // Only version #0 and #1 are supported so far.
3375       unsigned module_version = Record[0];
3376       switch (module_version) {
3377         default:
3378           return error("Invalid value");
3379         case 0:
3380           UseRelativeIDs = false;
3381           break;
3382         case 1:
3383           UseRelativeIDs = true;
3384           break;
3385       }
3386       break;
3387     }
3388     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3389       std::string S;
3390       if (convertToString(Record, 0, S))
3391         return error("Invalid record");
3392       TheModule->setTargetTriple(S);
3393       break;
3394     }
3395     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
3396       std::string S;
3397       if (convertToString(Record, 0, S))
3398         return error("Invalid record");
3399       TheModule->setDataLayout(S);
3400       break;
3401     }
3402     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
3403       std::string S;
3404       if (convertToString(Record, 0, S))
3405         return error("Invalid record");
3406       TheModule->setModuleInlineAsm(S);
3407       break;
3408     }
3409     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
3410       // FIXME: Remove in 4.0.
3411       std::string S;
3412       if (convertToString(Record, 0, S))
3413         return error("Invalid record");
3414       // Ignore value.
3415       break;
3416     }
3417     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
3418       std::string S;
3419       if (convertToString(Record, 0, S))
3420         return error("Invalid record");
3421       SectionTable.push_back(S);
3422       break;
3423     }
3424     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
3425       std::string S;
3426       if (convertToString(Record, 0, S))
3427         return error("Invalid record");
3428       GCTable.push_back(S);
3429       break;
3430     }
3431     case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3432       if (Record.size() < 2)
3433         return error("Invalid record");
3434       Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3435       unsigned ComdatNameSize = Record[1];
3436       std::string ComdatName;
3437       ComdatName.reserve(ComdatNameSize);
3438       for (unsigned i = 0; i != ComdatNameSize; ++i)
3439         ComdatName += (char)Record[2 + i];
3440       Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3441       C->setSelectionKind(SK);
3442       ComdatList.push_back(C);
3443       break;
3444     }
3445     // GLOBALVAR: [pointer type, isconst, initid,
3446     //             linkage, alignment, section, visibility, threadlocal,
3447     //             unnamed_addr, externally_initialized, dllstorageclass,
3448     //             comdat]
3449     case bitc::MODULE_CODE_GLOBALVAR: {
3450       if (Record.size() < 6)
3451         return error("Invalid record");
3452       Type *Ty = getTypeByID(Record[0]);
3453       if (!Ty)
3454         return error("Invalid record");
3455       bool isConstant = Record[1] & 1;
3456       bool explicitType = Record[1] & 2;
3457       unsigned AddressSpace;
3458       if (explicitType) {
3459         AddressSpace = Record[1] >> 2;
3460       } else {
3461         if (!Ty->isPointerTy())
3462           return error("Invalid type for value");
3463         AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3464         Ty = cast<PointerType>(Ty)->getElementType();
3465       }
3466
3467       uint64_t RawLinkage = Record[3];
3468       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3469       unsigned Alignment;
3470       if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3471         return EC;
3472       std::string Section;
3473       if (Record[5]) {
3474         if (Record[5]-1 >= SectionTable.size())
3475           return error("Invalid ID");
3476         Section = SectionTable[Record[5]-1];
3477       }
3478       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3479       // Local linkage must have default visibility.
3480       if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3481         // FIXME: Change to an error if non-default in 4.0.
3482         Visibility = getDecodedVisibility(Record[6]);
3483
3484       GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3485       if (Record.size() > 7)
3486         TLM = getDecodedThreadLocalMode(Record[7]);
3487
3488       bool UnnamedAddr = false;
3489       if (Record.size() > 8)
3490         UnnamedAddr = Record[8];
3491
3492       bool ExternallyInitialized = false;
3493       if (Record.size() > 9)
3494         ExternallyInitialized = Record[9];
3495
3496       GlobalVariable *NewGV =
3497         new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
3498                            TLM, AddressSpace, ExternallyInitialized);
3499       NewGV->setAlignment(Alignment);
3500       if (!Section.empty())
3501         NewGV->setSection(Section);
3502       NewGV->setVisibility(Visibility);
3503       NewGV->setUnnamedAddr(UnnamedAddr);
3504
3505       if (Record.size() > 10)
3506         NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3507       else
3508         upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3509
3510       ValueList.push_back(NewGV);
3511
3512       // Remember which value to use for the global initializer.
3513       if (unsigned InitID = Record[2])
3514         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
3515
3516       if (Record.size() > 11) {
3517         if (unsigned ComdatID = Record[11]) {
3518           if (ComdatID > ComdatList.size())
3519             return error("Invalid global variable comdat ID");
3520           NewGV->setComdat(ComdatList[ComdatID - 1]);
3521         }
3522       } else if (hasImplicitComdat(RawLinkage)) {
3523         NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3524       }
3525       break;
3526     }
3527     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
3528     //             alignment, section, visibility, gc, unnamed_addr,
3529     //             prologuedata, dllstorageclass, comdat, prefixdata]
3530     case bitc::MODULE_CODE_FUNCTION: {
3531       if (Record.size() < 8)
3532         return error("Invalid record");
3533       Type *Ty = getTypeByID(Record[0]);
3534       if (!Ty)
3535         return error("Invalid record");
3536       if (auto *PTy = dyn_cast<PointerType>(Ty))
3537         Ty = PTy->getElementType();
3538       auto *FTy = dyn_cast<FunctionType>(Ty);
3539       if (!FTy)
3540         return error("Invalid type for value");
3541       auto CC = static_cast<CallingConv::ID>(Record[1]);
3542       if (CC & ~CallingConv::MaxID)
3543         return error("Invalid calling convention ID");
3544
3545       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3546                                         "", TheModule);
3547
3548       Func->setCallingConv(CC);
3549       bool isProto = Record[2];
3550       uint64_t RawLinkage = Record[3];
3551       Func->setLinkage(getDecodedLinkage(RawLinkage));
3552       Func->setAttributes(getAttributes(Record[4]));
3553
3554       unsigned Alignment;
3555       if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3556         return EC;
3557       Func->setAlignment(Alignment);
3558       if (Record[6]) {
3559         if (Record[6]-1 >= SectionTable.size())
3560           return error("Invalid ID");
3561         Func->setSection(SectionTable[Record[6]-1]);
3562       }
3563       // Local linkage must have default visibility.
3564       if (!Func->hasLocalLinkage())
3565         // FIXME: Change to an error if non-default in 4.0.
3566         Func->setVisibility(getDecodedVisibility(Record[7]));
3567       if (Record.size() > 8 && Record[8]) {
3568         if (Record[8]-1 >= GCTable.size())
3569           return error("Invalid ID");
3570         Func->setGC(GCTable[Record[8]-1].c_str());
3571       }
3572       bool UnnamedAddr = false;
3573       if (Record.size() > 9)
3574         UnnamedAddr = Record[9];
3575       Func->setUnnamedAddr(UnnamedAddr);
3576       if (Record.size() > 10 && Record[10] != 0)
3577         FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
3578
3579       if (Record.size() > 11)
3580         Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3581       else
3582         upgradeDLLImportExportLinkage(Func, RawLinkage);
3583
3584       if (Record.size() > 12) {
3585         if (unsigned ComdatID = Record[12]) {
3586           if (ComdatID > ComdatList.size())
3587             return error("Invalid function comdat ID");
3588           Func->setComdat(ComdatList[ComdatID - 1]);
3589         }
3590       } else if (hasImplicitComdat(RawLinkage)) {
3591         Func->setComdat(reinterpret_cast<Comdat *>(1));
3592       }
3593
3594       if (Record.size() > 13 && Record[13] != 0)
3595         FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3596
3597       if (Record.size() > 14 && Record[14] != 0)
3598         FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3599
3600       ValueList.push_back(Func);
3601
3602       // If this is a function with a body, remember the prototype we are
3603       // creating now, so that we can match up the body with them later.
3604       if (!isProto) {
3605         Func->setIsMaterializable(true);
3606         FunctionsWithBodies.push_back(Func);
3607         DeferredFunctionInfo[Func] = 0;
3608       }
3609       break;
3610     }
3611     // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3612     // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3613     case bitc::MODULE_CODE_ALIAS:
3614     case bitc::MODULE_CODE_ALIAS_OLD: {
3615       bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
3616       if (Record.size() < (3 + (unsigned)NewRecord))
3617         return error("Invalid record");
3618       unsigned OpNum = 0;
3619       Type *Ty = getTypeByID(Record[OpNum++]);
3620       if (!Ty)
3621         return error("Invalid record");
3622
3623       unsigned AddrSpace;
3624       if (!NewRecord) {
3625         auto *PTy = dyn_cast<PointerType>(Ty);
3626         if (!PTy)
3627           return error("Invalid type for value");
3628         Ty = PTy->getElementType();
3629         AddrSpace = PTy->getAddressSpace();
3630       } else {
3631         AddrSpace = Record[OpNum++];
3632       }
3633
3634       auto Val = Record[OpNum++];
3635       auto Linkage = Record[OpNum++];
3636       auto *NewGA = GlobalAlias::create(
3637           Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
3638       // Old bitcode files didn't have visibility field.
3639       // Local linkage must have default visibility.
3640       if (OpNum != Record.size()) {
3641         auto VisInd = OpNum++;
3642         if (!NewGA->hasLocalLinkage())
3643           // FIXME: Change to an error if non-default in 4.0.
3644           NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3645       }
3646       if (OpNum != Record.size())
3647         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3648       else
3649         upgradeDLLImportExportLinkage(NewGA, Linkage);
3650       if (OpNum != Record.size())
3651         NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3652       if (OpNum != Record.size())
3653         NewGA->setUnnamedAddr(Record[OpNum++]);
3654       ValueList.push_back(NewGA);
3655       AliasInits.push_back(std::make_pair(NewGA, Val));
3656       break;
3657     }
3658     /// MODULE_CODE_PURGEVALS: [numvals]
3659     case bitc::MODULE_CODE_PURGEVALS:
3660       // Trim down the value list to the specified size.
3661       if (Record.size() < 1 || Record[0] > ValueList.size())
3662         return error("Invalid record");
3663       ValueList.shrinkTo(Record[0]);
3664       break;
3665     /// MODULE_CODE_VSTOFFSET: [offset]
3666     case bitc::MODULE_CODE_VSTOFFSET:
3667       if (Record.size() < 1)
3668         return error("Invalid record");
3669       VSTOffset = Record[0];
3670       break;
3671     /// MODULE_CODE_METADATA_VALUES: [numvals]
3672     case bitc::MODULE_CODE_METADATA_VALUES:
3673       if (Record.size() < 1)
3674         return error("Invalid record");
3675       assert(!IsMetadataMaterialized);
3676       // This record contains the number of metadata values in the module-level
3677       // METADATA_BLOCK. It is used to support lazy parsing of metadata as
3678       // a postpass, where we will parse function-level metadata first.
3679       // This is needed because the ids of metadata are assigned implicitly
3680       // based on their ordering in the bitcode, with the function-level
3681       // metadata ids starting after the module-level metadata ids. Otherwise,
3682       // we would have to parse the module-level metadata block to prime the
3683       // MetadataList when we are lazy loading metadata during function
3684       // importing. Initialize the MetadataList size here based on the
3685       // record value, regardless of whether we are doing lazy metadata
3686       // loading, so that we have consistent handling and assertion
3687       // checking in parseMetadata for module-level metadata.
3688       NumModuleMDs = Record[0];
3689       SeenModuleValuesRecord = true;
3690       assert(MetadataList.size() == 0);
3691       MetadataList.resize(NumModuleMDs);
3692       break;
3693     }
3694     Record.clear();
3695   }
3696 }
3697
3698 /// Helper to read the header common to all bitcode files.
3699 static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3700   // Sniff for the signature.
3701   if (Stream.Read(8) != 'B' ||
3702       Stream.Read(8) != 'C' ||
3703       Stream.Read(4) != 0x0 ||
3704       Stream.Read(4) != 0xC ||
3705       Stream.Read(4) != 0xE ||
3706       Stream.Read(4) != 0xD)
3707     return false;
3708   return true;
3709 }
3710
3711 std::error_code
3712 BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3713                                 Module *M, bool ShouldLazyLoadMetadata) {
3714   TheModule = M;
3715
3716   if (std::error_code EC = initStream(std::move(Streamer)))
3717     return EC;
3718
3719   // Sniff for the signature.
3720   if (!hasValidBitcodeHeader(Stream))
3721     return error("Invalid bitcode signature");
3722
3723   // We expect a number of well-defined blocks, though we don't necessarily
3724   // need to understand them all.
3725   while (1) {
3726     if (Stream.AtEndOfStream()) {
3727       // We didn't really read a proper Module.
3728       return error("Malformed IR file");
3729     }
3730
3731     BitstreamEntry Entry =
3732       Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
3733
3734     if (Entry.Kind != BitstreamEntry::SubBlock)
3735       return error("Malformed block");
3736
3737     if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3738       parseBitcodeVersion();
3739       continue;
3740     }
3741
3742     if (Entry.ID == bitc::MODULE_BLOCK_ID)
3743       return parseModule(0, ShouldLazyLoadMetadata);
3744
3745     if (Stream.SkipBlock())
3746       return error("Invalid record");
3747   }
3748 }
3749
3750 ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
3751   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
3752     return error("Invalid record");
3753
3754   SmallVector<uint64_t, 64> Record;
3755
3756   std::string Triple;
3757   // Read all the records for this module.
3758   while (1) {
3759     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3760
3761     switch (Entry.Kind) {
3762     case BitstreamEntry::SubBlock: // Handled for us already.
3763     case BitstreamEntry::Error:
3764       return error("Malformed block");
3765     case BitstreamEntry::EndBlock:
3766       return Triple;
3767     case BitstreamEntry::Record:
3768       // The interesting case.
3769       break;
3770     }
3771
3772     // Read a record.
3773     switch (Stream.readRecord(Entry.ID, Record)) {
3774     default: break;  // Default behavior, ignore unknown content.
3775     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
3776       std::string S;
3777       if (convertToString(Record, 0, S))
3778         return error("Invalid record");
3779       Triple = S;
3780       break;
3781     }
3782     }
3783     Record.clear();
3784   }
3785   llvm_unreachable("Exit infinite loop");
3786 }
3787
3788 ErrorOr<std::string> BitcodeReader::parseTriple() {
3789   if (std::error_code EC = initStream(nullptr))
3790     return EC;
3791
3792   // Sniff for the signature.
3793   if (!hasValidBitcodeHeader(Stream))
3794     return error("Invalid bitcode signature");
3795
3796   // We expect a number of well-defined blocks, though we don't necessarily
3797   // need to understand them all.
3798   while (1) {
3799     BitstreamEntry Entry = Stream.advance();
3800
3801     switch (Entry.Kind) {
3802     case BitstreamEntry::Error:
3803       return error("Malformed block");
3804     case BitstreamEntry::EndBlock:
3805       return std::error_code();
3806
3807     case BitstreamEntry::SubBlock:
3808       if (Entry.ID == bitc::MODULE_BLOCK_ID)
3809         return parseModuleTriple();
3810
3811       // Ignore other sub-blocks.
3812       if (Stream.SkipBlock())
3813         return error("Malformed block");
3814       continue;
3815
3816     case BitstreamEntry::Record:
3817       Stream.skipRecord(Entry.ID);
3818       continue;
3819     }
3820   }
3821 }
3822
3823 ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3824   if (std::error_code EC = initStream(nullptr))
3825     return EC;
3826
3827   // Sniff for the signature.
3828   if (!hasValidBitcodeHeader(Stream))
3829     return error("Invalid bitcode signature");
3830
3831   // We expect a number of well-defined blocks, though we don't necessarily
3832   // need to understand them all.
3833   while (1) {
3834     BitstreamEntry Entry = Stream.advance();
3835     switch (Entry.Kind) {
3836     case BitstreamEntry::Error:
3837       return error("Malformed block");
3838     case BitstreamEntry::EndBlock:
3839       return std::error_code();
3840
3841     case BitstreamEntry::SubBlock:
3842       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3843         if (std::error_code EC = parseBitcodeVersion())
3844           return EC;
3845         return ProducerIdentification;
3846       }
3847       // Ignore other sub-blocks.
3848       if (Stream.SkipBlock())
3849         return error("Malformed block");
3850       continue;
3851     case BitstreamEntry::Record:
3852       Stream.skipRecord(Entry.ID);
3853       continue;
3854     }
3855   }
3856 }
3857
3858 /// Parse metadata attachments.
3859 std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
3860   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
3861     return error("Invalid record");
3862
3863   SmallVector<uint64_t, 64> Record;
3864   while (1) {
3865     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
3866
3867     switch (Entry.Kind) {
3868     case BitstreamEntry::SubBlock: // Handled for us already.
3869     case BitstreamEntry::Error:
3870       return error("Malformed block");
3871     case BitstreamEntry::EndBlock:
3872       return std::error_code();
3873     case BitstreamEntry::Record:
3874       // The interesting case.
3875       break;
3876     }
3877
3878     // Read a metadata attachment record.
3879     Record.clear();
3880     switch (Stream.readRecord(Entry.ID, Record)) {
3881     default:  // Default behavior: ignore.
3882       break;
3883     case bitc::METADATA_ATTACHMENT: {
3884       unsigned RecordLength = Record.size();
3885       if (Record.empty())
3886         return error("Invalid record");
3887       if (RecordLength % 2 == 0) {
3888         // A function attachment.
3889         for (unsigned I = 0; I != RecordLength; I += 2) {
3890           auto K = MDKindMap.find(Record[I]);
3891           if (K == MDKindMap.end())
3892             return error("Invalid ID");
3893           Metadata *MD = MetadataList.getValueFwdRef(Record[I + 1]);
3894           F.setMetadata(K->second, cast<MDNode>(MD));
3895         }
3896         continue;
3897       }
3898
3899       // An instruction attachment.
3900       Instruction *Inst = InstructionList[Record[0]];
3901       for (unsigned i = 1; i != RecordLength; i = i+2) {
3902         unsigned Kind = Record[i];
3903         DenseMap<unsigned, unsigned>::iterator I =
3904           MDKindMap.find(Kind);
3905         if (I == MDKindMap.end())
3906           return error("Invalid ID");
3907         Metadata *Node = MetadataList.getValueFwdRef(Record[i + 1]);
3908         if (isa<LocalAsMetadata>(Node))
3909           // Drop the attachment.  This used to be legal, but there's no
3910           // upgrade path.
3911           break;
3912         Inst->setMetadata(I->second, cast<MDNode>(Node));
3913         if (I->second == LLVMContext::MD_tbaa)
3914           InstsWithTBAATag.push_back(Inst);
3915       }
3916       break;
3917     }
3918     }
3919   }
3920 }
3921
3922 static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3923   LLVMContext &Context = PtrType->getContext();
3924   if (!isa<PointerType>(PtrType))
3925     return error(Context, "Load/Store operand is not a pointer type");
3926   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3927
3928   if (ValType && ValType != ElemType)
3929     return error(Context, "Explicit load/store type does not match pointee "
3930                           "type of pointer operand");
3931   if (!PointerType::isLoadableOrStorableType(ElemType))
3932     return error(Context, "Cannot load/store from pointer");
3933   return std::error_code();
3934 }
3935
3936 /// Lazily parse the specified function body block.
3937 std::error_code BitcodeReader::parseFunctionBody(Function *F) {
3938   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
3939     return error("Invalid record");
3940
3941   InstructionList.clear();
3942   unsigned ModuleValueListSize = ValueList.size();
3943   unsigned ModuleMetadataListSize = MetadataList.size();
3944
3945   // Add all the function arguments to the value table.
3946   for (Argument &I : F->args())
3947     ValueList.push_back(&I);
3948
3949   unsigned NextValueNo = ValueList.size();
3950   BasicBlock *CurBB = nullptr;
3951   unsigned CurBBNo = 0;
3952
3953   DebugLoc LastLoc;
3954   auto getLastInstruction = [&]() -> Instruction * {
3955     if (CurBB && !CurBB->empty())
3956       return &CurBB->back();
3957     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3958              !FunctionBBs[CurBBNo - 1]->empty())
3959       return &FunctionBBs[CurBBNo - 1]->back();
3960     return nullptr;
3961   };
3962
3963   std::vector<OperandBundleDef> OperandBundles;
3964
3965   // Read all the records.
3966   SmallVector<uint64_t, 64> Record;
3967   while (1) {
3968     BitstreamEntry Entry = Stream.advance();
3969
3970     switch (Entry.Kind) {
3971     case BitstreamEntry::Error:
3972       return error("Malformed block");
3973     case BitstreamEntry::EndBlock:
3974       goto OutOfRecordLoop;
3975
3976     case BitstreamEntry::SubBlock:
3977       switch (Entry.ID) {
3978       default:  // Skip unknown content.
3979         if (Stream.SkipBlock())
3980           return error("Invalid record");
3981         break;
3982       case bitc::CONSTANTS_BLOCK_ID:
3983         if (std::error_code EC = parseConstants())
3984           return EC;
3985         NextValueNo = ValueList.size();
3986         break;
3987       case bitc::VALUE_SYMTAB_BLOCK_ID:
3988         if (std::error_code EC = parseValueSymbolTable())
3989           return EC;
3990         break;
3991       case bitc::METADATA_ATTACHMENT_ID:
3992         if (std::error_code EC = parseMetadataAttachment(*F))
3993           return EC;
3994         break;
3995       case bitc::METADATA_BLOCK_ID:
3996         if (std::error_code EC = parseMetadata())
3997           return EC;
3998         break;
3999       case bitc::USELIST_BLOCK_ID:
4000         if (std::error_code EC = parseUseLists())
4001           return EC;
4002         break;
4003       }
4004       continue;
4005
4006     case BitstreamEntry::Record:
4007       // The interesting case.
4008       break;
4009     }
4010
4011     // Read a record.
4012     Record.clear();
4013     Instruction *I = nullptr;
4014     unsigned BitCode = Stream.readRecord(Entry.ID, Record);
4015     switch (BitCode) {
4016     default: // Default behavior: reject
4017       return error("Invalid value");
4018     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4019       if (Record.size() < 1 || Record[0] == 0)
4020         return error("Invalid record");
4021       // Create all the basic blocks for the function.
4022       FunctionBBs.resize(Record[0]);
4023
4024       // See if anything took the address of blocks in this function.
4025       auto BBFRI = BasicBlockFwdRefs.find(F);
4026       if (BBFRI == BasicBlockFwdRefs.end()) {
4027         for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4028           FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4029       } else {
4030         auto &BBRefs = BBFRI->second;
4031         // Check for invalid basic block references.
4032         if (BBRefs.size() > FunctionBBs.size())
4033           return error("Invalid ID");
4034         assert(!BBRefs.empty() && "Unexpected empty array");
4035         assert(!BBRefs.front() && "Invalid reference to entry block");
4036         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4037              ++I)
4038           if (I < RE && BBRefs[I]) {
4039             BBRefs[I]->insertInto(F);
4040             FunctionBBs[I] = BBRefs[I];
4041           } else {
4042             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4043           }
4044
4045         // Erase from the table.
4046         BasicBlockFwdRefs.erase(BBFRI);
4047       }
4048
4049       CurBB = FunctionBBs[0];
4050       continue;
4051     }
4052
4053     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4054       // This record indicates that the last instruction is at the same
4055       // location as the previous instruction with a location.
4056       I = getLastInstruction();
4057
4058       if (!I)
4059         return error("Invalid record");
4060       I->setDebugLoc(LastLoc);
4061       I = nullptr;
4062       continue;
4063
4064     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
4065       I = getLastInstruction();
4066       if (!I || Record.size() < 4)
4067         return error("Invalid record");
4068
4069       unsigned Line = Record[0], Col = Record[1];
4070       unsigned ScopeID = Record[2], IAID = Record[3];
4071
4072       MDNode *Scope = nullptr, *IA = nullptr;
4073       if (ScopeID)
4074         Scope = cast<MDNode>(MetadataList.getValueFwdRef(ScopeID - 1));
4075       if (IAID)
4076         IA = cast<MDNode>(MetadataList.getValueFwdRef(IAID - 1));
4077       LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4078       I->setDebugLoc(LastLoc);
4079       I = nullptr;
4080       continue;
4081     }
4082
4083     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4084       unsigned OpNum = 0;
4085       Value *LHS, *RHS;
4086       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4087           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
4088           OpNum+1 > Record.size())
4089         return error("Invalid record");
4090
4091       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4092       if (Opc == -1)
4093         return error("Invalid record");
4094       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4095       InstructionList.push_back(I);
4096       if (OpNum < Record.size()) {
4097         if (Opc == Instruction::Add ||
4098             Opc == Instruction::Sub ||
4099             Opc == Instruction::Mul ||
4100             Opc == Instruction::Shl) {
4101           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4102             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4103           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4104             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4105         } else if (Opc == Instruction::SDiv ||
4106                    Opc == Instruction::UDiv ||
4107                    Opc == Instruction::LShr ||
4108                    Opc == Instruction::AShr) {
4109           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4110             cast<BinaryOperator>(I)->setIsExact(true);
4111         } else if (isa<FPMathOperator>(I)) {
4112           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4113           if (FMF.any())
4114             I->setFastMathFlags(FMF);
4115         }
4116
4117       }
4118       break;
4119     }
4120     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4121       unsigned OpNum = 0;
4122       Value *Op;
4123       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4124           OpNum+2 != Record.size())
4125         return error("Invalid record");
4126
4127       Type *ResTy = getTypeByID(Record[OpNum]);
4128       int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4129       if (Opc == -1 || !ResTy)
4130         return error("Invalid record");
4131       Instruction *Temp = nullptr;
4132       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4133         if (Temp) {
4134           InstructionList.push_back(Temp);
4135           CurBB->getInstList().push_back(Temp);
4136         }
4137       } else {
4138         auto CastOp = (Instruction::CastOps)Opc;
4139         if (!CastInst::castIsValid(CastOp, Op, ResTy))
4140           return error("Invalid cast");
4141         I = CastInst::Create(CastOp, Op, ResTy);
4142       }
4143       InstructionList.push_back(I);
4144       break;
4145     }
4146     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4147     case bitc::FUNC_CODE_INST_GEP_OLD:
4148     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4149       unsigned OpNum = 0;
4150
4151       Type *Ty;
4152       bool InBounds;
4153
4154       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4155         InBounds = Record[OpNum++];
4156         Ty = getTypeByID(Record[OpNum++]);
4157       } else {
4158         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4159         Ty = nullptr;
4160       }
4161
4162       Value *BasePtr;
4163       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
4164         return error("Invalid record");
4165
4166       if (!Ty)
4167         Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4168                  ->getElementType();
4169       else if (Ty !=
4170                cast<SequentialType>(BasePtr->getType()->getScalarType())
4171                    ->getElementType())
4172         return error(
4173             "Explicit gep type does not match pointee type of pointer operand");
4174
4175       SmallVector<Value*, 16> GEPIdx;
4176       while (OpNum != Record.size()) {
4177         Value *Op;
4178         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4179           return error("Invalid record");
4180         GEPIdx.push_back(Op);
4181       }
4182
4183       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4184
4185       InstructionList.push_back(I);
4186       if (InBounds)
4187         cast<GetElementPtrInst>(I)->setIsInBounds(true);
4188       break;
4189     }
4190
4191     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4192                                        // EXTRACTVAL: [opty, opval, n x indices]
4193       unsigned OpNum = 0;
4194       Value *Agg;
4195       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4196         return error("Invalid record");
4197
4198       unsigned RecSize = Record.size();
4199       if (OpNum == RecSize)
4200         return error("EXTRACTVAL: Invalid instruction with 0 indices");
4201
4202       SmallVector<unsigned, 4> EXTRACTVALIdx;
4203       Type *CurTy = Agg->getType();
4204       for (; OpNum != RecSize; ++OpNum) {
4205         bool IsArray = CurTy->isArrayTy();
4206         bool IsStruct = CurTy->isStructTy();
4207         uint64_t Index = Record[OpNum];
4208
4209         if (!IsStruct && !IsArray)
4210           return error("EXTRACTVAL: Invalid type");
4211         if ((unsigned)Index != Index)
4212           return error("Invalid value");
4213         if (IsStruct && Index >= CurTy->subtypes().size())
4214           return error("EXTRACTVAL: Invalid struct index");
4215         if (IsArray && Index >= CurTy->getArrayNumElements())
4216           return error("EXTRACTVAL: Invalid array index");
4217         EXTRACTVALIdx.push_back((unsigned)Index);
4218
4219         if (IsStruct)
4220           CurTy = CurTy->subtypes()[Index];
4221         else
4222           CurTy = CurTy->subtypes()[0];
4223       }
4224
4225       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4226       InstructionList.push_back(I);
4227       break;
4228     }
4229
4230     case bitc::FUNC_CODE_INST_INSERTVAL: {
4231                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
4232       unsigned OpNum = 0;
4233       Value *Agg;
4234       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
4235         return error("Invalid record");
4236       Value *Val;
4237       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
4238         return error("Invalid record");
4239
4240       unsigned RecSize = Record.size();
4241       if (OpNum == RecSize)
4242         return error("INSERTVAL: Invalid instruction with 0 indices");
4243
4244       SmallVector<unsigned, 4> INSERTVALIdx;
4245       Type *CurTy = Agg->getType();
4246       for (; OpNum != RecSize; ++OpNum) {
4247         bool IsArray = CurTy->isArrayTy();
4248         bool IsStruct = CurTy->isStructTy();
4249         uint64_t Index = Record[OpNum];
4250
4251         if (!IsStruct && !IsArray)
4252           return error("INSERTVAL: Invalid type");
4253         if ((unsigned)Index != Index)
4254           return error("Invalid value");
4255         if (IsStruct && Index >= CurTy->subtypes().size())
4256           return error("INSERTVAL: Invalid struct index");
4257         if (IsArray && Index >= CurTy->getArrayNumElements())
4258           return error("INSERTVAL: Invalid array index");
4259
4260         INSERTVALIdx.push_back((unsigned)Index);
4261         if (IsStruct)
4262           CurTy = CurTy->subtypes()[Index];
4263         else
4264           CurTy = CurTy->subtypes()[0];
4265       }
4266
4267       if (CurTy != Val->getType())
4268         return error("Inserted value type doesn't match aggregate type");
4269
4270       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4271       InstructionList.push_back(I);
4272       break;
4273     }
4274
4275     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4276       // obsolete form of select
4277       // handles select i1 ... in old bitcode
4278       unsigned OpNum = 0;
4279       Value *TrueVal, *FalseVal, *Cond;
4280       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4281           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4282           popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
4283         return error("Invalid record");
4284
4285       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4286       InstructionList.push_back(I);
4287       break;
4288     }
4289
4290     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4291       // new form of select
4292       // handles select i1 or select [N x i1]
4293       unsigned OpNum = 0;
4294       Value *TrueVal, *FalseVal, *Cond;
4295       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
4296           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4297           getValueTypePair(Record, OpNum, NextValueNo, Cond))
4298         return error("Invalid record");
4299
4300       // select condition can be either i1 or [N x i1]
4301       if (VectorType* vector_type =
4302           dyn_cast<VectorType>(Cond->getType())) {
4303         // expect <n x i1>
4304         if (vector_type->getElementType() != Type::getInt1Ty(Context))
4305           return error("Invalid type for value");
4306       } else {
4307         // expect i1
4308         if (Cond->getType() != Type::getInt1Ty(Context))
4309           return error("Invalid type for value");
4310       }
4311
4312       I = SelectInst::Create(Cond, TrueVal, FalseVal);
4313       InstructionList.push_back(I);
4314       break;
4315     }
4316
4317     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4318       unsigned OpNum = 0;
4319       Value *Vec, *Idx;
4320       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
4321           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4322         return error("Invalid record");
4323       if (!Vec->getType()->isVectorTy())
4324         return error("Invalid type for value");
4325       I = ExtractElementInst::Create(Vec, Idx);
4326       InstructionList.push_back(I);
4327       break;
4328     }
4329
4330     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
4331       unsigned OpNum = 0;
4332       Value *Vec, *Elt, *Idx;
4333       if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
4334         return error("Invalid record");
4335       if (!Vec->getType()->isVectorTy())
4336         return error("Invalid type for value");
4337       if (popValue(Record, OpNum, NextValueNo,
4338                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
4339           getValueTypePair(Record, OpNum, NextValueNo, Idx))
4340         return error("Invalid record");
4341       I = InsertElementInst::Create(Vec, Elt, Idx);
4342       InstructionList.push_back(I);
4343       break;
4344     }
4345
4346     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4347       unsigned OpNum = 0;
4348       Value *Vec1, *Vec2, *Mask;
4349       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
4350           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
4351         return error("Invalid record");
4352
4353       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
4354         return error("Invalid record");
4355       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
4356         return error("Invalid type for value");
4357       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
4358       InstructionList.push_back(I);
4359       break;
4360     }
4361
4362     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
4363       // Old form of ICmp/FCmp returning bool
4364       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4365       // both legal on vectors but had different behaviour.
4366     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4367       // FCmp/ICmp returning bool or vector of bool
4368
4369       unsigned OpNum = 0;
4370       Value *LHS, *RHS;
4371       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
4372           popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4373         return error("Invalid record");
4374
4375       unsigned PredVal = Record[OpNum];
4376       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4377       FastMathFlags FMF;
4378       if (IsFP && Record.size() > OpNum+1)
4379         FMF = getDecodedFastMathFlags(Record[++OpNum]);
4380
4381       if (OpNum+1 != Record.size())
4382         return error("Invalid record");
4383
4384       if (LHS->getType()->isFPOrFPVectorTy())
4385         I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
4386       else
4387         I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4388
4389       if (FMF.any())
4390         I->setFastMathFlags(FMF);
4391       InstructionList.push_back(I);
4392       break;
4393     }
4394
4395     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
4396       {
4397         unsigned Size = Record.size();
4398         if (Size == 0) {
4399           I = ReturnInst::Create(Context);
4400           InstructionList.push_back(I);
4401           break;
4402         }
4403
4404         unsigned OpNum = 0;
4405         Value *Op = nullptr;
4406         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4407           return error("Invalid record");
4408         if (OpNum != Record.size())
4409           return error("Invalid record");
4410
4411         I = ReturnInst::Create(Context, Op);
4412         InstructionList.push_back(I);
4413         break;
4414       }
4415     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
4416       if (Record.size() != 1 && Record.size() != 3)
4417         return error("Invalid record");
4418       BasicBlock *TrueDest = getBasicBlock(Record[0]);
4419       if (!TrueDest)
4420         return error("Invalid record");
4421
4422       if (Record.size() == 1) {
4423         I = BranchInst::Create(TrueDest);
4424         InstructionList.push_back(I);
4425       }
4426       else {
4427         BasicBlock *FalseDest = getBasicBlock(Record[1]);
4428         Value *Cond = getValue(Record, 2, NextValueNo,
4429                                Type::getInt1Ty(Context));
4430         if (!FalseDest || !Cond)
4431           return error("Invalid record");
4432         I = BranchInst::Create(TrueDest, FalseDest, Cond);
4433         InstructionList.push_back(I);
4434       }
4435       break;
4436     }
4437     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
4438       if (Record.size() != 1 && Record.size() != 2)
4439         return error("Invalid record");
4440       unsigned Idx = 0;
4441       Value *CleanupPad =
4442           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4443       if (!CleanupPad)
4444         return error("Invalid record");
4445       BasicBlock *UnwindDest = nullptr;
4446       if (Record.size() == 2) {
4447         UnwindDest = getBasicBlock(Record[Idx++]);
4448         if (!UnwindDest)
4449           return error("Invalid record");
4450       }
4451
4452       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
4453       InstructionList.push_back(I);
4454       break;
4455     }
4456     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4457       if (Record.size() != 2)
4458         return error("Invalid record");
4459       unsigned Idx = 0;
4460       Value *CatchPad =
4461           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4462       if (!CatchPad)
4463         return error("Invalid record");
4464       BasicBlock *BB = getBasicBlock(Record[Idx++]);
4465       if (!BB)
4466         return error("Invalid record");
4467
4468       I = CatchReturnInst::Create(CatchPad, BB);
4469       InstructionList.push_back(I);
4470       break;
4471     }
4472     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4473       // We must have, at minimum, the outer scope and the number of arguments.
4474       if (Record.size() < 2)
4475         return error("Invalid record");
4476
4477       unsigned Idx = 0;
4478
4479       Value *ParentPad =
4480           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4481
4482       unsigned NumHandlers = Record[Idx++];
4483
4484       SmallVector<BasicBlock *, 2> Handlers;
4485       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4486         BasicBlock *BB = getBasicBlock(Record[Idx++]);
4487         if (!BB)
4488           return error("Invalid record");
4489         Handlers.push_back(BB);
4490       }
4491
4492       BasicBlock *UnwindDest = nullptr;
4493       if (Idx + 1 == Record.size()) {
4494         UnwindDest = getBasicBlock(Record[Idx++]);
4495         if (!UnwindDest)
4496           return error("Invalid record");
4497       }
4498
4499       if (Record.size() != Idx)
4500         return error("Invalid record");
4501
4502       auto *CatchSwitch =
4503           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4504       for (BasicBlock *Handler : Handlers)
4505         CatchSwitch->addHandler(Handler);
4506       I = CatchSwitch;
4507       InstructionList.push_back(I);
4508       break;
4509     }
4510     case bitc::FUNC_CODE_INST_CATCHPAD:
4511     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4512       // We must have, at minimum, the outer scope and the number of arguments.
4513       if (Record.size() < 2)
4514         return error("Invalid record");
4515
4516       unsigned Idx = 0;
4517
4518       Value *ParentPad =
4519           getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4520
4521       unsigned NumArgOperands = Record[Idx++];
4522
4523       SmallVector<Value *, 2> Args;
4524       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4525         Value *Val;
4526         if (getValueTypePair(Record, Idx, NextValueNo, Val))
4527           return error("Invalid record");
4528         Args.push_back(Val);
4529       }
4530
4531       if (Record.size() != Idx)
4532         return error("Invalid record");
4533
4534       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4535         I = CleanupPadInst::Create(ParentPad, Args);
4536       else
4537         I = CatchPadInst::Create(ParentPad, Args);
4538       InstructionList.push_back(I);
4539       break;
4540     }
4541     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
4542       // Check magic
4543       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
4544         // "New" SwitchInst format with case ranges. The changes to write this
4545         // format were reverted but we still recognize bitcode that uses it.
4546         // Hopefully someday we will have support for case ranges and can use
4547         // this format again.
4548
4549         Type *OpTy = getTypeByID(Record[1]);
4550         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4551
4552         Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
4553         BasicBlock *Default = getBasicBlock(Record[3]);
4554         if (!OpTy || !Cond || !Default)
4555           return error("Invalid record");
4556
4557         unsigned NumCases = Record[4];
4558
4559         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4560         InstructionList.push_back(SI);
4561
4562         unsigned CurIdx = 5;
4563         for (unsigned i = 0; i != NumCases; ++i) {
4564           SmallVector<ConstantInt*, 1> CaseVals;
4565           unsigned NumItems = Record[CurIdx++];
4566           for (unsigned ci = 0; ci != NumItems; ++ci) {
4567             bool isSingleNumber = Record[CurIdx++];
4568
4569             APInt Low;
4570             unsigned ActiveWords = 1;
4571             if (ValueBitWidth > 64)
4572               ActiveWords = Record[CurIdx++];
4573             Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
4574                                 ValueBitWidth);
4575             CurIdx += ActiveWords;
4576
4577             if (!isSingleNumber) {
4578               ActiveWords = 1;
4579               if (ValueBitWidth > 64)
4580                 ActiveWords = Record[CurIdx++];
4581               APInt High = readWideAPInt(
4582                   makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
4583               CurIdx += ActiveWords;
4584
4585               // FIXME: It is not clear whether values in the range should be
4586               // compared as signed or unsigned values. The partially
4587               // implemented changes that used this format in the past used
4588               // unsigned comparisons.
4589               for ( ; Low.ule(High); ++Low)
4590                 CaseVals.push_back(ConstantInt::get(Context, Low));
4591             } else
4592               CaseVals.push_back(ConstantInt::get(Context, Low));
4593           }
4594           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
4595           for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4596                  cve = CaseVals.end(); cvi != cve; ++cvi)
4597             SI->addCase(*cvi, DestBB);
4598         }
4599         I = SI;
4600         break;
4601       }
4602
4603       // Old SwitchInst format without case ranges.
4604
4605       if (Record.size() < 3 || (Record.size() & 1) == 0)
4606         return error("Invalid record");
4607       Type *OpTy = getTypeByID(Record[0]);
4608       Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
4609       BasicBlock *Default = getBasicBlock(Record[2]);
4610       if (!OpTy || !Cond || !Default)
4611         return error("Invalid record");
4612       unsigned NumCases = (Record.size()-3)/2;
4613       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4614       InstructionList.push_back(SI);
4615       for (unsigned i = 0, e = NumCases; i != e; ++i) {
4616         ConstantInt *CaseVal =
4617           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4618         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
4619         if (!CaseVal || !DestBB) {
4620           delete SI;
4621           return error("Invalid record");
4622         }
4623         SI->addCase(CaseVal, DestBB);
4624       }
4625       I = SI;
4626       break;
4627     }
4628     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
4629       if (Record.size() < 2)
4630         return error("Invalid record");
4631       Type *OpTy = getTypeByID(Record[0]);
4632       Value *Address = getValue(Record, 1, NextValueNo, OpTy);
4633       if (!OpTy || !Address)
4634         return error("Invalid record");
4635       unsigned NumDests = Record.size()-2;
4636       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
4637       InstructionList.push_back(IBI);
4638       for (unsigned i = 0, e = NumDests; i != e; ++i) {
4639         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4640           IBI->addDestination(DestBB);
4641         } else {
4642           delete IBI;
4643           return error("Invalid record");
4644         }
4645       }
4646       I = IBI;
4647       break;
4648     }
4649
4650     case bitc::FUNC_CODE_INST_INVOKE: {
4651       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
4652       if (Record.size() < 4)
4653         return error("Invalid record");
4654       unsigned OpNum = 0;
4655       AttributeSet PAL = getAttributes(Record[OpNum++]);
4656       unsigned CCInfo = Record[OpNum++];
4657       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4658       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
4659
4660       FunctionType *FTy = nullptr;
4661       if (CCInfo >> 13 & 1 &&
4662           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4663         return error("Explicit invoke type is not a function type");
4664
4665       Value *Callee;
4666       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4667         return error("Invalid record");
4668
4669       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
4670       if (!CalleeTy)
4671         return error("Callee is not a pointer");
4672       if (!FTy) {
4673         FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4674         if (!FTy)
4675           return error("Callee is not of pointer to function type");
4676       } else if (CalleeTy->getElementType() != FTy)
4677         return error("Explicit invoke type does not match pointee type of "
4678                      "callee operand");
4679       if (Record.size() < FTy->getNumParams() + OpNum)
4680         return error("Insufficient operands to call");
4681
4682       SmallVector<Value*, 16> Ops;
4683       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4684         Ops.push_back(getValue(Record, OpNum, NextValueNo,
4685                                FTy->getParamType(i)));
4686         if (!Ops.back())
4687           return error("Invalid record");
4688       }
4689
4690       if (!FTy->isVarArg()) {
4691         if (Record.size() != OpNum)
4692           return error("Invalid record");
4693       } else {
4694         // Read type/value pairs for varargs params.
4695         while (OpNum != Record.size()) {
4696           Value *Op;
4697           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4698             return error("Invalid record");
4699           Ops.push_back(Op);
4700         }
4701       }
4702
4703       I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4704       OperandBundles.clear();
4705       InstructionList.push_back(I);
4706       cast<InvokeInst>(I)->setCallingConv(
4707           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
4708       cast<InvokeInst>(I)->setAttributes(PAL);
4709       break;
4710     }
4711     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4712       unsigned Idx = 0;
4713       Value *Val = nullptr;
4714       if (getValueTypePair(Record, Idx, NextValueNo, Val))
4715         return error("Invalid record");
4716       I = ResumeInst::Create(Val);
4717       InstructionList.push_back(I);
4718       break;
4719     }
4720     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
4721       I = new UnreachableInst(Context);
4722       InstructionList.push_back(I);
4723       break;
4724     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
4725       if (Record.size() < 1 || ((Record.size()-1)&1))
4726         return error("Invalid record");
4727       Type *Ty = getTypeByID(Record[0]);
4728       if (!Ty)
4729         return error("Invalid record");
4730
4731       PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
4732       InstructionList.push_back(PN);
4733
4734       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
4735         Value *V;
4736         // With the new function encoding, it is possible that operands have
4737         // negative IDs (for forward references).  Use a signed VBR
4738         // representation to keep the encoding small.
4739         if (UseRelativeIDs)
4740           V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4741         else
4742           V = getValue(Record, 1+i, NextValueNo, Ty);
4743         BasicBlock *BB = getBasicBlock(Record[2+i]);
4744         if (!V || !BB)
4745           return error("Invalid record");
4746         PN->addIncoming(V, BB);
4747       }
4748       I = PN;
4749       break;
4750     }
4751
4752     case bitc::FUNC_CODE_INST_LANDINGPAD:
4753     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
4754       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4755       unsigned Idx = 0;
4756       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4757         if (Record.size() < 3)
4758           return error("Invalid record");
4759       } else {
4760         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4761         if (Record.size() < 4)
4762           return error("Invalid record");
4763       }
4764       Type *Ty = getTypeByID(Record[Idx++]);
4765       if (!Ty)
4766         return error("Invalid record");
4767       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4768         Value *PersFn = nullptr;
4769         if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4770           return error("Invalid record");
4771
4772         if (!F->hasPersonalityFn())
4773           F->setPersonalityFn(cast<Constant>(PersFn));
4774         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4775           return error("Personality function mismatch");
4776       }
4777
4778       bool IsCleanup = !!Record[Idx++];
4779       unsigned NumClauses = Record[Idx++];
4780       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
4781       LP->setCleanup(IsCleanup);
4782       for (unsigned J = 0; J != NumClauses; ++J) {
4783         LandingPadInst::ClauseType CT =
4784           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4785         Value *Val;
4786
4787         if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4788           delete LP;
4789           return error("Invalid record");
4790         }
4791
4792         assert((CT != LandingPadInst::Catch ||
4793                 !isa<ArrayType>(Val->getType())) &&
4794                "Catch clause has a invalid type!");
4795         assert((CT != LandingPadInst::Filter ||
4796                 isa<ArrayType>(Val->getType())) &&
4797                "Filter clause has invalid type!");
4798         LP->addClause(cast<Constant>(Val));
4799       }
4800
4801       I = LP;
4802       InstructionList.push_back(I);
4803       break;
4804     }
4805
4806     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4807       if (Record.size() != 4)
4808         return error("Invalid record");
4809       uint64_t AlignRecord = Record[3];
4810       const uint64_t InAllocaMask = uint64_t(1) << 5;
4811       const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4812       // Reserve bit 7 for SwiftError flag.
4813       // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4814       const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
4815       bool InAlloca = AlignRecord & InAllocaMask;
4816       Type *Ty = getTypeByID(Record[0]);
4817       if ((AlignRecord & ExplicitTypeMask) == 0) {
4818         auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4819         if (!PTy)
4820           return error("Old-style alloca with a non-pointer type");
4821         Ty = PTy->getElementType();
4822       }
4823       Type *OpTy = getTypeByID(Record[1]);
4824       Value *Size = getFnValueByID(Record[2], OpTy);
4825       unsigned Align;
4826       if (std::error_code EC =
4827               parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4828         return EC;
4829       }
4830       if (!Ty || !Size)
4831         return error("Invalid record");
4832       AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4833       AI->setUsedWithInAlloca(InAlloca);
4834       I = AI;
4835       InstructionList.push_back(I);
4836       break;
4837     }
4838     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4839       unsigned OpNum = 0;
4840       Value *Op;
4841       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4842           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4843         return error("Invalid record");
4844
4845       Type *Ty = nullptr;
4846       if (OpNum + 3 == Record.size())
4847         Ty = getTypeByID(Record[OpNum++]);
4848       if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
4849         return EC;
4850       if (!Ty)
4851         Ty = cast<PointerType>(Op->getType())->getElementType();
4852
4853       unsigned Align;
4854       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4855         return EC;
4856       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4857
4858       InstructionList.push_back(I);
4859       break;
4860     }
4861     case bitc::FUNC_CODE_INST_LOADATOMIC: {
4862        // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4863       unsigned OpNum = 0;
4864       Value *Op;
4865       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4866           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4867         return error("Invalid record");
4868
4869       Type *Ty = nullptr;
4870       if (OpNum + 5 == Record.size())
4871         Ty = getTypeByID(Record[OpNum++]);
4872       if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
4873         return EC;
4874       if (!Ty)
4875         Ty = cast<PointerType>(Op->getType())->getElementType();
4876
4877       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4878       if (Ordering == NotAtomic || Ordering == Release ||
4879           Ordering == AcquireRelease)
4880         return error("Invalid record");
4881       if (Ordering != NotAtomic && Record[OpNum] == 0)
4882         return error("Invalid record");
4883       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4884
4885       unsigned Align;
4886       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4887         return EC;
4888       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4889
4890       InstructionList.push_back(I);
4891       break;
4892     }
4893     case bitc::FUNC_CODE_INST_STORE:
4894     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4895       unsigned OpNum = 0;
4896       Value *Val, *Ptr;
4897       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4898           (BitCode == bitc::FUNC_CODE_INST_STORE
4899                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4900                : popValue(Record, OpNum, NextValueNo,
4901                           cast<PointerType>(Ptr->getType())->getElementType(),
4902                           Val)) ||
4903           OpNum + 2 != Record.size())
4904         return error("Invalid record");
4905
4906       if (std::error_code EC =
4907               typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4908         return EC;
4909       unsigned Align;
4910       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4911         return EC;
4912       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4913       InstructionList.push_back(I);
4914       break;
4915     }
4916     case bitc::FUNC_CODE_INST_STOREATOMIC:
4917     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
4918       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4919       unsigned OpNum = 0;
4920       Value *Val, *Ptr;
4921       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4922           (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4923                ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4924                : popValue(Record, OpNum, NextValueNo,
4925                           cast<PointerType>(Ptr->getType())->getElementType(),
4926                           Val)) ||
4927           OpNum + 4 != Record.size())
4928         return error("Invalid record");
4929
4930       if (std::error_code EC =
4931               typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4932         return EC;
4933       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4934       if (Ordering == NotAtomic || Ordering == Acquire ||
4935           Ordering == AcquireRelease)
4936         return error("Invalid record");
4937       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4938       if (Ordering != NotAtomic && Record[OpNum] == 0)
4939         return error("Invalid record");
4940
4941       unsigned Align;
4942       if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4943         return EC;
4944       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4945       InstructionList.push_back(I);
4946       break;
4947     }
4948     case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
4949     case bitc::FUNC_CODE_INST_CMPXCHG: {
4950       // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4951       //          failureordering?, isweak?]
4952       unsigned OpNum = 0;
4953       Value *Ptr, *Cmp, *New;
4954       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4955           (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4956                ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4957                : popValue(Record, OpNum, NextValueNo,
4958                           cast<PointerType>(Ptr->getType())->getElementType(),
4959                           Cmp)) ||
4960           popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4961           Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4962         return error("Invalid record");
4963       AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4964       if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
4965         return error("Invalid record");
4966       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4967
4968       if (std::error_code EC =
4969               typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4970         return EC;
4971       AtomicOrdering FailureOrdering;
4972       if (Record.size() < 7)
4973         FailureOrdering =
4974             AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4975       else
4976         FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4977
4978       I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4979                                 SynchScope);
4980       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4981
4982       if (Record.size() < 8) {
4983         // Before weak cmpxchgs existed, the instruction simply returned the
4984         // value loaded from memory, so bitcode files from that era will be
4985         // expecting the first component of a modern cmpxchg.
4986         CurBB->getInstList().push_back(I);
4987         I = ExtractValueInst::Create(I, 0);
4988       } else {
4989         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4990       }
4991
4992       InstructionList.push_back(I);
4993       break;
4994     }
4995     case bitc::FUNC_CODE_INST_ATOMICRMW: {
4996       // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4997       unsigned OpNum = 0;
4998       Value *Ptr, *Val;
4999       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
5000           popValue(Record, OpNum, NextValueNo,
5001                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5002           OpNum+4 != Record.size())
5003         return error("Invalid record");
5004       AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
5005       if (Operation < AtomicRMWInst::FIRST_BINOP ||
5006           Operation > AtomicRMWInst::LAST_BINOP)
5007         return error("Invalid record");
5008       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
5009       if (Ordering == NotAtomic || Ordering == Unordered)
5010         return error("Invalid record");
5011       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
5012       I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5013       cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5014       InstructionList.push_back(I);
5015       break;
5016     }
5017     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5018       if (2 != Record.size())
5019         return error("Invalid record");
5020       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
5021       if (Ordering == NotAtomic || Ordering == Unordered ||
5022           Ordering == Monotonic)
5023         return error("Invalid record");
5024       SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
5025       I = new FenceInst(Context, Ordering, SynchScope);
5026       InstructionList.push_back(I);
5027       break;
5028     }
5029     case bitc::FUNC_CODE_INST_CALL: {
5030       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
5031       if (Record.size() < 3)
5032         return error("Invalid record");
5033
5034       unsigned OpNum = 0;
5035       AttributeSet PAL = getAttributes(Record[OpNum++]);
5036       unsigned CCInfo = Record[OpNum++];
5037
5038       FastMathFlags FMF;
5039       if ((CCInfo >> bitc::CALL_FMF) & 1) {
5040         FMF = getDecodedFastMathFlags(Record[OpNum++]);
5041         if (!FMF.any())
5042           return error("Fast math flags indicator set for call with no FMF");
5043       }
5044
5045       FunctionType *FTy = nullptr;
5046       if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
5047           !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
5048         return error("Explicit call type is not a function type");
5049
5050       Value *Callee;
5051       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
5052         return error("Invalid record");
5053
5054       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5055       if (!OpTy)
5056         return error("Callee is not a pointer type");
5057       if (!FTy) {
5058         FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5059         if (!FTy)
5060           return error("Callee is not of pointer to function type");
5061       } else if (OpTy->getElementType() != FTy)
5062         return error("Explicit call type does not match pointee type of "
5063                      "callee operand");
5064       if (Record.size() < FTy->getNumParams() + OpNum)
5065         return error("Insufficient operands to call");
5066
5067       SmallVector<Value*, 16> Args;
5068       // Read the fixed params.
5069       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5070         if (FTy->getParamType(i)->isLabelTy())
5071           Args.push_back(getBasicBlock(Record[OpNum]));
5072         else
5073           Args.push_back(getValue(Record, OpNum, NextValueNo,
5074                                   FTy->getParamType(i)));
5075         if (!Args.back())
5076           return error("Invalid record");
5077       }
5078
5079       // Read type/value pairs for varargs params.
5080       if (!FTy->isVarArg()) {
5081         if (OpNum != Record.size())
5082           return error("Invalid record");
5083       } else {
5084         while (OpNum != Record.size()) {
5085           Value *Op;
5086           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5087             return error("Invalid record");
5088           Args.push_back(Op);
5089         }
5090       }
5091
5092       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5093       OperandBundles.clear();
5094       InstructionList.push_back(I);
5095       cast<CallInst>(I)->setCallingConv(
5096           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5097       CallInst::TailCallKind TCK = CallInst::TCK_None;
5098       if (CCInfo & 1 << bitc::CALL_TAIL)
5099         TCK = CallInst::TCK_Tail;
5100       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
5101         TCK = CallInst::TCK_MustTail;
5102       if (CCInfo & (1 << bitc::CALL_NOTAIL))
5103         TCK = CallInst::TCK_NoTail;
5104       cast<CallInst>(I)->setTailCallKind(TCK);
5105       cast<CallInst>(I)->setAttributes(PAL);
5106       if (FMF.any()) {
5107         if (!isa<FPMathOperator>(I))
5108           return error("Fast-math-flags specified for call without "
5109                        "floating-point scalar or vector return type");
5110         I->setFastMathFlags(FMF);
5111       }
5112       break;
5113     }
5114     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5115       if (Record.size() < 3)
5116         return error("Invalid record");
5117       Type *OpTy = getTypeByID(Record[0]);
5118       Value *Op = getValue(Record, 1, NextValueNo, OpTy);
5119       Type *ResTy = getTypeByID(Record[2]);
5120       if (!OpTy || !Op || !ResTy)
5121         return error("Invalid record");
5122       I = new VAArgInst(Op, ResTy);
5123       InstructionList.push_back(I);
5124       break;
5125     }
5126
5127     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5128       // A call or an invoke can be optionally prefixed with some variable
5129       // number of operand bundle blocks.  These blocks are read into
5130       // OperandBundles and consumed at the next call or invoke instruction.
5131
5132       if (Record.size() < 1 || Record[0] >= BundleTags.size())
5133         return error("Invalid record");
5134
5135       std::vector<Value *> Inputs;
5136
5137       unsigned OpNum = 1;
5138       while (OpNum != Record.size()) {
5139         Value *Op;
5140         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5141           return error("Invalid record");
5142         Inputs.push_back(Op);
5143       }
5144
5145       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
5146       continue;
5147     }
5148     }
5149
5150     // Add instruction to end of current BB.  If there is no current BB, reject
5151     // this file.
5152     if (!CurBB) {
5153       delete I;
5154       return error("Invalid instruction with no BB");
5155     }
5156     if (!OperandBundles.empty()) {
5157       delete I;
5158       return error("Operand bundles found with no consumer");
5159     }
5160     CurBB->getInstList().push_back(I);
5161
5162     // If this was a terminator instruction, move to the next block.
5163     if (isa<TerminatorInst>(I)) {
5164       ++CurBBNo;
5165       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
5166     }
5167
5168     // Non-void values get registered in the value table for future use.
5169     if (I && !I->getType()->isVoidTy())
5170       ValueList.assignValue(I, NextValueNo++);
5171   }
5172
5173 OutOfRecordLoop:
5174
5175   if (!OperandBundles.empty())
5176     return error("Operand bundles found with no consumer");
5177
5178   // Check the function list for unresolved values.
5179   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
5180     if (!A->getParent()) {
5181       // We found at least one unresolved value.  Nuke them all to avoid leaks.
5182       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
5183         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
5184           A->replaceAllUsesWith(UndefValue::get(A->getType()));
5185           delete A;
5186         }
5187       }
5188       return error("Never resolved value found in function");
5189     }
5190   }
5191
5192   // FIXME: Check for unresolved forward-declared metadata references
5193   // and clean up leaks.
5194
5195   // Trim the value list down to the size it was before we parsed this function.
5196   ValueList.shrinkTo(ModuleValueListSize);
5197   MetadataList.shrinkTo(ModuleMetadataListSize);
5198   std::vector<BasicBlock*>().swap(FunctionBBs);
5199   return std::error_code();
5200 }
5201
5202 /// Find the function body in the bitcode stream
5203 std::error_code BitcodeReader::findFunctionInStream(
5204     Function *F,
5205     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
5206   while (DeferredFunctionInfoIterator->second == 0) {
5207     // This is the fallback handling for the old format bitcode that
5208     // didn't contain the function index in the VST, or when we have
5209     // an anonymous function which would not have a VST entry.
5210     // Assert that we have one of those two cases.
5211     assert(VSTOffset == 0 || !F->hasName());
5212     // Parse the next body in the stream and set its position in the
5213     // DeferredFunctionInfo map.
5214     if (std::error_code EC = rememberAndSkipFunctionBodies())
5215       return EC;
5216   }
5217   return std::error_code();
5218 }
5219
5220 //===----------------------------------------------------------------------===//
5221 // GVMaterializer implementation
5222 //===----------------------------------------------------------------------===//
5223
5224 void BitcodeReader::releaseBuffer() { Buffer.release(); }
5225
5226 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
5227   // In older bitcode we must materialize the metadata before parsing
5228   // any functions, in order to set up the MetadataList properly.
5229   if (!SeenModuleValuesRecord) {
5230     if (std::error_code EC = materializeMetadata())
5231       return EC;
5232   }
5233
5234   Function *F = dyn_cast<Function>(GV);
5235   // If it's not a function or is already material, ignore the request.
5236   if (!F || !F->isMaterializable())
5237     return std::error_code();
5238
5239   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
5240   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
5241   // If its position is recorded as 0, its body is somewhere in the stream
5242   // but we haven't seen it yet.
5243   if (DFII->second == 0)
5244     if (std::error_code EC = findFunctionInStream(F, DFII))
5245       return EC;
5246
5247   // Move the bit stream to the saved position of the deferred function body.
5248   Stream.JumpToBit(DFII->second);
5249
5250   if (std::error_code EC = parseFunctionBody(F))
5251     return EC;
5252   F->setIsMaterializable(false);
5253
5254   if (StripDebugInfo)
5255     stripDebugInfo(*F);
5256
5257   // Upgrade any old intrinsic calls in the function.
5258   for (auto &I : UpgradedIntrinsics) {
5259     for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5260          UI != UE;) {
5261       User *U = *UI;
5262       ++UI;
5263       if (CallInst *CI = dyn_cast<CallInst>(U))
5264         UpgradeIntrinsicCall(CI, I.second);
5265     }
5266   }
5267
5268   // Finish fn->subprogram upgrade for materialized functions.
5269   if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5270     F->setSubprogram(SP);
5271
5272   // Bring in any functions that this function forward-referenced via
5273   // blockaddresses.
5274   return materializeForwardReferencedFunctions();
5275 }
5276
5277 std::error_code BitcodeReader::materializeModule() {
5278   if (std::error_code EC = materializeMetadata())
5279     return EC;
5280
5281   // Promise to materialize all forward references.
5282   WillMaterializeAllForwardRefs = true;
5283
5284   // Iterate over the module, deserializing any functions that are still on
5285   // disk.
5286   for (Function &F : *TheModule) {
5287     if (std::error_code EC = materialize(&F))
5288       return EC;
5289   }
5290   // At this point, if there are any function bodies, parse the rest of
5291   // the bits in the module past the last function block we have recorded
5292   // through either lazy scanning or the VST.
5293   if (LastFunctionBlockBit || NextUnreadBit)
5294     parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5295                                                      : NextUnreadBit);
5296
5297   // Check that all block address forward references got resolved (as we
5298   // promised above).
5299   if (!BasicBlockFwdRefs.empty())
5300     return error("Never resolved function from blockaddress");
5301
5302   // Upgrade any intrinsic calls that slipped through (should not happen!) and
5303   // delete the old functions to clean up. We can't do this unless the entire
5304   // module is materialized because there could always be another function body
5305   // with calls to the old function.
5306   for (auto &I : UpgradedIntrinsics) {
5307     for (auto *U : I.first->users()) {
5308       if (CallInst *CI = dyn_cast<CallInst>(U))
5309         UpgradeIntrinsicCall(CI, I.second);
5310     }
5311     if (!I.first->use_empty())
5312       I.first->replaceAllUsesWith(I.second);
5313     I.first->eraseFromParent();
5314   }
5315   UpgradedIntrinsics.clear();
5316
5317   for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5318     UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5319
5320   UpgradeDebugInfo(*TheModule);
5321   return std::error_code();
5322 }
5323
5324 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5325   return IdentifiedStructTypes;
5326 }
5327
5328 std::error_code
5329 BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5330   if (Streamer)
5331     return initLazyStream(std::move(Streamer));
5332   return initStreamFromBuffer();
5333 }
5334
5335 std::error_code BitcodeReader::initStreamFromBuffer() {
5336   const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
5337   const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5338
5339   if (Buffer->getBufferSize() & 3)
5340     return error("Invalid bitcode signature");
5341
5342   // If we have a wrapper header, parse it and ignore the non-bc file contents.
5343   // The magic number is 0x0B17C0DE stored in little endian.
5344   if (isBitcodeWrapper(BufPtr, BufEnd))
5345     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5346       return error("Invalid bitcode wrapper header");
5347
5348   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5349   Stream.init(&*StreamFile);
5350
5351   return std::error_code();
5352 }
5353
5354 std::error_code
5355 BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
5356   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5357   // see it.
5358   auto OwnedBytes =
5359       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5360   StreamingMemoryObject &Bytes = *OwnedBytes;
5361   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5362   Stream.init(&*StreamFile);
5363
5364   unsigned char buf[16];
5365   if (Bytes.readBytes(buf, 16, 0) != 16)
5366     return error("Invalid bitcode signature");
5367
5368   if (!isBitcode(buf, buf + 16))
5369     return error("Invalid bitcode signature");
5370
5371   if (isBitcodeWrapper(buf, buf + 4)) {
5372     const unsigned char *bitcodeStart = buf;
5373     const unsigned char *bitcodeEnd = buf + 16;
5374     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5375     Bytes.dropLeadingBytes(bitcodeStart - buf);
5376     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5377   }
5378   return std::error_code();
5379 }
5380
5381 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E,
5382                                                   const Twine &Message) {
5383   return ::error(DiagnosticHandler, make_error_code(E), Message);
5384 }
5385
5386 std::error_code FunctionIndexBitcodeReader::error(const Twine &Message) {
5387   return ::error(DiagnosticHandler,
5388                  make_error_code(BitcodeError::CorruptedBitcode), Message);
5389 }
5390
5391 std::error_code FunctionIndexBitcodeReader::error(BitcodeError E) {
5392   return ::error(DiagnosticHandler, make_error_code(E));
5393 }
5394
5395 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5396     MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5397     bool IsLazy, bool CheckFuncSummaryPresenceOnly)
5398     : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
5399       CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5400
5401 FunctionIndexBitcodeReader::FunctionIndexBitcodeReader(
5402     DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
5403     bool CheckFuncSummaryPresenceOnly)
5404     : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
5405       CheckFuncSummaryPresenceOnly(CheckFuncSummaryPresenceOnly) {}
5406
5407 void FunctionIndexBitcodeReader::freeState() { Buffer = nullptr; }
5408
5409 void FunctionIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
5410
5411 // Specialized value symbol table parser used when reading function index
5412 // blocks where we don't actually create global values.
5413 // At the end of this routine the function index is populated with a map
5414 // from function name to FunctionInfo. The function info contains
5415 // the function block's bitcode offset as well as the offset into the
5416 // function summary section.
5417 std::error_code FunctionIndexBitcodeReader::parseValueSymbolTable() {
5418   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5419     return error("Invalid record");
5420
5421   SmallVector<uint64_t, 64> Record;
5422
5423   // Read all the records for this value table.
5424   SmallString<128> ValueName;
5425   while (1) {
5426     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5427
5428     switch (Entry.Kind) {
5429     case BitstreamEntry::SubBlock: // Handled for us already.
5430     case BitstreamEntry::Error:
5431       return error("Malformed block");
5432     case BitstreamEntry::EndBlock:
5433       return std::error_code();
5434     case BitstreamEntry::Record:
5435       // The interesting case.
5436       break;
5437     }
5438
5439     // Read a record.
5440     Record.clear();
5441     switch (Stream.readRecord(Entry.ID, Record)) {
5442     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5443       break;
5444     case bitc::VST_CODE_FNENTRY: {
5445       // VST_FNENTRY: [valueid, offset, namechar x N]
5446       if (convertToString(Record, 2, ValueName))
5447         return error("Invalid record");
5448       unsigned ValueID = Record[0];
5449       uint64_t FuncOffset = Record[1];
5450       std::unique_ptr<FunctionInfo> FuncInfo =
5451           llvm::make_unique<FunctionInfo>(FuncOffset);
5452       if (foundFuncSummary() && !IsLazy) {
5453         DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5454             SummaryMap.find(ValueID);
5455         assert(SMI != SummaryMap.end() && "Summary info not found");
5456         FuncInfo->setFunctionSummary(std::move(SMI->second));
5457       }
5458       TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5459
5460       ValueName.clear();
5461       break;
5462     }
5463     case bitc::VST_CODE_COMBINED_FNENTRY: {
5464       // VST_FNENTRY: [offset, namechar x N]
5465       if (convertToString(Record, 1, ValueName))
5466         return error("Invalid record");
5467       uint64_t FuncSummaryOffset = Record[0];
5468       std::unique_ptr<FunctionInfo> FuncInfo =
5469           llvm::make_unique<FunctionInfo>(FuncSummaryOffset);
5470       if (foundFuncSummary() && !IsLazy) {
5471         DenseMap<uint64_t, std::unique_ptr<FunctionSummary>>::iterator SMI =
5472             SummaryMap.find(FuncSummaryOffset);
5473         assert(SMI != SummaryMap.end() && "Summary info not found");
5474         FuncInfo->setFunctionSummary(std::move(SMI->second));
5475       }
5476       TheIndex->addFunctionInfo(ValueName, std::move(FuncInfo));
5477
5478       ValueName.clear();
5479       break;
5480     }
5481     }
5482   }
5483 }
5484
5485 // Parse just the blocks needed for function index building out of the module.
5486 // At the end of this routine the function Index is populated with a map
5487 // from function name to FunctionInfo. The function info contains
5488 // either the parsed function summary information (when parsing summaries
5489 // eagerly), or just to the function summary record's offset
5490 // if parsing lazily (IsLazy).
5491 std::error_code FunctionIndexBitcodeReader::parseModule() {
5492   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5493     return error("Invalid record");
5494
5495   // Read the function index for this module.
5496   while (1) {
5497     BitstreamEntry Entry = Stream.advance();
5498
5499     switch (Entry.Kind) {
5500     case BitstreamEntry::Error:
5501       return error("Malformed block");
5502     case BitstreamEntry::EndBlock:
5503       return std::error_code();
5504
5505     case BitstreamEntry::SubBlock:
5506       if (CheckFuncSummaryPresenceOnly) {
5507         if (Entry.ID == bitc::FUNCTION_SUMMARY_BLOCK_ID) {
5508           SeenFuncSummary = true;
5509           // No need to parse the rest since we found the summary.
5510           return std::error_code();
5511         }
5512         if (Stream.SkipBlock())
5513           return error("Invalid record");
5514         continue;
5515       }
5516       switch (Entry.ID) {
5517       default: // Skip unknown content.
5518         if (Stream.SkipBlock())
5519           return error("Invalid record");
5520         break;
5521       case bitc::BLOCKINFO_BLOCK_ID:
5522         // Need to parse these to get abbrev ids (e.g. for VST)
5523         if (Stream.ReadBlockInfoBlock())
5524           return error("Malformed block");
5525         break;
5526       case bitc::VALUE_SYMTAB_BLOCK_ID:
5527         if (std::error_code EC = parseValueSymbolTable())
5528           return EC;
5529         break;
5530       case bitc::FUNCTION_SUMMARY_BLOCK_ID:
5531         SeenFuncSummary = true;
5532         if (IsLazy) {
5533           // Lazy parsing of summary info, skip it.
5534           if (Stream.SkipBlock())
5535             return error("Invalid record");
5536         } else if (std::error_code EC = parseEntireSummary())
5537           return EC;
5538         break;
5539       case bitc::MODULE_STRTAB_BLOCK_ID:
5540         if (std::error_code EC = parseModuleStringTable())
5541           return EC;
5542         break;
5543       }
5544       continue;
5545
5546     case BitstreamEntry::Record:
5547       Stream.skipRecord(Entry.ID);
5548       continue;
5549     }
5550   }
5551 }
5552
5553 // Eagerly parse the entire function summary block (i.e. for all functions
5554 // in the index). This populates the FunctionSummary objects in
5555 // the index.
5556 std::error_code FunctionIndexBitcodeReader::parseEntireSummary() {
5557   if (Stream.EnterSubBlock(bitc::FUNCTION_SUMMARY_BLOCK_ID))
5558     return error("Invalid record");
5559
5560   SmallVector<uint64_t, 64> Record;
5561
5562   while (1) {
5563     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5564
5565     switch (Entry.Kind) {
5566     case BitstreamEntry::SubBlock: // Handled for us already.
5567     case BitstreamEntry::Error:
5568       return error("Malformed block");
5569     case BitstreamEntry::EndBlock:
5570       return std::error_code();
5571     case BitstreamEntry::Record:
5572       // The interesting case.
5573       break;
5574     }
5575
5576     // Read a record. The record format depends on whether this
5577     // is a per-module index or a combined index file. In the per-module
5578     // case the records contain the associated value's ID for correlation
5579     // with VST entries. In the combined index the correlation is done
5580     // via the bitcode offset of the summary records (which were saved
5581     // in the combined index VST entries). The records also contain
5582     // information used for ThinLTO renaming and importing.
5583     Record.clear();
5584     uint64_t CurRecordBit = Stream.GetCurrentBitNo();
5585     switch (Stream.readRecord(Entry.ID, Record)) {
5586     default: // Default behavior: ignore.
5587       break;
5588     // FS_PERMODULE_ENTRY: [valueid, islocal, instcount]
5589     case bitc::FS_CODE_PERMODULE_ENTRY: {
5590       unsigned ValueID = Record[0];
5591       bool IsLocal = Record[1];
5592       unsigned InstCount = Record[2];
5593       std::unique_ptr<FunctionSummary> FS =
5594           llvm::make_unique<FunctionSummary>(InstCount);
5595       FS->setLocalFunction(IsLocal);
5596       // The module path string ref set in the summary must be owned by the
5597       // index's module string table. Since we don't have a module path
5598       // string table section in the per-module index, we create a single
5599       // module path string table entry with an empty (0) ID to take
5600       // ownership.
5601       FS->setModulePath(
5602           TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0));
5603       SummaryMap[ValueID] = std::move(FS);
5604     }
5605     // FS_COMBINED_ENTRY: [modid, instcount]
5606     case bitc::FS_CODE_COMBINED_ENTRY: {
5607       uint64_t ModuleId = Record[0];
5608       unsigned InstCount = Record[1];
5609       std::unique_ptr<FunctionSummary> FS =
5610           llvm::make_unique<FunctionSummary>(InstCount);
5611       FS->setModulePath(ModuleIdMap[ModuleId]);
5612       SummaryMap[CurRecordBit] = std::move(FS);
5613     }
5614     }
5615   }
5616   llvm_unreachable("Exit infinite loop");
5617 }
5618
5619 // Parse the  module string table block into the Index.
5620 // This populates the ModulePathStringTable map in the index.
5621 std::error_code FunctionIndexBitcodeReader::parseModuleStringTable() {
5622   if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5623     return error("Invalid record");
5624
5625   SmallVector<uint64_t, 64> Record;
5626
5627   SmallString<128> ModulePath;
5628   while (1) {
5629     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5630
5631     switch (Entry.Kind) {
5632     case BitstreamEntry::SubBlock: // Handled for us already.
5633     case BitstreamEntry::Error:
5634       return error("Malformed block");
5635     case BitstreamEntry::EndBlock:
5636       return std::error_code();
5637     case BitstreamEntry::Record:
5638       // The interesting case.
5639       break;
5640     }
5641
5642     Record.clear();
5643     switch (Stream.readRecord(Entry.ID, Record)) {
5644     default: // Default behavior: ignore.
5645       break;
5646     case bitc::MST_CODE_ENTRY: {
5647       // MST_ENTRY: [modid, namechar x N]
5648       if (convertToString(Record, 1, ModulePath))
5649         return error("Invalid record");
5650       uint64_t ModuleId = Record[0];
5651       StringRef ModulePathInMap = TheIndex->addModulePath(ModulePath, ModuleId);
5652       ModuleIdMap[ModuleId] = ModulePathInMap;
5653       ModulePath.clear();
5654       break;
5655     }
5656     }
5657   }
5658   llvm_unreachable("Exit infinite loop");
5659 }
5660
5661 // Parse the function info index from the bitcode streamer into the given index.
5662 std::error_code FunctionIndexBitcodeReader::parseSummaryIndexInto(
5663     std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I) {
5664   TheIndex = I;
5665
5666   if (std::error_code EC = initStream(std::move(Streamer)))
5667     return EC;
5668
5669   // Sniff for the signature.
5670   if (!hasValidBitcodeHeader(Stream))
5671     return error("Invalid bitcode signature");
5672
5673   // We expect a number of well-defined blocks, though we don't necessarily
5674   // need to understand them all.
5675   while (1) {
5676     if (Stream.AtEndOfStream()) {
5677       // We didn't really read a proper Module block.
5678       return error("Malformed block");
5679     }
5680
5681     BitstreamEntry Entry =
5682         Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5683
5684     if (Entry.Kind != BitstreamEntry::SubBlock)
5685       return error("Malformed block");
5686
5687     // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5688     // building the function summary index.
5689     if (Entry.ID == bitc::MODULE_BLOCK_ID)
5690       return parseModule();
5691
5692     if (Stream.SkipBlock())
5693       return error("Invalid record");
5694   }
5695 }
5696
5697 // Parse the function information at the given offset in the buffer into
5698 // the index. Used to support lazy parsing of function summaries from the
5699 // combined index during importing.
5700 // TODO: This function is not yet complete as it won't have a consumer
5701 // until ThinLTO function importing is added.
5702 std::error_code FunctionIndexBitcodeReader::parseFunctionSummary(
5703     std::unique_ptr<DataStreamer> Streamer, FunctionInfoIndex *I,
5704     size_t FunctionSummaryOffset) {
5705   TheIndex = I;
5706
5707   if (std::error_code EC = initStream(std::move(Streamer)))
5708     return EC;
5709
5710   // Sniff for the signature.
5711   if (!hasValidBitcodeHeader(Stream))
5712     return error("Invalid bitcode signature");
5713
5714   Stream.JumpToBit(FunctionSummaryOffset);
5715
5716   BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5717
5718   switch (Entry.Kind) {
5719   default:
5720     return error("Malformed block");
5721   case BitstreamEntry::Record:
5722     // The expected case.
5723     break;
5724   }
5725
5726   // TODO: Read a record. This interface will be completed when ThinLTO
5727   // importing is added so that it can be tested.
5728   SmallVector<uint64_t, 64> Record;
5729   switch (Stream.readRecord(Entry.ID, Record)) {
5730   case bitc::FS_CODE_COMBINED_ENTRY:
5731   default:
5732     return error("Invalid record");
5733   }
5734
5735   return std::error_code();
5736 }
5737
5738 std::error_code
5739 FunctionIndexBitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
5740   if (Streamer)
5741     return initLazyStream(std::move(Streamer));
5742   return initStreamFromBuffer();
5743 }
5744
5745 std::error_code FunctionIndexBitcodeReader::initStreamFromBuffer() {
5746   const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
5747   const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
5748
5749   if (Buffer->getBufferSize() & 3)
5750     return error("Invalid bitcode signature");
5751
5752   // If we have a wrapper header, parse it and ignore the non-bc file contents.
5753   // The magic number is 0x0B17C0DE stored in little endian.
5754   if (isBitcodeWrapper(BufPtr, BufEnd))
5755     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
5756       return error("Invalid bitcode wrapper header");
5757
5758   StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
5759   Stream.init(&*StreamFile);
5760
5761   return std::error_code();
5762 }
5763
5764 std::error_code FunctionIndexBitcodeReader::initLazyStream(
5765     std::unique_ptr<DataStreamer> Streamer) {
5766   // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5767   // see it.
5768   auto OwnedBytes =
5769       llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
5770   StreamingMemoryObject &Bytes = *OwnedBytes;
5771   StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
5772   Stream.init(&*StreamFile);
5773
5774   unsigned char buf[16];
5775   if (Bytes.readBytes(buf, 16, 0) != 16)
5776     return error("Invalid bitcode signature");
5777
5778   if (!isBitcode(buf, buf + 16))
5779     return error("Invalid bitcode signature");
5780
5781   if (isBitcodeWrapper(buf, buf + 4)) {
5782     const unsigned char *bitcodeStart = buf;
5783     const unsigned char *bitcodeEnd = buf + 16;
5784     SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
5785     Bytes.dropLeadingBytes(bitcodeStart - buf);
5786     Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
5787   }
5788   return std::error_code();
5789 }
5790
5791 namespace {
5792 class BitcodeErrorCategoryType : public std::error_category {
5793   const char *name() const LLVM_NOEXCEPT override {
5794     return "llvm.bitcode";
5795   }
5796   std::string message(int IE) const override {
5797     BitcodeError E = static_cast<BitcodeError>(IE);
5798     switch (E) {
5799     case BitcodeError::InvalidBitcodeSignature:
5800       return "Invalid bitcode signature";
5801     case BitcodeError::CorruptedBitcode:
5802       return "Corrupted bitcode";
5803     }
5804     llvm_unreachable("Unknown error type!");
5805   }
5806 };
5807 }
5808
5809 static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
5810
5811 const std::error_category &llvm::BitcodeErrorCategory() {
5812   return *ErrorCategory;
5813 }
5814
5815 //===----------------------------------------------------------------------===//
5816 // External interface
5817 //===----------------------------------------------------------------------===//
5818
5819 static ErrorOr<std::unique_ptr<Module>>
5820 getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
5821                      BitcodeReader *R, LLVMContext &Context,
5822                      bool MaterializeAll, bool ShouldLazyLoadMetadata) {
5823   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5824   M->setMaterializer(R);
5825
5826   auto cleanupOnError = [&](std::error_code EC) {
5827     R->releaseBuffer(); // Never take ownership on error.
5828     return EC;
5829   };
5830
5831   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5832   if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
5833                                                ShouldLazyLoadMetadata))
5834     return cleanupOnError(EC);
5835
5836   if (MaterializeAll) {
5837     // Read in the entire module, and destroy the BitcodeReader.
5838     if (std::error_code EC = M->materializeAll())
5839       return cleanupOnError(EC);
5840   } else {
5841     // Resolve forward references from blockaddresses.
5842     if (std::error_code EC = R->materializeForwardReferencedFunctions())
5843       return cleanupOnError(EC);
5844   }
5845   return std::move(M);
5846 }
5847
5848 /// \brief Get a lazy one-at-time loading module from bitcode.
5849 ///
5850 /// This isn't always used in a lazy context.  In particular, it's also used by
5851 /// \a parseBitcodeFile().  If this is truly lazy, then we need to eagerly pull
5852 /// in forward-referenced functions from block address references.
5853 ///
5854 /// \param[in] MaterializeAll Set to \c true if we should materialize
5855 /// everything.
5856 static ErrorOr<std::unique_ptr<Module>>
5857 getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
5858                          LLVMContext &Context, bool MaterializeAll,
5859                          bool ShouldLazyLoadMetadata = false) {
5860   BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
5861
5862   ErrorOr<std::unique_ptr<Module>> Ret =
5863       getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
5864                            MaterializeAll, ShouldLazyLoadMetadata);
5865   if (!Ret)
5866     return Ret;
5867
5868   Buffer.release(); // The BitcodeReader owns it now.
5869   return Ret;
5870 }
5871
5872 ErrorOr<std::unique_ptr<Module>>
5873 llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
5874                            LLVMContext &Context, bool ShouldLazyLoadMetadata) {
5875   return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
5876                                   ShouldLazyLoadMetadata);
5877 }
5878
5879 ErrorOr<std::unique_ptr<Module>>
5880 llvm::getStreamedBitcodeModule(StringRef Name,
5881                                std::unique_ptr<DataStreamer> Streamer,
5882                                LLVMContext &Context) {
5883   std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
5884   BitcodeReader *R = new BitcodeReader(Context);
5885
5886   return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
5887                               false);
5888 }
5889
5890 ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
5891                                                         LLVMContext &Context) {
5892   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5893   return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
5894   // TODO: Restore the use-lists to the in-memory state when the bitcode was
5895   // written.  We must defer until the Module has been fully materialized.
5896 }
5897
5898 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
5899                                          LLVMContext &Context) {
5900   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5901   auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
5902   ErrorOr<std::string> Triple = R->parseTriple();
5903   if (Triple.getError())
5904     return "";
5905   return Triple.get();
5906 }
5907
5908 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
5909                                            LLVMContext &Context) {
5910   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5911   BitcodeReader R(Buf.release(), Context);
5912   ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
5913   if (ProducerString.getError())
5914     return "";
5915   return ProducerString.get();
5916 }
5917
5918 // Parse the specified bitcode buffer, returning the function info index.
5919 // If IsLazy is false, parse the entire function summary into
5920 // the index. Otherwise skip the function summary section, and only create
5921 // an index object with a map from function name to function summary offset.
5922 // The index is used to perform lazy function summary reading later.
5923 ErrorOr<std::unique_ptr<FunctionInfoIndex>>
5924 llvm::getFunctionInfoIndex(MemoryBufferRef Buffer,
5925                            DiagnosticHandlerFunction DiagnosticHandler,
5926                            bool IsLazy) {
5927   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5928   FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
5929
5930   auto Index = llvm::make_unique<FunctionInfoIndex>();
5931
5932   auto cleanupOnError = [&](std::error_code EC) {
5933     R.releaseBuffer(); // Never take ownership on error.
5934     return EC;
5935   };
5936
5937   if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
5938     return cleanupOnError(EC);
5939
5940   Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5941   return std::move(Index);
5942 }
5943
5944 // Check if the given bitcode buffer contains a function summary block.
5945 bool llvm::hasFunctionSummary(MemoryBufferRef Buffer,
5946                               DiagnosticHandlerFunction DiagnosticHandler) {
5947   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5948   FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
5949
5950   auto cleanupOnError = [&](std::error_code EC) {
5951     R.releaseBuffer(); // Never take ownership on error.
5952     return false;
5953   };
5954
5955   if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
5956     return cleanupOnError(EC);
5957
5958   Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5959   return R.foundFuncSummary();
5960 }
5961
5962 // This method supports lazy reading of function summary data from the combined
5963 // index during ThinLTO function importing. When reading the combined index
5964 // file, getFunctionInfoIndex is first invoked with IsLazy=true.
5965 // Then this method is called for each function considered for importing,
5966 // to parse the summary information for the given function name into
5967 // the index.
5968 std::error_code llvm::readFunctionSummary(
5969     MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
5970     StringRef FunctionName, std::unique_ptr<FunctionInfoIndex> Index) {
5971   std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
5972   FunctionIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
5973
5974   auto cleanupOnError = [&](std::error_code EC) {
5975     R.releaseBuffer(); // Never take ownership on error.
5976     return EC;
5977   };
5978
5979   // Lookup the given function name in the FunctionMap, which may
5980   // contain a list of function infos in the case of a COMDAT. Walk through
5981   // and parse each function summary info at the function summary offset
5982   // recorded when parsing the value symbol table.
5983   for (const auto &FI : Index->getFunctionInfoList(FunctionName)) {
5984     size_t FunctionSummaryOffset = FI->bitcodeIndex();
5985     if (std::error_code EC =
5986             R.parseFunctionSummary(nullptr, Index.get(), FunctionSummaryOffset))
5987       return cleanupOnError(EC);
5988   }
5989
5990   Buf.release(); // The FunctionIndexBitcodeReader owns it now.
5991   return std::error_code();
5992 }