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