LLVM  15.0.0git
BitcodeWriter.cpp
Go to the documentation of this file.
1 //===- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Bitcode writer implementation.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "ValueEnumerator.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
34 #include "llvm/Config/llvm-config.h"
35 #include "llvm/IR/Attributes.h"
36 #include "llvm/IR/BasicBlock.h"
37 #include "llvm/IR/Comdat.h"
38 #include "llvm/IR/Constant.h"
39 #include "llvm/IR/Constants.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/IR/Function.h"
44 #include "llvm/IR/GlobalAlias.h"
45 #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/InlineAsm.h"
50 #include "llvm/IR/InstrTypes.h"
51 #include "llvm/IR/Instruction.h"
52 #include "llvm/IR/Instructions.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Metadata.h"
55 #include "llvm/IR/Module.h"
57 #include "llvm/IR/Operator.h"
58 #include "llvm/IR/Type.h"
59 #include "llvm/IR/UseListOrder.h"
60 #include "llvm/IR/Value.h"
63 #include "llvm/MC/TargetRegistry.h"
64 #include "llvm/Object/IRSymtab.h"
66 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/Endian.h"
69 #include "llvm/Support/Error.h"
72 #include "llvm/Support/SHA1.h"
74 #include <algorithm>
75 #include <cassert>
76 #include <cstddef>
77 #include <cstdint>
78 #include <iterator>
79 #include <map>
80 #include <memory>
81 #include <string>
82 #include <utility>
83 #include <vector>
84 
85 using namespace llvm;
86 
87 static cl::opt<unsigned>
88  IndexThreshold("bitcode-mdindex-threshold", cl::Hidden, cl::init(25),
89  cl::desc("Number of metadatas above which we emit an index "
90  "to enable lazy-loading"));
92  "bitcode-flush-threshold", cl::Hidden, cl::init(512),
93  cl::desc("The threshold (unit M) for flushing LLVM bitcode."));
94 
96  "write-relbf-to-summary", cl::Hidden, cl::init(false),
97  cl::desc("Write relative block frequency to function summary "));
98 
100 
101 namespace {
102 
103 /// These are manifest constants used by the bitcode writer. They do not need to
104 /// be kept in sync with the reader, but need to be consistent within this file.
105 enum {
106  // VALUE_SYMTAB_BLOCK abbrev id's.
107  VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
108  VST_ENTRY_7_ABBREV,
109  VST_ENTRY_6_ABBREV,
110  VST_BBENTRY_6_ABBREV,
111 
112  // CONSTANTS_BLOCK abbrev id's.
113  CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
114  CONSTANTS_INTEGER_ABBREV,
115  CONSTANTS_CE_CAST_Abbrev,
116  CONSTANTS_NULL_Abbrev,
117 
118  // FUNCTION_BLOCK abbrev id's.
119  FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
120  FUNCTION_INST_UNOP_ABBREV,
121  FUNCTION_INST_UNOP_FLAGS_ABBREV,
122  FUNCTION_INST_BINOP_ABBREV,
123  FUNCTION_INST_BINOP_FLAGS_ABBREV,
124  FUNCTION_INST_CAST_ABBREV,
125  FUNCTION_INST_RET_VOID_ABBREV,
126  FUNCTION_INST_RET_VAL_ABBREV,
127  FUNCTION_INST_UNREACHABLE_ABBREV,
128  FUNCTION_INST_GEP_ABBREV,
129 };
130 
131 /// Abstract class to manage the bitcode writing, subclassed for each bitcode
132 /// file type.
133 class BitcodeWriterBase {
134 protected:
135  /// The stream created and owned by the client.
137 
138  StringTableBuilder &StrtabBuilder;
139 
140 public:
141  /// Constructs a BitcodeWriterBase object that writes to the provided
142  /// \p Stream.
143  BitcodeWriterBase(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder)
144  : Stream(Stream), StrtabBuilder(StrtabBuilder) {}
145 
146 protected:
147  void writeModuleVersion();
148 };
149 
150 void BitcodeWriterBase::writeModuleVersion() {
151  // VERSION: [version#]
153 }
154 
155 /// Base class to manage the module bitcode writing, currently subclassed for
156 /// ModuleBitcodeWriter and ThinLinkBitcodeWriter.
157 class ModuleBitcodeWriterBase : public BitcodeWriterBase {
158 protected:
159  /// The Module to write to bitcode.
160  const Module &M;
161 
162  /// Enumerates ids for all values in the module.
163  ValueEnumerator VE;
164 
165  /// Optional per-module index to write for ThinLTO.
166  const ModuleSummaryIndex *Index;
167 
168  /// Map that holds the correspondence between GUIDs in the summary index,
169  /// that came from indirect call profiles, and a value id generated by this
170  /// class to use in the VST and summary block records.
171  std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
172 
173  /// Tracks the last value id recorded in the GUIDToValueMap.
174  unsigned GlobalValueId;
175 
176  /// Saves the offset of the VSTOffset record that must eventually be
177  /// backpatched with the offset of the actual VST.
178  uint64_t VSTOffsetPlaceholder = 0;
179 
180 public:
181  /// Constructs a ModuleBitcodeWriterBase object for the given Module,
182  /// writing to the provided \p Buffer.
183  ModuleBitcodeWriterBase(const Module &M, StringTableBuilder &StrtabBuilder,
184  BitstreamWriter &Stream,
185  bool ShouldPreserveUseListOrder,
186  const ModuleSummaryIndex *Index)
187  : BitcodeWriterBase(Stream, StrtabBuilder), M(M),
188  VE(M, ShouldPreserveUseListOrder), Index(Index) {
189  // Assign ValueIds to any callee values in the index that came from
190  // indirect call profiles and were recorded as a GUID not a Value*
191  // (which would have been assigned an ID by the ValueEnumerator).
192  // The starting ValueId is just after the number of values in the
193  // ValueEnumerator, so that they can be emitted in the VST.
194  GlobalValueId = VE.getValues().size();
195  if (!Index)
196  return;
197  for (const auto &GUIDSummaryLists : *Index)
198  // Examine all summaries for this GUID.
199  for (auto &Summary : GUIDSummaryLists.second.SummaryList)
200  if (auto FS = dyn_cast<FunctionSummary>(Summary.get()))
201  // For each call in the function summary, see if the call
202  // is to a GUID (which means it is for an indirect call,
203  // otherwise we would have a Value for it). If so, synthesize
204  // a value id.
205  for (auto &CallEdge : FS->calls())
206  if (!CallEdge.first.haveGVs() || !CallEdge.first.getValue())
207  assignValueId(CallEdge.first.getGUID());
208  }
209 
210 protected:
211  void writePerModuleGlobalValueSummary();
212 
213 private:
214  void writePerModuleFunctionSummaryRecord(SmallVector<uint64_t, 64> &NameVals,
215  GlobalValueSummary *Summary,
216  unsigned ValueID,
217  unsigned FSCallsAbbrev,
218  unsigned FSCallsProfileAbbrev,
219  const Function &F);
220  void writeModuleLevelReferences(const GlobalVariable &V,
221  SmallVector<uint64_t, 64> &NameVals,
222  unsigned FSModRefsAbbrev,
223  unsigned FSModVTableRefsAbbrev);
224 
225  void assignValueId(GlobalValue::GUID ValGUID) {
226  GUIDToValueIdMap[ValGUID] = ++GlobalValueId;
227  }
228 
229  unsigned getValueId(GlobalValue::GUID ValGUID) {
230  const auto &VMI = GUIDToValueIdMap.find(ValGUID);
231  // Expect that any GUID value had a value Id assigned by an
232  // earlier call to assignValueId.
233  assert(VMI != GUIDToValueIdMap.end() &&
234  "GUID does not have assigned value Id");
235  return VMI->second;
236  }
237 
238  // Helper to get the valueId for the type of value recorded in VI.
239  unsigned getValueId(ValueInfo VI) {
240  if (!VI.haveGVs() || !VI.getValue())
241  return getValueId(VI.getGUID());
242  return VE.getValueID(VI.getValue());
243  }
244 
245  std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
246 };
247 
248 /// Class to manage the bitcode writing for a module.
249 class ModuleBitcodeWriter : public ModuleBitcodeWriterBase {
250  /// Pointer to the buffer allocated by caller for bitcode writing.
251  const SmallVectorImpl<char> &Buffer;
252 
253  /// True if a module hash record should be written.
254  bool GenerateHash;
255 
256  /// If non-null, when GenerateHash is true, the resulting hash is written
257  /// into ModHash.
258  ModuleHash *ModHash;
259 
260  SHA1 Hasher;
261 
262  /// The start bit of the identification block.
263  uint64_t BitcodeStartBit;
264 
265 public:
266  /// Constructs a ModuleBitcodeWriter object for the given Module,
267  /// writing to the provided \p Buffer.
268  ModuleBitcodeWriter(const Module &M, SmallVectorImpl<char> &Buffer,
269  StringTableBuilder &StrtabBuilder,
270  BitstreamWriter &Stream, bool ShouldPreserveUseListOrder,
271  const ModuleSummaryIndex *Index, bool GenerateHash,
272  ModuleHash *ModHash = nullptr)
273  : ModuleBitcodeWriterBase(M, StrtabBuilder, Stream,
274  ShouldPreserveUseListOrder, Index),
275  Buffer(Buffer), GenerateHash(GenerateHash), ModHash(ModHash),
276  BitcodeStartBit(Stream.GetCurrentBitNo()) {}
277 
278  /// Emit the current module to the bitstream.
279  void write();
280 
281 private:
282  uint64_t bitcodeStartBit() { return BitcodeStartBit; }
283 
284  size_t addToStrtab(StringRef Str);
285 
286  void writeAttributeGroupTable();
287  void writeAttributeTable();
288  void writeTypeTable();
289  void writeComdats();
290  void writeValueSymbolTableForwardDecl();
291  void writeModuleInfo();
292  void writeValueAsMetadata(const ValueAsMetadata *MD,
295  unsigned Abbrev);
296  unsigned createDILocationAbbrev();
298  unsigned &Abbrev);
299  unsigned createGenericDINodeAbbrev();
300  void writeGenericDINode(const GenericDINode *N,
301  SmallVectorImpl<uint64_t> &Record, unsigned &Abbrev);
303  unsigned Abbrev);
306  unsigned Abbrev);
307  void writeDIEnumerator(const DIEnumerator *N,
308  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
310  unsigned Abbrev);
311  void writeDIStringType(const DIStringType *N,
312  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
313  void writeDIDerivedType(const DIDerivedType *N,
314  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
316  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
319  unsigned Abbrev);
321  unsigned Abbrev);
322  void writeDICompileUnit(const DICompileUnit *N,
323  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
324  void writeDISubprogram(const DISubprogram *N,
325  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
327  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
330  unsigned Abbrev);
331  void writeDICommonBlock(const DICommonBlock *N,
332  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
334  unsigned Abbrev);
336  unsigned Abbrev);
338  unsigned Abbrev);
340  unsigned Abbrev);
342  unsigned Abbrev);
345  unsigned Abbrev);
348  unsigned Abbrev);
351  unsigned Abbrev);
353  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
354  void writeDILabel(const DILabel *N,
355  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
356  void writeDIExpression(const DIExpression *N,
357  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
360  unsigned Abbrev);
362  SmallVectorImpl<uint64_t> &Record, unsigned Abbrev);
365  unsigned Abbrev);
366  unsigned createNamedMetadataAbbrev();
367  void writeNamedMetadata(SmallVectorImpl<uint64_t> &Record);
368  unsigned createMetadataStringsAbbrev();
369  void writeMetadataStrings(ArrayRef<const Metadata *> Strings,
371  void writeMetadataRecords(ArrayRef<const Metadata *> MDs,
373  std::vector<unsigned> *MDAbbrevs = nullptr,
374  std::vector<uint64_t> *IndexPos = nullptr);
375  void writeModuleMetadata();
376  void writeFunctionMetadata(const Function &F);
377  void writeFunctionMetadataAttachment(const Function &F);
378  void pushGlobalMetadataAttachment(SmallVectorImpl<uint64_t> &Record,
379  const GlobalObject &GO);
380  void writeModuleMetadataKinds();
381  void writeOperandBundleTags();
382  void writeSyncScopeNames();
383  void writeConstants(unsigned FirstVal, unsigned LastVal, bool isGlobal);
384  void writeModuleConstants();
385  bool pushValueAndType(const Value *V, unsigned InstID,
387  void writeOperandBundles(const CallBase &CB, unsigned InstID);
388  void pushValue(const Value *V, unsigned InstID,
390  void pushValueSigned(const Value *V, unsigned InstID,
392  void writeInstruction(const Instruction &I, unsigned InstID,
394  void writeFunctionLevelValueSymbolTable(const ValueSymbolTable &VST);
395  void writeGlobalValueSymbolTable(
396  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
397  void writeUseList(UseListOrder &&Order);
398  void writeUseListBlock(const Function *F);
399  void
400  writeFunction(const Function &F,
401  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex);
402  void writeBlockInfo();
403  void writeModuleHash(size_t BlockStartPos);
404 
405  unsigned getEncodedSyncScopeID(SyncScope::ID SSID) {
406  return unsigned(SSID);
407  }
408 
409  unsigned getEncodedAlign(MaybeAlign Alignment) { return encode(Alignment); }
410 };
411 
412 /// Class to manage the bitcode writing for a combined index.
413 class IndexBitcodeWriter : public BitcodeWriterBase {
414  /// The combined index to write to bitcode.
415  const ModuleSummaryIndex &Index;
416 
417  /// When writing a subset of the index for distributed backends, client
418  /// provides a map of modules to the corresponding GUIDs/summaries to write.
419  const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex;
420 
421  /// Map that holds the correspondence between the GUID used in the combined
422  /// index and a value id generated by this class to use in references.
423  std::map<GlobalValue::GUID, unsigned> GUIDToValueIdMap;
424 
425  /// Tracks the last value id recorded in the GUIDToValueMap.
426  unsigned GlobalValueId = 0;
427 
428 public:
429  /// Constructs a IndexBitcodeWriter object for the given combined index,
430  /// writing to the provided \p Buffer. When writing a subset of the index
431  /// for a distributed backend, provide a \p ModuleToSummariesForIndex map.
432  IndexBitcodeWriter(BitstreamWriter &Stream, StringTableBuilder &StrtabBuilder,
433  const ModuleSummaryIndex &Index,
434  const std::map<std::string, GVSummaryMapTy>
435  *ModuleToSummariesForIndex = nullptr)
436  : BitcodeWriterBase(Stream, StrtabBuilder), Index(Index),
437  ModuleToSummariesForIndex(ModuleToSummariesForIndex) {
438  // Assign unique value ids to all summaries to be written, for use
439  // in writing out the call graph edges. Save the mapping from GUID
440  // to the new global value id to use when writing those edges, which
441  // are currently saved in the index in terms of GUID.
442  forEachSummary([&](GVInfo I, bool) {
443  GUIDToValueIdMap[I.first] = ++GlobalValueId;
444  });
445  }
446 
447  /// The below iterator returns the GUID and associated summary.
448  using GVInfo = std::pair<GlobalValue::GUID, GlobalValueSummary *>;
449 
450  /// Calls the callback for each value GUID and summary to be written to
451  /// bitcode. This hides the details of whether they are being pulled from the
452  /// entire index or just those in a provided ModuleToSummariesForIndex map.
453  template<typename Functor>
454  void forEachSummary(Functor Callback) {
455  if (ModuleToSummariesForIndex) {
456  for (auto &M : *ModuleToSummariesForIndex)
457  for (auto &Summary : M.second) {
458  Callback(Summary, false);
459  // Ensure aliasee is handled, e.g. for assigning a valueId,
460  // even if we are not importing the aliasee directly (the
461  // imported alias will contain a copy of aliasee).
462  if (auto *AS = dyn_cast<AliasSummary>(Summary.getSecond()))
463  Callback({AS->getAliaseeGUID(), &AS->getAliasee()}, true);
464  }
465  } else {
466  for (auto &Summaries : Index)
467  for (auto &Summary : Summaries.second.SummaryList)
468  Callback({Summaries.first, Summary.get()}, false);
469  }
470  }
471 
472  /// Calls the callback for each entry in the modulePaths StringMap that
473  /// should be written to the module path string table. This hides the details
474  /// of whether they are being pulled from the entire index or just those in a
475  /// provided ModuleToSummariesForIndex map.
476  template <typename Functor> void forEachModule(Functor Callback) {
477  if (ModuleToSummariesForIndex) {
478  for (const auto &M : *ModuleToSummariesForIndex) {
479  const auto &MPI = Index.modulePaths().find(M.first);
480  if (MPI == Index.modulePaths().end()) {
481  // This should only happen if the bitcode file was empty, in which
482  // case we shouldn't be importing (the ModuleToSummariesForIndex
483  // would only include the module we are writing and index for).
484  assert(ModuleToSummariesForIndex->size() == 1);
485  continue;
486  }
487  Callback(*MPI);
488  }
489  } else {
490  for (const auto &MPSE : Index.modulePaths())
491  Callback(MPSE);
492  }
493  }
494 
495  /// Main entry point for writing a combined index to bitcode.
496  void write();
497 
498 private:
499  void writeModStrings();
500  void writeCombinedGlobalValueSummary();
501 
502  Optional<unsigned> getValueId(GlobalValue::GUID ValGUID) {
503  auto VMI = GUIDToValueIdMap.find(ValGUID);
504  if (VMI == GUIDToValueIdMap.end())
505  return None;
506  return VMI->second;
507  }
508 
509  std::map<GlobalValue::GUID, unsigned> &valueIds() { return GUIDToValueIdMap; }
510 };
511 
512 } // end anonymous namespace
513 
514 static unsigned getEncodedCastOpcode(unsigned Opcode) {
515  switch (Opcode) {
516  default: llvm_unreachable("Unknown cast instruction!");
517  case Instruction::Trunc : return bitc::CAST_TRUNC;
518  case Instruction::ZExt : return bitc::CAST_ZEXT;
519  case Instruction::SExt : return bitc::CAST_SEXT;
520  case Instruction::FPToUI : return bitc::CAST_FPTOUI;
521  case Instruction::FPToSI : return bitc::CAST_FPTOSI;
522  case Instruction::UIToFP : return bitc::CAST_UITOFP;
523  case Instruction::SIToFP : return bitc::CAST_SITOFP;
524  case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
525  case Instruction::FPExt : return bitc::CAST_FPEXT;
526  case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
527  case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
528  case Instruction::BitCast : return bitc::CAST_BITCAST;
529  case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
530  }
531 }
532 
533 static unsigned getEncodedUnaryOpcode(unsigned Opcode) {
534  switch (Opcode) {
535  default: llvm_unreachable("Unknown binary instruction!");
536  case Instruction::FNeg: return bitc::UNOP_FNEG;
537  }
538 }
539 
540 static unsigned getEncodedBinaryOpcode(unsigned Opcode) {
541  switch (Opcode) {
542  default: llvm_unreachable("Unknown binary instruction!");
543  case Instruction::Add:
544  case Instruction::FAdd: return bitc::BINOP_ADD;
545  case Instruction::Sub:
546  case Instruction::FSub: return bitc::BINOP_SUB;
547  case Instruction::Mul:
548  case Instruction::FMul: return bitc::BINOP_MUL;
549  case Instruction::UDiv: return bitc::BINOP_UDIV;
550  case Instruction::FDiv:
551  case Instruction::SDiv: return bitc::BINOP_SDIV;
552  case Instruction::URem: return bitc::BINOP_UREM;
553  case Instruction::FRem:
554  case Instruction::SRem: return bitc::BINOP_SREM;
555  case Instruction::Shl: return bitc::BINOP_SHL;
556  case Instruction::LShr: return bitc::BINOP_LSHR;
557  case Instruction::AShr: return bitc::BINOP_ASHR;
558  case Instruction::And: return bitc::BINOP_AND;
559  case Instruction::Or: return bitc::BINOP_OR;
560  case Instruction::Xor: return bitc::BINOP_XOR;
561  }
562 }
563 
565  switch (Op) {
566  default: llvm_unreachable("Unknown RMW operation!");
567  case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
568  case AtomicRMWInst::Add: return bitc::RMW_ADD;
569  case AtomicRMWInst::Sub: return bitc::RMW_SUB;
570  case AtomicRMWInst::And: return bitc::RMW_AND;
571  case AtomicRMWInst::Nand: return bitc::RMW_NAND;
572  case AtomicRMWInst::Or: return bitc::RMW_OR;
573  case AtomicRMWInst::Xor: return bitc::RMW_XOR;
574  case AtomicRMWInst::Max: return bitc::RMW_MAX;
575  case AtomicRMWInst::Min: return bitc::RMW_MIN;
576  case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
577  case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
578  case AtomicRMWInst::FAdd: return bitc::RMW_FADD;
579  case AtomicRMWInst::FSub: return bitc::RMW_FSUB;
580  case AtomicRMWInst::FMax: return bitc::RMW_FMAX;
581  case AtomicRMWInst::FMin: return bitc::RMW_FMIN;
582  }
583 }
584 
585 static unsigned getEncodedOrdering(AtomicOrdering Ordering) {
586  switch (Ordering) {
594  }
595  llvm_unreachable("Invalid ordering");
596 }
597 
598 static void writeStringRecord(BitstreamWriter &Stream, unsigned Code,
599  StringRef Str, unsigned AbbrevToUse) {
601 
602  // Code: [strchar x N]
603  for (char C : Str) {
604  if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(C))
605  AbbrevToUse = 0;
606  Vals.push_back(C);
607  }
608 
609  // Emit the finished record.
610  Stream.EmitRecord(Code, Vals, AbbrevToUse);
611 }
612 
614  switch (Kind) {
615  case Attribute::Alignment:
617  case Attribute::AllocAlign:
619  case Attribute::AllocSize:
621  case Attribute::AlwaysInline:
623  case Attribute::ArgMemOnly:
625  case Attribute::Builtin:
627  case Attribute::ByVal:
628  return bitc::ATTR_KIND_BY_VAL;
631  case Attribute::InAlloca:
633  case Attribute::Cold:
634  return bitc::ATTR_KIND_COLD;
635  case Attribute::DisableSanitizerInstrumentation:
637  case Attribute::FnRetThunkExtern:
639  case Attribute::Hot:
640  return bitc::ATTR_KIND_HOT;
641  case Attribute::ElementType:
643  case Attribute::InaccessibleMemOnly:
645  case Attribute::InaccessibleMemOrArgMemOnly:
647  case Attribute::InlineHint:
649  case Attribute::InReg:
650  return bitc::ATTR_KIND_IN_REG;
653  case Attribute::MinSize:
655  case Attribute::AllocatedPointer:
657  case Attribute::AllocKind:
659  case Attribute::Naked:
660  return bitc::ATTR_KIND_NAKED;
661  case Attribute::Nest:
662  return bitc::ATTR_KIND_NEST;
663  case Attribute::NoAlias:
665  case Attribute::NoBuiltin:
667  case Attribute::NoCallback:
669  case Attribute::NoCapture:
671  case Attribute::NoDuplicate:
673  case Attribute::NoFree:
674  return bitc::ATTR_KIND_NOFREE;
675  case Attribute::NoImplicitFloat:
677  case Attribute::NoInline:
679  case Attribute::NoRecurse:
681  case Attribute::NoMerge:
683  case Attribute::NonLazyBind:
685  case Attribute::NonNull:
687  case Attribute::Dereferenceable:
689  case Attribute::DereferenceableOrNull:
691  case Attribute::NoRedZone:
693  case Attribute::NoReturn:
695  case Attribute::NoSync:
696  return bitc::ATTR_KIND_NOSYNC;
697  case Attribute::NoCfCheck:
699  case Attribute::NoProfile:
701  case Attribute::NoUnwind:
703  case Attribute::NoSanitizeBounds:
705  case Attribute::NoSanitizeCoverage:
707  case Attribute::NullPointerIsValid:
709  case Attribute::OptForFuzzing:
711  case Attribute::OptimizeForSize:
713  case Attribute::OptimizeNone:
715  case Attribute::ReadNone:
717  case Attribute::ReadOnly:
719  case Attribute::Returned:
721  case Attribute::ReturnsTwice:
723  case Attribute::SExt:
724  return bitc::ATTR_KIND_S_EXT;
725  case Attribute::Speculatable:
727  case Attribute::StackAlignment:
729  case Attribute::StackProtect:
731  case Attribute::StackProtectReq:
733  case Attribute::StackProtectStrong:
735  case Attribute::SafeStack:
737  case Attribute::ShadowCallStack:
739  case Attribute::StrictFP:
741  case Attribute::StructRet:
743  case Attribute::SanitizeAddress:
745  case Attribute::SanitizeHWAddress:
747  case Attribute::SanitizeThread:
749  case Attribute::SanitizeMemory:
751  case Attribute::SpeculativeLoadHardening:
753  case Attribute::SwiftError:
755  case Attribute::SwiftSelf:
757  case Attribute::SwiftAsync:
759  case Attribute::UWTable:
761  case Attribute::VScaleRange:
763  case Attribute::WillReturn:
765  case Attribute::WriteOnly:
767  case Attribute::ZExt:
768  return bitc::ATTR_KIND_Z_EXT;
769  case Attribute::ImmArg:
770  return bitc::ATTR_KIND_IMMARG;
771  case Attribute::SanitizeMemTag:
773  case Attribute::Preallocated:
775  case Attribute::NoUndef:
777  case Attribute::ByRef:
778  return bitc::ATTR_KIND_BYREF;
779  case Attribute::MustProgress:
781  case Attribute::PresplitCoroutine:
784  llvm_unreachable("Can not encode end-attribute kinds marker.");
785  case Attribute::None:
786  llvm_unreachable("Can not encode none-attribute.");
787  case Attribute::EmptyKey:
789  llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
790  }
791 
792  llvm_unreachable("Trying to encode unknown attribute");
793 }
794 
795 void ModuleBitcodeWriter::writeAttributeGroupTable() {
796  const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
797  VE.getAttributeGroups();
798  if (AttrGrps.empty()) return;
799 
800  Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
801 
803  for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
804  unsigned AttrListIndex = Pair.first;
805  AttributeSet AS = Pair.second;
806  Record.push_back(VE.getAttributeGroupID(Pair));
807  Record.push_back(AttrListIndex);
808 
809  for (Attribute Attr : AS) {
810  if (Attr.isEnumAttribute()) {
811  Record.push_back(0);
812  Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
813  } else if (Attr.isIntAttribute()) {
814  Record.push_back(1);
815  Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
816  Record.push_back(Attr.getValueAsInt());
817  } else if (Attr.isStringAttribute()) {
818  StringRef Kind = Attr.getKindAsString();
819  StringRef Val = Attr.getValueAsString();
820 
821  Record.push_back(Val.empty() ? 3 : 4);
822  Record.append(Kind.begin(), Kind.end());
823  Record.push_back(0);
824  if (!Val.empty()) {
825  Record.append(Val.begin(), Val.end());
826  Record.push_back(0);
827  }
828  } else {
829  assert(Attr.isTypeAttribute());
830  Type *Ty = Attr.getValueAsType();
831  Record.push_back(Ty ? 6 : 5);
832  Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
833  if (Ty)
834  Record.push_back(VE.getTypeID(Attr.getValueAsType()));
835  }
836  }
837 
839  Record.clear();
840  }
841 
842  Stream.ExitBlock();
843 }
844 
845 void ModuleBitcodeWriter::writeAttributeTable() {
846  const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
847  if (Attrs.empty()) return;
848 
849  Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
850 
852  for (const AttributeList &AL : Attrs) {
853  for (unsigned i : AL.indexes()) {
854  AttributeSet AS = AL.getAttributes(i);
855  if (AS.hasAttributes())
856  Record.push_back(VE.getAttributeGroupID({i, AS}));
857  }
858 
860  Record.clear();
861  }
862 
863  Stream.ExitBlock();
864 }
865 
866 /// WriteTypeTable - Write out the type table for a module.
867 void ModuleBitcodeWriter::writeTypeTable() {
868  const ValueEnumerator::TypeList &TypeList = VE.getTypes();
869 
870  Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
871  SmallVector<uint64_t, 64> TypeVals;
872 
874 
875  // Abbrev for TYPE_CODE_POINTER.
876  auto Abbv = std::make_shared<BitCodeAbbrev>();
878  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
879  Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
880  unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
881 
882  // Abbrev for TYPE_CODE_OPAQUE_POINTER.
883  Abbv = std::make_shared<BitCodeAbbrev>();
885  Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
886  unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
887 
888  // Abbrev for TYPE_CODE_FUNCTION.
889  Abbv = std::make_shared<BitCodeAbbrev>();
891  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
893  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
894  unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
895 
896  // Abbrev for TYPE_CODE_STRUCT_ANON.
897  Abbv = std::make_shared<BitCodeAbbrev>();
899  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
901  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
902  unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
903 
904  // Abbrev for TYPE_CODE_STRUCT_NAME.
905  Abbv = std::make_shared<BitCodeAbbrev>();
909  unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
910 
911  // Abbrev for TYPE_CODE_STRUCT_NAMED.
912  Abbv = std::make_shared<BitCodeAbbrev>();
914  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
916  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
917  unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
918 
919  // Abbrev for TYPE_CODE_ARRAY.
920  Abbv = std::make_shared<BitCodeAbbrev>();
922  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
923  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
924  unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
925 
926  // Emit an entry count so the reader can reserve space.
927  TypeVals.push_back(TypeList.size());
928  Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
929  TypeVals.clear();
930 
931  // Loop over all of the types, emitting each in turn.
932  for (Type *T : TypeList) {
933  int AbbrevToUse = 0;
934  unsigned Code = 0;
935 
936  switch (T->getTypeID()) {
950  case Type::IntegerTyID:
951  // INTEGER: [width]
953  TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
954  break;
955  case Type::PointerTyID: {
956  PointerType *PTy = cast<PointerType>(T);
957  unsigned AddressSpace = PTy->getAddressSpace();
958  if (PTy->isOpaque()) {
959  // OPAQUE_POINTER: [address space]
961  TypeVals.push_back(AddressSpace);
962  if (AddressSpace == 0)
963  AbbrevToUse = OpaquePtrAbbrev;
964  } else {
965  // POINTER: [pointee type, address space]
967  TypeVals.push_back(VE.getTypeID(PTy->getNonOpaquePointerElementType()));
968  TypeVals.push_back(AddressSpace);
969  if (AddressSpace == 0)
970  AbbrevToUse = PtrAbbrev;
971  }
972  break;
973  }
974  case Type::FunctionTyID: {
975  FunctionType *FT = cast<FunctionType>(T);
976  // FUNCTION: [isvararg, retty, paramty x N]
978  TypeVals.push_back(FT->isVarArg());
979  TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
980  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
981  TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
982  AbbrevToUse = FunctionAbbrev;
983  break;
984  }
985  case Type::StructTyID: {
986  StructType *ST = cast<StructType>(T);
987  // STRUCT: [ispacked, eltty x N]
988  TypeVals.push_back(ST->isPacked());
989  // Output all of the element types.
990  for (Type *ET : ST->elements())
991  TypeVals.push_back(VE.getTypeID(ET));
992 
993  if (ST->isLiteral()) {
995  AbbrevToUse = StructAnonAbbrev;
996  } else {
997  if (ST->isOpaque()) {
999  } else {
1001  AbbrevToUse = StructNamedAbbrev;
1002  }
1003 
1004  // Emit the name if it is present.
1005  if (!ST->getName().empty())
1006  writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
1007  StructNameAbbrev);
1008  }
1009  break;
1010  }
1011  case Type::ArrayTyID: {
1012  ArrayType *AT = cast<ArrayType>(T);
1013  // ARRAY: [numelts, eltty]
1015  TypeVals.push_back(AT->getNumElements());
1016  TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1017  AbbrevToUse = ArrayAbbrev;
1018  break;
1019  }
1020  case Type::FixedVectorTyID:
1021  case Type::ScalableVectorTyID: {
1022  VectorType *VT = cast<VectorType>(T);
1023  // VECTOR [numelts, eltty] or
1024  // [numelts, eltty, scalable]
1026  TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1027  TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1028  if (isa<ScalableVectorType>(VT))
1029  TypeVals.push_back(true);
1030  break;
1031  }
1032  case Type::DXILPointerTyID:
1033  llvm_unreachable("DXIL pointers cannot be added to IR modules");
1034  }
1035 
1036  // Emit the finished record.
1037  Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1038  TypeVals.clear();
1039  }
1040 
1041  Stream.ExitBlock();
1042 }
1043 
1044 static unsigned getEncodedLinkage(const GlobalValue::LinkageTypes Linkage) {
1045  switch (Linkage) {
1047  return 0;
1049  return 16;
1051  return 2;
1053  return 3;
1055  return 18;
1057  return 7;
1059  return 8;
1061  return 9;
1063  return 17;
1065  return 19;
1067  return 12;
1068  }
1069  llvm_unreachable("Invalid linkage");
1070 }
1071 
1072 static unsigned getEncodedLinkage(const GlobalValue &GV) {
1073  return getEncodedLinkage(GV.getLinkage());
1074 }
1075 
1077  uint64_t RawFlags = 0;
1078  RawFlags |= Flags.ReadNone;
1079  RawFlags |= (Flags.ReadOnly << 1);
1080  RawFlags |= (Flags.NoRecurse << 2);
1081  RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1082  RawFlags |= (Flags.NoInline << 4);
1083  RawFlags |= (Flags.AlwaysInline << 5);
1084  RawFlags |= (Flags.NoUnwind << 6);
1085  RawFlags |= (Flags.MayThrow << 7);
1086  RawFlags |= (Flags.HasUnknownCall << 8);
1087  RawFlags |= (Flags.MustBeUnreachable << 9);
1088  return RawFlags;
1089 }
1090 
1091 // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1092 // in BitcodeReader.cpp.
1094  uint64_t RawFlags = 0;
1095 
1096  RawFlags |= Flags.NotEligibleToImport; // bool
1097  RawFlags |= (Flags.Live << 1);
1098  RawFlags |= (Flags.DSOLocal << 2);
1099  RawFlags |= (Flags.CanAutoHide << 3);
1100 
1101  // Linkage don't need to be remapped at that time for the summary. Any future
1102  // change to the getEncodedLinkage() function will need to be taken into
1103  // account here as well.
1104  RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1105 
1106  RawFlags |= (Flags.Visibility << 8); // 2 bits
1107 
1108  return RawFlags;
1109 }
1110 
1112  uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1113  (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1114  return RawFlags;
1115 }
1116 
1117 static unsigned getEncodedVisibility(const GlobalValue &GV) {
1118  switch (GV.getVisibility()) {
1119  case GlobalValue::DefaultVisibility: return 0;
1120  case GlobalValue::HiddenVisibility: return 1;
1121  case GlobalValue::ProtectedVisibility: return 2;
1122  }
1123  llvm_unreachable("Invalid visibility");
1124 }
1125 
1126 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1127  switch (GV.getDLLStorageClass()) {
1128  case GlobalValue::DefaultStorageClass: return 0;
1129  case GlobalValue::DLLImportStorageClass: return 1;
1130  case GlobalValue::DLLExportStorageClass: return 2;
1131  }
1132  llvm_unreachable("Invalid DLL storage class");
1133 }
1134 
1135 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1136  switch (GV.getThreadLocalMode()) {
1137  case GlobalVariable::NotThreadLocal: return 0;
1139  case GlobalVariable::LocalDynamicTLSModel: return 2;
1140  case GlobalVariable::InitialExecTLSModel: return 3;
1141  case GlobalVariable::LocalExecTLSModel: return 4;
1142  }
1143  llvm_unreachable("Invalid TLS model");
1144 }
1145 
1146 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1147  switch (C.getSelectionKind()) {
1148  case Comdat::Any:
1150  case Comdat::ExactMatch:
1152  case Comdat::Largest:
1154  case Comdat::NoDeduplicate:
1156  case Comdat::SameSize:
1158  }
1159  llvm_unreachable("Invalid selection kind");
1160 }
1161 
1162 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1163  switch (GV.getUnnamedAddr()) {
1164  case GlobalValue::UnnamedAddr::None: return 0;
1165  case GlobalValue::UnnamedAddr::Local: return 2;
1166  case GlobalValue::UnnamedAddr::Global: return 1;
1167  }
1168  llvm_unreachable("Invalid unnamed_addr");
1169 }
1170 
1171 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1172  if (GenerateHash)
1173  Hasher.update(Str);
1174  return StrtabBuilder.add(Str);
1175 }
1176 
1177 void ModuleBitcodeWriter::writeComdats() {
1179  for (const Comdat *C : VE.getComdats()) {
1180  // COMDAT: [strtab offset, strtab size, selection_kind]
1181  Vals.push_back(addToStrtab(C->getName()));
1182  Vals.push_back(C->getName().size());
1183  Vals.push_back(getEncodedComdatSelectionKind(*C));
1184  Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1185  Vals.clear();
1186  }
1187 }
1188 
1189 /// Write a record that will eventually hold the word offset of the
1190 /// module-level VST. For now the offset is 0, which will be backpatched
1191 /// after the real VST is written. Saves the bit offset to backpatch.
1192 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1193  // Write a placeholder value in for the offset of the real VST,
1194  // which is written after the function blocks so that it can include
1195  // the offset of each function. The placeholder offset will be
1196  // updated when the real VST is written.
1197  auto Abbv = std::make_shared<BitCodeAbbrev>();
1199  // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1200  // hold the real VST offset. Must use fixed instead of VBR as we don't
1201  // know how many VBR chunks to reserve ahead of time.
1202  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1203  unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1204 
1205  // Emit the placeholder
1206  uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1207  Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1208 
1209  // Compute and save the bit offset to the placeholder, which will be
1210  // patched when the real VST is written. We can simply subtract the 32-bit
1211  // fixed size from the current bit number to get the location to backpatch.
1212  VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1213 }
1214 
1216 
1217 /// Determine the encoding to use for the given string name and length.
1219  bool isChar6 = true;
1220  for (char C : Str) {
1221  if (isChar6)
1222  isChar6 = BitCodeAbbrevOp::isChar6(C);
1223  if ((unsigned char)C & 128)
1224  // don't bother scanning the rest.
1225  return SE_Fixed8;
1226  }
1227  if (isChar6)
1228  return SE_Char6;
1229  return SE_Fixed7;
1230 }
1231 
1232 static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1233  "Sanitizer Metadata is too large for naive serialization.");
1234 static unsigned
1236  return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1237  (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1238 }
1239 
1240 /// Emit top-level description of module, including target triple, inline asm,
1241 /// descriptors for global variables, and function prototype info.
1242 /// Returns the bit offset to backpatch with the location of the real VST.
1243 void ModuleBitcodeWriter::writeModuleInfo() {
1244  // Emit various pieces of data attached to a module.
1245  if (!M.getTargetTriple().empty())
1246  writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1247  0 /*TODO*/);
1248  const std::string &DL = M.getDataLayoutStr();
1249  if (!DL.empty())
1250  writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1251  if (!M.getModuleInlineAsm().empty())
1252  writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1253  0 /*TODO*/);
1254 
1255  // Emit information about sections and GC, computing how many there are. Also
1256  // compute the maximum alignment value.
1257  std::map<std::string, unsigned> SectionMap;
1258  std::map<std::string, unsigned> GCMap;
1259  MaybeAlign MaxAlignment;
1260  unsigned MaxGlobalType = 0;
1261  const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1262  if (A)
1263  MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1264  };
1265  for (const GlobalVariable &GV : M.globals()) {
1266  UpdateMaxAlignment(GV.getAlign());
1267  MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1268  if (GV.hasSection()) {
1269  // Give section names unique ID's.
1270  unsigned &Entry = SectionMap[std::string(GV.getSection())];
1271  if (!Entry) {
1272  writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1273  0 /*TODO*/);
1274  Entry = SectionMap.size();
1275  }
1276  }
1277  }
1278  for (const Function &F : M) {
1279  UpdateMaxAlignment(F.getAlign());
1280  if (F.hasSection()) {
1281  // Give section names unique ID's.
1282  unsigned &Entry = SectionMap[std::string(F.getSection())];
1283  if (!Entry) {
1284  writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1285  0 /*TODO*/);
1286  Entry = SectionMap.size();
1287  }
1288  }
1289  if (F.hasGC()) {
1290  // Same for GC names.
1291  unsigned &Entry = GCMap[F.getGC()];
1292  if (!Entry) {
1293  writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1294  0 /*TODO*/);
1295  Entry = GCMap.size();
1296  }
1297  }
1298  }
1299 
1300  // Emit abbrev for globals, now that we know # sections and max alignment.
1301  unsigned SimpleGVarAbbrev = 0;
1302  if (!M.global_empty()) {
1303  // Add an abbrev for common globals with no visibility or thread localness.
1304  auto Abbv = std::make_shared<BitCodeAbbrev>();
1306  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1307  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1309  Log2_32_Ceil(MaxGlobalType+1)));
1310  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1311  //| explicitType << 1
1312  //| constant
1313  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1314  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1315  if (!MaxAlignment) // Alignment.
1316  Abbv->Add(BitCodeAbbrevOp(0));
1317  else {
1318  unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1320  Log2_32_Ceil(MaxEncAlignment+1)));
1321  }
1322  if (SectionMap.empty()) // Section.
1323  Abbv->Add(BitCodeAbbrevOp(0));
1324  else
1326  Log2_32_Ceil(SectionMap.size()+1)));
1327  // Don't bother emitting vis + thread local.
1328  SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1329  }
1330 
1332  // Emit the module's source file name.
1333  {
1334  StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1336  if (Bits == SE_Char6)
1337  AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1338  else if (Bits == SE_Fixed7)
1339  AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1340 
1341  // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1342  auto Abbv = std::make_shared<BitCodeAbbrev>();
1345  Abbv->Add(AbbrevOpToUse);
1346  unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1347 
1348  for (const auto P : M.getSourceFileName())
1349  Vals.push_back((unsigned char)P);
1350 
1351  // Emit the finished record.
1352  Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1353  Vals.clear();
1354  }
1355 
1356  // Emit the global variable information.
1357  for (const GlobalVariable &GV : M.globals()) {
1358  unsigned AbbrevToUse = 0;
1359 
1360  // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1361  // linkage, alignment, section, visibility, threadlocal,
1362  // unnamed_addr, externally_initialized, dllstorageclass,
1363  // comdat, attributes, DSO_Local, GlobalSanitizer]
1364  Vals.push_back(addToStrtab(GV.getName()));
1365  Vals.push_back(GV.getName().size());
1366  Vals.push_back(VE.getTypeID(GV.getValueType()));
1367  Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1368  Vals.push_back(GV.isDeclaration() ? 0 :
1369  (VE.getValueID(GV.getInitializer()) + 1));
1370  Vals.push_back(getEncodedLinkage(GV));
1371  Vals.push_back(getEncodedAlign(GV.getAlign()));
1372  Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1373  : 0);
1374  if (GV.isThreadLocal() ||
1375  GV.getVisibility() != GlobalValue::DefaultVisibility ||
1376  GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1377  GV.isExternallyInitialized() ||
1378  GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1379  GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1380  GV.hasPartition() || GV.hasSanitizerMetadata()) {
1381  Vals.push_back(getEncodedVisibility(GV));
1382  Vals.push_back(getEncodedThreadLocalMode(GV));
1383  Vals.push_back(getEncodedUnnamedAddr(GV));
1384  Vals.push_back(GV.isExternallyInitialized());
1385  Vals.push_back(getEncodedDLLStorageClass(GV));
1386  Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1387 
1388  auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1389  Vals.push_back(VE.getAttributeListID(AL));
1390 
1391  Vals.push_back(GV.isDSOLocal());
1392  Vals.push_back(addToStrtab(GV.getPartition()));
1393  Vals.push_back(GV.getPartition().size());
1394 
1395  Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1396  GV.getSanitizerMetadata())
1397  : 0));
1398  } else {
1399  AbbrevToUse = SimpleGVarAbbrev;
1400  }
1401 
1402  Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1403  Vals.clear();
1404  }
1405 
1406  // Emit the function proto information.
1407  for (const Function &F : M) {
1408  // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1409  // linkage, paramattrs, alignment, section, visibility, gc,
1410  // unnamed_addr, prologuedata, dllstorageclass, comdat,
1411  // prefixdata, personalityfn, DSO_Local, addrspace]
1412  Vals.push_back(addToStrtab(F.getName()));
1413  Vals.push_back(F.getName().size());
1414  Vals.push_back(VE.getTypeID(F.getFunctionType()));
1415  Vals.push_back(F.getCallingConv());
1416  Vals.push_back(F.isDeclaration());
1417  Vals.push_back(getEncodedLinkage(F));
1418  Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1419  Vals.push_back(getEncodedAlign(F.getAlign()));
1420  Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1421  : 0);
1422  Vals.push_back(getEncodedVisibility(F));
1423  Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1424  Vals.push_back(getEncodedUnnamedAddr(F));
1425  Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1426  : 0);
1427  Vals.push_back(getEncodedDLLStorageClass(F));
1428  Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1429  Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1430  : 0);
1431  Vals.push_back(
1432  F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1433 
1434  Vals.push_back(F.isDSOLocal());
1435  Vals.push_back(F.getAddressSpace());
1436  Vals.push_back(addToStrtab(F.getPartition()));
1437  Vals.push_back(F.getPartition().size());
1438 
1439  unsigned AbbrevToUse = 0;
1440  Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1441  Vals.clear();
1442  }
1443 
1444  // Emit the alias information.
1445  for (const GlobalAlias &A : M.aliases()) {
1446  // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1447  // visibility, dllstorageclass, threadlocal, unnamed_addr,
1448  // DSO_Local]
1449  Vals.push_back(addToStrtab(A.getName()));
1450  Vals.push_back(A.getName().size());
1451  Vals.push_back(VE.getTypeID(A.getValueType()));
1452  Vals.push_back(A.getType()->getAddressSpace());
1453  Vals.push_back(VE.getValueID(A.getAliasee()));
1454  Vals.push_back(getEncodedLinkage(A));
1455  Vals.push_back(getEncodedVisibility(A));
1456  Vals.push_back(getEncodedDLLStorageClass(A));
1457  Vals.push_back(getEncodedThreadLocalMode(A));
1458  Vals.push_back(getEncodedUnnamedAddr(A));
1459  Vals.push_back(A.isDSOLocal());
1460  Vals.push_back(addToStrtab(A.getPartition()));
1461  Vals.push_back(A.getPartition().size());
1462 
1463  unsigned AbbrevToUse = 0;
1464  Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1465  Vals.clear();
1466  }
1467 
1468  // Emit the ifunc information.
1469  for (const GlobalIFunc &I : M.ifuncs()) {
1470  // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1471  // val#, linkage, visibility, DSO_Local]
1472  Vals.push_back(addToStrtab(I.getName()));
1473  Vals.push_back(I.getName().size());
1474  Vals.push_back(VE.getTypeID(I.getValueType()));
1475  Vals.push_back(I.getType()->getAddressSpace());
1476  Vals.push_back(VE.getValueID(I.getResolver()));
1477  Vals.push_back(getEncodedLinkage(I));
1478  Vals.push_back(getEncodedVisibility(I));
1479  Vals.push_back(I.isDSOLocal());
1480  Vals.push_back(addToStrtab(I.getPartition()));
1481  Vals.push_back(I.getPartition().size());
1482  Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1483  Vals.clear();
1484  }
1485 
1486  writeValueSymbolTableForwardDecl();
1487 }
1488 
1490  uint64_t Flags = 0;
1491 
1492  if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1493  if (OBO->hasNoSignedWrap())
1494  Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1495  if (OBO->hasNoUnsignedWrap())
1496  Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1497  } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1498  if (PEO->isExact())
1499  Flags |= 1 << bitc::PEO_EXACT;
1500  } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1501  if (FPMO->hasAllowReassoc())
1502  Flags |= bitc::AllowReassoc;
1503  if (FPMO->hasNoNaNs())
1504  Flags |= bitc::NoNaNs;
1505  if (FPMO->hasNoInfs())
1506  Flags |= bitc::NoInfs;
1507  if (FPMO->hasNoSignedZeros())
1508  Flags |= bitc::NoSignedZeros;
1509  if (FPMO->hasAllowReciprocal())
1510  Flags |= bitc::AllowReciprocal;
1511  if (FPMO->hasAllowContract())
1512  Flags |= bitc::AllowContract;
1513  if (FPMO->hasApproxFunc())
1514  Flags |= bitc::ApproxFunc;
1515  }
1516 
1517  return Flags;
1518 }
1519 
1520 void ModuleBitcodeWriter::writeValueAsMetadata(
1522  // Mimic an MDNode with a value as one operand.
1523  Value *V = MD->getValue();
1524  Record.push_back(VE.getTypeID(V->getType()));
1525  Record.push_back(VE.getValueID(V));
1526  Stream.EmitRecord(bitc::METADATA_VALUE, Record, 0);
1527  Record.clear();
1528 }
1529 
1532  unsigned Abbrev) {
1533  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1534  Metadata *MD = N->getOperand(i);
1535  assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1536  "Unexpected function-local metadata");
1537  Record.push_back(VE.getMetadataOrNullID(MD));
1538  }
1539  Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1541  Record, Abbrev);
1542  Record.clear();
1543 }
1544 
1545 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1546  // Assume the column is usually under 128, and always output the inlined-at
1547  // location (it's never more expensive than building an array size 1).
1548  auto Abbv = std::make_shared<BitCodeAbbrev>();
1550  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1551  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1552  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1553  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1554  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1555  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1556  return Stream.EmitAbbrev(std::move(Abbv));
1557 }
1558 
1561  unsigned &Abbrev) {
1562  if (!Abbrev)
1563  Abbrev = createDILocationAbbrev();
1564 
1565  Record.push_back(N->isDistinct());
1566  Record.push_back(N->getLine());
1567  Record.push_back(N->getColumn());
1568  Record.push_back(VE.getMetadataID(N->getScope()));
1569  Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1570  Record.push_back(N->isImplicitCode());
1571 
1572  Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1573  Record.clear();
1574 }
1575 
1576 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1577  // Assume the column is usually under 128, and always output the inlined-at
1578  // location (it's never more expensive than building an array size 1).
1579  auto Abbv = std::make_shared<BitCodeAbbrev>();
1581  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1582  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1583  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1584  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1586  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1587  return Stream.EmitAbbrev(std::move(Abbv));
1588 }
1589 
1592  unsigned &Abbrev) {
1593  if (!Abbrev)
1594  Abbrev = createGenericDINodeAbbrev();
1595 
1596  Record.push_back(N->isDistinct());
1597  Record.push_back(N->getTag());
1598  Record.push_back(0); // Per-tag version field; unused for now.
1599 
1600  for (auto &I : N->operands())
1601  Record.push_back(VE.getMetadataOrNullID(I));
1602 
1603  Stream.EmitRecord(bitc::METADATA_GENERIC_DEBUG, Record, Abbrev);
1604  Record.clear();
1605 }
1606 
1609  unsigned Abbrev) {
1610  const uint64_t Version = 2 << 1;
1611  Record.push_back((uint64_t)N->isDistinct() | Version);
1612  Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1613  Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1614  Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1615  Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1616 
1617  Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1618  Record.clear();
1619 }
1620 
1623  unsigned Abbrev) {
1624  Record.push_back((uint64_t)N->isDistinct());
1625  Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1626  Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1627  Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1628  Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1629 
1630  Stream.EmitRecord(bitc::METADATA_GENERIC_SUBRANGE, Record, Abbrev);
1631  Record.clear();
1632 }
1633 
1635  if ((int64_t)V >= 0)
1636  Vals.push_back(V << 1);
1637  else
1638  Vals.push_back((-V << 1) | 1);
1639 }
1640 
1641 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
1642  // We have an arbitrary precision integer value to write whose
1643  // bit width is > 64. However, in canonical unsigned integer
1644  // format it is likely that the high bits are going to be zero.
1645  // So, we only write the number of active words.
1646  unsigned NumWords = A.getActiveWords();
1647  const uint64_t *RawData = A.getRawData();
1648  for (unsigned i = 0; i < NumWords; i++)
1649  emitSignedInt64(Vals, RawData[i]);
1650 }
1651 
1654  unsigned Abbrev) {
1655  const uint64_t IsBigInt = 1 << 2;
1656  Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1657  Record.push_back(N->getValue().getBitWidth());
1658  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1659  emitWideAPInt(Record, N->getValue());
1660 
1661  Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1662  Record.clear();
1663 }
1664 
1667  unsigned Abbrev) {
1668  Record.push_back(N->isDistinct());
1669  Record.push_back(N->getTag());
1670  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1671  Record.push_back(N->getSizeInBits());
1672  Record.push_back(N->getAlignInBits());
1673  Record.push_back(N->getEncoding());
1674  Record.push_back(N->getFlags());
1675 
1676  Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1677  Record.clear();
1678 }
1679 
1682  unsigned Abbrev) {
1683  Record.push_back(N->isDistinct());
1684  Record.push_back(N->getTag());
1685  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1686  Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1687  Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1688  Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1689  Record.push_back(N->getSizeInBits());
1690  Record.push_back(N->getAlignInBits());
1691  Record.push_back(N->getEncoding());
1692 
1693  Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1694  Record.clear();
1695 }
1696 
1699  unsigned Abbrev) {
1700  Record.push_back(N->isDistinct());
1701  Record.push_back(N->getTag());
1702  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1703  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1704  Record.push_back(N->getLine());
1705  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1706  Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1707  Record.push_back(N->getSizeInBits());
1708  Record.push_back(N->getAlignInBits());
1709  Record.push_back(N->getOffsetInBits());
1710  Record.push_back(N->getFlags());
1711  Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1712 
1713  // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1714  // that there is no DWARF address space associated with DIDerivedType.
1715  if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1716  Record.push_back(*DWARFAddressSpace + 1);
1717  else
1718  Record.push_back(0);
1719 
1720  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1721 
1722  Stream.EmitRecord(bitc::METADATA_DERIVED_TYPE, Record, Abbrev);
1723  Record.clear();
1724 }
1725 
1728  unsigned Abbrev) {
1729  const unsigned IsNotUsedInOldTypeRef = 0x2;
1730  Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1731  Record.push_back(N->getTag());
1732  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1733  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1734  Record.push_back(N->getLine());
1735  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1736  Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1737  Record.push_back(N->getSizeInBits());
1738  Record.push_back(N->getAlignInBits());
1739  Record.push_back(N->getOffsetInBits());
1740  Record.push_back(N->getFlags());
1741  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1742  Record.push_back(N->getRuntimeLang());
1743  Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1744  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1745  Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1746  Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1747  Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1748  Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1749  Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1750  Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1751  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1752 
1753  Stream.EmitRecord(bitc::METADATA_COMPOSITE_TYPE, Record, Abbrev);
1754  Record.clear();
1755 }
1756 
1759  unsigned Abbrev) {
1760  const unsigned HasNoOldTypeRefs = 0x2;
1761  Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1762  Record.push_back(N->getFlags());
1763  Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1764  Record.push_back(N->getCC());
1765 
1766  Stream.EmitRecord(bitc::METADATA_SUBROUTINE_TYPE, Record, Abbrev);
1767  Record.clear();
1768 }
1769 
1772  unsigned Abbrev) {
1773  Record.push_back(N->isDistinct());
1774  Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1775  Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1776  if (N->getRawChecksum()) {
1777  Record.push_back(N->getRawChecksum()->Kind);
1778  Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1779  } else {
1780  // Maintain backwards compatibility with the old internal representation of
1781  // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1782  Record.push_back(0);
1783  Record.push_back(VE.getMetadataOrNullID(nullptr));
1784  }
1785  auto Source = N->getRawSource();
1786  if (Source)
1787  Record.push_back(VE.getMetadataOrNullID(*Source));
1788 
1789  Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1790  Record.clear();
1791 }
1792 
1795  unsigned Abbrev) {
1796  assert(N->isDistinct() && "Expected distinct compile units");
1797  Record.push_back(/* IsDistinct */ true);
1798  Record.push_back(N->getSourceLanguage());
1799  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1800  Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1801  Record.push_back(N->isOptimized());
1802  Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1803  Record.push_back(N->getRuntimeVersion());
1804  Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1805  Record.push_back(N->getEmissionKind());
1806  Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1807  Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1808  Record.push_back(/* subprograms */ 0);
1809  Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1810  Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1811  Record.push_back(N->getDWOId());
1812  Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1813  Record.push_back(N->getSplitDebugInlining());
1814  Record.push_back(N->getDebugInfoForProfiling());
1815  Record.push_back((unsigned)N->getNameTableKind());
1816  Record.push_back(N->getRangesBaseAddress());
1817  Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
1818  Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
1819 
1820  Stream.EmitRecord(bitc::METADATA_COMPILE_UNIT, Record, Abbrev);
1821  Record.clear();
1822 }
1823 
1826  unsigned Abbrev) {
1827  const uint64_t HasUnitFlag = 1 << 1;
1828  const uint64_t HasSPFlagsFlag = 1 << 2;
1829  Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1830  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1831  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1832  Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1833  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1834  Record.push_back(N->getLine());
1835  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1836  Record.push_back(N->getScopeLine());
1837  Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1838  Record.push_back(N->getSPFlags());
1839  Record.push_back(N->getVirtualIndex());
1840  Record.push_back(N->getFlags());
1841  Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1842  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1843  Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1844  Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1845  Record.push_back(N->getThisAdjustment());
1846  Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1847  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1848  Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
1849 
1850  Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1851  Record.clear();
1852 }
1853 
1856  unsigned Abbrev) {
1857  Record.push_back(N->isDistinct());
1858  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1859  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1860  Record.push_back(N->getLine());
1861  Record.push_back(N->getColumn());
1862 
1863  Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK, Record, Abbrev);
1864  Record.clear();
1865 }
1866 
1869  unsigned Abbrev) {
1870  Record.push_back(N->isDistinct());
1871  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1872  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1873  Record.push_back(N->getDiscriminator());
1874 
1875  Stream.EmitRecord(bitc::METADATA_LEXICAL_BLOCK_FILE, Record, Abbrev);
1876  Record.clear();
1877 }
1878 
1881  unsigned Abbrev) {
1882  Record.push_back(N->isDistinct());
1883  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1884  Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
1885  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1886  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1887  Record.push_back(N->getLineNo());
1888 
1889  Stream.EmitRecord(bitc::METADATA_COMMON_BLOCK, Record, Abbrev);
1890  Record.clear();
1891 }
1892 
1895  unsigned Abbrev) {
1896  Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1897  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1898  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1899 
1900  Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1901  Record.clear();
1902 }
1903 
1906  unsigned Abbrev) {
1907  Record.push_back(N->isDistinct());
1908  Record.push_back(N->getMacinfoType());
1909  Record.push_back(N->getLine());
1910  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1911  Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1912 
1913  Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1914  Record.clear();
1915 }
1916 
1919  unsigned Abbrev) {
1920  Record.push_back(N->isDistinct());
1921  Record.push_back(N->getMacinfoType());
1922  Record.push_back(N->getLine());
1923  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1924  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1925 
1926  Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1927  Record.clear();
1928 }
1929 
1932  unsigned Abbrev) {
1933  Record.reserve(N->getArgs().size());
1934  for (ValueAsMetadata *MD : N->getArgs())
1935  Record.push_back(VE.getMetadataID(MD));
1936 
1937  Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record, Abbrev);
1938  Record.clear();
1939 }
1940 
1943  unsigned Abbrev) {
1944  Record.push_back(N->isDistinct());
1945  for (auto &I : N->operands())
1946  Record.push_back(VE.getMetadataOrNullID(I));
1947  Record.push_back(N->getLineNo());
1948  Record.push_back(N->getIsDecl());
1949 
1950  Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1951  Record.clear();
1952 }
1953 
1956  unsigned Abbrev) {
1957  Record.push_back(N->isDistinct());
1958  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1959  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1960  Record.push_back(N->isDefault());
1961 
1962  Stream.EmitRecord(bitc::METADATA_TEMPLATE_TYPE, Record, Abbrev);
1963  Record.clear();
1964 }
1965 
1968  unsigned Abbrev) {
1969  Record.push_back(N->isDistinct());
1970  Record.push_back(N->getTag());
1971  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1972  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1973  Record.push_back(N->isDefault());
1974  Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1975 
1976  Stream.EmitRecord(bitc::METADATA_TEMPLATE_VALUE, Record, Abbrev);
1977  Record.clear();
1978 }
1979 
1982  unsigned Abbrev) {
1983  const uint64_t Version = 2 << 1;
1984  Record.push_back((uint64_t)N->isDistinct() | Version);
1985  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1986  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1987  Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1988  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1989  Record.push_back(N->getLine());
1990  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1991  Record.push_back(N->isLocalToUnit());
1992  Record.push_back(N->isDefinition());
1993  Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1994  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
1995  Record.push_back(N->getAlignInBits());
1996  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1997 
1998  Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
1999  Record.clear();
2000 }
2001 
2004  unsigned Abbrev) {
2005  // In order to support all possible bitcode formats in BitcodeReader we need
2006  // to distinguish the following cases:
2007  // 1) Record has no artificial tag (Record[1]),
2008  // has no obsolete inlinedAt field (Record[9]).
2009  // In this case Record size will be 8, HasAlignment flag is false.
2010  // 2) Record has artificial tag (Record[1]),
2011  // has no obsolete inlignedAt field (Record[9]).
2012  // In this case Record size will be 9, HasAlignment flag is false.
2013  // 3) Record has both artificial tag (Record[1]) and
2014  // obsolete inlignedAt field (Record[9]).
2015  // In this case Record size will be 10, HasAlignment flag is false.
2016  // 4) Record has neither artificial tag, nor inlignedAt field, but
2017  // HasAlignment flag is true and Record[8] contains alignment value.
2018  const uint64_t HasAlignmentFlag = 1 << 1;
2019  Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2020  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2021  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2022  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2023  Record.push_back(N->getLine());
2024  Record.push_back(VE.getMetadataOrNullID(N->getType()));
2025  Record.push_back(N->getArg());
2026  Record.push_back(N->getFlags());
2027  Record.push_back(N->getAlignInBits());
2028  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2029 
2030  Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2031  Record.clear();
2032 }
2033 
2036  unsigned Abbrev) {
2037  Record.push_back((uint64_t)N->isDistinct());
2038  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2039  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2040  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2041  Record.push_back(N->getLine());
2042 
2043  Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2044  Record.clear();
2045 }
2046 
2049  unsigned Abbrev) {
2050  Record.reserve(N->getElements().size() + 1);
2051  const uint64_t Version = 3 << 1;
2052  Record.push_back((uint64_t)N->isDistinct() | Version);
2053  Record.append(N->elements_begin(), N->elements_end());
2054 
2055  Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2056  Record.clear();
2057 }
2058 
2061  unsigned Abbrev) {
2062  Record.push_back(N->isDistinct());
2063  Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2064  Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2065 
2066  Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR_EXPR, Record, Abbrev);
2067  Record.clear();
2068 }
2069 
2072  unsigned Abbrev) {
2073  Record.push_back(N->isDistinct());
2074  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2075  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2076  Record.push_back(N->getLine());
2077  Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2078  Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2079  Record.push_back(N->getAttributes());
2080  Record.push_back(VE.getMetadataOrNullID(N->getType()));
2081 
2082  Stream.EmitRecord(bitc::METADATA_OBJC_PROPERTY, Record, Abbrev);
2083  Record.clear();
2084 }
2085 
2088  unsigned Abbrev) {
2089  Record.push_back(N->isDistinct());
2090  Record.push_back(N->getTag());
2091  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2092  Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2093  Record.push_back(N->getLine());
2094  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2095  Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2096  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2097 
2098  Stream.EmitRecord(bitc::METADATA_IMPORTED_ENTITY, Record, Abbrev);
2099  Record.clear();
2100 }
2101 
2102 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2103  auto Abbv = std::make_shared<BitCodeAbbrev>();
2106  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2107  return Stream.EmitAbbrev(std::move(Abbv));
2108 }
2109 
2110 void ModuleBitcodeWriter::writeNamedMetadata(
2112  if (M.named_metadata_empty())
2113  return;
2114 
2115  unsigned Abbrev = createNamedMetadataAbbrev();
2116  for (const NamedMDNode &NMD : M.named_metadata()) {
2117  // Write name.
2118  StringRef Str = NMD.getName();
2119  Record.append(Str.bytes_begin(), Str.bytes_end());
2120  Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2121  Record.clear();
2122 
2123  // Write named metadata operands.
2124  for (const MDNode *N : NMD.operands())
2125  Record.push_back(VE.getMetadataID(N));
2126  Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
2127  Record.clear();
2128  }
2129 }
2130 
2131 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2132  auto Abbv = std::make_shared<BitCodeAbbrev>();
2134  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2135  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2137  return Stream.EmitAbbrev(std::move(Abbv));
2138 }
2139 
2140 /// Write out a record for MDString.
2141 ///
2142 /// All the metadata strings in a metadata block are emitted in a single
2143 /// record. The sizes and strings themselves are shoved into a blob.
2144 void ModuleBitcodeWriter::writeMetadataStrings(
2146  if (Strings.empty())
2147  return;
2148 
2149  // Start the record with the number of strings.
2150  Record.push_back(bitc::METADATA_STRINGS);
2151  Record.push_back(Strings.size());
2152 
2153  // Emit the sizes of the strings in the blob.
2154  SmallString<256> Blob;
2155  {
2156  BitstreamWriter W(Blob);
2157  for (const Metadata *MD : Strings)
2158  W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2159  W.FlushToWord();
2160  }
2161 
2162  // Add the offset to the strings to the record.
2163  Record.push_back(Blob.size());
2164 
2165  // Add the strings to the blob.
2166  for (const Metadata *MD : Strings)
2167  Blob.append(cast<MDString>(MD)->getString());
2168 
2169  // Emit the final record.
2170  Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2171  Record.clear();
2172 }
2173 
2174 // Generates an enum to use as an index in the Abbrev array of Metadata record.
2175 enum MetadataAbbrev : unsigned {
2176 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2177 #include "llvm/IR/Metadata.def"
2179 };
2180 
2181 void ModuleBitcodeWriter::writeMetadataRecords(
2183  std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2184  if (MDs.empty())
2185  return;
2186 
2187  // Initialize MDNode abbreviations.
2188 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2189 #include "llvm/IR/Metadata.def"
2190 
2191  for (const Metadata *MD : MDs) {
2192  if (IndexPos)
2193  IndexPos->push_back(Stream.GetCurrentBitNo());
2194  if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2195  assert(N->isResolved() && "Expected forward references to be resolved");
2196 
2197  switch (N->getMetadataID()) {
2198  default:
2199  llvm_unreachable("Invalid MDNode subclass");
2200 #define HANDLE_MDNODE_LEAF(CLASS) \
2201  case Metadata::CLASS##Kind: \
2202  if (MDAbbrevs) \
2203  write##CLASS(cast<CLASS>(N), Record, \
2204  (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2205  else \
2206  write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2207  continue;
2208 #include "llvm/IR/Metadata.def"
2209  }
2210  }
2211  writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2212  }
2213 }
2214 
2215 void ModuleBitcodeWriter::writeModuleMetadata() {
2216  if (!VE.hasMDs() && M.named_metadata_empty())
2217  return;
2218 
2219  Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 4);
2221 
2222  // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2223  // block and load any metadata.
2224  std::vector<unsigned> MDAbbrevs;
2225 
2226  MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2227  MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2228  MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2229  createGenericDINodeAbbrev();
2230 
2231  auto Abbv = std::make_shared<BitCodeAbbrev>();
2233  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2234  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2235  unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2236 
2237  Abbv = std::make_shared<BitCodeAbbrev>();
2240  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2241  unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2242 
2243  // Emit MDStrings together upfront.
2244  writeMetadataStrings(VE.getMDStrings(), Record);
2245 
2246  // We only emit an index for the metadata record if we have more than a given
2247  // (naive) threshold of metadatas, otherwise it is not worth it.
2248  if (VE.getNonMDStrings().size() > IndexThreshold) {
2249  // Write a placeholder value in for the offset of the metadata index,
2250  // which is written after the records, so that it can include
2251  // the offset of each entry. The placeholder offset will be
2252  // updated after all records are emitted.
2253  uint64_t Vals[] = {0, 0};
2254  Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2255  }
2256 
2257  // Compute and save the bit offset to the current position, which will be
2258  // patched when we emit the index later. We can simply subtract the 64-bit
2259  // fixed size from the current bit number to get the location to backpatch.
2260  uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2261 
2262  // This index will contain the bitpos for each individual record.
2263  std::vector<uint64_t> IndexPos;
2264  IndexPos.reserve(VE.getNonMDStrings().size());
2265 
2266  // Write all the records
2267  writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2268 
2269  if (VE.getNonMDStrings().size() > IndexThreshold) {
2270  // Now that we have emitted all the records we will emit the index. But
2271  // first
2272  // backpatch the forward reference so that the reader can skip the records
2273  // efficiently.
2274  Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2275  Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2276 
2277  // Delta encode the index.
2278  uint64_t PreviousValue = IndexOffsetRecordBitPos;
2279  for (auto &Elt : IndexPos) {
2280  auto EltDelta = Elt - PreviousValue;
2281  PreviousValue = Elt;
2282  Elt = EltDelta;
2283  }
2284  // Emit the index record.
2285  Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2286  IndexPos.clear();
2287  }
2288 
2289  // Write the named metadata now.
2290  writeNamedMetadata(Record);
2291 
2292  auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2294  Record.push_back(VE.getValueID(&GO));
2295  pushGlobalMetadataAttachment(Record, GO);
2297  };
2298  for (const Function &F : M)
2299  if (F.isDeclaration() && F.hasMetadata())
2300  AddDeclAttachedMetadata(F);
2301  // FIXME: Only store metadata for declarations here, and move data for global
2302  // variable definitions to a separate block (PR28134).
2303  for (const GlobalVariable &GV : M.globals())
2304  if (GV.hasMetadata())
2305  AddDeclAttachedMetadata(GV);
2306 
2307  Stream.ExitBlock();
2308 }
2309 
2310 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2311  if (!VE.hasMDs())
2312  return;
2313 
2314  Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
2316  writeMetadataStrings(VE.getMDStrings(), Record);
2317  writeMetadataRecords(VE.getNonMDStrings(), Record);
2318  Stream.ExitBlock();
2319 }
2320 
2321 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2323  // [n x [id, mdnode]]
2325  GO.getAllMetadata(MDs);
2326  for (const auto &I : MDs) {
2327  Record.push_back(I.first);
2328  Record.push_back(VE.getMetadataID(I.second));
2329  }
2330 }
2331 
2332 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2333  Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
2334 
2336 
2337  if (F.hasMetadata()) {
2338  pushGlobalMetadataAttachment(Record, F);
2339  Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2340  Record.clear();
2341  }
2342 
2343  // Write metadata attachments
2344  // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2346  for (const BasicBlock &BB : F)
2347  for (const Instruction &I : BB) {
2348  MDs.clear();
2349  I.getAllMetadataOtherThanDebugLoc(MDs);
2350 
2351  // If no metadata, ignore instruction.
2352  if (MDs.empty()) continue;
2353 
2354  Record.push_back(VE.getInstructionID(&I));
2355 
2356  for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2357  Record.push_back(MDs[i].first);
2358  Record.push_back(VE.getMetadataID(MDs[i].second));
2359  }
2360  Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
2361  Record.clear();
2362  }
2363 
2364  Stream.ExitBlock();
2365 }
2366 
2367 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2369 
2370  // Write metadata kinds
2371  // METADATA_KIND - [n x [id, name]]
2373  M.getMDKindNames(Names);
2374 
2375  if (Names.empty()) return;
2376 
2377  Stream.EnterSubblock(bitc::METADATA_KIND_BLOCK_ID, 3);
2378 
2379  for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2380  Record.push_back(MDKindID);
2381  StringRef KName = Names[MDKindID];
2382  Record.append(KName.begin(), KName.end());
2383 
2384  Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
2385  Record.clear();
2386  }
2387 
2388  Stream.ExitBlock();
2389 }
2390 
2391 void ModuleBitcodeWriter::writeOperandBundleTags() {
2392  // Write metadata kinds
2393  //
2394  // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2395  //
2396  // OPERAND_BUNDLE_TAG - [strchr x N]
2397 
2399  M.getOperandBundleTags(Tags);
2400 
2401  if (Tags.empty())
2402  return;
2403 
2404  Stream.EnterSubblock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID, 3);
2405 
2407 
2408  for (auto Tag : Tags) {
2409  Record.append(Tag.begin(), Tag.end());
2410 
2411  Stream.EmitRecord(bitc::OPERAND_BUNDLE_TAG, Record, 0);
2412  Record.clear();
2413  }
2414 
2415  Stream.ExitBlock();
2416 }
2417 
2418 void ModuleBitcodeWriter::writeSyncScopeNames() {
2420  M.getContext().getSyncScopeNames(SSNs);
2421  if (SSNs.empty())
2422  return;
2423 
2424  Stream.EnterSubblock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID, 2);
2425 
2427  for (auto SSN : SSNs) {
2428  Record.append(SSN.begin(), SSN.end());
2429  Stream.EmitRecord(bitc::SYNC_SCOPE_NAME, Record, 0);
2430  Record.clear();
2431  }
2432 
2433  Stream.ExitBlock();
2434 }
2435 
2436 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2437  bool isGlobal) {
2438  if (FirstVal == LastVal) return;
2439 
2440  Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
2441 
2442  unsigned AggregateAbbrev = 0;
2443  unsigned String8Abbrev = 0;
2444  unsigned CString7Abbrev = 0;
2445  unsigned CString6Abbrev = 0;
2446  // If this is a constant pool for the module, emit module-specific abbrevs.
2447  if (isGlobal) {
2448  // Abbrev for CST_CODE_AGGREGATE.
2449  auto Abbv = std::make_shared<BitCodeAbbrev>();
2452  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2453  AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2454 
2455  // Abbrev for CST_CODE_STRING.
2456  Abbv = std::make_shared<BitCodeAbbrev>();
2459  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2460  String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2461  // Abbrev for CST_CODE_CSTRING.
2462  Abbv = std::make_shared<BitCodeAbbrev>();
2465  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2466  CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2467  // Abbrev for CST_CODE_CSTRING.
2468  Abbv = std::make_shared<BitCodeAbbrev>();
2472  CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2473  }
2474 
2476 
2477  const ValueEnumerator::ValueList &Vals = VE.getValues();
2478  Type *LastTy = nullptr;
2479  for (unsigned i = FirstVal; i != LastVal; ++i) {
2480  const Value *V = Vals[i].first;
2481  // If we need to switch types, do so now.
2482  if (V->getType() != LastTy) {
2483  LastTy = V->getType();
2484  Record.push_back(VE.getTypeID(LastTy));
2485  Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
2486  CONSTANTS_SETTYPE_ABBREV);
2487  Record.clear();
2488  }
2489 
2490  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2491  Record.push_back(VE.getTypeID(IA->getFunctionType()));
2492  Record.push_back(
2493  unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2494  unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2495 
2496  // Add the asm string.
2497  const std::string &AsmStr = IA->getAsmString();
2498  Record.push_back(AsmStr.size());
2499  Record.append(AsmStr.begin(), AsmStr.end());
2500 
2501  // Add the constraint string.
2502  const std::string &ConstraintStr = IA->getConstraintString();
2503  Record.push_back(ConstraintStr.size());
2504  Record.append(ConstraintStr.begin(), ConstraintStr.end());
2505  Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
2506  Record.clear();
2507  continue;
2508  }
2509  const Constant *C = cast<Constant>(V);
2510  unsigned Code = -1U;
2511  unsigned AbbrevToUse = 0;
2512  if (C->isNullValue()) {
2514  } else if (isa<PoisonValue>(C)) {
2516  } else if (isa<UndefValue>(C)) {
2518  } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2519  if (IV->getBitWidth() <= 64) {
2520  uint64_t V = IV->getSExtValue();
2521  emitSignedInt64(Record, V);
2523  AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2524  } else { // Wide integers, > 64 bits in size.
2525  emitWideAPInt(Record, IV->getValue());
2527  }
2528  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2530  Type *Ty = CFP->getType();
2531  if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2532  Ty->isDoubleTy()) {
2533  Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2534  } else if (Ty->isX86_FP80Ty()) {
2535  // api needed to prevent premature destruction
2536  // bits are not in the same order as a normal i80 APInt, compensate.
2537  APInt api = CFP->getValueAPF().bitcastToAPInt();
2538  const uint64_t *p = api.getRawData();
2539  Record.push_back((p[1] << 48) | (p[0] >> 16));
2540  Record.push_back(p[0] & 0xffffLL);
2541  } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2542  APInt api = CFP->getValueAPF().bitcastToAPInt();
2543  const uint64_t *p = api.getRawData();
2544  Record.push_back(p[0]);
2545  Record.push_back(p[1]);
2546  } else {
2547  assert(0 && "Unknown FP type!");
2548  }
2549  } else if (isa<ConstantDataSequential>(C) &&
2550  cast<ConstantDataSequential>(C)->isString()) {
2551  const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2552  // Emit constant strings specially.
2553  unsigned NumElts = Str->getNumElements();
2554  // If this is a null-terminated string, use the denser CSTRING encoding.
2555  if (Str->isCString()) {
2557  --NumElts; // Don't encode the null, which isn't allowed by char6.
2558  } else {
2560  AbbrevToUse = String8Abbrev;
2561  }
2562  bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2563  bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2564  for (unsigned i = 0; i != NumElts; ++i) {
2565  unsigned char V = Str->getElementAsInteger(i);
2566  Record.push_back(V);
2567  isCStr7 &= (V & 128) == 0;
2568  if (isCStrChar6)
2569  isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2570  }
2571 
2572  if (isCStrChar6)
2573  AbbrevToUse = CString6Abbrev;
2574  else if (isCStr7)
2575  AbbrevToUse = CString7Abbrev;
2576  } else if (const ConstantDataSequential *CDS =
2577  dyn_cast<ConstantDataSequential>(C)) {
2579  Type *EltTy = CDS->getElementType();
2580  if (isa<IntegerType>(EltTy)) {
2581  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2582  Record.push_back(CDS->getElementAsInteger(i));
2583  } else {
2584  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2585  Record.push_back(
2586  CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2587  }
2588  } else if (isa<ConstantAggregate>(C)) {
2590  for (const Value *Op : C->operands())
2591  Record.push_back(VE.getValueID(Op));
2592  AbbrevToUse = AggregateAbbrev;
2593  } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2594  switch (CE->getOpcode()) {
2595  default:
2596  if (Instruction::isCast(CE->getOpcode())) {
2598  Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2599  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2600  Record.push_back(VE.getValueID(C->getOperand(0)));
2601  AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2602  } else {
2603  assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2605  Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2606  Record.push_back(VE.getValueID(C->getOperand(0)));
2607  Record.push_back(VE.getValueID(C->getOperand(1)));
2608  uint64_t Flags = getOptimizationFlags(CE);
2609  if (Flags != 0)
2610  Record.push_back(Flags);
2611  }
2612  break;
2613  case Instruction::FNeg: {
2614  assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2616  Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2617  Record.push_back(VE.getValueID(C->getOperand(0)));
2618  uint64_t Flags = getOptimizationFlags(CE);
2619  if (Flags != 0)
2620  Record.push_back(Flags);
2621  break;
2622  }
2623  case Instruction::GetElementPtr: {
2625  const auto *GO = cast<GEPOperator>(C);
2626  Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2627  if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2629  Record.push_back((*Idx << 1) | GO->isInBounds());
2630  } else if (GO->isInBounds())
2632  for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2633  Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2634  Record.push_back(VE.getValueID(C->getOperand(i)));
2635  }
2636  break;
2637  }
2638  case Instruction::Select:
2640  Record.push_back(VE.getValueID(C->getOperand(0)));
2641  Record.push_back(VE.getValueID(C->getOperand(1)));
2642  Record.push_back(VE.getValueID(C->getOperand(2)));
2643  break;
2644  case Instruction::ExtractElement:
2646  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2647  Record.push_back(VE.getValueID(C->getOperand(0)));
2648  Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2649  Record.push_back(VE.getValueID(C->getOperand(1)));
2650  break;
2651  case Instruction::InsertElement:
2653  Record.push_back(VE.getValueID(C->getOperand(0)));
2654  Record.push_back(VE.getValueID(C->getOperand(1)));
2655  Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2656  Record.push_back(VE.getValueID(C->getOperand(2)));
2657  break;
2658  case Instruction::ShuffleVector:
2659  // If the return type and argument types are the same, this is a
2660  // standard shufflevector instruction. If the types are different,
2661  // then the shuffle is widening or truncating the input vectors, and
2662  // the argument type must also be encoded.
2663  if (C->getType() == C->getOperand(0)->getType()) {
2665  } else {
2667  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2668  }
2669  Record.push_back(VE.getValueID(C->getOperand(0)));
2670  Record.push_back(VE.getValueID(C->getOperand(1)));
2671  Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2672  break;
2673  case Instruction::ICmp:
2674  case Instruction::FCmp:
2676  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2677  Record.push_back(VE.getValueID(C->getOperand(0)));
2678  Record.push_back(VE.getValueID(C->getOperand(1)));
2679  Record.push_back(CE->getPredicate());
2680  break;
2681  }
2682  } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2684  Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2685  Record.push_back(VE.getValueID(BA->getFunction()));
2686  Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2687  } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2689  Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2690  Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2691  } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
2693  Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
2694  Record.push_back(VE.getValueID(NC->getGlobalValue()));
2695  } else {
2696 #ifndef NDEBUG
2697  C->dump();
2698 #endif
2699  llvm_unreachable("Unknown constant!");
2700  }
2701  Stream.EmitRecord(Code, Record, AbbrevToUse);
2702  Record.clear();
2703  }
2704 
2705  Stream.ExitBlock();
2706 }
2707 
2708 void ModuleBitcodeWriter::writeModuleConstants() {
2709  const ValueEnumerator::ValueList &Vals = VE.getValues();
2710 
2711  // Find the first constant to emit, which is the first non-globalvalue value.
2712  // We know globalvalues have been emitted by WriteModuleInfo.
2713  for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2714  if (!isa<GlobalValue>(Vals[i].first)) {
2715  writeConstants(i, Vals.size(), true);
2716  return;
2717  }
2718  }
2719 }
2720 
2721 /// pushValueAndType - The file has to encode both the value and type id for
2722 /// many values, because we need to know what type to create for forward
2723 /// references. However, most operands are not forward references, so this type
2724 /// field is not needed.
2725 ///
2726 /// This function adds V's value ID to Vals. If the value ID is higher than the
2727 /// instruction ID, then it is a forward reference, and it also includes the
2728 /// type ID. The value ID that is written is encoded relative to the InstID.
2729 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2730  SmallVectorImpl<unsigned> &Vals) {
2731  unsigned ValID = VE.getValueID(V);
2732  // Make encoding relative to the InstID.
2733  Vals.push_back(InstID - ValID);
2734  if (ValID >= InstID) {
2735  Vals.push_back(VE.getTypeID(V->getType()));
2736  return true;
2737  }
2738  return false;
2739 }
2740 
2741 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2742  unsigned InstID) {
2744  LLVMContext &C = CS.getContext();
2745 
2746  for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2747  const auto &Bundle = CS.getOperandBundleAt(i);
2748  Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2749 
2750  for (auto &Input : Bundle.Inputs)
2751  pushValueAndType(Input, InstID, Record);
2752 
2754  Record.clear();
2755  }
2756 }
2757 
2758 /// pushValue - Like pushValueAndType, but where the type of the value is
2759 /// omitted (perhaps it was already encoded in an earlier operand).
2760 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2761  SmallVectorImpl<unsigned> &Vals) {
2762  unsigned ValID = VE.getValueID(V);
2763  Vals.push_back(InstID - ValID);
2764 }
2765 
2766 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2767  SmallVectorImpl<uint64_t> &Vals) {
2768  unsigned ValID = VE.getValueID(V);
2769  int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2770  emitSignedInt64(Vals, diff);
2771 }
2772 
2773 /// WriteInstruction - Emit an instruction to the specified stream.
2774 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2775  unsigned InstID,
2776  SmallVectorImpl<unsigned> &Vals) {
2777  unsigned Code = 0;
2778  unsigned AbbrevToUse = 0;
2779  VE.setInstructionID(&I);
2780  switch (I.getOpcode()) {
2781  default:
2782  if (Instruction::isCast(I.getOpcode())) {
2784  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2785  AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2786  Vals.push_back(VE.getTypeID(I.getType()));
2787  Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2788  } else {
2789  assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2791  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2792  AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2793  pushValue(I.getOperand(1), InstID, Vals);
2794  Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2795  uint64_t Flags = getOptimizationFlags(&I);
2796  if (Flags != 0) {
2797  if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2798  AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2799  Vals.push_back(Flags);
2800  }
2801  }
2802  break;
2803  case Instruction::FNeg: {
2805  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2806  AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2807  Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2808  uint64_t Flags = getOptimizationFlags(&I);
2809  if (Flags != 0) {
2810  if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2811  AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2812  Vals.push_back(Flags);
2813  }
2814  break;
2815  }
2816  case Instruction::GetElementPtr: {
2818  AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2819  auto &GEPInst = cast<GetElementPtrInst>(I);
2820  Vals.push_back(GEPInst.isInBounds());
2821  Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2822  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2823  pushValueAndType(I.getOperand(i), InstID, Vals);
2824  break;
2825  }
2826  case Instruction::ExtractValue: {
2828  pushValueAndType(I.getOperand(0), InstID, Vals);
2829  const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2830  Vals.append(EVI->idx_begin(), EVI->idx_end());
2831  break;
2832  }
2833  case Instruction::InsertValue: {
2835  pushValueAndType(I.getOperand(0), InstID, Vals);
2836  pushValueAndType(I.getOperand(1), InstID, Vals);
2837  const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2838  Vals.append(IVI->idx_begin(), IVI->idx_end());
2839  break;
2840  }
2841  case Instruction::Select: {
2843  pushValueAndType(I.getOperand(1), InstID, Vals);
2844  pushValue(I.getOperand(2), InstID, Vals);
2845  pushValueAndType(I.getOperand(0), InstID, Vals);
2846  uint64_t Flags = getOptimizationFlags(&I);
2847  if (Flags != 0)
2848  Vals.push_back(Flags);
2849  break;
2850  }
2851  case Instruction::ExtractElement:
2853  pushValueAndType(I.getOperand(0), InstID, Vals);
2854  pushValueAndType(I.getOperand(1), InstID, Vals);
2855  break;
2856  case Instruction::InsertElement:
2858  pushValueAndType(I.getOperand(0), InstID, Vals);
2859  pushValue(I.getOperand(1), InstID, Vals);
2860  pushValueAndType(I.getOperand(2), InstID, Vals);
2861  break;
2862  case Instruction::ShuffleVector:
2864  pushValueAndType(I.getOperand(0), InstID, Vals);
2865  pushValue(I.getOperand(1), InstID, Vals);
2866  pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
2867  Vals);
2868  break;
2869  case Instruction::ICmp:
2870  case Instruction::FCmp: {
2871  // compare returning Int1Ty or vector of Int1Ty
2873  pushValueAndType(I.getOperand(0), InstID, Vals);
2874  pushValue(I.getOperand(1), InstID, Vals);
2875  Vals.push_back(cast<CmpInst>(I).getPredicate());
2876  uint64_t Flags = getOptimizationFlags(&I);
2877  if (Flags != 0)
2878  Vals.push_back(Flags);
2879  break;
2880  }
2881 
2882  case Instruction::Ret:
2883  {
2885  unsigned NumOperands = I.getNumOperands();
2886  if (NumOperands == 0)
2887  AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2888  else if (NumOperands == 1) {
2889  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2890  AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2891  } else {
2892  for (unsigned i = 0, e = NumOperands; i != e; ++i)
2893  pushValueAndType(I.getOperand(i), InstID, Vals);
2894  }
2895  }
2896  break;
2897  case Instruction::Br:
2898  {
2900  const BranchInst &II = cast<BranchInst>(I);
2901  Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2902  if (II.isConditional()) {
2903  Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2904  pushValue(II.getCondition(), InstID, Vals);
2905  }
2906  }
2907  break;
2908  case Instruction::Switch:
2909  {
2911  const SwitchInst &SI = cast<SwitchInst>(I);
2912  Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2913  pushValue(SI.getCondition(), InstID, Vals);
2914  Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2915  for (auto Case : SI.cases()) {
2916  Vals.push_back(VE.getValueID(Case.getCaseValue()));
2917  Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2918  }
2919  }
2920  break;
2921  case Instruction::IndirectBr:
2923  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2924  // Encode the address operand as relative, but not the basic blocks.
2925  pushValue(I.getOperand(0), InstID, Vals);
2926  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2927  Vals.push_back(VE.getValueID(I.getOperand(i)));
2928  break;
2929 
2930  case Instruction::Invoke: {
2931  const InvokeInst *II = cast<InvokeInst>(&I);
2932  const Value *Callee = II->getCalledOperand();
2933  FunctionType *FTy = II->getFunctionType();
2934 
2935  if (II->hasOperandBundles())
2936  writeOperandBundles(*II, InstID);
2937 
2939 
2940  Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2941  Vals.push_back(II->getCallingConv() | 1 << 13);
2942  Vals.push_back(VE.getValueID(II->getNormalDest()));
2943  Vals.push_back(VE.getValueID(II->getUnwindDest()));
2944  Vals.push_back(VE.getTypeID(FTy));
2945  pushValueAndType(Callee, InstID, Vals);
2946 
2947  // Emit value #'s for the fixed parameters.
2948  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2949  pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2950 
2951  // Emit type/value pairs for varargs params.
2952  if (FTy->isVarArg()) {
2953  for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
2954  pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2955  }
2956  break;
2957  }
2958  case Instruction::Resume:
2960  pushValueAndType(I.getOperand(0), InstID, Vals);
2961  break;
2962  case Instruction::CleanupRet: {
2964  const auto &CRI = cast<CleanupReturnInst>(I);
2965  pushValue(CRI.getCleanupPad(), InstID, Vals);
2966  if (CRI.hasUnwindDest())
2967  Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2968  break;
2969  }
2970  case Instruction::CatchRet: {
2972  const auto &CRI = cast<CatchReturnInst>(I);
2973  pushValue(CRI.getCatchPad(), InstID, Vals);
2974  Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2975  break;
2976  }
2977  case Instruction::CleanupPad:
2978  case Instruction::CatchPad: {
2979  const auto &FuncletPad = cast<FuncletPadInst>(I);
2980  Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2982  pushValue(FuncletPad.getParentPad(), InstID, Vals);
2983 
2984  unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2985  Vals.push_back(NumArgOperands);
2986  for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2987  pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2988  break;
2989  }
2990  case Instruction::CatchSwitch: {
2992  const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2993 
2994  pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2995 
2996  unsigned NumHandlers = CatchSwitch.getNumHandlers();
2997  Vals.push_back(NumHandlers);
2998  for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
2999  Vals.push_back(VE.getValueID(CatchPadBB));
3000 
3001  if (CatchSwitch.hasUnwindDest())
3002  Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3003  break;
3004  }
3005  case Instruction::CallBr: {
3006  const CallBrInst *CBI = cast<CallBrInst>(&I);
3007  const Value *Callee = CBI->getCalledOperand();
3008  FunctionType *FTy = CBI->getFunctionType();
3009 
3010  if (CBI->hasOperandBundles())
3011  writeOperandBundles(*CBI, InstID);
3012 
3014 
3015  Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
3016 
3017  Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
3019 
3020  Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3021  Vals.push_back(CBI->getNumIndirectDests());
3022  for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3023  Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3024 
3025  Vals.push_back(VE.getTypeID(FTy));
3026  pushValueAndType(Callee, InstID, Vals);
3027 
3028  // Emit value #'s for the fixed parameters.
3029  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3030  pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3031 
3032  // Emit type/value pairs for varargs params.
3033  if (FTy->isVarArg()) {
3034  for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3035  pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3036  }
3037  break;
3038  }
3039  case Instruction::Unreachable:
3041  AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3042  break;
3043 
3044  case Instruction::PHI: {
3045  const PHINode &PN = cast<PHINode>(I);
3047  // With the newer instruction encoding, forward references could give
3048  // negative valued IDs. This is most common for PHIs, so we use
3049  // signed VBRs.
3051  Vals64.push_back(VE.getTypeID(PN.getType()));
3052  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3053  pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3054  Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3055  }
3056 
3057  uint64_t Flags = getOptimizationFlags(&I);
3058  if (Flags != 0)
3059  Vals64.push_back(Flags);
3060 
3061  // Emit a Vals64 vector and exit.
3062  Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3063  Vals64.clear();
3064  return;
3065  }
3066 
3067  case Instruction::LandingPad: {
3068  const LandingPadInst &LP = cast<LandingPadInst>(I);
3070  Vals.push_back(VE.getTypeID(LP.getType()));
3071  Vals.push_back(LP.isCleanup());
3072  Vals.push_back(LP.getNumClauses());
3073  for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3074  if (LP.isCatch(I))
3075  Vals.push_back(LandingPadInst::Catch);
3076  else
3077  Vals.push_back(LandingPadInst::Filter);
3078  pushValueAndType(LP.getClause(I), InstID, Vals);
3079  }
3080  break;
3081  }
3082 
3083  case Instruction::Alloca: {
3085  const AllocaInst &AI = cast<AllocaInst>(I);
3086  Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3087  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3088  Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3089  using APV = AllocaPackedValues;
3090  unsigned Record = 0;
3091  unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3092  Bitfield::set<APV::AlignLower>(
3093  Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3094  Bitfield::set<APV::AlignUpper>(Record,
3095  EncodedAlign >> APV::AlignLower::Bits);
3096  Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3097  Bitfield::set<APV::ExplicitType>(Record, true);
3098  Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3099  Vals.push_back(Record);
3100 
3101  unsigned AS = AI.getAddressSpace();
3102  if (AS != M.getDataLayout().getAllocaAddrSpace())
3103  Vals.push_back(AS);
3104  break;
3105  }
3106 
3107  case Instruction::Load:
3108  if (cast<LoadInst>(I).isAtomic()) {
3110  pushValueAndType(I.getOperand(0), InstID, Vals);
3111  } else {
3113  if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3114  AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3115  }
3116  Vals.push_back(VE.getTypeID(I.getType()));
3117  Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3118  Vals.push_back(cast<LoadInst>(I).isVolatile());
3119  if (cast<LoadInst>(I).isAtomic()) {
3120  Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3121  Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3122  }
3123  break;
3124  case Instruction::Store:
3125  if (cast<StoreInst>(I).isAtomic())
3127  else
3129  pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3130  pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3131  Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3132  Vals.push_back(cast<StoreInst>(I).isVolatile());
3133  if (cast<StoreInst>(I).isAtomic()) {
3134  Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3135  Vals.push_back(
3136  getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3137  }
3138  break;
3139  case Instruction::AtomicCmpXchg:
3141  pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3142  pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3143  pushValue(I.getOperand(2), InstID, Vals); // newval.
3144  Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3145  Vals.push_back(
3146  getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3147  Vals.push_back(
3148  getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3149  Vals.push_back(
3150  getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3151  Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3152  Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3153  break;
3154  case Instruction::AtomicRMW:
3156  pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3157  pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3158  Vals.push_back(
3159  getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3160  Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3161  Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3162  Vals.push_back(
3163  getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3164  Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3165  break;
3166  case Instruction::Fence:
3168  Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3169  Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3170  break;
3171  case Instruction::Call: {
3172  const CallInst &CI = cast<CallInst>(I);
3173  FunctionType *FTy = CI.getFunctionType();
3174 
3175  if (CI.hasOperandBundles())
3176  writeOperandBundles(CI, InstID);
3177 
3179 
3180  Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
3181 
3182  unsigned Flags = getOptimizationFlags(&I);
3183  Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
3184  unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3185  unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3187  unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3188  unsigned(Flags != 0) << bitc::CALL_FMF);
3189  if (Flags != 0)
3190  Vals.push_back(Flags);
3191 
3192  Vals.push_back(VE.getTypeID(FTy));
3193  pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3194 
3195  // Emit value #'s for the fixed parameters.
3196  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3197  // Check for labels (can happen with asm labels).
3198  if (FTy->getParamType(i)->isLabelTy())
3199  Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3200  else
3201  pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3202  }
3203 
3204  // Emit type/value pairs for varargs params.
3205  if (FTy->isVarArg()) {
3206  for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3207  pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3208  }
3209  break;
3210  }
3211  case Instruction::VAArg:
3213  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3214  pushValue(I.getOperand(0), InstID, Vals); // valist.
3215  Vals.push_back(VE.getTypeID(I.getType())); // restype.
3216  break;
3217  case Instruction::Freeze:
3219  pushValueAndType(I.getOperand(0), InstID, Vals);
3220  break;
3221  }
3222 
3223  Stream.EmitRecord(Code, Vals, AbbrevToUse);
3224  Vals.clear();
3225 }
3226 
3227 /// Write a GlobalValue VST to the module. The purpose of this data structure is
3228 /// to allow clients to efficiently find the function body.
3229 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3230  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3231  // Get the offset of the VST we are writing, and backpatch it into
3232  // the VST forward declaration record.
3233  uint64_t VSTOffset = Stream.GetCurrentBitNo();
3234  // The BitcodeStartBit was the stream offset of the identification block.
3235  VSTOffset -= bitcodeStartBit();
3236  assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3237  // Note that we add 1 here because the offset is relative to one word
3238  // before the start of the identification block, which was historically
3239  // always the start of the regular bitcode header.
3240  Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3241 
3242  Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3243 
3244  auto Abbv = std::make_shared<BitCodeAbbrev>();
3246  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3247  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3248  unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3249 
3250  for (const Function &F : M) {
3251  uint64_t Record[2];
3252 
3253  if (F.isDeclaration())
3254  continue;
3255 
3256  Record[0] = VE.getValueID(&F);
3257 
3258  // Save the word offset of the function (from the start of the
3259  // actual bitcode written to the stream).
3260  uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3261  assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3262  // Note that we add 1 here because the offset is relative to one word
3263  // before the start of the identification block, which was historically
3264  // always the start of the regular bitcode header.
3265  Record[1] = BitcodeIndex / 32 + 1;
3266 
3267  Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3268  }
3269 
3270  Stream.ExitBlock();
3271 }
3272 
3273 /// Emit names for arguments, instructions and basic blocks in a function.
3274 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3275  const ValueSymbolTable &VST) {
3276  if (VST.empty())
3277  return;
3278 
3279  Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
3280 
3281  // FIXME: Set up the abbrev, we know how many values there are!
3282  // FIXME: We know if the type names can use 7-bit ascii.
3283  SmallVector<uint64_t, 64> NameVals;
3284 
3285  for (const ValueName &Name : VST) {
3286  // Figure out the encoding to use for the name.
3288 
3289  unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3290  NameVals.push_back(VE.getValueID(Name.getValue()));
3291 
3292  // VST_CODE_ENTRY: [valueid, namechar x N]
3293  // VST_CODE_BBENTRY: [bbid, namechar x N]
3294  unsigned Code;
3295  if (isa<BasicBlock>(Name.getValue())) {
3297  if (Bits == SE_Char6)
3298  AbbrevToUse = VST_BBENTRY_6_ABBREV;
3299  } else {
3301  if (Bits == SE_Char6)
3302  AbbrevToUse = VST_ENTRY_6_ABBREV;
3303  else if (Bits == SE_Fixed7)
3304  AbbrevToUse = VST_ENTRY_7_ABBREV;
3305  }
3306 
3307  for (const auto P : Name.getKey())
3308  NameVals.push_back((unsigned char)P);
3309 
3310  // Emit the finished record.
3311  Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3312  NameVals.clear();
3313  }
3314 
3315  Stream.ExitBlock();
3316 }
3317 
3318 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3319  assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3320  unsigned Code;
3321  if (isa<BasicBlock>(Order.V))
3323  else
3325 
3326  SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3327  Record.push_back(VE.getValueID(Order.V));
3328  Stream.EmitRecord(Code, Record);
3329 }
3330 
3331 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3333  "Expected to be preserving use-list order");
3334 
3335  auto hasMore = [&]() {
3336  return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3337  };
3338  if (!hasMore())
3339  // Nothing to do.
3340  return;
3341 
3342  Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
3343  while (hasMore()) {
3344  writeUseList(std::move(VE.UseListOrders.back()));
3345  VE.UseListOrders.pop_back();
3346  }
3347  Stream.ExitBlock();
3348 }
3349 
3350 /// Emit a function body to the module stream.
3351 void ModuleBitcodeWriter::writeFunction(
3352  const Function &F,
3353  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3354  // Save the bitcode index of the start of this function block for recording
3355  // in the VST.
3356  FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3357 
3358  Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
3359  VE.incorporateFunction(F);
3360 
3362 
3363  // Emit the number of basic blocks, so the reader can create them ahead of
3364  // time.
3365  Vals.push_back(VE.getBasicBlocks().size());
3366  Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
3367  Vals.clear();
3368 
3369  // If there are function-local constants, emit them now.
3370  unsigned CstStart, CstEnd;
3371  VE.getFunctionConstantRange(CstStart, CstEnd);
3372  writeConstants(CstStart, CstEnd, false);
3373 
3374  // If there is function-local metadata, emit it now.
3375  writeFunctionMetadata(F);
3376 
3377  // Keep a running idea of what the instruction ID is.
3378  unsigned InstID = CstEnd;
3379 
3380  bool NeedsMetadataAttachment = F.hasMetadata();
3381 
3382  DILocation *LastDL = nullptr;
3383  SmallSetVector<Function *, 4> BlockAddressUsers;
3384 
3385  // Finally, emit all the instructions, in order.
3386  for (const BasicBlock &BB : F) {
3387  for (const Instruction &I : BB) {
3388  writeInstruction(I, InstID, Vals);
3389 
3390  if (!I.getType()->isVoidTy())
3391  ++InstID;
3392 
3393  // If the instruction has metadata, write a metadata attachment later.
3394  NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3395 
3396  // If the instruction has a debug location, emit it.
3397  DILocation *DL = I.getDebugLoc();
3398  if (!DL)
3399  continue;
3400 
3401  if (DL == LastDL) {
3402  // Just repeat the same debug loc as last time.
3403  Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
3404  continue;
3405  }
3406 
3407  Vals.push_back(DL->getLine());
3408  Vals.push_back(DL->getColumn());
3409  Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3410  Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3411  Vals.push_back(DL->isImplicitCode());
3412  Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3413  Vals.clear();
3414 
3415  LastDL = DL;
3416  }
3417 
3418  if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3419  SmallVector<Value *> Worklist{BA};
3420  SmallPtrSet<Value *, 8> Visited{BA};
3421  while (!Worklist.empty()) {
3422  Value *V = Worklist.pop_back_val();
3423  for (User *U : V->users()) {
3424  if (auto *I = dyn_cast<Instruction>(U)) {
3425  Function *P = I->getFunction();
3426  if (P != &F)
3427  BlockAddressUsers.insert(P);
3428  } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3429  Visited.insert(U).second)
3430  Worklist.push_back(U);
3431  }
3432  }
3433  }
3434  }
3435 
3436  if (!BlockAddressUsers.empty()) {
3437  Vals.resize(BlockAddressUsers.size());
3438  for (auto I : llvm::enumerate(BlockAddressUsers))
3439  Vals[I.index()] = VE.getValueID(I.value());
3440  Stream.EmitRecord(bitc::FUNC_CODE_BLOCKADDR_USERS, Vals);
3441  Vals.clear();
3442  }
3443 
3444  // Emit names for all the instructions etc.
3445  if (auto *Symtab = F.getValueSymbolTable())
3446  writeFunctionLevelValueSymbolTable(*Symtab);
3447 
3448  if (NeedsMetadataAttachment)
3449  writeFunctionMetadataAttachment(F);
3450  if (VE.shouldPreserveUseListOrder())
3451  writeUseListBlock(&F);
3452  VE.purgeFunction();
3453  Stream.ExitBlock();
3454 }
3455 
3456 // Emit blockinfo, which defines the standard abbreviations etc.
3457 void ModuleBitcodeWriter::writeBlockInfo() {
3458  // We only want to emit block info records for blocks that have multiple
3459  // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3460  // Other blocks can define their abbrevs inline.
3461  Stream.EnterBlockInfoBlock();
3462 
3463  { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3464  auto Abbv = std::make_shared<BitCodeAbbrev>();
3465  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3466  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3468  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3469  if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3470  VST_ENTRY_8_ABBREV)
3471  llvm_unreachable("Unexpected abbrev ordering!");
3472  }
3473 
3474  { // 7-bit fixed width VST_CODE_ENTRY strings.
3475  auto Abbv = std::make_shared<BitCodeAbbrev>();
3477  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3479  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3480  if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3481  VST_ENTRY_7_ABBREV)
3482  llvm_unreachable("Unexpected abbrev ordering!");
3483  }
3484  { // 6-bit char6 VST_CODE_ENTRY strings.
3485  auto Abbv = std::make_shared<BitCodeAbbrev>();
3487  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3490  if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3491  VST_ENTRY_6_ABBREV)
3492  llvm_unreachable("Unexpected abbrev ordering!");
3493  }
3494  { // 6-bit char6 VST_CODE_BBENTRY strings.
3495  auto Abbv = std::make_shared<BitCodeAbbrev>();
3497  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3500  if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, Abbv) !=
3501  VST_BBENTRY_6_ABBREV)
3502  llvm_unreachable("Unexpected abbrev ordering!");
3503  }
3504 
3505  { // SETTYPE abbrev for CONSTANTS_BLOCK.
3506  auto Abbv = std::make_shared<BitCodeAbbrev>();
3510  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3511  CONSTANTS_SETTYPE_ABBREV)
3512  llvm_unreachable("Unexpected abbrev ordering!");
3513  }
3514 
3515  { // INTEGER abbrev for CONSTANTS_BLOCK.
3516  auto Abbv = std::make_shared<BitCodeAbbrev>();
3518  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3519  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3520  CONSTANTS_INTEGER_ABBREV)
3521  llvm_unreachable("Unexpected abbrev ordering!");
3522  }
3523 
3524  { // CE_CAST abbrev for CONSTANTS_BLOCK.
3525  auto Abbv = std::make_shared<BitCodeAbbrev>();
3527  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3528  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3530  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3531 
3532  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3533  CONSTANTS_CE_CAST_Abbrev)
3534  llvm_unreachable("Unexpected abbrev ordering!");
3535  }
3536  { // NULL abbrev for CONSTANTS_BLOCK.
3537  auto Abbv = std::make_shared<BitCodeAbbrev>();
3539  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3540  CONSTANTS_NULL_Abbrev)
3541  llvm_unreachable("Unexpected abbrev ordering!");
3542  }
3543 
3544  // FIXME: This should only use space for first class types!
3545 
3546  { // INST_LOAD abbrev for FUNCTION_BLOCK.
3547  auto Abbv = std::make_shared<BitCodeAbbrev>();
3549  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3550  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3552  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3553  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3554  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3555  FUNCTION_INST_LOAD_ABBREV)
3556  llvm_unreachable("Unexpected abbrev ordering!");
3557  }
3558  { // INST_UNOP abbrev for FUNCTION_BLOCK.
3559  auto Abbv = std::make_shared<BitCodeAbbrev>();
3561  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3562  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3563  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3564  FUNCTION_INST_UNOP_ABBREV)
3565  llvm_unreachable("Unexpected abbrev ordering!");
3566  }
3567  { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3568  auto Abbv = std::make_shared<BitCodeAbbrev>();
3570  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3571  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3572  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3573  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3574  FUNCTION_INST_UNOP_FLAGS_ABBREV)
3575  llvm_unreachable("Unexpected abbrev ordering!");
3576  }
3577  { // INST_BINOP abbrev for FUNCTION_BLOCK.
3578  auto Abbv = std::make_shared<BitCodeAbbrev>();
3580  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3581  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3582  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3583  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3584  FUNCTION_INST_BINOP_ABBREV)
3585  llvm_unreachable("Unexpected abbrev ordering!");
3586  }
3587  { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3588  auto Abbv = std::make_shared<BitCodeAbbrev>();
3590  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3591  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3592  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3593  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3594  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3595  FUNCTION_INST_BINOP_FLAGS_ABBREV)
3596  llvm_unreachable("Unexpected abbrev ordering!");
3597  }
3598  { // INST_CAST abbrev for FUNCTION_BLOCK.
3599  auto Abbv = std::make_shared<BitCodeAbbrev>();
3601  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3602  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3604  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3605  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3606  FUNCTION_INST_CAST_ABBREV)
3607  llvm_unreachable("Unexpected abbrev ordering!");
3608  }
3609 
3610  { // INST_RET abbrev for FUNCTION_BLOCK.
3611  auto Abbv = std::make_shared<BitCodeAbbrev>();
3613  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3614  FUNCTION_INST_RET_VOID_ABBREV)
3615  llvm_unreachable("Unexpected abbrev ordering!");
3616  }
3617  { // INST_RET abbrev for FUNCTION_BLOCK.
3618  auto Abbv = std::make_shared<BitCodeAbbrev>();
3620  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3621  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3622  FUNCTION_INST_RET_VAL_ABBREV)
3623  llvm_unreachable("Unexpected abbrev ordering!");
3624  }
3625  { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3626  auto Abbv = std::make_shared<BitCodeAbbrev>();
3628  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3629  FUNCTION_INST_UNREACHABLE_ABBREV)
3630  llvm_unreachable("Unexpected abbrev ordering!");
3631  }
3632  {
3633  auto Abbv = std::make_shared<BitCodeAbbrev>();
3635  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3636  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3637  Log2_32_Ceil(VE.getTypes().size() + 1)));
3639  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3640  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3641  FUNCTION_INST_GEP_ABBREV)
3642  llvm_unreachable("Unexpected abbrev ordering!");
3643  }
3644 
3645  Stream.ExitBlock();
3646 }
3647 
3648 /// Write the module path strings, currently only used when generating
3649 /// a combined index file.
3650 void IndexBitcodeWriter::writeModStrings() {
3651  Stream.EnterSubblock(bitc::MODULE_STRTAB_BLOCK_ID, 3);
3652 
3653  // TODO: See which abbrev sizes we actually need to emit
3654 
3655  // 8-bit fixed-width MST_ENTRY strings.
3656  auto Abbv = std::make_shared<BitCodeAbbrev>();
3658  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3660  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3661  unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3662 
3663  // 7-bit fixed width MST_ENTRY strings.
3664  Abbv = std::make_shared<BitCodeAbbrev>();
3666  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3668  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3669  unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3670 
3671  // 6-bit char6 MST_ENTRY strings.
3672  Abbv = std::make_shared<BitCodeAbbrev>();
3674  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3677  unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3678 
3679  // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3680  Abbv = std::make_shared<BitCodeAbbrev>();
3682  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3683  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3684  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3685  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3686  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3687  unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3688 
3690  forEachModule(
3691  [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3692  StringRef Key = MPSE.getKey();
3693  const auto &Value = MPSE.getValue();
3695  unsigned AbbrevToUse = Abbrev8Bit;
3696  if (Bits == SE_Char6)
3697  AbbrevToUse = Abbrev6Bit;
3698  else if (Bits == SE_Fixed7)
3699  AbbrevToUse = Abbrev7Bit;
3700 
3701  Vals.push_back(Value.first);
3702  Vals.append(Key.begin(), Key.end());
3703 
3704  // Emit the finished record.
3705  Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3706 
3707  // Emit an optional hash for the module now
3708  const auto &Hash = Value.second;
3709  if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3710  Vals.assign(Hash.begin(), Hash.end());
3711  // Emit the hash record.
3712  Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3713  }
3714 
3715  Vals.clear();
3716  });
3717  Stream.ExitBlock();
3718 }
3719 
3720 /// Write the function type metadata related records that need to appear before
3721 /// a function summary entry (whether per-module or combined).
3722 template <typename Fn>
3725  Fn GetValueID) {
3726  if (!FS->type_tests().empty())
3727  Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3728 
3730 
3731  auto WriteVFuncIdVec = [&](uint64_t Ty,
3733  if (VFs.empty())
3734  return;
3735  Record.clear();
3736  for (auto &VF : VFs) {
3737  Record.push_back(VF.GUID);
3738  Record.push_back(VF.Offset);
3739  }
3740  Stream.EmitRecord(Ty, Record);
3741  };
3742 
3743  WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3744  FS->type_test_assume_vcalls());
3745  WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3746  FS->type_checked_load_vcalls());
3747 
3748  auto WriteConstVCallVec = [&](uint64_t Ty,
3750  for (auto &VC : VCs) {
3751  Record.clear();
3752  Record.push_back(VC.VFunc.GUID);
3753  Record.push_back(VC.VFunc.Offset);
3754  llvm::append_range(Record, VC.Args);
3755  Stream.EmitRecord(Ty, Record);
3756  }
3757  };
3758 
3759  WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3760  FS->type_test_assume_const_vcalls());
3761  WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3762  FS->type_checked_load_const_vcalls());
3763 
3764  auto WriteRange = [&](ConstantRange Range) {
3765  Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
3766  assert(Range.getLower().getNumWords() == 1);
3767  assert(Range.getUpper().getNumWords() == 1);
3768  emitSignedInt64(Record, *Range.getLower().getRawData());
3769  emitSignedInt64(Record, *Range.getUpper().getRawData());
3770  };
3771 
3772  if (!FS->paramAccesses().empty()) {
3773  Record.clear();
3774  for (auto &Arg : FS->paramAccesses()) {
3775  size_t UndoSize = Record.size();
3776  Record.push_back(Arg.ParamNo);
3777  WriteRange(Arg.Use);
3778  Record.push_back(Arg.Calls.size());
3779  for (auto &Call : Arg.Calls) {
3780  Record.push_back(Call.ParamNo);
3781  Optional<unsigned> ValueID = GetValueID(Call.Callee);
3782  if (!ValueID) {
3783  // If ValueID is unknown we can't drop just this call, we must drop
3784  // entire parameter.
3785  Record.resize(UndoSize);
3786  break;
3787  }
3788  Record.push_back(*ValueID);
3789  WriteRange(Call.Offsets);
3790  }
3791  }
3792  if (!Record.empty())
3793  Stream.EmitRecord(bitc::FS_PARAM_ACCESS, Record);
3794  }
3795 }
3796 
3797 /// Collect type IDs from type tests used by function.
3798 static void
3800  std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3801  if (!FS->type_tests().empty())
3802  for (auto &TT : FS->type_tests())
3803  ReferencedTypeIds.insert(TT);
3804 
3805  auto GetReferencedTypesFromVFuncIdVec =
3807  for (auto &VF : VFs)
3808  ReferencedTypeIds.insert(VF.GUID);
3809  };
3810 
3811  GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3812  GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3813 
3814  auto GetReferencedTypesFromConstVCallVec =
3816  for (auto &VC : VCs)
3817  ReferencedTypeIds.insert(VC.VFunc.GUID);
3818  };
3819 
3820  GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3821  GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3822 }
3823 
3825  SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3826  const WholeProgramDevirtResolution::ByArg &ByArg) {
3827  NameVals.push_back(args.size());
3828  llvm::append_range(NameVals, args);
3829 
3830  NameVals.push_back(ByArg.TheKind);
3831  NameVals.push_back(ByArg.Info);
3832  NameVals.push_back(ByArg.Byte);
3833  NameVals.push_back(ByArg.Bit);
3834 }
3835 
3837  SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3839  NameVals.push_back(Id);
3840 
3841  NameVals.push_back(Wpd.TheKind);
3842  NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3843  NameVals.push_back(Wpd.SingleImplName.size());
3844 
3845  NameVals.push_back(Wpd.ResByArg.size());
3846  for (auto &A : Wpd.ResByArg)
3847  writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3848 }
3849 
3851  StringTableBuilder &StrtabBuilder,
3852  const std::string &Id,
3853  const TypeIdSummary &Summary) {
3854  NameVals.push_back(StrtabBuilder.add(Id));
3855  NameVals.push_back(Id.size());
3856 
3857  NameVals.push_back(Summary.TTRes.TheKind);
3858  NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3859  NameVals.push_back(Summary.TTRes.AlignLog2);
3860  NameVals.push_back(Summary.TTRes.SizeM1);
3861  NameVals.push_back(Summary.TTRes.BitMask);
3862  NameVals.push_back(Summary.TTRes.InlineBits);
3863 
3864  for (auto &W : Summary.WPDRes)
3865  writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3866  W.second);
3867 }
3868 
3870  SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3871  const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
3872  ValueEnumerator &VE) {
3873  NameVals.push_back(StrtabBuilder.add(Id));
3874  NameVals.push_back(Id.size());
3875 
3876  for (auto &P : Summary) {
3877  NameVals.push_back(P.AddressPointOffset);
3878  NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
3879  }
3880 }
3881 
3882 // Helper to emit a single function summary record.
3883 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3884  SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3885  unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3886  const Function &F) {
3887  NameVals.push_back(ValueID);
3888 
3889  FunctionSummary *FS = cast<FunctionSummary>(Summary);
3890 
3892  Stream, FS, [&](const ValueInfo &VI) -> Optional<unsigned> {
3893  return {VE.getValueID(VI.getValue())};
3894  });
3895 
3896  auto SpecialRefCnts = FS->specialRefCounts();
3897  NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3898  NameVals.push_back(FS->instCount());
3899  NameVals.push_back(getEncodedFFlags(FS->fflags()));
3900  NameVals.push_back(FS->refs().size());
3901  NameVals.push_back(SpecialRefCnts.first); // rorefcnt
3902  NameVals.push_back(SpecialRefCnts.second); // worefcnt
3903 
3904  for (auto &RI : FS->refs())
3905  NameVals.push_back(VE.getValueID(RI.getValue()));
3906 
3907  bool HasProfileData =
3908  F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
3909  for (auto &ECI : FS->calls()) {
3910  NameVals.push_back(getValueId(ECI.first));
3911  if (HasProfileData)
3912  NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3913  else if (WriteRelBFToSummary)
3914  NameVals.push_back(ECI.second.RelBlockFreq);
3915  }
3916 
3917  unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3918  unsigned Code =
3919  (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3921  : bitc::FS_PERMODULE));
3922 
3923  // Emit the finished record.
3924  Stream.EmitRecord(Code, NameVals, FSAbbrev);
3925  NameVals.clear();
3926 }
3927 
3928 // Collect the global value references in the given variable's initializer,
3929 // and emit them in a summary record.
3930 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3931  const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3932  unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
3933  auto VI = Index->getValueInfo(V.getGUID());
3934  if (!VI || VI.getSummaryList().empty()) {
3935  // Only declarations should not have a summary (a declaration might however
3936  // have a summary if the def was in module level asm).
3937  assert(V.isDeclaration());
3938  return;
3939  }
3940  auto *Summary = VI.getSummaryList()[0].get();
3941  NameVals.push_back(VE.getValueID(&V));
3942  GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3943  NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3944  NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3945 
3946  auto VTableFuncs = VS->vTableFuncs();
3947  if (!VTableFuncs.empty())
3948  NameVals.push_back(VS->refs().size());
3949 
3950  unsigned SizeBeforeRefs = NameVals.size();
3951  for (auto &RI : VS->refs())
3952  NameVals.push_back(VE.getValueID(RI.getValue()));
3953  // Sort the refs for determinism output, the vector returned by FS->refs() has
3954  // been initialized from a DenseSet.
3955  llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
3956 
3957  if (VTableFuncs.empty())
3958  Stream.EmitRecord(bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS, NameVals,
3959  FSModRefsAbbrev);
3960  else {
3961  // VTableFuncs pairs should already be sorted by offset.
3962  for (auto &P : VTableFuncs) {
3963  NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
3964  NameVals.push_back(P.VTableOffset);
3965  }
3966 
3968  FSModVTableRefsAbbrev);
3969  }
3970  NameVals.clear();
3971 }
3972 
3973 /// Emit the per-module summary section alongside the rest of
3974 /// the module's bitcode.
3975 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3976  // By default we compile with ThinLTO if the module has a summary, but the
3977  // client can request full LTO with a module flag.
3978  bool IsThinLTO = true;
3979  if (auto *MD =
3980  mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3981  IsThinLTO = MD->getZExtValue();
3982  Stream.EnterSubblock(IsThinLTO ? bitc::GLOBALVAL_SUMMARY_BLOCK_ID
3984  4);
3985 
3986  Stream.EmitRecord(
3989 
3990  // Write the index flags.
3991  uint64_t Flags = 0;
3992  // Bits 1-3 are set only in the combined index, skip them.
3993  if (Index->enableSplitLTOUnit())
3994  Flags |= 0x8;
3995  Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Flags});
3996 
3997  if (Index->begin() == Index->end()) {
3998  Stream.ExitBlock();
3999  return;
4000  }
4001 
4002  for (const auto &GVI : valueIds()) {
4003  Stream.EmitRecord(bitc::FS_VALUE_GUID,
4004  ArrayRef<uint64_t>{GVI.second, GVI.first});
4005  }
4006 
4007  // Abbrev for FS_PERMODULE_PROFILE.
4008  auto Abbv = std::make_shared<BitCodeAbbrev>();
4010  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4011  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4012  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4013  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4014  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4015  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4016  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4017  // numrefs x valueid, n x (valueid, hotness)
4019  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4020  unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4021 
4022  // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
4023  Abbv = std::make_shared<BitCodeAbbrev>();
4024  if (WriteRelBFToSummary)
4026  else
4027  Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
4028  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4029  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4030  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4031  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4032  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4033  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4034  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4035  // numrefs x valueid, n x (valueid [, rel_block_freq])
4037  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4038  unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4039 
4040  // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4041  Abbv = std::make_shared<BitCodeAbbrev>();
4043  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4044  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4045  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4046  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4047  unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4048 
4049  // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4050  Abbv = std::make_shared<BitCodeAbbrev>();
4052  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4053  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4054  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4055  // numrefs x valueid, n x (valueid , offset)
4057  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4058  unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4059 
4060  // Abbrev for FS_ALIAS.
4061  Abbv = std::make_shared<BitCodeAbbrev>();
4062  Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4063  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4064  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4065  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4066  unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4067 
4068  // Abbrev for FS_TYPE_ID_METADATA
4069  Abbv = std::make_shared<BitCodeAbbrev>();
4071  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4072  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4073  // n x (valueid , offset)
4075  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4076  unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4077 
4078  SmallVector<uint64_t, 64> NameVals;
4079  // Iterate over the list of functions instead of the Index to
4080  // ensure the ordering is stable.
4081  for (const Function &F : M) {
4082  // Summary emission does not support anonymous functions, they have to
4083  // renamed using the anonymous function renaming pass.
4084  if (!F.hasName())
4085  report_fatal_error("Unexpected anonymous function when writing summary");
4086 
4087  ValueInfo VI = Index->getValueInfo(F.getGUID());
4088  if (!VI || VI.getSummaryList().empty()) {
4089  // Only declarations should not have a summary (a declaration might
4090  // however have a summary if the def was in module level asm).
4091  assert(F.isDeclaration());
4092  continue;
4093  }
4094  auto *Summary = VI.getSummaryList()[0].get();
4095  writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
4096  FSCallsAbbrev, FSCallsProfileAbbrev, F);
4097  }
4098 
4099  // Capture references from GlobalVariable initializers, which are outside
4100  // of a function scope.
4101  for (const GlobalVariable &G : M.globals())
4102  writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4103  FSModVTableRefsAbbrev);
4104 
4105  for (const GlobalAlias &A : M.aliases()) {
4106  auto *Aliasee = A.getAliaseeObject();
4107  if (!Aliasee->hasName())
4108  // Nameless function don't have an entry in the summary, skip it.
4109  continue;
4110  auto AliasId = VE.getValueID(&A);
4111  auto AliaseeId = VE.getValueID(Aliasee);
4112  NameVals.push_back(AliasId);
4113  auto *Summary = Index->getGlobalValueSummary(A);
4114  AliasSummary *AS = cast<AliasSummary>(Summary);
4115  NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4116  NameVals.push_back(AliaseeId);
4117  Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4118  NameVals.clear();
4119  }
4120 
4121  for (auto &S : Index->typeIdCompatibleVtableMap()) {
4122  writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4123  S.second, VE);
4124  Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4125  TypeIdCompatibleVtableAbbrev);
4126  NameVals.clear();
4127  }
4128 
4129  Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4130  ArrayRef<uint64_t>{Index->getBlockCount()});
4131 
4132  Stream.ExitBlock();
4133 }
4134 
4135 /// Emit the combined summary section into the combined index file.
4136 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4137  Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 3);
4138  Stream.EmitRecord(
4141 
4142  // Write the index flags.
4143  Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4144 
4145  for (const auto &GVI : valueIds()) {
4146  Stream.EmitRecord(bitc::FS_VALUE_GUID,
4147  ArrayRef<uint64_t>{GVI.second, GVI.first});
4148  }
4149 
4150  // Abbrev for FS_COMBINED.
4151  auto Abbv = std::make_shared<BitCodeAbbrev>();
4152  Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
4153  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4154  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4155  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4156  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4157  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4158  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4159  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4160  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4161  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4162  // numrefs x valueid, n x (valueid)
4164  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4165  unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4166 
4167  // Abbrev for FS_COMBINED_PROFILE.
4168  Abbv = std::make_shared<BitCodeAbbrev>();
4170  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4171  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4172  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4173  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4174  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4175  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4176  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4177  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4178  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4179  // numrefs x valueid, n x (valueid, hotness)
4181  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4182  unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4183 
4184  // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4185  Abbv = std::make_shared<BitCodeAbbrev>();
4187  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4188  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4189  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4190  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4191  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4192  unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4193 
4194  // Abbrev for FS_COMBINED_ALIAS.
4195  Abbv = std::make_shared<BitCodeAbbrev>();
4197  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4198  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4199  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4200  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4201  unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4202 
4203  // The aliases are emitted as a post-pass, and will point to the value
4204  // id of the aliasee. Save them in a vector for post-processing.
4206 
4207  // Save the value id for each summary for alias emission.
4209 
4210  SmallVector<uint64_t, 64> NameVals;
4211 
4212  // Set that will be populated during call to writeFunctionTypeMetadataRecords
4213  // with the type ids referenced by this index file.
4214  std::set<GlobalValue::GUID> ReferencedTypeIds;
4215 
4216  // For local linkage, we also emit the original name separately
4217  // immediately after the record.
4218  auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4219  // We don't need to emit the original name if we are writing the index for
4220  // distributed backends (in which case ModuleToSummariesForIndex is
4221  // non-null). The original name is only needed during the thin link, since
4222  // for SamplePGO the indirect call targets for local functions have
4223  // have the original name annotated in profile.
4224  // Continue to emit it when writing out the entire combined index, which is
4225  // used in testing the thin link via llvm-lto.
4226  if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
4227  return;
4228  NameVals.push_back(S.getOriginalName());
4229  Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
4230  NameVals.clear();
4231  };
4232 
4233  std::set<GlobalValue::GUID> DefOrUseGUIDs;
4234  forEachSummary([&](GVInfo I, bool IsAliasee) {
4235  GlobalValueSummary *S = I.second;
4236  assert(S);
4237  DefOrUseGUIDs.insert(I.first);
4238  for (const ValueInfo &VI : S->refs())
4239  DefOrUseGUIDs.insert(VI.getGUID());
4240 
4241  auto ValueId = getValueId(I.first);
4242  assert(ValueId);
4243  SummaryToValueIdMap[S] = *ValueId;
4244 
4245  // If this is invoked for an aliasee, we want to record the above
4246  // mapping, but then not emit a summary entry (if the aliasee is
4247  // to be imported, we will invoke this separately with IsAliasee=false).
4248  if (IsAliasee)
4249  return;
4250 
4251  if (auto *AS = dyn_cast<AliasSummary>(S)) {
4252  // Will process aliases as a post-pass because the reader wants all
4253  // global to be loaded first.
4254  Aliases.push_back(AS);
4255  return;
4256  }
4257 
4258  if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4259  NameVals.push_back(*ValueId);
4260  NameVals.push_back(Index.getModuleId(VS->modulePath()));
4261  NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4262  NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4263  for (auto &RI : VS->refs()) {
4264  auto RefValueId = getValueId(RI.getGUID());
4265  if (!RefValueId)
4266  continue;
4267  NameVals.push_back(*RefValueId);
4268  }
4269 
4270  // Emit the finished record.
4271  Stream.EmitRecord(bitc::FS_COMBINED_GLOBALVAR_INIT_REFS, NameVals,
4272  FSModRefsAbbrev);
4273  NameVals.clear();
4274  MaybeEmitOriginalName(*S);
4275  return;
4276  }
4277 
4278  auto GetValueId = [&](const ValueInfo &VI) -> Optional<unsigned> {
4279  return getValueId(VI.getGUID());
4280  };
4281 
4282  auto *FS = cast<FunctionSummary>(S);
4283  writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
4284  getReferencedTypeIds(FS, ReferencedTypeIds);
4285 
4286  NameVals.push_back(*ValueId);
4287  NameVals.push_back(Index.getModuleId(FS->modulePath()));
4288  NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4289  NameVals.push_back(FS->instCount());
4290  NameVals.push_back(getEncodedFFlags(FS->fflags()));
4291  NameVals.push_back(FS->entryCount());
4292 
4293  // Fill in below
4294  NameVals.push_back(0); // numrefs
4295  NameVals.push_back(0); // rorefcnt
4296  NameVals.push_back(0); // worefcnt
4297 
4298  unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
4299  for (auto &RI : FS->refs()) {
4300  auto RefValueId = getValueId(RI.getGUID());
4301  if (!RefValueId)
4302  continue;
4303  NameVals.push_back(*RefValueId);
4304  if (RI.isReadOnly())
4305  RORefCnt++;
4306  else if (RI.isWriteOnly())
4307  WORefCnt++;
4308  Count++;
4309  }
4310  NameVals[6] = Count;
4311  NameVals[7] = RORefCnt;
4312  NameVals[8] = WORefCnt;
4313 
4314  bool HasProfileData = false;
4315  for (auto &EI : FS->calls()) {
4316  HasProfileData |=
4317  EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
4318  if (HasProfileData)
4319  break;
4320  }
4321 
4322  for (auto &EI : FS->calls()) {
4323  // If this GUID doesn't have a value id, it doesn't have a function
4324  // summary and we don't need to record any calls to it.
4325  Optional<unsigned> CallValueId = GetValueId(EI.first);
4326  if (!CallValueId)
4327  continue;
4328  NameVals.push_back(*CallValueId);
4329  if (HasProfileData)
4330  NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
4331  }
4332 
4333  unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
4334  unsigned Code =
4335  (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
4336 
4337  // Emit the finished record.
4338  Stream.EmitRecord(Code, NameVals, FSAbbrev);
4339  NameVals.clear();
4340  MaybeEmitOriginalName(*S);
4341  });
4342 
4343  for (auto *AS : Aliases) {
4344  auto AliasValueId = SummaryToValueIdMap[AS];
4345  assert(AliasValueId);
4346  NameVals.push_back(AliasValueId);
4347  NameVals.push_back(Index.getModuleId(AS->modulePath()));
4348  NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4349  auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
4350  assert(AliaseeValueId);
4351  NameVals.push_back(AliaseeValueId);
4352 
4353  // Emit the finished record.
4354  Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
4355  NameVals.clear();
4356  MaybeEmitOriginalName(*AS);
4357 
4358  if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4359  getReferencedTypeIds(FS, ReferencedTypeIds);
4360  }
4361 
4362  if (!Index.cfiFunctionDefs().empty()) {
4363  for (auto &S : Index.cfiFunctionDefs()) {
4364  if (DefOrUseGUIDs.count(
4366  NameVals.push_back(StrtabBuilder.add(S));
4367  NameVals.push_back(S.size());
4368  }
4369  }
4370  if (!NameVals.empty()) {
4371  Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
4372  NameVals.clear();
4373  }
4374  }
4375 
4376  if (!Index.cfiFunctionDecls().empty()) {
4377  for (auto &S : Index.cfiFunctionDecls()) {
4378  if (DefOrUseGUIDs.count(
4380  NameVals.push_back(StrtabBuilder.add(S));
4381  NameVals.push_back(S.size());
4382  }
4383  }
4384  if (!NameVals.empty()) {
4385  Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
4386  NameVals.clear();
4387  }
4388  }
4389 
4390  // Walk the GUIDs that were referenced, and write the
4391  // corresponding type id records.
4392  for (auto &T : ReferencedTypeIds) {
4393  auto TidIter = Index.typeIds().equal_range(T);
4394  for (auto It = TidIter.first; It != TidIter.second; ++It) {
4395  writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
4396  It->second.second);
4397  Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4398  NameVals.clear();
4399  }
4400  }
4401 
4402  Stream.EmitRecord(bitc::FS_BLOCK_COUNT,
4403  ArrayRef<uint64_t>{Index.getBlockCount()});
4404 
4405  Stream.ExitBlock();
4406 }
4407 
4408 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4409 /// current llvm version, and a record for the epoch number.
4411  Stream.EnterSubblock(bitc::IDENTIFICATION_BLOCK_ID, 5);
4412 
4413  // Write the "user readable" string identifying the bitcode producer
4414  auto Abbv = std::make_shared<BitCodeAbbrev>();
4418  auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4420  "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4421 
4422  // Write the epoch version
4423  Abbv = std::make_shared<BitCodeAbbrev>();
4425  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4426  auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4427  constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
4428  Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4429  Stream.ExitBlock();
4430 }
4431 
4432 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
4433  // Emit the module's hash.
4434  // MODULE_CODE_HASH: [5*i32]
4435  if (GenerateHash) {
4436  uint32_t Vals[5];
4437  Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4438  Buffer.size() - BlockStartPos));
4439  std::array<uint8_t, 20> Hash = Hasher.result();
4440  for (int Pos = 0; Pos < 20; Pos += 4) {
4441  Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4442  }
4443 
4444  // Emit the finished record.
4445  Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4446 
4447  if (ModHash)
4448  // Save the written hash value.
4449  llvm::copy(Vals, std::begin(*ModHash));
4450  }
4451 }
4452 
4454  writeIdentificationBlock(Stream);
4455 
4456  Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
4457  size_t BlockStartPos = Buffer.size();
4458 
4459  writeModuleVersion();
4460 
4461  // Emit blockinfo, which defines the standard abbreviations etc.
4462  writeBlockInfo();
4463 
4464  // Emit information describing all of the types in the module.
4465  writeTypeTable();
4466 
4467  // Emit information about attribute groups.
4468  writeAttributeGroupTable();
4469 
4470  // Emit information about parameter attributes.
4471  writeAttributeTable();
4472 
4473  writeComdats();
4474 
4475  // Emit top-level description of module, including target triple, inline asm,
4476  // descriptors for global variables, and function prototype info.
4477  writeModuleInfo();
4478 
4479  // Emit constants.
4480  writeModuleConstants();
4481 
4482  // Emit metadata kind names.
4483  writeModuleMetadataKinds();
4484 
4485  // Emit metadata.
4486  writeModuleMetadata();
4487 
4488  // Emit module-level use-lists.
4489  if (VE.shouldPreserveUseListOrder())
4490  writeUseListBlock(nullptr);
4491 
4492  writeOperandBundleTags();
4493  writeSyncScopeNames();
4494 
4495  // Emit function bodies.
4496  DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4497  for (const Function &F : M)
4498  if (!F.isDeclaration())
4499  writeFunction(F, FunctionToBitcodeIndex);
4500 
4501  // Need to write after the above call to WriteFunction which populates
4502  // the summary information in the index.
4503  if (Index)
4504  writePerModuleGlobalValueSummary();
4505 
4506  writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4507 
4508  writeModuleHash(BlockStartPos);
4509 
4510  Stream.ExitBlock();
4511 }
4512 
4514  uint32_t &Position) {
4515  support::endian::write32le(&Buffer[Position], Value);
4516  Position += 4;
4517 }
4518 
4519 /// If generating a bc file on darwin, we have to emit a
4520 /// header and trailer to make it compatible with the system archiver. To do
4521 /// this we emit the following header, and then emit a trailer that pads the
4522 /// file out to be a multiple of 16 bytes.
4523 ///
4524 /// struct bc_header {
4525 /// uint32_t Magic; // 0x0B17C0DE
4526 /// uint32_t Version; // Version, currently always 0.
4527 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4528 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
4529 /// uint32_t CPUType; // CPU specifier.
4530 /// ... potentially more later ...
4531 /// };
4533  const Triple &TT) {
4534  unsigned CPUType = ~0U;
4535 
4536  // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4537  // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4538  // number from /usr/include/mach/machine.h. It is ok to reproduce the
4539  // specific constants here because they are implicitly part of the Darwin ABI.
4540  enum {
4541  DARWIN_CPU_ARCH_ABI64 = 0x01000000,
4542  DARWIN_CPU_TYPE_X86 = 7,
4543  DARWIN_CPU_TYPE_ARM = 12,
4544  DARWIN_CPU_TYPE_POWERPC = 18
4545  };
4546 
4547  Triple::ArchType Arch = TT.getArch();
4548  if (Arch == Triple::x86_64)
4549  CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4550  else if (Arch == Triple::x86)
4551  CPUType = DARWIN_CPU_TYPE_X86;
4552  else if (Arch == Triple::ppc)
4553  CPUType = DARWIN_CPU_TYPE_POWERPC;
4554  else if (Arch == Triple::ppc64)
4555  CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4556  else if (Arch == Triple::arm || Arch == Triple::thumb)
4557  CPUType = DARWIN_CPU_TYPE_ARM;
4558 
4559  // Traditional Bitcode starts after header.
4560  assert(Buffer.size() >= BWH_HeaderSize &&
4561  "Expected header size to be reserved");
4562  unsigned BCOffset = BWH_HeaderSize;
4563  unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4564 
4565  // Write the magic and version.
4566  unsigned Position = 0;
4567  writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4568  writeInt32ToBuffer(0, Buffer, Position); // Version.
4569  writeInt32ToBuffer(BCOffset, Buffer, Position);
4570  writeInt32ToBuffer(BCSize, Buffer, Position);
4571  writeInt32ToBuffer(CPUType, Buffer, Position);
4572 
4573  // If the file is not a multiple of 16 bytes, insert dummy padding.
4574  while (Buffer.size() & 15)
4575  Buffer.push_back(0);
4576 }
4577 
4578 /// Helper to write the header common to all bitcode files.
4579 static void writeBitcodeHeader(BitstreamWriter &Stream) {
4580  // Emit the file header.
4581  Stream.Emit((unsigned)'B', 8);
4582  Stream.Emit((unsigned)'C', 8);
4583  Stream.Emit(0x0, 4);
4584  Stream.Emit(0xC, 4);
4585  Stream.Emit(0xE, 4);
4586  Stream.Emit(0xD, 4);
4587 }
4588 
4590  : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) {
4591  writeBitcodeHeader(*Stream);
4592 }
4593 
4595 
4596 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4597  Stream->EnterSubblock(Block, 3);
4598 
4599  auto Abbv = std::make_shared<BitCodeAbbrev>();
4600  Abbv->Add(BitCodeAbbrevOp(Record));
4602  auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4603 
4604  Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4605 
4606  Stream->ExitBlock();
4607 }
4608 
4610  assert(!WroteStrtab && !WroteSymtab);
4611 
4612  // If any module has module-level inline asm, we will require a registered asm
4613  // parser for the target so that we can create an accurate symbol table for
4614  // the module.
4615  for (Module *M : Mods) {
4616  if (M->getModuleInlineAsm().empty())
4617  continue;
4618 
4619  std::string Err;
4620  const Triple TT(M->getTargetTriple());
4621  const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4622  if (!T || !T->hasMCAsmParser())
4623  return;
4624  }
4625 
4626  WroteSymtab = true;
4627  SmallVector<char, 0> Symtab;
4628  // The irsymtab::build function may be unable to create a symbol table if the
4629  // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4630  // table is not required for correctness, but we still want to be able to
4631  // write malformed modules to bitcode files, so swallow the error.
4632  if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4634  return;
4635  }
4636 
4638  {Symtab.data(), Symtab.size()});
4639 }
4640 
4642  assert(!WroteStrtab);
4643 
4644  std::vector<char> Strtab;
4645  StrtabBuilder.finalizeInOrder();
4646  Strtab.resize(StrtabBuilder.getSize());
4647  StrtabBuilder.write((uint8_t *)Strtab.data());
4648 
4650  {Strtab.data(), Strtab.size()});
4651 
4652  WroteStrtab = true;
4653 }
4654 
4656  writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4657  WroteStrtab = true;
4658 }
4659 
4661  bool ShouldPreserveUseListOrder,
4662  const ModuleSummaryIndex *Index,
4663  bool GenerateHash, ModuleHash *ModHash) {
4664  assert(!WroteStrtab);
4665 
4666  // The Mods vector is used by irsymtab::build, which requires non-const
4667  // Modules in case it needs to materialize metadata. But the bitcode writer
4668  // requires that the module is materialized, so we can cast to non-const here,
4669  // after checking that it is in fact materialized.
4670  assert(M.isMaterialized());
4671  Mods.push_back(const_cast<Module *>(&M));
4672 
4673  ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4674  ShouldPreserveUseListOrder, Index,
4675  GenerateHash, ModHash);
4676  ModuleWriter.write();
4677