LLVM  4.0.0
BitcodeReader.cpp
Go to the documentation of this file.
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 #include "MetadataLoader.h"
12 #include "ValueList.h"
13 
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/ADT/Twine.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/CallSite.h"
33 #include "llvm/IR/Comdat.h"
34 #include "llvm/IR/Constant.h"
35 #include "llvm/IR/Constants.h"
36 #include "llvm/IR/DebugInfo.h"
38 #include "llvm/IR/DebugLoc.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/DiagnosticInfo.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalAlias.h"
44 #include "llvm/IR/GlobalIFunc.h"
46 #include "llvm/IR/GlobalObject.h"
47 #include "llvm/IR/GlobalValue.h"
48 #include "llvm/IR/GlobalVariable.h"
49 #include "llvm/IR/GVMaterializer.h"
50 #include "llvm/IR/InlineAsm.h"
51 #include "llvm/IR/InstIterator.h"
52 #include "llvm/IR/InstrTypes.h"
53 #include "llvm/IR/Instruction.h"
54 #include "llvm/IR/Instructions.h"
55 #include "llvm/IR/Intrinsics.h"
56 #include "llvm/IR/LLVMContext.h"
57 #include "llvm/IR/Module.h"
59 #include "llvm/IR/OperandTraits.h"
60 #include "llvm/IR/Operator.h"
61 #include "llvm/IR/TrackingMDRef.h"
62 #include "llvm/IR/Type.h"
63 #include "llvm/IR/ValueHandle.h"
64 #include "llvm/IR/Verifier.h"
66 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/Error.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstddef>
78 #include <cstdint>
79 #include <deque>
80 #include <limits>
81 #include <map>
82 #include <memory>
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 
96 namespace {
97 
98 enum {
99  SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
100 };
101 
102 Error error(const Twine &Message) {
103  return make_error<StringError>(
105 }
106 
107 /// Helper to read the header common to all bitcode files.
108 bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
109  // Sniff for the signature.
110  if (!Stream.canSkipToPos(4) ||
111  Stream.Read(8) != 'B' ||
112  Stream.Read(8) != 'C' ||
113  Stream.Read(4) != 0x0 ||
114  Stream.Read(4) != 0xC ||
115  Stream.Read(4) != 0xE ||
116  Stream.Read(4) != 0xD)
117  return false;
118  return true;
119 }
120 
121 Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
122  const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
123  const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
124 
125  if (Buffer.getBufferSize() & 3)
126  return error("Invalid bitcode signature");
127 
128  // If we have a wrapper header, parse it and ignore the non-bc file contents.
129  // The magic number is 0x0B17C0DE stored in little endian.
130  if (isBitcodeWrapper(BufPtr, BufEnd))
131  if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
132  return error("Invalid bitcode wrapper header");
133 
134  BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
135  if (!hasValidBitcodeHeader(Stream))
136  return error("Invalid bitcode signature");
137 
138  return std::move(Stream);
139 }
140 
141 /// Convert a string from a record into an std::string, return true on failure.
142 template <typename StrTy>
143 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
144  StrTy &Result) {
145  if (Idx > Record.size())
146  return true;
147 
148  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
149  Result += (char)Record[i];
150  return false;
151 }
152 
153 // Strip all the TBAA attachment for the module.
154 void stripTBAA(Module *M) {
155  for (auto &F : *M) {
156  if (F.isMaterializable())
157  continue;
158  for (auto &I : instructions(F))
159  I.setMetadata(LLVMContext::MD_tbaa, nullptr);
160  }
161 }
162 
163 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
164 /// "epoch" encoded in the bitcode, and return the producer name if any.
165 Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
167  return error("Invalid record");
168 
169  // Read all the records.
171 
172  std::string ProducerIdentification;
173 
174  while (true) {
175  BitstreamEntry Entry = Stream.advance();
176 
177  switch (Entry.Kind) {
178  default:
180  return error("Malformed block");
182  return ProducerIdentification;
184  // The interesting case.
185  break;
186  }
187 
188  // Read a record.
189  Record.clear();
190  unsigned BitCode = Stream.readRecord(Entry.ID, Record);
191  switch (BitCode) {
192  default: // Default behavior: reject
193  return error("Invalid value");
194  case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
195  convertToString(Record, 0, ProducerIdentification);
196  break;
197  case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
198  unsigned epoch = (unsigned)Record[0];
199  if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
200  return error(
201  Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
202  "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
203  }
204  }
205  }
206  }
207 }
208 
209 Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
210  // We expect a number of well-defined blocks, though we don't necessarily
211  // need to understand them all.
212  while (true) {
213  if (Stream.AtEndOfStream())
214  return "";
215 
216  BitstreamEntry Entry = Stream.advance();
217  switch (Entry.Kind) {
220  return error("Malformed block");
221 
223  if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
224  return readIdentificationBlock(Stream);
225 
226  // Ignore other sub-blocks.
227  if (Stream.SkipBlock())
228  return error("Malformed block");
229  continue;
231  Stream.skipRecord(Entry.ID);
232  continue;
233  }
234  }
235 }
236 
237 Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
239  return error("Invalid record");
240 
242  // Read all the records for this module.
243 
244  while (true) {
245  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
246 
247  switch (Entry.Kind) {
248  case BitstreamEntry::SubBlock: // Handled for us already.
250  return error("Malformed block");
252  return false;
254  // The interesting case.
255  break;
256  }
257 
258  // Read a record.
259  switch (Stream.readRecord(Entry.ID, Record)) {
260  default:
261  break; // Default behavior, ignore unknown content.
262  case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
263  std::string S;
264  if (convertToString(Record, 0, S))
265  return error("Invalid record");
266  // Check for the i386 and other (x86_64, ARM) conventions
267  if (S.find("__DATA, __objc_catlist") != std::string::npos ||
268  S.find("__OBJC,__category") != std::string::npos)
269  return true;
270  break;
271  }
272  }
273  Record.clear();
274  }
275  llvm_unreachable("Exit infinite loop");
276 }
277 
279  // We expect a number of well-defined blocks, though we don't necessarily
280  // need to understand them all.
281  while (true) {
282  BitstreamEntry Entry = Stream.advance();
283 
284  switch (Entry.Kind) {
286  return error("Malformed block");
288  return false;
289 
291  if (Entry.ID == bitc::MODULE_BLOCK_ID)
292  return hasObjCCategoryInModule(Stream);
293 
294  // Ignore other sub-blocks.
295  if (Stream.SkipBlock())
296  return error("Malformed block");
297  continue;
298 
300  Stream.skipRecord(Entry.ID);
301  continue;
302  }
303  }
304 }
305 
306 Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
308  return error("Invalid record");
309 
311 
312  std::string Triple;
313 
314  // Read all the records for this module.
315  while (true) {
316  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
317 
318  switch (Entry.Kind) {
319  case BitstreamEntry::SubBlock: // Handled for us already.
321  return error("Malformed block");
323  return Triple;
325  // The interesting case.
326  break;
327  }
328 
329  // Read a record.
330  switch (Stream.readRecord(Entry.ID, Record)) {
331  default: break; // Default behavior, ignore unknown content.
332  case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
333  std::string S;
334  if (convertToString(Record, 0, S))
335  return error("Invalid record");
336  Triple = S;
337  break;
338  }
339  }
340  Record.clear();
341  }
342  llvm_unreachable("Exit infinite loop");
343 }
344 
345 Expected<std::string> readTriple(BitstreamCursor &Stream) {
346  // We expect a number of well-defined blocks, though we don't necessarily
347  // need to understand them all.
348  while (true) {
349  BitstreamEntry Entry = Stream.advance();
350 
351  switch (Entry.Kind) {
353  return error("Malformed block");
355  return "";
356 
358  if (Entry.ID == bitc::MODULE_BLOCK_ID)
359  return readModuleTriple(Stream);
360 
361  // Ignore other sub-blocks.
362  if (Stream.SkipBlock())
363  return error("Malformed block");
364  continue;
365 
367  Stream.skipRecord(Entry.ID);
368  continue;
369  }
370  }
371 }
372 
373 class BitcodeReaderBase {
374 protected:
375  BitcodeReaderBase(BitstreamCursor Stream) : Stream(std::move(Stream)) {
376  this->Stream.setBlockInfo(&BlockInfo);
377  }
378 
379  BitstreamBlockInfo BlockInfo;
380  BitstreamCursor Stream;
381 
382  bool readBlockInfo();
383 
384  // Contains an arbitrary and optional string identifying the bitcode producer
385  std::string ProducerIdentification;
386 
387  Error error(const Twine &Message);
388 };
389 
390 Error BitcodeReaderBase::error(const Twine &Message) {
391  std::string FullMsg = Message.str();
392  if (!ProducerIdentification.empty())
393  FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
394  LLVM_VERSION_STRING "')";
395  return ::error(FullMsg);
396 }
397 
398 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
400  Module *TheModule = nullptr;
401  // Next offset to start scanning for lazy parsing of function bodies.
402  uint64_t NextUnreadBit = 0;
403  // Last function offset found in the VST.
404  uint64_t LastFunctionBlockBit = 0;
405  bool SeenValueSymbolTable = false;
406  uint64_t VSTOffset = 0;
407 
408  std::vector<Type*> TypeList;
409  BitcodeReaderValueList ValueList;
410  Optional<MetadataLoader> MDLoader;
411  std::vector<Comdat *> ComdatList;
412  SmallVector<Instruction *, 64> InstructionList;
413 
414  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
415  std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
416  std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
417  std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
418  std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
419 
420  /// The set of attributes by index. Index zero in the file is for null, and
421  /// is thus not represented here. As such all indices are off by one.
422  std::vector<AttributeSet> MAttributes;
423 
424  /// The set of attribute groups.
425  std::map<unsigned, AttributeSet> MAttributeGroups;
426 
427  /// While parsing a function body, this is a list of the basic blocks for the
428  /// function.
429  std::vector<BasicBlock*> FunctionBBs;
430 
431  // When reading the module header, this list is populated with functions that
432  // have bodies later in the file.
433  std::vector<Function*> FunctionsWithBodies;
434 
435  // When intrinsic functions are encountered which require upgrading they are
436  // stored here with their replacement function.
437  typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
438  UpdatedIntrinsicMap UpgradedIntrinsics;
439  // Intrinsics which were remangled because of types rename
440  UpdatedIntrinsicMap RemangledIntrinsics;
441 
442  // Several operations happen after the module header has been read, but
443  // before function bodies are processed. This keeps track of whether
444  // we've done this yet.
445  bool SeenFirstFunctionBody = false;
446 
447  /// When function bodies are initially scanned, this map contains info about
448  /// where to find deferred function body in the stream.
449  DenseMap<Function*, uint64_t> DeferredFunctionInfo;
450 
451  /// When Metadata block is initially scanned when parsing the module, we may
452  /// choose to defer parsing of the metadata. This vector contains info about
453  /// which Metadata blocks are deferred.
454  std::vector<uint64_t> DeferredMetadataInfo;
455 
456  /// These are basic blocks forward-referenced by block addresses. They are
457  /// inserted lazily into functions when they're loaded. The basic block ID is
458  /// its index into the vector.
460  std::deque<Function *> BasicBlockFwdRefQueue;
461 
462  /// Indicates that we are using a new encoding for instruction operands where
463  /// most operands in the current FUNCTION_BLOCK are encoded relative to the
464  /// instruction number, for a more compact encoding. Some instruction
465  /// operands are not relative to the instruction ID: basic block numbers, and
466  /// types. Once the old style function blocks have been phased out, we would
467  /// not need this flag.
468  bool UseRelativeIDs = false;
469 
470  /// True if all functions will be materialized, negating the need to process
471  /// (e.g.) blockaddress forward references.
472  bool WillMaterializeAllForwardRefs = false;
473 
474  bool StripDebugInfo = false;
475  TBAAVerifier TBAAVerifyHelper;
476 
477  std::vector<std::string> BundleTags;
478 
479 public:
480  BitcodeReader(BitstreamCursor Stream, StringRef ProducerIdentification,
482 
483  Error materializeForwardReferencedFunctions();
484 
485  Error materialize(GlobalValue *GV) override;
486  Error materializeModule() override;
487  std::vector<StructType *> getIdentifiedStructTypes() const override;
488 
489  /// \brief Main interface to parsing a bitcode buffer.
490  /// \returns true if an error occurred.
491  Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false,
492  bool IsImporting = false);
493 
494  static uint64_t decodeSignRotatedValue(uint64_t V);
495 
496  /// Materialize any deferred Metadata block.
497  Error materializeMetadata() override;
498 
499  void setStripDebugInfo() override;
500 
501 private:
502  std::vector<StructType *> IdentifiedStructTypes;
503  StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
504  StructType *createIdentifiedStructType(LLVMContext &Context);
505 
506  Type *getTypeByID(unsigned ID);
507 
508  Value *getFnValueByID(unsigned ID, Type *Ty) {
509  if (Ty && Ty->isMetadataTy())
510  return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
511  return ValueList.getValueFwdRef(ID, Ty);
512  }
513 
514  Metadata *getFnMetadataByID(unsigned ID) {
515  return MDLoader->getMetadataFwdRefOrLoad(ID);
516  }
517 
518  BasicBlock *getBasicBlock(unsigned ID) const {
519  if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
520  return FunctionBBs[ID];
521  }
522 
523  AttributeSet getAttributes(unsigned i) const {
524  if (i-1 < MAttributes.size())
525  return MAttributes[i-1];
526  return AttributeSet();
527  }
528 
529  /// Read a value/type pair out of the specified record from slot 'Slot'.
530  /// Increment Slot past the number of slots used in the record. Return true on
531  /// failure.
532  bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
533  unsigned InstNum, Value *&ResVal) {
534  if (Slot == Record.size()) return true;
535  unsigned ValNo = (unsigned)Record[Slot++];
536  // Adjust the ValNo, if it was encoded relative to the InstNum.
537  if (UseRelativeIDs)
538  ValNo = InstNum - ValNo;
539  if (ValNo < InstNum) {
540  // If this is not a forward reference, just return the value we already
541  // have.
542  ResVal = getFnValueByID(ValNo, nullptr);
543  return ResVal == nullptr;
544  }
545  if (Slot == Record.size())
546  return true;
547 
548  unsigned TypeNo = (unsigned)Record[Slot++];
549  ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
550  return ResVal == nullptr;
551  }
552 
553  /// Read a value out of the specified record from slot 'Slot'. Increment Slot
554  /// past the number of slots used by the value in the record. Return true if
555  /// there is an error.
556  bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
557  unsigned InstNum, Type *Ty, Value *&ResVal) {
558  if (getValue(Record, Slot, InstNum, Ty, ResVal))
559  return true;
560  // All values currently take a single record slot.
561  ++Slot;
562  return false;
563  }
564 
565  /// Like popValue, but does not increment the Slot number.
566  bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
567  unsigned InstNum, Type *Ty, Value *&ResVal) {
568  ResVal = getValue(Record, Slot, InstNum, Ty);
569  return ResVal == nullptr;
570  }
571 
572  /// Version of getValue that returns ResVal directly, or 0 if there is an
573  /// error.
574  Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
575  unsigned InstNum, Type *Ty) {
576  if (Slot == Record.size()) return nullptr;
577  unsigned ValNo = (unsigned)Record[Slot];
578  // Adjust the ValNo, if it was encoded relative to the InstNum.
579  if (UseRelativeIDs)
580  ValNo = InstNum - ValNo;
581  return getFnValueByID(ValNo, Ty);
582  }
583 
584  /// Like getValue, but decodes signed VBRs.
585  Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
586  unsigned InstNum, Type *Ty) {
587  if (Slot == Record.size()) return nullptr;
588  unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
589  // Adjust the ValNo, if it was encoded relative to the InstNum.
590  if (UseRelativeIDs)
591  ValNo = InstNum - ValNo;
592  return getFnValueByID(ValNo, Ty);
593  }
594 
595  /// Converts alignment exponent (i.e. power of two (or zero)) to the
596  /// corresponding alignment to use. If alignment is too large, returns
597  /// a corresponding error code.
598  Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
599  Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
600  Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
601  Error parseAttributeBlock();
602  Error parseAttributeGroupBlock();
603  Error parseTypeTable();
604  Error parseTypeTableBody();
605  Error parseOperandBundleTags();
606 
607  Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
608  unsigned NameIndex, Triple &TT);
609  Error parseValueSymbolTable(uint64_t Offset = 0);
610  Error parseConstants();
611  Error rememberAndSkipFunctionBodies();
612  Error rememberAndSkipFunctionBody();
613  /// Save the positions of the Metadata blocks and skip parsing the blocks.
614  Error rememberAndSkipMetadata();
615  Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
616  Error parseFunctionBody(Function *F);
617  Error globalCleanup();
618  Error resolveGlobalAndIndirectSymbolInits();
619  Error parseUseLists();
620  Error findFunctionInStream(
621  Function *F,
622  DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
623 };
624 
625 /// Class to manage reading and parsing function summary index bitcode
626 /// files/sections.
627 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
628  /// The module index built during parsing.
629  ModuleSummaryIndex &TheIndex;
630 
631  /// Indicates whether we have encountered a global value summary section
632  /// yet during parsing.
633  bool SeenGlobalValSummary = false;
634 
635  /// Indicates whether we have already parsed the VST, used for error checking.
636  bool SeenValueSymbolTable = false;
637 
638  /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
639  /// Used to enable on-demand parsing of the VST.
640  uint64_t VSTOffset = 0;
641 
642  // Map to save ValueId to GUID association that was recorded in the
643  // ValueSymbolTable. It is used after the VST is parsed to convert
644  // call graph edges read from the function summary from referencing
645  // callees by their ValueId to using the GUID instead, which is how
646  // they are recorded in the summary index being built.
647  // We save a second GUID which is the same as the first one, but ignoring the
648  // linkage, i.e. for value other than local linkage they are identical.
650  ValueIdToCallGraphGUIDMap;
651 
652  /// Map populated during module path string table parsing, from the
653  /// module ID to a string reference owned by the index's module
654  /// path string table, used to correlate with combined index
655  /// summary records.
656  DenseMap<uint64_t, StringRef> ModuleIdMap;
657 
658  /// Original source file name recorded in a bitcode record.
659  std::string SourceFileName;
660 
661 public:
662  ModuleSummaryIndexBitcodeReader(
663  BitstreamCursor Stream, ModuleSummaryIndex &TheIndex);
664 
665  Error parseModule(StringRef ModulePath);
666 
667 private:
668  Error parseValueSymbolTable(
669  uint64_t Offset,
670  DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
671  std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
672  std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
673  bool IsOldProfileFormat,
674  bool HasProfile);
675  Error parseEntireSummary(StringRef ModulePath);
676  Error parseModuleStringTable();
677 
678  std::pair<GlobalValue::GUID, GlobalValue::GUID>
679  getGUIDFromValueId(unsigned ValueId);
680 };
681 
682 } // end anonymous namespace
683 
685  Error Err) {
686  if (Err) {
687  std::error_code EC;
688  handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
689  EC = EIB.convertToErrorCode();
690  Ctx.emitError(EIB.message());
691  });
692  return EC;
693  }
694  return std::error_code();
695 }
696 
697 BitcodeReader::BitcodeReader(BitstreamCursor Stream,
698  StringRef ProducerIdentification,
700  : BitcodeReaderBase(std::move(Stream)), Context(Context),
701  ValueList(Context) {
702  this->ProducerIdentification = ProducerIdentification;
703 }
704 
705 Error BitcodeReader::materializeForwardReferencedFunctions() {
706  if (WillMaterializeAllForwardRefs)
707  return Error::success();
708 
709  // Prevent recursion.
710  WillMaterializeAllForwardRefs = true;
711 
712  while (!BasicBlockFwdRefQueue.empty()) {
713  Function *F = BasicBlockFwdRefQueue.front();
714  BasicBlockFwdRefQueue.pop_front();
715  assert(F && "Expected valid function");
716  if (!BasicBlockFwdRefs.count(F))
717  // Already materialized.
718  continue;
719 
720  // Check for a function that isn't materializable to prevent an infinite
721  // loop. When parsing a blockaddress stored in a global variable, there
722  // isn't a trivial way to check if a function will have a body without a
723  // linear search through FunctionsWithBodies, so just check it here.
724  if (!F->isMaterializable())
725  return error("Never resolved function from blockaddress");
726 
727  // Try to materialize F.
728  if (Error Err = materialize(F))
729  return Err;
730  }
731  assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
732 
733  // Reset state.
734  WillMaterializeAllForwardRefs = false;
735  return Error::success();
736 }
737 
738 //===----------------------------------------------------------------------===//
739 // Helper functions to implement forward reference resolution, etc.
740 //===----------------------------------------------------------------------===//
741 
742 static bool hasImplicitComdat(size_t Val) {
743  switch (Val) {
744  default:
745  return false;
746  case 1: // Old WeakAnyLinkage
747  case 4: // Old LinkOnceAnyLinkage
748  case 10: // Old WeakODRLinkage
749  case 11: // Old LinkOnceODRLinkage
750  return true;
751  }
752 }
753 
755  switch (Val) {
756  default: // Map unknown/new linkages to external
757  case 0:
758  return GlobalValue::ExternalLinkage;
759  case 2:
760  return GlobalValue::AppendingLinkage;
761  case 3:
762  return GlobalValue::InternalLinkage;
763  case 5:
764  return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
765  case 6:
766  return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
767  case 7:
768  return GlobalValue::ExternalWeakLinkage;
769  case 8:
770  return GlobalValue::CommonLinkage;
771  case 9:
772  return GlobalValue::PrivateLinkage;
773  case 12:
774  return GlobalValue::AvailableExternallyLinkage;
775  case 13:
776  return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
777  case 14:
778  return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
779  case 15:
780  return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
781  case 1: // Old value with implicit comdat.
782  case 16:
783  return GlobalValue::WeakAnyLinkage;
784  case 10: // Old value with implicit comdat.
785  case 17:
786  return GlobalValue::WeakODRLinkage;
787  case 4: // Old value with implicit comdat.
788  case 18:
789  return GlobalValue::LinkOnceAnyLinkage;
790  case 11: // Old value with implicit comdat.
791  case 19:
792  return GlobalValue::LinkOnceODRLinkage;
793  }
794 }
795 
796 /// Decode the flags for GlobalValue in the summary.
798  uint64_t Version) {
799  // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
800  // like getDecodedLinkage() above. Any future change to the linkage enum and
801  // to getDecodedLinkage() will need to be taken into account here as above.
802  auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
803  RawFlags = RawFlags >> 4;
804  bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
805  // The LiveRoot flag wasn't introduced until version 3. For dead stripping
806  // to work correctly on earlier versions, we must conservatively treat all
807  // values as live.
808  bool LiveRoot = (RawFlags & 0x2) || Version < 3;
809  return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, LiveRoot);
810 }
811 
813  switch (Val) {
814  default: // Map unknown visibilities to default.
815  case 0: return GlobalValue::DefaultVisibility;
816  case 1: return GlobalValue::HiddenVisibility;
817  case 2: return GlobalValue::ProtectedVisibility;
818  }
819 }
820 
823  switch (Val) {
824  default: // Map unknown values to default.
825  case 0: return GlobalValue::DefaultStorageClass;
826  case 1: return GlobalValue::DLLImportStorageClass;
827  case 2: return GlobalValue::DLLExportStorageClass;
828  }
829 }
830 
831 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
832  switch (Val) {
833  case 0: return GlobalVariable::NotThreadLocal;
834  default: // Map unknown non-zero value to general dynamic.
835  case 1: return GlobalVariable::GeneralDynamicTLSModel;
836  case 2: return GlobalVariable::LocalDynamicTLSModel;
837  case 3: return GlobalVariable::InitialExecTLSModel;
838  case 4: return GlobalVariable::LocalExecTLSModel;
839  }
840 }
841 
842 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
843  switch (Val) {
844  default: // Map unknown to UnnamedAddr::None.
845  case 0: return GlobalVariable::UnnamedAddr::None;
847  case 2: return GlobalVariable::UnnamedAddr::Local;
848  }
849 }
850 
851 static int getDecodedCastOpcode(unsigned Val) {
852  switch (Val) {
853  default: return -1;
854  case bitc::CAST_TRUNC : return Instruction::Trunc;
855  case bitc::CAST_ZEXT : return Instruction::ZExt;
856  case bitc::CAST_SEXT : return Instruction::SExt;
857  case bitc::CAST_FPTOUI : return Instruction::FPToUI;
858  case bitc::CAST_FPTOSI : return Instruction::FPToSI;
859  case bitc::CAST_UITOFP : return Instruction::UIToFP;
860  case bitc::CAST_SITOFP : return Instruction::SIToFP;
861  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
862  case bitc::CAST_FPEXT : return Instruction::FPExt;
863  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
864  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
865  case bitc::CAST_BITCAST : return Instruction::BitCast;
866  case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
867  }
868 }
869 
870 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
871  bool IsFP = Ty->isFPOrFPVectorTy();
872  // BinOps are only valid for int/fp or vector of int/fp types
873  if (!IsFP && !Ty->isIntOrIntVectorTy())
874  return -1;
875 
876  switch (Val) {
877  default:
878  return -1;
879  case bitc::BINOP_ADD:
880  return IsFP ? Instruction::FAdd : Instruction::Add;
881  case bitc::BINOP_SUB:
882  return IsFP ? Instruction::FSub : Instruction::Sub;
883  case bitc::BINOP_MUL:
884  return IsFP ? Instruction::FMul : Instruction::Mul;
885  case bitc::BINOP_UDIV:
886  return IsFP ? -1 : Instruction::UDiv;
887  case bitc::BINOP_SDIV:
888  return IsFP ? Instruction::FDiv : Instruction::SDiv;
889  case bitc::BINOP_UREM:
890  return IsFP ? -1 : Instruction::URem;
891  case bitc::BINOP_SREM:
892  return IsFP ? Instruction::FRem : Instruction::SRem;
893  case bitc::BINOP_SHL:
894  return IsFP ? -1 : Instruction::Shl;
895  case bitc::BINOP_LSHR:
896  return IsFP ? -1 : Instruction::LShr;
897  case bitc::BINOP_ASHR:
898  return IsFP ? -1 : Instruction::AShr;
899  case bitc::BINOP_AND:
900  return IsFP ? -1 : Instruction::And;
901  case bitc::BINOP_OR:
902  return IsFP ? -1 : Instruction::Or;
903  case bitc::BINOP_XOR:
904  return IsFP ? -1 : Instruction::Xor;
905  }
906 }
907 
909  switch (Val) {
910  default: return AtomicRMWInst::BAD_BINOP;
911  case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
912  case bitc::RMW_ADD: return AtomicRMWInst::Add;
913  case bitc::RMW_SUB: return AtomicRMWInst::Sub;
914  case bitc::RMW_AND: return AtomicRMWInst::And;
915  case bitc::RMW_NAND: return AtomicRMWInst::Nand;
916  case bitc::RMW_OR: return AtomicRMWInst::Or;
917  case bitc::RMW_XOR: return AtomicRMWInst::Xor;
918  case bitc::RMW_MAX: return AtomicRMWInst::Max;
919  case bitc::RMW_MIN: return AtomicRMWInst::Min;
920  case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
921  case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
922  }
923 }
924 
925 static AtomicOrdering getDecodedOrdering(unsigned Val) {
926  switch (Val) {
927  case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
928  case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
929  case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
930  case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
931  case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
932  case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
933  default: // Map unknown orderings to sequentially-consistent.
934  case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
935  }
936 }
937 
939  switch (Val) {
941  default: // Map unknown scopes to cross-thread.
943  }
944 }
945 
947  switch (Val) {
948  default: // Map unknown selection kinds to any.
950  return Comdat::Any;
952  return Comdat::ExactMatch;
954  return Comdat::Largest;
956  return Comdat::NoDuplicates;
958  return Comdat::SameSize;
959  }
960 }
961 
963  FastMathFlags FMF;
964  if (0 != (Val & FastMathFlags::UnsafeAlgebra))
965  FMF.setUnsafeAlgebra();
966  if (0 != (Val & FastMathFlags::NoNaNs))
967  FMF.setNoNaNs();
968  if (0 != (Val & FastMathFlags::NoInfs))
969  FMF.setNoInfs();
970  if (0 != (Val & FastMathFlags::NoSignedZeros))
971  FMF.setNoSignedZeros();
972  if (0 != (Val & FastMathFlags::AllowReciprocal))
973  FMF.setAllowReciprocal();
974  return FMF;
975 }
976 
977 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
978  switch (Val) {
979  case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
980  case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
981  }
982 }
983 
984 
985 Type *BitcodeReader::getTypeByID(unsigned ID) {
986  // The type table size is always specified correctly.
987  if (ID >= TypeList.size())
988  return nullptr;
989 
990  if (Type *Ty = TypeList[ID])
991  return Ty;
992 
993  // If we have a forward reference, the only possible case is when it is to a
994  // named struct. Just create a placeholder for now.
995  return TypeList[ID] = createIdentifiedStructType(Context);
996 }
997 
998 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
999  StringRef Name) {
1000  auto *Ret = StructType::create(Context, Name);
1001  IdentifiedStructTypes.push_back(Ret);
1002  return Ret;
1003 }
1004 
1005 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1006  auto *Ret = StructType::create(Context);
1007  IdentifiedStructTypes.push_back(Ret);
1008  return Ret;
1009 }
1010 
1011 //===----------------------------------------------------------------------===//
1012 // Functions for parsing blocks from the bitcode file
1013 //===----------------------------------------------------------------------===//
1014 
1016  switch (Val) {
1017  case Attribute::EndAttrKinds:
1018  llvm_unreachable("Synthetic enumerators which should never get here");
1019 
1020  case Attribute::None: return 0;
1021  case Attribute::ZExt: return 1 << 0;
1022  case Attribute::SExt: return 1 << 1;
1023  case Attribute::NoReturn: return 1 << 2;
1024  case Attribute::InReg: return 1 << 3;
1025  case Attribute::StructRet: return 1 << 4;
1026  case Attribute::NoUnwind: return 1 << 5;
1027  case Attribute::NoAlias: return 1 << 6;
1028  case Attribute::ByVal: return 1 << 7;
1029  case Attribute::Nest: return 1 << 8;
1030  case Attribute::ReadNone: return 1 << 9;
1031  case Attribute::ReadOnly: return 1 << 10;
1032  case Attribute::NoInline: return 1 << 11;
1033  case Attribute::AlwaysInline: return 1 << 12;
1034  case Attribute::OptimizeForSize: return 1 << 13;
1035  case Attribute::StackProtect: return 1 << 14;
1036  case Attribute::StackProtectReq: return 1 << 15;
1037  case Attribute::Alignment: return 31 << 16;
1038  case Attribute::NoCapture: return 1 << 21;
1039  case Attribute::NoRedZone: return 1 << 22;
1040  case Attribute::NoImplicitFloat: return 1 << 23;
1041  case Attribute::Naked: return 1 << 24;
1042  case Attribute::InlineHint: return 1 << 25;
1043  case Attribute::StackAlignment: return 7 << 26;
1044  case Attribute::ReturnsTwice: return 1 << 29;
1045  case Attribute::UWTable: return 1 << 30;
1046  case Attribute::NonLazyBind: return 1U << 31;
1047  case Attribute::SanitizeAddress: return 1ULL << 32;
1048  case Attribute::MinSize: return 1ULL << 33;
1049  case Attribute::NoDuplicate: return 1ULL << 34;
1050  case Attribute::StackProtectStrong: return 1ULL << 35;
1051  case Attribute::SanitizeThread: return 1ULL << 36;
1052  case Attribute::SanitizeMemory: return 1ULL << 37;
1053  case Attribute::NoBuiltin: return 1ULL << 38;
1054  case Attribute::Returned: return 1ULL << 39;
1055  case Attribute::Cold: return 1ULL << 40;
1056  case Attribute::Builtin: return 1ULL << 41;
1057  case Attribute::OptimizeNone: return 1ULL << 42;
1058  case Attribute::InAlloca: return 1ULL << 43;
1059  case Attribute::NonNull: return 1ULL << 44;
1060  case Attribute::JumpTable: return 1ULL << 45;
1061  case Attribute::Convergent: return 1ULL << 46;
1062  case Attribute::SafeStack: return 1ULL << 47;
1063  case Attribute::NoRecurse: return 1ULL << 48;
1064  case Attribute::InaccessibleMemOnly: return 1ULL << 49;
1065  case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
1066  case Attribute::SwiftSelf: return 1ULL << 51;
1067  case Attribute::SwiftError: return 1ULL << 52;
1068  case Attribute::WriteOnly: return 1ULL << 53;
1069  case Attribute::Dereferenceable:
1070  llvm_unreachable("dereferenceable attribute not supported in raw format");
1071  break;
1072  case Attribute::DereferenceableOrNull:
1073  llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
1074  "format");
1075  break;
1076  case Attribute::ArgMemOnly:
1077  llvm_unreachable("argmemonly attribute not supported in raw format");
1078  break;
1079  case Attribute::AllocSize:
1080  llvm_unreachable("allocsize not supported in raw format");
1081  break;
1082  }
1083  llvm_unreachable("Unsupported attribute type");
1084 }
1085 
1086 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1087  if (!Val) return;
1088 
1089  for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1090  I = Attribute::AttrKind(I + 1)) {
1091  if (I == Attribute::Dereferenceable ||
1092  I == Attribute::DereferenceableOrNull ||
1093  I == Attribute::ArgMemOnly ||
1094  I == Attribute::AllocSize)
1095  continue;
1096  if (uint64_t A = (Val & getRawAttributeMask(I))) {
1097  if (I == Attribute::Alignment)
1098  B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1099  else if (I == Attribute::StackAlignment)
1100  B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1101  else
1102  B.addAttribute(I);
1103  }
1104  }
1105 }
1106 
1107 /// \brief This fills an AttrBuilder object with the LLVM attributes that have
1108 /// been decoded from the given integer. This function must stay in sync with
1109 /// 'encodeLLVMAttributesForBitcode'.
1111  uint64_t EncodedAttrs) {
1112  // FIXME: Remove in 4.0.
1113 
1114  // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1115  // the bits above 31 down by 11 bits.
1116  unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1117  assert((!Alignment || isPowerOf2_32(Alignment)) &&
1118  "Alignment must be a power of two.");
1119 
1120  if (Alignment)
1121  B.addAlignmentAttr(Alignment);
1122  addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1123  (EncodedAttrs & 0xffff));
1124 }
1125 
1126 Error BitcodeReader::parseAttributeBlock() {
1128  return error("Invalid record");
1129 
1130  if (!MAttributes.empty())
1131  return error("Invalid multiple blocks");
1132 
1134 
1136 
1137  // Read all the records.
1138  while (true) {
1139  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1140 
1141  switch (Entry.Kind) {
1142  case BitstreamEntry::SubBlock: // Handled for us already.
1143  case BitstreamEntry::Error:
1144  return error("Malformed block");
1145  case BitstreamEntry::EndBlock:
1146  return Error::success();
1147  case BitstreamEntry::Record:
1148  // The interesting case.
1149  break;
1150  }
1151 
1152  // Read a record.
1153  Record.clear();
1154  switch (Stream.readRecord(Entry.ID, Record)) {
1155  default: // Default behavior: ignore.
1156  break;
1157  case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1158  // FIXME: Remove in 4.0.
1159  if (Record.size() & 1)
1160  return error("Invalid record");
1161 
1162  for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1163  AttrBuilder B;
1164  decodeLLVMAttributesForBitcode(B, Record[i+1]);
1165  Attrs.push_back(AttributeSet::get(Context, Record[i], B));
1166  }
1167 
1168  MAttributes.push_back(AttributeSet::get(Context, Attrs));
1169  Attrs.clear();
1170  break;
1171  }
1172  case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1173  for (unsigned i = 0, e = Record.size(); i != e; ++i)
1174  Attrs.push_back(MAttributeGroups[Record[i]]);
1175 
1176  MAttributes.push_back(AttributeSet::get(Context, Attrs));
1177  Attrs.clear();
1178  break;
1179  }
1180  }
1181  }
1182 }
1183 
1184 // Returns Attribute::None on unrecognized codes.
1186  switch (Code) {
1187  default:
1188  return Attribute::None;
1190  return Attribute::Alignment;
1192  return Attribute::AlwaysInline;
1194  return Attribute::ArgMemOnly;
1196  return Attribute::Builtin;
1198  return Attribute::ByVal;
1200  return Attribute::InAlloca;
1201  case bitc::ATTR_KIND_COLD:
1202  return Attribute::Cold;
1204  return Attribute::Convergent;
1206  return Attribute::InaccessibleMemOnly;
1208  return Attribute::InaccessibleMemOrArgMemOnly;
1210  return Attribute::InlineHint;
1212  return Attribute::InReg;
1214  return Attribute::JumpTable;
1216  return Attribute::MinSize;
1217  case bitc::ATTR_KIND_NAKED:
1218  return Attribute::Naked;
1219  case bitc::ATTR_KIND_NEST:
1220  return Attribute::Nest;
1222  return Attribute::NoAlias;
1224  return Attribute::NoBuiltin;
1226  return Attribute::NoCapture;
1228  return Attribute::NoDuplicate;
1230  return Attribute::NoImplicitFloat;
1232  return Attribute::NoInline;
1234  return Attribute::NoRecurse;
1236  return Attribute::NonLazyBind;
1238  return Attribute::NonNull;
1240  return Attribute::Dereferenceable;
1242  return Attribute::DereferenceableOrNull;
1244  return Attribute::AllocSize;
1246  return Attribute::NoRedZone;
1248  return Attribute::NoReturn;
1250  return Attribute::NoUnwind;
1252  return Attribute::OptimizeForSize;
1254  return Attribute::OptimizeNone;
1256  return Attribute::ReadNone;
1258  return Attribute::ReadOnly;
1260  return Attribute::Returned;
1262  return Attribute::ReturnsTwice;
1263  case bitc::ATTR_KIND_S_EXT:
1264  return Attribute::SExt;
1266  return Attribute::StackAlignment;
1268  return Attribute::StackProtect;
1270  return Attribute::StackProtectReq;
1272  return Attribute::StackProtectStrong;
1274  return Attribute::SafeStack;
1276  return Attribute::StructRet;
1278  return Attribute::SanitizeAddress;
1280  return Attribute::SanitizeThread;
1282  return Attribute::SanitizeMemory;
1284  return Attribute::SwiftError;
1286  return Attribute::SwiftSelf;
1288  return Attribute::UWTable;
1290  return Attribute::WriteOnly;
1291  case bitc::ATTR_KIND_Z_EXT:
1292  return Attribute::ZExt;
1293  }
1294 }
1295 
1296 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1297  unsigned &Alignment) {
1298  // Note: Alignment in bitcode files is incremented by 1, so that zero
1299  // can be used for default alignment.
1300  if (Exponent > Value::MaxAlignmentExponent + 1)
1301  return error("Invalid alignment value");
1302  Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1303  return Error::success();
1304 }
1305 
1307  *Kind = getAttrFromCode(Code);
1308  if (*Kind == Attribute::None)
1309  return error("Unknown attribute kind (" + Twine(Code) + ")");
1310  return Error::success();
1311 }
1312 
1313 Error BitcodeReader::parseAttributeGroupBlock() {
1315  return error("Invalid record");
1316 
1317  if (!MAttributeGroups.empty())
1318  return error("Invalid multiple blocks");
1319 
1321 
1322  // Read all the records.
1323  while (true) {
1324  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1325 
1326  switch (Entry.Kind) {
1327  case BitstreamEntry::SubBlock: // Handled for us already.
1328  case BitstreamEntry::Error:
1329  return error("Malformed block");
1330  case BitstreamEntry::EndBlock:
1331  return Error::success();
1332  case BitstreamEntry::Record:
1333  // The interesting case.
1334  break;
1335  }
1336 
1337  // Read a record.
1338  Record.clear();
1339  switch (Stream.readRecord(Entry.ID, Record)) {
1340  default: // Default behavior: ignore.
1341  break;
1342  case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1343  if (Record.size() < 3)
1344  return error("Invalid record");
1345 
1346  uint64_t GrpID = Record[0];
1347  uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1348 
1349  AttrBuilder B;
1350  for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1351  if (Record[i] == 0) { // Enum attribute
1353  if (Error Err = parseAttrKind(Record[++i], &Kind))
1354  return Err;
1355 
1356  B.addAttribute(Kind);
1357  } else if (Record[i] == 1) { // Integer attribute
1359  if (Error Err = parseAttrKind(Record[++i], &Kind))
1360  return Err;
1361  if (Kind == Attribute::Alignment)
1362  B.addAlignmentAttr(Record[++i]);
1363  else if (Kind == Attribute::StackAlignment)
1364  B.addStackAlignmentAttr(Record[++i]);
1365  else if (Kind == Attribute::Dereferenceable)
1366  B.addDereferenceableAttr(Record[++i]);
1367  else if (Kind == Attribute::DereferenceableOrNull)
1368  B.addDereferenceableOrNullAttr(Record[++i]);
1369  else if (Kind == Attribute::AllocSize)
1370  B.addAllocSizeAttrFromRawRepr(Record[++i]);
1371  } else { // String attribute
1372  assert((Record[i] == 3 || Record[i] == 4) &&
1373  "Invalid attribute group entry");
1374  bool HasValue = (Record[i++] == 4);
1375  SmallString<64> KindStr;
1376  SmallString<64> ValStr;
1377 
1378  while (Record[i] != 0 && i != e)
1379  KindStr += Record[i++];
1380  assert(Record[i] == 0 && "Kind string not null terminated");
1381 
1382  if (HasValue) {
1383  // Has a value associated with it.
1384  ++i; // Skip the '0' that terminates the "kind" string.
1385  while (Record[i] != 0 && i != e)
1386  ValStr += Record[i++];
1387  assert(Record[i] == 0 && "Value string not null terminated");
1388  }
1389 
1390  B.addAttribute(KindStr.str(), ValStr.str());
1391  }
1392  }
1393 
1394  MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
1395  break;
1396  }
1397  }
1398  }
1399 }
1400 
1401 Error BitcodeReader::parseTypeTable() {
1403  return error("Invalid record");
1404 
1405  return parseTypeTableBody();
1406 }
1407 
1408 Error BitcodeReader::parseTypeTableBody() {
1409  if (!TypeList.empty())
1410  return error("Invalid multiple blocks");
1411 
1413  unsigned NumRecords = 0;
1414 
1415  SmallString<64> TypeName;
1416 
1417  // Read all the records for this type table.
1418  while (true) {
1419  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1420 
1421  switch (Entry.Kind) {
1422  case BitstreamEntry::SubBlock: // Handled for us already.
1423  case BitstreamEntry::Error:
1424  return error("Malformed block");
1425  case BitstreamEntry::EndBlock:
1426  if (NumRecords != TypeList.size())
1427  return error("Malformed block");
1428  return Error::success();
1429  case BitstreamEntry::Record:
1430  // The interesting case.
1431  break;
1432  }
1433 
1434  // Read a record.
1435  Record.clear();
1436  Type *ResultTy = nullptr;
1437  switch (Stream.readRecord(Entry.ID, Record)) {
1438  default:
1439  return error("Invalid value");
1440  case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1441  // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1442  // type list. This allows us to reserve space.
1443  if (Record.size() < 1)
1444  return error("Invalid record");
1445  TypeList.resize(Record[0]);
1446  continue;
1447  case bitc::TYPE_CODE_VOID: // VOID
1448  ResultTy = Type::getVoidTy(Context);
1449  break;
1450  case bitc::TYPE_CODE_HALF: // HALF
1451  ResultTy = Type::getHalfTy(Context);
1452  break;
1453  case bitc::TYPE_CODE_FLOAT: // FLOAT
1454  ResultTy = Type::getFloatTy(Context);
1455  break;
1456  case bitc::TYPE_CODE_DOUBLE: // DOUBLE
1457  ResultTy = Type::getDoubleTy(Context);
1458  break;
1459  case bitc::TYPE_CODE_X86_FP80: // X86_FP80
1460  ResultTy = Type::getX86_FP80Ty(Context);
1461  break;
1462  case bitc::TYPE_CODE_FP128: // FP128
1463  ResultTy = Type::getFP128Ty(Context);
1464  break;
1465  case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1466  ResultTy = Type::getPPC_FP128Ty(Context);
1467  break;
1468  case bitc::TYPE_CODE_LABEL: // LABEL
1469  ResultTy = Type::getLabelTy(Context);
1470  break;
1471  case bitc::TYPE_CODE_METADATA: // METADATA
1472  ResultTy = Type::getMetadataTy(Context);
1473  break;
1474  case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1475  ResultTy = Type::getX86_MMXTy(Context);
1476  break;
1477  case bitc::TYPE_CODE_TOKEN: // TOKEN
1478  ResultTy = Type::getTokenTy(Context);
1479  break;
1480  case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
1481  if (Record.size() < 1)
1482  return error("Invalid record");
1483 
1484  uint64_t NumBits = Record[0];
1485  if (NumBits < IntegerType::MIN_INT_BITS ||
1486  NumBits > IntegerType::MAX_INT_BITS)
1487  return error("Bitwidth for integer type out of range");
1488  ResultTy = IntegerType::get(Context, NumBits);
1489  break;
1490  }
1491  case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1492  // [pointee type, address space]
1493  if (Record.size() < 1)
1494  return error("Invalid record");
1495  unsigned AddressSpace = 0;
1496  if (Record.size() == 2)
1497  AddressSpace = Record[1];
1498  ResultTy = getTypeByID(Record[0]);
1499  if (!ResultTy ||
1501  return error("Invalid type");
1502  ResultTy = PointerType::get(ResultTy, AddressSpace);
1503  break;
1504  }
1506  // FIXME: attrid is dead, remove it in LLVM 4.0
1507  // FUNCTION: [vararg, attrid, retty, paramty x N]
1508  if (Record.size() < 3)
1509  return error("Invalid record");
1510  SmallVector<Type*, 8> ArgTys;
1511  for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1512  if (Type *T = getTypeByID(Record[i]))
1513  ArgTys.push_back(T);
1514  else
1515  break;
1516  }
1517 
1518  ResultTy = getTypeByID(Record[2]);
1519  if (!ResultTy || ArgTys.size() < Record.size()-3)
1520  return error("Invalid type");
1521 
1522  ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1523  break;
1524  }
1525  case bitc::TYPE_CODE_FUNCTION: {
1526  // FUNCTION: [vararg, retty, paramty x N]
1527  if (Record.size() < 2)
1528  return error("Invalid record");
1529  SmallVector<Type*, 8> ArgTys;
1530  for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1531  if (Type *T = getTypeByID(Record[i])) {
1532  if (!FunctionType::isValidArgumentType(T))
1533  return error("Invalid function argument type");
1534  ArgTys.push_back(T);
1535  }
1536  else
1537  break;
1538  }
1539 
1540  ResultTy = getTypeByID(Record[1]);
1541  if (!ResultTy || ArgTys.size() < Record.size()-2)
1542  return error("Invalid type");
1543 
1544  ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1545  break;
1546  }
1547  case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
1548  if (Record.size() < 1)
1549  return error("Invalid record");
1550  SmallVector<Type*, 8> EltTys;
1551  for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1552  if (Type *T = getTypeByID(Record[i]))
1553  EltTys.push_back(T);
1554  else
1555  break;
1556  }
1557  if (EltTys.size() != Record.size()-1)
1558  return error("Invalid type");
1559  ResultTy = StructType::get(Context, EltTys, Record[0]);
1560  break;
1561  }
1562  case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
1563  if (convertToString(Record, 0, TypeName))
1564  return error("Invalid record");
1565  continue;
1566 
1567  case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1568  if (Record.size() < 1)
1569  return error("Invalid record");
1570 
1571  if (NumRecords >= TypeList.size())
1572  return error("Invalid TYPE table");
1573 
1574  // Check to see if this was forward referenced, if so fill in the temp.
1575  StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1576  if (Res) {
1577  Res->setName(TypeName);
1578  TypeList[NumRecords] = nullptr;
1579  } else // Otherwise, create a new struct.
1580  Res = createIdentifiedStructType(Context, TypeName);
1581  TypeName.clear();
1582 
1583  SmallVector<Type*, 8> EltTys;
1584  for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1585  if (Type *T = getTypeByID(Record[i]))
1586  EltTys.push_back(T);
1587  else
1588  break;
1589  }
1590  if (EltTys.size() != Record.size()-1)
1591  return error("Invalid record");
1592  Res->setBody(EltTys, Record[0]);
1593  ResultTy = Res;
1594  break;
1595  }
1596  case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1597  if (Record.size() != 1)
1598  return error("Invalid record");
1599 
1600  if (NumRecords >= TypeList.size())
1601  return error("Invalid TYPE table");
1602 
1603  // Check to see if this was forward referenced, if so fill in the temp.
1604  StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1605  if (Res) {
1606  Res->setName(TypeName);
1607  TypeList[NumRecords] = nullptr;
1608  } else // Otherwise, create a new struct with no body.
1609  Res = createIdentifiedStructType(Context, TypeName);
1610  TypeName.clear();
1611  ResultTy = Res;
1612  break;
1613  }
1614  case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1615  if (Record.size() < 2)
1616  return error("Invalid record");
1617  ResultTy = getTypeByID(Record[1]);
1618  if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
1619  return error("Invalid type");
1620  ResultTy = ArrayType::get(ResultTy, Record[0]);
1621  break;
1622  case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1623  if (Record.size() < 2)
1624  return error("Invalid record");
1625  if (Record[0] == 0)
1626  return error("Invalid vector length");
1627  ResultTy = getTypeByID(Record[1]);
1628  if (!ResultTy || !StructType::isValidElementType(ResultTy))
1629  return error("Invalid type");
1630  ResultTy = VectorType::get(ResultTy, Record[0]);
1631  break;
1632  }
1633 
1634  if (NumRecords >= TypeList.size())
1635  return error("Invalid TYPE table");
1636  if (TypeList[NumRecords])
1637  return error(
1638  "Invalid TYPE table: Only named structs can be forward referenced");
1639  assert(ResultTy && "Didn't read a type?");
1640  TypeList[NumRecords++] = ResultTy;
1641  }
1642 }
1643 
1644 Error BitcodeReader::parseOperandBundleTags() {
1646  return error("Invalid record");
1647 
1648  if (!BundleTags.empty())
1649  return error("Invalid multiple blocks");
1650 
1652 
1653  while (true) {
1654  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1655 
1656  switch (Entry.Kind) {
1657  case BitstreamEntry::SubBlock: // Handled for us already.
1658  case BitstreamEntry::Error:
1659  return error("Malformed block");
1660  case BitstreamEntry::EndBlock:
1661  return Error::success();
1662  case BitstreamEntry::Record:
1663  // The interesting case.
1664  break;
1665  }
1666 
1667  // Tags are implicitly mapped to integers by their order.
1668 
1669  if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1670  return error("Invalid record");
1671 
1672  // OPERAND_BUNDLE_TAG: [strchr x N]
1673  BundleTags.emplace_back();
1674  if (convertToString(Record, 0, BundleTags.back()))
1675  return error("Invalid record");
1676  Record.clear();
1677  }
1678 }
1679 
1680 /// Associate a value with its name from the given index in the provided record.
1681 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1682  unsigned NameIndex, Triple &TT) {
1684  if (convertToString(Record, NameIndex, ValueName))
1685  return error("Invalid record");
1686  unsigned ValueID = Record[0];
1687  if (ValueID >= ValueList.size() || !ValueList[ValueID])
1688  return error("Invalid record");
1689  Value *V = ValueList[ValueID];
1690 
1691  StringRef NameStr(ValueName.data(), ValueName.size());
1692  if (NameStr.find_first_of(0) != StringRef::npos)
1693  return error("Invalid value name");
1694  V->setName(NameStr);
1695  auto *GO = dyn_cast<GlobalObject>(V);
1696  if (GO) {
1697  if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1698  if (TT.isOSBinFormatMachO())
1699  GO->setComdat(nullptr);
1700  else
1701  GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1702  }
1703  }
1704  return V;
1705 }
1706 
1707 /// Helper to note and return the current location, and jump to the given
1708 /// offset.
1709 static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1710  BitstreamCursor &Stream) {
1711  // Save the current parsing location so we can jump back at the end
1712  // of the VST read.
1713  uint64_t CurrentBit = Stream.GetCurrentBitNo();
1714  Stream.JumpToBit(Offset * 32);
1715 #ifndef NDEBUG
1716  // Do some checking if we are in debug mode.
1717  BitstreamEntry Entry = Stream.advance();
1718  assert(Entry.Kind == BitstreamEntry::SubBlock);
1720 #else
1721  // In NDEBUG mode ignore the output so we don't get an unused variable
1722  // warning.
1723  Stream.advance();
1724 #endif
1725  return CurrentBit;
1726 }
1727 
1728 /// Parse the value symbol table at either the current parsing location or
1729 /// at the given bit offset if provided.
1730 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
1731  uint64_t CurrentBit;
1732  // Pass in the Offset to distinguish between calling for the module-level
1733  // VST (where we want to jump to the VST offset) and the function-level
1734  // VST (where we don't).
1735  if (Offset > 0)
1736  CurrentBit = jumpToValueSymbolTable(Offset, Stream);
1737 
1738  // Compute the delta between the bitcode indices in the VST (the word offset
1739  // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1740  // expected by the lazy reader. The reader's EnterSubBlock expects to have
1741  // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1742  // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1743  // just before entering the VST subblock because: 1) the EnterSubBlock
1744  // changes the AbbrevID width; 2) the VST block is nested within the same
1745  // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1746  // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1747  // jump to the FUNCTION_BLOCK using this offset later, we don't want
1748  // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1749  unsigned FuncBitcodeOffsetDelta =
1751 
1753  return error("Invalid record");
1754 
1756 
1757  Triple TT(TheModule->getTargetTriple());
1758 
1759  // Read all the records for this value table.
1761 
1762  while (true) {
1763  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1764 
1765  switch (Entry.Kind) {
1766  case BitstreamEntry::SubBlock: // Handled for us already.
1767  case BitstreamEntry::Error:
1768  return error("Malformed block");
1769  case BitstreamEntry::EndBlock:
1770  if (Offset > 0)
1771  Stream.JumpToBit(CurrentBit);
1772  return Error::success();
1773  case BitstreamEntry::Record:
1774  // The interesting case.
1775  break;
1776  }
1777 
1778  // Read a record.
1779  Record.clear();
1780  switch (Stream.readRecord(Entry.ID, Record)) {
1781  default: // Default behavior: unknown type.
1782  break;
1783  case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
1784  Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
1785  if (Error Err = ValOrErr.takeError())
1786  return Err;
1787  ValOrErr.get();
1788  break;
1789  }
1790  case bitc::VST_CODE_FNENTRY: {
1791  // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
1792  Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
1793  if (Error Err = ValOrErr.takeError())
1794  return Err;
1795  Value *V = ValOrErr.get();
1796 
1797  auto *GO = dyn_cast<GlobalObject>(V);
1798  if (!GO) {
1799  // If this is an alias, need to get the actual Function object
1800  // it aliases, in order to set up the DeferredFunctionInfo entry below.
1801  auto *GA = dyn_cast<GlobalAlias>(V);
1802  if (GA)
1803  GO = GA->getBaseObject();
1804  assert(GO);
1805  }
1806 
1807  // Note that we subtract 1 here because the offset is relative to one word
1808  // before the start of the identification or module block, which was
1809  // historically always the start of the regular bitcode header.
1810  uint64_t FuncWordOffset = Record[1] - 1;
1811  Function *F = dyn_cast<Function>(GO);
1812  assert(F);
1813  uint64_t FuncBitOffset = FuncWordOffset * 32;
1814  DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
1815  // Set the LastFunctionBlockBit to point to the last function block.
1816  // Later when parsing is resumed after function materialization,
1817  // we can simply skip that last function block.
1818  if (FuncBitOffset > LastFunctionBlockBit)
1819  LastFunctionBlockBit = FuncBitOffset;
1820  break;
1821  }
1822  case bitc::VST_CODE_BBENTRY: {
1823  if (convertToString(Record, 1, ValueName))
1824  return error("Invalid record");
1825  BasicBlock *BB = getBasicBlock(Record[0]);
1826  if (!BB)
1827  return error("Invalid record");
1828 
1829  BB->setName(StringRef(ValueName.data(), ValueName.size()));
1830  ValueName.clear();
1831  break;
1832  }
1833  }
1834  }
1835 }
1836 
1837 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
1838 /// encoding.
1839 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1840  if ((V & 1) == 0)
1841  return V >> 1;
1842  if (V != 1)
1843  return -(V >> 1);
1844  // There is no such thing as -0 with integers. "-0" really means MININT.
1845  return 1ULL << 63;
1846 }
1847 
1848 /// Resolve all of the initializers for global values and aliases that we can.
1849 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
1850  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1851  std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
1852  IndirectSymbolInitWorklist;
1853  std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1854  std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
1855  std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
1856 
1857  GlobalInitWorklist.swap(GlobalInits);
1858  IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
1859  FunctionPrefixWorklist.swap(FunctionPrefixes);
1860  FunctionPrologueWorklist.swap(FunctionPrologues);
1861  FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
1862 
1863  while (!GlobalInitWorklist.empty()) {
1864  unsigned ValID = GlobalInitWorklist.back().second;
1865  if (ValID >= ValueList.size()) {
1866  // Not ready to resolve this yet, it requires something later in the file.
1867  GlobalInits.push_back(GlobalInitWorklist.back());
1868  } else {
1869  if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1870  GlobalInitWorklist.back().first->setInitializer(C);
1871  else
1872  return error("Expected a constant");
1873  }
1874  GlobalInitWorklist.pop_back();
1875  }
1876 
1877  while (!IndirectSymbolInitWorklist.empty()) {
1878  unsigned ValID = IndirectSymbolInitWorklist.back().second;
1879  if (ValID >= ValueList.size()) {
1880  IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
1881  } else {
1882  Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
1883  if (!C)
1884  return error("Expected a constant");
1885  GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
1886  if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
1887  return error("Alias and aliasee types don't match");
1888  GIS->setIndirectSymbol(C);
1889  }
1890  IndirectSymbolInitWorklist.pop_back();
1891  }
1892 
1893  while (!FunctionPrefixWorklist.empty()) {
1894  unsigned ValID = FunctionPrefixWorklist.back().second;
1895  if (ValID >= ValueList.size()) {
1896  FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1897  } else {
1898  if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1899  FunctionPrefixWorklist.back().first->setPrefixData(C);
1900  else
1901  return error("Expected a constant");
1902  }
1903  FunctionPrefixWorklist.pop_back();
1904  }
1905 
1906  while (!FunctionPrologueWorklist.empty()) {
1907  unsigned ValID = FunctionPrologueWorklist.back().second;
1908  if (ValID >= ValueList.size()) {
1909  FunctionPrologues.push_back(FunctionPrologueWorklist.back());
1910  } else {
1911  if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1912  FunctionPrologueWorklist.back().first->setPrologueData(C);
1913  else
1914  return error("Expected a constant");
1915  }
1916  FunctionPrologueWorklist.pop_back();
1917  }
1918 
1919  while (!FunctionPersonalityFnWorklist.empty()) {
1920  unsigned ValID = FunctionPersonalityFnWorklist.back().second;
1921  if (ValID >= ValueList.size()) {
1922  FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
1923  } else {
1924  if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1925  FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
1926  else
1927  return error("Expected a constant");
1928  }
1929  FunctionPersonalityFnWorklist.pop_back();
1930  }
1931 
1932  return Error::success();
1933 }
1934 
1935 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1936  SmallVector<uint64_t, 8> Words(Vals.size());
1937  transform(Vals, Words.begin(),
1938  BitcodeReader::decodeSignRotatedValue);
1939 
1940  return APInt(TypeBits, Words);
1941 }
1942 
1943 Error BitcodeReader::parseConstants() {
1945  return error("Invalid record");
1946 
1948 
1949  // Read all the records for this value table.
1950  Type *CurTy = Type::getInt32Ty(Context);
1951  unsigned NextCstNo = ValueList.size();
1952 
1953  while (true) {
1954  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1955 
1956  switch (Entry.Kind) {
1957  case BitstreamEntry::SubBlock: // Handled for us already.
1958  case BitstreamEntry::Error:
1959  return error("Malformed block");
1960  case BitstreamEntry::EndBlock:
1961  if (NextCstNo != ValueList.size())
1962  return error("Invalid constant reference");
1963 
1964  // Once all the constants have been read, go through and resolve forward
1965  // references.
1966  ValueList.resolveConstantForwardRefs();
1967  return Error::success();
1968  case BitstreamEntry::Record:
1969  // The interesting case.
1970  break;
1971  }
1972 
1973  // Read a record.
1974  Record.clear();
1975  Type *VoidType = Type::getVoidTy(Context);
1976  Value *V = nullptr;
1977  unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1978  switch (BitCode) {
1979  default: // Default behavior: unknown constant
1980  case bitc::CST_CODE_UNDEF: // UNDEF
1981  V = UndefValue::get(CurTy);
1982  break;
1983  case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
1984  if (Record.empty())
1985  return error("Invalid record");
1986  if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1987  return error("Invalid record");
1988  if (TypeList[Record[0]] == VoidType)
1989  return error("Invalid constant type");
1990  CurTy = TypeList[Record[0]];
1991  continue; // Skip the ValueList manipulation.
1992  case bitc::CST_CODE_NULL: // NULL
1993  V = Constant::getNullValue(CurTy);
1994  break;
1995  case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
1996  if (!CurTy->isIntegerTy() || Record.empty())
1997  return error("Invalid record");
1998  V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1999  break;
2000  case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
2001  if (!CurTy->isIntegerTy() || Record.empty())
2002  return error("Invalid record");
2003 
2004  APInt VInt =
2005  readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
2006  V = ConstantInt::get(Context, VInt);
2007 
2008  break;
2009  }
2010  case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
2011  if (Record.empty())
2012  return error("Invalid record");
2013  if (CurTy->isHalfTy())
2014  V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
2015  APInt(16, (uint16_t)Record[0])));
2016  else if (CurTy->isFloatTy())
2017  V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
2018  APInt(32, (uint32_t)Record[0])));
2019  else if (CurTy->isDoubleTy())
2020  V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
2021  APInt(64, Record[0])));
2022  else if (CurTy->isX86_FP80Ty()) {
2023  // Bits are not stored the same way as a normal i80 APInt, compensate.
2024  uint64_t Rearrange[2];
2025  Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2026  Rearrange[1] = Record[0] >> 48;
2027  V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
2028  APInt(80, Rearrange)));
2029  } else if (CurTy->isFP128Ty())
2030  V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
2031  APInt(128, Record)));
2032  else if (CurTy->isPPC_FP128Ty())
2033  V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
2034  APInt(128, Record)));
2035  else
2036  V = UndefValue::get(CurTy);
2037  break;
2038  }
2039 
2040  case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2041  if (Record.empty())
2042  return error("Invalid record");
2043 
2044  unsigned Size = Record.size();
2046 
2047  if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2048  for (unsigned i = 0; i != Size; ++i)
2049  Elts.push_back(ValueList.getConstantFwdRef(Record[i],
2050  STy->getElementType(i)));
2051  V = ConstantStruct::get(STy, Elts);
2052  } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2053  Type *EltTy = ATy->getElementType();
2054  for (unsigned i = 0; i != Size; ++i)
2055  Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2056  V = ConstantArray::get(ATy, Elts);
2057  } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2058  Type *EltTy = VTy->getElementType();
2059  for (unsigned i = 0; i != Size; ++i)
2060  Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
2061  V = ConstantVector::get(Elts);
2062  } else {
2063  V = UndefValue::get(CurTy);
2064  }
2065  break;
2066  }
2067  case bitc::CST_CODE_STRING: // STRING: [values]
2068  case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2069  if (Record.empty())
2070  return error("Invalid record");
2071 
2072  SmallString<16> Elts(Record.begin(), Record.end());
2073  V = ConstantDataArray::getString(Context, Elts,
2074  BitCode == bitc::CST_CODE_CSTRING);
2075  break;
2076  }
2077  case bitc::CST_CODE_DATA: {// DATA: [n x value]
2078  if (Record.empty())
2079  return error("Invalid record");
2080 
2081  Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2082  if (EltTy->isIntegerTy(8)) {
2083  SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2084  if (isa<VectorType>(CurTy))
2085  V = ConstantDataVector::get(Context, Elts);
2086  else
2087  V = ConstantDataArray::get(Context, Elts);
2088  } else if (EltTy->isIntegerTy(16)) {
2089  SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2090  if (isa<VectorType>(CurTy))
2091  V = ConstantDataVector::get(Context, Elts);
2092  else
2093  V = ConstantDataArray::get(Context, Elts);
2094  } else if (EltTy->isIntegerTy(32)) {
2095  SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2096  if (isa<VectorType>(CurTy))
2097  V = ConstantDataVector::get(Context, Elts);
2098  else
2099  V = ConstantDataArray::get(Context, Elts);
2100  } else if (EltTy->isIntegerTy(64)) {
2101  SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2102  if (isa<VectorType>(CurTy))
2103  V = ConstantDataVector::get(Context, Elts);
2104  else
2105  V = ConstantDataArray::get(Context, Elts);
2106  } else if (EltTy->isHalfTy()) {
2107  SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2108  if (isa<VectorType>(CurTy))
2109  V = ConstantDataVector::getFP(Context, Elts);
2110  else
2111  V = ConstantDataArray::getFP(Context, Elts);
2112  } else if (EltTy->isFloatTy()) {
2113  SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2114  if (isa<VectorType>(CurTy))
2115  V = ConstantDataVector::getFP(Context, Elts);
2116  else
2117  V = ConstantDataArray::getFP(Context, Elts);
2118  } else if (EltTy->isDoubleTy()) {
2119  SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2120  if (isa<VectorType>(CurTy))
2121  V = ConstantDataVector::getFP(Context, Elts);
2122  else
2123  V = ConstantDataArray::getFP(Context, Elts);
2124  } else {
2125  return error("Invalid type for value");
2126  }
2127  break;
2128  }
2129  case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
2130  if (Record.size() < 3)
2131  return error("Invalid record");
2132  int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
2133  if (Opc < 0) {
2134  V = UndefValue::get(CurTy); // Unknown binop.
2135  } else {
2136  Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2137  Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
2138  unsigned Flags = 0;
2139  if (Record.size() >= 4) {
2140  if (Opc == Instruction::Add ||
2141  Opc == Instruction::Sub ||
2142  Opc == Instruction::Mul ||
2143  Opc == Instruction::Shl) {
2144  if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2145  Flags |= OverflowingBinaryOperator::NoSignedWrap;
2146  if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2147  Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
2148  } else if (Opc == Instruction::SDiv ||
2149  Opc == Instruction::UDiv ||
2150  Opc == Instruction::LShr ||
2151  Opc == Instruction::AShr) {
2152  if (Record[3] & (1 << bitc::PEO_EXACT))
2153  Flags |= SDivOperator::IsExact;
2154  }
2155  }
2156  V = ConstantExpr::get(Opc, LHS, RHS, Flags);
2157  }
2158  break;
2159  }
2160  case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
2161  if (Record.size() < 3)
2162  return error("Invalid record");
2163  int Opc = getDecodedCastOpcode(Record[0]);
2164  if (Opc < 0) {
2165  V = UndefValue::get(CurTy); // Unknown cast.
2166  } else {
2167  Type *OpTy = getTypeByID(Record[1]);
2168  if (!OpTy)
2169  return error("Invalid record");
2170  Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
2171  V = UpgradeBitCastExpr(Opc, Op, CurTy);
2172  if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
2173  }
2174  break;
2175  }
2176  case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
2177  case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
2178  case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
2179  // operands]
2180  unsigned OpNum = 0;
2181  Type *PointeeType = nullptr;
2183  Record.size() % 2)
2184  PointeeType = getTypeByID(Record[OpNum++]);
2185 
2186  bool InBounds = false;
2187  Optional<unsigned> InRangeIndex;
2189  uint64_t Op = Record[OpNum++];
2190  InBounds = Op & 1;
2191  InRangeIndex = Op >> 1;
2192  } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
2193  InBounds = true;
2194 
2196  while (OpNum != Record.size()) {
2197  Type *ElTy = getTypeByID(Record[OpNum++]);
2198  if (!ElTy)
2199  return error("Invalid record");
2200  Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
2201  }
2202 
2203  if (PointeeType &&
2204  PointeeType !=
2205  cast<PointerType>(Elts[0]->getType()->getScalarType())
2206  ->getElementType())
2207  return error("Explicit gep operator type does not match pointee type "
2208  "of pointer operand");
2209 
2210  if (Elts.size() < 1)
2211  return error("Invalid gep with no operands");
2212 
2213  ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2214  V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2215  InBounds, InRangeIndex);
2216  break;
2217  }
2218  case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
2219  if (Record.size() < 3)
2220  return error("Invalid record");
2221 
2222  Type *SelectorTy = Type::getInt1Ty(Context);
2223 
2224  // The selector might be an i1 or an <n x i1>
2225  // Get the type from the ValueList before getting a forward ref.
2226  if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2227  if (Value *V = ValueList[Record[0]])
2228  if (SelectorTy != V->getType())
2229  SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
2230 
2231  V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2232  SelectorTy),
2233  ValueList.getConstantFwdRef(Record[1],CurTy),
2234  ValueList.getConstantFwdRef(Record[2],CurTy));
2235  break;
2236  }
2238  : { // CE_EXTRACTELT: [opty, opval, opty, opval]
2239  if (Record.size() < 3)
2240  return error("Invalid record");
2241  VectorType *OpTy =
2242  dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2243  if (!OpTy)
2244  return error("Invalid record");
2245  Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2246  Constant *Op1 = nullptr;
2247  if (Record.size() == 4) {
2248  Type *IdxTy = getTypeByID(Record[2]);
2249  if (!IdxTy)
2250  return error("Invalid record");
2251  Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2252  } else // TODO: Remove with llvm 4.0
2253  Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2254  if (!Op1)
2255  return error("Invalid record");
2256  V = ConstantExpr::getExtractElement(Op0, Op1);
2257  break;
2258  }
2260  : { // CE_INSERTELT: [opval, opval, opty, opval]
2261  VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2262  if (Record.size() < 3 || !OpTy)
2263  return error("Invalid record");
2264  Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2265  Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2266  OpTy->getElementType());
2267  Constant *Op2 = nullptr;
2268  if (Record.size() == 4) {
2269  Type *IdxTy = getTypeByID(Record[2]);
2270  if (!IdxTy)
2271  return error("Invalid record");
2272  Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2273  } else // TODO: Remove with llvm 4.0
2274  Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2275  if (!Op2)
2276  return error("Invalid record");
2277  V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
2278  break;
2279  }
2280  case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
2281  VectorType *OpTy = dyn_cast<VectorType>(CurTy);
2282  if (Record.size() < 3 || !OpTy)
2283  return error("Invalid record");
2284  Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2285  Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
2286  Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2287  OpTy->getNumElements());
2288  Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
2289  V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2290  break;
2291  }
2292  case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
2293  VectorType *RTy = dyn_cast<VectorType>(CurTy);
2294  VectorType *OpTy =
2295  dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
2296  if (Record.size() < 4 || !RTy || !OpTy)
2297  return error("Invalid record");
2298  Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2299  Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2300  Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
2301  RTy->getNumElements());
2302  Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
2303  V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
2304  break;
2305  }
2306  case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
2307  if (Record.size() < 4)
2308  return error("Invalid record");
2309  Type *OpTy = getTypeByID(Record[0]);
2310  if (!OpTy)
2311  return error("Invalid record");
2312  Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2313  Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2314 
2315  if (OpTy->isFPOrFPVectorTy())
2316  V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
2317  else
2318  V = ConstantExpr::getICmp(Record[3], Op0, Op1);
2319  break;
2320  }
2321  // This maintains backward compatibility, pre-asm dialect keywords.
2322  // FIXME: Remove with the 4.0 release.
2324  if (Record.size() < 2)
2325  return error("Invalid record");
2326  std::string AsmStr, ConstrStr;
2327  bool HasSideEffects = Record[0] & 1;
2328  bool IsAlignStack = Record[0] >> 1;
2329  unsigned AsmStrSize = Record[1];
2330  if (2+AsmStrSize >= Record.size())
2331  return error("Invalid record");
2332  unsigned ConstStrSize = Record[2+AsmStrSize];
2333  if (3+AsmStrSize+ConstStrSize > Record.size())
2334  return error("Invalid record");
2335 
2336  for (unsigned i = 0; i != AsmStrSize; ++i)
2337  AsmStr += (char)Record[2+i];
2338  for (unsigned i = 0; i != ConstStrSize; ++i)
2339  ConstrStr += (char)Record[3+AsmStrSize+i];
2340  PointerType *PTy = cast<PointerType>(CurTy);
2341  V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2342  AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
2343  break;
2344  }
2345  // This version adds support for the asm dialect keywords (e.g.,
2346  // inteldialect).
2347  case bitc::CST_CODE_INLINEASM: {
2348  if (Record.size() < 2)
2349  return error("Invalid record");
2350  std::string AsmStr, ConstrStr;
2351  bool HasSideEffects = Record[0] & 1;
2352  bool IsAlignStack = (Record[0] >> 1) & 1;
2353  unsigned AsmDialect = Record[0] >> 2;
2354  unsigned AsmStrSize = Record[1];
2355  if (2+AsmStrSize >= Record.size())
2356  return error("Invalid record");
2357  unsigned ConstStrSize = Record[2+AsmStrSize];
2358  if (3+AsmStrSize+ConstStrSize > Record.size())
2359  return error("Invalid record");
2360 
2361  for (unsigned i = 0; i != AsmStrSize; ++i)
2362  AsmStr += (char)Record[2+i];
2363  for (unsigned i = 0; i != ConstStrSize; ++i)
2364  ConstrStr += (char)Record[3+AsmStrSize+i];
2365  PointerType *PTy = cast<PointerType>(CurTy);
2366  V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2367  AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
2368  InlineAsm::AsmDialect(AsmDialect));
2369  break;
2370  }
2372  if (Record.size() < 3)
2373  return error("Invalid record");
2374  Type *FnTy = getTypeByID(Record[0]);
2375  if (!FnTy)
2376  return error("Invalid record");
2377  Function *Fn =
2378  dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
2379  if (!Fn)
2380  return error("Invalid record");
2381 
2382  // If the function is already parsed we can insert the block address right
2383  // away.
2384  BasicBlock *BB;
2385  unsigned BBID = Record[2];
2386  if (!BBID)
2387  // Invalid reference to entry block.
2388  return error("Invalid ID");
2389  if (!Fn->empty()) {
2390  Function::iterator BBI = Fn->begin(), BBE = Fn->end();
2391  for (size_t I = 0, E = BBID; I != E; ++I) {
2392  if (BBI == BBE)
2393  return error("Invalid ID");
2394  ++BBI;
2395  }
2396  BB = &*BBI;
2397  } else {
2398  // Otherwise insert a placeholder and remember it so it can be inserted
2399  // when the function is parsed.
2400  auto &FwdBBs = BasicBlockFwdRefs[Fn];
2401  if (FwdBBs.empty())
2402  BasicBlockFwdRefQueue.push_back(Fn);
2403  if (FwdBBs.size() < BBID + 1)
2404  FwdBBs.resize(BBID + 1);
2405  if (!FwdBBs[BBID])
2406  FwdBBs[BBID] = BasicBlock::Create(Context);
2407  BB = FwdBBs[BBID];
2408  }
2409  V = BlockAddress::get(Fn, BB);
2410  break;
2411  }
2412  }
2413 
2414  ValueList.assignValue(V, NextCstNo);
2415  ++NextCstNo;
2416  }
2417 }
2418 
2419 Error BitcodeReader::parseUseLists() {
2421  return error("Invalid record");
2422 
2423  // Read all the records.
2425 
2426  while (true) {
2427  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2428 
2429  switch (Entry.Kind) {
2430  case BitstreamEntry::SubBlock: // Handled for us already.
2431  case BitstreamEntry::Error:
2432  return error("Malformed block");
2433  case BitstreamEntry::EndBlock:
2434  return Error::success();
2435  case BitstreamEntry::Record:
2436  // The interesting case.
2437  break;
2438  }
2439 
2440  // Read a use list record.
2441  Record.clear();
2442  bool IsBB = false;
2443  switch (Stream.readRecord(Entry.ID, Record)) {
2444  default: // Default behavior: unknown type.
2445  break;
2446  case bitc::USELIST_CODE_BB:
2447  IsBB = true;
2450  unsigned RecordLength = Record.size();
2451  if (RecordLength < 3)
2452  // Records should have at least an ID and two indexes.
2453  return error("Invalid record");
2454  unsigned ID = Record.back();
2455  Record.pop_back();
2456 
2457  Value *V;
2458  if (IsBB) {
2459  assert(ID < FunctionBBs.size() && "Basic block not found");
2460  V = FunctionBBs[ID];
2461  } else
2462  V = ValueList[ID];
2463  unsigned NumUses = 0;
2465  for (const Use &U : V->materialized_uses()) {
2466  if (++NumUses > Record.size())
2467  break;
2468  Order[&U] = Record[NumUses - 1];
2469  }
2470  if (Order.size() != Record.size() || NumUses > Record.size())
2471  // Mismatches can happen if the functions are being materialized lazily
2472  // (out-of-order), or a value has been upgraded.
2473  break;
2474 
2475  V->sortUseList([&](const Use &L, const Use &R) {
2476  return Order.lookup(&L) < Order.lookup(&R);
2477  });
2478  break;
2479  }
2480  }
2481  }
2482 }
2483 
2484 /// When we see the block for metadata, remember where it is and then skip it.
2485 /// This lets us lazily deserialize the metadata.
2486 Error BitcodeReader::rememberAndSkipMetadata() {
2487  // Save the current stream state.
2488  uint64_t CurBit = Stream.GetCurrentBitNo();
2489  DeferredMetadataInfo.push_back(CurBit);
2490 
2491  // Skip over the block for now.
2492  if (Stream.SkipBlock())
2493  return error("Invalid record");
2494  return Error::success();
2495 }
2496 
2497 Error BitcodeReader::materializeMetadata() {
2498  for (uint64_t BitPos : DeferredMetadataInfo) {
2499  // Move the bit stream to the saved position.
2500  Stream.JumpToBit(BitPos);
2501  if (Error Err = MDLoader->parseModuleMetadata())
2502  return Err;
2503  }
2504  DeferredMetadataInfo.clear();
2505  return Error::success();
2506 }
2507 
2508 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
2509 
2510 /// When we see the block for a function body, remember where it is and then
2511 /// skip it. This lets us lazily deserialize the functions.
2512 Error BitcodeReader::rememberAndSkipFunctionBody() {
2513  // Get the function we are talking about.
2514  if (FunctionsWithBodies.empty())
2515  return error("Insufficient function protos");
2516 
2517  Function *Fn = FunctionsWithBodies.back();
2518  FunctionsWithBodies.pop_back();
2519 
2520  // Save the current stream state.
2521  uint64_t CurBit = Stream.GetCurrentBitNo();
2522  assert(
2523  (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
2524  "Mismatch between VST and scanned function offsets");
2525  DeferredFunctionInfo[Fn] = CurBit;
2526 
2527  // Skip over the function block for now.
2528  if (Stream.SkipBlock())
2529  return error("Invalid record");
2530  return Error::success();
2531 }
2532 
2533 Error BitcodeReader::globalCleanup() {
2534  // Patch the initializers for globals and aliases up.
2535  if (Error Err = resolveGlobalAndIndirectSymbolInits())
2536  return Err;
2537  if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
2538  return error("Malformed global initializer set");
2539 
2540  // Look for intrinsic functions which need to be upgraded at some point
2541  for (Function &F : *TheModule) {
2542  Function *NewFn;
2543  if (UpgradeIntrinsicFunction(&F, NewFn))
2544  UpgradedIntrinsics[&F] = NewFn;
2545  else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
2546  // Some types could be renamed during loading if several modules are
2547  // loaded in the same LLVMContext (LTO scenario). In this case we should
2548  // remangle intrinsics names as well.
2549  RemangledIntrinsics[&F] = Remangled.getValue();
2550  }
2551 
2552  // Look for global variables which need to be renamed.
2553  for (GlobalVariable &GV : TheModule->globals())
2554  UpgradeGlobalVariable(&GV);
2555 
2556  // Force deallocation of memory for these vectors to favor the client that
2557  // want lazy deserialization.
2558  std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2559  std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
2560  IndirectSymbolInits);
2561  return Error::success();
2562 }
2563 
2564 /// Support for lazy parsing of function bodies. This is required if we
2565 /// either have an old bitcode file without a VST forward declaration record,
2566 /// or if we have an anonymous function being materialized, since anonymous
2567 /// functions do not have a name and are therefore not in the VST.
2568 Error BitcodeReader::rememberAndSkipFunctionBodies() {
2569  Stream.JumpToBit(NextUnreadBit);
2570 
2571  if (Stream.AtEndOfStream())
2572  return error("Could not find function in stream");
2573 
2574  if (!SeenFirstFunctionBody)
2575  return error("Trying to materialize functions before seeing function blocks");
2576 
2577  // An old bitcode file with the symbol table at the end would have
2578  // finished the parse greedily.
2579  assert(SeenValueSymbolTable);
2580 
2582 
2583  while (true) {
2584  BitstreamEntry Entry = Stream.advance();
2585  switch (Entry.Kind) {
2586  default:
2587  return error("Expect SubBlock");
2588  case BitstreamEntry::SubBlock:
2589  switch (Entry.ID) {
2590  default:
2591  return error("Expect function block");
2593  if (Error Err = rememberAndSkipFunctionBody())
2594  return Err;
2595  NextUnreadBit = Stream.GetCurrentBitNo();
2596  return Error::success();
2597  }
2598  }
2599  }
2600 }
2601 
2602 bool BitcodeReaderBase::readBlockInfo() {
2603  Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
2604  if (!NewBlockInfo)
2605  return true;
2606  BlockInfo = std::move(*NewBlockInfo);
2607  return false;
2608 }
2609 
2610 Error BitcodeReader::parseModule(uint64_t ResumeBit,
2611  bool ShouldLazyLoadMetadata) {
2612  if (ResumeBit)
2613  Stream.JumpToBit(ResumeBit);
2614  else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2615  return error("Invalid record");
2616 
2618  std::vector<std::string> SectionTable;
2619  std::vector<std::string> GCTable;
2620 
2621  // Read all the records for this module.
2622  while (true) {
2623  BitstreamEntry Entry = Stream.advance();
2624 
2625  switch (Entry.Kind) {
2626  case BitstreamEntry::Error:
2627  return error("Malformed block");
2628  case BitstreamEntry::EndBlock:
2629  return globalCleanup();
2630 
2631  case BitstreamEntry::SubBlock:
2632  switch (Entry.ID) {
2633  default: // Skip unknown content.
2634  if (Stream.SkipBlock())
2635  return error("Invalid record");
2636  break;
2638  if (readBlockInfo())
2639  return error("Malformed block");
2640  break;
2642  if (Error Err = parseAttributeBlock())
2643  return Err;
2644  break;
2646  if (Error Err = parseAttributeGroupBlock())
2647  return Err;
2648  break;
2650  if (Error Err = parseTypeTable())
2651  return Err;
2652  break;
2654  if (!SeenValueSymbolTable) {
2655  // Either this is an old form VST without function index and an
2656  // associated VST forward declaration record (which would have caused
2657  // the VST to be jumped to and parsed before it was encountered
2658  // normally in the stream), or there were no function blocks to
2659  // trigger an earlier parsing of the VST.
2660  assert(VSTOffset == 0 || FunctionsWithBodies.empty());
2661  if (Error Err = parseValueSymbolTable())
2662  return Err;
2663  SeenValueSymbolTable = true;
2664  } else {
2665  // We must have had a VST forward declaration record, which caused
2666  // the parser to jump to and parse the VST earlier.
2667  assert(VSTOffset > 0);
2668  if (Stream.SkipBlock())
2669  return error("Invalid record");
2670  }
2671  break;
2673  if (Error Err = parseConstants())
2674  return Err;
2675  if (Error Err = resolveGlobalAndIndirectSymbolInits())
2676  return Err;
2677  break;
2679  if (ShouldLazyLoadMetadata) {
2680  if (Error Err = rememberAndSkipMetadata())
2681  return Err;
2682  break;
2683  }
2684  assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
2685  if (Error Err = MDLoader->parseModuleMetadata())
2686  return Err;
2687  break;
2689  if (Error Err = MDLoader->parseMetadataKinds())
2690  return Err;
2691  break;
2693  // If this is the first function body we've seen, reverse the
2694  // FunctionsWithBodies list.
2695  if (!SeenFirstFunctionBody) {
2696  std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2697  if (Error Err = globalCleanup())
2698  return Err;
2699  SeenFirstFunctionBody = true;
2700  }
2701 
2702  if (VSTOffset > 0) {
2703  // If we have a VST forward declaration record, make sure we
2704  // parse the VST now if we haven't already. It is needed to
2705  // set up the DeferredFunctionInfo vector for lazy reading.
2706  if (!SeenValueSymbolTable) {
2707  if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
2708  return Err;
2709  SeenValueSymbolTable = true;
2710  // Fall through so that we record the NextUnreadBit below.
2711  // This is necessary in case we have an anonymous function that
2712  // is later materialized. Since it will not have a VST entry we
2713  // need to fall back to the lazy parse to find its offset.
2714  } else {
2715  // If we have a VST forward declaration record, but have already
2716  // parsed the VST (just above, when the first function body was
2717  // encountered here), then we are resuming the parse after
2718  // materializing functions. The ResumeBit points to the
2719  // start of the last function block recorded in the
2720  // DeferredFunctionInfo map. Skip it.
2721  if (Stream.SkipBlock())
2722  return error("Invalid record");
2723  continue;
2724  }
2725  }
2726 
2727  // Support older bitcode files that did not have the function
2728  // index in the VST, nor a VST forward declaration record, as
2729  // well as anonymous functions that do not have VST entries.
2730  // Build the DeferredFunctionInfo vector on the fly.
2731  if (Error Err = rememberAndSkipFunctionBody())
2732  return Err;
2733 
2734  // Suspend parsing when we reach the function bodies. Subsequent
2735  // materialization calls will resume it when necessary. If the bitcode
2736  // file is old, the symbol table will be at the end instead and will not
2737  // have been seen yet. In this case, just finish the parse now.
2738  if (SeenValueSymbolTable) {
2739  NextUnreadBit = Stream.GetCurrentBitNo();
2740  // After the VST has been parsed, we need to make sure intrinsic name
2741  // are auto-upgraded.
2742  return globalCleanup();
2743  }
2744  break;
2746  if (Error Err = parseUseLists())
2747  return Err;
2748  break;
2750  if (Error Err = parseOperandBundleTags())
2751  return Err;
2752  break;
2753  }
2754  continue;
2755 
2756  case BitstreamEntry::Record:
2757  // The interesting case.
2758  break;
2759  }
2760 
2761  // Read a record.
2762  auto BitCode = Stream.readRecord(Entry.ID, Record);
2763  switch (BitCode) {
2764  default: break; // Default behavior, ignore unknown content.
2765  case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
2766  if (Record.size() < 1)
2767  return error("Invalid record");
2768  // Only version #0 and #1 are supported so far.
2769  unsigned module_version = Record[0];
2770  switch (module_version) {
2771  default:
2772  return error("Invalid value");
2773  case 0:
2774  UseRelativeIDs = false;
2775  break;
2776  case 1:
2777  UseRelativeIDs = true;
2778  break;
2779  }
2780  break;
2781  }
2782  case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
2783  std::string S;
2784  if (convertToString(Record, 0, S))
2785  return error("Invalid record");
2786  TheModule->setTargetTriple(S);
2787  break;
2788  }
2789  case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
2790  std::string S;
2791  if (convertToString(Record, 0, S))
2792  return error("Invalid record");
2793  TheModule->setDataLayout(S);
2794  break;
2795  }
2796  case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
2797  std::string S;
2798  if (convertToString(Record, 0, S))
2799  return error("Invalid record");
2800  TheModule->setModuleInlineAsm(S);
2801  break;
2802  }
2803  case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2804  // FIXME: Remove in 4.0.
2805  std::string S;
2806  if (convertToString(Record, 0, S))
2807  return error("Invalid record");
2808  // Ignore value.
2809  break;
2810  }
2811  case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
2812  std::string S;
2813  if (convertToString(Record, 0, S))
2814  return error("Invalid record");
2815  SectionTable.push_back(S);
2816  break;
2817  }
2818  case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
2819  std::string S;
2820  if (convertToString(Record, 0, S))
2821  return error("Invalid record");
2822  GCTable.push_back(S);
2823  break;
2824  }
2825  case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2826  if (Record.size() < 2)
2827  return error("Invalid record");
2829  unsigned ComdatNameSize = Record[1];
2830  std::string ComdatName;
2831  ComdatName.reserve(ComdatNameSize);
2832  for (unsigned i = 0; i != ComdatNameSize; ++i)
2833  ComdatName += (char)Record[2 + i];
2834  Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2835  C->setSelectionKind(SK);
2836  ComdatList.push_back(C);
2837  break;
2838  }
2839  // GLOBALVAR: [pointer type, isconst, initid,
2840  // linkage, alignment, section, visibility, threadlocal,
2841  // unnamed_addr, externally_initialized, dllstorageclass,
2842  // comdat]
2844  if (Record.size() < 6)
2845  return error("Invalid record");
2846  Type *Ty = getTypeByID(Record[0]);
2847  if (!Ty)
2848  return error("Invalid record");
2849  bool isConstant = Record[1] & 1;
2850  bool explicitType = Record[1] & 2;
2851  unsigned AddressSpace;
2852  if (explicitType) {
2853  AddressSpace = Record[1] >> 2;
2854  } else {
2855  if (!Ty->isPointerTy())
2856  return error("Invalid type for value");
2857  AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2858  Ty = cast<PointerType>(Ty)->getElementType();
2859  }
2860 
2861  uint64_t RawLinkage = Record[3];
2862  GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2863  unsigned Alignment;
2864  if (Error Err = parseAlignmentValue(Record[4], Alignment))
2865  return Err;
2866  std::string Section;
2867  if (Record[5]) {
2868  if (Record[5]-1 >= SectionTable.size())
2869  return error("Invalid ID");
2870  Section = SectionTable[Record[5]-1];
2871  }
2872  GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2873  // Local linkage must have default visibility.
2874  if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
2875  // FIXME: Change to an error if non-default in 4.0.
2876  Visibility = getDecodedVisibility(Record[6]);
2877 
2878  GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2879  if (Record.size() > 7)
2880  TLM = getDecodedThreadLocalMode(Record[7]);
2881 
2883  if (Record.size() > 8)
2884  UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
2885 
2886  bool ExternallyInitialized = false;
2887  if (Record.size() > 9)
2888  ExternallyInitialized = Record[9];
2889 
2890  GlobalVariable *NewGV =
2891  new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2892  TLM, AddressSpace, ExternallyInitialized);
2893  NewGV->setAlignment(Alignment);
2894  if (!Section.empty())
2895  NewGV->setSection(Section);
2896  NewGV->setVisibility(Visibility);
2897  NewGV->setUnnamedAddr(UnnamedAddr);
2898 
2899  if (Record.size() > 10)
2900  NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
2901  else
2902  upgradeDLLImportExportLinkage(NewGV, RawLinkage);
2903 
2904  ValueList.push_back(NewGV);
2905 
2906  // Remember which value to use for the global initializer.
2907  if (unsigned InitID = Record[2])
2908  GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2909 
2910  if (Record.size() > 11) {
2911  if (unsigned ComdatID = Record[11]) {
2912  if (ComdatID > ComdatList.size())
2913  return error("Invalid global variable comdat ID");
2914  NewGV->setComdat(ComdatList[ComdatID - 1]);
2915  }
2916  } else if (hasImplicitComdat(RawLinkage)) {
2917  NewGV->setComdat(reinterpret_cast<Comdat *>(1));
2918  }
2919 
2920  break;
2921  }
2922  // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
2923  // alignment, section, visibility, gc, unnamed_addr,
2924  // prologuedata, dllstorageclass, comdat, prefixdata]
2926  if (Record.size() < 8)
2927  return error("Invalid record");
2928  Type *Ty = getTypeByID(Record[0]);
2929  if (!Ty)
2930  return error("Invalid record");
2931  if (auto *PTy = dyn_cast<PointerType>(Ty))
2932  Ty = PTy->getElementType();
2933  auto *FTy = dyn_cast<FunctionType>(Ty);
2934  if (!FTy)
2935  return error("Invalid type for value");
2936  auto CC = static_cast<CallingConv::ID>(Record[1]);
2937  if (CC & ~CallingConv::MaxID)
2938  return error("Invalid calling convention ID");
2939 
2940  Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2941  "", TheModule);
2942 
2943  Func->setCallingConv(CC);
2944  bool isProto = Record[2];
2945  uint64_t RawLinkage = Record[3];
2946  Func->setLinkage(getDecodedLinkage(RawLinkage));
2947  Func->setAttributes(getAttributes(Record[4]));
2948 
2949  unsigned Alignment;
2950  if (Error Err = parseAlignmentValue(Record[5], Alignment))
2951  return Err;
2952  Func->setAlignment(Alignment);
2953  if (Record[6]) {
2954  if (Record[6]-1 >= SectionTable.size())
2955  return error("Invalid ID");
2956  Func->setSection(SectionTable[Record[6]-1]);
2957  }
2958  // Local linkage must have default visibility.
2959  if (!Func->hasLocalLinkage())
2960  // FIXME: Change to an error if non-default in 4.0.
2961  Func->setVisibility(getDecodedVisibility(Record[7]));
2962  if (Record.size() > 8 && Record[8]) {
2963  if (Record[8]-1 >= GCTable.size())
2964  return error("Invalid ID");
2965  Func->setGC(GCTable[Record[8] - 1]);
2966  }
2968  if (Record.size() > 9)
2969  UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
2970  Func->setUnnamedAddr(UnnamedAddr);
2971  if (Record.size() > 10 && Record[10] != 0)
2972  FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
2973 
2974  if (Record.size() > 11)
2975  Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
2976  else
2977  upgradeDLLImportExportLinkage(Func, RawLinkage);
2978 
2979  if (Record.size() > 12) {
2980  if (unsigned ComdatID = Record[12]) {
2981  if (ComdatID > ComdatList.size())
2982  return error("Invalid function comdat ID");
2983  Func->setComdat(ComdatList[ComdatID - 1]);
2984  }
2985  } else if (hasImplicitComdat(RawLinkage)) {
2986  Func->setComdat(reinterpret_cast<Comdat *>(1));
2987  }
2988 
2989  if (Record.size() > 13 && Record[13] != 0)
2990  FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
2991 
2992  if (Record.size() > 14 && Record[14] != 0)
2993  FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
2994 
2995  ValueList.push_back(Func);
2996 
2997  // If this is a function with a body, remember the prototype we are
2998  // creating now, so that we can match up the body with them later.
2999  if (!isProto) {
3000  Func->setIsMaterializable(true);
3001  FunctionsWithBodies.push_back(Func);
3002  DeferredFunctionInfo[Func] = 0;
3003  }
3004  break;
3005  }
3006  // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3007  // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3008  // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3012  bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
3013  if (Record.size() < (3 + (unsigned)NewRecord))
3014  return error("Invalid record");
3015  unsigned OpNum = 0;
3016  Type *Ty = getTypeByID(Record[OpNum++]);
3017  if (!Ty)
3018  return error("Invalid record");
3019 
3020  unsigned AddrSpace;
3021  if (!NewRecord) {
3022  auto *PTy = dyn_cast<PointerType>(Ty);
3023  if (!PTy)
3024  return error("Invalid type for value");
3025  Ty = PTy->getElementType();
3026  AddrSpace = PTy->getAddressSpace();
3027  } else {
3028  AddrSpace = Record[OpNum++];
3029  }
3030 
3031  auto Val = Record[OpNum++];
3032  auto Linkage = Record[OpNum++];
3033  GlobalIndirectSymbol *NewGA;
3034  if (BitCode == bitc::MODULE_CODE_ALIAS ||
3035  BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3036  NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3037  "", TheModule);
3038  else
3039  NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
3040  "", nullptr, TheModule);
3041  // Old bitcode files didn't have visibility field.
3042  // Local linkage must have default visibility.
3043  if (OpNum != Record.size()) {
3044  auto VisInd = OpNum++;
3045  if (!NewGA->hasLocalLinkage())
3046  // FIXME: Change to an error if non-default in 4.0.
3047  NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3048  }
3049  if (OpNum != Record.size())
3050  NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
3051  else
3052  upgradeDLLImportExportLinkage(NewGA, Linkage);
3053  if (OpNum != Record.size())
3054  NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3055  if (OpNum != Record.size())
3056  NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
3057  ValueList.push_back(NewGA);
3058  IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
3059  break;
3060  }
3061  /// MODULE_CODE_PURGEVALS: [numvals]
3063  // Trim down the value list to the specified size.
3064  if (Record.size() < 1 || Record[0] > ValueList.size())
3065  return error("Invalid record");
3066  ValueList.shrinkTo(Record[0]);
3067  break;
3068  /// MODULE_CODE_VSTOFFSET: [offset]
3070  if (Record.size() < 1)
3071  return error("Invalid record");
3072  // Note that we subtract 1 here because the offset is relative to one word
3073  // before the start of the identification or module block, which was
3074  // historically always the start of the regular bitcode header.
3075  VSTOffset = Record[0] - 1;
3076  break;
3077  /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3080  if (convertToString(Record, 0, ValueName))
3081  return error("Invalid record");
3082  TheModule->setSourceFileName(ValueName);
3083  break;
3084  }
3085  Record.clear();
3086  }
3087 }
3088 
3089 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
3090  bool IsImporting) {
3091  TheModule = M;
3092  MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting,
3093  [&](unsigned ID) { return getTypeByID(ID); });
3094  return parseModule(0, ShouldLazyLoadMetadata);
3095 }
3096 
3097 
3098 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3099  if (!isa<PointerType>(PtrType))
3100  return error("Load/Store operand is not a pointer type");
3101  Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3102 
3103  if (ValType && ValType != ElemType)
3104  return error("Explicit load/store type does not match pointee "
3105  "type of pointer operand");
3106  if (!PointerType::isLoadableOrStorableType(ElemType))
3107  return error("Cannot load/store from pointer");
3108  return Error::success();
3109 }
3110 
3111 /// Lazily parse the specified function body block.
3112 Error BitcodeReader::parseFunctionBody(Function *F) {
3114  return error("Invalid record");
3115 
3116  // Unexpected unresolved metadata when parsing function.
3117  if (MDLoader->hasFwdRefs())
3118  return error("Invalid function metadata: incoming forward references");
3119 
3120  InstructionList.clear();
3121  unsigned ModuleValueListSize = ValueList.size();
3122  unsigned ModuleMDLoaderSize = MDLoader->size();
3123 
3124  // Add all the function arguments to the value table.
3125  for (Argument &I : F->args())
3126  ValueList.push_back(&I);
3127 
3128  unsigned NextValueNo = ValueList.size();
3129  BasicBlock *CurBB = nullptr;
3130  unsigned CurBBNo = 0;
3131 
3132  DebugLoc LastLoc;
3133  auto getLastInstruction = [&]() -> Instruction * {
3134  if (CurBB && !CurBB->empty())
3135  return &CurBB->back();
3136  else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3137  !FunctionBBs[CurBBNo - 1]->empty())
3138  return &FunctionBBs[CurBBNo - 1]->back();
3139  return nullptr;
3140  };
3141 
3142  std::vector<OperandBundleDef> OperandBundles;
3143 
3144  // Read all the records.
3146 
3147  while (true) {
3148  BitstreamEntry Entry = Stream.advance();
3149 
3150  switch (Entry.Kind) {
3151  case BitstreamEntry::Error:
3152  return error("Malformed block");
3153  case BitstreamEntry::EndBlock:
3154  goto OutOfRecordLoop;
3155 
3156  case BitstreamEntry::SubBlock:
3157  switch (Entry.ID) {
3158  default: // Skip unknown content.
3159  if (Stream.SkipBlock())
3160  return error("Invalid record");
3161  break;
3163  if (Error Err = parseConstants())
3164  return Err;
3165  NextValueNo = ValueList.size();
3166  break;
3168  if (Error Err = parseValueSymbolTable())
3169  return Err;
3170  break;
3172  if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
3173  return Err;
3174  break;
3176  assert(DeferredMetadataInfo.empty() &&
3177  "Must read all module-level metadata before function-level");
3178  if (Error Err = MDLoader->parseFunctionMetadata())
3179  return Err;
3180  break;
3182  if (Error Err = parseUseLists())
3183  return Err;
3184  break;
3185  }
3186  continue;
3187 
3188  case BitstreamEntry::Record:
3189  // The interesting case.
3190  break;
3191  }
3192 
3193  // Read a record.
3194  Record.clear();
3195  Instruction *I = nullptr;
3196  unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3197  switch (BitCode) {
3198  default: // Default behavior: reject
3199  return error("Invalid value");
3200  case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
3201  if (Record.size() < 1 || Record[0] == 0)
3202  return error("Invalid record");
3203  // Create all the basic blocks for the function.
3204  FunctionBBs.resize(Record[0]);
3205 
3206  // See if anything took the address of blocks in this function.
3207  auto BBFRI = BasicBlockFwdRefs.find(F);
3208  if (BBFRI == BasicBlockFwdRefs.end()) {
3209  for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3210  FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3211  } else {
3212  auto &BBRefs = BBFRI->second;
3213  // Check for invalid basic block references.
3214  if (BBRefs.size() > FunctionBBs.size())
3215  return error("Invalid ID");
3216  assert(!BBRefs.empty() && "Unexpected empty array");
3217  assert(!BBRefs.front() && "Invalid reference to entry block");
3218  for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3219  ++I)
3220  if (I < RE && BBRefs[I]) {
3221  BBRefs[I]->insertInto(F);
3222  FunctionBBs[I] = BBRefs[I];
3223  } else {
3224  FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3225  }
3226 
3227  // Erase from the table.
3228  BasicBlockFwdRefs.erase(BBFRI);
3229  }
3230 
3231  CurBB = FunctionBBs[0];
3232  continue;
3233  }
3234 
3235  case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3236  // This record indicates that the last instruction is at the same
3237  // location as the previous instruction with a location.
3238  I = getLastInstruction();
3239 
3240  if (!I)
3241  return error("Invalid record");
3242  I->setDebugLoc(LastLoc);
3243  I = nullptr;
3244  continue;
3245 
3246  case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
3247  I = getLastInstruction();
3248  if (!I || Record.size() < 4)
3249  return error("Invalid record");
3250 
3251  unsigned Line = Record[0], Col = Record[1];
3252  unsigned ScopeID = Record[2], IAID = Record[3];
3253 
3254  MDNode *Scope = nullptr, *IA = nullptr;
3255  if (ScopeID) {
3256  Scope = MDLoader->getMDNodeFwdRefOrNull(ScopeID - 1);
3257  if (!Scope)
3258  return error("Invalid record");
3259  }
3260  if (IAID) {
3261  IA = MDLoader->getMDNodeFwdRefOrNull(IAID - 1);
3262  if (!IA)
3263  return error("Invalid record");
3264  }
3265  LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3266  I->setDebugLoc(LastLoc);
3267  I = nullptr;
3268  continue;
3269  }
3270 
3271  case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3272  unsigned OpNum = 0;
3273  Value *LHS, *RHS;
3274  if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3275  popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
3276  OpNum+1 > Record.size())
3277  return error("Invalid record");
3278 
3279  int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
3280  if (Opc == -1)
3281  return error("Invalid record");
3282  I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
3283  InstructionList.push_back(I);
3284  if (OpNum < Record.size()) {
3285  if (Opc == Instruction::Add ||
3286  Opc == Instruction::Sub ||
3287  Opc == Instruction::Mul ||
3288  Opc == Instruction::Shl) {
3289  if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3290  cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
3291  if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3292  cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
3293  } else if (Opc == Instruction::SDiv ||
3294  Opc == Instruction::UDiv ||
3295  Opc == Instruction::LShr ||
3296  Opc == Instruction::AShr) {
3297  if (Record[OpNum] & (1 << bitc::PEO_EXACT))
3298  cast<BinaryOperator>(I)->setIsExact(true);
3299  } else if (isa<FPMathOperator>(I)) {
3300  FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
3301  if (FMF.any())
3302  I->setFastMathFlags(FMF);
3303  }
3304 
3305  }
3306  break;
3307  }
3308  case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3309  unsigned OpNum = 0;
3310  Value *Op;
3311  if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3312  OpNum+2 != Record.size())
3313  return error("Invalid record");
3314 
3315  Type *ResTy = getTypeByID(Record[OpNum]);
3316  int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
3317  if (Opc == -1 || !ResTy)
3318  return error("Invalid record");
3319  Instruction *Temp = nullptr;
3320  if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3321  if (Temp) {
3322  InstructionList.push_back(Temp);
3323  CurBB->getInstList().push_back(Temp);
3324  }
3325  } else {
3326  auto CastOp = (Instruction::CastOps)Opc;
3327  if (!CastInst::castIsValid(CastOp, Op, ResTy))
3328  return error("Invalid cast");
3329  I = CastInst::Create(CastOp, Op, ResTy);
3330  }
3331  InstructionList.push_back(I);
3332  break;
3333  }
3336  case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
3337  unsigned OpNum = 0;
3338 
3339  Type *Ty;
3340  bool InBounds;
3341 
3342  if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3343  InBounds = Record[OpNum++];
3344  Ty = getTypeByID(Record[OpNum++]);
3345  } else {
3346  InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3347  Ty = nullptr;
3348  }
3349 
3350  Value *BasePtr;
3351  if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
3352  return error("Invalid record");
3353 
3354  if (!Ty)
3355  Ty = cast<PointerType>(BasePtr->getType()->getScalarType())
3356  ->getElementType();
3357  else if (Ty !=
3358  cast<PointerType>(BasePtr->getType()->getScalarType())
3359  ->getElementType())
3360  return error(
3361  "Explicit gep type does not match pointee type of pointer operand");
3362 
3363  SmallVector<Value*, 16> GEPIdx;
3364  while (OpNum != Record.size()) {
3365  Value *Op;
3366  if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3367  return error("Invalid record");
3368  GEPIdx.push_back(Op);
3369  }
3370 
3371  I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
3372 
3373  InstructionList.push_back(I);
3374  if (InBounds)
3375  cast<GetElementPtrInst>(I)->setIsInBounds(true);
3376  break;
3377  }
3378 
3380  // EXTRACTVAL: [opty, opval, n x indices]
3381  unsigned OpNum = 0;
3382  Value *Agg;
3383  if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3384  return error("Invalid record");
3385 
3386  unsigned RecSize = Record.size();
3387  if (OpNum == RecSize)
3388  return error("EXTRACTVAL: Invalid instruction with 0 indices");
3389 
3390  SmallVector<unsigned, 4> EXTRACTVALIdx;
3391  Type *CurTy = Agg->getType();
3392  for (; OpNum != RecSize; ++OpNum) {
3393  bool IsArray = CurTy->isArrayTy();
3394  bool IsStruct = CurTy->isStructTy();
3395  uint64_t Index = Record[OpNum];
3396 
3397  if (!IsStruct && !IsArray)
3398  return error("EXTRACTVAL: Invalid type");
3399  if ((unsigned)Index != Index)
3400  return error("Invalid value");
3401  if (IsStruct && Index >= CurTy->subtypes().size())
3402  return error("EXTRACTVAL: Invalid struct index");
3403  if (IsArray && Index >= CurTy->getArrayNumElements())
3404  return error("EXTRACTVAL: Invalid array index");
3405  EXTRACTVALIdx.push_back((unsigned)Index);
3406 
3407  if (IsStruct)
3408  CurTy = CurTy->subtypes()[Index];
3409  else
3410  CurTy = CurTy->subtypes()[0];
3411  }
3412 
3413  I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
3414  InstructionList.push_back(I);
3415  break;
3416  }
3417 
3419  // INSERTVAL: [opty, opval, opty, opval, n x indices]
3420  unsigned OpNum = 0;
3421  Value *Agg;
3422  if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
3423  return error("Invalid record");
3424  Value *Val;
3425  if (getValueTypePair(Record, OpNum, NextValueNo, Val))
3426  return error("Invalid record");
3427 
3428  unsigned RecSize = Record.size();
3429  if (OpNum == RecSize)
3430  return error("INSERTVAL: Invalid instruction with 0 indices");
3431 
3432  SmallVector<unsigned, 4> INSERTVALIdx;
3433  Type *CurTy = Agg->getType();
3434  for (; OpNum != RecSize; ++OpNum) {
3435  bool IsArray = CurTy->isArrayTy();
3436  bool IsStruct = CurTy->isStructTy();
3437  uint64_t Index = Record[OpNum];
3438 
3439  if (!IsStruct && !IsArray)
3440  return error("INSERTVAL: Invalid type");
3441  if ((unsigned)Index != Index)
3442  return error("Invalid value");
3443  if (IsStruct && Index >= CurTy->subtypes().size())
3444  return error("INSERTVAL: Invalid struct index");
3445  if (IsArray && Index >= CurTy->getArrayNumElements())
3446  return error("INSERTVAL: Invalid array index");
3447 
3448  INSERTVALIdx.push_back((unsigned)Index);
3449  if (IsStruct)
3450  CurTy = CurTy->subtypes()[Index];
3451  else
3452  CurTy = CurTy->subtypes()[0];
3453  }
3454 
3455  if (CurTy != Val->getType())
3456  return error("Inserted value type doesn't match aggregate type");
3457 
3458  I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
3459  InstructionList.push_back(I);
3460  break;
3461  }
3462 
3463  case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
3464  // obsolete form of select
3465  // handles select i1 ... in old bitcode
3466  unsigned OpNum = 0;
3467  Value *TrueVal, *FalseVal, *Cond;
3468  if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3469  popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3470  popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
3471  return error("Invalid record");
3472 
3473  I = SelectInst::Create(Cond, TrueVal, FalseVal);
3474  InstructionList.push_back(I);
3475  break;
3476  }
3477 
3478  case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3479  // new form of select
3480  // handles select i1 or select [N x i1]
3481  unsigned OpNum = 0;
3482  Value *TrueVal, *FalseVal, *Cond;
3483  if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
3484  popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3485  getValueTypePair(Record, OpNum, NextValueNo, Cond))
3486  return error("Invalid record");
3487 
3488  // select condition can be either i1 or [N x i1]
3489  if (VectorType* vector_type =
3490  dyn_cast<VectorType>(Cond->getType())) {
3491  // expect <n x i1>
3492  if (vector_type->getElementType() != Type::getInt1Ty(Context))
3493  return error("Invalid type for value");
3494  } else {
3495  // expect i1
3496  if (Cond->getType() != Type::getInt1Ty(Context))
3497  return error("Invalid type for value");
3498  }
3499 
3500  I = SelectInst::Create(Cond, TrueVal, FalseVal);
3501  InstructionList.push_back(I);
3502  break;
3503  }
3504 
3505  case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
3506  unsigned OpNum = 0;
3507  Value *Vec, *Idx;
3508  if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
3509  getValueTypePair(Record, OpNum, NextValueNo, Idx))
3510  return error("Invalid record");
3511  if (!Vec->getType()->isVectorTy())
3512  return error("Invalid type for value");
3513  I = ExtractElementInst::Create(Vec, Idx);
3514  InstructionList.push_back(I);
3515  break;
3516  }
3517 
3518  case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
3519  unsigned OpNum = 0;
3520  Value *Vec, *Elt, *Idx;
3521  if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
3522  return error("Invalid record");
3523  if (!Vec->getType()->isVectorTy())
3524  return error("Invalid type for value");
3525  if (popValue(Record, OpNum, NextValueNo,
3526  cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
3527  getValueTypePair(Record, OpNum, NextValueNo, Idx))
3528  return error("Invalid record");
3529  I = InsertElementInst::Create(Vec, Elt, Idx);
3530  InstructionList.push_back(I);
3531  break;
3532  }
3533 
3534  case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3535  unsigned OpNum = 0;
3536  Value *Vec1, *Vec2, *Mask;
3537  if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
3538  popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
3539  return error("Invalid record");
3540 
3541  if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
3542  return error("Invalid record");
3543  if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
3544  return error("Invalid type for value");
3545  I = new ShuffleVectorInst(Vec1, Vec2, Mask);
3546  InstructionList.push_back(I);
3547  break;
3548  }
3549 
3550  case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3551  // Old form of ICmp/FCmp returning bool
3552  // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3553  // both legal on vectors but had different behaviour.
3554  case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3555  // FCmp/ICmp returning bool or vector of bool
3556 
3557  unsigned OpNum = 0;
3558  Value *LHS, *RHS;
3559  if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
3560  popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3561  return error("Invalid record");
3562 
3563  unsigned PredVal = Record[OpNum];
3564  bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3565  FastMathFlags FMF;
3566  if (IsFP && Record.size() > OpNum+1)
3567  FMF = getDecodedFastMathFlags(Record[++OpNum]);
3568 
3569  if (OpNum+1 != Record.size())
3570  return error("Invalid record");
3571 
3572  if (LHS->getType()->isFPOrFPVectorTy())
3573  I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
3574  else
3575  I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3576 
3577  if (FMF.any())
3578  I->setFastMathFlags(FMF);
3579  InstructionList.push_back(I);
3580  break;
3581  }
3582 
3583  case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
3584  {
3585  unsigned Size = Record.size();
3586  if (Size == 0) {
3587  I = ReturnInst::Create(Context);
3588  InstructionList.push_back(I);
3589  break;
3590  }
3591 
3592  unsigned OpNum = 0;
3593  Value *Op = nullptr;
3594  if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3595  return error("Invalid record");
3596  if (OpNum != Record.size())
3597  return error("Invalid record");
3598 
3599  I = ReturnInst::Create(Context, Op);
3600  InstructionList.push_back(I);
3601  break;
3602  }
3603  case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
3604  if (Record.size() != 1 && Record.size() != 3)
3605  return error("Invalid record");
3606  BasicBlock *TrueDest = getBasicBlock(Record[0]);
3607  if (!TrueDest)
3608  return error("Invalid record");
3609 
3610  if (Record.size() == 1) {
3611  I = BranchInst::Create(TrueDest);
3612  InstructionList.push_back(I);
3613  }
3614  else {
3615  BasicBlock *FalseDest = getBasicBlock(Record[1]);
3616  Value *Cond = getValue(Record, 2, NextValueNo,
3617  Type::getInt1Ty(Context));
3618  if (!FalseDest || !Cond)
3619  return error("Invalid record");
3620  I = BranchInst::Create(TrueDest, FalseDest, Cond);
3621  InstructionList.push_back(I);
3622  }
3623  break;
3624  }
3625  case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
3626  if (Record.size() != 1 && Record.size() != 2)
3627  return error("Invalid record");
3628  unsigned Idx = 0;
3629  Value *CleanupPad =
3630  getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3631  if (!CleanupPad)
3632  return error("Invalid record");
3633  BasicBlock *UnwindDest = nullptr;
3634  if (Record.size() == 2) {
3635  UnwindDest = getBasicBlock(Record[Idx++]);
3636  if (!UnwindDest)
3637  return error("Invalid record");
3638  }
3639 
3640  I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
3641  InstructionList.push_back(I);
3642  break;
3643  }
3644  case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3645  if (Record.size() != 2)
3646  return error("Invalid record");
3647  unsigned Idx = 0;
3648  Value *CatchPad =
3649  getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3650  if (!CatchPad)
3651  return error("Invalid record");
3652  BasicBlock *BB = getBasicBlock(Record[Idx++]);
3653  if (!BB)
3654  return error("Invalid record");
3655 
3656  I = CatchReturnInst::Create(CatchPad, BB);
3657  InstructionList.push_back(I);
3658  break;
3659  }
3660  case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
3661  // We must have, at minimum, the outer scope and the number of arguments.
3662  if (Record.size() < 2)
3663  return error("Invalid record");
3664 
3665  unsigned Idx = 0;
3666 
3667  Value *ParentPad =
3668  getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3669 
3670  unsigned NumHandlers = Record[Idx++];
3671 
3673  for (unsigned Op = 0; Op != NumHandlers; ++Op) {
3674  BasicBlock *BB = getBasicBlock(Record[Idx++]);
3675  if (!BB)
3676  return error("Invalid record");
3677  Handlers.push_back(BB);
3678  }
3679 
3680  BasicBlock *UnwindDest = nullptr;
3681  if (Idx + 1 == Record.size()) {
3682  UnwindDest = getBasicBlock(Record[Idx++]);
3683  if (!UnwindDest)
3684  return error("Invalid record");
3685  }
3686 
3687  if (Record.size() != Idx)
3688  return error("Invalid record");
3689 
3690  auto *CatchSwitch =
3691  CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
3692  for (BasicBlock *Handler : Handlers)
3693  CatchSwitch->addHandler(Handler);
3694  I = CatchSwitch;
3695  InstructionList.push_back(I);
3696  break;
3697  }
3699  case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
3700  // We must have, at minimum, the outer scope and the number of arguments.
3701  if (Record.size() < 2)
3702  return error("Invalid record");
3703 
3704  unsigned Idx = 0;
3705 
3706  Value *ParentPad =
3707  getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
3708 
3709  unsigned NumArgOperands = Record[Idx++];
3710 
3712  for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3713  Value *Val;
3714  if (getValueTypePair(Record, Idx, NextValueNo, Val))
3715  return error("Invalid record");
3716  Args.push_back(Val);
3717  }
3718 
3719  if (Record.size() != Idx)
3720  return error("Invalid record");
3721 
3722  if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
3723  I = CleanupPadInst::Create(ParentPad, Args);
3724  else
3725  I = CatchPadInst::Create(ParentPad, Args);
3726  InstructionList.push_back(I);
3727  break;
3728  }
3729  case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
3730  // Check magic
3731  if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
3732  // "New" SwitchInst format with case ranges. The changes to write this
3733  // format were reverted but we still recognize bitcode that uses it.
3734  // Hopefully someday we will have support for case ranges and can use
3735  // this format again.
3736 
3737  Type *OpTy = getTypeByID(Record[1]);
3738  unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
3739 
3740  Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
3741  BasicBlock *Default = getBasicBlock(Record[3]);
3742  if (!OpTy || !Cond || !Default)
3743  return error("Invalid record");
3744 
3745  unsigned NumCases = Record[4];
3746 
3747  SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3748  InstructionList.push_back(SI);
3749 
3750  unsigned CurIdx = 5;
3751  for (unsigned i = 0; i != NumCases; ++i) {
3753  unsigned NumItems = Record[CurIdx++];
3754  for (unsigned ci = 0; ci != NumItems; ++ci) {
3755  bool isSingleNumber = Record[CurIdx++];
3756 
3757  APInt Low;
3758  unsigned ActiveWords = 1;
3759  if (ValueBitWidth > 64)
3760  ActiveWords = Record[CurIdx++];
3761  Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
3762  ValueBitWidth);
3763  CurIdx += ActiveWords;
3764 
3765  if (!isSingleNumber) {
3766  ActiveWords = 1;
3767  if (ValueBitWidth > 64)
3768  ActiveWords = Record[CurIdx++];
3770  makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
3771  CurIdx += ActiveWords;
3772 
3773  // FIXME: It is not clear whether values in the range should be
3774  // compared as signed or unsigned values. The partially
3775  // implemented changes that used this format in the past used
3776  // unsigned comparisons.
3777  for ( ; Low.ule(High); ++Low)
3778  CaseVals.push_back(ConstantInt::get(Context, Low));
3779  } else
3780  CaseVals.push_back(ConstantInt::get(Context, Low));
3781  }
3782  BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
3783  for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
3784  cve = CaseVals.end(); cvi != cve; ++cvi)
3785  SI->addCase(*cvi, DestBB);
3786  }
3787  I = SI;
3788  break;
3789  }
3790 
3791  // Old SwitchInst format without case ranges.
3792 
3793  if (Record.size() < 3 || (Record.size() & 1) == 0)
3794  return error("Invalid record");
3795  Type *OpTy = getTypeByID(Record[0]);
3796  Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
3797  BasicBlock *Default = getBasicBlock(Record[2]);
3798  if (!OpTy || !Cond || !Default)
3799  return error("Invalid record");
3800  unsigned NumCases = (Record.size()-3)/2;
3801  SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
3802  InstructionList.push_back(SI);
3803  for (unsigned i = 0, e = NumCases; i != e; ++i) {
3804  ConstantInt *CaseVal =
3805  dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
3806  BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
3807  if (!CaseVal || !DestBB) {
3808  delete SI;
3809  return error("Invalid record");
3810  }
3811  SI->addCase(CaseVal, DestBB);
3812  }
3813  I = SI;
3814  break;
3815  }
3816  case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
3817  if (Record.size() < 2)
3818  return error("Invalid record");
3819  Type *OpTy = getTypeByID(Record[0]);
3820  Value *Address = getValue(Record, 1, NextValueNo, OpTy);
3821  if (!OpTy || !Address)
3822  return error("Invalid record");
3823  unsigned NumDests = Record.size()-2;
3824  IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
3825  InstructionList.push_back(IBI);
3826  for (unsigned i = 0, e = NumDests; i != e; ++i) {
3827  if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
3828  IBI->addDestination(DestBB);
3829  } else {
3830  delete IBI;
3831  return error("Invalid record");
3832  }
3833  }
3834  I = IBI;
3835  break;
3836  }
3837 
3839  // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
3840  if (Record.size() < 4)
3841  return error("Invalid record");
3842  unsigned OpNum = 0;
3843  AttributeSet PAL = getAttributes(Record[OpNum++]);
3844  unsigned CCInfo = Record[OpNum++];
3845  BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
3846  BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
3847 
3848  FunctionType *FTy = nullptr;
3849  if (CCInfo >> 13 & 1 &&
3850  !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
3851  return error("Explicit invoke type is not a function type");
3852 
3853  Value *Callee;
3854  if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3855  return error("Invalid record");
3856 
3857  PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3858  if (!CalleeTy)
3859  return error("Callee is not a pointer");
3860  if (!FTy) {
3861  FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
3862  if (!FTy)
3863  return error("Callee is not of pointer to function type");
3864  } else if (CalleeTy->getElementType() != FTy)
3865  return error("Explicit invoke type does not match pointee type of "
3866  "callee operand");
3867  if (Record.size() < FTy->getNumParams() + OpNum)
3868  return error("Insufficient operands to call");
3869 
3871  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3872  Ops.push_back(getValue(Record, OpNum, NextValueNo,
3873  FTy->getParamType(i)));
3874  if (!Ops.back())
3875  return error("Invalid record");
3876  }
3877 
3878  if (!FTy->isVarArg()) {
3879  if (Record.size() != OpNum)
3880  return error("Invalid record");
3881  } else {
3882  // Read type/value pairs for varargs params.
3883  while (OpNum != Record.size()) {
3884  Value *Op;
3885  if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3886  return error("Invalid record");
3887  Ops.push_back(Op);
3888  }
3889  }
3890 
3891  I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
3892  OperandBundles.clear();
3893  InstructionList.push_back(I);
3894  cast<InvokeInst>(I)->setCallingConv(
3895  static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
3896  cast<InvokeInst>(I)->setAttributes(PAL);
3897  break;
3898  }
3899  case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
3900  unsigned Idx = 0;
3901  Value *Val = nullptr;
3902  if (getValueTypePair(Record, Idx, NextValueNo, Val))
3903  return error("Invalid record");
3904  I = ResumeInst::Create(Val);
3905  InstructionList.push_back(I);
3906  break;
3907  }
3908  case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3909  I = new UnreachableInst(Context);
3910  InstructionList.push_back(I);
3911  break;
3912  case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3913  if (Record.size() < 1 || ((Record.size()-1)&1))
3914  return error("Invalid record");
3915  Type *Ty = getTypeByID(Record[0]);
3916  if (!Ty)
3917  return error("Invalid record");
3918 
3919  PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3920  InstructionList.push_back(PN);
3921 
3922  for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3923  Value *V;
3924  // With the new function encoding, it is possible that operands have
3925  // negative IDs (for forward references). Use a signed VBR
3926  // representation to keep the encoding small.
3927  if (UseRelativeIDs)
3928  V = getValueSigned(Record, 1+i, NextValueNo, Ty);
3929  else
3930  V = getValue(Record, 1+i, NextValueNo, Ty);
3931  BasicBlock *BB = getBasicBlock(Record[2+i]);
3932  if (!V || !BB)
3933  return error("Invalid record");
3934  PN->addIncoming(V, BB);
3935  }
3936  I = PN;
3937  break;
3938  }
3939 
3942  // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
3943  unsigned Idx = 0;
3944  if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
3945  if (Record.size() < 3)
3946  return error("Invalid record");
3947  } else {
3949  if (Record.size() < 4)
3950  return error("Invalid record");
3951  }
3952  Type *Ty = getTypeByID(Record[Idx++]);
3953  if (!Ty)
3954  return error("Invalid record");
3955  if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
3956  Value *PersFn = nullptr;
3957  if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3958  return error("Invalid record");
3959 
3960  if (!F->hasPersonalityFn())
3961  F->setPersonalityFn(cast<Constant>(PersFn));
3962  else if (F->getPersonalityFn() != cast<Constant>(PersFn))
3963  return error("Personality function mismatch");
3964  }
3965 
3966  bool IsCleanup = !!Record[Idx++];
3967  unsigned NumClauses = Record[Idx++];
3968  LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
3969  LP->setCleanup(IsCleanup);
3970  for (unsigned J = 0; J != NumClauses; ++J) {
3972  LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
3973  Value *Val;
3974 
3975  if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
3976  delete LP;
3977  return error("Invalid record");
3978  }
3979 
3980  assert((CT != LandingPadInst::Catch ||
3981  !isa<ArrayType>(Val->getType())) &&
3982  "Catch clause has a invalid type!");
3983  assert((CT != LandingPadInst::Filter ||
3984  isa<ArrayType>(Val->getType())) &&
3985  "Filter clause has invalid type!");
3986  LP->addClause(cast<Constant>(Val));
3987  }
3988 
3989  I = LP;
3990  InstructionList.push_back(I);
3991  break;
3992  }
3993 
3994  case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3995  if (Record.size() != 4)
3996  return error("Invalid record");
3997  uint64_t AlignRecord = Record[3];
3998  const uint64_t InAllocaMask = uint64_t(1) << 5;
3999  const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
4000  const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4001  const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4002  SwiftErrorMask;
4003  bool InAlloca = AlignRecord & InAllocaMask;
4004  bool SwiftError = AlignRecord & SwiftErrorMask;
4005  Type *Ty = getTypeByID(Record[0]);
4006  if ((AlignRecord & ExplicitTypeMask) == 0) {
4007  auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4008  if (!PTy)
4009  return error("Old-style alloca with a non-pointer type");
4010  Ty = PTy->getElementType();
4011  }
4012  Type *OpTy = getTypeByID(Record[1]);
4013  Value *Size = getFnValueByID(Record[2], OpTy);
4014  unsigned Align;
4015  if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
4016  return Err;
4017  }
4018  if (!Ty || !Size)
4019  return error("Invalid record");
4020  AllocaInst *AI = new AllocaInst(Ty, Size, Align);
4021  AI->setUsedWithInAlloca(InAlloca);
4022  AI->setSwiftError(SwiftError);
4023  I = AI;
4024  InstructionList.push_back(I);
4025  break;
4026  }
4027  case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
4028  unsigned OpNum = 0;
4029  Value *Op;
4030  if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4031  (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
4032  return error("Invalid record");
4033 
4034  Type *Ty = nullptr;
4035  if (OpNum + 3 == Record.size())
4036  Ty = getTypeByID(Record[OpNum++]);
4037  if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4038  return Err;
4039  if (!Ty)
4040  Ty = cast<PointerType>(Op->getType())->getElementType();
4041 
4042  unsigned Align;
4043  if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4044  return Err;
4045  I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
4046 
4047  InstructionList.push_back(I);
4048  break;
4049  }
4051  // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4052  unsigned OpNum = 0;
4053  Value *Op;
4054  if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4055  (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
4056  return error("Invalid record");
4057 
4058  Type *Ty = nullptr;
4059  if (OpNum + 5 == Record.size())
4060  Ty = getTypeByID(Record[OpNum++]);
4061  if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
4062  return Err;
4063  if (!Ty)
4064  Ty = cast<PointerType>(Op->getType())->getElementType();
4065 
4066  AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4067  if (Ordering == AtomicOrdering::NotAtomic ||
4068  Ordering == AtomicOrdering::Release ||
4069  Ordering == AtomicOrdering::AcquireRelease)
4070  return error("Invalid record");
4071  if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4072  return error("Invalid record");
4073  SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4074 
4075  unsigned Align;
4076  if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4077  return Err;
4078  I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
4079 
4080  InstructionList.push_back(I);
4081  break;
4082  }
4084  case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
4085  unsigned OpNum = 0;
4086  Value *Val, *Ptr;
4087  if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4088  (BitCode == bitc::FUNC_CODE_INST_STORE
4089  ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4090  : popValue(Record, OpNum, NextValueNo,
4091  cast<PointerType>(Ptr->getType())->getElementType(),
4092  Val)) ||
4093  OpNum + 2 != Record.size())
4094  return error("Invalid record");
4095 
4096  if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4097  return Err;
4098  unsigned Align;
4099  if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4100  return Err;
4101  I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
4102  InstructionList.push_back(I);
4103  break;
4104  }
4107  // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4108  unsigned OpNum = 0;
4109  Value *Val, *Ptr;
4110  if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4111  !isa<PointerType>(Ptr->getType()) ||
4113  ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4114  : popValue(Record, OpNum, NextValueNo,
4115  cast<PointerType>(Ptr->getType())->getElementType(),
4116  Val)) ||
4117  OpNum + 4 != Record.size())
4118  return error("Invalid record");
4119 
4120  if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
4121  return Err;
4122  AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4123  if (Ordering == AtomicOrdering::NotAtomic ||
4124  Ordering == AtomicOrdering::Acquire ||
4125  Ordering == AtomicOrdering::AcquireRelease)
4126  return error("Invalid record");
4127  SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4128  if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
4129  return error("Invalid record");
4130 
4131  unsigned Align;
4132  if (Error Err = parseAlignmentValue(Record[OpNum], Align))
4133  return Err;
4134  I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
4135  InstructionList.push_back(I);
4136  break;
4137  }
4140  // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
4141  // failureordering?, isweak?]
4142  unsigned OpNum = 0;
4143  Value *Ptr, *Cmp, *New;
4144  if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4145  (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4146  ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4147  : popValue(Record, OpNum, NextValueNo,
4148  cast<PointerType>(Ptr->getType())->getElementType(),
4149  Cmp)) ||
4150  popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4151  Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
4152  return error("Invalid record");
4153  AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
4154  if (SuccessOrdering == AtomicOrdering::NotAtomic ||
4155  SuccessOrdering == AtomicOrdering::Unordered)
4156  return error("Invalid record");
4157  SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
4158 
4159  if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
4160  return Err;
4161  AtomicOrdering FailureOrdering;
4162  if (Record.size() < 7)
4163  FailureOrdering =
4164  AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4165  else
4166  FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
4167 
4168  I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4169  SynchScope);
4170  cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
4171 
4172  if (Record.size() < 8) {
4173  // Before weak cmpxchgs existed, the instruction simply returned the
4174  // value loaded from memory, so bitcode files from that era will be
4175  // expecting the first component of a modern cmpxchg.
4176  CurBB->getInstList().push_back(I);
4177  I = ExtractValueInst::Create(I, 0);
4178  } else {
4179  cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4180  }
4181 
4182  InstructionList.push_back(I);
4183  break;
4184  }
4186  // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4187  unsigned OpNum = 0;
4188  Value *Ptr, *Val;
4189  if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
4190  !isa<PointerType>(Ptr->getType()) ||
4191  popValue(Record, OpNum, NextValueNo,
4192  cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4193  OpNum+4 != Record.size())
4194  return error("Invalid record");
4195  AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
4196  if (Operation < AtomicRMWInst::FIRST_BINOP ||
4197  Operation > AtomicRMWInst::LAST_BINOP)
4198  return error("Invalid record");
4199  AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
4200  if (Ordering == AtomicOrdering::NotAtomic ||
4201  Ordering == AtomicOrdering::Unordered)
4202  return error("Invalid record");
4203  SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
4204  I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4205  cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4206  InstructionList.push_back(I);
4207  break;
4208  }
4209  case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4210  if (2 != Record.size())
4211  return error("Invalid record");
4212  AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
4213  if (Ordering == AtomicOrdering::NotAtomic ||
4214  Ordering == AtomicOrdering::Unordered ||
4215  Ordering == AtomicOrdering::Monotonic)
4216  return error("Invalid record");
4217  SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
4218  I = new FenceInst(Context, Ordering, SynchScope);
4219  InstructionList.push_back(I);
4220  break;
4221  }
4223  // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
4224  if (Record.size() < 3)
4225  return error("Invalid record");
4226 
4227  unsigned OpNum = 0;
4228  AttributeSet PAL = getAttributes(Record[OpNum++]);
4229  unsigned CCInfo = Record[OpNum++];
4230 
4231  FastMathFlags FMF;
4232  if ((CCInfo >> bitc::CALL_FMF) & 1) {
4233  FMF = getDecodedFastMathFlags(Record[OpNum++]);
4234  if (!FMF.any())
4235  return error("Fast math flags indicator set for call with no FMF");
4236  }
4237 
4238  FunctionType *FTy = nullptr;
4239  if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
4240  !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
4241  return error("Explicit call type is not a function type");
4242 
4243  Value *Callee;
4244  if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
4245  return error("Invalid record");
4246 
4247  PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
4248  if (!OpTy)
4249  return error("Callee is not a pointer type");
4250  if (!FTy) {
4251  FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4252  if (!FTy)
4253  return error("Callee is not of pointer to function type");
4254  } else if (OpTy->getElementType() != FTy)
4255  return error("Explicit call type does not match pointee type of "
4256  "callee operand");
4257  if (Record.size() < FTy->getNumParams() + OpNum)
4258  return error("Insufficient operands to call");
4259 
4261  // Read the fixed params.
4262  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
4263  if (FTy->getParamType(i)->isLabelTy())
4264  Args.push_back(getBasicBlock(Record[OpNum]));
4265  else
4266  Args.push_back(getValue(Record, OpNum, NextValueNo,
4267  FTy->getParamType(i)));
4268  if (!Args.back())
4269  return error("Invalid record");
4270  }
4271 
4272  // Read type/value pairs for varargs params.
4273  if (!FTy->isVarArg()) {
4274  if (OpNum != Record.size())
4275  return error("Invalid record");
4276  } else {
4277  while (OpNum != Record.size()) {
4278  Value *Op;
4279  if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4280  return error("Invalid record");
4281  Args.push_back(Op);
4282  }
4283  }
4284 
4285  I = CallInst::Create(FTy, Callee, Args, OperandBundles);
4286  OperandBundles.clear();
4287  InstructionList.push_back(I);
4288  cast<CallInst>(I)->setCallingConv(
4289  static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
4290  CallInst::TailCallKind TCK = CallInst::TCK_None;
4291  if (CCInfo & 1 << bitc::CALL_TAIL)
4292  TCK = CallInst::TCK_Tail;
4293  if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
4294  TCK = CallInst::TCK_MustTail;
4295  if (CCInfo & (1 << bitc::CALL_NOTAIL))
4296  TCK = CallInst::TCK_NoTail;
4297  cast<CallInst>(I)->setTailCallKind(TCK);
4298  cast<CallInst>(I)->setAttributes(PAL);
4299  if (FMF.any()) {
4300  if (!isa<FPMathOperator>(I))
4301  return error("Fast-math-flags specified for call without "
4302  "floating-point scalar or vector return type");
4303  I->setFastMathFlags(FMF);
4304  }
4305  break;
4306  }
4307  case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4308  if (Record.size() < 3)
4309  return error("Invalid record");
4310  Type *OpTy = getTypeByID(Record[0]);
4311  Value *Op = getValue(Record, 1, NextValueNo, OpTy);
4312  Type *ResTy = getTypeByID(Record[2]);
4313  if (!OpTy || !Op || !ResTy)
4314  return error("Invalid record");
4315  I = new VAArgInst(Op, ResTy);
4316  InstructionList.push_back(I);
4317  break;
4318  }
4319 
4321  // A call or an invoke can be optionally prefixed with some variable
4322  // number of operand bundle blocks. These blocks are read into
4323  // OperandBundles and consumed at the next call or invoke instruction.
4324 
4325  if (Record.size() < 1 || Record[0] >= BundleTags.size())
4326  return error("Invalid record");
4327 
4328  std::vector<Value *> Inputs;
4329 
4330  unsigned OpNum = 1;
4331  while (OpNum != Record.size()) {
4332  Value *Op;
4333  if (getValueTypePair(Record, OpNum, NextValueNo, Op))
4334  return error("Invalid record");
4335  Inputs.push_back(Op);
4336  }
4337 
4338  OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
4339  continue;
4340  }
4341  }
4342 
4343  // Add instruction to end of current BB. If there is no current BB, reject
4344  // this file.
4345  if (!CurBB) {
4346  delete I;
4347  return error("Invalid instruction with no BB");
4348  }
4349  if (!OperandBundles.empty()) {
4350  delete I;
4351  return error("Operand bundles found with no consumer");
4352  }
4353  CurBB->getInstList().push_back(I);
4354 
4355  // If this was a terminator instruction, move to the next block.
4356  if (isa<TerminatorInst>(I)) {
4357  ++CurBBNo;
4358  CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
4359  }
4360 
4361  // Non-void values get registered in the value table for future use.
4362  if (I && !I->getType()->isVoidTy())
4363  ValueList.assignValue(I, NextValueNo++);
4364  }
4365 
4366 OutOfRecordLoop:
4367 
4368  if (!OperandBundles.empty())
4369  return error("Operand bundles found with no consumer");
4370 
4371  // Check the function list for unresolved values.
4372  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
4373  if (!A->getParent()) {
4374  // We found at least one unresolved value. Nuke them all to avoid leaks.
4375  for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
4376  if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
4377  A->replaceAllUsesWith(UndefValue::get(A->getType()));
4378  delete A;
4379  }
4380  }
4381  return error("Never resolved value found in function");
4382  }
4383  }
4384 
4385  // Unexpected unresolved metadata about to be dropped.
4386  if (MDLoader->hasFwdRefs())
4387  return error("Invalid function metadata: outgoing forward refs");
4388 
4389  // Trim the value list down to the size it was before we parsed this function.
4390  ValueList.shrinkTo(ModuleValueListSize);
4391  MDLoader->shrinkTo(ModuleMDLoaderSize);
4392  std::vector<BasicBlock*>().swap(FunctionBBs);
4393  return Error::success();
4394 }
4395 
4396 /// Find the function body in the bitcode stream
4397 Error BitcodeReader::findFunctionInStream(
4398  Function *F,
4399  DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
4400  while (DeferredFunctionInfoIterator->second == 0) {
4401  // This is the fallback handling for the old format bitcode that
4402  // didn't contain the function index in the VST, or when we have
4403  // an anonymous function which would not have a VST entry.
4404  // Assert that we have one of those two cases.
4405  assert(VSTOffset == 0 || !F->hasName());
4406  // Parse the next body in the stream and set its position in the
4407  // DeferredFunctionInfo map.
4408  if (Error Err = rememberAndSkipFunctionBodies())
4409  return Err;
4410  }
4411  return Error::success();
4412 }
4413 
4414 //===----------------------------------------------------------------------===//
4415 // GVMaterializer implementation
4416 //===----------------------------------------------------------------------===//
4417 
4418 Error BitcodeReader::materialize(GlobalValue *GV) {
4419  Function *F = dyn_cast<Function>(GV);
4420  // If it's not a function or is already material, ignore the request.
4421  if (!F || !F->isMaterializable())
4422  return Error::success();
4423 
4424  DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
4425  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
4426  // If its position is recorded as 0, its body is somewhere in the stream
4427  // but we haven't seen it yet.
4428  if (DFII->second == 0)
4429  if (Error Err = findFunctionInStream(F, DFII))
4430  return Err;
4431 
4432  // Materialize metadata before parsing any function bodies.
4433  if (Error Err = materializeMetadata())
4434  return Err;
4435 
4436  // Move the bit stream to the saved position of the deferred function body.
4437  Stream.JumpToBit(DFII->second);
4438 
4439  if (Error Err = parseFunctionBody(F))
4440  return Err;
4441  F->setIsMaterializable(false);
4442 
4443  if (StripDebugInfo)
4444  stripDebugInfo(*F);
4445 
4446  // Upgrade any old intrinsic calls in the function.
4447  for (auto &I : UpgradedIntrinsics) {
4448  for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4449  UI != UE;) {
4450  User *U = *UI;
4451  ++UI;
4452  if (CallInst *CI = dyn_cast<CallInst>(U))
4453  UpgradeIntrinsicCall(CI, I.second);
4454  }
4455  }
4456 
4457  // Update calls to the remangled intrinsics
4458  for (auto &I : RemangledIntrinsics)
4459  for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
4460  UI != UE;)
4461  // Don't expect any other users than call sites
4462  CallSite(*UI++).setCalledFunction(I.second);
4463 
4464  // Finish fn->subprogram upgrade for materialized functions.
4465  if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
4466  F->setSubprogram(SP);
4467 
4468  // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
4469  if (!MDLoader->isStrippingTBAA()) {
4470  for (auto &I : instructions(F)) {
4471  MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
4472  if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
4473  continue;
4474  MDLoader->setStripTBAA(true);
4475  stripTBAA(F->getParent());
4476  }
4477  }
4478 
4479  // Bring in any functions that this function forward-referenced via
4480  // blockaddresses.
4481  return materializeForwardReferencedFunctions();
4482 }
4483 
4484 Error BitcodeReader::materializeModule() {
4485  if (Error Err = materializeMetadata())
4486  return Err;
4487 
4488  // Promise to materialize all forward references.
4489  WillMaterializeAllForwardRefs = true;
4490 
4491  // Iterate over the module, deserializing any functions that are still on
4492  // disk.
4493  for (Function &F : *TheModule) {
4494  if (Error Err = materialize(&F))
4495  return Err;
4496  }
4497  // At this point, if there are any function bodies, parse the rest of
4498  // the bits in the module past the last function block we have recorded
4499  // through either lazy scanning or the VST.
4500  if (LastFunctionBlockBit || NextUnreadBit)
4501  if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
4502  ? LastFunctionBlockBit
4503  : NextUnreadBit))
4504  return Err;
4505 
4506  // Check that all block address forward references got resolved (as we
4507  // promised above).
4508  if (!BasicBlockFwdRefs.empty())
4509  return error("Never resolved function from blockaddress");
4510 
4511  // Upgrade any intrinsic calls that slipped through (should not happen!) and
4512  // delete the old functions to clean up. We can't do this unless the entire
4513  // module is materialized because there could always be another function body
4514  // with calls to the old function.
4515  for (auto &I : UpgradedIntrinsics) {
4516  for (auto *U : I.first->users()) {
4517  if (CallInst *CI = dyn_cast<CallInst>(U))
4518  UpgradeIntrinsicCall(CI, I.second);
4519  }
4520  if (!I.first->use_empty())
4521  I.first->replaceAllUsesWith(I.second);
4522  I.first->eraseFromParent();
4523  }
4524  UpgradedIntrinsics.clear();
4525  // Do the same for remangled intrinsics
4526  for (auto &I : RemangledIntrinsics) {
4527  I.first->replaceAllUsesWith(I.second);
4528  I.first->eraseFromParent();
4529  }
4530  RemangledIntrinsics.clear();
4531 
4532  UpgradeDebugInfo(*TheModule);
4533 
4534  UpgradeModuleFlags(*TheModule);
4535  return Error::success();
4536 }
4537 
4538 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4539  return IdentifiedStructTypes;
4540 }
4541 
4542 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
4543  BitstreamCursor Cursor, ModuleSummaryIndex &TheIndex)
4544  : BitcodeReaderBase(std::move(Cursor)), TheIndex(TheIndex) {}
4545 
4546 std::pair<GlobalValue::GUID, GlobalValue::GUID>
4547 ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
4548  auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
4549  assert(VGI != ValueIdToCallGraphGUIDMap.end());
4550  return VGI->second;
4551 }
4552 
4553 // Specialized value symbol table parser used when reading module index
4554 // blocks where we don't actually create global values. The parsed information
4555 // is saved in the bitcode reader for use when later parsing summaries.
4556 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
4557  uint64_t Offset,
4558  DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
4559  assert(Offset > 0 && "Expected non-zero VST offset");
4560  uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
4561 
4563  return error("Invalid record");
4564 
4566 
4567  // Read all the records for this value table.
4569 
4570  while (true) {
4571  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4572 
4573  switch (Entry.Kind) {
4574  case BitstreamEntry::SubBlock: // Handled for us already.
4575  case BitstreamEntry::Error:
4576  return error("Malformed block");
4577  case BitstreamEntry::EndBlock:
4578  // Done parsing VST, jump back to wherever we came from.
4579  Stream.JumpToBit(CurrentBit);
4580  return Error::success();
4581  case BitstreamEntry::Record:
4582  // The interesting case.
4583  break;
4584  }
4585 
4586  // Read a record.
4587  Record.clear();
4588  switch (Stream.readRecord(Entry.ID, Record)) {
4589  default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
4590  break;
4591  case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
4592  if (convertToString(Record, 1, ValueName))
4593  return error("Invalid record");
4594  unsigned ValueID = Record[0];
4595  assert(!SourceFileName.empty());
4596  auto VLI = ValueIdToLinkageMap.find(ValueID);
4597  assert(VLI != ValueIdToLinkageMap.end() &&
4598  "No linkage found for VST entry?");
4599  auto Linkage = VLI->second;
4600  std::string GlobalId =
4601  GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
4602  auto ValueGUID = GlobalValue::getGUID(GlobalId);
4603  auto OriginalNameID = ValueGUID;
4604  if (GlobalValue::isLocalLinkage(Linkage))
4605  OriginalNameID = GlobalValue::getGUID(ValueName);
4606  if (PrintSummaryGUIDs)
4607  dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
4608  << ValueName << "\n";
4609  ValueIdToCallGraphGUIDMap[ValueID] =
4610  std::make_pair(ValueGUID, OriginalNameID);
4611  ValueName.clear();
4612  break;
4613  }
4614  case bitc::VST_CODE_FNENTRY: {
4615  // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
4616  if (convertToString(Record, 2, ValueName))
4617  return error("Invalid record");
4618  unsigned ValueID = Record[0];
4619  assert(!SourceFileName.empty());
4620  auto VLI = ValueIdToLinkageMap.find(ValueID);
4621  assert(VLI != ValueIdToLinkageMap.end() &&
4622  "No linkage found for VST entry?");
4623  auto Linkage = VLI->second;
4624  std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
4625  ValueName, VLI->second, SourceFileName);
4626  auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
4627  auto OriginalNameID = FunctionGUID;
4628  if (GlobalValue::isLocalLinkage(Linkage))
4629  OriginalNameID = GlobalValue::getGUID(ValueName);
4630  if (PrintSummaryGUIDs)
4631  dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
4632  << ValueName << "\n";
4633  ValueIdToCallGraphGUIDMap[ValueID] =
4634  std::make_pair(FunctionGUID, OriginalNameID);
4635 
4636  ValueName.clear();
4637  break;
4638  }
4640  // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
4641  unsigned ValueID = Record[0];
4642  GlobalValue::GUID RefGUID = Record[1];
4643  // The "original name", which is the second value of the pair will be
4644  // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
4645  ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
4646  break;
4647  }
4648  }
4649  }
4650 }
4651 
4652 // Parse just the blocks needed for building the index out of the module.
4653 // At the end of this routine the module Index is populated with a map
4654 // from global value id to GlobalValueSummary objects.
4655 Error ModuleSummaryIndexBitcodeReader::parseModule(StringRef ModulePath) {
4657  return error("Invalid record");
4658 
4661  unsigned ValueId = 0;
4662 
4663  // Read the index for this module.
4664  while (true) {
4665  BitstreamEntry Entry = Stream.advance();
4666 
4667  switch (Entry.Kind) {
4668  case BitstreamEntry::Error:
4669  return error("Malformed block");
4670  case BitstreamEntry::EndBlock:
4671  return Error::success();
4672 
4673  case BitstreamEntry::SubBlock:
4674  switch (Entry.ID) {
4675  default: // Skip unknown content.
4676  if (Stream.SkipBlock())
4677  return error("Invalid record");
4678  break;
4680  // Need to parse these to get abbrev ids (e.g. for VST)
4681  if (readBlockInfo())
4682  return error("Malformed block");
4683  break;
4685  // Should have been parsed earlier via VSTOffset, unless there
4686  // is no summary section.
4687  assert(((SeenValueSymbolTable && VSTOffset > 0) ||
4688  !SeenGlobalValSummary) &&
4689  "Expected early VST parse via VSTOffset record");
4690  if (Stream.SkipBlock())
4691  return error("Invalid record");
4692  break;
4694  assert(!SeenValueSymbolTable &&
4695  "Already read VST when parsing summary block?");
4696  // We might not have a VST if there were no values in the
4697  // summary. An empty summary block generated when we are
4698  // performing ThinLTO compiles so we don't later invoke
4699  // the regular LTO process on them.
4700  if (VSTOffset > 0) {
4701  if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
4702  return Err;
4703  SeenValueSymbolTable = true;
4704  }
4705  SeenGlobalValSummary = true;
4706  if (Error Err = parseEntireSummary(ModulePath))
4707  return Err;
4708  break;
4710  if (Error Err = parseModuleStringTable())
4711  return Err;
4712  break;
4713  }
4714  continue;
4715 
4716  case BitstreamEntry::Record: {
4717  Record.clear();
4718  auto BitCode = Stream.readRecord(Entry.ID, Record);
4719  switch (BitCode) {
4720  default:
4721  break; // Default behavior, ignore unknown content.
4722  /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4725  if (convertToString(Record, 0, ValueName))
4726  return error("Invalid record");
4727  SourceFileName = ValueName.c_str();
4728  break;
4729  }
4730  /// MODULE_CODE_HASH: [5*i32]
4731  case bitc::MODULE_CODE_HASH: {
4732  if (Record.size() != 5)
4733  return error("Invalid hash length " + Twine(Record.size()).str());
4734  if (TheIndex.modulePaths().empty())
4735  // We always seed the index with the module.
4736  TheIndex.addModulePath(ModulePath, 0);
4737  if (TheIndex.modulePaths().size() != 1)
4738  return error("Don't expect multiple modules defined?");
4739  auto &Hash = TheIndex.modulePaths().begin()->second.second;
4740  int Pos = 0;
4741  for (auto &Val : Record) {
4742  assert(!(Val >> 32) && "Unexpected high bits set");
4743  Hash[Pos++] = Val;
4744  }
4745  break;
4746  }
4747  /// MODULE_CODE_VSTOFFSET: [offset]
4749  if (Record.size() < 1)
4750  return error("Invalid record");
4751  // Note that we subtract 1 here because the offset is relative to one
4752  // word before the start of the identification or module block, which
4753  // was historically always the start of the regular bitcode header.
4754  VSTOffset = Record[0] - 1;
4755  break;
4756  // GLOBALVAR: [pointer type, isconst, initid,
4757  // linkage, alignment, section, visibility, threadlocal,
4758  // unnamed_addr, externally_initialized, dllstorageclass,
4759  // comdat]
4761  if (Record.size() < 6)
4762  return error("Invalid record");
4763  uint64_t RawLinkage = Record[3];
4764  GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
4765  ValueIdToLinkageMap[ValueId++] = Linkage;
4766  break;
4767  }
4768  // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
4769  // alignment, section, visibility, gc, unnamed_addr,
4770  // prologuedata, dllstorageclass, comdat, prefixdata]
4772  if (Record.size() < 8)
4773  return error("Invalid record");
4774  uint64_t RawLinkage = Record[3];
4775  GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
4776  ValueIdToLinkageMap[ValueId++] = Linkage;
4777  break;
4778  }
4779  // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
4780  // dllstorageclass]
4781  case bitc::MODULE_CODE_ALIAS: {
4782  if (Record.size() < 6)
4783  return error("Invalid record");
4784  uint64_t RawLinkage = Record[3];
4785  GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
4786  ValueIdToLinkageMap[ValueId++] = Linkage;
4787  break;
4788  }
4789  }
4790  }
4791  continue;
4792  }
4793  }
4794 }
4795 
4796 std::vector<ValueInfo>
4797 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
4798  std::vector<ValueInfo> Ret;
4799  Ret.reserve(Record.size());
4800  for (uint64_t RefValueId : Record)
4801  Ret.push_back(getGUIDFromValueId(RefValueId).first);
4802  return Ret;
4803 }
4804 
4805 std::vector<FunctionSummary::EdgeTy> ModuleSummaryIndexBitcodeReader::makeCallList(
4806  ArrayRef<uint64_t> Record, bool IsOldProfileFormat, bool HasProfile) {
4807  std::vector<FunctionSummary::EdgeTy> Ret;
4808  Ret.reserve(Record.size());
4809  for (unsigned I = 0, E = Record.size(); I != E; ++I) {
4811  GlobalValue::GUID CalleeGUID = getGUIDFromValueId(Record[I]).first;
4812  if (IsOldProfileFormat) {
4813  I += 1; // Skip old callsitecount field
4814  if (HasProfile)
4815  I += 1; // Skip old profilecount field
4816  } else if (HasProfile)
4817  Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
4818  Ret.push_back(FunctionSummary::EdgeTy{CalleeGUID, CalleeInfo{Hotness}});
4819  }
4820  return Ret;
4821 }
4822 
4823 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
4824 // objects in the index.
4825 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(
4826  StringRef ModulePath) {
4828  return error("Invalid record");
4830 
4831  // Parse version
4832  {
4833  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4834  if (Entry.Kind != BitstreamEntry::Record)
4835  return error("Invalid Summary Block: record for version expected");
4836  if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
4837  return error("Invalid Summary Block: version expected");
4838  }
4839  const uint64_t Version = Record[0];
4840  const bool IsOldProfileFormat = Version == 1;
4841  if (Version < 1 || Version > 3)
4842  return error("Invalid summary version " + Twine(Version) +
4843  ", 1, 2 or 3 expected");
4844  Record.clear();
4845 
4846  // Keep around the last seen summary to be used when we see an optional
4847  // "OriginalName" attachement.
4848  GlobalValueSummary *LastSeenSummary = nullptr;
4849  bool Combined = false;
4850  std::vector<GlobalValue::GUID> PendingTypeTests;
4851 
4852  while (true) {
4853  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
4854 
4855  switch (Entry.Kind) {
4856  case BitstreamEntry::SubBlock: // Handled for us already.
4857  case BitstreamEntry::Error:
4858  return error("Malformed block");
4859  case BitstreamEntry::EndBlock:
4860  // For a per-module index, remove any entries that still have empty
4861  // summaries. The VST parsing creates entries eagerly for all symbols,
4862  // but not all have associated summaries (e.g. it doesn't know how to
4863  // distinguish between VST_CODE_ENTRY for function declarations vs global
4864  // variables with initializers that end up with a summary). Remove those
4865  // entries now so that we don't need to rely on the combined index merger
4866  // to clean them up (especially since that may not run for the first
4867  // module's index if we merge into that).
4868  if (!Combined)
4869  TheIndex.removeEmptySummaryEntries();
4870  return Error::success();
4871  case BitstreamEntry::Record:
4872  // The interesting case.
4873  break;
4874  }
4875 
4876  // Read a record. The record format depends on whether this
4877  // is a per-module index or a combined index file. In the per-module
4878  // case the records contain the associated value's ID for correlation
4879  // with VST entries. In the combined index the correlation is done
4880  // via the bitcode offset of the summary records (which were saved
4881  // in the combined index VST entries). The records also contain
4882  // information used for ThinLTO renaming and importing.
4883  Record.clear();
4884  auto BitCode = Stream.readRecord(Entry.ID, Record);
4885  switch (BitCode) {
4886  default: // Default behavior: ignore.
4887  break;
4888  // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
4889  // n x (valueid)]
4890  // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
4891  // numrefs x valueid,
4892  // n x (valueid, hotness)]
4893  case bitc::FS_PERMODULE:
4895  unsigned ValueID = Record[0];
4896  uint64_t RawFlags = Record[1];
4897  unsigned InstCount = Record[2];
4898  unsigned NumRefs = Record[3];
4899  auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
4900  // The module path string ref set in the summary must be owned by the
4901  // index's module string table. Since we don't have a module path
4902  // string table section in the per-module index, we create a single
4903  // module path string table entry with an empty (0) ID to take
4904  // ownership.
4905  static int RefListStartIndex = 4;
4906  int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
4907  assert(Record.size() >= RefListStartIndex + NumRefs &&
4908  "Record size inconsistent with number of references");
4909  std::vector<ValueInfo> Refs = makeRefList(
4910  ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
4911  bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
4912  std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
4913  ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
4914  IsOldProfileFormat, HasProfile);
4915  auto FS = llvm::make_unique<FunctionSummary>(
4916  Flags, InstCount, std::move(Refs), std::move(Calls),
4917  std::move(PendingTypeTests));
4918  PendingTypeTests.clear();
4919  auto GUID = getGUIDFromValueId(ValueID);
4920  FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
4921  FS->setOriginalName(GUID.second);
4922  TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
4923  break;
4924  }
4925  // FS_ALIAS: [valueid, flags, valueid]
4926  // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
4927  // they expect all aliasee summaries to be available.
4928  case bitc::FS_ALIAS: {
4929  unsigned ValueID = Record[0];
4930  uint64_t RawFlags = Record[1];
4931  unsigned AliaseeID = Record[2];
4932  auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
4933  auto AS =
4934  llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
4935  // The module path string ref set in the summary must be owned by the
4936  // index's module string table. Since we don't have a module path
4937  // string table section in the per-module index, we create a single
4938  // module path string table entry with an empty (0) ID to take
4939  // ownership.
4940  AS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
4941 
4942  GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
4943  auto *AliaseeSummary = TheIndex.getGlobalValueSummary(AliaseeGUID);
4944  if (!AliaseeSummary)
4945  return error("Alias expects aliasee summary to be parsed");
4946  AS->setAliasee(AliaseeSummary);
4947 
4948  auto GUID = getGUIDFromValueId(ValueID);
4949  AS->setOriginalName(GUID.second);
4950  TheIndex.addGlobalValueSummary(GUID.first, std::move(AS));
4951  break;
4952  }
4953  // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
4955  unsigned ValueID = Record[0];
4956  uint64_t RawFlags = Record[1];
4957  auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
4958  std::vector<ValueInfo> Refs =
4959  makeRefList(ArrayRef<uint64_t>(Record).slice(2));
4960  auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
4961  FS->setModulePath(TheIndex.addModulePath(ModulePath, 0)->first());
4962  auto GUID = getGUIDFromValueId(ValueID);
4963  FS->setOriginalName(GUID.second);
4964  TheIndex.addGlobalValueSummary(GUID.first, std::move(FS));
4965  break;
4966  }
4967  // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
4968  // numrefs x valueid, n x (valueid)]
4969  // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
4970  // numrefs x valueid, n x (valueid, hotness)]
4971  case bitc::FS_COMBINED:
4973  unsigned ValueID = Record[0];
4974  uint64_t ModuleId = Record[1];
4975  uint64_t RawFlags = Record[2];
4976  unsigned InstCount = Record[3];
4977  unsigned NumRefs = Record[4];
4978  auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
4979  static int RefListStartIndex = 5;
4980  int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
4981  assert(Record.size() >= RefListStartIndex + NumRefs &&
4982  "Record size inconsistent with number of references");
4983  std::vector<ValueInfo> Refs = makeRefList(
4984  ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
4985  bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
4986  std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
4987  ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
4988  IsOldProfileFormat, HasProfile);
4989  GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
4990  auto FS = llvm::make_unique<FunctionSummary>(
4991  Flags, InstCount, std::move(Refs), std::move(Edges),
4992  std::move(PendingTypeTests));
4993  PendingTypeTests.clear();
4994  LastSeenSummary = FS.get();
4995  FS->setModulePath(ModuleIdMap[ModuleId]);
4996  TheIndex.addGlobalValueSummary(GUID, std::move(FS));
4997  Combined = true;
4998  break;
4999  }
5000  // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
5001  // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
5002  // they expect all aliasee summaries to be available.
5003  case bitc::FS_COMBINED_ALIAS: {
5004  unsigned ValueID = Record[0];
5005  uint64_t ModuleId = Record[1];
5006  uint64_t RawFlags = Record[2];
5007  unsigned AliaseeValueId = Record[3];
5008  auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5009  auto AS = llvm::make_unique<AliasSummary>(Flags, std::vector<ValueInfo>{});
5010  LastSeenSummary = AS.get();
5011  AS->setModulePath(ModuleIdMap[ModuleId]);
5012 
5013  auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
5014  auto AliaseeInModule =
5015  TheIndex.findSummaryInModule(AliaseeGUID, AS->modulePath());
5016  if (!AliaseeInModule)
5017  return error("Alias expects aliasee summary to be parsed");
5018  AS->setAliasee(AliaseeInModule);
5019 
5020  GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
5021  TheIndex.addGlobalValueSummary(GUID, std::move(AS));
5022  Combined = true;
5023  break;
5024  }
5025  // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
5027  unsigned ValueID = Record[0];
5028  uint64_t ModuleId = Record[1];
5029  uint64_t RawFlags = Record[2];
5030  auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
5031  std::vector<ValueInfo> Refs =
5032  makeRefList(ArrayRef<uint64_t>(Record).slice(3));
5033  auto FS = llvm::make_unique<GlobalVarSummary>(Flags, std::move(Refs));
5034  LastSeenSummary = FS.get();
5035  FS->setModulePath(ModuleIdMap[ModuleId]);
5036  GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
5037  TheIndex.addGlobalValueSummary(GUID, std::move(FS));
5038  Combined = true;
5039  break;
5040  }
5041  // FS_COMBINED_ORIGINAL_NAME: [original_name]
5043  uint64_t OriginalName = Record[0];
5044  if (!LastSeenSummary)
5045  return error("Name attachment that does not follow a combined record");
5046  LastSeenSummary->setOriginalName(OriginalName);
5047  // Reset the LastSeenSummary
5048  LastSeenSummary = nullptr;
5049  break;
5050  }
5051  case bitc::FS_TYPE_TESTS: {
5052  assert(PendingTypeTests.empty());
5053  PendingTypeTests.insert(PendingTypeTests.end(), Record.begin(),
5054  Record.end());
5055  break;
5056  }
5057  }
5058  }
5059  llvm_unreachable("Exit infinite loop");
5060 }
5061 
5062 // Parse the module string table block into the Index.
5063 // This populates the ModulePathStringTable map in the index.
5064 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
5066  return error("Invalid record");
5067 
5069 
5070  SmallString<128> ModulePath;
5071  ModulePathStringTableTy::iterator LastSeenModulePath;
5072 
5073  while (true) {
5074  BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5075 
5076  switch (Entry.Kind) {
5077  case BitstreamEntry::SubBlock: // Handled for us already.
5078  case BitstreamEntry::Error:
5079  return error("Malformed block");
5080  case BitstreamEntry::EndBlock:
5081  return Error::success();
5082  case BitstreamEntry::Record:
5083  // The interesting case.
5084  break;
5085  }
5086 
5087  Record.clear();
5088  switch (Stream.readRecord(Entry.ID, Record)) {
5089  default: // Default behavior: ignore.
5090  break;
5091  case bitc::MST_CODE_ENTRY: {
5092  // MST_ENTRY: [modid, namechar x N]
5093  uint64_t ModuleId = Record[0];
5094 
5095  if (convertToString(Record, 1, ModulePath))
5096  return error("Invalid record");
5097 
5098  LastSeenModulePath = TheIndex.addModulePath(ModulePath, ModuleId);
5099  ModuleIdMap[ModuleId] = LastSeenModulePath->first();
5100 
5101  ModulePath.clear();
5102  break;
5103  }
5104  /// MST_CODE_HASH: [5*i32]
5105  case bitc::MST_CODE_HASH: {
5106  if (Record.size() != 5)
5107  return error("Invalid hash length " + Twine(Record.size()).str());
5108  if (LastSeenModulePath == TheIndex.modulePaths().end())
5109  return error("Invalid hash that does not follow a module path");
5110  int Pos = 0;
5111  for (auto &Val : Record) {
5112  assert(!(Val >> 32) && "Unexpected high bits set");
5113  LastSeenModulePath->second.second[Pos++] = Val;
5114  }
5115  // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
5116  LastSeenModulePath = TheIndex.modulePaths().end();
5117  break;
5118  }
5119  }
5120  }
5121  llvm_unreachable("Exit infinite loop");
5122 }
5123 
5124 namespace {
5125 
5126 // FIXME: This class is only here to support the transition to llvm::Error. It
5127 // will be removed once this transition is complete. Clients should prefer to
5128 // deal with the Error value directly, rather than converting to error_code.
5129 class BitcodeErrorCategoryType : public std::error_category {
5130  const char *name() const noexcept override {
5131  return "llvm.bitcode";
5132  }
5133  std::string message(int IE) const override {
5134  BitcodeError E = static_cast<BitcodeError>(IE);
5135  switch (E) {
5136  case BitcodeError::CorruptedBitcode:
5137  return "Corrupted bitcode";
5138  }
5139  llvm_unreachable("Unknown error type!");
5140  }
5141 };
5142 
5143 } // end anonymous namespace
5144 
5146 
5148  return *ErrorCategory;
5149 }
5150 
5151 //===----------------------------------------------------------------------===//
5152 // External interface
5153 //===----------------------------------------------------------------------===//
5154 
5157  Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5158  if (!StreamOrErr)
5159  return StreamOrErr.takeError();
5160  BitstreamCursor &Stream = *StreamOrErr;
5161 
5162  std::vector<BitcodeModule> Modules;
5163  while (true) {
5164  uint64_t BCBegin = Stream.getCurrentByteNo();
5165 
5166  // We may be consuming bitcode from a client that leaves garbage at the end
5167  // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
5168  // the end that there cannot possibly be another module, stop looking.
5169  if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
5170  return Modules;
5171 
5172  BitstreamEntry Entry = Stream.advance();
5173  switch (Entry.Kind) {
5174  case BitstreamEntry::EndBlock:
5175  case BitstreamEntry::Error:
5176  return error("Malformed block");
5177 
5178  case BitstreamEntry::SubBlock: {
5179  uint64_t IdentificationBit = -1ull;
5180  if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
5181  IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5182  if (Stream.SkipBlock())
5183  return error("Malformed block");
5184 
5185  Entry = Stream.advance();
5186  if (Entry.Kind != BitstreamEntry::SubBlock ||
5187  Entry.ID != bitc::MODULE_BLOCK_ID)
5188  return error("Malformed block");
5189  }
5190 
5191  if (Entry.ID == bitc::MODULE_BLOCK_ID) {
5192  uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
5193  if (Stream.SkipBlock())
5194  return error("Malformed block");
5195 
5196  Modules.push_back({Stream.getBitcodeBytes().slice(
5197  BCBegin, Stream.getCurrentByteNo() - BCBegin),
5198  Buffer.getBufferIdentifier(), IdentificationBit,
5199  ModuleBit});
5200  continue;
5201  }
5202 
5203  if (Stream.SkipBlock())
5204  return error("Malformed block");
5205  continue;
5206  }
5207  case BitstreamEntry::Record:
5208  Stream.skipRecord(Entry.ID);
5209  continue;
5210  }
5211  }
5212 }
5213 
5214 /// \brief Get a lazy one-at-time loading module from bitcode.
5215 ///
5216 /// This isn't always used in a lazy context. In particular, it's also used by
5217 /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
5218 /// in forward-referenced functions from block address references.
5219 ///
5220 /// \param[in] MaterializeAll Set to \c true if we should materialize
5221 /// everything.
5223 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
5224  bool ShouldLazyLoadMetadata, bool IsImporting) {
5225  BitstreamCursor Stream(Buffer);
5226 
5227  std::string ProducerIdentification;
5228  if (IdentificationBit != -1ull) {
5229  Stream.JumpToBit(IdentificationBit);
5230  Expected<std::string> ProducerIdentificationOrErr =
5231  readIdentificationBlock(Stream);
5232  if (!ProducerIdentificationOrErr)
5233  return ProducerIdentificationOrErr.takeError();
5234 
5235  ProducerIdentification = *ProducerIdentificationOrErr;
5236  }
5237 
5238  Stream.JumpToBit(ModuleBit);
5239  auto *R =
5240  new BitcodeReader(std::move(Stream), ProducerIdentification, Context);
5241 
5242  std::unique_ptr<Module> M =
5243  llvm::make_unique<Module>(ModuleIdentifier, Context);
5244  M->setMaterializer(R);
5245 
5246  // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
5247  if (Error Err =
5248  R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata, IsImporting))
5249  return std::move(Err);
5250 
5251  if (MaterializeAll) {
5252  // Read in the entire module, and destroy the BitcodeReader.
5253  if (Error Err = M->materializeAll())
5254  return std::move(Err);
5255  } else {
5256  // Resolve forward references from blockaddresses.
5257  if (Error Err = R->materializeForwardReferencedFunctions())
5258  return std::move(Err);
5259  }
5260  return std::move(M);
5261 }
5262 
5264 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
5265  bool IsImporting) {
5266  return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting);
5267 }
5268 
5269 // Parse the specified bitcode buffer, returning the function info index.
5271  BitstreamCursor Stream(Buffer);
5272  Stream.JumpToBit(ModuleBit);
5273 
5274  auto Index = llvm::make_unique<ModuleSummaryIndex>();
5275  ModuleSummaryIndexBitcodeReader R(std::move(Stream), *Index);
5276 
5277  if (Error Err = R.parseModule(ModuleIdentifier))
5278  return std::move(Err);
5279 
5280  return std::move(Index);
5281 }
5282 
5283 // Check if the given bitcode buffer contains a global value summary block.
5285  BitstreamCursor Stream(Buffer);
5286  Stream.JumpToBit(ModuleBit);
5287 
5289  return error("Invalid record");
5290 
5291  while (true) {
5292  BitstreamEntry Entry = Stream.advance();
5293 
5294  switch (Entry.Kind) {
5295  case BitstreamEntry::Error:
5296  return error("Malformed block");
5298  return false;
5299 
5301  if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID)
5302  return true;
5303 
5304  // Ignore other sub-blocks.
5305  if (Stream.SkipBlock())
5306  return error("Malformed block");
5307  continue;
5308 
5310  Stream.skipRecord(Entry.ID);
5311  continue;
5312  }
5313  }
5314 }
5315 
5318  if (!MsOrErr)
5319  return MsOrErr.takeError();
5320 
5321  if (MsOrErr->size() != 1)
5322  return error("Expected a single module");
5323 
5324  return (*MsOrErr)[0];
5325 }
5326 
5329  bool ShouldLazyLoadMetadata, bool IsImporting) {
5331  if (!BM)
5332  return BM.takeError();
5333 
5334  return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting);
5335 }
5336 
5338  std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
5339  bool ShouldLazyLoadMetadata, bool IsImporting) {
5340  auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
5341  IsImporting);
5342  if (MOrErr)
5343  (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
5344  return MOrErr;
5345 }
5346 
5349  return getModuleImpl(Context, true, false, false);
5350  // TODO: Restore the use-lists to the in-memory state when the bitcode was
5351  // written. We must defer until the Module has been fully materialized.
5352 }
5353 
5355  LLVMContext &Context) {
5357  if (!BM)
5358  return BM.takeError();
5359 
5360  return BM->parseModule(Context);
5361 }
5362 
5364  Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5365  if (!StreamOrErr)
5366  return StreamOrErr.takeError();
5367 
5368  return readTriple(*StreamOrErr);
5369 }
5370 
5372  Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5373  if (!StreamOrErr)
5374  return StreamOrErr.takeError();
5375 
5376  return hasObjCCategory(*StreamOrErr);
5377 }
5378 
5380  Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
5381  if (!StreamOrErr)
5382  return StreamOrErr.takeError();
5383 
5384  return readIdentificationCode(*StreamOrErr);
5385 }
5386 
5390  if (!BM)
5391  return BM.takeError();
5392 
5393  return BM->getSummary();
5394 }
5395 
5398  if (!BM)
5399  return BM.takeError();
5400 
5401  return BM->hasSummary();
5402 }
void setVisibility(VisibilityTypes V)
Definition: GlobalValue.h:225
MachineLoop * L
static AtomicOrdering getDecodedOrdering(unsigned Val)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type (if unknown returns 0).
const NoneType None
Definition: None.h:23
The highest possible calling convention ID. Must be some 2^k - 1.
Definition: CallingConv.h:200
void sortUseList(Compare Cmp)
Sort the use-list.
Definition: Value.h:640
static APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BLOCKINFO_BLOCK is used to define metadata about blocks, for example, standard abbrevs that should be...
Definition: BitCodes.h:69
LLVM Argument representation.
Definition: Argument.h:34
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:575
LLVMContext & Context
void setNoSignedZeros()
Definition: Operator.h:203
const Instruction & back() const
Definition: BasicBlock.h:242
Atomic ordering constants.
bool hasName() const
Definition: Value.h:236
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:465
size_t i
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:162
uint64_t GetCurrentBitNo() const
Return the bit # of the bit we are reading.
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:52
Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
Definition: DerivedTypes.h:137
void setNoNaNs()
Flag setters.
Definition: Operator.h:201
An instruction for ordering other memory operations.
Definition: Instructions.h:430
iterator end()
Definition: Function.h:537
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:504
static int getDecodedBinaryOpcode(unsigned Val, Type *Ty)
void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
void setMaterializer(GVMaterializer *GVM)
Sets the GVMaterializer to GVM.
Definition: Module.cpp:402
This class represents a function call, abstracting a target machine's calling convention.
void setGC(std::string Str)
Definition: Function.cpp:417
Expected< bool > hasSummary()
Check if the given bitcode buffer contains a summary block.
Expected< std::unique_ptr< ModuleSummaryIndex > > getSummary()
Parse the specified bitcode buffer, returning the module summary index.
This instruction constructs a fixed permutation of two input vectors.
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition: Type.h:148
bool isBitcodeWrapper(const unsigned char *BufPtr, const unsigned char *BufEnd)
isBitcodeWrapper - Return true if the given bytes are the magic bytes for an LLVM IR bitcode wrapper...
static uint64_t jumpToValueSymbolTable(uint64_t Offset, BitstreamCursor &Stream)
Helper to note and return the current location, and jump to the given offset.
const char * getBufferStart() const
Definition: MemoryBuffer.h:173
AttrBuilder & addDereferenceableAttr(uint64_t Bytes)
This turns the number of dereferenceable bytes into the form used internally in Attribute.
A debug info location.
Definition: DebugLoc.h:34
Metadata node.
Definition: Metadata.h:830
The two locations do not alias at all.
Definition: AliasAnalysis.h:79
bool stripDebugInfo(Function &F)
Definition: DebugInfo.cpp:242
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:471
An instruction for reading from memory.
Definition: Instructions.h:164
ELFYAML::ELF_STV Visibility
Definition: ELFYAML.cpp:661
static Attribute::AttrKind getAttrFromCode(uint64_t Code)
FunctionType * getType(LLVMContext &Context, ID id, ArrayRef< Type * > Tys=None)
Return the function type for an intrinsic.
Definition: Function.cpp:905
AttrBuilder & addAttribute(Attribute::AttrKind Val)
Add an attribute to the builder.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Definition: Instructions.h:669
Error takeError()
Take ownership of the stored error.
Type * getElementType() const
Definition: DerivedTypes.h:462
void reserve(size_type N)
Definition: SmallVector.h:377
void UpgradeIntrinsicCall(CallInst *CI, Function *NewFn)
This is the complement to the above, replacing a specific call to an intrinsic function with a call t...
void setAlignment(unsigned Align)
Definition: Globals.cpp:86
Base class for error info classes.
Definition: Support/Error.h:46
void setBlockInfo(BitstreamBlockInfo *BI)
Set the block info to be used by this BitstreamCursor to interpret abbreviated records.
word_t Read(unsigned NumBits)
uint64_t High
static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val)
bool isMaterializable() const
Definition: Function.cpp:216
uint64_t getArrayNumElements() const
Definition: DerivedTypes.h:364
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:191
ArrayRef< uint8_t > getBitcodeBytes() const
void setIndirectSymbol(Constant *Symbol)
These methods set and retrieve indirect symbol.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array...
Definition: ArrayRef.h:171
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
struct fuzzer::@269 Flags
AttrBuilder & addDereferenceableOrNullAttr(uint64_t Bytes)
This turns the number of dereferenceable_or_null bytes into the form used internally in Attribute...
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:440
Class to represent struct types.
Definition: DerivedTypes.h:199
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
bool canSkipToPos(size_t pos) const
void setThreadLocalMode(ThreadLocalMode Val)
Definition: GlobalValue.h:236
Constant * getPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.cpp:1218
std::error_code make_error_code(BitcodeError E)
This file contains the simple types necessary to represent the attributes associated with functions a...
SynchronizationScope
Definition: Instructions.h:50
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:257
Tagged union holding either a T or a Error.
void setDLLStorageClass(DLLStorageClassTypes C)
Definition: GlobalValue.h:253
This file implements a class to represent arbitrary precision integral constant values and operations...
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
AtomicOrdering
Atomic ordering for LLVM's memory model.
static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:241
void emitError(unsigned LocCookie, const Twine &ErrorStr)
emitError - Emit an error message to the currently installed error handler with optional location inf...
Subprogram description.
llvm::Optional< Function * > remangleIntrinsicFunction(Function *F)
Definition: Function.cpp:1135
Class to represent function types.
Definition: DerivedTypes.h:102
void setCleanup(bool V)
Indicate that this landingpad instruction is a cleanup.
#define F(x, y, z)
Definition: MD5.cpp:51
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
const BasicBlock & back() const
Definition: Function.h:544
BinOp
This enumeration lists the possible modifications atomicrmw can make.
Definition: Instructions.h:681
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition: Type.h:142
Class to represent array types.
Definition: DerivedTypes.h:345
VisibilityTypes
An enumeration for the kinds of visibility of global values.
Definition: GlobalValue.h:63
bool empty() const
Definition: BasicBlock.h:239
std::pair< ValueInfo, CalleeInfo > EdgeTy
<CalleeValueInfo, CalleeInfo> call edge pair.
This instruction compares its operands according to the predicate given to the constructor.
void setComdat(Comdat *C)
Definition: GlobalObject.h:94
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:266
bool UpgradeIntrinsicFunction(Function *F, Function *&NewFn)
This is a more granular function that simply checks an intrinsic function for upgrading, and returns true if it requires upgrading.
static GCRegistry::Add< OcamlGC > B("ocaml","ocaml 3.10-compatible GC")
An instruction for storing to memory.
Definition: Instructions.h:300
bool isArrayTy() const
True if this is an instance of ArrayType.
Definition: Type.h:210
BitstreamEntry advanceSkippingSubblocks(unsigned Flags=0)
This is a convenience function for clients that don't expect any subblocks.
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM...
iterator begin()
Definition: Function.h:535
Class to hold module path string table and global value map, and encapsulate methods for operating on...
AttrBuilder & addAllocSizeAttrFromRawRepr(uint64_t RawAllocSizeRepr)
Add an allocsize attribute, using the representation returned by Attribute.getIntValue().
Type * getScalarType() const LLVM_READONLY
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.cpp:44
bool isPPC_FP128Ty() const
Return true if this is powerpc long double.
Definition: Type.h:157
Type * getElementType() const
Definition: DerivedTypes.h:336
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:141
static GlobalValue::DLLStorageClassTypes getDecodedDLLStorageClass(unsigned Val)
const std::error_category & BitcodeErrorCategory()
Class to represent pointers.
Definition: DerivedTypes.h:443
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
static MetadataAsValue * get(LLVMContext &Context, Metadata *MD)
Definition: Metadata.cpp:74
T Min(T a, T b)
Definition: FuzzerDefs.h:56
Expected< std::string > getBitcodeProducerString(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the producer string information...
void setCallingConv(CallingConv::ID CC)
Definition: Function.h:169
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:201
Type * getParamType(unsigned i) const
Parameter type accessors.
Definition: DerivedTypes.h:133
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:395
static Expected< BitcodeModule > getSingleModule(MemoryBufferRef Buffer)
void setSubprogram(DISubprogram *SP)
Set the attached subprogram.
Definition: Metadata.cpp:1454
The landingpad instruction holds all of the information necessary to generate correct exception handl...
constexpr bool isPowerOf2_32(uint32_t Value)
isPowerOf2_32 - This function returns true if the argument is a power of two > 0. ...
Definition: MathExtras.h:399
LLVM Basic Block Representation.
Definition: BasicBlock.h:51
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:48
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:219
This function has undefined behavior.
This is an important base class in LLVM.
Definition: Constant.h:42
static bool hasImplicitComdat(size_t Val)
This represents a position within a bitcode file, implemented on top of a SimpleBitstreamCursor.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:115
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void setUsedWithInAlloca(bool V)
Specify whether this alloca is used to represent the arguments to a call.
Definition: Instructions.h:126
Indirect Branch Instruction.
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition: Type.h:145
APInt Or(const APInt &LHS, const APInt &RHS)
Bitwise OR function for APInt.
Definition: APInt.h:1947
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
APInt Xor(const APInt &LHS, const APInt &RHS)
Bitwise XOR function for APInt.
Definition: APInt.h:1952
Class to accumulate and hold information about a callee.
iterator_range< use_iterator > materialized_uses()
Definition: Value.h:320
bool hasPersonalityFn() const
Check whether this function has a personality function.
Definition: Function.h:581
static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val)
void setUnsafeAlgebra()
Definition: Operator.h:205
uint64_t getCurrentByteNo() const
static ManagedStatic< _object_error_category > error_category
This file declares a class to represent arbitrary precision floating point values and provide a varie...
uint32_t Offset
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:249
const GlobalObject * getBaseObject() const
Select target instructions out of generic instructions
This instruction compares its operands according to the predicate given to the constructor.
iterator begin() const
Definition: ArrayRef.h:129
uint64_t getNumElements() const
Definition: DerivedTypes.h:335
void addClause(Constant *ClauseVal)
Add a catch or filter clause to the landing pad.
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
DLLStorageClassTypes
Storage classes of global values for PE targets.
Definition: GlobalValue.h:70
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
Function and variable summary information to aid decisions and implementation of importing.
void JumpToBit(uint64_t BitNo)
Reset the stream to the specified bit number.
bool isFP128Ty() const
Return true if this is 'fp128'.
Definition: Type.h:154
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:213
This class represents the va_arg llvm instruction, which returns an argument of the specified type gi...
static Attribute::AttrKind parseAttrKind(StringRef Kind)
bool SkipBlock()
Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip over the body of this block...
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:183
static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val)
void setBody(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type.
Definition: Type.cpp:350
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
size_t getBufferSize() const
Definition: MemoryBuffer.h:175
static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val)
Instruction * UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy, Instruction *&Temp)
This is an auto-upgrade for bitcast between pointers with different address spaces: the instruction i...
static void addRawAttributeValue(AttrBuilder &B, uint64_t Val)
uint64_t * Vals
Iterator for intrusive lists based on ilist_node.
Expected< bool > isBitcodeContainingObjCCategory(MemoryBufferRef Buffer)
Return true if Buffer contains a bitcode file with ObjC code (category or class) in it...
static bool hasObjCCategory(StringRef Name)
Definition: DwarfDebug.cpp:295
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...
This is the shared class of boolean and integer constants.
Definition: Constants.h:88
void setSelectionKind(SelectionKind Val)
Definition: Comdat.h:43
Helper class that handles loading Metadatas and keeping them available.
ValType
This is used to indicate local types.
void setAllowReciprocal()
Definition: Operator.h:204
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:843
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:230
bool UpgradeGlobalVariable(GlobalVariable *GV)
This checks for global variables which should be upgraded.
unsigned readRecord(unsigned AbbrevID, SmallVectorImpl< uint64_t > &Vals, StringRef *Blob=nullptr)
AddressSpace
Definition: NVPTXBaseInfo.h:22
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
Definition: PPCPredicates.h:27
This class maintains the abbreviations read from a block info block.
virtual std::error_code convertToErrorCode() const =0
Convert this error to a std::error_code.
reference get()
Returns a reference to the stored T value.
static SynchronizationScope getDecodedSynchScope(unsigned Val)
bool any() const
Whether any flag is set.
Definition: Operator.h:188
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:424
static GCRegistry::Add< ShadowStackGC > C("shadow-stack","Very portable GC for uncooperative code generators")
static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:586
Class to represent vector types.
Definition: DerivedTypes.h:369
unsigned skipRecord(unsigned AbbrevID)
Read the current record and discard it, returning the code for the record.
Class for arbitrary precision integers.
Definition: APInt.h:77
static int getDecodedCastOpcode(unsigned Val)
void push_back(pointer val)
Definition: ilist.h:326
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:267
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:48
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:195
iterator_range< user_iterator > users()
Definition: Value.h:370
Optional< BitstreamBlockInfo > ReadBlockInfoBlock(bool ReadBlockInfoNames=false)
Read and return a block info block from the bitstream.
bool empty() const
Definition: Function.h:541
void setIsMaterializable(bool V)
Definition: Function.cpp:220
void setAttributes(AttributeSet Attrs)
Set the attribute list for this Function.
Definition: Function.h:179
void setSwiftError(bool V)
Specify whether this alloca is used to represent a swifterror.
Definition: Instructions.h:137
APInt And(const APInt &LHS, const APInt &RHS)
Bitwise AND function for APInt.
Definition: APInt.h:1942
bool isStructTy() const
True if this is an instance of StructType.
Definition: Type.h:207
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
Definition: Type.cpp:367
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:259
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:119
static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val)
bool isX86_FP80Ty() const
Return true if this is x86 long double.
Definition: Type.h:151
ValID - Represents a reference of a definition of some sort with no type.
Definition: LLParser.h:47
pointer data()
Return a pointer to the vector's buffer, even if empty().
Definition: SmallVector.h:142
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:203
bool SkipBitcodeWrapperHeader(const unsigned char *&BufPtr, const unsigned char *&BufEnd, bool VerifyBufferSize)
SkipBitcodeWrapperHeader - Some systems wrap bc files with a special header for padding or other reas...
bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP=nullptr)
Having read the ENTER_SUBBLOCK abbrevid, enter the block, and return true if the block has an error...
const char * c_str()
Definition: SmallString.h:270
enum llvm::BitstreamEntry::@32 Kind
#define I(x, y, z)
Definition: MD5.cpp:54
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
static bool isValidElementType(Type *Ty)
Predicate for the element types that the SLP vectorizer supports.
iterator find(const KeyT &Val)
Definition: DenseMap.h:127
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:287
AttributeSet getAttributes(LLVMContext &C, ID id)
Return the attributes for an intrinsic.
void setModulePath(StringRef ModPath)
Set the path to the module containing this function, for use in the combined index.
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
Definition: STLExtras.h:807
bool hasLocalLinkage() const
Definition: GlobalValue.h:415
void addDestination(BasicBlock *Dest)
Add a destination.
bool isVarArg() const
Definition: DerivedTypes.h:122
const unsigned Kind
Multiway switch.
static void decodeLLVMAttributesForBitcode(AttrBuilder &B, uint64_t EncodedAttrs)
This fills an AttrBuilder object with the LLVM attributes that have been decoded from the given integ...
Expected< std::unique_ptr< Module > > getOwningLazyBitcodeModule(std::unique_ptr< MemoryBuffer > &&Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Like getLazyBitcodeModule, except that the module takes ownership of the memory buffer if successful...
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
StringRef getBufferIdentifier() const
Definition: MemoryBuffer.h:171
StringMapEntry< Value * > ValueName
Definition: Value.h:51
std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err)
aarch64 promote const
bool isLabelTy() const
Return true if this is 'label'.
Definition: Type.h:186
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:537
Verify that the TBAA Metadatas are valid.
Definition: Verifier.h:36
LLVM Value Representation.
Definition: Value.h:71
Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
static const char * name
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
Definition: Compiler.h:239
Lightweight error class with error context and mandatory checking.
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:81
AttrBuilder & addStackAlignmentAttr(unsigned Align)
This turns an int stack alignment (which must be a power of 2) into the form used internally in Attri...
static cl::opt< bool > PrintSummaryGUIDs("print-summary-global-ids", cl::init(false), cl::Hidden, cl::desc("Print the global id for each value when reading the module summary"))
Group flags (Linkage, NotEligibleToImport, etc.) as a bitfield.
Error error(const Twine &Message)
Expected< std::unique_ptr< Module > > getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata, bool IsImporting)
Read the bitcode module and prepare for lazy deserialization of function bodies.
virtual std::string message() const
Return the error message as a string.
Definition: Support/Error.h:54
std::string Hash(const Unit &U)
Definition: FuzzerSHA1.cpp:216
Expected< std::unique_ptr< Module > > parseModule(LLVMContext &Context)
Read the entire bitcode module and return it.
BitstreamEntry advance(unsigned Flags=0)
Advance the current bitstream, returning the next entry in the stream.
Convenience struct for specifying and reasoning about fast-math flags.
Definition: Operator.h:168
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:47
inst_range instructions(Function *F)
Definition: InstIterator.h:132
static ManagedStatic< BitcodeErrorCategoryType > ErrorCategory
AttrBuilder & addAlignmentAttr(unsigned Align)
This turns an int alignment (which must be a power of 2) into the form used internally in Attribute...
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
Definition: ManagedStatic.h:63
void setPersonalityFn(Constant *Fn)
Definition: Function.cpp:1223
int * Ptr
Value * UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy)
This is an auto-upgrade for bitcast constant expression between pointers with different address space...
T Max(T a, T b)
Definition: FuzzerDefs.h:57
unsigned getAbbrevIDWidth() const
Return the number of bits used to encode an abbrev #.
AddressSpace
Definition: AVR.h:42
static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags, uint64_t Version)
Decode the flags for GlobalValue in the summary.
Expected< bool > hasGlobalValueSummary(MemoryBufferRef Buffer)
Check if the given bitcode buffer contains a summary block.
static GCRegistry::Add< ErlangGC > A("erlang","erlang-compatible garbage collector")
Root of the metadata hierarchy.
Definition: Metadata.h:55
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1051
const uint64_t Version
Definition: InstrProf.h:799
void setSection(StringRef S)
Change the section for this global.
Definition: Globals.cpp:173
void setCalledFunction(Value *V)
setCalledFunction - Set the callee to the specified value.
Definition: CallSite.h:116
TLM
Definition: LLParser.cpp:1329
iterator_range< arg_iterator > args()
Definition: Function.h:568
static FastMathFlags getDecodedFastMathFlags(unsigned Val)
ArrayRef< Type * > subtypes() const
Definition: Type.h:301
an instruction to allocate memory on the stack
Definition: Instructions.h:60
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results...
Definition: Attributes.h:67
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition: Type.h:189
static uint64_t getRawAttributeMask(Attribute::AttrKind Val)