LLVM  16.0.0git
BitcodeReader.cpp
Go to the documentation of this file.
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
10 #include "MetadataLoader.h"
11 #include "ValueList.h"
12 #include "llvm/ADT/APFloat.h"
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/Twine.h"
26 #include "llvm/Config/llvm-config.h"
27 #include "llvm/IR/Argument.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/AutoUpgrade.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Comdat.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DebugInfo.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GVMaterializer.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalIFunc.h"
45 #include "llvm/IR/GlobalObject.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/InlineAsm.h"
49 #include "llvm/IR/InstIterator.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instruction.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/IntrinsicsAArch64.h"
55 #include "llvm/IR/IntrinsicsARM.h"
56 #include "llvm/IR/LLVMContext.h"
57 #include "llvm/IR/Metadata.h"
58 #include "llvm/IR/Module.h"
60 #include "llvm/IR/Operator.h"
61 #include "llvm/IR/Type.h"
62 #include "llvm/IR/Value.h"
63 #include "llvm/IR/Verifier.h"
65 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/Compiler.h"
68 #include "llvm/Support/Debug.h"
69 #include "llvm/Support/Error.h"
71 #include "llvm/Support/ErrorOr.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstddef>
78 #include <cstdint>
79 #include <deque>
80 #include <map>
81 #include <memory>
82 #include <set>
83 #include <string>
84 #include <system_error>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
88 
89 using namespace llvm;
90 
92  "print-summary-global-ids", cl::init(false), cl::Hidden,
93  cl::desc(
94  "Print the global id for each value when reading the module summary"));
95 
97  "expand-constant-exprs", cl::Hidden,
98  cl::desc(
99  "Expand constant expressions to instructions for testing purposes"));
100 
101 namespace {
102 
103 enum {
104  SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
105 };
106 
107 } // end anonymous namespace
108 
109 static Error error(const Twine &Message) {
110  return make_error<StringError>(
112 }
113 
115  if (!Stream.canSkipToPos(4))
116  return createStringError(std::errc::illegal_byte_sequence,
117  "file too small to contain bitcode header");
118  for (unsigned C : {'B', 'C'})
119  if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
120  if (Res.get() != C)
121  return createStringError(std::errc::illegal_byte_sequence,
122  "file doesn't start with bitcode header");
123  } else
124  return Res.takeError();
125  for (unsigned C : {0x0, 0xC, 0xE, 0xD})
126  if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
127  if (Res.get() != C)
128  return createStringError(std::errc::illegal_byte_sequence,
129  "file doesn't start with bitcode header");
130  } else
131  return Res.takeError();
132  return Error::success();
133 }
134 
136  const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
137  const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
138 
139  if (Buffer.getBufferSize() & 3)
140  return error("Invalid bitcode signature");
141 
142  // If we have a wrapper header, parse it and ignore the non-bc file contents.
143  // The magic number is 0x0B17C0DE stored in little endian.
144  if (isBitcodeWrapper(BufPtr, BufEnd))
145  if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
146  return error("Invalid bitcode wrapper header");
147 
148  BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
149  if (Error Err = hasInvalidBitcodeHeader(Stream))
150  return std::move(Err);
151 
152  return std::move(Stream);
153 }
154 
155 /// Convert a string from a record into an std::string, return true on failure.
156 template <typename StrTy>
157 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
158  StrTy &Result) {
159  if (Idx > Record.size())
160  return true;
161 
162  Result.append(Record.begin() + Idx, Record.end());
163  return false;
164 }
165 
166 // Strip all the TBAA attachment for the module.
167 static void stripTBAA(Module *M) {
168  for (auto &F : *M) {
169  if (F.isMaterializable())
170  continue;
171  for (auto &I : instructions(F))
172  I.setMetadata(LLVMContext::MD_tbaa, nullptr);
173  }
174 }
175 
176 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
177 /// "epoch" encoded in the bitcode, and return the producer name if any.
180  return std::move(Err);
181 
182  // Read all the records.
184 
185  std::string ProducerIdentification;
186 
187  while (true) {
188  BitstreamEntry Entry;
189  if (Error E = Stream.advance().moveInto(Entry))
190  return std::move(E);
191 
192  switch (Entry.Kind) {
193  default:
195  return error("Malformed block");
197  return ProducerIdentification;
199  // The interesting case.
200  break;
201  }
202 
203  // Read a record.
204  Record.clear();
205  Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
206  if (!MaybeBitCode)
207  return MaybeBitCode.takeError();
208  switch (MaybeBitCode.get()) {
209  default: // Default behavior: reject
210  return error("Invalid value");
211  case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
212  convertToString(Record, 0, ProducerIdentification);
213  break;
214  case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
215  unsigned epoch = (unsigned)Record[0];
216  if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
217  return error(
218  Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
219  "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
220  }
221  }
222  }
223  }
224 }
225 
227  // We expect a number of well-defined blocks, though we don't necessarily
228  // need to understand them all.
229  while (true) {
230  if (Stream.AtEndOfStream())
231  return "";
232 
233  BitstreamEntry Entry;
234  if (Error E = Stream.advance().moveInto(Entry))
235  return std::move(E);
236 
237  switch (Entry.Kind) {
240  return error("Malformed block");
241 
243  if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
244  return readIdentificationBlock(Stream);
245 
246  // Ignore other sub-blocks.
247  if (Error Err = Stream.SkipBlock())
248  return std::move(Err);
249  continue;
251  if (Error E = Stream.skipRecord(Entry.ID).takeError())
252  return std::move(E);
253  continue;
254  }
255  }
256 }
257 
259  if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
260  return std::move(Err);
261 
263  // Read all the records for this module.
264 
265  while (true) {
267  if (!MaybeEntry)
268  return MaybeEntry.takeError();
269  BitstreamEntry Entry = MaybeEntry.get();
270 
271  switch (Entry.Kind) {
272  case BitstreamEntry::SubBlock: // Handled for us already.
274  return error("Malformed block");
276  return false;
278  // The interesting case.
279  break;
280  }
281 
282  // Read a record.
283  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
284  if (!MaybeRecord)
285  return MaybeRecord.takeError();
286  switch (MaybeRecord.get()) {
287  default:
288  break; // Default behavior, ignore unknown content.
289  case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
290  std::string S;
291  if (convertToString(Record, 0, S))
292  return error("Invalid section name record");
293  // Check for the i386 and other (x86_64, ARM) conventions
294  if (S.find("__DATA,__objc_catlist") != std::string::npos ||
295  S.find("__OBJC,__category") != std::string::npos)
296  return true;
297  break;
298  }
299  }
300  Record.clear();
301  }
302  llvm_unreachable("Exit infinite loop");
303 }
304 
306  // We expect a number of well-defined blocks, though we don't necessarily
307  // need to understand them all.
308  while (true) {
309  BitstreamEntry Entry;
310  if (Error E = Stream.advance().moveInto(Entry))
311  return std::move(E);
312 
313  switch (Entry.Kind) {
315  return error("Malformed block");
317  return false;
318 
320  if (Entry.ID == bitc::MODULE_BLOCK_ID)
321  return hasObjCCategoryInModule(Stream);
322 
323  // Ignore other sub-blocks.
324  if (Error Err = Stream.SkipBlock())
325  return std::move(Err);
326  continue;
327 
329  if (Error E = Stream.skipRecord(Entry.ID).takeError())
330  return std::move(E);
331  continue;
332  }
333  }
334 }
335 
337  if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
338  return std::move(Err);
339 
341 
342  std::string Triple;
343 
344  // Read all the records for this module.
345  while (true) {
347  if (!MaybeEntry)
348  return MaybeEntry.takeError();
349  BitstreamEntry Entry = MaybeEntry.get();
350 
351  switch (Entry.Kind) {
352  case BitstreamEntry::SubBlock: // Handled for us already.
354  return error("Malformed block");
356  return Triple;
358  // The interesting case.
359  break;
360  }
361 
362  // Read a record.
363  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
364  if (!MaybeRecord)
365  return MaybeRecord.takeError();
366  switch (MaybeRecord.get()) {
367  default: break; // Default behavior, ignore unknown content.
368  case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
369  std::string S;
370  if (convertToString(Record, 0, S))
371  return error("Invalid triple record");
372  Triple = S;
373  break;
374  }
375  }
376  Record.clear();
377  }
378  llvm_unreachable("Exit infinite loop");
379 }
380 
382  // We expect a number of well-defined blocks, though we don't necessarily
383  // need to understand them all.
384  while (true) {
385  Expected<BitstreamEntry> MaybeEntry = Stream.advance();
386  if (!MaybeEntry)
387  return MaybeEntry.takeError();
388  BitstreamEntry Entry = MaybeEntry.get();
389 
390  switch (Entry.Kind) {
392  return error("Malformed block");
394  return "";
395 
397  if (Entry.ID == bitc::MODULE_BLOCK_ID)
398  return readModuleTriple(Stream);
399 
400  // Ignore other sub-blocks.
401  if (Error Err = Stream.SkipBlock())
402  return std::move(Err);
403  continue;
404 
406  if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
407  continue;
408  else
409  return Skipped.takeError();
410  }
411  }
412 }
413 
414 namespace {
415 
416 class BitcodeReaderBase {
417 protected:
418  BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
419  : Stream(std::move(Stream)), Strtab(Strtab) {
420  this->Stream.setBlockInfo(&BlockInfo);
421  }
422 
423  BitstreamBlockInfo BlockInfo;
424  BitstreamCursor Stream;
425  StringRef Strtab;
426 
427  /// In version 2 of the bitcode we store names of global values and comdats in
428  /// a string table rather than in the VST.
429  bool UseStrtab = false;
430 
431  Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
432 
433  /// If this module uses a string table, pop the reference to the string table
434  /// and return the referenced string and the rest of the record. Otherwise
435  /// just return the record itself.
436  std::pair<StringRef, ArrayRef<uint64_t>>
437  readNameFromStrtab(ArrayRef<uint64_t> Record);
438 
439  Error readBlockInfo();
440 
441  // Contains an arbitrary and optional string identifying the bitcode producer
442  std::string ProducerIdentification;
443 
444  Error error(const Twine &Message);
445 };
446 
447 } // end anonymous namespace
448 
449 Error BitcodeReaderBase::error(const Twine &Message) {
450  std::string FullMsg = Message.str();
451  if (!ProducerIdentification.empty())
452  FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
453  LLVM_VERSION_STRING "')";
454  return ::error(FullMsg);
455 }
456 
458 BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
459  if (Record.empty())
460  return error("Invalid version record");
461  unsigned ModuleVersion = Record[0];
462  if (ModuleVersion > 2)
463  return error("Invalid value");
464  UseStrtab = ModuleVersion >= 2;
465  return ModuleVersion;
466 }
467 
468 std::pair<StringRef, ArrayRef<uint64_t>>
469 BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
470  if (!UseStrtab)
471  return {"", Record};
472  // Invalid reference. Let the caller complain about the record being empty.
473  if (Record[0] + Record[1] > Strtab.size())
474  return {"", {}};
475  return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
476 }
477 
478 namespace {
479 
480 /// This represents a constant expression or constant aggregate using a custom
481 /// structure internal to the bitcode reader. Later, this structure will be
482 /// expanded by materializeValue() either into a constant expression/aggregate,
483 /// or into an instruction sequence at the point of use. This allows us to
484 /// upgrade bitcode using constant expressions even if this kind of constant
485 /// expression is no longer supported.
486 class BitcodeConstant final : public Value,
487  TrailingObjects<BitcodeConstant, unsigned> {
488  friend TrailingObjects;
489 
490  // Value subclass ID: Pick largest possible value to avoid any clashes.
491  static constexpr uint8_t SubclassID = 255;
492 
493 public:
494  // Opcodes used for non-expressions. This includes constant aggregates
495  // (struct, array, vector) that might need expansion, as well as non-leaf
496  // constants that don't need expansion (no_cfi, dso_local, blockaddress),
497  // but still go through BitcodeConstant to avoid different uselist orders
498  // between the two cases.
499  static constexpr uint8_t ConstantStructOpcode = 255;
500  static constexpr uint8_t ConstantArrayOpcode = 254;
501  static constexpr uint8_t ConstantVectorOpcode = 253;
502  static constexpr uint8_t NoCFIOpcode = 252;
503  static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
504  static constexpr uint8_t BlockAddressOpcode = 250;
505  static constexpr uint8_t FirstSpecialOpcode = BlockAddressOpcode;
506 
507  // Separate struct to make passing different number of parameters to
508  // BitcodeConstant::create() more convenient.
509  struct ExtraInfo {
510  uint8_t Opcode;
511  uint8_t Flags;
512  unsigned Extra;
513  Type *SrcElemTy;
514 
515  ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, unsigned Extra = 0,
516  Type *SrcElemTy = nullptr)
517  : Opcode(Opcode), Flags(Flags), Extra(Extra), SrcElemTy(SrcElemTy) {}
518  };
519 
520  uint8_t Opcode;
521  uint8_t Flags;
522  unsigned NumOperands;
523  unsigned Extra; // GEP inrange index or blockaddress BB id.
524  Type *SrcElemTy; // GEP source element type.
525 
526 private:
527  BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
528  : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags),
529  NumOperands(OpIDs.size()), Extra(Info.Extra),
530  SrcElemTy(Info.SrcElemTy) {
531  std::uninitialized_copy(OpIDs.begin(), OpIDs.end(),
532  getTrailingObjects<unsigned>());
533  }
534 
535  BitcodeConstant &operator=(const BitcodeConstant &) = delete;
536 
537 public:
538  static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty,
539  const ExtraInfo &Info,
540  ArrayRef<unsigned> OpIDs) {
541  void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()),
542  alignof(BitcodeConstant));
543  return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
544  }
545 
546  static bool classof(const Value *V) { return V->getValueID() == SubclassID; }
547 
548  ArrayRef<unsigned> getOperandIDs() const {
549  return makeArrayRef(getTrailingObjects<unsigned>(), NumOperands);
550  }
551 
552  Optional<unsigned> getInRangeIndex() const {
553  assert(Opcode == Instruction::GetElementPtr);
554  if (Extra == (unsigned)-1)
555  return None;
556  return Extra;
557  }
558 
559  const char *getOpcodeName() const {
560  return Instruction::getOpcodeName(Opcode);
561  }
562 };
563 
564 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
566  Module *TheModule = nullptr;
567  // Next offset to start scanning for lazy parsing of function bodies.
568  uint64_t NextUnreadBit = 0;
569  // Last function offset found in the VST.
570  uint64_t LastFunctionBlockBit = 0;
571  bool SeenValueSymbolTable = false;
572  uint64_t VSTOffset = 0;
573 
574  std::vector<std::string> SectionTable;
575  std::vector<std::string> GCTable;
576 
577  std::vector<Type *> TypeList;
578  /// Track type IDs of contained types. Order is the same as the contained
579  /// types of a Type*. This is used during upgrades of typed pointer IR in
580  /// opaque pointer mode.
582  /// In some cases, we need to create a type ID for a type that was not
583  /// explicitly encoded in the bitcode, or we don't know about at the current
584  /// point. For example, a global may explicitly encode the value type ID, but
585  /// not have a type ID for the pointer to value type, for which we create a
586  /// virtual type ID instead. This map stores the new type ID that was created
587  /// for the given pair of Type and contained type ID.
588  DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs;
589  DenseMap<Function *, unsigned> FunctionTypeIDs;
590  /// Allocator for BitcodeConstants. This should come before ValueList,
591  /// because the ValueList might hold ValueHandles to these constants, so
592  /// ValueList must be destroyed before Alloc.
594  BitcodeReaderValueList ValueList;
595  Optional<MetadataLoader> MDLoader;
596  std::vector<Comdat *> ComdatList;
597  DenseSet<GlobalObject *> ImplicitComdatObjects;
598  SmallVector<Instruction *, 64> InstructionList;
599 
600  std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
601  std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
602 
603  struct FunctionOperandInfo {
604  Function *F;
605  unsigned PersonalityFn;
606  unsigned Prefix;
607  unsigned Prologue;
608  };
609  std::vector<FunctionOperandInfo> FunctionOperands;
610 
611  /// The set of attributes by index. Index zero in the file is for null, and
612  /// is thus not represented here. As such all indices are off by one.
613  std::vector<AttributeList> MAttributes;
614 
615  /// The set of attribute groups.
616  std::map<unsigned, AttributeList> MAttributeGroups;
617 
618  /// While parsing a function body, this is a list of the basic blocks for the
619  /// function.
620  std::vector<BasicBlock*> FunctionBBs;
621 
622  // When reading the module header, this list is populated with functions that
623  // have bodies later in the file.
624  std::vector<Function*> FunctionsWithBodies;
625 
626  // When intrinsic functions are encountered which require upgrading they are
627  // stored here with their replacement function.
628  using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
629  UpdatedIntrinsicMap UpgradedIntrinsics;
630  // Intrinsics which were remangled because of types rename
631  UpdatedIntrinsicMap RemangledIntrinsics;
632 
633  // Several operations happen after the module header has been read, but
634  // before function bodies are processed. This keeps track of whether
635  // we've done this yet.
636  bool SeenFirstFunctionBody = false;
637 
638  /// When function bodies are initially scanned, this map contains info about
639  /// where to find deferred function body in the stream.
640  DenseMap<Function*, uint64_t> DeferredFunctionInfo;
641 
642  /// When Metadata block is initially scanned when parsing the module, we may
643  /// choose to defer parsing of the metadata. This vector contains info about
644  /// which Metadata blocks are deferred.
645  std::vector<uint64_t> DeferredMetadataInfo;
646 
647  /// These are basic blocks forward-referenced by block addresses. They are
648  /// inserted lazily into functions when they're loaded. The basic block ID is
649  /// its index into the vector.
651  std::deque<Function *> BasicBlockFwdRefQueue;
652 
653  /// These are Functions that contain BlockAddresses which refer a different
654  /// Function. When parsing the different Function, queue Functions that refer
655  /// to the different Function. Those Functions must be materialized in order
656  /// to resolve their BlockAddress constants before the different Function
657  /// gets moved into another Module.
658  std::vector<Function *> BackwardRefFunctions;
659 
660  /// Indicates that we are using a new encoding for instruction operands where
661  /// most operands in the current FUNCTION_BLOCK are encoded relative to the
662  /// instruction number, for a more compact encoding. Some instruction
663  /// operands are not relative to the instruction ID: basic block numbers, and
664  /// types. Once the old style function blocks have been phased out, we would
665  /// not need this flag.
666  bool UseRelativeIDs = false;
667 
668  /// True if all functions will be materialized, negating the need to process
669  /// (e.g.) blockaddress forward references.
670  bool WillMaterializeAllForwardRefs = false;
671 
672  bool StripDebugInfo = false;
673  TBAAVerifier TBAAVerifyHelper;
674 
675  std::vector<std::string> BundleTags;
677 
678 public:
679  BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
680  StringRef ProducerIdentification, LLVMContext &Context);
681 
682  Error materializeForwardReferencedFunctions();
683 
684  Error materialize(GlobalValue *GV) override;
685  Error materializeModule() override;
686  std::vector<StructType *> getIdentifiedStructTypes() const override;
687 
688  /// Main interface to parsing a bitcode buffer.
689  /// \returns true if an error occurred.
690  Error parseBitcodeInto(
691  Module *M, bool ShouldLazyLoadMetadata, bool IsImporting,
692  DataLayoutCallbackTy DataLayoutCallback);
693 
695 
696  /// Materialize any deferred Metadata block.
697  Error materializeMetadata() override;
698 
699  void setStripDebugInfo() override;
700 
701 private:
702  std::vector<StructType *> IdentifiedStructTypes;
703  StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
704  StructType *createIdentifiedStructType(LLVMContext &Context);
705 
706  static constexpr unsigned InvalidTypeID = ~0u;
707 
708  Type *getTypeByID(unsigned ID);
709  Type *getPtrElementTypeByID(unsigned ID);
710  unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0);
711  unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
712 
713  Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB);
714  Expected<Constant *> getValueForInitializer(unsigned ID);
715 
716  Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID,
717  BasicBlock *ConstExprInsertBB) {
718  if (Ty && Ty->isMetadataTy())
719  return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
720  return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB);
721  }
722 
723  Metadata *getFnMetadataByID(unsigned ID) {
724  return MDLoader->getMetadataFwdRefOrLoad(ID);
725  }
726 
727  BasicBlock *getBasicBlock(unsigned ID) const {
728  if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
729  return FunctionBBs[ID];
730  }
731 
732  AttributeList getAttributes(unsigned i) const {
733  if (i-1 < MAttributes.size())
734  return MAttributes[i-1];
735  return AttributeList();
736  }
737 
738  /// Read a value/type pair out of the specified record from slot 'Slot'.
739  /// Increment Slot past the number of slots used in the record. Return true on
740  /// failure.
741  bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
742  unsigned InstNum, Value *&ResVal, unsigned &TypeID,
743  BasicBlock *ConstExprInsertBB) {
744  if (Slot == Record.size()) return true;
745  unsigned ValNo = (unsigned)Record[Slot++];
746  // Adjust the ValNo, if it was encoded relative to the InstNum.
747  if (UseRelativeIDs)
748  ValNo = InstNum - ValNo;
749  if (ValNo < InstNum) {
750  // If this is not a forward reference, just return the value we already
751  // have.
752  TypeID = ValueList.getTypeID(ValNo);
753  ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB);
754  assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) &&
755  "Incorrect type ID stored for value");
756  return ResVal == nullptr;
757  }
758  if (Slot == Record.size())
759  return true;
760 
761  TypeID = (unsigned)Record[Slot++];
762  ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID,
763  ConstExprInsertBB);
764  return ResVal == nullptr;
765  }
766 
767  /// Read a value out of the specified record from slot 'Slot'. Increment Slot
768  /// past the number of slots used by the value in the record. Return true if
769  /// there is an error.
770  bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
771  unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
772  BasicBlock *ConstExprInsertBB) {
773  if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
774  return true;
775  // All values currently take a single record slot.
776  ++Slot;
777  return false;
778  }
779 
780  /// Like popValue, but does not increment the Slot number.
781  bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
782  unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
783  BasicBlock *ConstExprInsertBB) {
784  ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
785  return ResVal == nullptr;
786  }
787 
788  /// Version of getValue that returns ResVal directly, or 0 if there is an
789  /// error.
790  Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
791  unsigned InstNum, Type *Ty, unsigned TyID,
792  BasicBlock *ConstExprInsertBB) {
793  if (Slot == Record.size()) return nullptr;
794  unsigned ValNo = (unsigned)Record[Slot];
795  // Adjust the ValNo, if it was encoded relative to the InstNum.
796  if (UseRelativeIDs)
797  ValNo = InstNum - ValNo;
798  return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
799  }
800 
801  /// Like getValue, but decodes signed VBRs.
802  Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
803  unsigned InstNum, Type *Ty, unsigned TyID,
804  BasicBlock *ConstExprInsertBB) {
805  if (Slot == Record.size()) return nullptr;
806  unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
807  // Adjust the ValNo, if it was encoded relative to the InstNum.
808  if (UseRelativeIDs)
809  ValNo = InstNum - ValNo;
810  return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
811  }
812 
813  /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
814  /// corresponding argument's pointee type. Also upgrades intrinsics that now
815  /// require an elementtype attribute.
816  Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
817 
818  /// Converts alignment exponent (i.e. power of two (or zero)) to the
819  /// corresponding alignment to use. If alignment is too large, returns
820  /// a corresponding error code.
821  Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
822  Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
824  uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
825  DataLayoutCallbackTy DataLayoutCallback = [](StringRef) { return None; });
826 
827  Error parseComdatRecord(ArrayRef<uint64_t> Record);
828  Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
829  Error parseFunctionRecord(ArrayRef<uint64_t> Record);
830  Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
832 
833  Error parseAttributeBlock();
834  Error parseAttributeGroupBlock();
835  Error parseTypeTable();
836  Error parseTypeTableBody();
837  Error parseOperandBundleTags();
838  Error parseSyncScopeNames();
839 
841  unsigned NameIndex, Triple &TT);
842  void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
844  Error parseValueSymbolTable(uint64_t Offset = 0);
845  Error parseGlobalValueSymbolTable();
846  Error parseConstants();
847  Error rememberAndSkipFunctionBodies();
848  Error rememberAndSkipFunctionBody();
849  /// Save the positions of the Metadata blocks and skip parsing the blocks.
850  Error rememberAndSkipMetadata();
851  Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
852  Error parseFunctionBody(Function *F);
853  Error globalCleanup();
854  Error resolveGlobalAndIndirectSymbolInits();
855  Error parseUseLists();
856  Error findFunctionInStream(
857  Function *F,
858  DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
859 
860  SyncScope::ID getDecodedSyncScopeID(unsigned Val);
861 };
862 
863 /// Class to manage reading and parsing function summary index bitcode
864 /// files/sections.
865 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
866  /// The module index built during parsing.
867  ModuleSummaryIndex &TheIndex;
868 
869  /// Indicates whether we have encountered a global value summary section
870  /// yet during parsing.
871  bool SeenGlobalValSummary = false;
872 
873  /// Indicates whether we have already parsed the VST, used for error checking.
874  bool SeenValueSymbolTable = false;
875 
876  /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
877  /// Used to enable on-demand parsing of the VST.
878  uint64_t VSTOffset = 0;
879 
880  // Map to save ValueId to ValueInfo association that was recorded in the
881  // ValueSymbolTable. It is used after the VST is parsed to convert
882  // call graph edges read from the function summary from referencing
883  // callees by their ValueId to using the ValueInfo instead, which is how
884  // they are recorded in the summary index being built.
885  // We save a GUID which refers to the same global as the ValueInfo, but
886  // ignoring the linkage, i.e. for values other than local linkage they are
887  // identical.
889  ValueIdToValueInfoMap;
890 
891  /// Map populated during module path string table parsing, from the
892  /// module ID to a string reference owned by the index's module
893  /// path string table, used to correlate with combined index
894  /// summary records.
895  DenseMap<uint64_t, StringRef> ModuleIdMap;
896 
897  /// Original source file name recorded in a bitcode record.
898  std::string SourceFileName;
899 
900  /// The string identifier given to this module by the client, normally the
901  /// path to the bitcode file.
902  StringRef ModulePath;
903 
904  /// For per-module summary indexes, the unique numerical identifier given to
905  /// this module by the client.
906  unsigned ModuleId;
907 
908 public:
909  ModuleSummaryIndexBitcodeReader(BitstreamCursor Stream, StringRef Strtab,
910  ModuleSummaryIndex &TheIndex,
911  StringRef ModulePath, unsigned ModuleId);
912 
913  Error parseModule();
914 
915 private:
916  void setValueGUID(uint64_t ValueID, StringRef ValueName,
918  StringRef SourceFileName);
919  Error parseValueSymbolTable(
920  uint64_t Offset,
921  DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
922  std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
923  std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
924  bool IsOldProfileFormat,
925  bool HasProfile,
926  bool HasRelBF);
927  Error parseEntireSummary(unsigned ID);
928  Error parseModuleStringTable();
929  void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
930  void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
932  std::vector<FunctionSummary::ParamAccess>
933  parseParamAccesses(ArrayRef<uint64_t> Record);
934 
935  std::pair<ValueInfo, GlobalValue::GUID>
936  getValueInfoFromValueId(unsigned ValueId);
937 
938  void addThisModule();
939  ModuleSummaryIndex::ModuleInfo *getThisModule();
940 };
941 
942 } // end anonymous namespace
943 
945  Error Err) {
946  if (Err) {
947  std::error_code EC;
948  handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
949  EC = EIB.convertToErrorCode();
950  Ctx.emitError(EIB.message());
951  });
952  return EC;
953  }
954  return std::error_code();
955 }
956 
957 BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
958  StringRef ProducerIdentification,
960  : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
961  ValueList(this->Stream.SizeInBytes(),
962  [this](unsigned ValID, BasicBlock *InsertBB) {
963  return materializeValue(ValID, InsertBB);
964  }) {
965  this->ProducerIdentification = std::string(ProducerIdentification);
966 }
967 
968 Error BitcodeReader::materializeForwardReferencedFunctions() {
969  if (WillMaterializeAllForwardRefs)
970  return Error::success();
971 
972  // Prevent recursion.
973  WillMaterializeAllForwardRefs = true;
974 
975  while (!BasicBlockFwdRefQueue.empty()) {
976  Function *F = BasicBlockFwdRefQueue.front();
977  BasicBlockFwdRefQueue.pop_front();
978  assert(F && "Expected valid function");
979  if (!BasicBlockFwdRefs.count(F))
980  // Already materialized.
981  continue;
982 
983  // Check for a function that isn't materializable to prevent an infinite
984  // loop. When parsing a blockaddress stored in a global variable, there
985  // isn't a trivial way to check if a function will have a body without a
986  // linear search through FunctionsWithBodies, so just check it here.
987  if (!F->isMaterializable())
988  return error("Never resolved function from blockaddress");
989 
990  // Try to materialize F.
991  if (Error Err = materialize(F))
992  return Err;
993  }
994  assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
995 
996  for (Function *F : BackwardRefFunctions)
997  if (Error Err = materialize(F))
998  return Err;
999  BackwardRefFunctions.clear();
1000 
1001  // Reset state.
1002  WillMaterializeAllForwardRefs = false;
1003  return Error::success();
1004 }
1005 
1006 //===----------------------------------------------------------------------===//
1007 // Helper functions to implement forward reference resolution, etc.
1008 //===----------------------------------------------------------------------===//
1009 
1010 static bool hasImplicitComdat(size_t Val) {
1011  switch (Val) {
1012  default:
1013  return false;
1014  case 1: // Old WeakAnyLinkage
1015  case 4: // Old LinkOnceAnyLinkage
1016  case 10: // Old WeakODRLinkage
1017  case 11: // Old LinkOnceODRLinkage
1018  return true;
1019  }
1020 }
1021 
1023  switch (Val) {
1024  default: // Map unknown/new linkages to external
1025  case 0:
1026  return GlobalValue::ExternalLinkage;
1027  case 2:
1028  return GlobalValue::AppendingLinkage;
1029  case 3:
1030  return GlobalValue::InternalLinkage;
1031  case 5:
1032  return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
1033  case 6:
1034  return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
1035  case 7:
1036  return GlobalValue::ExternalWeakLinkage;
1037  case 8:
1038  return GlobalValue::CommonLinkage;
1039  case 9:
1040  return GlobalValue::PrivateLinkage;
1041  case 12:
1042  return GlobalValue::AvailableExternallyLinkage;
1043  case 13:
1044  return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
1045  case 14:
1046  return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
1047  case 15:
1048  return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
1049  case 1: // Old value with implicit comdat.
1050  case 16:
1051  return GlobalValue::WeakAnyLinkage;
1052  case 10: // Old value with implicit comdat.
1053  case 17:
1054  return GlobalValue::WeakODRLinkage;
1055  case 4: // Old value with implicit comdat.
1056  case 18:
1057  return GlobalValue::LinkOnceAnyLinkage;
1058  case 11: // Old value with implicit comdat.
1059  case 19:
1060  return GlobalValue::LinkOnceODRLinkage;
1061  }
1062 }
1063 
1066  Flags.ReadNone = RawFlags & 0x1;
1067  Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1068  Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1069  Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1070  Flags.NoInline = (RawFlags >> 4) & 0x1;
1071  Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1072  Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1073  Flags.MayThrow = (RawFlags >> 7) & 0x1;
1074  Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1075  Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1076  return Flags;
1077 }
1078 
1079 // Decode the flags for GlobalValue in the summary. The bits for each attribute:
1080 //
1081 // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
1082 // visibility: [8, 10).
1084  uint64_t Version) {
1085  // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
1086  // like getDecodedLinkage() above. Any future change to the linkage enum and
1087  // to getDecodedLinkage() will need to be taken into account here as above.
1088  auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
1089  auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
1090  RawFlags = RawFlags >> 4;
1091  bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1092  // The Live flag wasn't introduced until version 3. For dead stripping
1093  // to work correctly on earlier versions, we must conservatively treat all
1094  // values as live.
1095  bool Live = (RawFlags & 0x2) || Version < 3;
1096  bool Local = (RawFlags & 0x4);
1097  bool AutoHide = (RawFlags & 0x8);
1098 
1099  return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
1100  Live, Local, AutoHide);
1101 }
1102 
1103 // Decode the flags for GlobalVariable in the summary
1106  (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
1107  (RawFlags & 0x4) ? true : false,
1108  (GlobalObject::VCallVisibility)(RawFlags >> 3));
1109 }
1110 
1112  switch (Val) {
1113  default: // Map unknown visibilities to default.
1114  case 0: return GlobalValue::DefaultVisibility;
1115  case 1: return GlobalValue::HiddenVisibility;
1116  case 2: return GlobalValue::ProtectedVisibility;
1117  }
1118 }
1119 
1122  switch (Val) {
1123  default: // Map unknown values to default.
1124  case 0: return GlobalValue::DefaultStorageClass;
1125  case 1: return GlobalValue::DLLImportStorageClass;
1126  case 2: return GlobalValue::DLLExportStorageClass;
1127  }
1128 }
1129 
1130 static bool getDecodedDSOLocal(unsigned Val) {
1131  switch(Val) {
1132  default: // Map unknown values to preemptable.
1133  case 0: return false;
1134  case 1: return true;
1135  }
1136 }
1137 
1138 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
1139  switch (Val) {
1140  case 0: return GlobalVariable::NotThreadLocal;
1141  default: // Map unknown non-zero value to general dynamic.
1142  case 1: return GlobalVariable::GeneralDynamicTLSModel;
1143  case 2: return GlobalVariable::LocalDynamicTLSModel;
1144  case 3: return GlobalVariable::InitialExecTLSModel;
1145  case 4: return GlobalVariable::LocalExecTLSModel;
1146  }
1147 }
1148 
1149 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
1150  switch (Val) {
1151  default: // Map unknown to UnnamedAddr::None.
1152  case 0: return GlobalVariable::UnnamedAddr::None;
1153  case 1: return GlobalVariable::UnnamedAddr::Global;
1154  case 2: return GlobalVariable::UnnamedAddr::Local;
1155  }
1156 }
1157 
1158 static int getDecodedCastOpcode(unsigned Val) {
1159  switch (Val) {
1160  default: return -1;
1161  case bitc::CAST_TRUNC : return Instruction::Trunc;
1162  case bitc::CAST_ZEXT : return Instruction::ZExt;
1163  case bitc::CAST_SEXT : return Instruction::SExt;
1164  case bitc::CAST_FPTOUI : return Instruction::FPToUI;
1165  case bitc::CAST_FPTOSI : return Instruction::FPToSI;
1166  case bitc::CAST_UITOFP : return Instruction::UIToFP;
1167  case bitc::CAST_SITOFP : return Instruction::SIToFP;
1168  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
1169  case bitc::CAST_FPEXT : return Instruction::FPExt;
1170  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
1171  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
1172  case bitc::CAST_BITCAST : return Instruction::BitCast;
1173  case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
1174  }
1175 }
1176 
1177 static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
1178  bool IsFP = Ty->isFPOrFPVectorTy();
1179  // UnOps are only valid for int/fp or vector of int/fp types
1180  if (!IsFP && !Ty->isIntOrIntVectorTy())
1181  return -1;
1182 
1183  switch (Val) {
1184  default:
1185  return -1;
1186  case bitc::UNOP_FNEG:
1187  return IsFP ? Instruction::FNeg : -1;
1188  }
1189 }
1190 
1191 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
1192  bool IsFP = Ty->isFPOrFPVectorTy();
1193  // BinOps are only valid for int/fp or vector of int/fp types
1194  if (!IsFP && !Ty->isIntOrIntVectorTy())
1195  return -1;
1196 
1197  switch (Val) {
1198  default:
1199  return -1;
1200  case bitc::BINOP_ADD:
1201  return IsFP ? Instruction::FAdd : Instruction::Add;
1202  case bitc::BINOP_SUB:
1203  return IsFP ? Instruction::FSub : Instruction::Sub;
1204  case bitc::BINOP_MUL:
1205  return IsFP ? Instruction::FMul : Instruction::Mul;
1206  case bitc::BINOP_UDIV:
1207  return IsFP ? -1 : Instruction::UDiv;
1208  case bitc::BINOP_SDIV:
1209  return IsFP ? Instruction::FDiv : Instruction::SDiv;
1210  case bitc::BINOP_UREM:
1211  return IsFP ? -1 : Instruction::URem;
1212  case bitc::BINOP_SREM:
1213  return IsFP ? Instruction::FRem : Instruction::SRem;
1214  case bitc::BINOP_SHL:
1215  return IsFP ? -1 : Instruction::Shl;
1216  case bitc::BINOP_LSHR:
1217  return IsFP ? -1 : Instruction::LShr;
1218  case bitc::BINOP_ASHR:
1219  return IsFP ? -1 : Instruction::AShr;
1220  case bitc::BINOP_AND:
1221  return IsFP ? -1 : Instruction::And;
1222  case bitc::BINOP_OR:
1223  return IsFP ? -1 : Instruction::Or;
1224  case bitc::BINOP_XOR:
1225  return IsFP ? -1 : Instruction::Xor;
1226  }
1227 }
1228 
1230  switch (Val) {
1231  default: return AtomicRMWInst::BAD_BINOP;
1232  case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1233  case bitc::RMW_ADD: return AtomicRMWInst::Add;
1234  case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1235  case bitc::RMW_AND: return AtomicRMWInst::And;
1236  case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1237  case bitc::RMW_OR: return AtomicRMWInst::Or;
1238  case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1239  case bitc::RMW_MAX: return AtomicRMWInst::Max;
1240  case bitc::RMW_MIN: return AtomicRMWInst::Min;
1241  case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1242  case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1243  case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
1244  case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1245  case bitc::RMW_FMAX: return AtomicRMWInst::FMax;
1246  case bitc::RMW_FMIN: return AtomicRMWInst::FMin;
1247  }
1248 }
1249 
1250 static AtomicOrdering getDecodedOrdering(unsigned Val) {
1251  switch (Val) {
1252  case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1254  case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1255  case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1256  case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1257  case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
1258  default: // Map unknown orderings to sequentially-consistent.
1259  case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
1260  }
1261 }
1262 
1264  switch (Val) {
1265  default: // Map unknown selection kinds to any.
1267  return Comdat::Any;
1269  return Comdat::ExactMatch;
1271  return Comdat::Largest;
1273  return Comdat::NoDeduplicate;
1275  return Comdat::SameSize;
1276  }
1277 }
1278 
1280  FastMathFlags FMF;
1281  if (0 != (Val & bitc::UnsafeAlgebra))
1282  FMF.setFast();
1283  if (0 != (Val & bitc::AllowReassoc))
1284  FMF.setAllowReassoc();
1285  if (0 != (Val & bitc::NoNaNs))
1286  FMF.setNoNaNs();
1287  if (0 != (Val & bitc::NoInfs))
1288  FMF.setNoInfs();
1289  if (0 != (Val & bitc::NoSignedZeros))
1290  FMF.setNoSignedZeros();
1291  if (0 != (Val & bitc::AllowReciprocal))
1292  FMF.setAllowReciprocal();
1293  if (0 != (Val & bitc::AllowContract))
1294  FMF.setAllowContract(true);
1295  if (0 != (Val & bitc::ApproxFunc))
1296  FMF.setApproxFunc();
1297  return FMF;
1298 }
1299 
1300 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1301  switch (Val) {
1302  case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1303  case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1304  }
1305 }
1306 
1307 Type *BitcodeReader::getTypeByID(unsigned ID) {
1308  // The type table size is always specified correctly.
1309  if (ID >= TypeList.size())
1310  return nullptr;
1311 
1312  if (Type *Ty = TypeList[ID])
1313  return Ty;
1314 
1315  // If we have a forward reference, the only possible case is when it is to a
1316  // named struct. Just create a placeholder for now.
1317  return TypeList[ID] = createIdentifiedStructType(Context);
1318 }
1319 
1320 unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) {
1321  auto It = ContainedTypeIDs.find(ID);
1322  if (It == ContainedTypeIDs.end())
1323  return InvalidTypeID;
1324 
1325  if (Idx >= It->second.size())
1326  return InvalidTypeID;
1327 
1328  return It->second[Idx];
1329 }
1330 
1331 Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) {
1332  if (ID >= TypeList.size())
1333  return nullptr;
1334 
1335  Type *Ty = TypeList[ID];
1336  if (!Ty->isPointerTy())
1337  return nullptr;
1338 
1339  Type *ElemTy = getTypeByID(getContainedTypeID(ID, 0));
1340  if (!ElemTy)
1341  return nullptr;
1342 
1343  assert(cast<PointerType>(Ty)->isOpaqueOrPointeeTypeMatches(ElemTy) &&
1344  "Incorrect element type");
1345  return ElemTy;
1346 }
1347 
1348 unsigned BitcodeReader::getVirtualTypeID(Type *Ty,
1349  ArrayRef<unsigned> ChildTypeIDs) {
1350  unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0];
1351  auto CacheKey = std::make_pair(Ty, ChildTypeID);
1352  auto It = VirtualTypeIDs.find(CacheKey);
1353  if (It != VirtualTypeIDs.end()) {
1354  // The cmpxchg return value is the only place we need more than one
1355  // contained type ID, however the second one will always be the same (i1),
1356  // so we don't need to include it in the cache key. This asserts that the
1357  // contained types are indeed as expected and there are no collisions.
1358  assert((ChildTypeIDs.empty() ||
1359  ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1360  "Incorrect cached contained type IDs");
1361  return It->second;
1362  }
1363 
1364 #ifndef NDEBUG
1365  if (!Ty->isOpaquePointerTy()) {
1366  assert(Ty->getNumContainedTypes() == ChildTypeIDs.size() &&
1367  "Wrong number of contained types");
1368  for (auto Pair : zip(Ty->subtypes(), ChildTypeIDs)) {
1369  assert(std::get<0>(Pair) == getTypeByID(std::get<1>(Pair)) &&
1370  "Incorrect contained type ID");
1371  }
1372  }
1373 #endif
1374 
1375  unsigned TypeID = TypeList.size();
1376  TypeList.push_back(Ty);
1377  if (!ChildTypeIDs.empty())
1378  append_range(ContainedTypeIDs[TypeID], ChildTypeIDs);
1379  VirtualTypeIDs.insert({CacheKey, TypeID});
1380  return TypeID;
1381 }
1382 
1383 static bool isConstExprSupported(uint8_t Opcode) {
1384  // These are not real constant expressions, always consider them supported.
1385  if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1386  return true;
1387 
1388  // If -expand-constant-exprs is set, we want to consider all expressions
1389  // as unsupported.
1390  if (ExpandConstantExprs)
1391  return false;
1392 
1393  if (Instruction::isBinaryOp(Opcode))
1394  return ConstantExpr::isSupportedBinOp(Opcode);
1395 
1396  return Opcode != Instruction::FNeg;
1397 }
1398 
1399 Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID,
1400  BasicBlock *InsertBB) {
1401  // Quickly handle the case where there is no BitcodeConstant to resolve.
1402  if (StartValID < ValueList.size() && ValueList[StartValID] &&
1403  !isa<BitcodeConstant>(ValueList[StartValID]))
1404  return ValueList[StartValID];
1405 
1406  SmallDenseMap<unsigned, Value *> MaterializedValues;
1407  SmallVector<unsigned> Worklist;
1408  Worklist.push_back(StartValID);
1409  while (!Worklist.empty()) {
1410  unsigned ValID = Worklist.back();
1411  if (MaterializedValues.count(ValID)) {
1412  // Duplicate expression that was already handled.
1413  Worklist.pop_back();
1414  continue;
1415  }
1416 
1417  if (ValID >= ValueList.size() || !ValueList[ValID])
1418  return error("Invalid value ID");
1419 
1420  Value *V = ValueList[ValID];
1421  auto *BC = dyn_cast<BitcodeConstant>(V);
1422  if (!BC) {
1423  MaterializedValues.insert({ValID, V});
1424  Worklist.pop_back();
1425  continue;
1426  }
1427 
1428  // Iterate in reverse, so values will get popped from the worklist in
1429  // expected order.
1431  for (unsigned OpID : reverse(BC->getOperandIDs())) {
1432  auto It = MaterializedValues.find(OpID);
1433  if (It != MaterializedValues.end())
1434  Ops.push_back(It->second);
1435  else
1436  Worklist.push_back(OpID);
1437  }
1438 
1439  // Some expressions have not been resolved yet, handle them first and then
1440  // revisit this one.
1441  if (Ops.size() != BC->getOperandIDs().size())
1442  continue;
1443  std::reverse(Ops.begin(), Ops.end());
1444 
1445  SmallVector<Constant *> ConstOps;
1446  for (Value *Op : Ops)
1447  if (auto *C = dyn_cast<Constant>(Op))
1448  ConstOps.push_back(C);
1449 
1450  // Materialize as constant expression if possible.
1451  if (isConstExprSupported(BC->Opcode) && ConstOps.size() == Ops.size()) {
1452  Constant *C;
1453  if (Instruction::isCast(BC->Opcode)) {
1454  C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType());
1455  if (!C)
1456  C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType());
1457  } else if (Instruction::isBinaryOp(BC->Opcode)) {
1458  C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags);
1459  } else {
1460  switch (BC->Opcode) {
1461  case BitcodeConstant::NoCFIOpcode: {
1462  auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1463  if (!GV)
1464  return error("no_cfi operand must be GlobalValue");
1465  C = NoCFIValue::get(GV);
1466  break;
1467  }
1468  case BitcodeConstant::DSOLocalEquivalentOpcode: {
1469  auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1470  if (!GV)
1471  return error("dso_local operand must be GlobalValue");
1472  C = DSOLocalEquivalent::get(GV);
1473  break;
1474  }
1475  case BitcodeConstant::BlockAddressOpcode: {
1476  Function *Fn = dyn_cast<Function>(ConstOps[0]);
1477  if (!Fn)
1478  return error("blockaddress operand must be a function");
1479 
1480  // If the function is already parsed we can insert the block address
1481  // right away.
1482  BasicBlock *BB;
1483  unsigned BBID = BC->Extra;
1484  if (!BBID)
1485  // Invalid reference to entry block.
1486  return error("Invalid ID");
1487  if (!Fn->empty()) {
1488  Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1489  for (size_t I = 0, E = BBID; I != E; ++I) {
1490  if (BBI == BBE)
1491  return error("Invalid ID");
1492  ++BBI;
1493  }
1494  BB = &*BBI;
1495  } else {
1496  // Otherwise insert a placeholder and remember it so it can be
1497  // inserted when the function is parsed.
1498  auto &FwdBBs = BasicBlockFwdRefs[Fn];
1499  if (FwdBBs.empty())
1500  BasicBlockFwdRefQueue.push_back(Fn);
1501  if (FwdBBs.size() < BBID + 1)
1502  FwdBBs.resize(BBID + 1);
1503  if (!FwdBBs[BBID])
1504  FwdBBs[BBID] = BasicBlock::Create(Context);
1505  BB = FwdBBs[BBID];
1506  }
1507  C = BlockAddress::get(Fn, BB);
1508  break;
1509  }
1510  case BitcodeConstant::ConstantStructOpcode:
1511  C = ConstantStruct::get(cast<StructType>(BC->getType()), ConstOps);
1512  break;
1513  case BitcodeConstant::ConstantArrayOpcode:
1514  C = ConstantArray::get(cast<ArrayType>(BC->getType()), ConstOps);
1515  break;
1516  case BitcodeConstant::ConstantVectorOpcode:
1517  C = ConstantVector::get(ConstOps);
1518  break;
1519  case Instruction::ICmp:
1520  case Instruction::FCmp:
1521  C = ConstantExpr::getCompare(BC->Flags, ConstOps[0], ConstOps[1]);
1522  break;
1523  case Instruction::GetElementPtr:
1524  C = ConstantExpr::getGetElementPtr(
1525  BC->SrcElemTy, ConstOps[0], makeArrayRef(ConstOps).drop_front(),
1526  BC->Flags, BC->getInRangeIndex());
1527  break;
1528  case Instruction::Select:
1529  C = ConstantExpr::getSelect(ConstOps[0], ConstOps[1], ConstOps[2]);
1530  break;
1531  case Instruction::ExtractElement:
1532  C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]);
1533  break;
1534  case Instruction::InsertElement:
1535  C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1],
1536  ConstOps[2]);
1537  break;
1538  case Instruction::ShuffleVector: {
1540  ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask);
1541  C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask);
1542  break;
1543  }
1544  default:
1545  llvm_unreachable("Unhandled bitcode constant");
1546  }
1547  }
1548 
1549  // Cache resolved constant.
1550  ValueList.replaceValueWithoutRAUW(ValID, C);
1551  MaterializedValues.insert({ValID, C});
1552  Worklist.pop_back();
1553  continue;
1554  }
1555 
1556  if (!InsertBB)
1557  return error(Twine("Value referenced by initializer is an unsupported "
1558  "constant expression of type ") +
1559  BC->getOpcodeName());
1560 
1561  // Materialize as instructions if necessary.
1562  Instruction *I;
1563  if (Instruction::isCast(BC->Opcode)) {
1564  I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0],
1565  BC->getType(), "constexpr", InsertBB);
1566  } else if (Instruction::isUnaryOp(BC->Opcode)) {
1567  I = UnaryOperator::Create((Instruction::UnaryOps)BC->Opcode, Ops[0],
1568  "constexpr", InsertBB);
1569  } else if (Instruction::isBinaryOp(BC->Opcode)) {
1570  I = BinaryOperator::Create((Instruction::BinaryOps)BC->Opcode, Ops[0],
1571  Ops[1], "constexpr", InsertBB);
1572  if (isa<OverflowingBinaryOperator>(I)) {
1573  if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap)
1574  I->setHasNoSignedWrap();
1575  if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap)
1576  I->setHasNoUnsignedWrap();
1577  }
1578  if (isa<PossiblyExactOperator>(I) &&
1579  (BC->Flags & PossiblyExactOperator::IsExact))
1580  I->setIsExact();
1581  } else {
1582  switch (BC->Opcode) {
1583  case BitcodeConstant::ConstantVectorOpcode: {
1584  Type *IdxTy = Type::getInt32Ty(BC->getContext());
1585  Value *V = PoisonValue::get(BC->getType());
1586  for (auto Pair : enumerate(Ops)) {
1587  Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1588  V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins",
1589  InsertBB);
1590  }
1591  I = cast<Instruction>(V);
1592  break;
1593  }
1594  case BitcodeConstant::ConstantStructOpcode:
1595  case BitcodeConstant::ConstantArrayOpcode: {
1596  Value *V = PoisonValue::get(BC->getType());
1597  for (auto Pair : enumerate(Ops))
1598  V = InsertValueInst::Create(V, Pair.value(), Pair.index(),
1599  "constexpr.ins", InsertBB);
1600  I = cast<Instruction>(V);
1601  break;
1602  }
1603  case Instruction::ICmp:
1604  case Instruction::FCmp:
1605  I = CmpInst::Create((Instruction::OtherOps)BC->Opcode,
1606  (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1],
1607  "constexpr", InsertBB);
1608  break;
1609  case Instruction::GetElementPtr:
1610  I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0],
1611  makeArrayRef(Ops).drop_front(),
1612  "constexpr", InsertBB);
1613  if (BC->Flags)
1614  cast<GetElementPtrInst>(I)->setIsInBounds();
1615  break;
1616  case Instruction::Select:
1617  I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB);
1618  break;
1619  case Instruction::ExtractElement:
1620  I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB);
1621  break;
1622  case Instruction::InsertElement:
1623  I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr",
1624  InsertBB);
1625  break;
1626  case Instruction::ShuffleVector:
1627  I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr",
1628  InsertBB);
1629  break;
1630  default:
1631  llvm_unreachable("Unhandled bitcode constant");
1632  }
1633  }
1634 
1635  MaterializedValues.insert({ValID, I});
1636  Worklist.pop_back();
1637  }
1638 
1639  return MaterializedValues[StartValID];
1640 }
1641 
1642 Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) {
1643  Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr);
1644  if (!MaybeV)
1645  return MaybeV.takeError();
1646 
1647  // Result must be Constant if InsertBB is nullptr.
1648  return cast<Constant>(MaybeV.get());
1649 }
1650 
1651 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1652  StringRef Name) {
1653  auto *Ret = StructType::create(Context, Name);
1654  IdentifiedStructTypes.push_back(Ret);
1655  return Ret;
1656 }
1657 
1658 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1659  auto *Ret = StructType::create(Context);
1660  IdentifiedStructTypes.push_back(Ret);
1661  return Ret;
1662 }
1663 
1664 //===----------------------------------------------------------------------===//
1665 // Functions for parsing blocks from the bitcode file
1666 //===----------------------------------------------------------------------===//
1667 
1669  switch (Val) {
1670  case Attribute::EndAttrKinds:
1671  case Attribute::EmptyKey:
1672  case Attribute::TombstoneKey:
1673  llvm_unreachable("Synthetic enumerators which should never get here");
1674 
1675  case Attribute::None: return 0;
1676  case Attribute::ZExt: return 1 << 0;
1677  case Attribute::SExt: return 1 << 1;
1678  case Attribute::NoReturn: return 1 << 2;
1679  case Attribute::InReg: return 1 << 3;
1680  case Attribute::StructRet: return 1 << 4;
1681  case Attribute::NoUnwind: return 1 << 5;
1682  case Attribute::NoAlias: return 1 << 6;
1683  case Attribute::ByVal: return 1 << 7;
1684  case Attribute::Nest: return 1 << 8;
1685  case Attribute::ReadNone: return 1 << 9;
1686  case Attribute::ReadOnly: return 1 << 10;
1687  case Attribute::NoInline: return 1 << 11;
1688  case Attribute::AlwaysInline: return 1 << 12;
1689  case Attribute::OptimizeForSize: return 1 << 13;
1690  case Attribute::StackProtect: return 1 << 14;
1691  case Attribute::StackProtectReq: return 1 << 15;
1692  case Attribute::Alignment: return 31 << 16;
1693  case Attribute::NoCapture: return 1 << 21;
1694  case Attribute::NoRedZone: return 1 << 22;
1695  case Attribute::NoImplicitFloat: return 1 << 23;
1696  case Attribute::Naked: return 1 << 24;
1697  case Attribute::InlineHint: return 1 << 25;
1698  case Attribute::StackAlignment: return 7 << 26;
1699  case Attribute::ReturnsTwice: return 1 << 29;
1700  case Attribute::UWTable: return 1 << 30;
1701  case Attribute::NonLazyBind: return 1U << 31;
1702  case Attribute::SanitizeAddress: return 1ULL << 32;
1703  case Attribute::MinSize: return 1ULL << 33;
1704  case Attribute::NoDuplicate: return 1ULL << 34;
1705  case Attribute::StackProtectStrong: return 1ULL << 35;
1706  case Attribute::SanitizeThread: return 1ULL << 36;
1707  case Attribute::SanitizeMemory: return 1ULL << 37;
1708  case Attribute::NoBuiltin: return 1ULL << 38;
1709  case Attribute::Returned: return 1ULL << 39;
1710  case Attribute::Cold: return 1ULL << 40;
1711  case Attribute::Builtin: return 1ULL << 41;
1712  case Attribute::OptimizeNone: return 1ULL << 42;
1713  case Attribute::InAlloca: return 1ULL << 43;
1714  case Attribute::NonNull: return 1ULL << 44;
1715  case Attribute::JumpTable: return 1ULL << 45;
1716  case Attribute::Convergent: return 1ULL << 46;
1717  case Attribute::SafeStack: return 1ULL << 47;
1718  case Attribute::NoRecurse: return 1ULL << 48;
1719  case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1720  case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1721  case Attribute::SwiftSelf: return 1ULL << 51;
1722  case Attribute::SwiftError: return 1ULL << 52;
1723  case Attribute::WriteOnly: return 1ULL << 53;
1724  case Attribute::Speculatable: return 1ULL << 54;
1725  case Attribute::StrictFP: return 1ULL << 55;
1726  case Attribute::SanitizeHWAddress: return 1ULL << 56;
1727  case Attribute::NoCfCheck: return 1ULL << 57;
1728  case Attribute::OptForFuzzing: return 1ULL << 58;
1729  case Attribute::ShadowCallStack: return 1ULL << 59;
1730  case Attribute::SpeculativeLoadHardening:
1731  return 1ULL << 60;
1732  case Attribute::ImmArg:
1733  return 1ULL << 61;
1734  case Attribute::WillReturn:
1735  return 1ULL << 62;
1736  case Attribute::NoFree:
1737  return 1ULL << 63;
1738  default:
1739  // Other attributes are not supported in the raw format,
1740  // as we ran out of space.
1741  return 0;
1742  }
1743  llvm_unreachable("Unsupported attribute type");
1744 }
1745 
1747  if (!Val) return;
1748 
1749  for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1750  I = Attribute::AttrKind(I + 1)) {
1751  if (uint64_t A = (Val & getRawAttributeMask(I))) {
1752  if (I == Attribute::Alignment)
1753  B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1754  else if (I == Attribute::StackAlignment)
1755  B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1756  else if (Attribute::isTypeAttrKind(I))
1757  B.addTypeAttr(I, nullptr); // Type will be auto-upgraded.
1758  else
1759  B.addAttribute(I);
1760  }
1761  }
1762 }
1763 
1764 /// This fills an AttrBuilder object with the LLVM attributes that have
1765 /// been decoded from the given integer. This function must stay in sync with
1766 /// 'encodeLLVMAttributesForBitcode'.
1768  uint64_t EncodedAttrs) {
1769  // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1770  // the bits above 31 down by 11 bits.
1771  unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1772  assert((!Alignment || isPowerOf2_32(Alignment)) &&
1773  "Alignment must be a power of two.");
1774 
1775  if (Alignment)
1776  B.addAlignmentAttr(Alignment);
1777  addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1778  (EncodedAttrs & 0xffff));
1779 }
1780 
1781 Error BitcodeReader::parseAttributeBlock() {
1782  if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1783  return Err;
1784 
1785  if (!MAttributes.empty())
1786  return error("Invalid multiple blocks");
1787 
1789 
1791 
1792  // Read all the records.
1793  while (true) {
1794  Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1795  if (!MaybeEntry)
1796  return MaybeEntry.takeError();
1797  BitstreamEntry Entry = MaybeEntry.get();
1798 
1799  switch (Entry.Kind) {
1800  case BitstreamEntry::SubBlock: // Handled for us already.
1801  case BitstreamEntry::Error:
1802  return error("Malformed block");
1803  case BitstreamEntry::EndBlock:
1804  return Error::success();
1805  case BitstreamEntry::Record:
1806  // The interesting case.
1807  break;
1808  }
1809 
1810  // Read a record.
1811  Record.clear();
1812  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1813  if (!MaybeRecord)
1814  return MaybeRecord.takeError();
1815  switch (MaybeRecord.get()) {
1816  default: // Default behavior: ignore.
1817  break;
1818  case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1819  // Deprecated, but still needed to read old bitcode files.
1820  if (Record.size() & 1)
1821  return error("Invalid parameter attribute record");
1822 
1823  for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1826  Attrs.push_back(AttributeList::get(Context, Record[i], B));
1827  }
1828 
1829  MAttributes.push_back(AttributeList::get(Context, Attrs));
1830  Attrs.clear();
1831  break;
1832  case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1833  for (unsigned i = 0, e = Record.size(); i != e; ++i)
1834  Attrs.push_back(MAttributeGroups[Record[i]]);
1835 
1836  MAttributes.push_back(AttributeList::get(Context, Attrs));
1837  Attrs.clear();
1838  break;
1839  }
1840  }
1841 }
1842 
1843 // Returns Attribute::None on unrecognized codes.
1845  switch (Code) {
1846  default:
1847  return Attribute::None;
1849  return Attribute::Alignment;
1851  return Attribute::AlwaysInline;
1853  return Attribute::ArgMemOnly;
1855  return Attribute::Builtin;
1857  return Attribute::ByVal;
1859  return Attribute::InAlloca;
1860  case bitc::ATTR_KIND_COLD:
1861  return Attribute::Cold;
1863  return Attribute::Convergent;
1865  return Attribute::DisableSanitizerInstrumentation;
1867  return Attribute::ElementType;
1869  return Attribute::FnRetThunkExtern;
1871  return Attribute::InaccessibleMemOnly;
1873  return Attribute::InaccessibleMemOrArgMemOnly;
1875  return Attribute::InlineHint;
1877  return Attribute::InReg;
1879  return Attribute::JumpTable;
1881  return Attribute::MinSize;
1882  case bitc::ATTR_KIND_NAKED:
1883  return Attribute::Naked;
1884  case bitc::ATTR_KIND_NEST:
1885  return Attribute::Nest;
1887  return Attribute::NoAlias;
1889  return Attribute::NoBuiltin;
1891  return Attribute::NoCallback;
1893  return Attribute::NoCapture;
1895  return Attribute::NoDuplicate;
1897  return Attribute::NoFree;
1899  return Attribute::NoImplicitFloat;
1901  return Attribute::NoInline;
1903  return Attribute::NoRecurse;
1905  return Attribute::NoMerge;
1907  return Attribute::NonLazyBind;
1909  return Attribute::NonNull;
1911  return Attribute::Dereferenceable;
1913  return Attribute::DereferenceableOrNull;
1915  return Attribute::AllocAlign;
1917  return Attribute::AllocKind;
1919  return Attribute::AllocSize;
1921  return Attribute::AllocatedPointer;
1923  return Attribute::NoRedZone;
1925  return Attribute::NoReturn;
1927  return Attribute::NoSync;
1929  return Attribute::NoCfCheck;
1931  return Attribute::NoProfile;
1933  return Attribute::SkipProfile;
1935  return Attribute::NoUnwind;
1937  return Attribute::NoSanitizeBounds;
1939  return Attribute::NoSanitizeCoverage;
1941  return Attribute::NullPointerIsValid;
1943  return Attribute::OptForFuzzing;
1945  return Attribute::OptimizeForSize;
1947  return Attribute::OptimizeNone;
1949  return Attribute::ReadNone;
1951  return Attribute::ReadOnly;
1953  return Attribute::Returned;
1955  return Attribute::ReturnsTwice;
1956  case bitc::ATTR_KIND_S_EXT:
1957  return Attribute::SExt;
1959  return Attribute::Speculatable;
1961  return Attribute::StackAlignment;
1963  return Attribute::StackProtect;
1965  return Attribute::StackProtectReq;
1967  return Attribute::StackProtectStrong;
1969  return Attribute::SafeStack;
1971  return Attribute::ShadowCallStack;
1973  return Attribute::StrictFP;
1975  return Attribute::StructRet;
1977  return Attribute::SanitizeAddress;
1979  return Attribute::SanitizeHWAddress;
1981  return Attribute::SanitizeThread;
1983  return Attribute::SanitizeMemory;
1985  return Attribute::SpeculativeLoadHardening;
1987  return Attribute::SwiftError;
1989  return Attribute::SwiftSelf;
1991  return Attribute::SwiftAsync;
1993  return Attribute::UWTable;
1995  return Attribute::VScaleRange;
1997  return Attribute::WillReturn;
1999  return Attribute::WriteOnly;
2000  case bitc::ATTR_KIND_Z_EXT:
2001  return Attribute::ZExt;
2003  return Attribute::ImmArg;
2005  return Attribute::SanitizeMemTag;
2007  return Attribute::Preallocated;
2009  return Attribute::NoUndef;
2010  case bitc::ATTR_KIND_BYREF:
2011  return Attribute::ByRef;
2013  return Attribute::MustProgress;
2014  case bitc::ATTR_KIND_HOT:
2015  return Attribute::Hot;
2017  return Attribute::PresplitCoroutine;
2018  }
2019 }
2020 
2021 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
2022  MaybeAlign &Alignment) {
2023  // Note: Alignment in bitcode files is incremented by 1, so that zero
2024  // can be used for default alignment.
2025  if (Exponent > Value::MaxAlignmentExponent + 1)
2026  return error("Invalid alignment value");
2027  Alignment = decodeMaybeAlign(Exponent);
2028  return Error::success();
2029 }
2030 
2031 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2033  if (*Kind == Attribute::None)
2034  return error("Unknown attribute kind (" + Twine(Code) + ")");
2035  return Error::success();
2036 }
2037 
2038 Error BitcodeReader::parseAttributeGroupBlock() {
2039  if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
2040  return Err;
2041 
2042  if (!MAttributeGroups.empty())
2043  return error("Invalid multiple blocks");
2044 
2046 
2047  // Read all the records.
2048  while (true) {
2049  Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2050  if (!MaybeEntry)
2051  return MaybeEntry.takeError();
2052  BitstreamEntry Entry = MaybeEntry.get();
2053 
2054  switch (Entry.Kind) {
2055  case BitstreamEntry::SubBlock: // Handled for us already.
2056  case BitstreamEntry::Error:
2057  return error("Malformed block");
2058  case BitstreamEntry::EndBlock:
2059  return Error::success();
2060  case BitstreamEntry::Record:
2061  // The interesting case.
2062  break;
2063  }
2064 
2065  // Read a record.
2066  Record.clear();
2067  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2068  if (!MaybeRecord)
2069  return MaybeRecord.takeError();
2070  switch (MaybeRecord.get()) {
2071  default: // Default behavior: ignore.
2072  break;
2073  case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
2074  if (Record.size() < 3)
2075  return error("Invalid grp record");
2076 
2077  uint64_t GrpID = Record[0];
2078  uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
2079 
2081  for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2082  if (Record[i] == 0) { // Enum attribute
2084  if (Error Err = parseAttrKind(Record[++i], &Kind))
2085  return Err;
2086 
2087  // Upgrade old-style byval attribute to one with a type, even if it's
2088  // nullptr. We will have to insert the real type when we associate
2089  // this AttributeList with a function.
2090  if (Kind == Attribute::ByVal)
2091  B.addByValAttr(nullptr);
2092  else if (Kind == Attribute::StructRet)
2093  B.addStructRetAttr(nullptr);
2094  else if (Kind == Attribute::InAlloca)
2095  B.addInAllocaAttr(nullptr);
2096  else if (Kind == Attribute::UWTable)
2097  B.addUWTableAttr(UWTableKind::Default);
2098  else if (Attribute::isEnumAttrKind(Kind))
2099  B.addAttribute(Kind);
2100  else
2101  return error("Not an enum attribute");
2102  } else if (Record[i] == 1) { // Integer attribute
2104  if (Error Err = parseAttrKind(Record[++i], &Kind))
2105  return Err;
2106  if (!Attribute::isIntAttrKind(Kind))
2107  return error("Not an int attribute");
2108  if (Kind == Attribute::Alignment)
2109  B.addAlignmentAttr(Record[++i]);
2110  else if (Kind == Attribute::StackAlignment)
2111  B.addStackAlignmentAttr(Record[++i]);
2112  else if (Kind == Attribute::Dereferenceable)
2113  B.addDereferenceableAttr(Record[++i]);
2114  else if (Kind == Attribute::DereferenceableOrNull)
2115  B.addDereferenceableOrNullAttr(Record[++i]);
2116  else if (Kind == Attribute::AllocSize)
2117  B.addAllocSizeAttrFromRawRepr(Record[++i]);
2118  else if (Kind == Attribute::VScaleRange)
2119  B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2120  else if (Kind == Attribute::UWTable)
2121  B.addUWTableAttr(UWTableKind(Record[++i]));
2122  else if (Kind == Attribute::AllocKind)
2123  B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i]));
2124  } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
2125  bool HasValue = (Record[i++] == 4);
2126  SmallString<64> KindStr;
2127  SmallString<64> ValStr;
2128 
2129  while (Record[i] != 0 && i != e)
2130  KindStr += Record[i++];
2131  assert(Record[i] == 0 && "Kind string not null terminated");
2132 
2133  if (HasValue) {
2134  // Has a value associated with it.
2135  ++i; // Skip the '0' that terminates the "kind" string.
2136  while (Record[i] != 0 && i != e)
2137  ValStr += Record[i++];
2138  assert(Record[i] == 0 && "Value string not null terminated");
2139  }
2140 
2141  B.addAttribute(KindStr.str(), ValStr.str());
2142  } else if (Record[i] == 5 || Record[i] == 6) {
2143  bool HasType = Record[i] == 6;
2145  if (Error Err = parseAttrKind(Record[++i], &Kind))
2146  return Err;
2147  if (!Attribute::isTypeAttrKind(Kind))
2148  return error("Not a type attribute");
2149 
2150  B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
2151  } else {
2152  return error("Invalid attribute group entry");
2153  }
2154  }
2155 
2157  MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
2158  break;
2159  }
2160  }
2161  }
2162 }
2163 
2164 Error BitcodeReader::parseTypeTable() {
2165  if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
2166  return Err;
2167 
2168  return parseTypeTableBody();
2169 }
2170 
2171 Error BitcodeReader::parseTypeTableBody() {
2172  if (!TypeList.empty())
2173  return error("Invalid multiple blocks");
2174 
2176  unsigned NumRecords = 0;
2177 
2179 
2180  // Read all the records for this type table.
2181  while (true) {
2182  Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2183  if (!MaybeEntry)
2184  return MaybeEntry.takeError();
2185  BitstreamEntry Entry = MaybeEntry.get();
2186 
2187  switch (Entry.Kind) {
2188  case BitstreamEntry::SubBlock: // Handled for us already.
2189  case BitstreamEntry::Error:
2190  return error("Malformed block");
2191  case BitstreamEntry::EndBlock:
2192  if (NumRecords != TypeList.size())
2193  return error("Malformed block");
2194  return Error::success();
2195  case BitstreamEntry::Record:
2196  // The interesting case.
2197  break;
2198  }
2199 
2200  // Read a record.
2201  Record.clear();
2202  Type *ResultTy = nullptr;
2203  SmallVector<unsigned> ContainedIDs;
2204  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2205  if (!MaybeRecord)
2206  return MaybeRecord.takeError();
2207  switch (MaybeRecord.get()) {
2208  default:
2209  return error("Invalid value");
2210  case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
2211  // TYPE_CODE_NUMENTRY contains a count of the number of types in the
2212  // type list. This allows us to reserve space.
2213  if (Record.empty())
2214  return error("Invalid numentry record");
2215  TypeList.resize(Record[0]);
2216  continue;
2217  case bitc::TYPE_CODE_VOID: // VOID
2218  ResultTy = Type::getVoidTy(Context);
2219  break;
2220  case bitc::TYPE_CODE_HALF: // HALF
2221  ResultTy = Type::getHalfTy(Context);
2222  break;
2223  case bitc::TYPE_CODE_BFLOAT: // BFLOAT
2224  ResultTy = Type::getBFloatTy(Context);
2225  break;
2226  case bitc::TYPE_CODE_FLOAT: // FLOAT
2227  ResultTy = Type::getFloatTy(Context);
2228  break;
2229  case bitc::TYPE_CODE_DOUBLE: // DOUBLE
2230  ResultTy = Type::getDoubleTy(Context);
2231  break;
2232  case bitc::TYPE_CODE_X86_FP80: // X86_FP80
2233  ResultTy = Type::getX86_FP80Ty(Context);
2234  break;
2235  case bitc::TYPE_CODE_FP128: // FP128
2236  ResultTy = Type::getFP128Ty(Context);
2237  break;
2238  case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
2239  ResultTy = Type::getPPC_FP128Ty(Context);
2240  break;
2241  case bitc::TYPE_CODE_LABEL: // LABEL
2242  ResultTy = Type::getLabelTy(Context);
2243  break;
2244  case bitc::TYPE_CODE_METADATA: // METADATA
2245  ResultTy = Type::getMetadataTy(Context);
2246  break;
2247  case bitc::TYPE_CODE_X86_MMX: // X86_MMX
2248  ResultTy = Type::getX86_MMXTy(Context);
2249  break;
2250  case bitc::TYPE_CODE_X86_AMX: // X86_AMX
2251  ResultTy = Type::getX86_AMXTy(Context);
2252  break;
2253  case bitc::TYPE_CODE_TOKEN: // TOKEN
2254  ResultTy = Type::getTokenTy(Context);
2255  break;
2256  case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
2257  if (Record.empty())
2258  return error("Invalid integer record");
2259 
2260  uint64_t NumBits = Record[0];
2261  if (NumBits < IntegerType::MIN_INT_BITS ||
2262  NumBits > IntegerType::MAX_INT_BITS)
2263  return error("Bitwidth for integer type out of range");
2264  ResultTy = IntegerType::get(Context, NumBits);
2265  break;
2266  }
2267  case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
2268  // [pointee type, address space]
2269  if (Record.empty())
2270  return error("Invalid pointer record");
2271  unsigned AddressSpace = 0;
2272  if (Record.size() == 2)
2273  AddressSpace = Record[1];
2274  ResultTy = getTypeByID(Record[0]);
2275  if (!ResultTy ||
2277  return error("Invalid type");
2279  Context.setOpaquePointers(false);
2280  ContainedIDs.push_back(Record[0]);
2281  ResultTy = PointerType::get(ResultTy, AddressSpace);
2282  break;
2283  }
2284  case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
2285  if (Record.size() != 1)
2286  return error("Invalid opaque pointer record");
2288  Context.setOpaquePointers(true);
2289  } else if (Context.supportsTypedPointers())
2290  return error(
2291  "Opaque pointers are only supported in -opaque-pointers mode");
2292  unsigned AddressSpace = Record[0];
2293  ResultTy = PointerType::get(Context, AddressSpace);
2294  break;
2295  }
2297  // Deprecated, but still needed to read old bitcode files.
2298  // FUNCTION: [vararg, attrid, retty, paramty x N]
2299  if (Record.size() < 3)
2300  return error("Invalid function record");
2301  SmallVector<Type*, 8> ArgTys;
2302  for (unsigned i = 3, e = Record.size(); i != e; ++i) {
2303  if (Type *T = getTypeByID(Record[i]))
2304  ArgTys.push_back(T);
2305  else
2306  break;
2307  }
2308 
2309  ResultTy = getTypeByID(Record[2]);
2310  if (!ResultTy || ArgTys.size() < Record.size()-3)
2311  return error("Invalid type");
2312 
2313  ContainedIDs.append(Record.begin() + 2, Record.end());
2314  ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2315  break;
2316  }
2317  case bitc::TYPE_CODE_FUNCTION: {
2318  // FUNCTION: [vararg, retty, paramty x N]
2319  if (Record.size() < 2)
2320  return error("Invalid function record");
2321  SmallVector<Type*, 8> ArgTys;
2322  for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2323  if (Type *T = getTypeByID(Record[i])) {
2324  if (!FunctionType::isValidArgumentType(T))
2325  return error("Invalid function argument type");
2326  ArgTys.push_back(T);
2327  }
2328  else
2329  break;
2330  }
2331 
2332  ResultTy = getTypeByID(Record[1]);
2333  if (!ResultTy || ArgTys.size() < Record.size()-2)
2334  return error("Invalid type");
2335 
2336  ContainedIDs.append(Record.begin() + 1, Record.end());
2337  ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2338  break;
2339  }
2340  case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
2341  if (Record.empty())
2342  return error("Invalid anon struct record");
2343  SmallVector<Type*, 8> EltTys;
2344  for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2345  if (Type *T = getTypeByID(Record[i]))
2346  EltTys.push_back(T);
2347  else
2348  break;
2349  }
2350  if (EltTys.size() != Record.size()-1)
2351  return error("Invalid type");
2352  ContainedIDs.append(Record.begin() + 1, Record.end());
2353  ResultTy = StructType::get(Context, EltTys, Record[0]);
2354  break;
2355  }
2356  case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
2357  if (convertToString(Record, 0, TypeName))
2358  return error("Invalid struct name record");
2359  continue;
2360 
2361  case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
2362  if (Record.empty())
2363  return error("Invalid named struct record");
2364 
2365  if (NumRecords >= TypeList.size())
2366  return error("Invalid TYPE table");
2367 
2368  // Check to see if this was forward referenced, if so fill in the temp.
2369  StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2370  if (Res) {
2371  Res->setName(TypeName);
2372  TypeList[NumRecords] = nullptr;
2373  } else // Otherwise, create a new struct.
2374  Res = createIdentifiedStructType(Context, TypeName);
2375  TypeName.clear();
2376 
2377  SmallVector<Type*, 8> EltTys;
2378  for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2379  if (Type *T = getTypeByID(Record[i]))
2380  EltTys.push_back(T);
2381  else
2382  break;
2383  }
2384  if (EltTys.size() != Record.size()-1)
2385  return error("Invalid named struct record");
2386  Res->setBody(EltTys, Record[0]);
2387  ContainedIDs.append(Record.begin() + 1, Record.end());
2388  ResultTy = Res;
2389  break;
2390  }
2391  case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
2392  if (Record.size() != 1)
2393  return error("Invalid opaque type record");
2394 
2395  if (NumRecords >= TypeList.size())
2396  return error("Invalid TYPE table");
2397 
2398  // Check to see if this was forward referenced, if so fill in the temp.
2399  StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2400  if (Res) {
2401  Res->setName(TypeName);
2402  TypeList[NumRecords] = nullptr;
2403  } else // Otherwise, create a new struct with no body.
2404  Res = createIdentifiedStructType(Context, TypeName);
2405  TypeName.clear();
2406  ResultTy = Res;
2407  break;
2408  }
2409  case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
2410  if (Record.size() < 2)
2411  return error("Invalid array type record");
2412  ResultTy = getTypeByID(Record[1]);
2413  if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2414  return error("Invalid type");
2415  ContainedIDs.push_back(Record[1]);
2416  ResultTy = ArrayType::get(ResultTy, Record[0]);
2417  break;
2418  case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or
2419  // [numelts, eltty, scalable]
2420  if (Record.size() < 2)
2421  return error("Invalid vector type record");
2422  if (Record[0] == 0)
2423  return error("Invalid vector length");
2424  ResultTy = getTypeByID(Record[1]);
2425  if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2426  return error("Invalid type");
2427  bool Scalable = Record.size() > 2 ? Record[2] : false;
2428  ContainedIDs.push_back(Record[1]);
2429  ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2430  break;
2431  }
2432 
2433  if (NumRecords >= TypeList.size())
2434  return error("Invalid TYPE table");
2435  if (TypeList[NumRecords])
2436  return error(
2437  "Invalid TYPE table: Only named structs can be forward referenced");
2438  assert(ResultTy && "Didn't read a type?");
2439  TypeList[NumRecords] = ResultTy;
2440  if (!ContainedIDs.empty())
2441  ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2442  ++NumRecords;
2443  }
2444 }
2445 
2446 Error BitcodeReader::parseOperandBundleTags() {
2447  if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
2448  return Err;
2449 
2450  if (!BundleTags.empty())
2451  return error("Invalid multiple blocks");
2452 
2454 
2455  while (true) {
2456  Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2457  if (!MaybeEntry)
2458  return MaybeEntry.takeError();
2459  BitstreamEntry Entry = MaybeEntry.get();
2460 
2461  switch (Entry.Kind) {
2462  case BitstreamEntry::SubBlock: // Handled for us already.
2463  case BitstreamEntry::Error:
2464  return error("Malformed block");
2465  case BitstreamEntry::EndBlock:
2466  return Error::success();
2467  case BitstreamEntry::Record:
2468  // The interesting case.
2469  break;
2470  }
2471 
2472  // Tags are implicitly mapped to integers by their order.
2473 
2474  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2475  if (!MaybeRecord)
2476  return MaybeRecord.takeError();
2477  if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
2478  return error("Invalid operand bundle record");
2479 
2480  // OPERAND_BUNDLE_TAG: [strchr x N]
2481  BundleTags.emplace_back();
2482  if (convertToString(Record, 0, BundleTags.back()))
2483  return error("Invalid operand bundle record");
2484  Record.clear();
2485  }
2486 }
2487 
2488 Error BitcodeReader::parseSyncScopeNames() {
2489  if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2490  return Err;
2491 
2492  if (!SSIDs.empty())
2493  return error("Invalid multiple synchronization scope names blocks");
2494 
2496  while (true) {
2497  Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2498  if (!MaybeEntry)
2499  return MaybeEntry.takeError();
2500  BitstreamEntry Entry = MaybeEntry.get();
2501 
2502  switch (Entry.Kind) {
2503  case BitstreamEntry::SubBlock: // Handled for us already.
2504  case BitstreamEntry::Error:
2505  return error("Malformed block");
2506  case BitstreamEntry::EndBlock:
2507  if (SSIDs.empty())
2508  return error("Invalid empty synchronization scope names block");
2509  return Error::success();
2510  case BitstreamEntry::Record:
2511  // The interesting case.
2512  break;
2513  }
2514 
2515  // Synchronization scope names are implicitly mapped to synchronization
2516  // scope IDs by their order.
2517 
2518  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2519  if (!MaybeRecord)
2520  return MaybeRecord.takeError();
2521  if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2522  return error("Invalid sync scope record");
2523 
2524  SmallString<16> SSN;
2525  if (convertToString(Record, 0, SSN))
2526  return error("Invalid sync scope record");
2527 
2528  SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2529  Record.clear();
2530  }
2531 }
2532 
2533 /// Associate a value with its name from the given index in the provided record.
2534 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2535  unsigned NameIndex, Triple &TT) {
2537  if (convertToString(Record, NameIndex, ValueName))
2538  return error("Invalid record");
2539  unsigned ValueID = Record[0];
2540  if (ValueID >= ValueList.size() || !ValueList[ValueID])
2541  return error("Invalid record");
2542  Value *V = ValueList[ValueID];
2543 
2544  StringRef NameStr(ValueName.data(), ValueName.size());
2545  if (NameStr.find_first_of(0) != StringRef::npos)
2546  return error("Invalid value name");
2547  V->setName(NameStr);
2548  auto *GO = dyn_cast<GlobalObject>(V);
2549  if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
2550  GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2551  return V;
2552 }
2553 
2554 /// Helper to note and return the current location, and jump to the given
2555 /// offset.
2557  BitstreamCursor &Stream) {
2558  // Save the current parsing location so we can jump back at the end
2559  // of the VST read.
2560  uint64_t CurrentBit = Stream.GetCurrentBitNo();
2561  if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2562  return std::move(JumpFailed);
2563  Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2564  if (!MaybeEntry)
2565  return MaybeEntry.takeError();
2566  if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
2567  MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
2568  return error("Expected value symbol table subblock");
2569  return CurrentBit;
2570 }
2571 
2572 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2573  Function *F,
2575  // Note that we subtract 1 here because the offset is relative to one word
2576  // before the start of the identification or module block, which was
2577  // historically always the start of the regular bitcode header.
2578  uint64_t FuncWordOffset = Record[1] - 1;
2579  uint64_t FuncBitOffset = FuncWordOffset * 32;
2580  DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2581  // Set the LastFunctionBlockBit to point to the last function block.
2582  // Later when parsing is resumed after function materialization,
2583  // we can simply skip that last function block.
2584  if (FuncBitOffset > LastFunctionBlockBit)
2585  LastFunctionBlockBit = FuncBitOffset;
2586 }
2587 
2588 /// Read a new-style GlobalValue symbol table.
2589 Error BitcodeReader::parseGlobalValueSymbolTable() {
2590  unsigned FuncBitcodeOffsetDelta =
2591  Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2592 
2593  if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2594  return Err;
2595 
2597  while (true) {
2598  Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2599  if (!MaybeEntry)
2600  return MaybeEntry.takeError();
2601  BitstreamEntry Entry = MaybeEntry.get();
2602 
2603  switch (Entry.Kind) {
2604  case BitstreamEntry::SubBlock:
2605  case BitstreamEntry::Error:
2606  return error("Malformed block");
2607  case BitstreamEntry::EndBlock:
2608  return Error::success();
2609  case BitstreamEntry::Record:
2610  break;
2611  }
2612 
2613  Record.clear();
2614  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2615  if (!MaybeRecord)
2616  return MaybeRecord.takeError();
2617  switch (MaybeRecord.get()) {
2618  case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
2619  unsigned ValueID = Record[0];
2620  if (ValueID >= ValueList.size() || !ValueList[ValueID])
2621  return error("Invalid value reference in symbol table");
2622  setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2623  cast<Function>(ValueList[ValueID]), Record);
2624  break;
2625  }
2626  }
2627  }
2628 }
2629 
2630 /// Parse the value symbol table at either the current parsing location or
2631 /// at the given bit offset if provided.
2632 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
2633  uint64_t CurrentBit;
2634  // Pass in the Offset to distinguish between calling for the module-level
2635  // VST (where we want to jump to the VST offset) and the function-level
2636  // VST (where we don't).
2637  if (Offset > 0) {
2638  Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2639  if (!MaybeCurrentBit)
2640  return MaybeCurrentBit.takeError();
2641  CurrentBit = MaybeCurrentBit.get();
2642  // If this module uses a string table, read this as a module-level VST.
2643  if (UseStrtab) {
2644  if (Error Err = parseGlobalValueSymbolTable())
2645  return Err;
2646  if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2647  return JumpFailed;
2648  return Error::success();
2649  }
2650  // Otherwise, the VST will be in a similar format to a function-level VST,
2651  // and will contain symbol names.
2652  }
2653 
2654  // Compute the delta between the bitcode indices in the VST (the word offset
2655  // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2656  // expected by the lazy reader. The reader's EnterSubBlock expects to have
2657  // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2658  // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2659  // just before entering the VST subblock because: 1) the EnterSubBlock
2660  // changes the AbbrevID width; 2) the VST block is nested within the same
2661  // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2662  // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2663  // jump to the FUNCTION_BLOCK using this offset later, we don't want
2664  // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2665  unsigned FuncBitcodeOffsetDelta =
2666  Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2667 
2668  if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2669  return Err;
2670 
2672 
2673  Triple TT(TheModule->getTargetTriple());
2674 
2675  // Read all the records for this value table.
2677 
2678  while (true) {
2679  Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2680  if (!MaybeEntry)
2681  return MaybeEntry.takeError();
2682  BitstreamEntry Entry = MaybeEntry.get();
2683 
2684  switch (Entry.Kind) {
2685  case BitstreamEntry::SubBlock: // Handled for us already.
2686  case BitstreamEntry::Error:
2687  return error("Malformed block");
2688  case BitstreamEntry::EndBlock:
2689  if (Offset > 0)
2690  if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2691  return JumpFailed;
2692  return Error::success();
2693  case BitstreamEntry::Record:
2694  // The interesting case.
2695  break;
2696  }
2697 
2698  // Read a record.
2699  Record.clear();
2700  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2701  if (!MaybeRecord)
2702  return MaybeRecord.takeError();
2703  switch (MaybeRecord.get()) {
2704  default: // Default behavior: unknown type.
2705  break;
2706  case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
2707  Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2708  if (Error Err = ValOrErr.takeError())
2709  return Err;
2710  ValOrErr.get();
2711  break;
2712  }
2713  case bitc::VST_CODE_FNENTRY: {
2714  // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2715  Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2716  if (Error Err = ValOrErr.takeError())
2717  return Err;
2718  Value *V = ValOrErr.get();
2719 
2720  // Ignore function offsets emitted for aliases of functions in older
2721  // versions of LLVM.
2722  if (auto *F = dyn_cast<Function>(V))
2723  setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2724  break;
2725  }
2726  case bitc::VST_CODE_BBENTRY: {
2727  if (convertToString(Record, 1, ValueName))
2728  return error("Invalid bbentry record");
2729  BasicBlock *BB = getBasicBlock(Record[0]);
2730  if (!BB)
2731  return error("Invalid bbentry record");
2732 
2733  BB->setName(StringRef(ValueName.data(), ValueName.size()));
2734  ValueName.clear();
2735  break;
2736  }
2737  }
2738  }
2739 }
2740 
2741 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2742 /// encoding.
2744  if ((V & 1) == 0)
2745  return V >> 1;
2746  if (V != 1)
2747  return -(V >> 1);
2748  // There is no such thing as -0 with integers. "-0" really means MININT.
2749  return 1ULL << 63;
2750 }
2751 
2752 /// Resolve all of the initializers for global values and aliases that we can.
2753 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2754  std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2755  std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
2756  std::vector<FunctionOperandInfo> FunctionOperandWorklist;
2757 
2758  GlobalInitWorklist.swap(GlobalInits);
2759  IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2760  FunctionOperandWorklist.swap(FunctionOperands);
2761 
2762  while (!GlobalInitWorklist.empty()) {
2763  unsigned ValID = GlobalInitWorklist.back().second;
2764  if (ValID >= ValueList.size()) {
2765  // Not ready to resolve this yet, it requires something later in the file.
2766  GlobalInits.push_back(GlobalInitWorklist.back());
2767  } else {
2768  Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2769  if (!MaybeC)
2770  return MaybeC.takeError();
2771  GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
2772  }
2773  GlobalInitWorklist.pop_back();
2774  }
2775 
2776  while (!IndirectSymbolInitWorklist.empty()) {
2777  unsigned ValID = IndirectSymbolInitWorklist.back().second;
2778  if (ValID >= ValueList.size()) {
2779  IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2780  } else {
2781  Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2782  if (!MaybeC)
2783  return MaybeC.takeError();
2784  Constant *C = MaybeC.get();
2785  GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
2786  if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
2787  if (C->getType() != GV->getType())
2788  return error("Alias and aliasee types don't match");
2789  GA->setAliasee(C);
2790  } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
2791  Type *ResolverFTy =
2792  GlobalIFunc::getResolverFunctionType(GI->getValueType());
2793  // Transparently fix up the type for compatibility with older bitcode
2794  GI->setResolver(
2795  ConstantExpr::getBitCast(C, ResolverFTy->getPointerTo()));
2796  } else {
2797  return error("Expected an alias or an ifunc");
2798  }
2799  }
2800  IndirectSymbolInitWorklist.pop_back();
2801  }
2802 
2803  while (!FunctionOperandWorklist.empty()) {
2804  FunctionOperandInfo &Info = FunctionOperandWorklist.back();
2805  if (Info.PersonalityFn) {
2806  unsigned ValID = Info.PersonalityFn - 1;
2807  if (ValID < ValueList.size()) {
2808  Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2809  if (!MaybeC)
2810  return MaybeC.takeError();
2811  Info.F->setPersonalityFn(MaybeC.get());
2812  Info.PersonalityFn = 0;
2813  }
2814  }
2815  if (Info.Prefix) {
2816  unsigned ValID = Info.Prefix - 1;
2817  if (ValID < ValueList.size()) {
2818  Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2819  if (!MaybeC)
2820  return MaybeC.takeError();
2821  Info.F->setPrefixData(MaybeC.get());
2822  Info.Prefix = 0;
2823  }
2824  }
2825  if (Info.Prologue) {
2826  unsigned ValID = Info.Prologue - 1;
2827  if (ValID < ValueList.size()) {
2828  Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2829  if (!MaybeC)
2830  return MaybeC.takeError();
2831  Info.F->setPrologueData(MaybeC.get());
2832  Info.Prologue = 0;
2833  }
2834  }
2835  if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
2836  FunctionOperands.push_back(Info);
2837  FunctionOperandWorklist.pop_back();
2838  }
2839 
2840  return Error::success();
2841 }
2842 
2844  SmallVector<uint64_t, 8> Words(Vals.size());
2845  transform(Vals, Words.begin(),
2847 
2848  return APInt(TypeBits, Words);
2849 }
2850 
2851 Error BitcodeReader::parseConstants() {
2852  if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2853  return Err;
2854 
2856 
2857  // Read all the records for this value table.
2858  Type *CurTy = Type::getInt32Ty(Context);
2859  unsigned Int32TyID = getVirtualTypeID(CurTy);
2860  unsigned CurTyID = Int32TyID;
2861  Type *CurElemTy = nullptr;
2862  unsigned NextCstNo = ValueList.size();
2863 
2864  while (true) {
2865  Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2866  if (!MaybeEntry)
2867  return MaybeEntry.takeError();
2868  BitstreamEntry Entry = MaybeEntry.get();
2869 
2870  switch (Entry.Kind) {
2871  case BitstreamEntry::SubBlock: // Handled for us already.
2872  case BitstreamEntry::Error:
2873  return error("Malformed block");
2874  case BitstreamEntry::EndBlock:
2875  if (NextCstNo != ValueList.size())
2876  return error("Invalid constant reference");
2877  return Error::success();
2878  case BitstreamEntry::Record:
2879  // The interesting case.
2880  break;
2881  }
2882 
2883  // Read a record.
2884  Record.clear();
2885  Type *VoidType = Type::getVoidTy(Context);
2886  Value *V = nullptr;
2887  Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
2888  if (!MaybeBitCode)
2889  return MaybeBitCode.takeError();
2890  switch (unsigned BitCode = MaybeBitCode.get()) {
2891  default: // Default behavior: unknown constant
2892  case bitc::CST_CODE_UNDEF: // UNDEF
2893  V = UndefValue::get(CurTy);
2894  break;
2895  case bitc::CST_CODE_POISON: // POISON
2896  V = PoisonValue::get(CurTy);
2897  break;
2898  case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2899  if (Record.empty())
2900  return error("Invalid settype record");
2901  if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
2902  return error("Invalid settype record");
2903  if (TypeList[Record[0]] == VoidType)
2904  return error("Invalid constant type");
2905  CurTyID = Record[0];
2906  CurTy = TypeList[CurTyID];
2907  CurElemTy = getPtrElementTypeByID(CurTyID);
2908  continue; // Skip the ValueList manipulation.
2909  case bitc::CST_CODE_NULL: // NULL
2910  if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
2911  return error("Invalid type for a constant null value");
2912  V = Constant::getNullValue(CurTy);
2913  break;
2914  case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
2915  if (!CurTy->isIntegerTy() || Record.empty())
2916  return error("Invalid integer const record");
2918  break;
2919  case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2920  if (!CurTy->isIntegerTy() || Record.empty())
2921  return error("Invalid wide integer const record");
2922 
2923  APInt VInt =
2924  readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2925  V = ConstantInt::get(Context, VInt);
2926 
2927  break;
2928  }
2929  case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2930  if (Record.empty())
2931  return error("Invalid float const record");
2932  if (CurTy->isHalfTy())
2933  V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2934  APInt(16, (uint16_t)Record[0])));
2935  else if (CurTy->isBFloatTy())
2936  V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
2937  APInt(16, (uint32_t)Record[0])));
2938  else if (CurTy->isFloatTy())
2939  V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2940  APInt(32, (uint32_t)Record[0])));
2941  else if (CurTy->isDoubleTy())
2942  V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2943  APInt(64, Record[0])));
2944  else if (CurTy->isX86_FP80Ty()) {
2945  // Bits are not stored the same way as a normal i80 APInt, compensate.
2946  uint64_t Rearrange[2];
2947  Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2948  Rearrange[1] = Record[0] >> 48;
2949  V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2950  APInt(80, Rearrange)));
2951  } else if (CurTy->isFP128Ty())
2952  V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2953  APInt(128, Record)));
2954  else if (CurTy->isPPC_FP128Ty())
2955  V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2956  APInt(128, Record)));
2957  else
2958  V = UndefValue::get(CurTy);
2959  break;
2960  }
2961 
2962  case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2963  if (Record.empty())
2964  return error("Invalid aggregate record");
2965 
2966  unsigned Size = Record.size();
2968  for (unsigned i = 0; i != Size; ++i)
2969  Elts.push_back(Record[i]);
2970 
2971  if (isa<StructType>(CurTy)) {
2972  V = BitcodeConstant::create(
2973  Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
2974  } else if (isa<ArrayType>(CurTy)) {
2975  V = BitcodeConstant::create(Alloc, CurTy,
2976  BitcodeConstant::ConstantArrayOpcode, Elts);
2977  } else if (isa<VectorType>(CurTy)) {
2978  V = BitcodeConstant::create(
2979  Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
2980  } else {
2981  V = UndefValue::get(CurTy);
2982  }
2983  break;
2984  }
2985  case bitc::CST_CODE_STRING: // STRING: [values]
2986  case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2987  if (Record.empty())
2988  return error("Invalid string record");
2989 
2990  SmallString<16> Elts(Record.begin(), Record.end());
2991  V = ConstantDataArray::getString(Context, Elts,
2992  BitCode == bitc::CST_CODE_CSTRING);
2993  break;
2994  }
2995  case bitc::CST_CODE_DATA: {// DATA: [n x value]
2996  if (Record.empty())
2997  return error("Invalid data record");
2998 
2999  Type *EltTy;
3000  if (auto *Array = dyn_cast<ArrayType>(CurTy))
3001  EltTy = Array->getElementType();
3002  else
3003  EltTy = cast<VectorType>(CurTy)->getElementType();
3004  if (EltTy->isIntegerTy(8)) {
3005  SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3006  if (isa<VectorType>(CurTy))
3007  V = ConstantDataVector::get(Context, Elts);
3008  else
3009  V = ConstantDataArray::get(Context, Elts);
3010  } else if (EltTy->isIntegerTy(16)) {
3011  SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3012  if (isa<VectorType>(CurTy))
3013  V = ConstantDataVector::get(Context, Elts);
3014  else
3015  V = ConstantDataArray::get(Context, Elts);
3016  } else if (EltTy->isIntegerTy(32)) {
3017  SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3018  if (isa<VectorType>(CurTy))
3019  V = ConstantDataVector::get(Context, Elts);
3020  else
3021  V = ConstantDataArray::get(Context, Elts);
3022  } else if (EltTy->isIntegerTy(64)) {
3023  SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3024  if (isa<VectorType>(CurTy))
3025  V = ConstantDataVector::get(Context, Elts);
3026  else
3027  V = ConstantDataArray::get(Context, Elts);
3028  } else if (EltTy->isHalfTy()) {
3029  SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3030  if (isa<VectorType>(CurTy))
3031  V = ConstantDataVector::getFP(EltTy, Elts);
3032  else
3033  V = ConstantDataArray::getFP(EltTy, Elts);
3034  } else if (EltTy->isBFloatTy()) {
3035  SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3036  if (isa<VectorType>(CurTy))
3037  V = ConstantDataVector::getFP(EltTy, Elts);
3038  else
3039  V = ConstantDataArray::getFP(EltTy, Elts);
3040  } else if (EltTy->isFloatTy()) {
3041  SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3042  if (isa<VectorType>(CurTy))
3043  V = ConstantDataVector::getFP(EltTy, Elts);
3044  else
3045  V = ConstantDataArray::getFP(EltTy, Elts);
3046  } else if (EltTy->isDoubleTy()) {
3047  SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3048  if (isa<VectorType>(CurTy))
3049  V = ConstantDataVector::getFP(EltTy, Elts);
3050  else
3051  V = ConstantDataArray::getFP(EltTy, Elts);
3052  } else {
3053  return error("Invalid type for value");
3054  }
3055  break;
3056  }
3057  case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
3058  if (Record.size() < 2)
3059  return error("Invalid unary op constexpr record");
3060  int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
3061  if (Opc < 0) {
3062  V = UndefValue::get(CurTy); // Unknown unop.
3063  } else {
3064  V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]);
3065  }
3066  break;
3067  }
3068  case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
3069  if (Record.size() < 3)
3070  return error("Invalid binary op constexpr record");
3071  int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
3072  if (Opc < 0) {
3073  V = UndefValue::get(CurTy); // Unknown binop.
3074  } else {
3075  uint8_t Flags = 0;
3076  if (Record.size() >= 4) {
3077  if (Opc == Instruction::Add ||
3078  Opc == Instruction::Sub ||
3079  Opc == Instruction::Mul ||
3080  Opc == Instruction::Shl) {
3081  if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3082  Flags |= OverflowingBinaryOperator::NoSignedWrap;
3083  if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3084  Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3085  } else if (Opc == Instruction::SDiv ||
3086  Opc == Instruction::UDiv ||
3087  Opc == Instruction::LShr ||
3088  Opc == Instruction::AShr) {
3089  if (Record[3] & (1 << bitc::PEO_EXACT))
3090  Flags |= SDivOperator::IsExact;
3091  }
3092  }
3093  V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags},
3094  {(unsigned)Record[1], (unsigned)Record[2]});
3095  }
3096  break;
3097  }
3098  case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
3099  if (Record.size() < 3)
3100  return error("Invalid cast constexpr record");
3101  int Opc = getDecodedCastOpcode(Record[0]);
3102  if (Opc < 0) {
3103  V = UndefValue::get(CurTy); // Unknown cast.
3104  } else {
3105  unsigned OpTyID = Record[1];
3106  Type *OpTy = getTypeByID(OpTyID);
3107  if (!OpTy)
3108  return error("Invalid cast constexpr record");
3109  V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]);
3110  }
3111  break;
3112  }
3113  case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
3114  case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
3115  case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
3116  // operands]
3117  if (Record.size() < 2)
3118  return error("Constant GEP record must have at least two elements");
3119  unsigned OpNum = 0;
3120  Type *PointeeType = nullptr;
3122  Record.size() % 2)
3123  PointeeType = getTypeByID(Record[OpNum++]);
3124 
3125  bool InBounds = false;
3126  Optional<unsigned> InRangeIndex;
3128  uint64_t Op = Record[OpNum++];
3129  InBounds = Op & 1;
3130  InRangeIndex = Op >> 1;
3131  } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
3132  InBounds = true;
3133 
3135  unsigned BaseTypeID = Record[OpNum];
3136  while (OpNum != Record.size()) {
3137  unsigned ElTyID = Record[OpNum++];
3138  Type *ElTy = getTypeByID(ElTyID);
3139  if (!ElTy)
3140  return error("Invalid getelementptr constexpr record");
3141  Elts.push_back(Record[OpNum++]);
3142  }
3143 
3144  if (Elts.size() < 1)
3145  return error("Invalid gep with no operands");
3146 
3147  Type *BaseType = getTypeByID(BaseTypeID);
3148  if (isa<VectorType>(BaseType)) {
3149  BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3150  BaseType = getTypeByID(BaseTypeID);
3151  }
3152 
3153  PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType);
3154  if (!OrigPtrTy)
3155  return error("GEP base operand must be pointer or vector of pointer");
3156 
3157  if (!PointeeType) {
3158  PointeeType = getPtrElementTypeByID(BaseTypeID);
3159  if (!PointeeType)
3160  return error("Missing element type for old-style constant GEP");
3161  } else if (!OrigPtrTy->isOpaqueOrPointeeTypeMatches(PointeeType))
3162  return error("Explicit gep operator type does not match pointee type "
3163  "of pointer operand");
3164 
3165  V = BitcodeConstant::create(Alloc, CurTy,
3166  {Instruction::GetElementPtr, InBounds,
3167  InRangeIndex.value_or(-1), PointeeType},
3168  Elts);
3169  break;
3170  }
3171  case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
3172  if (Record.size() < 3)
3173  return error("Invalid select constexpr record");
3174 
3175  V = BitcodeConstant::create(
3176  Alloc, CurTy, Instruction::Select,
3177  {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3178  break;
3179  }
3181  : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3182  if (Record.size() < 3)
3183  return error("Invalid extractelement constexpr record");
3184  unsigned OpTyID = Record[0];
3185  VectorType *OpTy =
3186  dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
3187  if (!OpTy)
3188  return error("Invalid extractelement constexpr record");
3189  unsigned IdxRecord;
3190  if (Record.size() == 4) {
3191  unsigned IdxTyID = Record[2];
3192  Type *IdxTy = getTypeByID(IdxTyID);
3193  if (!IdxTy)
3194  return error("Invalid extractelement constexpr record");
3195  IdxRecord = Record[3];
3196  } else {
3197  // Deprecated, but still needed to read old bitcode files.
3198  IdxRecord = Record[2];
3199  }
3200  V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
3201  {(unsigned)Record[1], IdxRecord});
3202  break;
3203  }
3205  : { // CE_INSERTELT: [opval, opval, opty, opval]
3206  VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3207  if (Record.size() < 3 || !OpTy)
3208  return error("Invalid insertelement constexpr record");
3209  unsigned IdxRecord;
3210  if (Record.size() == 4) {
3211  unsigned IdxTyID = Record[2];
3212  Type *IdxTy = getTypeByID(IdxTyID);
3213  if (!IdxTy)
3214  return error("Invalid insertelement constexpr record");
3215  IdxRecord = Record[3];
3216  } else {
3217  // Deprecated, but still needed to read old bitcode files.
3218  IdxRecord = Record[2];
3219  }
3220  V = BitcodeConstant::create(
3221  Alloc, CurTy, Instruction::InsertElement,
3222  {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
3223  break;
3224  }
3225  case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
3226  VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3227  if (Record.size() < 3 || !OpTy)
3228  return error("Invalid shufflevector constexpr record");
3229  V = BitcodeConstant::create(
3230  Alloc, CurTy, Instruction::ShuffleVector,
3231  {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3232  break;
3233  }
3234  case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
3235  VectorType *RTy = dyn_cast<VectorType>(CurTy);
3236  VectorType *OpTy =
3237  dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3238  if (Record.size() < 4 || !RTy || !OpTy)
3239  return error("Invalid shufflevector constexpr record");
3240  V = BitcodeConstant::create(
3241  Alloc, CurTy, Instruction::ShuffleVector,
3242  {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]});
3243  break;
3244  }
3245  case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
3246  if (Record.size() < 4)
3247  return error("Invalid cmp constexpt record");
3248  unsigned OpTyID = Record[0];
3249  Type *OpTy = getTypeByID(OpTyID);
3250  if (!OpTy)
3251  return error("Invalid cmp constexpr record");
3252  V = BitcodeConstant::create(
3253  Alloc, CurTy,
3254  {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
3255  : Instruction::ICmp),
3256  (uint8_t)Record[3]},
3257  {(unsigned)Record[1], (unsigned)Record[2]});
3258  break;
3259  }
3260  // This maintains backward compatibility, pre-asm dialect keywords.
3261  // Deprecated, but still needed to read old bitcode files.
3263  if (Record.size() < 2)
3264  return error("Invalid inlineasm record");
3265  std::string AsmStr, ConstrStr;
3266  bool HasSideEffects = Record[0] & 1;
3267  bool IsAlignStack = Record[0] >> 1;
3268  unsigned AsmStrSize = Record[1];
3269  if (2+AsmStrSize >= Record.size())
3270  return error("Invalid inlineasm record");
3271  unsigned ConstStrSize = Record[2+AsmStrSize];
3272  if (3+AsmStrSize+ConstStrSize > Record.size())
3273  return error("Invalid inlineasm record");
3274 
3275  for (unsigned i = 0; i != AsmStrSize; ++i)
3276  AsmStr += (char)Record[2+i];
3277  for (unsigned i = 0; i != ConstStrSize; ++i)
3278  ConstrStr += (char)Record[3+AsmStrSize+i];
3279  UpgradeInlineAsmString(&AsmStr);
3280  if (!CurElemTy)
3281  return error("Missing element type for old-style inlineasm");
3282  V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3283  HasSideEffects, IsAlignStack);
3284  break;
3285  }
3286  // This version adds support for the asm dialect keywords (e.g.,
3287  // inteldialect).
3289  if (Record.size() < 2)
3290  return error("Invalid inlineasm record");
3291  std::string AsmStr, ConstrStr;
3292  bool HasSideEffects = Record[0] & 1;
3293  bool IsAlignStack = (Record[0] >> 1) & 1;
3294  unsigned AsmDialect = Record[0] >> 2;
3295  unsigned AsmStrSize = Record[1];
3296  if (2+AsmStrSize >= Record.size())
3297  return error("Invalid inlineasm record");
3298  unsigned ConstStrSize = Record[2+AsmStrSize];
3299  if (3+AsmStrSize+ConstStrSize > Record.size())
3300  return error("Invalid inlineasm record");
3301 
3302  for (unsigned i = 0; i != AsmStrSize; ++i)
3303  AsmStr += (char)Record[2+i];
3304  for (unsigned i = 0; i != ConstStrSize; ++i)
3305  ConstrStr += (char)Record[3+AsmStrSize+i];
3306  UpgradeInlineAsmString(&AsmStr);
3307  if (!CurElemTy)
3308  return error("Missing element type for old-style inlineasm");
3309  V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3310  HasSideEffects, IsAlignStack,
3311  InlineAsm::AsmDialect(AsmDialect));
3312  break;
3313  }
3314  // This version adds support for the unwind keyword.
3316  if (Record.size() < 2)
3317  return error("Invalid inlineasm record");
3318  unsigned OpNum = 0;
3319  std::string AsmStr, ConstrStr;
3320  bool HasSideEffects = Record[OpNum] & 1;
3321  bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3322  unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3323  bool CanThrow = (Record[OpNum] >> 3) & 1;
3324  ++OpNum;
3325  unsigned AsmStrSize = Record[OpNum];
3326  ++OpNum;
3327  if (OpNum + AsmStrSize >= Record.size())
3328  return error("Invalid inlineasm record");
3329  unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3330  if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3331  return error("Invalid inlineasm record");
3332 
3333  for (unsigned i = 0; i != AsmStrSize; ++i)
3334  AsmStr += (char)Record[OpNum + i];
3335  ++OpNum;
3336  for (unsigned i = 0; i != ConstStrSize; ++i)
3337  ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3338  UpgradeInlineAsmString(&AsmStr);
3339  if (!CurElemTy)
3340  return error("Missing element type for old-style inlineasm");
3341  V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3342  HasSideEffects, IsAlignStack,
3343  InlineAsm::AsmDialect(AsmDialect), CanThrow);
3344  break;
3345  }
3346  // This version adds explicit function type.
3347  case bitc::CST_CODE_INLINEASM: {
3348  if (Record.size() < 3)
3349  return error("Invalid inlineasm record");
3350  unsigned OpNum = 0;
3351  auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
3352  ++OpNum;
3353  if (!FnTy)
3354  return error("Invalid inlineasm record");
3355  std::string AsmStr, ConstrStr;
3356  bool HasSideEffects = Record[OpNum] & 1;
3357  bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3358  unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3359  bool CanThrow = (Record[OpNum] >> 3) & 1;
3360  ++OpNum;
3361  unsigned AsmStrSize = Record[OpNum];
3362  ++OpNum;
3363  if (OpNum + AsmStrSize >= Record.size())
3364  return error("Invalid inlineasm record");
3365  unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3366  if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3367  return error("Invalid inlineasm record");
3368 
3369  for (unsigned i = 0; i != AsmStrSize; ++i)
3370  AsmStr += (char)Record[OpNum + i];
3371  ++OpNum;
3372  for (unsigned i = 0; i != ConstStrSize; ++i)
3373  ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3374  UpgradeInlineAsmString(&AsmStr);
3375  V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3376  InlineAsm::AsmDialect(AsmDialect), CanThrow);
3377  break;
3378  }
3380  if (Record.size() < 3)
3381  return error("Invalid blockaddress record");
3382  unsigned FnTyID = Record[0];
3383  Type *FnTy = getTypeByID(FnTyID);
3384  if (!FnTy)
3385  return error("Invalid blockaddress record");
3386  V = BitcodeConstant::create(
3387  Alloc, CurTy,
3388  {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3389  Record[1]);
3390  break;
3391  }
3393  if (Record.size() < 2)
3394  return error("Invalid dso_local record");
3395  unsigned GVTyID = Record[0];
3396  Type *GVTy = getTypeByID(GVTyID);
3397  if (!GVTy)
3398  return error("Invalid dso_local record");
3399  V = BitcodeConstant::create(
3400  Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3401  break;
3402  }
3404  if (Record.size() < 2)
3405  return error("Invalid no_cfi record");
3406  unsigned GVTyID = Record[0];
3407  Type *GVTy = getTypeByID(GVTyID);
3408  if (!GVTy)
3409  return error("Invalid no_cfi record");
3410  V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3411  Record[1]);
3412  break;
3413  }
3414  }
3415 
3416  assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
3417  if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))
3418  return Err;
3419  ++NextCstNo;
3420  }
3421 }
3422 
3423 Error BitcodeReader::parseUseLists() {
3424  if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3425  return Err;
3426 
3427  // Read all the records.
3429 
3430  while (true) {
3431  Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3432  if (!MaybeEntry)
3433  return MaybeEntry.takeError();
3434  BitstreamEntry Entry = MaybeEntry.get();
3435 
3436  switch (Entry.Kind) {
3437  case BitstreamEntry::SubBlock: // Handled for us already.
3438  case BitstreamEntry::Error:
3439  return error("Malformed block");
3440  case BitstreamEntry::EndBlock:
3441  return Error::success();
3442  case BitstreamEntry::Record:
3443  // The interesting case.
3444  break;
3445  }
3446 
3447  // Read a use list record.
3448  Record.clear();
3449  bool IsBB = false;
3450  Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3451  if (!MaybeRecord)
3452  return MaybeRecord.takeError();
3453  switch (MaybeRecord.get()) {
3454  default: // Default behavior: unknown type.
3455  break;
3456  case bitc::USELIST_CODE_BB:
3457  IsBB = true;
3458  [[fallthrough]];
3460  unsigned RecordLength = Record.size();
3461  if (RecordLength < 3)
3462  // Records should have at least an ID and two indexes.
3463  return error("Invalid record");
3464  unsigned ID = Record.pop_back_val();
3465 
3466  Value *V;
3467  if (IsBB) {
3468  assert(ID < FunctionBBs.size() && "Basic block not found");
3469  V = FunctionBBs[ID];
3470  } else
3471  V = ValueList[ID];
3472  unsigned NumUses = 0;
3474  for (const Use &U : V->materialized_uses()) {
3475  if (++NumUses > Record.size())
3476  break;
3477  Order[&U] = Record[NumUses - 1];
3478  }
3479  if (Order.size() != Record.size() || NumUses > Record.size())
3480  // Mismatches can happen if the functions are being materialized lazily
3481  // (out-of-order), or a value has been upgraded.
3482  break;
3483 
3484  V->sortUseList([&](const Use &L, const Use &R) {
3485  return Order.lookup(&L) < Order.lookup(&R);
3486  });
3487  break;
3488  }
3489  }
3490  }
3491 }
3492 
3493 /// When we see the block for metadata, remember where it is and then skip it.
3494 /// This lets us lazily deserialize the metadata.
3495 Error BitcodeReader::rememberAndSkipMetadata() {
3496  // Save the current stream state.
3497  uint64_t CurBit = Stream.GetCurrentBitNo();
3498  DeferredMetadataInfo.push_back(CurBit);
3499 
3500  // Skip over the block for now.
3501  if (Error Err = Stream.SkipBlock())
3502  return Err;
3503  return Error::success();
3504 }
3505 
3506 Error BitcodeReader::materializeMetadata() {
3507  for (uint64_t BitPos : DeferredMetadataInfo) {
3508  // Move the bit stream to the saved position.
3509  if (Error JumpFailed = Stream.JumpToBit(BitPos))
3510  return JumpFailed;
3511  if (Error Err = MDLoader->parseModuleMetadata())
3512  return Err;
3513  }
3514 
3515  // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3516  // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3517  // multiple times.
3518  if (!TheModule->getNamedMetadata("llvm.linker.options")) {
3519  if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
3520  NamedMDNode *LinkerOpts =
3521  TheModule->getOrInsertNamedMetadata("llvm.linker.options");
3522  for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3523  LinkerOpts->addOperand(cast<MDNode>(MDOptions));
3524  }
3525  }
3526 
3527  DeferredMetadataInfo.clear();
3528  return Error::success();
3529 }
3530 
3531 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3532 
3533 /// When we see the block for a function body, remember where it is and then
3534 /// skip it. This lets us lazily deserialize the functions.
3535 Error BitcodeReader::rememberAndSkipFunctionBody() {
3536  // Get the function we are talking about.
3537  if (FunctionsWithBodies.empty())
3538  return error("Insufficient function protos");
3539 
3540  Function *Fn = FunctionsWithBodies.back();
3541  FunctionsWithBodies.pop_back();
3542 
3543  // Save the current stream state.
3544  uint64_t CurBit = Stream.GetCurrentBitNo();
3545  assert(
3546  (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3547  "Mismatch between VST and scanned function offsets");
3548  DeferredFunctionInfo[Fn] = CurBit;
3549 
3550  // Skip over the function block for now.
3551  if (Error Err = Stream.SkipBlock())
3552  return Err;
3553  return Error::success();
3554 }
3555 
3556 Error BitcodeReader::globalCleanup() {
3557  // Patch the initializers for globals and aliases up.
3558  if (Error Err = resolveGlobalAndIndirectSymbolInits())
3559  return Err;
3560  if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3561  return error("Malformed global initializer set");
3562 
3563  // Look for intrinsic functions which need to be upgraded at some point
3564  // and functions that need to have their function attributes upgraded.
3565  for (Function &F : *TheModule) {
3566  MDLoader->upgradeDebugIntrinsics(F);
3567  Function *NewFn;
3568  if (UpgradeIntrinsicFunction(&F, NewFn))
3569  UpgradedIntrinsics[&F] = NewFn;
3570  else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
3571  // Some types could be renamed during loading if several modules are
3572  // loaded in the same LLVMContext (LTO scenario). In this case we should
3573  // remangle intrinsics names as well.
3574  RemangledIntrinsics[&F] = *Remangled;
3575  // Look for functions that rely on old function attribute behavior.
3577  }
3578 
3579  // Look for global variables which need to be renamed.
3580  std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3581  for (GlobalVariable &GV : TheModule->globals())
3582  if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
3583  UpgradedVariables.emplace_back(&GV, Upgraded);
3584  for (auto &Pair : UpgradedVariables) {
3585  Pair.first->eraseFromParent();
3586  TheModule->getGlobalList().push_back(Pair.second);
3587  }
3588 
3589  // Force deallocation of memory for these vectors to favor the client that
3590  // want lazy deserialization.
3591  std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3592  std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
3593  return Error::success();
3594 }
3595 
3596 /// Support for lazy parsing of function bodies. This is required if we
3597 /// either have an old bitcode file without a VST forward declaration record,
3598 /// or if we have an anonymous function being materialized, since anonymous
3599 /// functions do not have a name and are therefore not in the VST.
3600 Error BitcodeReader::rememberAndSkipFunctionBodies() {
3601  if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3602  return JumpFailed;
3603 
3604  if (Stream.AtEndOfStream())
3605  return error("Could not find function in stream");
3606 
3607  if (!SeenFirstFunctionBody)
3608  return error("Trying to materialize functions before seeing function blocks");
3609 
3610  // An old bitcode file with the symbol table at the end would have
3611  // finished the parse greedily.
3612  assert(SeenValueSymbolTable);
3613 
3615 
3616  while (true) {
3617  Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3618  if (!MaybeEntry)
3619  return MaybeEntry.takeError();
3620  llvm::BitstreamEntry Entry = MaybeEntry.get();
3621 
3622  switch (Entry.Kind) {
3623  default:
3624  return error("Expect SubBlock");
3625  case BitstreamEntry::SubBlock:
3626  switch (Entry.ID) {
3627  default:
3628  return error("Expect function block");
3630  if (Error Err = rememberAndSkipFunctionBody())
3631  return Err;
3632  NextUnreadBit = Stream.GetCurrentBitNo();
3633  return Error::success();
3634  }
3635  }
3636  }
3637 }
3638 
3639 Error BitcodeReaderBase::readBlockInfo() {
3640  Expected<Optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
3641  Stream.ReadBlockInfoBlock();
3642  if (!MaybeNewBlockInfo)
3643  return MaybeNewBlockInfo.takeError();
3644  Optional<BitstreamBlockInfo> NewBlockInfo =
3645  std::move(MaybeNewBlockInfo.get());
3646  if (!NewBlockInfo)
3647  return error("Malformed block");
3648  BlockInfo = std::move(*NewBlockInfo);
3649  return Error::success();
3650 }
3651 
3652 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
3653  // v1: [selection_kind, name]
3654  // v2: [strtab_offset, strtab_size, selection_kind]
3655  StringRef Name;
3656  std::tie(Name, Record) = readNameFromStrtab(Record);
3657 
3658  if (Record.empty())
3659  return error("Invalid record");
3661  std::string OldFormatName;
3662  if (!UseStrtab) {
3663  if (Record.size() < 2)
3664  return error("Invalid record");
3665  unsigned ComdatNameSize = Record[1];
3666  if (ComdatNameSize > Record.size() - 2)
3667  return error("Comdat name size too large");
3668  OldFormatName.reserve(ComdatNameSize);
3669  for (unsigned i = 0; i != ComdatNameSize; ++i)
3670  OldFormatName += (char)Record[2 + i];
3671  Name = OldFormatName;
3672  }
3673  Comdat *C = TheModule->getOrInsertComdat(Name);
3674  C->setSelectionKind(SK);
3675  ComdatList.push_back(C);
3676  return Error::success();
3677 }
3678 
3679 static void inferDSOLocal(GlobalValue *GV) {
3680  // infer dso_local from linkage and visibility if it is not encoded.
3681  if (GV->hasLocalLinkage() ||
3682  (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
3683  GV->setDSOLocal(true);
3684 }
3685 
3688  if (V & (1 << 0))
3689  Meta.NoAddress = true;
3690  if (V & (1 << 1))
3691  Meta.NoHWAddress = true;
3692  if (V & (1 << 2))
3693  Meta.Memtag = true;
3694  if (V & (1 << 3))
3695  Meta.IsDynInit = true;
3696  return Meta;
3697 }
3698 
3699 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
3700  // v1: [pointer type, isconst, initid, linkage, alignment, section,
3701  // visibility, threadlocal, unnamed_addr, externally_initialized,
3702  // dllstorageclass, comdat, attributes, preemption specifier,
3703  // partition strtab offset, partition strtab size] (name in VST)
3704  // v2: [strtab_offset, strtab_size, v1]
3705  StringRef Name;
3706  std::tie(Name, Record) = readNameFromStrtab(Record);
3707 
3708  if (Record.size() < 6)
3709  return error("Invalid record");
3710  unsigned TyID = Record[0];
3711  Type *Ty = getTypeByID(TyID);
3712  if (!Ty)
3713  return error("Invalid record");
3714  bool isConstant = Record[1] & 1;
3715  bool explicitType = Record[1] & 2;
3716  unsigned AddressSpace;
3717  if (explicitType) {
3718  AddressSpace = Record[1] >> 2;
3719  } else {
3720  if (!Ty->isPointerTy())
3721  return error("Invalid type for value");
3722  AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3723  TyID = getContainedTypeID(TyID);
3724  Ty = getTypeByID(TyID);
3725  if (!Ty)
3726  return error("Missing element type for old-style global");
3727  }
3728 
3729  uint64_t RawLinkage = Record[3];
3731  MaybeAlign Alignment;
3732  if (Error Err = parseAlignmentValue(Record[4], Alignment))
3733  return Err;
3734  std::string Section;
3735  if (Record[5]) {
3736  if (Record[5] - 1 >= SectionTable.size())
3737  return error("Invalid ID");
3738  Section = SectionTable[Record[5] - 1];
3739  }
3740  GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3741  // Local linkage must have default visibility.
3742  // auto-upgrade `hidden` and `protected` for old bitcode.
3743  if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3744  Visibility = getDecodedVisibility(Record[6]);
3745 
3746  GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3747  if (Record.size() > 7)
3749 
3751  if (Record.size() > 8)
3752  UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3753 
3754  bool ExternallyInitialized = false;
3755  if (Record.size() > 9)
3756  ExternallyInitialized = Record[9];
3757 
3758  GlobalVariable *NewGV =
3759  new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
3760  nullptr, TLM, AddressSpace, ExternallyInitialized);
3761  NewGV->setAlignment(Alignment);
3762  if (!Section.empty())
3763  NewGV->setSection(Section);
3764  NewGV->setVisibility(Visibility);
3765  NewGV->setUnnamedAddr(UnnamedAddr);
3766 
3767  if (Record.size() > 10)
3769  else
3770  upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3771 
3772  ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));
3773 
3774  // Remember which value to use for the global initializer.
3775  if (unsigned InitID = Record[2])
3776  GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
3777 
3778  if (Record.size() > 11) {
3779  if (unsigned ComdatID = Record[11]) {
3780  if (ComdatID > ComdatList.size())
3781  return error("Invalid global variable comdat ID");
3782  NewGV->setComdat(ComdatList[ComdatID - 1]);
3783  }
3784  } else if (hasImplicitComdat(RawLinkage)) {
3785  ImplicitComdatObjects.insert(NewGV);
3786  }
3787 
3788  if (Record.size() > 12) {
3789  auto AS = getAttributes(Record[12]).getFnAttrs();
3790  NewGV->setAttributes(AS);
3791  }
3792 
3793  if (Record.size() > 13) {
3794  NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
3795  }
3796  inferDSOLocal(NewGV);
3797 
3798  // Check whether we have enough values to read a partition name.
3799  if (Record.size() > 15)
3800  NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
3801 
3802  if (Record.size() > 16 && Record[16]) {
3805  NewGV->setSanitizerMetadata(Meta);
3806  }
3807 
3808  return Error::success();
3809 }
3810 
3811 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
3812  // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3813  // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3814  // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
3815  // v2: [strtab_offset, strtab_size, v1]
3816  StringRef Name;
3817  std::tie(Name, Record) = readNameFromStrtab(Record);
3818 
3819  if (Record.size() < 8)
3820  return error("Invalid record");
3821  unsigned FTyID = Record[0];
3822  Type *FTy = getTypeByID(FTyID);
3823  if (!FTy)
3824  return error("Invalid record");
3825  if (isa<PointerType>(FTy)) {
3826  FTyID = getContainedTypeID(FTyID, 0);
3827  FTy = getTypeByID(FTyID);
3828  if (!FTy)
3829  return error("Missing element type for old-style function");
3830  }
3831 
3832  if (!isa<FunctionType>(FTy))
3833  return error("Invalid type for value");
3834  auto CC = static_cast<CallingConv::ID>(Record[1]);
3835  if (CC & ~CallingConv::MaxID)
3836  return error("Invalid calling convention ID");
3837 
3838  unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3839  if (Record.size() > 16)
3840  AddrSpace = Record[16];
3841 
3842  Function *Func =
3843  Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
3844  AddrSpace, Name, TheModule);
3845 
3846  assert(Func->getFunctionType() == FTy &&
3847  "Incorrect fully specified type provided for function");
3848  FunctionTypeIDs[Func] = FTyID;
3849 
3850  Func->setCallingConv(CC);
3851  bool isProto = Record[2];
3852  uint64_t RawLinkage = Record[3];
3853  Func->setLinkage(getDecodedLinkage(RawLinkage));
3854  Func->setAttributes(getAttributes(Record[4]));
3855 
3856  // Upgrade any old-style byval or sret without a type by propagating the
3857  // argument's pointee type. There should be no opaque pointers where the byval
3858  // type is implicit.
3859  for (unsigned i = 0; i != Func->arg_size(); ++i) {
3860  for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
3861  Attribute::InAlloca}) {
3862  if (!Func->hasParamAttribute(i, Kind))
3863  continue;
3864 
3865  if (Func->getParamAttribute(i, Kind).getValueAsType())
3866  continue;
3867 
3868  Func->removeParamAttr(i, Kind);
3869 
3870  unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
3871  Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
3872  if (!PtrEltTy)
3873  return error("Missing param element type for attribute upgrade");
3874 
3875  Attribute NewAttr;
3876  switch (Kind) {
3877  case Attribute::ByVal:
3878  NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
3879  break;
3880  case Attribute::StructRet:
3881  NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
3882  break;
3883  case Attribute::InAlloca:
3884  NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
3885  break;
3886  default:
3887  llvm_unreachable("not an upgraded type attribute");
3888  }
3889 
3890  Func->addParamAttr(i, NewAttr);
3891  }
3892  }
3893 
3894  if (Func->getCallingConv() == CallingConv::X86_INTR &&
3895  !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {
3896  unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
3897  Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
3898  if (!ByValTy)
3899  return error("Missing param element type for x86_intrcc upgrade");
3900  Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
3901  Func->addParamAttr(0, NewAttr);
3902  }
3903 
3904  MaybeAlign Alignment;
3905  if (Error Err = parseAlignmentValue(Record[5], Alignment))
3906  return Err;
3907  Func->setAlignment(Alignment);
3908  if (Record[6]) {
3909  if (Record[6] - 1 >= SectionTable.size())
3910  return error("Invalid ID");
3911  Func->setSection(SectionTable[Record[6] - 1]);
3912  }
3913  // Local linkage must have default visibility.
3914  // auto-upgrade `hidden` and `protected` for old bitcode.
3915  if (!Func->hasLocalLinkage())
3916  Func->setVisibility(getDecodedVisibility(Record[7]));
3917  if (Record.size() > 8 && Record[8]) {
3918  if (Record[8] - 1 >= GCTable.size())
3919  return error("Invalid ID");
3920  Func->setGC(GCTable[Record[8] - 1]);
3921  }
3923  if (Record.size() > 9)
3924  UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
3925  Func->setUnnamedAddr(UnnamedAddr);
3926 
3927  FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
3928  if (Record.size() > 10)
3929  OperandInfo.Prologue = Record[10];
3930 
3931  if (Record.size() > 11)
3932  Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
3933  else
3934  upgradeDLLImportExportLinkage(Func, RawLinkage);
3935 
3936  if (Record.size() > 12) {
3937  if (unsigned ComdatID = Record[12]) {
3938  if (ComdatID > ComdatList.size())
3939  return error("Invalid function comdat ID");
3940  Func->setComdat(ComdatList[ComdatID - 1]);
3941  }
3942  } else if (hasImplicitComdat(RawLinkage)) {
3943  ImplicitComdatObjects.insert(Func);
3944  }
3945 
3946  if (Record.size() > 13)
3947  OperandInfo.Prefix = Record[13];
3948 
3949  if (Record.size() > 14)
3950  OperandInfo.PersonalityFn = Record[14];
3951 
3952  if (Record.size() > 15) {
3953  Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
3954  }
3955  inferDSOLocal(Func);
3956 
3957  // Record[16] is the address space number.
3958 
3959  // Check whether we have enough values to read a partition name. Also make
3960  // sure Strtab has enough values.
3961  if (Record.size() > 18 && Strtab.data() &&
3962  Record[17] + Record[18] <= Strtab.size()) {
3963  Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
3964  }
3965 
3966  ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
3967 
3968  if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
3969  FunctionOperands.push_back(OperandInfo);
3970 
3971  // If this is a function with a body, remember the prototype we are
3972  // creating now, so that we can match up the body with them later.
3973  if (!isProto) {
3974  Func->setIsMaterializable(true);
3975  FunctionsWithBodies.push_back(Func);
3976  DeferredFunctionInfo[Func] = 0;
3977  }
3978  return Error::success();
3979 }
3980 
3981 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
3982  unsigned BitCode, ArrayRef<uint64_t> Record) {
3983  // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
3984  // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
3985  // dllstorageclass, threadlocal, unnamed_addr,
3986  // preemption specifier] (name in VST)
3987  // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
3988  // visibility, dllstorageclass, threadlocal, unnamed_addr,
3989  // preemption specifier] (name in VST)
3990  // v2: [strtab_offset, strtab_size, v1]
3991  StringRef Name;
3992  std::tie(Name, Record) = readNameFromStrtab(Record);
3993 
3994  bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3995  if (Record.size() < (3 + (unsigned)NewRecord))
3996  return error("Invalid record");
3997  unsigned OpNum = 0;
3998  unsigned TypeID = Record[OpNum++];
3999  Type *Ty = getTypeByID(TypeID);
4000  if (!Ty)
4001  return error("Invalid record");
4002 
4003  unsigned AddrSpace;
4004  if (!NewRecord) {
4005  auto *PTy = dyn_cast<PointerType>(Ty);
4006  if (!PTy)
4007  return error("Invalid type for value");
4008  AddrSpace = PTy->getAddressSpace();
4009  TypeID = getContainedTypeID(TypeID);
4010  Ty = getTypeByID(TypeID);
4011  if (!Ty)
4012  return error("Missing element type for old-style indirect symbol");
4013  } else {
4014  AddrSpace = Record[OpNum++];
4015  }
4016 
4017  auto Val = Record[OpNum++];
4018  auto Linkage = Record[OpNum++];
4019  GlobalValue *NewGA;
4020  if (BitCode == bitc::MODULE_CODE_ALIAS ||
4021  BitCode == bitc::MODULE_CODE_ALIAS_OLD)
4022  NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4023  TheModule);
4024  else
4025  NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4026  nullptr, TheModule);
4027 
4028  // Local linkage must have default visibility.
4029  // auto-upgrade `hidden` and `protected` for old bitcode.
4030  if (OpNum != Record.size()) {
4031  auto VisInd = OpNum++;
4032  if (!NewGA->hasLocalLinkage())
4033  NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
4034  }
4035  if (BitCode == bitc::MODULE_CODE_ALIAS ||
4036  BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
4037  if (OpNum != Record.size())
4039  else
4041  if (OpNum != Record.size())
4043  if (OpNum != Record.size())
4045  }
4046  if (OpNum != Record.size())
4047  NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
4048  inferDSOLocal(NewGA);
4049 
4050  // Check whether we have enough values to read a partition name.
4051  if (OpNum + 1 < Record.size()) {
4052  NewGA->setPartition(
4053  StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
4054  OpNum += 2;
4055  }
4056 
4057  ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
4058  IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4059  return Error::success();
4060 }
4061 
4063  bool ShouldLazyLoadMetadata,
4064  DataLayoutCallbackTy DataLayoutCallback) {
4065  if (ResumeBit) {
4066  if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
4067  return JumpFailed;
4068  } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4069  return Err;
4070 
4072 
4073  // Parts of bitcode parsing depend on the datalayout. Make sure we
4074  // finalize the datalayout before we run any of that code.
4075  bool ResolvedDataLayout = false;
4076  auto ResolveDataLayout = [&] {
4077  if (ResolvedDataLayout)
4078  return;
4079 
4080  // datalayout and triple can't be parsed after this point.
4081  ResolvedDataLayout = true;
4082 
4083  // Upgrade data layout string.
4084  std::string DL = llvm::UpgradeDataLayoutString(
4085  TheModule->getDataLayoutStr(), TheModule->getTargetTriple());
4086  TheModule->setDataLayout(DL);
4087 
4088  if (auto LayoutOverride =
4089  DataLayoutCallback(TheModule->getTargetTriple()))
4090  TheModule->setDataLayout(*LayoutOverride);
4091  };
4092 
4093  // Read all the records for this module.
4094  while (true) {
4095  Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4096  if (!MaybeEntry)
4097  return MaybeEntry.takeError();
4098  llvm::BitstreamEntry Entry = MaybeEntry.get();
4099 
4100  switch (Entry.Kind) {
4101  case BitstreamEntry::Error:
4102  return error("Malformed block");
4103  case BitstreamEntry::EndBlock:
4104  ResolveDataLayout();
4105  return globalCleanup();
4106 
4107  case BitstreamEntry::SubBlock:
4108  switch (Entry.ID) {
4109  default: // Skip unknown content.
4110  if (Error Err = Stream.SkipBlock())
4111  return Err;
4112  break;
4114  if (Error Err = readBlockInfo())
4115  return Err;
4116  break;
4118  if (Error Err = parseAttributeBlock())
4119  return Err;
4120  break;
4122  if (Error Err = parseAttributeGroupBlock())
4123  return Err;
4124  break;
4126  if (Error Err = parseTypeTable())
4127  return Err;
4128  break;
4130  if (!SeenValueSymbolTable) {
4131  // Either this is an old form VST without function index and an
4132  // associated VST forward declaration record (which would have caused
4133  // the VST to be jumped to and parsed before it was encountered
4134  // normally in the stream), or there were no function blocks to
4135  // trigger an earlier parsing of the VST.
4136  assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4137  if (Error Err = parseValueSymbolTable())
4138  return Err;
4139  SeenValueSymbolTable = true;
4140  } else {
4141  // We must have had a VST forward declaration record, which caused
4142  // the parser to jump to and parse the VST earlier.
4143  assert(VSTOffset > 0);
4144  if (Error Err = Stream.SkipBlock())
4145  return Err;
4146  }
4147  break;
4149  if (Error Err = parseConstants())
4150  return Err;
4151  if (Error Err = resolveGlobalAndIndirectSymbolInits())
4152  return Err;
4153  break;
4155  if (ShouldLazyLoadMetadata) {
4156  if (Error Err = rememberAndSkipMetadata())
4157  return Err;
4158  break;
4159  }
4160  assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
4161  if (Error Err = MDLoader->parseModuleMetadata())
4162  return Err;
4163  break;
4165  if (Error Err = MDLoader->parseMetadataKinds())
4166  return Err;
4167  break;
4169  ResolveDataLayout();
4170 
4171  // If this is the first function body we've seen, reverse the
4172  // FunctionsWithBodies list.
4173  if (!SeenFirstFunctionBody) {
4174  std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4175  if (Error Err = globalCleanup())
4176  return Err;
4177  SeenFirstFunctionBody = true;
4178  }
4179 
4180  if (VSTOffset > 0) {
4181  // If we have a VST forward declaration record, make sure we
4182  // parse the VST now if we haven't already. It is needed to
4183  // set up the DeferredFunctionInfo vector for lazy reading.
4184  if (!SeenValueSymbolTable) {
4185  if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4186  return Err;
4187  SeenValueSymbolTable = true;
4188  // Fall through so that we record the NextUnreadBit below.
4189  // This is necessary in case we have an anonymous function that
4190  // is later materialized. Since it will not have a VST entry we
4191  // need to fall back to the lazy parse to find its offset.
4192  } else {
4193  // If we have a VST forward declaration record, but have already
4194  // parsed the VST (just above, when the first function body was
4195  // encountered here), then we are resuming the parse after
4196  // materializing functions. The ResumeBit points to the
4197  // start of the last function block recorded in the
4198  // DeferredFunctionInfo map. Skip it.
4199  if (Error Err = Stream.SkipBlock())
4200  return Err;
4201  continue;
4202  }
4203  }
4204 
4205  // Support older bitcode files that did not have the function
4206  // index in the VST, nor a VST forward declaration record, as
4207  // well as anonymous functions that do not have VST entries.
4208  // Build the DeferredFunctionInfo vector on the fly.
4209  if (Error Err = rememberAndSkipFunctionBody())
4210  return Err;
4211 
4212  // Suspend parsing when we reach the function bodies. Subsequent
4213  // materialization calls will resume it when necessary. If the bitcode
4214  // file is old, the symbol table will be at the end instead and will not
4215  // have been seen yet. In this case, just finish the parse now.
4216  if (SeenValueSymbolTable) {
4217  NextUnreadBit = Stream.GetCurrentBitNo();
4218  // After the VST has been parsed, we need to make sure intrinsic name
4219  // are auto-upgraded.
4220  return globalCleanup();
4221  }
4222  break;
4224  if (Error Err = parseUseLists())
4225  return Err;
4226  break;
4228  if (Error Err = parseOperandBundleTags())
4229  return Err;
4230  break;
4232  if (Error Err = parseSyncScopeNames())
4233  return Err;
4234  break;
4235  }
4236  continue;
4237 
4238  case BitstreamEntry::Record:
4239  // The interesting case.
4240  break;
4241  }
4242 
4243  // Read a record.
4244  Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4245  if (!MaybeBitCode)
4246  return MaybeBitCode.takeError();
4247  switch (unsigned BitCode = MaybeBitCode.get()) {
4248  default: break; // Default behavior, ignore unknown content.
4250  Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4251  if (!VersionOrErr)
4252  return VersionOrErr.takeError();
4253  UseRelativeIDs = *VersionOrErr >= 1;
4254  break;
4255  }
4256  case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
4257  if (ResolvedDataLayout)
4258  return error("target triple too late in module");
4259  std::string S;
4260  if (convertToString(Record, 0, S))
4261  return error("Invalid record");
4262  TheModule->setTargetTriple(S);
4263  break;
4264  }
4265  case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
4266  if (ResolvedDataLayout)
4267  return error("datalayout too late in module");
4268  std::string S;
4269  if (convertToString(Record, 0, S))
4270  return error("Invalid record");
4272  if (!MaybeDL)
4273  return MaybeDL.takeError();
4274  TheModule->setDataLayout(MaybeDL.get());
4275  break;
4276  }
4277  case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
4278  std::string S;
4279  if (convertToString(Record, 0, S))
4280  return error("Invalid record");
4281  TheModule->setModuleInlineAsm(S);
4282  break;
4283  }
4284  case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
4285  // Deprecated, but still needed to read old bitcode files.
4286  std::string S;
4287  if (convertToString(Record, 0, S))
4288  return error("Invalid record");
4289  // Ignore value.
4290  break;
4291  }
4292  case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
4293  std::string S;
4294  if (convertToString(Record, 0, S))
4295  return error("Invalid record");
4296  SectionTable.push_back(S);
4297  break;
4298  }
4299  case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
4300  std::string S;
4301  if (convertToString(Record, 0, S))
4302  return error("Invalid record");
4303  GCTable.push_back(S);
4304  break;
4305  }
4307  if (Error Err = parseComdatRecord(Record))
4308  return Err;
4309  break;
4310  // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
4311  // written by ThinLinkBitcodeWriter. See
4312  // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
4313  // record
4314  // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4316  if (Error Err = parseGlobalVarRecord(Record))
4317  return Err;
4318  break;
4320  ResolveDataLayout();
4321  if (Error Err = parseFunctionRecord(Record))
4322  return Err;
4323  break;
4327  if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4328  return Err;
4329  break;
4330  /// MODULE_CODE_VSTOFFSET: [offset]
4332  if (Record.empty())
4333  return error("Invalid record");
4334  // Note that we subtract 1 here because the offset is relative to one word
4335  // before the start of the identification or module block, which was
4336  // historically always the start of the regular bitcode header.
4337  VSTOffset = Record[0] - 1;
4338  break;
4339  /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4342  if (convertToString(Record, 0, ValueName))
4343  return error("Invalid record");
4344  TheModule->setSourceFileName(ValueName);
4345  break;
4346  }
4347  Record.clear();
4348  }
4349 }
4350 
4351 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
4352  bool IsImporting,
4353  DataLayoutCallbackTy DataLayoutCallback) {
4354  TheModule = M;
4355  MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
4356  [&](unsigned ID) { return getTypeByID(ID); });
4357  return parseModule(0, ShouldLazyLoadMetadata, DataLayoutCallback);
4358 }
4359 
4360 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4361  if (!isa<PointerType>(PtrType))
4362  return error("Load/Store operand is not a pointer type");
4363 
4364  if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType))
4365  return error("Explicit load/store type does not match pointee "
4366  "type of pointer operand");
4367  if (!PointerType::isLoadableOrStorableType(ValType))
4368  return error("Cannot load/store from pointer");
4369  return Error::success();
4370 }
4371 
4372 Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4373  ArrayRef<unsigned> ArgTyIDs) {
4375  for (unsigned i = 0; i != CB->arg_size(); ++i) {
4376  for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4377  Attribute::InAlloca}) {
4378  if (!Attrs.hasParamAttr(i, Kind) ||
4379  Attrs.getParamAttr(i, Kind).getValueAsType())
4380  continue;
4381 
4382  Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4383  if (!PtrEltTy)
4384  return error("Missing element type for typed attribute upgrade");
4385 
4386  Attribute NewAttr;
4387  switch (Kind) {
4388  case Attribute::ByVal:
4389  NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4390  break;
4391  case Attribute::StructRet:
4392  NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4393  break;
4394  case Attribute::InAlloca:
4395  NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4396  break;
4397  default:
4398  llvm_unreachable("not an upgraded type attribute");
4399  }
4400 
4401  Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
4402  }
4403  }
4404 
4405  if (CB->isInlineAsm()) {
4406  const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
4407  unsigned ArgNo = 0;
4408  for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4409  if (!CI.hasArg())
4410  continue;
4411 
4412  if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
4413  Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4414  if (!ElemTy)
4415  return error("Missing element type for inline asm upgrade");
4416  Attrs = Attrs.addParamAttribute(
4417  Context, ArgNo,
4418  Attribute::get(Context, Attribute::ElementType, ElemTy));
4419  }
4420 
4421  ArgNo++;
4422  }
4423  }
4424 
4425  switch (CB->getIntrinsicID()) {
4426  case Intrinsic::preserve_array_access_index:
4427  case Intrinsic::preserve_struct_access_index:
4428  case Intrinsic::aarch64_ldaxr:
4429  case Intrinsic::aarch64_ldxr:
4430  case Intrinsic::aarch64_stlxr:
4431  case Intrinsic::aarch64_stxr:
4432  case Intrinsic::arm_ldaex:
4433  case Intrinsic::arm_ldrex:
4434  case Intrinsic::arm_stlex:
4435  case Intrinsic::arm_strex: {
4436  unsigned ArgNo;
4437  switch (CB->getIntrinsicID()) {
4438  case Intrinsic::aarch64_stlxr:
4439  case Intrinsic::aarch64_stxr:
4440  case Intrinsic::arm_stlex:
4441  case Intrinsic::arm_strex:
4442  ArgNo = 1;
4443  break;
4444  default:
4445  ArgNo = 0;
4446  break;
4447  }
4448  if (!Attrs.getParamElementType(ArgNo)) {
4449  Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4450  if (!ElTy)
4451  return error("Missing element type for elementtype upgrade");
4452  Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
4453  Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4454  }
4455  break;
4456  }
4457  default:
4458  break;
4459  }
4460 
4461  CB->setAttributes(Attrs);
4462  return Error::success();
4463 }
4464 
4465 /// Lazily parse the specified function body block.
4466 Error BitcodeReader::parseFunctionBody(Function *F) {
4467  if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4468  return Err;
4469 
4470  // Unexpected unresolved metadata when parsing function.
4471  if (MDLoader->hasFwdRefs())
4472  return error("Invalid function metadata: incoming forward references");
4473 
4474  InstructionList.clear();
4475  unsigned ModuleValueListSize = ValueList.size();
4476  unsigned ModuleMDLoaderSize = MDLoader->size();
4477 
4478  // Add all the function arguments to the value table.
4479  unsigned ArgNo = 0;
4480  unsigned FTyID = FunctionTypeIDs[F];
4481  for (Argument &I : F->args()) {
4482  unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4483  assert(I.getType() == getTypeByID(ArgTyID) &&
4484  "Incorrect fully specified type for Function Argument");
4485  ValueList.push_back(&I, ArgTyID);
4486  ++ArgNo;
4487  }
4488  unsigned NextValueNo = ValueList.size();
4489  BasicBlock *CurBB = nullptr;
4490  unsigned CurBBNo = 0;
4491  // Block into which constant expressions from phi nodes are materialized.
4492  BasicBlock *PhiConstExprBB = nullptr;
4493  // Edge blocks for phi nodes into which constant expressions have been
4494  // expanded.
4496  ConstExprEdgeBBs;
4497 
4498  DebugLoc LastLoc;
4499  auto getLastInstruction = [&]() -> Instruction * {
4500  if (CurBB && !CurBB->empty())
4501  return &CurBB->back();
4502  else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4503  !FunctionBBs[CurBBNo - 1]->empty())
4504  return &FunctionBBs[CurBBNo - 1]->back();
4505  return nullptr;
4506  };
4507 
4508  std::vector<OperandBundleDef> OperandBundles;
4509 
4510  // Read all the records.
4512 
4513  while (true) {
4514  Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4515  if (!MaybeEntry)
4516  return MaybeEntry.takeError();
4517  llvm::BitstreamEntry Entry = MaybeEntry.get();
4518 
4519  switch (Entry.Kind) {
4520  case BitstreamEntry::Error:
4521  return error("Malformed block");
4522  case BitstreamEntry::EndBlock:
4523  goto OutOfRecordLoop;
4524 
4525  case BitstreamEntry::SubBlock:
4526  switch (Entry.ID) {
4527  default: // Skip unknown content.
4528  if (Error Err = Stream.SkipBlock())
4529  return Err;
4530  break;
4532  if (Error Err = parseConstants())
4533  return Err;
4534  NextValueNo = ValueList.size();
4535  break;
4537  if (Error Err = parseValueSymbolTable())
4538  return Err;
4539  break;
4541  if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
4542  return Err;
4543  break;
4545  assert(DeferredMetadataInfo.empty() &&
4546  "Must read all module-level metadata before function-level");
4547  if (Error Err = MDLoader->parseFunctionMetadata())
4548  return Err;
4549  break;
4551  if (Error Err = parseUseLists())
4552  return Err;
4553  break;
4554  }
4555  continue;
4556 
4557  case BitstreamEntry::Record:
4558  // The interesting case.
4559  break;
4560  }
4561 
4562  // Read a record.
4563  Record.clear();
4564  Instruction *I = nullptr;
4565  unsigned ResTypeID = InvalidTypeID;
4566  Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4567  if (!MaybeBitCode)
4568  return MaybeBitCode.takeError();
4569  switch (unsigned BitCode = MaybeBitCode.get()) {
4570  default: // Default behavior: reject
4571  return error("Invalid value");
4572  case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
4573  if (Record.empty() || Record[0] == 0)
4574  return error("Invalid record");
4575  // Create all the basic blocks for the function.
4576  FunctionBBs.resize(Record[0]);
4577 
4578  // See if anything took the address of blocks in this function.
4579  auto BBFRI = BasicBlockFwdRefs.find(F);
4580  if (BBFRI == BasicBlockFwdRefs.end()) {
4581  for (BasicBlock *&BB : FunctionBBs)
4582  BB = BasicBlock::Create(Context, "", F);
4583  } else {
4584  auto &BBRefs = BBFRI->second;
4585  // Check for invalid basic block references.
4586  if (BBRefs.size() > FunctionBBs.size())
4587  return error("Invalid ID");
4588  assert(!BBRefs.empty() && "Unexpected empty array");
4589  assert(!BBRefs.front() && "Invalid reference to entry block");
4590  for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4591  ++I)
4592  if (I < RE && BBRefs[I]) {
4593  BBRefs[I]->insertInto(F);
4594  FunctionBBs[I] = BBRefs[I];
4595  } else {
4596  FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4597  }
4598 
4599  // Erase from the table.
4600  BasicBlockFwdRefs.erase(BBFRI);
4601  }
4602 
4603  CurBB = FunctionBBs[0];
4604  continue;
4605  }
4606 
4607  case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
4608  // The record should not be emitted if it's an empty list.
4609  if (Record.empty())
4610  return error("Invalid record");
4611  // When we have the RARE case of a BlockAddress Constant that is not
4612  // scoped to the Function it refers to, we need to conservatively
4613  // materialize the referred to Function, regardless of whether or not
4614  // that Function will ultimately be linked, otherwise users of
4615  // BitcodeReader might start splicing out Function bodies such that we
4616  // might no longer be able to materialize the BlockAddress since the
4617  // BasicBlock (and entire body of the Function) the BlockAddress refers
4618  // to may have been moved. In the case that the user of BitcodeReader
4619  // decides ultimately not to link the Function body, materializing here
4620  // could be considered wasteful, but it's better than a deserialization
4621  // failure as described. This keeps BitcodeReader unaware of complex
4622  // linkage policy decisions such as those use by LTO, leaving those
4623  // decisions "one layer up."
4624  for (uint64_t ValID : Record)
4625  if (auto *F = dyn_cast<Function>(ValueList[ValID]))
4626  BackwardRefFunctions.push_back(F);
4627  else
4628  return error("Invalid record");
4629 
4630  continue;
4631 
4632  case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4633  // This record indicates that the last instruction is at the same
4634  // location as the previous instruction with a location.
4635  I = getLastInstruction();
4636 
4637  if (!I)
4638  return error("Invalid record");
4639  I->setDebugLoc(LastLoc);
4640  I = nullptr;
4641  continue;
4642 
4643  case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
4644  I = getLastInstruction();
4645  if (!I || Record.size() < 4)
4646  return error("Invalid record");
4647 
4648  unsigned Line = Record[0], Col = Record[1];
4649  unsigned ScopeID = Record[2], IAID = Record[3];
4650  bool isImplicitCode = Record.size() == 5 && Record[4];
4651 
4652  MDNode *Scope = nullptr, *IA = nullptr;
4653  if (ScopeID) {
4654  Scope = dyn_cast_or_null<MDNode>(
4655  MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
4656  if (!Scope)
4657  return error("Invalid record");
4658  }
4659  if (IAID) {
4660  IA = dyn_cast_or_null<MDNode>(
4661  MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
4662  if (!IA)
4663  return error("Invalid record");
4664  }
4665  LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4666  isImplicitCode);
4667  I->setDebugLoc(LastLoc);
4668  I = nullptr;
4669  continue;
4670  }
4671  case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
4672  unsigned OpNum = 0;
4673  Value *LHS;
4674  unsigned TypeID;
4675  if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
4676  OpNum+1 > Record.size())
4677  return error("Invalid record");
4678 
4679  int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
4680  if (Opc == -1)
4681  return error("Invalid record");
4682  I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
4683  ResTypeID = TypeID;
4684  InstructionList.push_back(I);
4685  if (OpNum < Record.size()) {
4686  if (isa<FPMathOperator>(I)) {
4688  if (FMF.any())
4689  I->setFastMathFlags(FMF);
4690  }
4691  }
4692  break;
4693  }
4694  case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4695  unsigned OpNum = 0;
4696  Value *LHS, *RHS;
4697  unsigned TypeID;
4698  if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
4699  popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
4700  CurBB) ||
4701  OpNum+1 > Record.size())
4702  return error("Invalid record");
4703 
4704  int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4705  if (Opc == -1)
4706  return error("Invalid record");
4707  I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4708  ResTypeID = TypeID;
4709  InstructionList.push_back(I);
4710  if (OpNum < Record.size()) {
4711  if (Opc == Instruction::Add ||
4712  Opc == Instruction::Sub ||
4713  Opc == Instruction::Mul ||
4714  Opc == Instruction::Shl) {
4715  if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4716  cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4717  if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4718  cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4719  } else if (Opc == Instruction::SDiv ||
4720  Opc == Instruction::UDiv ||
4721  Opc == Instruction::LShr ||
4722  Opc == Instruction::AShr) {
4723  if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4724  cast<BinaryOperator>(I)->setIsExact(true);
4725  } else if (isa<FPMathOperator>(I)) {
4727  if (FMF.any())
4728  I->setFastMathFlags(FMF);
4729  }
4730 
4731  }
4732  break;
4733  }
4734  case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4735  unsigned OpNum = 0;
4736  Value *Op;
4737  unsigned OpTypeID;
4738  if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
4739  OpNum+2 != Record.size())
4740  return error("Invalid record");
4741 
4742  ResTypeID = Record[OpNum];
4743  Type *ResTy = getTypeByID(ResTypeID);
4744  int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
4745  if (Opc == -1 || !ResTy)
4746  return error("Invalid record");
4747  Instruction *Temp = nullptr;
4748  if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4749  if (Temp) {
4750  InstructionList.push_back(Temp);
4751  assert(CurBB && "No current BB?");
4752  CurBB->getInstList().push_back(Temp);
4753  }
4754  } else {
4755  auto CastOp = (Instruction::CastOps)Opc;
4756  if (!CastInst::castIsValid(CastOp, Op, ResTy))
4757  return error("Invalid cast");
4758  I = CastInst::Create(CastOp, Op, ResTy);
4759  }
4760  InstructionList.push_back(I);
4761  break;
4762  }
4765  case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4766  unsigned OpNum = 0;
4767 
4768  unsigned TyID;
4769  Type *Ty;
4770  bool InBounds;
4771 
4772  if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4773  InBounds = Record[OpNum++];
4774  TyID = Record[OpNum++];
4775  Ty = getTypeByID(TyID);
4776  } else {
4777  InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4778  TyID = InvalidTypeID;
4779  Ty = nullptr;
4780  }
4781 
4782  Value *BasePtr;
4783  unsigned BasePtrTypeID;
4784  if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
4785  CurBB))
4786  return error("Invalid record");
4787 
4788  if (!Ty) {
4789  TyID = getContainedTypeID(BasePtrTypeID);
4790  if (BasePtr->getType()->isVectorTy())
4791  TyID = getContainedTypeID(TyID);
4792  Ty = getTypeByID(TyID);
4793  } else if (!cast<PointerType>(BasePtr->getType()->getScalarType())
4794  ->isOpaqueOrPointeeTypeMatches(Ty)) {
4795  return error(
4796  "Explicit gep type does not match pointee type of pointer operand");
4797  }
4798 
4799  SmallVector<Value*, 16> GEPIdx;
4800  while (OpNum != Record.size()) {
4801  Value *Op;
4802  unsigned OpTypeID;
4803  if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
4804  return error("Invalid record");
4805  GEPIdx.push_back(Op);
4806  }
4807 
4808  I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4809 
4810  ResTypeID = TyID;
4811  if (cast<GEPOperator>(I)->getNumIndices() != 0) {
4812  auto GTI = std::next(gep_type_begin(I));
4813  for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
4814  unsigned SubType = 0;
4815  if (GTI.isStruct()) {
4816  ConstantInt *IdxC =
4817  Idx->getType()->isVectorTy()
4818  ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
4819  : cast<ConstantInt>(Idx);
4820  SubType = IdxC->getZExtValue();
4821  }
4822  ResTypeID = getContainedTypeID(ResTypeID, SubType);
4823  ++GTI;
4824  }
4825  }
4826 
4827  // At this point ResTypeID is the result element type. We need a pointer
4828  // or vector of pointer to it.
4829  ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
4830  if (I->getType()->isVectorTy())
4831  ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
4832 
4833  InstructionList.push_back(I);
4834  if (InBounds)
4835  cast<GetElementPtrInst>(I)->setIsInBounds(true);
4836  break;
4837  }
4838 
4840  // EXTRACTVAL: [opty, opval, n x indices]
4841  unsigned OpNum = 0;
4842  Value *Agg;
4843  unsigned AggTypeID;
4844  if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
4845  return error("Invalid record");
4846  Type *Ty = Agg->getType();
4847 
4848  unsigned RecSize = Record.size();
4849  if (OpNum == RecSize)
4850  return error("EXTRACTVAL: Invalid instruction with 0 indices");
4851 
4852  SmallVector<unsigned, 4> EXTRACTVALIdx;
4853  ResTypeID = AggTypeID;
4854  for (; OpNum != RecSize; ++OpNum) {
4855  bool IsArray = Ty->isArrayTy();
4856  bool IsStruct = Ty->isStructTy();
4857  uint64_t Index = Record[OpNum];
4858 
4859  if (!IsStruct && !IsArray)
4860  return error("EXTRACTVAL: Invalid type");
4861  if ((unsigned)Index != Index)
4862  return error("Invalid value");
4863  if (IsStruct && Index >= Ty->getStructNumElements())
4864  return error("EXTRACTVAL: Invalid struct index");
4865  if (IsArray && Index >= Ty->getArrayNumElements())
4866  return error("EXTRACTVAL: Invalid array index");
4867  EXTRACTVALIdx.push_back((unsigned)Index);
4868 
4869  if (IsStruct) {
4870  Ty = Ty->getStructElementType(Index);
4871  ResTypeID = getContainedTypeID(ResTypeID, Index);
4872  } else {
4873  Ty = Ty->getArrayElementType();
4874  ResTypeID = getContainedTypeID(ResTypeID);
4875  }
4876  }
4877 
4878  I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
4879  InstructionList.push_back(I);
4880  break;
4881  }
4882 
4884  // INSERTVAL: [opty, opval, opty, opval, n x indices]
4885  unsigned OpNum = 0;
4886  Value *Agg;
4887  unsigned AggTypeID;
4888  if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
4889  return error("Invalid record");
4890  Value *Val;
4891  unsigned ValTypeID;
4892  if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
4893  return error("Invalid record");
4894 
4895  unsigned RecSize = Record.size();
4896  if (OpNum == RecSize)
4897  return error("INSERTVAL: Invalid instruction with 0 indices");
4898 
4899  SmallVector<unsigned, 4> INSERTVALIdx;
4900  Type *CurTy = Agg->getType();
4901  for (; OpNum != RecSize; ++OpNum) {
4902  bool IsArray = CurTy->isArrayTy();
4903  bool IsStruct = CurTy->isStructTy();
4904  uint64_t Index = Record[OpNum];
4905 
4906  if (!IsStruct && !IsArray)
4907  return error("INSERTVAL: Invalid type");
4908  if ((unsigned)Index != Index)
4909  return error("Invalid value");
4910  if (IsStruct && Index >= CurTy->getStructNumElements())
4911  return error("INSERTVAL: Invalid struct index");
4912  if (IsArray && Index >= CurTy->getArrayNumElements())
4913  return error("INSERTVAL: Invalid array index");
4914 
4915  INSERTVALIdx.push_back((unsigned)Index);
4916  if (IsStruct)
4917  CurTy = CurTy->getStructElementType(Index);
4918  else
4919  CurTy = CurTy->getArrayElementType();
4920  }
4921 
4922  if (CurTy != Val->getType())
4923  return error("Inserted value type doesn't match aggregate type");
4924 
4925  I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
4926  ResTypeID = AggTypeID;
4927  InstructionList.push_back(I);
4928  break;
4929  }
4930 
4931  case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
4932  // obsolete form of select
4933  // handles select i1 ... in old bitcode
4934  unsigned OpNum = 0;
4935  Value *TrueVal, *FalseVal, *Cond;
4936  unsigned TypeID;
4937  Type *CondType = Type::getInt1Ty(Context);
4938  if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
4939  CurBB) ||
4940  popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
4941  FalseVal, CurBB) ||
4942  popValue(Record, OpNum, NextValueNo, CondType,
4943  getVirtualTypeID(CondType), Cond, CurBB))
4944  return error("Invalid record");
4945 
4946  I = SelectInst::Create(Cond, TrueVal, FalseVal);
4947  ResTypeID = TypeID;
4948  InstructionList.push_back(I);
4949  break;
4950  }
4951 
4952  case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4953  // new form of select
4954  // handles select i1 or select [N x i1]
4955  unsigned OpNum = 0;
4956  Value *TrueVal, *FalseVal, *Cond;
4957  unsigned ValTypeID, CondTypeID;
4958  if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
4959  CurBB) ||
4960  popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
4961  FalseVal, CurBB) ||
4962  getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
4963  return error("Invalid record");
4964 
4965  // select condition can be either i1 or [N x i1]
4966  if (VectorType* vector_type =
4967  dyn_cast<VectorType>(Cond->getType())) {
4968  // expect <n x i1>
4969  if (vector_type->getElementType() != Type::getInt1Ty(Context))
4970  return error("Invalid type for value");
4971  } else {
4972  // expect i1
4973  if (Cond->getType() != Type::getInt1Ty(Context))
4974  return error("Invalid type for value");
4975  }
4976 
4977  I = SelectInst::Create(Cond, TrueVal, FalseVal);
4978  ResTypeID = ValTypeID;
4979  InstructionList.push_back(I);
4980  if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
4982  if (FMF.any())
4983  I->setFastMathFlags(FMF);
4984  }
4985  break;
4986  }
4987 
4988  case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
4989  unsigned OpNum = 0;
4990  Value *Vec, *Idx;
4991  unsigned VecTypeID, IdxTypeID;
4992  if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
4993  getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
4994  return error("Invalid record");
4995  if (!Vec->getType()->isVectorTy())
4996  return error("Invalid type for value");
4997  I = ExtractElementInst::Create(Vec, Idx);
4998  ResTypeID = getContainedTypeID(VecTypeID);
4999  InstructionList.push_back(I);
5000  break;
5001  }
5002 
5003  case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
5004  unsigned OpNum = 0;
5005  Value *Vec, *Elt, *Idx;
5006  unsigned VecTypeID, IdxTypeID;
5007  if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5008  return error("Invalid record");
5009  if (!Vec->getType()->isVectorTy())
5010  return error("Invalid type for value");
5011  if (popValue(Record, OpNum, NextValueNo,
5012  cast<VectorType>(Vec->getType())->getElementType(),
5013  getContainedTypeID(VecTypeID), Elt, CurBB) ||
5014  getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5015  return error("Invalid record");
5016  I = InsertElementInst::Create(Vec, Elt, Idx);
5017  ResTypeID = VecTypeID;
5018  InstructionList.push_back(I);
5019  break;
5020  }
5021 
5022  case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
5023  unsigned OpNum = 0;
5024  Value *Vec1, *Vec2, *Mask;
5025  unsigned Vec1TypeID;
5026  if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5027  CurBB) ||
5028  popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
5029  Vec2, CurBB))
5030  return error("Invalid record");
5031 
5032  unsigned MaskTypeID;
5033  if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5034  return error("Invalid record");
5035  if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
5036  return error("Invalid type for value");
5037 
5038  I = new ShuffleVectorInst(Vec1, Vec2, Mask);
5039  ResTypeID =
5040  getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
5041  InstructionList.push_back(I);
5042  break;
5043  }
5044 
5045  case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
5046  // Old form of ICmp/FCmp returning bool
5047  // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
5048  // both legal on vectors but had different behaviour.
5049  case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
5050  // FCmp/ICmp returning bool or vector of bool
5051 
5052  unsigned OpNum = 0;
5053  Value *LHS, *RHS;
5054  unsigned LHSTypeID;
5055  if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
5056  popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
5057  CurBB))
5058  return error("Invalid record");
5059 
5060  if (OpNum >= Record.size())
5061  return error(
5062  "Invalid record: operand number exceeded available operands");
5063 
5064  unsigned PredVal = Record[OpNum];
5065  bool IsFP = LHS->getType()->isFPOrFPVectorTy();
5066  FastMathFlags FMF;
5067  if (IsFP && Record.size() > OpNum+1)
5068  FMF = getDecodedFastMathFlags(Record[++OpNum]);
5069 
5070  if (OpNum+1 != Record.size())
5071  return error("Invalid record");
5072 
5073  if (LHS->getType()->isFPOrFPVectorTy())
5074  I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
5075  else
5076  I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
5077 
5078  ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
5079  if (LHS->getType()->isVectorTy())
5080  ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5081 
5082  if (FMF.any())
5083  I->setFastMathFlags(FMF);
5084  InstructionList.push_back(I);
5085  break;
5086  }
5087 
5088  case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
5089  {
5090  unsigned Size = Record.size();
5091  if (Size == 0) {
5092  I = ReturnInst::Create(Context);
5093  InstructionList.push_back(I);
5094  break;
5095  }
5096 
5097  unsigned OpNum = 0;
5098  Value *Op = nullptr;
5099  unsigned OpTypeID;
5100  if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5101  return error("Invalid record");
5102  if (OpNum != Record.size())
5103  return error("Invalid record");
5104 
5105  I = ReturnInst::Create(Context, Op);
5106  InstructionList.push_back(I);
5107  break;
5108  }
5109  case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
5110  if (Record.size() != 1 && Record.size() != 3)
5111  return error("Invalid record");
5112  BasicBlock *TrueDest = getBasicBlock(Record[0]);
5113  if (!TrueDest)
5114  return error("Invalid record");
5115 
5116  if (Record.size() == 1) {
5117  I = BranchInst::Create(TrueDest);
5118  InstructionList.push_back(I);
5119  }
5120  else {
5121  BasicBlock *FalseDest = getBasicBlock(Record[1]);
5122  Type *CondType = Type::getInt1Ty(Context);
5123  Value *Cond = getValue(Record, 2, NextValueNo, CondType,
5124  getVirtualTypeID(CondType), CurBB);
5125  if (!FalseDest || !Cond)
5126  return error("Invalid record");
5127  I = BranchInst::Create(TrueDest, FalseDest, Cond);
5128  InstructionList.push_back(I);
5129  }
5130  break;
5131  }
5132  case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
5133  if (Record.size() != 1 && Record.size() != 2)
5134  return error("Invalid record");
5135  unsigned Idx = 0;
5136  Type *TokenTy = Type::getTokenTy(Context);
5137  Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5138  getVirtualTypeID(TokenTy), CurBB);
5139  if (!CleanupPad)
5140  return error("Invalid record");
5141  BasicBlock *UnwindDest = nullptr;
5142  if (Record.size() == 2) {
5143  UnwindDest = getBasicBlock(Record[Idx++]);
5144  if (!UnwindDest)
5145  return error("Invalid record");
5146  }
5147 
5148  I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
5149  InstructionList.push_back(I);
5150  break;
5151  }
5152  case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5153  if (Record.size() != 2)
5154  return error("Invalid record");
5155  unsigned Idx = 0;
5156  Type *TokenTy = Type::getTokenTy(Context);
5157  Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5158  getVirtualTypeID(TokenTy), CurBB);
5159  if (!CatchPad)
5160  return error("Invalid record");
5161  BasicBlock *BB = getBasicBlock(Record[Idx++]);
5162  if (!BB)
5163  return error("Invalid record");
5164 
5165  I = CatchReturnInst::Create(CatchPad, BB);
5166  InstructionList.push_back(I);
5167  break;
5168  }
5169  case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5170  // We must have, at minimum, the outer scope and the number of arguments.
5171  if (Record.size() < 2)
5172  return error("Invalid record");
5173 
5174  unsigned Idx = 0;
5175 
5176  Type *TokenTy = Type::getTokenTy(Context);
5177  Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5178  getVirtualTypeID(TokenTy), CurBB);
5179 
5180  unsigned NumHandlers = Record[Idx++];
5181 
5183  for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5184  BasicBlock *BB = getBasicBlock(Record[Idx++]);
5185  if (!BB)
5186  return error("Invalid record");
5187  Handlers.push_back(BB);
5188  }
5189 
5190  BasicBlock *UnwindDest = nullptr;
5191  if (Idx + 1 == Record.size()) {
5192  UnwindDest = getBasicBlock(Record[Idx++]);
5193  if (!UnwindDest)
5194  return error("Invalid record");
5195  }
5196 
5197  if (Record.size() != Idx)
5198