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