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