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