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