LLVM  16.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.
136  BitstreamWriter &Stream;
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#]
152  Stream.EmitRecord(bitc::MODULE_CODE_VERSION, ArrayRef<uint64_t>{2});
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::SkipProfile:
703  case Attribute::NoUnwind:
705  case Attribute::NoSanitizeBounds:
707  case Attribute::NoSanitizeCoverage:
709  case Attribute::NullPointerIsValid:
711  case Attribute::OptForFuzzing:
713  case Attribute::OptimizeForSize:
715  case Attribute::OptimizeNone:
717  case Attribute::ReadNone:
719  case Attribute::ReadOnly:
721  case Attribute::Returned:
723  case Attribute::ReturnsTwice:
725  case Attribute::SExt:
726  return bitc::ATTR_KIND_S_EXT;
727  case Attribute::Speculatable:
729  case Attribute::StackAlignment:
731  case Attribute::StackProtect:
733  case Attribute::StackProtectReq:
735  case Attribute::StackProtectStrong:
737  case Attribute::SafeStack:
739  case Attribute::ShadowCallStack:
741  case Attribute::StrictFP:
743  case Attribute::StructRet:
745  case Attribute::SanitizeAddress:
747  case Attribute::SanitizeHWAddress:
749  case Attribute::SanitizeThread:
751  case Attribute::SanitizeMemory:
753  case Attribute::SpeculativeLoadHardening:
755  case Attribute::SwiftError:
757  case Attribute::SwiftSelf:
759  case Attribute::SwiftAsync:
761  case Attribute::UWTable:
763  case Attribute::VScaleRange:
765  case Attribute::WillReturn:
767  case Attribute::WriteOnly:
769  case Attribute::ZExt:
770  return bitc::ATTR_KIND_Z_EXT;
771  case Attribute::ImmArg:
772  return bitc::ATTR_KIND_IMMARG;
773  case Attribute::SanitizeMemTag:
775  case Attribute::Preallocated:
777  case Attribute::NoUndef:
779  case Attribute::ByRef:
780  return bitc::ATTR_KIND_BYREF;
781  case Attribute::MustProgress:
783  case Attribute::PresplitCoroutine:
786  llvm_unreachable("Can not encode end-attribute kinds marker.");
787  case Attribute::None:
788  llvm_unreachable("Can not encode none-attribute.");
789  case Attribute::EmptyKey:
791  llvm_unreachable("Trying to encode EmptyKey/TombstoneKey");
792  }
793 
794  llvm_unreachable("Trying to encode unknown attribute");
795 }
796 
797 void ModuleBitcodeWriter::writeAttributeGroupTable() {
798  const std::vector<ValueEnumerator::IndexAndAttrSet> &AttrGrps =
799  VE.getAttributeGroups();
800  if (AttrGrps.empty()) return;
801 
803 
805  for (ValueEnumerator::IndexAndAttrSet Pair : AttrGrps) {
806  unsigned AttrListIndex = Pair.first;
807  AttributeSet AS = Pair.second;
808  Record.push_back(VE.getAttributeGroupID(Pair));
809  Record.push_back(AttrListIndex);
810 
811  for (Attribute Attr : AS) {
812  if (Attr.isEnumAttribute()) {
813  Record.push_back(0);
814  Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
815  } else if (Attr.isIntAttribute()) {
816  Record.push_back(1);
817  Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
818  Record.push_back(Attr.getValueAsInt());
819  } else if (Attr.isStringAttribute()) {
820  StringRef Kind = Attr.getKindAsString();
821  StringRef Val = Attr.getValueAsString();
822 
823  Record.push_back(Val.empty() ? 3 : 4);
824  Record.append(Kind.begin(), Kind.end());
825  Record.push_back(0);
826  if (!Val.empty()) {
827  Record.append(Val.begin(), Val.end());
828  Record.push_back(0);
829  }
830  } else {
831  assert(Attr.isTypeAttribute());
832  Type *Ty = Attr.getValueAsType();
833  Record.push_back(Ty ? 6 : 5);
834  Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
835  if (Ty)
836  Record.push_back(VE.getTypeID(Attr.getValueAsType()));
837  }
838  }
839 
841  Record.clear();
842  }
843 
844  Stream.ExitBlock();
845 }
846 
847 void ModuleBitcodeWriter::writeAttributeTable() {
848  const std::vector<AttributeList> &Attrs = VE.getAttributeLists();
849  if (Attrs.empty()) return;
850 
852 
854  for (const AttributeList &AL : Attrs) {
855  for (unsigned i : AL.indexes()) {
856  AttributeSet AS = AL.getAttributes(i);
857  if (AS.hasAttributes())
858  Record.push_back(VE.getAttributeGroupID({i, AS}));
859  }
860 
862  Record.clear();
863  }
864 
865  Stream.ExitBlock();
866 }
867 
868 /// WriteTypeTable - Write out the type table for a module.
869 void ModuleBitcodeWriter::writeTypeTable() {
870  const ValueEnumerator::TypeList &TypeList = VE.getTypes();
871 
872  Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
873  SmallVector<uint64_t, 64> TypeVals;
874 
876 
877  // Abbrev for TYPE_CODE_POINTER.
878  auto Abbv = std::make_shared<BitCodeAbbrev>();
880  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
881  Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
882  unsigned PtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
883 
884  // Abbrev for TYPE_CODE_OPAQUE_POINTER.
885  Abbv = std::make_shared<BitCodeAbbrev>();
887  Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
888  unsigned OpaquePtrAbbrev = Stream.EmitAbbrev(std::move(Abbv));
889 
890  // Abbrev for TYPE_CODE_FUNCTION.
891  Abbv = std::make_shared<BitCodeAbbrev>();
893  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
895  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
896  unsigned FunctionAbbrev = Stream.EmitAbbrev(std::move(Abbv));
897 
898  // Abbrev for TYPE_CODE_STRUCT_ANON.
899  Abbv = std::make_shared<BitCodeAbbrev>();
901  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
903  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
904  unsigned StructAnonAbbrev = Stream.EmitAbbrev(std::move(Abbv));
905 
906  // Abbrev for TYPE_CODE_STRUCT_NAME.
907  Abbv = std::make_shared<BitCodeAbbrev>();
911  unsigned StructNameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
912 
913  // Abbrev for TYPE_CODE_STRUCT_NAMED.
914  Abbv = std::make_shared<BitCodeAbbrev>();
916  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
918  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
919  unsigned StructNamedAbbrev = Stream.EmitAbbrev(std::move(Abbv));
920 
921  // Abbrev for TYPE_CODE_ARRAY.
922  Abbv = std::make_shared<BitCodeAbbrev>();
924  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
925  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
926  unsigned ArrayAbbrev = Stream.EmitAbbrev(std::move(Abbv));
927 
928  // Emit an entry count so the reader can reserve space.
929  TypeVals.push_back(TypeList.size());
930  Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
931  TypeVals.clear();
932 
933  // Loop over all of the types, emitting each in turn.
934  for (Type *T : TypeList) {
935  int AbbrevToUse = 0;
936  unsigned Code = 0;
937 
938  switch (T->getTypeID()) {
952  case Type::IntegerTyID:
953  // INTEGER: [width]
955  TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
956  break;
957  case Type::PointerTyID: {
958  PointerType *PTy = cast<PointerType>(T);
959  unsigned AddressSpace = PTy->getAddressSpace();
960  if (PTy->isOpaque()) {
961  // OPAQUE_POINTER: [address space]
963  TypeVals.push_back(AddressSpace);
964  if (AddressSpace == 0)
965  AbbrevToUse = OpaquePtrAbbrev;
966  } else {
967  // POINTER: [pointee type, address space]
969  TypeVals.push_back(VE.getTypeID(PTy->getNonOpaquePointerElementType()));
970  TypeVals.push_back(AddressSpace);
971  if (AddressSpace == 0)
972  AbbrevToUse = PtrAbbrev;
973  }
974  break;
975  }
976  case Type::FunctionTyID: {
977  FunctionType *FT = cast<FunctionType>(T);
978  // FUNCTION: [isvararg, retty, paramty x N]
980  TypeVals.push_back(FT->isVarArg());
981  TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
982  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
983  TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
984  AbbrevToUse = FunctionAbbrev;
985  break;
986  }
987  case Type::StructTyID: {
988  StructType *ST = cast<StructType>(T);
989  // STRUCT: [ispacked, eltty x N]
990  TypeVals.push_back(ST->isPacked());
991  // Output all of the element types.
992  for (Type *ET : ST->elements())
993  TypeVals.push_back(VE.getTypeID(ET));
994 
995  if (ST->isLiteral()) {
997  AbbrevToUse = StructAnonAbbrev;
998  } else {
999  if (ST->isOpaque()) {
1001  } else {
1003  AbbrevToUse = StructNamedAbbrev;
1004  }
1005 
1006  // Emit the name if it is present.
1007  if (!ST->getName().empty())
1008  writeStringRecord(Stream, bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
1009  StructNameAbbrev);
1010  }
1011  break;
1012  }
1013  case Type::ArrayTyID: {
1014  ArrayType *AT = cast<ArrayType>(T);
1015  // ARRAY: [numelts, eltty]
1017  TypeVals.push_back(AT->getNumElements());
1018  TypeVals.push_back(VE.getTypeID(AT->getElementType()));
1019  AbbrevToUse = ArrayAbbrev;
1020  break;
1021  }
1022  case Type::FixedVectorTyID:
1023  case Type::ScalableVectorTyID: {
1024  VectorType *VT = cast<VectorType>(T);
1025  // VECTOR [numelts, eltty] or
1026  // [numelts, eltty, scalable]
1028  TypeVals.push_back(VT->getElementCount().getKnownMinValue());
1029  TypeVals.push_back(VE.getTypeID(VT->getElementType()));
1030  if (isa<ScalableVectorType>(VT))
1031  TypeVals.push_back(true);
1032  break;
1033  }
1035  llvm_unreachable("Typed pointers cannot be added to IR modules");
1036  }
1037 
1038  // Emit the finished record.
1039  Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
1040  TypeVals.clear();
1041  }
1042 
1043  Stream.ExitBlock();
1044 }
1045 
1047  switch (Linkage) {
1049  return 0;
1051  return 16;
1053  return 2;
1055  return 3;
1057  return 18;
1059  return 7;
1061  return 8;
1063  return 9;
1065  return 17;
1067  return 19;
1069  return 12;
1070  }
1071  llvm_unreachable("Invalid linkage");
1072 }
1073 
1074 static unsigned getEncodedLinkage(const GlobalValue &GV) {
1075  return getEncodedLinkage(GV.getLinkage());
1076 }
1077 
1079  uint64_t RawFlags = 0;
1080  RawFlags |= Flags.ReadNone;
1081  RawFlags |= (Flags.ReadOnly << 1);
1082  RawFlags |= (Flags.NoRecurse << 2);
1083  RawFlags |= (Flags.ReturnDoesNotAlias << 3);
1084  RawFlags |= (Flags.NoInline << 4);
1085  RawFlags |= (Flags.AlwaysInline << 5);
1086  RawFlags |= (Flags.NoUnwind << 6);
1087  RawFlags |= (Flags.MayThrow << 7);
1088  RawFlags |= (Flags.HasUnknownCall << 8);
1089  RawFlags |= (Flags.MustBeUnreachable << 9);
1090  return RawFlags;
1091 }
1092 
1093 // Decode the flags for GlobalValue in the summary. See getDecodedGVSummaryFlags
1094 // in BitcodeReader.cpp.
1096  uint64_t RawFlags = 0;
1097 
1098  RawFlags |= Flags.NotEligibleToImport; // bool
1099  RawFlags |= (Flags.Live << 1);
1100  RawFlags |= (Flags.DSOLocal << 2);
1101  RawFlags |= (Flags.CanAutoHide << 3);
1102 
1103  // Linkage don't need to be remapped at that time for the summary. Any future
1104  // change to the getEncodedLinkage() function will need to be taken into
1105  // account here as well.
1106  RawFlags = (RawFlags << 4) | Flags.Linkage; // 4 bits
1107 
1108  RawFlags |= (Flags.Visibility << 8); // 2 bits
1109 
1110  return RawFlags;
1111 }
1112 
1114  uint64_t RawFlags = Flags.MaybeReadOnly | (Flags.MaybeWriteOnly << 1) |
1115  (Flags.Constant << 2) | Flags.VCallVisibility << 3;
1116  return RawFlags;
1117 }
1118 
1119 static unsigned getEncodedVisibility(const GlobalValue &GV) {
1120  switch (GV.getVisibility()) {
1121  case GlobalValue::DefaultVisibility: return 0;
1122  case GlobalValue::HiddenVisibility: return 1;
1123  case GlobalValue::ProtectedVisibility: return 2;
1124  }
1125  llvm_unreachable("Invalid visibility");
1126 }
1127 
1128 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
1129  switch (GV.getDLLStorageClass()) {
1130  case GlobalValue::DefaultStorageClass: return 0;
1131  case GlobalValue::DLLImportStorageClass: return 1;
1132  case GlobalValue::DLLExportStorageClass: return 2;
1133  }
1134  llvm_unreachable("Invalid DLL storage class");
1135 }
1136 
1137 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
1138  switch (GV.getThreadLocalMode()) {
1139  case GlobalVariable::NotThreadLocal: return 0;
1141  case GlobalVariable::LocalDynamicTLSModel: return 2;
1142  case GlobalVariable::InitialExecTLSModel: return 3;
1143  case GlobalVariable::LocalExecTLSModel: return 4;
1144  }
1145  llvm_unreachable("Invalid TLS model");
1146 }
1147 
1148 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
1149  switch (C.getSelectionKind()) {
1150  case Comdat::Any:
1152  case Comdat::ExactMatch:
1154  case Comdat::Largest:
1156  case Comdat::NoDeduplicate:
1158  case Comdat::SameSize:
1160  }
1161  llvm_unreachable("Invalid selection kind");
1162 }
1163 
1164 static unsigned getEncodedUnnamedAddr(const GlobalValue &GV) {
1165  switch (GV.getUnnamedAddr()) {
1166  case GlobalValue::UnnamedAddr::None: return 0;
1167  case GlobalValue::UnnamedAddr::Local: return 2;
1168  case GlobalValue::UnnamedAddr::Global: return 1;
1169  }
1170  llvm_unreachable("Invalid unnamed_addr");
1171 }
1172 
1173 size_t ModuleBitcodeWriter::addToStrtab(StringRef Str) {
1174  if (GenerateHash)
1175  Hasher.update(Str);
1176  return StrtabBuilder.add(Str);
1177 }
1178 
1179 void ModuleBitcodeWriter::writeComdats() {
1181  for (const Comdat *C : VE.getComdats()) {
1182  // COMDAT: [strtab offset, strtab size, selection_kind]
1183  Vals.push_back(addToStrtab(C->getName()));
1184  Vals.push_back(C->getName().size());
1185  Vals.push_back(getEncodedComdatSelectionKind(*C));
1186  Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
1187  Vals.clear();
1188  }
1189 }
1190 
1191 /// Write a record that will eventually hold the word offset of the
1192 /// module-level VST. For now the offset is 0, which will be backpatched
1193 /// after the real VST is written. Saves the bit offset to backpatch.
1194 void ModuleBitcodeWriter::writeValueSymbolTableForwardDecl() {
1195  // Write a placeholder value in for the offset of the real VST,
1196  // which is written after the function blocks so that it can include
1197  // the offset of each function. The placeholder offset will be
1198  // updated when the real VST is written.
1199  auto Abbv = std::make_shared<BitCodeAbbrev>();
1201  // Blocks are 32-bit aligned, so we can use a 32-bit word offset to
1202  // hold the real VST offset. Must use fixed instead of VBR as we don't
1203  // know how many VBR chunks to reserve ahead of time.
1204  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
1205  unsigned VSTOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1206 
1207  // Emit the placeholder
1208  uint64_t Vals[] = {bitc::MODULE_CODE_VSTOFFSET, 0};
1209  Stream.EmitRecordWithAbbrev(VSTOffsetAbbrev, Vals);
1210 
1211  // Compute and save the bit offset to the placeholder, which will be
1212  // patched when the real VST is written. We can simply subtract the 32-bit
1213  // fixed size from the current bit number to get the location to backpatch.
1214  VSTOffsetPlaceholder = Stream.GetCurrentBitNo() - 32;
1215 }
1216 
1218 
1219 /// Determine the encoding to use for the given string name and length.
1221  bool isChar6 = true;
1222  for (char C : Str) {
1223  if (isChar6)
1224  isChar6 = BitCodeAbbrevOp::isChar6(C);
1225  if ((unsigned char)C & 128)
1226  // don't bother scanning the rest.
1227  return SE_Fixed8;
1228  }
1229  if (isChar6)
1230  return SE_Char6;
1231  return SE_Fixed7;
1232 }
1233 
1234 static_assert(sizeof(GlobalValue::SanitizerMetadata) <= sizeof(unsigned),
1235  "Sanitizer Metadata is too large for naive serialization.");
1236 static unsigned
1238  return Meta.NoAddress | (Meta.NoHWAddress << 1) |
1239  (Meta.Memtag << 2) | (Meta.IsDynInit << 3);
1240 }
1241 
1242 /// Emit top-level description of module, including target triple, inline asm,
1243 /// descriptors for global variables, and function prototype info.
1244 /// Returns the bit offset to backpatch with the location of the real VST.
1245 void ModuleBitcodeWriter::writeModuleInfo() {
1246  // Emit various pieces of data attached to a module.
1247  if (!M.getTargetTriple().empty())
1248  writeStringRecord(Stream, bitc::MODULE_CODE_TRIPLE, M.getTargetTriple(),
1249  0 /*TODO*/);
1250  const std::string &DL = M.getDataLayoutStr();
1251  if (!DL.empty())
1252  writeStringRecord(Stream, bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/);
1253  if (!M.getModuleInlineAsm().empty())
1254  writeStringRecord(Stream, bitc::MODULE_CODE_ASM, M.getModuleInlineAsm(),
1255  0 /*TODO*/);
1256 
1257  // Emit information about sections and GC, computing how many there are. Also
1258  // compute the maximum alignment value.
1259  std::map<std::string, unsigned> SectionMap;
1260  std::map<std::string, unsigned> GCMap;
1261  MaybeAlign MaxAlignment;
1262  unsigned MaxGlobalType = 0;
1263  const auto UpdateMaxAlignment = [&MaxAlignment](const MaybeAlign A) {
1264  if (A)
1265  MaxAlignment = !MaxAlignment ? *A : std::max(*MaxAlignment, *A);
1266  };
1267  for (const GlobalVariable &GV : M.globals()) {
1268  UpdateMaxAlignment(GV.getAlign());
1269  MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getValueType()));
1270  if (GV.hasSection()) {
1271  // Give section names unique ID's.
1272  unsigned &Entry = SectionMap[std::string(GV.getSection())];
1273  if (!Entry) {
1274  writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
1275  0 /*TODO*/);
1276  Entry = SectionMap.size();
1277  }
1278  }
1279  }
1280  for (const Function &F : M) {
1281  UpdateMaxAlignment(F.getAlign());
1282  if (F.hasSection()) {
1283  // Give section names unique ID's.
1284  unsigned &Entry = SectionMap[std::string(F.getSection())];
1285  if (!Entry) {
1286  writeStringRecord(Stream, bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
1287  0 /*TODO*/);
1288  Entry = SectionMap.size();
1289  }
1290  }
1291  if (F.hasGC()) {
1292  // Same for GC names.
1293  unsigned &Entry = GCMap[F.getGC()];
1294  if (!Entry) {
1295  writeStringRecord(Stream, bitc::MODULE_CODE_GCNAME, F.getGC(),
1296  0 /*TODO*/);
1297  Entry = GCMap.size();
1298  }
1299  }
1300  }
1301 
1302  // Emit abbrev for globals, now that we know # sections and max alignment.
1303  unsigned SimpleGVarAbbrev = 0;
1304  if (!M.global_empty()) {
1305  // Add an abbrev for common globals with no visibility or thread localness.
1306  auto Abbv = std::make_shared<BitCodeAbbrev>();
1308  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1309  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1311  Log2_32_Ceil(MaxGlobalType+1)));
1312  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // AddrSpace << 2
1313  //| explicitType << 1
1314  //| constant
1315  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
1316  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 5)); // Linkage.
1317  if (!MaxAlignment) // Alignment.
1318  Abbv->Add(BitCodeAbbrevOp(0));
1319  else {
1320  unsigned MaxEncAlignment = getEncodedAlign(MaxAlignment);
1322  Log2_32_Ceil(MaxEncAlignment+1)));
1323  }
1324  if (SectionMap.empty()) // Section.
1325  Abbv->Add(BitCodeAbbrevOp(0));
1326  else
1328  Log2_32_Ceil(SectionMap.size()+1)));
1329  // Don't bother emitting vis + thread local.
1330  SimpleGVarAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1331  }
1332 
1334  // Emit the module's source file name.
1335  {
1336  StringEncoding Bits = getStringEncoding(M.getSourceFileName());
1338  if (Bits == SE_Char6)
1339  AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Char6);
1340  else if (Bits == SE_Fixed7)
1341  AbbrevOpToUse = BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7);
1342 
1343  // MODULE_CODE_SOURCE_FILENAME: [namechar x N]
1344  auto Abbv = std::make_shared<BitCodeAbbrev>();
1347  Abbv->Add(AbbrevOpToUse);
1348  unsigned FilenameAbbrev = Stream.EmitAbbrev(std::move(Abbv));
1349 
1350  for (const auto P : M.getSourceFileName())
1351  Vals.push_back((unsigned char)P);
1352 
1353  // Emit the finished record.
1354  Stream.EmitRecord(bitc::MODULE_CODE_SOURCE_FILENAME, Vals, FilenameAbbrev);
1355  Vals.clear();
1356  }
1357 
1358  // Emit the global variable information.
1359  for (const GlobalVariable &GV : M.globals()) {
1360  unsigned AbbrevToUse = 0;
1361 
1362  // GLOBALVAR: [strtab offset, strtab size, type, isconst, initid,
1363  // linkage, alignment, section, visibility, threadlocal,
1364  // unnamed_addr, externally_initialized, dllstorageclass,
1365  // comdat, attributes, DSO_Local, GlobalSanitizer]
1366  Vals.push_back(addToStrtab(GV.getName()));
1367  Vals.push_back(GV.getName().size());
1368  Vals.push_back(VE.getTypeID(GV.getValueType()));
1369  Vals.push_back(GV.getType()->getAddressSpace() << 2 | 2 | GV.isConstant());
1370  Vals.push_back(GV.isDeclaration() ? 0 :
1371  (VE.getValueID(GV.getInitializer()) + 1));
1372  Vals.push_back(getEncodedLinkage(GV));
1373  Vals.push_back(getEncodedAlign(GV.getAlign()));
1374  Vals.push_back(GV.hasSection() ? SectionMap[std::string(GV.getSection())]
1375  : 0);
1376  if (GV.isThreadLocal() ||
1377  GV.getVisibility() != GlobalValue::DefaultVisibility ||
1378  GV.getUnnamedAddr() != GlobalValue::UnnamedAddr::None ||
1379  GV.isExternallyInitialized() ||
1380  GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
1381  GV.hasComdat() || GV.hasAttributes() || GV.isDSOLocal() ||
1382  GV.hasPartition() || GV.hasSanitizerMetadata()) {
1383  Vals.push_back(getEncodedVisibility(GV));
1384  Vals.push_back(getEncodedThreadLocalMode(GV));
1385  Vals.push_back(getEncodedUnnamedAddr(GV));
1386  Vals.push_back(GV.isExternallyInitialized());
1387  Vals.push_back(getEncodedDLLStorageClass(GV));
1388  Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
1389 
1390  auto AL = GV.getAttributesAsList(AttributeList::FunctionIndex);
1391  Vals.push_back(VE.getAttributeListID(AL));
1392 
1393  Vals.push_back(GV.isDSOLocal());
1394  Vals.push_back(addToStrtab(GV.getPartition()));
1395  Vals.push_back(GV.getPartition().size());
1396 
1397  Vals.push_back((GV.hasSanitizerMetadata() ? serializeSanitizerMetadata(
1398  GV.getSanitizerMetadata())
1399  : 0));
1400  } else {
1401  AbbrevToUse = SimpleGVarAbbrev;
1402  }
1403 
1404  Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
1405  Vals.clear();
1406  }
1407 
1408  // Emit the function proto information.
1409  for (const Function &F : M) {
1410  // FUNCTION: [strtab offset, strtab size, type, callingconv, isproto,
1411  // linkage, paramattrs, alignment, section, visibility, gc,
1412  // unnamed_addr, prologuedata, dllstorageclass, comdat,
1413  // prefixdata, personalityfn, DSO_Local, addrspace]
1414  Vals.push_back(addToStrtab(F.getName()));
1415  Vals.push_back(F.getName().size());
1416  Vals.push_back(VE.getTypeID(F.getFunctionType()));
1417  Vals.push_back(F.getCallingConv());
1418  Vals.push_back(F.isDeclaration());
1419  Vals.push_back(getEncodedLinkage(F));
1420  Vals.push_back(VE.getAttributeListID(F.getAttributes()));
1421  Vals.push_back(getEncodedAlign(F.getAlign()));
1422  Vals.push_back(F.hasSection() ? SectionMap[std::string(F.getSection())]
1423  : 0);
1424  Vals.push_back(getEncodedVisibility(F));
1425  Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
1426  Vals.push_back(getEncodedUnnamedAddr(F));
1427  Vals.push_back(F.hasPrologueData() ? (VE.getValueID(F.getPrologueData()) + 1)
1428  : 0);
1429  Vals.push_back(getEncodedDLLStorageClass(F));
1430  Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
1431  Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
1432  : 0);
1433  Vals.push_back(
1434  F.hasPersonalityFn() ? (VE.getValueID(F.getPersonalityFn()) + 1) : 0);
1435 
1436  Vals.push_back(F.isDSOLocal());
1437  Vals.push_back(F.getAddressSpace());
1438  Vals.push_back(addToStrtab(F.getPartition()));
1439  Vals.push_back(F.getPartition().size());
1440 
1441  unsigned AbbrevToUse = 0;
1442  Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
1443  Vals.clear();
1444  }
1445 
1446  // Emit the alias information.
1447  for (const GlobalAlias &A : M.aliases()) {
1448  // ALIAS: [strtab offset, strtab size, alias type, aliasee val#, linkage,
1449  // visibility, dllstorageclass, threadlocal, unnamed_addr,
1450  // DSO_Local]
1451  Vals.push_back(addToStrtab(A.getName()));
1452  Vals.push_back(A.getName().size());
1453  Vals.push_back(VE.getTypeID(A.getValueType()));
1454  Vals.push_back(A.getType()->getAddressSpace());
1455  Vals.push_back(VE.getValueID(A.getAliasee()));
1456  Vals.push_back(getEncodedLinkage(A));
1457  Vals.push_back(getEncodedVisibility(A));
1458  Vals.push_back(getEncodedDLLStorageClass(A));
1459  Vals.push_back(getEncodedThreadLocalMode(A));
1460  Vals.push_back(getEncodedUnnamedAddr(A));
1461  Vals.push_back(A.isDSOLocal());
1462  Vals.push_back(addToStrtab(A.getPartition()));
1463  Vals.push_back(A.getPartition().size());
1464 
1465  unsigned AbbrevToUse = 0;
1466  Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
1467  Vals.clear();
1468  }
1469 
1470  // Emit the ifunc information.
1471  for (const GlobalIFunc &I : M.ifuncs()) {
1472  // IFUNC: [strtab offset, strtab size, ifunc type, address space, resolver
1473  // val#, linkage, visibility, DSO_Local]
1474  Vals.push_back(addToStrtab(I.getName()));
1475  Vals.push_back(I.getName().size());
1476  Vals.push_back(VE.getTypeID(I.getValueType()));
1477  Vals.push_back(I.getType()->getAddressSpace());
1478  Vals.push_back(VE.getValueID(I.getResolver()));
1479  Vals.push_back(getEncodedLinkage(I));
1480  Vals.push_back(getEncodedVisibility(I));
1481  Vals.push_back(I.isDSOLocal());
1482  Vals.push_back(addToStrtab(I.getPartition()));
1483  Vals.push_back(I.getPartition().size());
1484  Stream.EmitRecord(bitc::MODULE_CODE_IFUNC, Vals);
1485  Vals.clear();
1486  }
1487 
1488  writeValueSymbolTableForwardDecl();
1489 }
1490 
1492  uint64_t Flags = 0;
1493 
1494  if (const auto *OBO = dyn_cast<OverflowingBinaryOperator>(V)) {
1495  if (OBO->hasNoSignedWrap())
1496  Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
1497  if (OBO->hasNoUnsignedWrap())
1498  Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
1499  } else if (const auto *PEO = dyn_cast<PossiblyExactOperator>(V)) {
1500  if (PEO->isExact())
1501  Flags |= 1 << bitc::PEO_EXACT;
1502  } else if (const auto *FPMO = dyn_cast<FPMathOperator>(V)) {
1503  if (FPMO->hasAllowReassoc())
1504  Flags |= bitc::AllowReassoc;
1505  if (FPMO->hasNoNaNs())
1506  Flags |= bitc::NoNaNs;
1507  if (FPMO->hasNoInfs())
1508  Flags |= bitc::NoInfs;
1509  if (FPMO->hasNoSignedZeros())
1510  Flags |= bitc::NoSignedZeros;
1511  if (FPMO->hasAllowReciprocal())
1512  Flags |= bitc::AllowReciprocal;
1513  if (FPMO->hasAllowContract())
1514  Flags |= bitc::AllowContract;
1515  if (FPMO->hasApproxFunc())
1516  Flags |= bitc::ApproxFunc;
1517  }
1518 
1519  return Flags;
1520 }
1521 
1522 void ModuleBitcodeWriter::writeValueAsMetadata(
1524  // Mimic an MDNode with a value as one operand.
1525  Value *V = MD->getValue();
1526  Record.push_back(VE.getTypeID(V->getType()));
1527  Record.push_back(VE.getValueID(V));
1529  Record.clear();
1530 }
1531 
1534  unsigned Abbrev) {
1535  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1536  Metadata *MD = N->getOperand(i);
1537  assert(!(MD && isa<LocalAsMetadata>(MD)) &&
1538  "Unexpected function-local metadata");
1539  Record.push_back(VE.getMetadataOrNullID(MD));
1540  }
1541  Stream.EmitRecord(N->isDistinct() ? bitc::METADATA_DISTINCT_NODE
1543  Record, Abbrev);
1544  Record.clear();
1545 }
1546 
1547 unsigned ModuleBitcodeWriter::createDILocationAbbrev() {
1548  // Assume the column is usually under 128, and always output the inlined-at
1549  // location (it's never more expensive than building an array size 1).
1550  auto Abbv = std::make_shared<BitCodeAbbrev>();
1552  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1553  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1554  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
1555  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1556  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1557  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1558  return Stream.EmitAbbrev(std::move(Abbv));
1559 }
1560 
1563  unsigned &Abbrev) {
1564  if (!Abbrev)
1565  Abbrev = createDILocationAbbrev();
1566 
1567  Record.push_back(N->isDistinct());
1568  Record.push_back(N->getLine());
1569  Record.push_back(N->getColumn());
1570  Record.push_back(VE.getMetadataID(N->getScope()));
1571  Record.push_back(VE.getMetadataOrNullID(N->getInlinedAt()));
1572  Record.push_back(N->isImplicitCode());
1573 
1574  Stream.EmitRecord(bitc::METADATA_LOCATION, Record, Abbrev);
1575  Record.clear();
1576 }
1577 
1578 unsigned ModuleBitcodeWriter::createGenericDINodeAbbrev() {
1579  // Assume the column is usually under 128, and always output the inlined-at
1580  // location (it's never more expensive than building an array size 1).
1581  auto Abbv = std::make_shared<BitCodeAbbrev>();
1583  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1584  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1585  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
1586  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1588  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
1589  return Stream.EmitAbbrev(std::move(Abbv));
1590 }
1591 
1594  unsigned &Abbrev) {
1595  if (!Abbrev)
1596  Abbrev = createGenericDINodeAbbrev();
1597 
1598  Record.push_back(N->isDistinct());
1599  Record.push_back(N->getTag());
1600  Record.push_back(0); // Per-tag version field; unused for now.
1601 
1602  for (auto &I : N->operands())
1603  Record.push_back(VE.getMetadataOrNullID(I));
1604 
1606  Record.clear();
1607 }
1608 
1611  unsigned Abbrev) {
1612  const uint64_t Version = 2 << 1;
1613  Record.push_back((uint64_t)N->isDistinct() | Version);
1614  Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1615  Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1616  Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1617  Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1618 
1619  Stream.EmitRecord(bitc::METADATA_SUBRANGE, Record, Abbrev);
1620  Record.clear();
1621 }
1622 
1625  unsigned Abbrev) {
1626  Record.push_back((uint64_t)N->isDistinct());
1627  Record.push_back(VE.getMetadataOrNullID(N->getRawCountNode()));
1628  Record.push_back(VE.getMetadataOrNullID(N->getRawLowerBound()));
1629  Record.push_back(VE.getMetadataOrNullID(N->getRawUpperBound()));
1630  Record.push_back(VE.getMetadataOrNullID(N->getRawStride()));
1631 
1633  Record.clear();
1634 }
1635 
1637  if ((int64_t)V >= 0)
1638  Vals.push_back(V << 1);
1639  else
1640  Vals.push_back((-V << 1) | 1);
1641 }
1642 
1643 static void emitWideAPInt(SmallVectorImpl<uint64_t> &Vals, const APInt &A) {
1644  // We have an arbitrary precision integer value to write whose
1645  // bit width is > 64. However, in canonical unsigned integer
1646  // format it is likely that the high bits are going to be zero.
1647  // So, we only write the number of active words.
1648  unsigned NumWords = A.getActiveWords();
1649  const uint64_t *RawData = A.getRawData();
1650  for (unsigned i = 0; i < NumWords; i++)
1651  emitSignedInt64(Vals, RawData[i]);
1652 }
1653 
1656  unsigned Abbrev) {
1657  const uint64_t IsBigInt = 1 << 2;
1658  Record.push_back(IsBigInt | (N->isUnsigned() << 1) | N->isDistinct());
1659  Record.push_back(N->getValue().getBitWidth());
1660  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1661  emitWideAPInt(Record, N->getValue());
1662 
1663  Stream.EmitRecord(bitc::METADATA_ENUMERATOR, Record, Abbrev);
1664  Record.clear();
1665 }
1666 
1669  unsigned Abbrev) {
1670  Record.push_back(N->isDistinct());
1671  Record.push_back(N->getTag());
1672  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1673  Record.push_back(N->getSizeInBits());
1674  Record.push_back(N->getAlignInBits());
1675  Record.push_back(N->getEncoding());
1676  Record.push_back(N->getFlags());
1677 
1678  Stream.EmitRecord(bitc::METADATA_BASIC_TYPE, Record, Abbrev);
1679  Record.clear();
1680 }
1681 
1684  unsigned Abbrev) {
1685  Record.push_back(N->isDistinct());
1686  Record.push_back(N->getTag());
1687  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1688  Record.push_back(VE.getMetadataOrNullID(N->getStringLength()));
1689  Record.push_back(VE.getMetadataOrNullID(N->getStringLengthExp()));
1690  Record.push_back(VE.getMetadataOrNullID(N->getStringLocationExp()));
1691  Record.push_back(N->getSizeInBits());
1692  Record.push_back(N->getAlignInBits());
1693  Record.push_back(N->getEncoding());
1694 
1695  Stream.EmitRecord(bitc::METADATA_STRING_TYPE, Record, Abbrev);
1696  Record.clear();
1697 }
1698 
1701  unsigned Abbrev) {
1702  Record.push_back(N->isDistinct());
1703  Record.push_back(N->getTag());
1704  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1705  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1706  Record.push_back(N->getLine());
1707  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1708  Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1709  Record.push_back(N->getSizeInBits());
1710  Record.push_back(N->getAlignInBits());
1711  Record.push_back(N->getOffsetInBits());
1712  Record.push_back(N->getFlags());
1713  Record.push_back(VE.getMetadataOrNullID(N->getExtraData()));
1714 
1715  // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1716  // that there is no DWARF address space associated with DIDerivedType.
1717  if (const auto &DWARFAddressSpace = N->getDWARFAddressSpace())
1718  Record.push_back(*DWARFAddressSpace + 1);
1719  else
1720  Record.push_back(0);
1721 
1722  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1723 
1725  Record.clear();
1726 }
1727 
1730  unsigned Abbrev) {
1731  const unsigned IsNotUsedInOldTypeRef = 0x2;
1732  Record.push_back(IsNotUsedInOldTypeRef | (unsigned)N->isDistinct());
1733  Record.push_back(N->getTag());
1734  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1735  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1736  Record.push_back(N->getLine());
1737  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1738  Record.push_back(VE.getMetadataOrNullID(N->getBaseType()));
1739  Record.push_back(N->getSizeInBits());
1740  Record.push_back(N->getAlignInBits());
1741  Record.push_back(N->getOffsetInBits());
1742  Record.push_back(N->getFlags());
1743  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1744  Record.push_back(N->getRuntimeLang());
1745  Record.push_back(VE.getMetadataOrNullID(N->getVTableHolder()));
1746  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1747  Record.push_back(VE.getMetadataOrNullID(N->getRawIdentifier()));
1748  Record.push_back(VE.getMetadataOrNullID(N->getDiscriminator()));
1749  Record.push_back(VE.getMetadataOrNullID(N->getRawDataLocation()));
1750  Record.push_back(VE.getMetadataOrNullID(N->getRawAssociated()));
1751  Record.push_back(VE.getMetadataOrNullID(N->getRawAllocated()));
1752  Record.push_back(VE.getMetadataOrNullID(N->getRawRank()));
1753  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1754 
1756  Record.clear();
1757 }
1758 
1761  unsigned Abbrev) {
1762  const unsigned HasNoOldTypeRefs = 0x2;
1763  Record.push_back(HasNoOldTypeRefs | (unsigned)N->isDistinct());
1764  Record.push_back(N->getFlags());
1765  Record.push_back(VE.getMetadataOrNullID(N->getTypeArray().get()));
1766  Record.push_back(N->getCC());
1767 
1769  Record.clear();
1770 }
1771 
1774  unsigned Abbrev) {
1775  Record.push_back(N->isDistinct());
1776  Record.push_back(VE.getMetadataOrNullID(N->getRawFilename()));
1777  Record.push_back(VE.getMetadataOrNullID(N->getRawDirectory()));
1778  if (N->getRawChecksum()) {
1779  Record.push_back(N->getRawChecksum()->Kind);
1780  Record.push_back(VE.getMetadataOrNullID(N->getRawChecksum()->Value));
1781  } else {
1782  // Maintain backwards compatibility with the old internal representation of
1783  // CSK_None in ChecksumKind by writing nulls here when Checksum is None.
1784  Record.push_back(0);
1785  Record.push_back(VE.getMetadataOrNullID(nullptr));
1786  }
1787  auto Source = N->getRawSource();
1788  if (Source)
1789  Record.push_back(VE.getMetadataOrNullID(*Source));
1790 
1791  Stream.EmitRecord(bitc::METADATA_FILE, Record, Abbrev);
1792  Record.clear();
1793 }
1794 
1797  unsigned Abbrev) {
1798  assert(N->isDistinct() && "Expected distinct compile units");
1799  Record.push_back(/* IsDistinct */ true);
1800  Record.push_back(N->getSourceLanguage());
1801  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1802  Record.push_back(VE.getMetadataOrNullID(N->getRawProducer()));
1803  Record.push_back(N->isOptimized());
1804  Record.push_back(VE.getMetadataOrNullID(N->getRawFlags()));
1805  Record.push_back(N->getRuntimeVersion());
1806  Record.push_back(VE.getMetadataOrNullID(N->getRawSplitDebugFilename()));
1807  Record.push_back(N->getEmissionKind());
1808  Record.push_back(VE.getMetadataOrNullID(N->getEnumTypes().get()));
1809  Record.push_back(VE.getMetadataOrNullID(N->getRetainedTypes().get()));
1810  Record.push_back(/* subprograms */ 0);
1811  Record.push_back(VE.getMetadataOrNullID(N->getGlobalVariables().get()));
1812  Record.push_back(VE.getMetadataOrNullID(N->getImportedEntities().get()));
1813  Record.push_back(N->getDWOId());
1814  Record.push_back(VE.getMetadataOrNullID(N->getMacros().get()));
1815  Record.push_back(N->getSplitDebugInlining());
1816  Record.push_back(N->getDebugInfoForProfiling());
1817  Record.push_back((unsigned)N->getNameTableKind());
1818  Record.push_back(N->getRangesBaseAddress());
1819  Record.push_back(VE.getMetadataOrNullID(N->getRawSysRoot()));
1820  Record.push_back(VE.getMetadataOrNullID(N->getRawSDK()));
1821 
1823  Record.clear();
1824 }
1825 
1828  unsigned Abbrev) {
1829  const uint64_t HasUnitFlag = 1 << 1;
1830  const uint64_t HasSPFlagsFlag = 1 << 2;
1831  Record.push_back(uint64_t(N->isDistinct()) | HasUnitFlag | HasSPFlagsFlag);
1832  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1833  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1834  Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1835  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1836  Record.push_back(N->getLine());
1837  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1838  Record.push_back(N->getScopeLine());
1839  Record.push_back(VE.getMetadataOrNullID(N->getContainingType()));
1840  Record.push_back(N->getSPFlags());
1841  Record.push_back(N->getVirtualIndex());
1842  Record.push_back(N->getFlags());
1843  Record.push_back(VE.getMetadataOrNullID(N->getRawUnit()));
1844  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams().get()));
1845  Record.push_back(VE.getMetadataOrNullID(N->getDeclaration()));
1846  Record.push_back(VE.getMetadataOrNullID(N->getRetainedNodes().get()));
1847  Record.push_back(N->getThisAdjustment());
1848  Record.push_back(VE.getMetadataOrNullID(N->getThrownTypes().get()));
1849  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1850  Record.push_back(VE.getMetadataOrNullID(N->getRawTargetFuncName()));
1851 
1852  Stream.EmitRecord(bitc::METADATA_SUBPROGRAM, Record, Abbrev);
1853  Record.clear();
1854 }
1855 
1858  unsigned Abbrev) {
1859  Record.push_back(N->isDistinct());
1860  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1861  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1862  Record.push_back(N->getLine());
1863  Record.push_back(N->getColumn());
1864 
1866  Record.clear();
1867 }
1868 
1871  unsigned Abbrev) {
1872  Record.push_back(N->isDistinct());
1873  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1874  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1875  Record.push_back(N->getDiscriminator());
1876 
1878  Record.clear();
1879 }
1880 
1883  unsigned Abbrev) {
1884  Record.push_back(N->isDistinct());
1885  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1886  Record.push_back(VE.getMetadataOrNullID(N->getDecl()));
1887  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1888  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1889  Record.push_back(N->getLineNo());
1890 
1892  Record.clear();
1893 }
1894 
1897  unsigned Abbrev) {
1898  Record.push_back(N->isDistinct() | N->getExportSymbols() << 1);
1899  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1900  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1901 
1902  Stream.EmitRecord(bitc::METADATA_NAMESPACE, Record, Abbrev);
1903  Record.clear();
1904 }
1905 
1908  unsigned Abbrev) {
1909  Record.push_back(N->isDistinct());
1910  Record.push_back(N->getMacinfoType());
1911  Record.push_back(N->getLine());
1912  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1913  Record.push_back(VE.getMetadataOrNullID(N->getRawValue()));
1914 
1915  Stream.EmitRecord(bitc::METADATA_MACRO, Record, Abbrev);
1916  Record.clear();
1917 }
1918 
1921  unsigned Abbrev) {
1922  Record.push_back(N->isDistinct());
1923  Record.push_back(N->getMacinfoType());
1924  Record.push_back(N->getLine());
1925  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1926  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
1927 
1928  Stream.EmitRecord(bitc::METADATA_MACRO_FILE, Record, Abbrev);
1929  Record.clear();
1930 }
1931 
1934  unsigned Abbrev) {
1935  Record.reserve(N->getArgs().size());
1936  for (ValueAsMetadata *MD : N->getArgs())
1937  Record.push_back(VE.getMetadataID(MD));
1938 
1939  Stream.EmitRecord(bitc::METADATA_ARG_LIST, Record, Abbrev);
1940  Record.clear();
1941 }
1942 
1945  unsigned Abbrev) {
1946  Record.push_back(N->isDistinct());
1947  for (auto &I : N->operands())
1948  Record.push_back(VE.getMetadataOrNullID(I));
1949  Record.push_back(N->getLineNo());
1950  Record.push_back(N->getIsDecl());
1951 
1952  Stream.EmitRecord(bitc::METADATA_MODULE, Record, Abbrev);
1953  Record.clear();
1954 }
1955 
1958  unsigned Abbrev) {
1959  Record.push_back(N->isDistinct());
1960  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1961  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1962  Record.push_back(N->isDefault());
1963 
1965  Record.clear();
1966 }
1967 
1970  unsigned Abbrev) {
1971  Record.push_back(N->isDistinct());
1972  Record.push_back(N->getTag());
1973  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1974  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1975  Record.push_back(N->isDefault());
1976  Record.push_back(VE.getMetadataOrNullID(N->getValue()));
1977 
1979  Record.clear();
1980 }
1981 
1984  unsigned Abbrev) {
1985  const uint64_t Version = 2 << 1;
1986  Record.push_back((uint64_t)N->isDistinct() | Version);
1987  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
1988  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
1989  Record.push_back(VE.getMetadataOrNullID(N->getRawLinkageName()));
1990  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
1991  Record.push_back(N->getLine());
1992  Record.push_back(VE.getMetadataOrNullID(N->getType()));
1993  Record.push_back(N->isLocalToUnit());
1994  Record.push_back(N->isDefinition());
1995  Record.push_back(VE.getMetadataOrNullID(N->getStaticDataMemberDeclaration()));
1996  Record.push_back(VE.getMetadataOrNullID(N->getTemplateParams()));
1997  Record.push_back(N->getAlignInBits());
1998  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
1999 
2000  Stream.EmitRecord(bitc::METADATA_GLOBAL_VAR, Record, Abbrev);
2001  Record.clear();
2002 }
2003 
2006  unsigned Abbrev) {
2007  // In order to support all possible bitcode formats in BitcodeReader we need
2008  // to distinguish the following cases:
2009  // 1) Record has no artificial tag (Record[1]),
2010  // has no obsolete inlinedAt field (Record[9]).
2011  // In this case Record size will be 8, HasAlignment flag is false.
2012  // 2) Record has artificial tag (Record[1]),
2013  // has no obsolete inlignedAt field (Record[9]).
2014  // In this case Record size will be 9, HasAlignment flag is false.
2015  // 3) Record has both artificial tag (Record[1]) and
2016  // obsolete inlignedAt field (Record[9]).
2017  // In this case Record size will be 10, HasAlignment flag is false.
2018  // 4) Record has neither artificial tag, nor inlignedAt field, but
2019  // HasAlignment flag is true and Record[8] contains alignment value.
2020  const uint64_t HasAlignmentFlag = 1 << 1;
2021  Record.push_back((uint64_t)N->isDistinct() | HasAlignmentFlag);
2022  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2023  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2024  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2025  Record.push_back(N->getLine());
2026  Record.push_back(VE.getMetadataOrNullID(N->getType()));
2027  Record.push_back(N->getArg());
2028  Record.push_back(N->getFlags());
2029  Record.push_back(N->getAlignInBits());
2030  Record.push_back(VE.getMetadataOrNullID(N->getAnnotations().get()));
2031 
2032  Stream.EmitRecord(bitc::METADATA_LOCAL_VAR, Record, Abbrev);
2033  Record.clear();
2034 }
2035 
2038  unsigned Abbrev) {
2039  Record.push_back((uint64_t)N->isDistinct());
2040  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2041  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2042  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2043  Record.push_back(N->getLine());
2044 
2045  Stream.EmitRecord(bitc::METADATA_LABEL, Record, Abbrev);
2046  Record.clear();
2047 }
2048 
2051  unsigned Abbrev) {
2052  Record.reserve(N->getElements().size() + 1);
2053  const uint64_t Version = 3 << 1;
2054  Record.push_back((uint64_t)N->isDistinct() | Version);
2055  Record.append(N->elements_begin(), N->elements_end());
2056 
2057  Stream.EmitRecord(bitc::METADATA_EXPRESSION, Record, Abbrev);
2058  Record.clear();
2059 }
2060 
2063  unsigned Abbrev) {
2064  Record.push_back(N->isDistinct());
2065  Record.push_back(VE.getMetadataOrNullID(N->getVariable()));
2066  Record.push_back(VE.getMetadataOrNullID(N->getExpression()));
2067 
2069  Record.clear();
2070 }
2071 
2074  unsigned Abbrev) {
2075  Record.push_back(N->isDistinct());
2076  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2077  Record.push_back(VE.getMetadataOrNullID(N->getFile()));
2078  Record.push_back(N->getLine());
2079  Record.push_back(VE.getMetadataOrNullID(N->getRawSetterName()));
2080  Record.push_back(VE.getMetadataOrNullID(N->getRawGetterName()));
2081  Record.push_back(N->getAttributes());
2082  Record.push_back(VE.getMetadataOrNullID(N->getType()));
2083 
2085  Record.clear();
2086 }
2087 
2090  unsigned Abbrev) {
2091  Record.push_back(N->isDistinct());
2092  Record.push_back(N->getTag());
2093  Record.push_back(VE.getMetadataOrNullID(N->getScope()));
2094  Record.push_back(VE.getMetadataOrNullID(N->getEntity()));
2095  Record.push_back(N->getLine());
2096  Record.push_back(VE.getMetadataOrNullID(N->getRawName()));
2097  Record.push_back(VE.getMetadataOrNullID(N->getRawFile()));
2098  Record.push_back(VE.getMetadataOrNullID(N->getElements().get()));
2099 
2101  Record.clear();
2102 }
2103 
2104 unsigned ModuleBitcodeWriter::createNamedMetadataAbbrev() {
2105  auto Abbv = std::make_shared<BitCodeAbbrev>();
2108  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2109  return Stream.EmitAbbrev(std::move(Abbv));
2110 }
2111 
2112 void ModuleBitcodeWriter::writeNamedMetadata(
2114  if (M.named_metadata_empty())
2115  return;
2116 
2117  unsigned Abbrev = createNamedMetadataAbbrev();
2118  for (const NamedMDNode &NMD : M.named_metadata()) {
2119  // Write name.
2120  StringRef Str = NMD.getName();
2121  Record.append(Str.bytes_begin(), Str.bytes_end());
2122  Stream.EmitRecord(bitc::METADATA_NAME, Record, Abbrev);
2123  Record.clear();
2124 
2125  // Write named metadata operands.
2126  for (const MDNode *N : NMD.operands())
2127  Record.push_back(VE.getMetadataID(N));
2129  Record.clear();
2130  }
2131 }
2132 
2133 unsigned ModuleBitcodeWriter::createMetadataStringsAbbrev() {
2134  auto Abbv = std::make_shared<BitCodeAbbrev>();
2136  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of strings
2137  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // offset to chars
2139  return Stream.EmitAbbrev(std::move(Abbv));
2140 }
2141 
2142 /// Write out a record for MDString.
2143 ///
2144 /// All the metadata strings in a metadata block are emitted in a single
2145 /// record. The sizes and strings themselves are shoved into a blob.
2146 void ModuleBitcodeWriter::writeMetadataStrings(
2148  if (Strings.empty())
2149  return;
2150 
2151  // Start the record with the number of strings.
2152  Record.push_back(bitc::METADATA_STRINGS);
2153  Record.push_back(Strings.size());
2154 
2155  // Emit the sizes of the strings in the blob.
2156  SmallString<256> Blob;
2157  {
2158  BitstreamWriter W(Blob);
2159  for (const Metadata *MD : Strings)
2160  W.EmitVBR(cast<MDString>(MD)->getLength(), 6);
2161  W.FlushToWord();
2162  }
2163 
2164  // Add the offset to the strings to the record.
2165  Record.push_back(Blob.size());
2166 
2167  // Add the strings to the blob.
2168  for (const Metadata *MD : Strings)
2169  Blob.append(cast<MDString>(MD)->getString());
2170 
2171  // Emit the final record.
2172  Stream.EmitRecordWithBlob(createMetadataStringsAbbrev(), Record, Blob);
2173  Record.clear();
2174 }
2175 
2176 // Generates an enum to use as an index in the Abbrev array of Metadata record.
2177 enum MetadataAbbrev : unsigned {
2178 #define HANDLE_MDNODE_LEAF(CLASS) CLASS##AbbrevID,
2179 #include "llvm/IR/Metadata.def"
2181 };
2182 
2183 void ModuleBitcodeWriter::writeMetadataRecords(
2185  std::vector<unsigned> *MDAbbrevs, std::vector<uint64_t> *IndexPos) {
2186  if (MDs.empty())
2187  return;
2188 
2189  // Initialize MDNode abbreviations.
2190 #define HANDLE_MDNODE_LEAF(CLASS) unsigned CLASS##Abbrev = 0;
2191 #include "llvm/IR/Metadata.def"
2192 
2193  for (const Metadata *MD : MDs) {
2194  if (IndexPos)
2195  IndexPos->push_back(Stream.GetCurrentBitNo());
2196  if (const MDNode *N = dyn_cast<MDNode>(MD)) {
2197  assert(N->isResolved() && "Expected forward references to be resolved");
2198 
2199  switch (N->getMetadataID()) {
2200  default:
2201  llvm_unreachable("Invalid MDNode subclass");
2202 #define HANDLE_MDNODE_LEAF(CLASS) \
2203  case Metadata::CLASS##Kind: \
2204  if (MDAbbrevs) \
2205  write##CLASS(cast<CLASS>(N), Record, \
2206  (*MDAbbrevs)[MetadataAbbrev::CLASS##AbbrevID]); \
2207  else \
2208  write##CLASS(cast<CLASS>(N), Record, CLASS##Abbrev); \
2209  continue;
2210 #include "llvm/IR/Metadata.def"
2211  }
2212  }
2213  writeValueAsMetadata(cast<ValueAsMetadata>(MD), Record);
2214  }
2215 }
2216 
2217 void ModuleBitcodeWriter::writeModuleMetadata() {
2218  if (!VE.hasMDs() && M.named_metadata_empty())
2219  return;
2220 
2223 
2224  // Emit all abbrevs upfront, so that the reader can jump in the middle of the
2225  // block and load any metadata.
2226  std::vector<unsigned> MDAbbrevs;
2227 
2228  MDAbbrevs.resize(MetadataAbbrev::LastPlusOne);
2229  MDAbbrevs[MetadataAbbrev::DILocationAbbrevID] = createDILocationAbbrev();
2230  MDAbbrevs[MetadataAbbrev::GenericDINodeAbbrevID] =
2231  createGenericDINodeAbbrev();
2232 
2233  auto Abbv = std::make_shared<BitCodeAbbrev>();
2235  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2236  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
2237  unsigned OffsetAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2238 
2239  Abbv = std::make_shared<BitCodeAbbrev>();
2242  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
2243  unsigned IndexAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2244 
2245  // Emit MDStrings together upfront.
2246  writeMetadataStrings(VE.getMDStrings(), Record);
2247 
2248  // We only emit an index for the metadata record if we have more than a given
2249  // (naive) threshold of metadatas, otherwise it is not worth it.
2250  if (VE.getNonMDStrings().size() > IndexThreshold) {
2251  // Write a placeholder value in for the offset of the metadata index,
2252  // which is written after the records, so that it can include
2253  // the offset of each entry. The placeholder offset will be
2254  // updated after all records are emitted.
2255  uint64_t Vals[] = {0, 0};
2256  Stream.EmitRecord(bitc::METADATA_INDEX_OFFSET, Vals, OffsetAbbrev);
2257  }
2258 
2259  // Compute and save the bit offset to the current position, which will be
2260  // patched when we emit the index later. We can simply subtract the 64-bit
2261  // fixed size from the current bit number to get the location to backpatch.
2262  uint64_t IndexOffsetRecordBitPos = Stream.GetCurrentBitNo();
2263 
2264  // This index will contain the bitpos for each individual record.
2265  std::vector<uint64_t> IndexPos;
2266  IndexPos.reserve(VE.getNonMDStrings().size());
2267 
2268  // Write all the records
2269  writeMetadataRecords(VE.getNonMDStrings(), Record, &MDAbbrevs, &IndexPos);
2270 
2271  if (VE.getNonMDStrings().size() > IndexThreshold) {
2272  // Now that we have emitted all the records we will emit the index. But
2273  // first
2274  // backpatch the forward reference so that the reader can skip the records
2275  // efficiently.
2276  Stream.BackpatchWord64(IndexOffsetRecordBitPos - 64,
2277  Stream.GetCurrentBitNo() - IndexOffsetRecordBitPos);
2278 
2279  // Delta encode the index.
2280  uint64_t PreviousValue = IndexOffsetRecordBitPos;
2281  for (auto &Elt : IndexPos) {
2282  auto EltDelta = Elt - PreviousValue;
2283  PreviousValue = Elt;
2284  Elt = EltDelta;
2285  }
2286  // Emit the index record.
2287  Stream.EmitRecord(bitc::METADATA_INDEX, IndexPos, IndexAbbrev);
2288  IndexPos.clear();
2289  }
2290 
2291  // Write the named metadata now.
2292  writeNamedMetadata(Record);
2293 
2294  auto AddDeclAttachedMetadata = [&](const GlobalObject &GO) {
2296  Record.push_back(VE.getValueID(&GO));
2297  pushGlobalMetadataAttachment(Record, GO);
2299  };
2300  for (const Function &F : M)
2301  if (F.isDeclaration() && F.hasMetadata())
2302  AddDeclAttachedMetadata(F);
2303  // FIXME: Only store metadata for declarations here, and move data for global
2304  // variable definitions to a separate block (PR28134).
2305  for (const GlobalVariable &GV : M.globals())
2306  if (GV.hasMetadata())
2307  AddDeclAttachedMetadata(GV);
2308 
2309  Stream.ExitBlock();
2310 }
2311 
2312 void ModuleBitcodeWriter::writeFunctionMetadata(const Function &F) {
2313  if (!VE.hasMDs())
2314  return;
2315 
2318  writeMetadataStrings(VE.getMDStrings(), Record);
2319  writeMetadataRecords(VE.getNonMDStrings(), Record);
2320  Stream.ExitBlock();
2321 }
2322 
2323 void ModuleBitcodeWriter::pushGlobalMetadataAttachment(
2325  // [n x [id, mdnode]]
2327  GO.getAllMetadata(MDs);
2328  for (const auto &I : MDs) {
2329  Record.push_back(I.first);
2330  Record.push_back(VE.getMetadataID(I.second));
2331  }
2332 }
2333 
2334 void ModuleBitcodeWriter::writeFunctionMetadataAttachment(const Function &F) {
2336 
2338 
2339  if (F.hasMetadata()) {
2340  pushGlobalMetadataAttachment(Record, F);
2342  Record.clear();
2343  }
2344 
2345  // Write metadata attachments
2346  // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
2348  for (const BasicBlock &BB : F)
2349  for (const Instruction &I : BB) {
2350  MDs.clear();
2351  I.getAllMetadataOtherThanDebugLoc(MDs);
2352 
2353  // If no metadata, ignore instruction.
2354  if (MDs.empty()) continue;
2355 
2356  Record.push_back(VE.getInstructionID(&I));
2357 
2358  for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
2359  Record.push_back(MDs[i].first);
2360  Record.push_back(VE.getMetadataID(MDs[i].second));
2361  }
2363  Record.clear();
2364  }
2365 
2366  Stream.ExitBlock();
2367 }
2368 
2369 void ModuleBitcodeWriter::writeModuleMetadataKinds() {
2371 
2372  // Write metadata kinds
2373  // METADATA_KIND - [n x [id, name]]
2375  M.getMDKindNames(Names);
2376 
2377  if (Names.empty()) return;
2378 
2380 
2381  for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
2382  Record.push_back(MDKindID);
2383  StringRef KName = Names[MDKindID];
2384  Record.append(KName.begin(), KName.end());
2385 
2387  Record.clear();
2388  }
2389 
2390  Stream.ExitBlock();
2391 }
2392 
2393 void ModuleBitcodeWriter::writeOperandBundleTags() {
2394  // Write metadata kinds
2395  //
2396  // OPERAND_BUNDLE_TAGS_BLOCK_ID : N x OPERAND_BUNDLE_TAG
2397  //
2398  // OPERAND_BUNDLE_TAG - [strchr x N]
2399 
2401  M.getOperandBundleTags(Tags);
2402 
2403  if (Tags.empty())
2404  return;
2405 
2407 
2409 
2410  for (auto Tag : Tags) {
2411  Record.append(Tag.begin(), Tag.end());
2412 
2414  Record.clear();
2415  }
2416 
2417  Stream.ExitBlock();
2418 }
2419 
2420 void ModuleBitcodeWriter::writeSyncScopeNames() {
2422  M.getContext().getSyncScopeNames(SSNs);
2423  if (SSNs.empty())
2424  return;
2425 
2427 
2429  for (auto SSN : SSNs) {
2430  Record.append(SSN.begin(), SSN.end());
2432  Record.clear();
2433  }
2434 
2435  Stream.ExitBlock();
2436 }
2437 
2438 void ModuleBitcodeWriter::writeConstants(unsigned FirstVal, unsigned LastVal,
2439  bool isGlobal) {
2440  if (FirstVal == LastVal) return;
2441 
2443 
2444  unsigned AggregateAbbrev = 0;
2445  unsigned String8Abbrev = 0;
2446  unsigned CString7Abbrev = 0;
2447  unsigned CString6Abbrev = 0;
2448  // If this is a constant pool for the module, emit module-specific abbrevs.
2449  if (isGlobal) {
2450  // Abbrev for CST_CODE_AGGREGATE.
2451  auto Abbv = std::make_shared<BitCodeAbbrev>();
2454  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
2455  AggregateAbbrev = Stream.EmitAbbrev(std::move(Abbv));
2456 
2457  // Abbrev for CST_CODE_STRING.
2458  Abbv = std::make_shared<BitCodeAbbrev>();
2461  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
2462  String8Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2463  // Abbrev for CST_CODE_CSTRING.
2464  Abbv = std::make_shared<BitCodeAbbrev>();
2467  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
2468  CString7Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2469  // Abbrev for CST_CODE_CSTRING.
2470  Abbv = std::make_shared<BitCodeAbbrev>();
2474  CString6Abbrev = Stream.EmitAbbrev(std::move(Abbv));
2475  }
2476 
2478 
2479  const ValueEnumerator::ValueList &Vals = VE.getValues();
2480  Type *LastTy = nullptr;
2481  for (unsigned i = FirstVal; i != LastVal; ++i) {
2482  const Value *V = Vals[i].first;
2483  // If we need to switch types, do so now.
2484  if (V->getType() != LastTy) {
2485  LastTy = V->getType();
2486  Record.push_back(VE.getTypeID(LastTy));
2488  CONSTANTS_SETTYPE_ABBREV);
2489  Record.clear();
2490  }
2491 
2492  if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
2493  Record.push_back(VE.getTypeID(IA->getFunctionType()));
2494  Record.push_back(
2495  unsigned(IA->hasSideEffects()) | unsigned(IA->isAlignStack()) << 1 |
2496  unsigned(IA->getDialect() & 1) << 2 | unsigned(IA->canThrow()) << 3);
2497 
2498  // Add the asm string.
2499  const std::string &AsmStr = IA->getAsmString();
2500  Record.push_back(AsmStr.size());
2501  Record.append(AsmStr.begin(), AsmStr.end());
2502 
2503  // Add the constraint string.
2504  const std::string &ConstraintStr = IA->getConstraintString();
2505  Record.push_back(ConstraintStr.size());
2506  Record.append(ConstraintStr.begin(), ConstraintStr.end());
2508  Record.clear();
2509  continue;
2510  }
2511  const Constant *C = cast<Constant>(V);
2512  unsigned Code = -1U;
2513  unsigned AbbrevToUse = 0;
2514  if (C->isNullValue()) {
2516  } else if (isa<PoisonValue>(C)) {
2518  } else if (isa<UndefValue>(C)) {
2520  } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
2521  if (IV->getBitWidth() <= 64) {
2522  uint64_t V = IV->getSExtValue();
2523  emitSignedInt64(Record, V);
2525  AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
2526  } else { // Wide integers, > 64 bits in size.
2527  emitWideAPInt(Record, IV->getValue());
2529  }
2530  } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
2532  Type *Ty = CFP->getType();
2533  if (Ty->isHalfTy() || Ty->isBFloatTy() || Ty->isFloatTy() ||
2534  Ty->isDoubleTy()) {
2535  Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
2536  } else if (Ty->isX86_FP80Ty()) {
2537  // api needed to prevent premature destruction
2538  // bits are not in the same order as a normal i80 APInt, compensate.
2539  APInt api = CFP->getValueAPF().bitcastToAPInt();
2540  const uint64_t *p = api.getRawData();
2541  Record.push_back((p[1] << 48) | (p[0] >> 16));
2542  Record.push_back(p[0] & 0xffffLL);
2543  } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
2544  APInt api = CFP->getValueAPF().bitcastToAPInt();
2545  const uint64_t *p = api.getRawData();
2546  Record.push_back(p[0]);
2547  Record.push_back(p[1]);
2548  } else {
2549  assert(0 && "Unknown FP type!");
2550  }
2551  } else if (isa<ConstantDataSequential>(C) &&
2552  cast<ConstantDataSequential>(C)->isString()) {
2553  const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
2554  // Emit constant strings specially.
2555  unsigned NumElts = Str->getNumElements();
2556  // If this is a null-terminated string, use the denser CSTRING encoding.
2557  if (Str->isCString()) {
2559  --NumElts; // Don't encode the null, which isn't allowed by char6.
2560  } else {
2562  AbbrevToUse = String8Abbrev;
2563  }
2564  bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
2565  bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
2566  for (unsigned i = 0; i != NumElts; ++i) {
2567  unsigned char V = Str->getElementAsInteger(i);
2568  Record.push_back(V);
2569  isCStr7 &= (V & 128) == 0;
2570  if (isCStrChar6)
2571  isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
2572  }
2573 
2574  if (isCStrChar6)
2575  AbbrevToUse = CString6Abbrev;
2576  else if (isCStr7)
2577  AbbrevToUse = CString7Abbrev;
2578  } else if (const ConstantDataSequential *CDS =
2579  dyn_cast<ConstantDataSequential>(C)) {
2581  Type *EltTy = CDS->getElementType();
2582  if (isa<IntegerType>(EltTy)) {
2583  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2584  Record.push_back(CDS->getElementAsInteger(i));
2585  } else {
2586  for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
2587  Record.push_back(
2588  CDS->getElementAsAPFloat(i).bitcastToAPInt().getLimitedValue());
2589  }
2590  } else if (isa<ConstantAggregate>(C)) {
2592  for (const Value *Op : C->operands())
2593  Record.push_back(VE.getValueID(Op));
2594  AbbrevToUse = AggregateAbbrev;
2595  } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2596  switch (CE->getOpcode()) {
2597  default:
2598  if (Instruction::isCast(CE->getOpcode())) {
2600  Record.push_back(getEncodedCastOpcode(CE->getOpcode()));
2601  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2602  Record.push_back(VE.getValueID(C->getOperand(0)));
2603  AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
2604  } else {
2605  assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
2607  Record.push_back(getEncodedBinaryOpcode(CE->getOpcode()));
2608  Record.push_back(VE.getValueID(C->getOperand(0)));
2609  Record.push_back(VE.getValueID(C->getOperand(1)));
2610  uint64_t Flags = getOptimizationFlags(CE);
2611  if (Flags != 0)
2612  Record.push_back(Flags);
2613  }
2614  break;
2615  case Instruction::FNeg: {
2616  assert(CE->getNumOperands() == 1 && "Unknown constant expr!");
2618  Record.push_back(getEncodedUnaryOpcode(CE->getOpcode()));
2619  Record.push_back(VE.getValueID(C->getOperand(0)));
2620  uint64_t Flags = getOptimizationFlags(CE);
2621  if (Flags != 0)
2622  Record.push_back(Flags);
2623  break;
2624  }
2625  case Instruction::GetElementPtr: {
2627  const auto *GO = cast<GEPOperator>(C);
2628  Record.push_back(VE.getTypeID(GO->getSourceElementType()));
2629  if (Optional<unsigned> Idx = GO->getInRangeIndex()) {
2631  Record.push_back((*Idx << 1) | GO->isInBounds());
2632  } else if (GO->isInBounds())
2634  for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
2635  Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
2636  Record.push_back(VE.getValueID(C->getOperand(i)));
2637  }
2638  break;
2639  }
2640  case Instruction::Select:
2642  Record.push_back(VE.getValueID(C->getOperand(0)));
2643  Record.push_back(VE.getValueID(C->getOperand(1)));
2644  Record.push_back(VE.getValueID(C->getOperand(2)));
2645  break;
2646  case Instruction::ExtractElement:
2648  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2649  Record.push_back(VE.getValueID(C->getOperand(0)));
2650  Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
2651  Record.push_back(VE.getValueID(C->getOperand(1)));
2652  break;
2653  case Instruction::InsertElement:
2655  Record.push_back(VE.getValueID(C->getOperand(0)));
2656  Record.push_back(VE.getValueID(C->getOperand(1)));
2657  Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
2658  Record.push_back(VE.getValueID(C->getOperand(2)));
2659  break;
2660  case Instruction::ShuffleVector:
2661  // If the return type and argument types are the same, this is a
2662  // standard shufflevector instruction. If the types are different,
2663  // then the shuffle is widening or truncating the input vectors, and
2664  // the argument type must also be encoded.
2665  if (C->getType() == C->getOperand(0)->getType()) {
2667  } else {
2669  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2670  }
2671  Record.push_back(VE.getValueID(C->getOperand(0)));
2672  Record.push_back(VE.getValueID(C->getOperand(1)));
2673  Record.push_back(VE.getValueID(CE->getShuffleMaskForBitcode()));
2674  break;
2675  case Instruction::ICmp:
2676  case Instruction::FCmp:
2678  Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
2679  Record.push_back(VE.getValueID(C->getOperand(0)));
2680  Record.push_back(VE.getValueID(C->getOperand(1)));
2681  Record.push_back(CE->getPredicate());
2682  break;
2683  }
2684  } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
2686  Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
2687  Record.push_back(VE.getValueID(BA->getFunction()));
2688  Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
2689  } else if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C)) {
2691  Record.push_back(VE.getTypeID(Equiv->getGlobalValue()->getType()));
2692  Record.push_back(VE.getValueID(Equiv->getGlobalValue()));
2693  } else if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
2695  Record.push_back(VE.getTypeID(NC->getGlobalValue()->getType()));
2696  Record.push_back(VE.getValueID(NC->getGlobalValue()));
2697  } else {
2698 #ifndef NDEBUG
2699  C->dump();
2700 #endif
2701  llvm_unreachable("Unknown constant!");
2702  }
2703  Stream.EmitRecord(Code, Record, AbbrevToUse);
2704  Record.clear();
2705  }
2706 
2707  Stream.ExitBlock();
2708 }
2709 
2710 void ModuleBitcodeWriter::writeModuleConstants() {
2711  const ValueEnumerator::ValueList &Vals = VE.getValues();
2712 
2713  // Find the first constant to emit, which is the first non-globalvalue value.
2714  // We know globalvalues have been emitted by WriteModuleInfo.
2715  for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
2716  if (!isa<GlobalValue>(Vals[i].first)) {
2717  writeConstants(i, Vals.size(), true);
2718  return;
2719  }
2720  }
2721 }
2722 
2723 /// pushValueAndType - The file has to encode both the value and type id for
2724 /// many values, because we need to know what type to create for forward
2725 /// references. However, most operands are not forward references, so this type
2726 /// field is not needed.
2727 ///
2728 /// This function adds V's value ID to Vals. If the value ID is higher than the
2729 /// instruction ID, then it is a forward reference, and it also includes the
2730 /// type ID. The value ID that is written is encoded relative to the InstID.
2731 bool ModuleBitcodeWriter::pushValueAndType(const Value *V, unsigned InstID,
2732  SmallVectorImpl<unsigned> &Vals) {
2733  unsigned ValID = VE.getValueID(V);
2734  // Make encoding relative to the InstID.
2735  Vals.push_back(InstID - ValID);
2736  if (ValID >= InstID) {
2737  Vals.push_back(VE.getTypeID(V->getType()));
2738  return true;
2739  }
2740  return false;
2741 }
2742 
2743 void ModuleBitcodeWriter::writeOperandBundles(const CallBase &CS,
2744  unsigned InstID) {
2746  LLVMContext &C = CS.getContext();
2747 
2748  for (unsigned i = 0, e = CS.getNumOperandBundles(); i != e; ++i) {
2749  const auto &Bundle = CS.getOperandBundleAt(i);
2750  Record.push_back(C.getOperandBundleTagID(Bundle.getTagName()));
2751 
2752  for (auto &Input : Bundle.Inputs)
2753  pushValueAndType(Input, InstID, Record);
2754 
2756  Record.clear();
2757  }
2758 }
2759 
2760 /// pushValue - Like pushValueAndType, but where the type of the value is
2761 /// omitted (perhaps it was already encoded in an earlier operand).
2762 void ModuleBitcodeWriter::pushValue(const Value *V, unsigned InstID,
2763  SmallVectorImpl<unsigned> &Vals) {
2764  unsigned ValID = VE.getValueID(V);
2765  Vals.push_back(InstID - ValID);
2766 }
2767 
2768 void ModuleBitcodeWriter::pushValueSigned(const Value *V, unsigned InstID,
2769  SmallVectorImpl<uint64_t> &Vals) {
2770  unsigned ValID = VE.getValueID(V);
2771  int64_t diff = ((int32_t)InstID - (int32_t)ValID);
2772  emitSignedInt64(Vals, diff);
2773 }
2774 
2775 /// WriteInstruction - Emit an instruction to the specified stream.
2776 void ModuleBitcodeWriter::writeInstruction(const Instruction &I,
2777  unsigned InstID,
2778  SmallVectorImpl<unsigned> &Vals) {
2779  unsigned Code = 0;
2780  unsigned AbbrevToUse = 0;
2781  VE.setInstructionID(&I);
2782  switch (I.getOpcode()) {
2783  default:
2784  if (Instruction::isCast(I.getOpcode())) {
2786  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2787  AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
2788  Vals.push_back(VE.getTypeID(I.getType()));
2789  Vals.push_back(getEncodedCastOpcode(I.getOpcode()));
2790  } else {
2791  assert(isa<BinaryOperator>(I) && "Unknown instruction!");
2793  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2794  AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
2795  pushValue(I.getOperand(1), InstID, Vals);
2796  Vals.push_back(getEncodedBinaryOpcode(I.getOpcode()));
2797  uint64_t Flags = getOptimizationFlags(&I);
2798  if (Flags != 0) {
2799  if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
2800  AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
2801  Vals.push_back(Flags);
2802  }
2803  }
2804  break;
2805  case Instruction::FNeg: {
2807  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2808  AbbrevToUse = FUNCTION_INST_UNOP_ABBREV;
2809  Vals.push_back(getEncodedUnaryOpcode(I.getOpcode()));
2810  uint64_t Flags = getOptimizationFlags(&I);
2811  if (Flags != 0) {
2812  if (AbbrevToUse == FUNCTION_INST_UNOP_ABBREV)
2813  AbbrevToUse = FUNCTION_INST_UNOP_FLAGS_ABBREV;
2814  Vals.push_back(Flags);
2815  }
2816  break;
2817  }
2818  case Instruction::GetElementPtr: {
2820  AbbrevToUse = FUNCTION_INST_GEP_ABBREV;
2821  auto &GEPInst = cast<GetElementPtrInst>(I);
2822  Vals.push_back(GEPInst.isInBounds());
2823  Vals.push_back(VE.getTypeID(GEPInst.getSourceElementType()));
2824  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
2825  pushValueAndType(I.getOperand(i), InstID, Vals);
2826  break;
2827  }
2828  case Instruction::ExtractValue: {
2830  pushValueAndType(I.getOperand(0), InstID, Vals);
2831  const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
2832  Vals.append(EVI->idx_begin(), EVI->idx_end());
2833  break;
2834  }
2835  case Instruction::InsertValue: {
2837  pushValueAndType(I.getOperand(0), InstID, Vals);
2838  pushValueAndType(I.getOperand(1), InstID, Vals);
2839  const InsertValueInst *IVI = cast<InsertValueInst>(&I);
2840  Vals.append(IVI->idx_begin(), IVI->idx_end());
2841  break;
2842  }
2843  case Instruction::Select: {
2845  pushValueAndType(I.getOperand(1), InstID, Vals);
2846  pushValue(I.getOperand(2), InstID, Vals);
2847  pushValueAndType(I.getOperand(0), InstID, Vals);
2848  uint64_t Flags = getOptimizationFlags(&I);
2849  if (Flags != 0)
2850  Vals.push_back(Flags);
2851  break;
2852  }
2853  case Instruction::ExtractElement:
2855  pushValueAndType(I.getOperand(0), InstID, Vals);
2856  pushValueAndType(I.getOperand(1), InstID, Vals);
2857  break;
2858  case Instruction::InsertElement:
2860  pushValueAndType(I.getOperand(0), InstID, Vals);
2861  pushValue(I.getOperand(1), InstID, Vals);
2862  pushValueAndType(I.getOperand(2), InstID, Vals);
2863  break;
2864  case Instruction::ShuffleVector:
2866  pushValueAndType(I.getOperand(0), InstID, Vals);
2867  pushValue(I.getOperand(1), InstID, Vals);
2868  pushValue(cast<ShuffleVectorInst>(I).getShuffleMaskForBitcode(), InstID,
2869  Vals);
2870  break;
2871  case Instruction::ICmp:
2872  case Instruction::FCmp: {
2873  // compare returning Int1Ty or vector of Int1Ty
2875  pushValueAndType(I.getOperand(0), InstID, Vals);
2876  pushValue(I.getOperand(1), InstID, Vals);
2877  Vals.push_back(cast<CmpInst>(I).getPredicate());
2878  uint64_t Flags = getOptimizationFlags(&I);
2879  if (Flags != 0)
2880  Vals.push_back(Flags);
2881  break;
2882  }
2883 
2884  case Instruction::Ret:
2885  {
2887  unsigned NumOperands = I.getNumOperands();
2888  if (NumOperands == 0)
2889  AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
2890  else if (NumOperands == 1) {
2891  if (!pushValueAndType(I.getOperand(0), InstID, Vals))
2892  AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
2893  } else {
2894  for (unsigned i = 0, e = NumOperands; i != e; ++i)
2895  pushValueAndType(I.getOperand(i), InstID, Vals);
2896  }
2897  }
2898  break;
2899  case Instruction::Br:
2900  {
2902  const BranchInst &II = cast<BranchInst>(I);
2903  Vals.push_back(VE.getValueID(II.getSuccessor(0)));
2904  if (II.isConditional()) {
2905  Vals.push_back(VE.getValueID(II.getSuccessor(1)));
2906  pushValue(II.getCondition(), InstID, Vals);
2907  }
2908  }
2909  break;
2910  case Instruction::Switch:
2911  {
2913  const SwitchInst &SI = cast<SwitchInst>(I);
2914  Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
2915  pushValue(SI.getCondition(), InstID, Vals);
2916  Vals.push_back(VE.getValueID(SI.getDefaultDest()));
2917  for (auto Case : SI.cases()) {
2918  Vals.push_back(VE.getValueID(Case.getCaseValue()));
2919  Vals.push_back(VE.getValueID(Case.getCaseSuccessor()));
2920  }
2921  }
2922  break;
2923  case Instruction::IndirectBr:
2925  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
2926  // Encode the address operand as relative, but not the basic blocks.
2927  pushValue(I.getOperand(0), InstID, Vals);
2928  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
2929  Vals.push_back(VE.getValueID(I.getOperand(i)));
2930  break;
2931 
2932  case Instruction::Invoke: {
2933  const InvokeInst *II = cast<InvokeInst>(&I);
2934  const Value *Callee = II->getCalledOperand();
2935  FunctionType *FTy = II->getFunctionType();
2936 
2937  if (II->hasOperandBundles())
2938  writeOperandBundles(*II, InstID);
2939 
2941 
2942  Vals.push_back(VE.getAttributeListID(II->getAttributes()));
2943  Vals.push_back(II->getCallingConv() | 1 << 13);
2944  Vals.push_back(VE.getValueID(II->getNormalDest()));
2945  Vals.push_back(VE.getValueID(II->getUnwindDest()));
2946  Vals.push_back(VE.getTypeID(FTy));
2947  pushValueAndType(Callee, InstID, Vals);
2948 
2949  // Emit value #'s for the fixed parameters.
2950  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
2951  pushValue(I.getOperand(i), InstID, Vals); // fixed param.
2952 
2953  // Emit type/value pairs for varargs params.
2954  if (FTy->isVarArg()) {
2955  for (unsigned i = FTy->getNumParams(), e = II->arg_size(); i != e; ++i)
2956  pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
2957  }
2958  break;
2959  }
2960  case Instruction::Resume:
2962  pushValueAndType(I.getOperand(0), InstID, Vals);
2963  break;
2964  case Instruction::CleanupRet: {
2966  const auto &CRI = cast<CleanupReturnInst>(I);
2967  pushValue(CRI.getCleanupPad(), InstID, Vals);
2968  if (CRI.hasUnwindDest())
2969  Vals.push_back(VE.getValueID(CRI.getUnwindDest()));
2970  break;
2971  }
2972  case Instruction::CatchRet: {
2974  const auto &CRI = cast<CatchReturnInst>(I);
2975  pushValue(CRI.getCatchPad(), InstID, Vals);
2976  Vals.push_back(VE.getValueID(CRI.getSuccessor()));
2977  break;
2978  }
2979  case Instruction::CleanupPad:
2980  case Instruction::CatchPad: {
2981  const auto &FuncletPad = cast<FuncletPadInst>(I);
2982  Code = isa<CatchPadInst>(FuncletPad) ? bitc::FUNC_CODE_INST_CATCHPAD
2984  pushValue(FuncletPad.getParentPad(), InstID, Vals);
2985 
2986  unsigned NumArgOperands = FuncletPad.getNumArgOperands();
2987  Vals.push_back(NumArgOperands);
2988  for (unsigned Op = 0; Op != NumArgOperands; ++Op)
2989  pushValueAndType(FuncletPad.getArgOperand(Op), InstID, Vals);
2990  break;
2991  }
2992  case Instruction::CatchSwitch: {
2994  const auto &CatchSwitch = cast<CatchSwitchInst>(I);
2995 
2996  pushValue(CatchSwitch.getParentPad(), InstID, Vals);
2997 
2998  unsigned NumHandlers = CatchSwitch.getNumHandlers();
2999  Vals.push_back(NumHandlers);
3000  for (const BasicBlock *CatchPadBB : CatchSwitch.handlers())
3001  Vals.push_back(VE.getValueID(CatchPadBB));
3002 
3003  if (CatchSwitch.hasUnwindDest())
3004  Vals.push_back(VE.getValueID(CatchSwitch.getUnwindDest()));
3005  break;
3006  }
3007  case Instruction::CallBr: {
3008  const CallBrInst *CBI = cast<CallBrInst>(&I);
3009  const Value *Callee = CBI->getCalledOperand();
3010  FunctionType *FTy = CBI->getFunctionType();
3011 
3012  if (CBI->hasOperandBundles())
3013  writeOperandBundles(*CBI, InstID);
3014 
3016 
3017  Vals.push_back(VE.getAttributeListID(CBI->getAttributes()));
3018 
3019  Vals.push_back(CBI->getCallingConv() << bitc::CALL_CCONV |
3021 
3022  Vals.push_back(VE.getValueID(CBI->getDefaultDest()));
3023  Vals.push_back(CBI->getNumIndirectDests());
3024  for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
3025  Vals.push_back(VE.getValueID(CBI->getIndirectDest(i)));
3026 
3027  Vals.push_back(VE.getTypeID(FTy));
3028  pushValueAndType(Callee, InstID, Vals);
3029 
3030  // Emit value #'s for the fixed parameters.
3031  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
3032  pushValue(I.getOperand(i), InstID, Vals); // fixed param.
3033 
3034  // Emit type/value pairs for varargs params.
3035  if (FTy->isVarArg()) {
3036  for (unsigned i = FTy->getNumParams(), e = CBI->arg_size(); i != e; ++i)
3037  pushValueAndType(I.getOperand(i), InstID, Vals); // vararg
3038  }
3039  break;
3040  }
3041  case Instruction::Unreachable:
3043  AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
3044  break;
3045 
3046  case Instruction::PHI: {
3047  const PHINode &PN = cast<PHINode>(I);
3049  // With the newer instruction encoding, forward references could give
3050  // negative valued IDs. This is most common for PHIs, so we use
3051  // signed VBRs.
3053  Vals64.push_back(VE.getTypeID(PN.getType()));
3054  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3055  pushValueSigned(PN.getIncomingValue(i), InstID, Vals64);
3056  Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
3057  }
3058 
3059  uint64_t Flags = getOptimizationFlags(&I);
3060  if (Flags != 0)
3061  Vals64.push_back(Flags);
3062 
3063  // Emit a Vals64 vector and exit.
3064  Stream.EmitRecord(Code, Vals64, AbbrevToUse);
3065  Vals64.clear();
3066  return;
3067  }
3068 
3069  case Instruction::LandingPad: {
3070  const LandingPadInst &LP = cast<LandingPadInst>(I);
3072  Vals.push_back(VE.getTypeID(LP.getType()));
3073  Vals.push_back(LP.isCleanup());
3074  Vals.push_back(LP.getNumClauses());
3075  for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
3076  if (LP.isCatch(I))
3077  Vals.push_back(LandingPadInst::Catch);
3078  else
3079  Vals.push_back(LandingPadInst::Filter);
3080  pushValueAndType(LP.getClause(I), InstID, Vals);
3081  }
3082  break;
3083  }
3084 
3085  case Instruction::Alloca: {
3087  const AllocaInst &AI = cast<AllocaInst>(I);
3088  Vals.push_back(VE.getTypeID(AI.getAllocatedType()));
3089  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
3090  Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
3091  using APV = AllocaPackedValues;
3092  unsigned Record = 0;
3093  unsigned EncodedAlign = getEncodedAlign(AI.getAlign());
3094  Bitfield::set<APV::AlignLower>(
3095  Record, EncodedAlign & ((1 << APV::AlignLower::Bits) - 1));
3096  Bitfield::set<APV::AlignUpper>(Record,
3097  EncodedAlign >> APV::AlignLower::Bits);
3098  Bitfield::set<APV::UsedWithInAlloca>(Record, AI.isUsedWithInAlloca());
3099  Bitfield::set<APV::ExplicitType>(Record, true);
3100  Bitfield::set<APV::SwiftError>(Record, AI.isSwiftError());
3101  Vals.push_back(Record);
3102 
3103  unsigned AS = AI.getAddressSpace();
3104  if (AS != M.getDataLayout().getAllocaAddrSpace())
3105  Vals.push_back(AS);
3106  break;
3107  }
3108 
3109  case Instruction::Load:
3110  if (cast<LoadInst>(I).isAtomic()) {
3112  pushValueAndType(I.getOperand(0), InstID, Vals);
3113  } else {
3115  if (!pushValueAndType(I.getOperand(0), InstID, Vals)) // ptr
3116  AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
3117  }
3118  Vals.push_back(VE.getTypeID(I.getType()));
3119  Vals.push_back(getEncodedAlign(cast<LoadInst>(I).getAlign()));
3120  Vals.push_back(cast<LoadInst>(I).isVolatile());
3121  if (cast<LoadInst>(I).isAtomic()) {
3122  Vals.push_back(getEncodedOrdering(cast<LoadInst>(I).getOrdering()));
3123  Vals.push_back(getEncodedSyncScopeID(cast<LoadInst>(I).getSyncScopeID()));
3124  }
3125  break;
3126  case Instruction::Store:
3127  if (cast<StoreInst>(I).isAtomic())
3129  else
3131  pushValueAndType(I.getOperand(1), InstID, Vals); // ptrty + ptr
3132  pushValueAndType(I.getOperand(0), InstID, Vals); // valty + val
3133  Vals.push_back(getEncodedAlign(cast<StoreInst>(I).getAlign()));
3134  Vals.push_back(cast<StoreInst>(I).isVolatile());
3135  if (cast<StoreInst>(I).isAtomic()) {
3136  Vals.push_back(getEncodedOrdering(cast<StoreInst>(I).getOrdering()));
3137  Vals.push_back(
3138  getEncodedSyncScopeID(cast<StoreInst>(I).getSyncScopeID()));
3139  }
3140  break;
3141  case Instruction::AtomicCmpXchg:
3143  pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3144  pushValueAndType(I.getOperand(1), InstID, Vals); // cmp.
3145  pushValue(I.getOperand(2), InstID, Vals); // newval.
3146  Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
3147  Vals.push_back(
3148  getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
3149  Vals.push_back(
3150  getEncodedSyncScopeID(cast<AtomicCmpXchgInst>(I).getSyncScopeID()));
3151  Vals.push_back(
3152  getEncodedOrdering(cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
3153  Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
3154  Vals.push_back(getEncodedAlign(cast<AtomicCmpXchgInst>(I).getAlign()));
3155  break;
3156  case Instruction::AtomicRMW:
3158  pushValueAndType(I.getOperand(0), InstID, Vals); // ptrty + ptr
3159  pushValueAndType(I.getOperand(1), InstID, Vals); // valty + val
3160  Vals.push_back(
3161  getEncodedRMWOperation(cast<AtomicRMWInst>(I).getOperation()));
3162  Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
3163  Vals.push_back(getEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
3164  Vals.push_back(
3165  getEncodedSyncScopeID(cast<AtomicRMWInst>(I).getSyncScopeID()));
3166  Vals.push_back(getEncodedAlign(cast<AtomicRMWInst>(I).getAlign()));
3167  break;
3168  case Instruction::Fence:
3170  Vals.push_back(getEncodedOrdering(cast<FenceInst>(I).getOrdering()));
3171  Vals.push_back(getEncodedSyncScopeID(cast<FenceInst>(I).getSyncScopeID()));
3172  break;
3173  case Instruction::Call: {
3174  const CallInst &CI = cast<CallInst>(I);
3175  FunctionType *FTy = CI.getFunctionType();
3176 
3177  if (CI.hasOperandBundles())
3178  writeOperandBundles(CI, InstID);
3179 
3181 
3182  Vals.push_back(VE.getAttributeListID(CI.getAttributes()));
3183 
3184  unsigned Flags = getOptimizationFlags(&I);
3185  Vals.push_back(CI.getCallingConv() << bitc::CALL_CCONV |
3186  unsigned(CI.isTailCall()) << bitc::CALL_TAIL |
3187  unsigned(CI.isMustTailCall()) << bitc::CALL_MUSTTAIL |
3189  unsigned(CI.isNoTailCall()) << bitc::CALL_NOTAIL |
3190  unsigned(Flags != 0) << bitc::CALL_FMF);
3191  if (Flags != 0)
3192  Vals.push_back(Flags);
3193 
3194  Vals.push_back(VE.getTypeID(FTy));
3195  pushValueAndType(CI.getCalledOperand(), InstID, Vals); // Callee
3196 
3197  // Emit value #'s for the fixed parameters.
3198  for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
3199  // Check for labels (can happen with asm labels).
3200  if (FTy->getParamType(i)->isLabelTy())
3201  Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
3202  else
3203  pushValue(CI.getArgOperand(i), InstID, Vals); // fixed param.
3204  }
3205 
3206  // Emit type/value pairs for varargs params.
3207  if (FTy->isVarArg()) {
3208  for (unsigned i = FTy->getNumParams(), e = CI.arg_size(); i != e; ++i)
3209  pushValueAndType(CI.getArgOperand(i), InstID, Vals); // varargs
3210  }
3211  break;
3212  }
3213  case Instruction::VAArg:
3215  Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
3216  pushValue(I.getOperand(0), InstID, Vals); // valist.
3217  Vals.push_back(VE.getTypeID(I.getType())); // restype.
3218  break;
3219  case Instruction::Freeze:
3221  pushValueAndType(I.getOperand(0), InstID, Vals);
3222  break;
3223  }
3224 
3225  Stream.EmitRecord(Code, Vals, AbbrevToUse);
3226  Vals.clear();
3227 }
3228 
3229 /// Write a GlobalValue VST to the module. The purpose of this data structure is
3230 /// to allow clients to efficiently find the function body.
3231 void ModuleBitcodeWriter::writeGlobalValueSymbolTable(
3232  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3233  // Get the offset of the VST we are writing, and backpatch it into
3234  // the VST forward declaration record.
3235  uint64_t VSTOffset = Stream.GetCurrentBitNo();
3236  // The BitcodeStartBit was the stream offset of the identification block.
3237  VSTOffset -= bitcodeStartBit();
3238  assert((VSTOffset & 31) == 0 && "VST block not 32-bit aligned");
3239  // Note that we add 1 here because the offset is relative to one word
3240  // before the start of the identification block, which was historically
3241  // always the start of the regular bitcode header.
3242  Stream.BackpatchWord(VSTOffsetPlaceholder, VSTOffset / 32 + 1);
3243 
3245 
3246  auto Abbv = std::make_shared<BitCodeAbbrev>();
3248  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3249  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // funcoffset
3250  unsigned FnEntryAbbrev = Stream.EmitAbbrev(std::move(Abbv));
3251 
3252  for (const Function &F : M) {
3253  uint64_t Record[2];
3254 
3255  if (F.isDeclaration())
3256  continue;
3257 
3258  Record[0] = VE.getValueID(&F);
3259 
3260  // Save the word offset of the function (from the start of the
3261  // actual bitcode written to the stream).
3262  uint64_t BitcodeIndex = FunctionToBitcodeIndex[&F] - bitcodeStartBit();
3263  assert((BitcodeIndex & 31) == 0 && "function block not 32-bit aligned");
3264  // Note that we add 1 here because the offset is relative to one word
3265  // before the start of the identification block, which was historically
3266  // always the start of the regular bitcode header.
3267  Record[1] = BitcodeIndex / 32 + 1;
3268 
3269  Stream.EmitRecord(bitc::VST_CODE_FNENTRY, Record, FnEntryAbbrev);
3270  }
3271 
3272  Stream.ExitBlock();
3273 }
3274 
3275 /// Emit names for arguments, instructions and basic blocks in a function.
3276 void ModuleBitcodeWriter::writeFunctionLevelValueSymbolTable(
3277  const ValueSymbolTable &VST) {
3278  if (VST.empty())
3279  return;
3280 
3282 
3283  // FIXME: Set up the abbrev, we know how many values there are!
3284  // FIXME: We know if the type names can use 7-bit ascii.
3285  SmallVector<uint64_t, 64> NameVals;
3286 
3287  for (const ValueName &Name : VST) {
3288  // Figure out the encoding to use for the name.
3290 
3291  unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
3292  NameVals.push_back(VE.getValueID(Name.getValue()));
3293 
3294  // VST_CODE_ENTRY: [valueid, namechar x N]
3295  // VST_CODE_BBENTRY: [bbid, namechar x N]
3296  unsigned Code;
3297  if (isa<BasicBlock>(Name.getValue())) {
3299  if (Bits == SE_Char6)
3300  AbbrevToUse = VST_BBENTRY_6_ABBREV;
3301  } else {
3303  if (Bits == SE_Char6)
3304  AbbrevToUse = VST_ENTRY_6_ABBREV;
3305  else if (Bits == SE_Fixed7)
3306  AbbrevToUse = VST_ENTRY_7_ABBREV;
3307  }
3308 
3309  for (const auto P : Name.getKey())
3310  NameVals.push_back((unsigned char)P);
3311 
3312  // Emit the finished record.
3313  Stream.EmitRecord(Code, NameVals, AbbrevToUse);
3314  NameVals.clear();
3315  }
3316 
3317  Stream.ExitBlock();
3318 }
3319 
3320 void ModuleBitcodeWriter::writeUseList(UseListOrder &&Order) {
3321  assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
3322  unsigned Code;
3323  if (isa<BasicBlock>(Order.V))
3325  else
3327 
3328  SmallVector<uint64_t, 64> Record(Order.Shuffle.begin(), Order.Shuffle.end());
3329  Record.push_back(VE.getValueID(Order.V));
3330  Stream.EmitRecord(Code, Record);
3331 }
3332 
3333 void ModuleBitcodeWriter::writeUseListBlock(const Function *F) {
3335  "Expected to be preserving use-list order");
3336 
3337  auto hasMore = [&]() {
3338  return !VE.UseListOrders.empty() && VE.UseListOrders.back().F == F;
3339  };
3340  if (!hasMore())
3341  // Nothing to do.
3342  return;
3343 
3345  while (hasMore()) {
3346  writeUseList(std::move(VE.UseListOrders.back()));
3347  VE.UseListOrders.pop_back();
3348  }
3349  Stream.ExitBlock();
3350 }
3351 
3352 /// Emit a function body to the module stream.
3353 void ModuleBitcodeWriter::writeFunction(
3354  const Function &F,
3355  DenseMap<const Function *, uint64_t> &FunctionToBitcodeIndex) {
3356  // Save the bitcode index of the start of this function block for recording
3357  // in the VST.
3358  FunctionToBitcodeIndex[&F] = Stream.GetCurrentBitNo();
3359 
3361  VE.incorporateFunction(F);
3362 
3364 
3365  // Emit the number of basic blocks, so the reader can create them ahead of
3366  // time.
3367  Vals.push_back(VE.getBasicBlocks().size());
3369  Vals.clear();
3370 
3371  // If there are function-local constants, emit them now.
3372  unsigned CstStart, CstEnd;
3373  VE.getFunctionConstantRange(CstStart, CstEnd);
3374  writeConstants(CstStart, CstEnd, false);
3375 
3376  // If there is function-local metadata, emit it now.
3377  writeFunctionMetadata(F);
3378 
3379  // Keep a running idea of what the instruction ID is.
3380  unsigned InstID = CstEnd;
3381 
3382  bool NeedsMetadataAttachment = F.hasMetadata();
3383 
3384  DILocation *LastDL = nullptr;
3385  SmallSetVector<Function *, 4> BlockAddressUsers;
3386 
3387  // Finally, emit all the instructions, in order.
3388  for (const BasicBlock &BB : F) {
3389  for (const Instruction &I : BB) {
3390  writeInstruction(I, InstID, Vals);
3391 
3392  if (!I.getType()->isVoidTy())
3393  ++InstID;
3394 
3395  // If the instruction has metadata, write a metadata attachment later.
3396  NeedsMetadataAttachment |= I.hasMetadataOtherThanDebugLoc();
3397 
3398  // If the instruction has a debug location, emit it.
3399  DILocation *DL = I.getDebugLoc();
3400  if (!DL)
3401  continue;
3402 
3403  if (DL == LastDL) {
3404  // Just repeat the same debug loc as last time.
3406  continue;
3407  }
3408 
3409  Vals.push_back(DL->getLine());
3410  Vals.push_back(DL->getColumn());
3411  Vals.push_back(VE.getMetadataOrNullID(DL->getScope()));
3412  Vals.push_back(VE.getMetadataOrNullID(DL->getInlinedAt()));
3413  Vals.push_back(DL->isImplicitCode());
3414  Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
3415  Vals.clear();
3416 
3417  LastDL = DL;
3418  }
3419 
3420  if (BlockAddress *BA = BlockAddress::lookup(&BB)) {
3421  SmallVector<Value *> Worklist{BA};
3422  SmallPtrSet<Value *, 8> Visited{BA};
3423  while (!Worklist.empty()) {
3424  Value *V = Worklist.pop_back_val();
3425  for (User *U : V->users()) {
3426  if (auto *I = dyn_cast<Instruction>(U)) {
3427  Function *P = I->getFunction();
3428  if (P != &F)
3429  BlockAddressUsers.insert(P);
3430  } else if (isa<Constant>(U) && !isa<GlobalValue>(U) &&
3431  Visited.insert(U).second)
3432  Worklist.push_back(U);
3433  }
3434  }
3435  }
3436  }
3437 
3438  if (!BlockAddressUsers.empty()) {
3439  Vals.resize(BlockAddressUsers.size());
3440  for (auto I : llvm::enumerate(BlockAddressUsers))
3441  Vals[I.index()] = VE.getValueID(I.value());
3443  Vals.clear();
3444  }
3445 
3446  // Emit names for all the instructions etc.
3447  if (auto *Symtab = F.getValueSymbolTable())
3448  writeFunctionLevelValueSymbolTable(*Symtab);
3449 
3450  if (NeedsMetadataAttachment)
3451  writeFunctionMetadataAttachment(F);
3452  if (VE.shouldPreserveUseListOrder())
3453  writeUseListBlock(&F);
3454  VE.purgeFunction();
3455  Stream.ExitBlock();
3456 }
3457 
3458 // Emit blockinfo, which defines the standard abbreviations etc.
3459 void ModuleBitcodeWriter::writeBlockInfo() {
3460  // We only want to emit block info records for blocks that have multiple
3461  // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
3462  // Other blocks can define their abbrevs inline.
3463  Stream.EnterBlockInfoBlock();
3464 
3465  { // 8-bit fixed-width VST_CODE_ENTRY/VST_CODE_BBENTRY strings.
3466  auto Abbv = std::make_shared<BitCodeAbbrev>();
3467  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
3468  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3470  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3472  VST_ENTRY_8_ABBREV)
3473  llvm_unreachable("Unexpected abbrev ordering!");
3474  }
3475 
3476  { // 7-bit fixed width VST_CODE_ENTRY strings.
3477  auto Abbv = std::make_shared<BitCodeAbbrev>();
3479  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3481  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3483  VST_ENTRY_7_ABBREV)
3484  llvm_unreachable("Unexpected abbrev ordering!");
3485  }
3486  { // 6-bit char6 VST_CODE_ENTRY strings.
3487  auto Abbv = std::make_shared<BitCodeAbbrev>();
3489  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3493  VST_ENTRY_6_ABBREV)
3494  llvm_unreachable("Unexpected abbrev ordering!");
3495  }
3496  { // 6-bit char6 VST_CODE_BBENTRY strings.
3497  auto Abbv = std::make_shared<BitCodeAbbrev>();
3499  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3503  VST_BBENTRY_6_ABBREV)
3504  llvm_unreachable("Unexpected abbrev ordering!");
3505  }
3506 
3507  { // SETTYPE abbrev for CONSTANTS_BLOCK.
3508  auto Abbv = std::make_shared<BitCodeAbbrev>();
3512  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3513  CONSTANTS_SETTYPE_ABBREV)
3514  llvm_unreachable("Unexpected abbrev ordering!");
3515  }
3516 
3517  { // INTEGER abbrev for CONSTANTS_BLOCK.
3518  auto Abbv = std::make_shared<BitCodeAbbrev>();
3520  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3521  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3522  CONSTANTS_INTEGER_ABBREV)
3523  llvm_unreachable("Unexpected abbrev ordering!");
3524  }
3525 
3526  { // CE_CAST abbrev for CONSTANTS_BLOCK.
3527  auto Abbv = std::make_shared<BitCodeAbbrev>();
3529  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
3530  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
3532  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
3533 
3534  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3535  CONSTANTS_CE_CAST_Abbrev)
3536  llvm_unreachable("Unexpected abbrev ordering!");
3537  }
3538  { // NULL abbrev for CONSTANTS_BLOCK.
3539  auto Abbv = std::make_shared<BitCodeAbbrev>();
3541  if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, Abbv) !=
3542  CONSTANTS_NULL_Abbrev)
3543  llvm_unreachable("Unexpected abbrev ordering!");
3544  }
3545 
3546  // FIXME: This should only use space for first class types!
3547 
3548  { // INST_LOAD abbrev for FUNCTION_BLOCK.
3549  auto Abbv = std::make_shared<BitCodeAbbrev>();
3551  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
3552  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3554  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
3555  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
3556  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3557  FUNCTION_INST_LOAD_ABBREV)
3558  llvm_unreachable("Unexpected abbrev ordering!");
3559  }
3560  { // INST_UNOP abbrev for FUNCTION_BLOCK.
3561  auto Abbv = std::make_shared<BitCodeAbbrev>();
3563  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3564  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3565  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3566  FUNCTION_INST_UNOP_ABBREV)
3567  llvm_unreachable("Unexpected abbrev ordering!");
3568  }
3569  { // INST_UNOP_FLAGS abbrev for FUNCTION_BLOCK.
3570  auto Abbv = std::make_shared<BitCodeAbbrev>();
3572  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3573  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3574  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3575  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3576  FUNCTION_INST_UNOP_FLAGS_ABBREV)
3577  llvm_unreachable("Unexpected abbrev ordering!");
3578  }
3579  { // INST_BINOP abbrev for FUNCTION_BLOCK.
3580  auto Abbv = std::make_shared<BitCodeAbbrev>();
3582  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3583  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3584  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3585  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3586  FUNCTION_INST_BINOP_ABBREV)
3587  llvm_unreachable("Unexpected abbrev ordering!");
3588  }
3589  { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
3590  auto Abbv = std::make_shared<BitCodeAbbrev>();
3592  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
3593  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
3594  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3595  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // flags
3596  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3597  FUNCTION_INST_BINOP_FLAGS_ABBREV)
3598  llvm_unreachable("Unexpected abbrev ordering!");
3599  }
3600  { // INST_CAST abbrev for FUNCTION_BLOCK.
3601  auto Abbv = std::make_shared<BitCodeAbbrev>();
3603  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
3604  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3606  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
3607  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3608  FUNCTION_INST_CAST_ABBREV)
3609  llvm_unreachable("Unexpected abbrev ordering!");
3610  }
3611 
3612  { // INST_RET abbrev for FUNCTION_BLOCK.
3613  auto Abbv = std::make_shared<BitCodeAbbrev>();
3615  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3616  FUNCTION_INST_RET_VOID_ABBREV)
3617  llvm_unreachable("Unexpected abbrev ordering!");
3618  }
3619  { // INST_RET abbrev for FUNCTION_BLOCK.
3620  auto Abbv = std::make_shared<BitCodeAbbrev>();
3622  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
3623  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3624  FUNCTION_INST_RET_VAL_ABBREV)
3625  llvm_unreachable("Unexpected abbrev ordering!");
3626  }
3627  { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
3628  auto Abbv = std::make_shared<BitCodeAbbrev>();
3630  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3631  FUNCTION_INST_UNREACHABLE_ABBREV)
3632  llvm_unreachable("Unexpected abbrev ordering!");
3633  }
3634  {
3635  auto Abbv = std::make_shared<BitCodeAbbrev>();
3637  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));
3638  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
3639  Log2_32_Ceil(VE.getTypes().size() + 1)));
3641  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
3642  if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, Abbv) !=
3643  FUNCTION_INST_GEP_ABBREV)
3644  llvm_unreachable("Unexpected abbrev ordering!");
3645  }
3646 
3647  Stream.ExitBlock();
3648 }
3649 
3650 /// Write the module path strings, currently only used when generating
3651 /// a combined index file.
3652 void IndexBitcodeWriter::writeModStrings() {
3654 
3655  // TODO: See which abbrev sizes we actually need to emit
3656 
3657  // 8-bit fixed-width MST_ENTRY strings.
3658  auto Abbv = std::make_shared<BitCodeAbbrev>();
3660  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3662  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
3663  unsigned Abbrev8Bit = Stream.EmitAbbrev(std::move(Abbv));
3664 
3665  // 7-bit fixed width MST_ENTRY strings.
3666  Abbv = std::make_shared<BitCodeAbbrev>();
3668  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3670  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
3671  unsigned Abbrev7Bit = Stream.EmitAbbrev(std::move(Abbv));
3672 
3673  // 6-bit char6 MST_ENTRY strings.
3674  Abbv = std::make_shared<BitCodeAbbrev>();
3676  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
3679  unsigned Abbrev6Bit = Stream.EmitAbbrev(std::move(Abbv));
3680 
3681  // Module Hash, 160 bits SHA1. Optionally, emitted after each MST_CODE_ENTRY.
3682  Abbv = std::make_shared<BitCodeAbbrev>();
3684  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3685  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3686  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3687  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3688  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
3689  unsigned AbbrevHash = Stream.EmitAbbrev(std::move(Abbv));
3690 
3692  forEachModule(
3693  [&](const StringMapEntry<std::pair<uint64_t, ModuleHash>> &MPSE) {
3694  StringRef Key = MPSE.getKey();
3695  const auto &Value = MPSE.getValue();
3697  unsigned AbbrevToUse = Abbrev8Bit;
3698  if (Bits == SE_Char6)
3699  AbbrevToUse = Abbrev6Bit;
3700  else if (Bits == SE_Fixed7)
3701  AbbrevToUse = Abbrev7Bit;
3702 
3703  Vals.push_back(Value.first);
3704  Vals.append(Key.begin(), Key.end());
3705 
3706  // Emit the finished record.
3707  Stream.EmitRecord(bitc::MST_CODE_ENTRY, Vals, AbbrevToUse);
3708 
3709  // Emit an optional hash for the module now
3710  const auto &Hash = Value.second;
3711  if (llvm::any_of(Hash, [](uint32_t H) { return H; })) {
3712  Vals.assign(Hash.begin(), Hash.end());
3713  // Emit the hash record.
3714  Stream.EmitRecord(bitc::MST_CODE_HASH, Vals, AbbrevHash);
3715  }
3716 
3717  Vals.clear();
3718  });
3719  Stream.ExitBlock();
3720 }
3721 
3722 /// Write the function type metadata related records that need to appear before
3723 /// a function summary entry (whether per-module or combined).
3724 template <typename Fn>
3727  Fn GetValueID) {
3728  if (!FS->type_tests().empty())
3729  Stream.EmitRecord(bitc::FS_TYPE_TESTS, FS->type_tests());
3730 
3732 
3733  auto WriteVFuncIdVec = [&](uint64_t Ty,
3735  if (VFs.empty())
3736  return;
3737  Record.clear();
3738  for (auto &VF : VFs) {
3739  Record.push_back(VF.GUID);
3740  Record.push_back(VF.Offset);
3741  }
3742  Stream.EmitRecord(Ty, Record);
3743  };
3744 
3745  WriteVFuncIdVec(bitc::FS_TYPE_TEST_ASSUME_VCALLS,
3746  FS->type_test_assume_vcalls());
3747  WriteVFuncIdVec(bitc::FS_TYPE_CHECKED_LOAD_VCALLS,
3748  FS->type_checked_load_vcalls());
3749 
3750  auto WriteConstVCallVec = [&](uint64_t Ty,
3752  for (auto &VC : VCs) {
3753  Record.clear();
3754  Record.push_back(VC.VFunc.GUID);
3755  Record.push_back(VC.VFunc.Offset);
3756  llvm::append_range(Record, VC.Args);
3757  Stream.EmitRecord(Ty, Record);
3758  }
3759  };
3760 
3761  WriteConstVCallVec(bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL,
3762  FS->type_test_assume_const_vcalls());
3763  WriteConstVCallVec(bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL,
3764  FS->type_checked_load_const_vcalls());
3765 
3766  auto WriteRange = [&](ConstantRange Range) {
3767  Range = Range.sextOrTrunc(FunctionSummary::ParamAccess::RangeWidth);
3768  assert(Range.getLower().getNumWords() == 1);
3769  assert(Range.getUpper().getNumWords() == 1);
3770  emitSignedInt64(Record, *Range.getLower().getRawData());
3771  emitSignedInt64(Record, *Range.getUpper().getRawData());
3772  };
3773 
3774  if (!FS->paramAccesses().empty()) {
3775  Record.clear();
3776  for (auto &Arg : FS->paramAccesses()) {
3777  size_t UndoSize = Record.size();
3778  Record.push_back(Arg.ParamNo);
3779  WriteRange(Arg.Use);
3780  Record.push_back(Arg.Calls.size());
3781  for (auto &Call : Arg.Calls) {
3782  Record.push_back(Call.ParamNo);
3783  Optional<unsigned> ValueID = GetValueID(Call.Callee);
3784  if (!ValueID) {
3785  // If ValueID is unknown we can't drop just this call, we must drop
3786  // entire parameter.
3787  Record.resize(UndoSize);
3788  break;
3789  }
3790  Record.push_back(*ValueID);
3791  WriteRange(Call.Offsets);
3792  }
3793  }
3794  if (!Record.empty())
3796  }
3797 }
3798 
3799 /// Collect type IDs from type tests used by function.
3800 static void
3802  std::set<GlobalValue::GUID> &ReferencedTypeIds) {
3803  if (!FS->type_tests().empty())
3804  for (auto &TT : FS->type_tests())
3805  ReferencedTypeIds.insert(TT);
3806 
3807  auto GetReferencedTypesFromVFuncIdVec =
3809  for (auto &VF : VFs)
3810  ReferencedTypeIds.insert(VF.GUID);
3811  };
3812 
3813  GetReferencedTypesFromVFuncIdVec(FS->type_test_assume_vcalls());
3814  GetReferencedTypesFromVFuncIdVec(FS->type_checked_load_vcalls());
3815 
3816  auto GetReferencedTypesFromConstVCallVec =
3818  for (auto &VC : VCs)
3819  ReferencedTypeIds.insert(VC.VFunc.GUID);
3820  };
3821 
3822  GetReferencedTypesFromConstVCallVec(FS->type_test_assume_const_vcalls());
3823  GetReferencedTypesFromConstVCallVec(FS->type_checked_load_const_vcalls());
3824 }
3825 
3827  SmallVector<uint64_t, 64> &NameVals, const std::vector<uint64_t> &args,
3828  const WholeProgramDevirtResolution::ByArg &ByArg) {
3829  NameVals.push_back(args.size());
3830  llvm::append_range(NameVals, args);
3831 
3832  NameVals.push_back(ByArg.TheKind);
3833  NameVals.push_back(ByArg.Info);
3834  NameVals.push_back(ByArg.Byte);
3835  NameVals.push_back(ByArg.Bit);
3836 }
3837 
3839  SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3841  NameVals.push_back(Id);
3842 
3843  NameVals.push_back(Wpd.TheKind);
3844  NameVals.push_back(StrtabBuilder.add(Wpd.SingleImplName));
3845  NameVals.push_back(Wpd.SingleImplName.size());
3846 
3847  NameVals.push_back(Wpd.ResByArg.size());
3848  for (auto &A : Wpd.ResByArg)
3849  writeWholeProgramDevirtResolutionByArg(NameVals, A.first, A.second);
3850 }
3851 
3853  StringTableBuilder &StrtabBuilder,
3854  const std::string &Id,
3855  const TypeIdSummary &Summary) {
3856  NameVals.push_back(StrtabBuilder.add(Id));
3857  NameVals.push_back(Id.size());
3858 
3859  NameVals.push_back(Summary.TTRes.TheKind);
3860  NameVals.push_back(Summary.TTRes.SizeM1BitWidth);
3861  NameVals.push_back(Summary.TTRes.AlignLog2);
3862  NameVals.push_back(Summary.TTRes.SizeM1);
3863  NameVals.push_back(Summary.TTRes.BitMask);
3864  NameVals.push_back(Summary.TTRes.InlineBits);
3865 
3866  for (auto &W : Summary.WPDRes)
3867  writeWholeProgramDevirtResolution(NameVals, StrtabBuilder, W.first,
3868  W.second);
3869 }
3870 
3872  SmallVector<uint64_t, 64> &NameVals, StringTableBuilder &StrtabBuilder,
3873  const std::string &Id, const TypeIdCompatibleVtableInfo &Summary,
3874  ValueEnumerator &VE) {
3875  NameVals.push_back(StrtabBuilder.add(Id));
3876  NameVals.push_back(Id.size());
3877 
3878  for (auto &P : Summary) {
3879  NameVals.push_back(P.AddressPointOffset);
3880  NameVals.push_back(VE.getValueID(P.VTableVI.getValue()));
3881  }
3882 }
3883 
3884 // Helper to emit a single function summary record.
3885 void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
3886  SmallVector<uint64_t, 64> &NameVals, GlobalValueSummary *Summary,
3887  unsigned ValueID, unsigned FSCallsAbbrev, unsigned FSCallsProfileAbbrev,
3888  const Function &F) {
3889  NameVals.push_back(ValueID);
3890 
3891  FunctionSummary *FS = cast<FunctionSummary>(Summary);
3892 
3894  Stream, FS, [&](const ValueInfo &VI) -> Optional<unsigned> {
3895  return {VE.getValueID(VI.getValue())};
3896  });
3897 
3898  auto SpecialRefCnts = FS->specialRefCounts();
3899  NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
3900  NameVals.push_back(FS->instCount());
3901  NameVals.push_back(getEncodedFFlags(FS->fflags()));
3902  NameVals.push_back(FS->refs().size());
3903  NameVals.push_back(SpecialRefCnts.first); // rorefcnt
3904  NameVals.push_back(SpecialRefCnts.second); // worefcnt
3905 
3906  for (auto &RI : FS->refs())
3907  NameVals.push_back(VE.getValueID(RI.getValue()));
3908 
3909  bool HasProfileData =
3910  F.hasProfileData() || ForceSummaryEdgesCold != FunctionSummary::FSHT_None;
3911  for (auto &ECI : FS->calls()) {
3912  NameVals.push_back(getValueId(ECI.first));
3913  if (HasProfileData)
3914  NameVals.push_back(static_cast<uint8_t>(ECI.second.Hotness));
3915  else if (WriteRelBFToSummary)
3916  NameVals.push_back(ECI.second.RelBlockFreq);
3917  }
3918 
3919  unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
3920  unsigned Code =
3921  (HasProfileData ? bitc::FS_PERMODULE_PROFILE
3923  : bitc::FS_PERMODULE));
3924 
3925  // Emit the finished record.
3926  Stream.EmitRecord(Code, NameVals, FSAbbrev);
3927  NameVals.clear();
3928 }
3929 
3930 // Collect the global value references in the given variable's initializer,
3931 // and emit them in a summary record.
3932 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
3933  const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
3934  unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
3935  auto VI = Index->getValueInfo(V.getGUID());
3936  if (!VI || VI.getSummaryList().empty()) {
3937  // Only declarations should not have a summary (a declaration might however
3938  // have a summary if the def was in module level asm).
3939  assert(V.isDeclaration());
3940  return;
3941  }
3942  auto *Summary = VI.getSummaryList()[0].get();
3943  NameVals.push_back(VE.getValueID(&V));
3944  GlobalVarSummary *VS = cast<GlobalVarSummary>(Summary);
3945  NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
3946  NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
3947 
3948  auto VTableFuncs = VS->vTableFuncs();
3949  if (!VTableFuncs.empty())
3950  NameVals.push_back(VS->refs().size());
3951 
3952  unsigned SizeBeforeRefs = NameVals.size();
3953  for (auto &RI : VS->refs())
3954  NameVals.push_back(VE.getValueID(RI.getValue()));
3955  // Sort the refs for determinism output, the vector returned by FS->refs() has
3956  // been initialized from a DenseSet.
3957  llvm::sort(drop_begin(NameVals, SizeBeforeRefs));
3958 
3959  if (VTableFuncs.empty())
3961  FSModRefsAbbrev);
3962  else {
3963  // VTableFuncs pairs should already be sorted by offset.
3964  for (auto &P : VTableFuncs) {
3965  NameVals.push_back(VE.getValueID(P.FuncVI.getValue()));
3966  NameVals.push_back(P.VTableOffset);
3967  }
3968 
3970  FSModVTableRefsAbbrev);
3971  }
3972  NameVals.clear();
3973 }
3974 
3975 /// Emit the per-module summary section alongside the rest of
3976 /// the module's bitcode.
3977 void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
3978  // By default we compile with ThinLTO if the module has a summary, but the
3979  // client can request full LTO with a module flag.
3980  bool IsThinLTO = true;
3981  if (auto *MD =
3982  mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("ThinLTO")))
3983  IsThinLTO = MD->getZExtValue();
3986  4);
3987 
3988  Stream.EmitRecord(
3991 
3992  // Write the index flags.
3993  uint64_t Flags = 0;
3994  // Bits 1-3 are set only in the combined index, skip them.
3995  if (Index->enableSplitLTOUnit())
3996  Flags |= 0x8;
3998 
3999  if (Index->begin() == Index->end()) {
4000  Stream.ExitBlock();
4001  return;
4002  }
4003 
4004  for (const auto &GVI : valueIds()) {
4006  ArrayRef<uint64_t>{GVI.second, GVI.first});
4007  }
4008 
4009  // Abbrev for FS_PERMODULE_PROFILE.
4010  auto Abbv = std::make_shared<BitCodeAbbrev>();
4012  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4013  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4014  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4015  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4016  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4017  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4018  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4019  // numrefs x valueid, n x (valueid, hotness)
4021  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4022  unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4023 
4024  // Abbrev for FS_PERMODULE or FS_PERMODULE_RELBF.
4025  Abbv = std::make_shared<BitCodeAbbrev>();
4026  if (WriteRelBFToSummary)
4028  else
4029  Abbv->Add(BitCodeAbbrevOp(bitc::FS_PERMODULE));
4030  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4031  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4032  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4033  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4034  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4035  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4036  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4037  // numrefs x valueid, n x (valueid [, rel_block_freq])
4039  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4040  unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4041 
4042  // Abbrev for FS_PERMODULE_GLOBALVAR_INIT_REFS.
4043  Abbv = std::make_shared<BitCodeAbbrev>();
4045  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4046  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4047  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4048  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4049  unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4050 
4051  // Abbrev for FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS.
4052  Abbv = std::make_shared<BitCodeAbbrev>();
4054  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4055  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4056  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4057  // numrefs x valueid, n x (valueid , offset)
4059  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4060  unsigned FSModVTableRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4061 
4062  // Abbrev for FS_ALIAS.
4063  Abbv = std::make_shared<BitCodeAbbrev>();
4064  Abbv->Add(BitCodeAbbrevOp(bitc::FS_ALIAS));
4065  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4066  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4067  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4068  unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4069 
4070  // Abbrev for FS_TYPE_ID_METADATA
4071  Abbv = std::make_shared<BitCodeAbbrev>();
4073  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid strtab index
4074  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // typeid length
4075  // n x (valueid , offset)
4077  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4078  unsigned TypeIdCompatibleVtableAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4079 
4080  SmallVector<uint64_t, 64> NameVals;
4081  // Iterate over the list of functions instead of the Index to
4082  // ensure the ordering is stable.
4083  for (const Function &F : M) {
4084  // Summary emission does not support anonymous functions, they have to
4085  // renamed using the anonymous function renaming pass.
4086  if (!F.hasName())
4087  report_fatal_error("Unexpected anonymous function when writing summary");
4088 
4089  ValueInfo VI = Index->getValueInfo(F.getGUID());
4090  if (!VI || VI.getSummaryList().empty()) {
4091  // Only declarations should not have a summary (a declaration might
4092  // however have a summary if the def was in module level asm).
4093  assert(F.isDeclaration());
4094  continue;
4095  }
4096  auto *Summary = VI.getSummaryList()[0].get();
4097  writePerModuleFunctionSummaryRecord(NameVals, Summary, VE.getValueID(&F),
4098  FSCallsAbbrev, FSCallsProfileAbbrev, F);
4099  }
4100 
4101  // Capture references from GlobalVariable initializers, which are outside
4102  // of a function scope.
4103  for (const GlobalVariable &G : M.globals())
4104  writeModuleLevelReferences(G, NameVals, FSModRefsAbbrev,
4105  FSModVTableRefsAbbrev);
4106 
4107  for (const GlobalAlias &A : M.aliases()) {
4108  auto *Aliasee = A.getAliaseeObject();
4109  // Skip ifunc and nameless functions which don't have an entry in the
4110  // summary.
4111  if (!Aliasee->hasName() || isa<GlobalIFunc>(Aliasee))
4112  continue;
4113  auto AliasId = VE.getValueID(&A);
4114  auto AliaseeId = VE.getValueID(Aliasee);
4115  NameVals.push_back(AliasId);
4116  auto *Summary = Index->getGlobalValueSummary(A);
4117  AliasSummary *AS = cast<AliasSummary>(Summary);
4118  NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4119  NameVals.push_back(AliaseeId);
4120  Stream.EmitRecord(bitc::FS_ALIAS, NameVals, FSAliasAbbrev);
4121  NameVals.clear();
4122  }
4123 
4124  for (auto &S : Index->typeIdCompatibleVtableMap()) {
4125  writeTypeIdCompatibleVtableSummaryRecord(NameVals, StrtabBuilder, S.first,
4126  S.second, VE);
4127  Stream.EmitRecord(bitc::FS_TYPE_ID_METADATA, NameVals,
4128  TypeIdCompatibleVtableAbbrev);
4129  NameVals.clear();
4130  }
4131 
4133  ArrayRef<uint64_t>{Index->getBlockCount()});
4134 
4135  Stream.ExitBlock();
4136 }
4137 
4138 /// Emit the combined summary section into the combined index file.
4139 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
4141  Stream.EmitRecord(
4144 
4145  // Write the index flags.
4146  Stream.EmitRecord(bitc::FS_FLAGS, ArrayRef<uint64_t>{Index.getFlags()});
4147 
4148  for (const auto &GVI : valueIds()) {
4150  ArrayRef<uint64_t>{GVI.second, GVI.first});
4151  }
4152 
4153  // Abbrev for FS_COMBINED.
4154  auto Abbv = std::make_shared<BitCodeAbbrev>();
4155  Abbv->Add(BitCodeAbbrevOp(bitc::FS_COMBINED));
4156  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4157  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4158  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4159  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4160  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4161  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4162  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4163  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4164  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4165  // numrefs x valueid, n x (valueid)
4167  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4168  unsigned FSCallsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4169 
4170  // Abbrev for FS_COMBINED_PROFILE.
4171  Abbv = std::make_shared<BitCodeAbbrev>();
4173  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4174  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4175  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4176  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // instcount
4177  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // fflags
4178  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // entrycount
4179  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // numrefs
4180  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // rorefcnt
4181  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // worefcnt
4182  // numrefs x valueid, n x (valueid, hotness)
4184  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4185  unsigned FSCallsProfileAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4186 
4187  // Abbrev for FS_COMBINED_GLOBALVAR_INIT_REFS.
4188  Abbv = std::make_shared<BitCodeAbbrev>();
4190  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4191  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4192  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4193  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); // valueids
4194  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
4195  unsigned FSModRefsAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4196 
4197  // Abbrev for FS_COMBINED_ALIAS.
4198  Abbv = std::make_shared<BitCodeAbbrev>();
4200  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4201  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // modid
4202  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // flags
4203  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // valueid
4204  unsigned FSAliasAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4205 
4206  // The aliases are emitted as a post-pass, and will point to the value
4207  // id of the aliasee. Save them in a vector for post-processing.
4209 
4210  // Save the value id for each summary for alias emission.
4212 
4213  SmallVector<uint64_t, 64> NameVals;
4214 
4215  // Set that will be populated during call to writeFunctionTypeMetadataRecords
4216  // with the type ids referenced by this index file.
4217  std::set<GlobalValue::GUID> ReferencedTypeIds;
4218 
4219  // For local linkage, we also emit the original name separately
4220  // immediately after the record.
4221  auto MaybeEmitOriginalName = [&](GlobalValueSummary &S) {
4222  // We don't need to emit the original name if we are writing the index for
4223  // distributed backends (in which case ModuleToSummariesForIndex is
4224  // non-null). The original name is only needed during the thin link, since
4225  // for SamplePGO the indirect call targets for local functions have
4226  // have the original name annotated in profile.
4227  // Continue to emit it when writing out the entire combined index, which is
4228  // used in testing the thin link via llvm-lto.
4229  if (ModuleToSummariesForIndex || !GlobalValue::isLocalLinkage(S.linkage()))
4230  return;
4231  NameVals.push_back(S.getOriginalName());
4232  Stream.EmitRecord(bitc::FS_COMBINED_ORIGINAL_NAME, NameVals);
4233  NameVals.clear();
4234  };
4235 
4236  std::set<GlobalValue::GUID> DefOrUseGUIDs;
4237  forEachSummary([&](GVInfo I, bool IsAliasee) {
4238  GlobalValueSummary *S = I.second;
4239  assert(S);
4240  DefOrUseGUIDs.insert(I.first);
4241  for (const ValueInfo &VI : S->refs())
4242  DefOrUseGUIDs.insert(VI.getGUID());
4243 
4244  auto ValueId = getValueId(I.first);
4245  assert(ValueId);
4246  SummaryToValueIdMap[S] = *ValueId;
4247 
4248  // If this is invoked for an aliasee, we want to record the above
4249  // mapping, but then not emit a summary entry (if the aliasee is
4250  // to be imported, we will invoke this separately with IsAliasee=false).
4251  if (IsAliasee)
4252  return;
4253 
4254  if (auto *AS = dyn_cast<AliasSummary>(S)) {
4255  // Will process aliases as a post-pass because the reader wants all
4256  // global to be loaded first.
4257  Aliases.push_back(AS);
4258  return;
4259  }
4260 
4261  if (auto *VS = dyn_cast<GlobalVarSummary>(S)) {
4262  NameVals.push_back(*ValueId);
4263  NameVals.push_back(Index.getModuleId(VS->modulePath()));
4264  NameVals.push_back(getEncodedGVSummaryFlags(VS->flags()));
4265  NameVals.push_back(getEncodedGVarFlags(VS->varflags()));
4266  for (auto &RI : VS->refs()) {
4267  auto RefValueId = getValueId(RI.getGUID());
4268  if (!RefValueId)
4269  continue;
4270  NameVals.push_back(*RefValueId);
4271  }
4272 
4273  // Emit the finished record.
4275  FSModRefsAbbrev);
4276  NameVals.clear();
4277  MaybeEmitOriginalName(*S);
4278  return;
4279  }
4280 
4281  auto GetValueId = [&](const ValueInfo &VI) -> Optional<unsigned> {
4282  return getValueId(VI.getGUID());
4283  };
4284 
4285  auto *FS = cast<FunctionSummary>(S);
4286  writeFunctionTypeMetadataRecords(Stream, FS, GetValueId);
4287  getReferencedTypeIds(FS, ReferencedTypeIds);
4288 
4289  NameVals.push_back(*ValueId);
4290  NameVals.push_back(Index.getModuleId(FS->modulePath()));
4291  NameVals.push_back(getEncodedGVSummaryFlags(FS->flags()));
4292  NameVals.push_back(FS->instCount());
4293  NameVals.push_back(getEncodedFFlags(FS->fflags()));
4294  NameVals.push_back(FS->entryCount());
4295 
4296  // Fill in below
4297  NameVals.push_back(0); // numrefs
4298  NameVals.push_back(0); // rorefcnt
4299  NameVals.push_back(0); // worefcnt
4300 
4301  unsigned Count = 0, RORefCnt = 0, WORefCnt = 0;
4302  for (auto &RI : FS->refs()) {
4303  auto RefValueId = getValueId(RI.getGUID());
4304  if (!RefValueId)
4305  continue;
4306  NameVals.push_back(*RefValueId);
4307  if (RI.isReadOnly())
4308  RORefCnt++;
4309  else if (RI.isWriteOnly())
4310  WORefCnt++;
4311  Count++;
4312  }
4313  NameVals[6] = Count;
4314  NameVals[7] = RORefCnt;
4315  NameVals[8] = WORefCnt;
4316 
4317  bool HasProfileData = false;
4318  for (auto &EI : FS->calls()) {
4319  HasProfileData |=
4320  EI.second.getHotness() != CalleeInfo::HotnessType::Unknown;
4321  if (HasProfileData)
4322  break;
4323  }
4324 
4325  for (auto &EI : FS->calls()) {
4326  // If this GUID doesn't have a value id, it doesn't have a function
4327  // summary and we don't need to record any calls to it.
4328  Optional<unsigned> CallValueId = GetValueId(EI.first);
4329  if (!CallValueId)
4330  continue;
4331  NameVals.push_back(*CallValueId);
4332  if (HasProfileData)
4333  NameVals.push_back(static_cast<uint8_t>(EI.second.Hotness));
4334  }
4335 
4336  unsigned FSAbbrev = (HasProfileData ? FSCallsProfileAbbrev : FSCallsAbbrev);
4337  unsigned Code =
4338  (HasProfileData ? bitc::FS_COMBINED_PROFILE : bitc::FS_COMBINED);
4339 
4340  // Emit the finished record.
4341  Stream.EmitRecord(Code, NameVals, FSAbbrev);
4342  NameVals.clear();
4343  MaybeEmitOriginalName(*S);
4344  });
4345 
4346  for (auto *AS : Aliases) {
4347  auto AliasValueId = SummaryToValueIdMap[AS];
4348  assert(AliasValueId);
4349  NameVals.push_back(AliasValueId);
4350  NameVals.push_back(Index.getModuleId(AS->modulePath()));
4351  NameVals.push_back(getEncodedGVSummaryFlags(AS->flags()));
4352  auto AliaseeValueId = SummaryToValueIdMap[&AS->getAliasee()];
4353  assert(AliaseeValueId);
4354  NameVals.push_back(AliaseeValueId);
4355 
4356  // Emit the finished record.
4357  Stream.EmitRecord(bitc::FS_COMBINED_ALIAS, NameVals, FSAliasAbbrev);
4358  NameVals.clear();
4359  MaybeEmitOriginalName(*AS);
4360 
4361  if (auto *FS = dyn_cast<FunctionSummary>(&AS->getAliasee()))
4362  getReferencedTypeIds(FS, ReferencedTypeIds);
4363  }
4364 
4365  if (!Index.cfiFunctionDefs().empty()) {
4366  for (auto &S : Index.cfiFunctionDefs()) {
4367  if (DefOrUseGUIDs.count(
4369  NameVals.push_back(StrtabBuilder.add(S));
4370  NameVals.push_back(S.size());
4371  }
4372  }
4373  if (!NameVals.empty()) {
4374  Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DEFS, NameVals);
4375  NameVals.clear();
4376  }
4377  }
4378 
4379  if (!Index.cfiFunctionDecls().empty()) {
4380  for (auto &S : Index.cfiFunctionDecls()) {
4381  if (DefOrUseGUIDs.count(
4383  NameVals.push_back(StrtabBuilder.add(S));
4384  NameVals.push_back(S.size());
4385  }
4386  }
4387  if (!NameVals.empty()) {
4388  Stream.EmitRecord(bitc::FS_CFI_FUNCTION_DECLS, NameVals);
4389  NameVals.clear();
4390  }
4391  }
4392 
4393  // Walk the GUIDs that were referenced, and write the
4394  // corresponding type id records.
4395  for (auto &T : ReferencedTypeIds) {
4396  auto TidIter = Index.typeIds().equal_range(T);
4397  for (auto It = TidIter.first; It != TidIter.second; ++It) {
4398  writeTypeIdSummaryRecord(NameVals, StrtabBuilder, It->second.first,
4399  It->second.second);
4400  Stream.EmitRecord(bitc::FS_TYPE_ID, NameVals);
4401  NameVals.clear();
4402  }
4403  }
4404 
4406  ArrayRef<uint64_t>{Index.getBlockCount()});
4407 
4408  Stream.ExitBlock();
4409 }
4410 
4411 /// Create the "IDENTIFICATION_BLOCK_ID" containing a single string with the
4412 /// current llvm version, and a record for the epoch number.
4415 
4416  // Write the "user readable" string identifying the bitcode producer
4417  auto Abbv = std::make_shared<BitCodeAbbrev>();
4421  auto StringAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4423  "LLVM" LLVM_VERSION_STRING, StringAbbrev);
4424 
4425  // Write the epoch version
4426  Abbv = std::make_shared<BitCodeAbbrev>();
4428  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));
4429  auto EpochAbbrev = Stream.EmitAbbrev(std::move(Abbv));
4430  constexpr std::array<unsigned, 1> Vals = {{bitc::BITCODE_CURRENT_EPOCH}};
4431  Stream.EmitRecord(bitc::IDENTIFICATION_CODE_EPOCH, Vals, EpochAbbrev);
4432  Stream.ExitBlock();
4433 }
4434 
4435 void ModuleBitcodeWriter::writeModuleHash(size_t BlockStartPos) {
4436  // Emit the module's hash.
4437  // MODULE_CODE_HASH: [5*i32]
4438  if (GenerateHash) {
4439  uint32_t Vals[5];
4440  Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&(Buffer)[BlockStartPos],
4441  Buffer.size() - BlockStartPos));
4442  std::array<uint8_t, 20> Hash = Hasher.result();
4443  for (int Pos = 0; Pos < 20; Pos += 4) {
4444  Vals[Pos / 4] = support::endian::read32be(Hash.data() + Pos);
4445  }
4446 
4447  // Emit the finished record.
4448  Stream.EmitRecord(bitc::MODULE_CODE_HASH, Vals);
4449 
4450  if (ModHash)
4451  // Save the written hash value.
4452  llvm::copy(Vals, std::begin(*ModHash));
4453  }
4454 }
4455 
4457  writeIdentificationBlock(Stream);
4458 
4460  size_t BlockStartPos = Buffer.size();
4461 
4462  writeModuleVersion();
4463 
4464  // Emit blockinfo, which defines the standard abbreviations etc.
4465  writeBlockInfo();
4466 
4467  // Emit information describing all of the types in the module.
4468  writeTypeTable();
4469 
4470  // Emit information about attribute groups.
4471  writeAttributeGroupTable();
4472 
4473  // Emit information about parameter attributes.
4474  writeAttributeTable();
4475 
4476  writeComdats();
4477 
4478  // Emit top-level description of module, including target triple, inline asm,
4479  // descriptors for global variables, and function prototype info.
4480  writeModuleInfo();
4481 
4482  // Emit constants.
4483  writeModuleConstants();
4484 
4485  // Emit metadata kind names.
4486  writeModuleMetadataKinds();
4487 
4488  // Emit metadata.
4489  writeModuleMetadata();
4490 
4491  // Emit module-level use-lists.
4492  if (VE.shouldPreserveUseListOrder())
4493  writeUseListBlock(nullptr);
4494 
4495  writeOperandBundleTags();
4496  writeSyncScopeNames();
4497 
4498  // Emit function bodies.
4499  DenseMap<const Function *, uint64_t> FunctionToBitcodeIndex;
4500  for (const Function &F : M)
4501  if (!F.isDeclaration())
4502  writeFunction(F, FunctionToBitcodeIndex);
4503 
4504  // Need to write after the above call to WriteFunction which populates
4505  // the summary information in the index.
4506  if (Index)
4507  writePerModuleGlobalValueSummary();
4508 
4509  writeGlobalValueSymbolTable(FunctionToBitcodeIndex);
4510 
4511  writeModuleHash(BlockStartPos);
4512 
4513  Stream.ExitBlock();
4514 }
4515 
4517  uint32_t &Position) {
4518  support::endian::write32le(&Buffer[Position], Value);
4519  Position += 4;
4520 }
4521 
4522 /// If generating a bc file on darwin, we have to emit a
4523 /// header and trailer to make it compatible with the system archiver. To do
4524 /// this we emit the following header, and then emit a trailer that pads the
4525 /// file out to be a multiple of 16 bytes.
4526 ///
4527 /// struct bc_header {
4528 /// uint32_t Magic; // 0x0B17C0DE
4529 /// uint32_t Version; // Version, currently always 0.
4530 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
4531 /// uint32_t BitcodeSize; // Size of traditional bitcode file.
4532 /// uint32_t CPUType; // CPU specifier.
4533 /// ... potentially more later ...
4534 /// };
4536  const Triple &TT) {
4537  unsigned CPUType = ~0U;
4538 
4539  // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
4540  // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
4541  // number from /usr/include/mach/machine.h. It is ok to reproduce the
4542  // specific constants here because they are implicitly part of the Darwin ABI.
4543  enum {
4544  DARWIN_CPU_ARCH_ABI64 = 0x01000000,
4545  DARWIN_CPU_TYPE_X86 = 7,
4546  DARWIN_CPU_TYPE_ARM = 12,
4547  DARWIN_CPU_TYPE_POWERPC = 18
4548  };
4549 
4550  Triple::ArchType Arch = TT.getArch();
4551  if (Arch == Triple::x86_64)
4552  CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
4553  else if (Arch == Triple::x86)
4554  CPUType = DARWIN_CPU_TYPE_X86;
4555  else if (Arch == Triple::ppc)
4556  CPUType = DARWIN_CPU_TYPE_POWERPC;
4557  else if (Arch == Triple::ppc64)
4558  CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
4559  else if (Arch == Triple::arm || Arch == Triple::thumb)
4560  CPUType = DARWIN_CPU_TYPE_ARM;
4561 
4562  // Traditional Bitcode starts after header.
4563  assert(Buffer.size() >= BWH_HeaderSize &&
4564  "Expected header size to be reserved");
4565  unsigned BCOffset = BWH_HeaderSize;
4566  unsigned BCSize = Buffer.size() - BWH_HeaderSize;
4567 
4568  // Write the magic and version.
4569  unsigned Position = 0;
4570  writeInt32ToBuffer(0x0B17C0DE, Buffer, Position);
4571  writeInt32ToBuffer(0, Buffer, Position); // Version.
4572  writeInt32ToBuffer(BCOffset, Buffer, Position);
4573  writeInt32ToBuffer(BCSize, Buffer, Position);
4574  writeInt32ToBuffer(CPUType, Buffer, Position);
4575 
4576  // If the file is not a multiple of 16 bytes, insert dummy padding.
4577  while (Buffer.size() & 15)
4578  Buffer.push_back(0);
4579 }
4580 
4581 /// Helper to write the header common to all bitcode files.
4582 static void writeBitcodeHeader(BitstreamWriter &Stream) {
4583  // Emit the file header.
4584  Stream.Emit((unsigned)'B', 8);
4585  Stream.Emit((unsigned)'C', 8);
4586  Stream.Emit(0x0, 4);
4587  Stream.Emit(0xC, 4);
4588  Stream.Emit(0xE, 4);
4589  Stream.Emit(0xD, 4);
4590 }
4591 
4593  : Buffer(Buffer), Stream(new BitstreamWriter(Buffer, FS, FlushThreshold)) {
4594  writeBitcodeHeader(*Stream);
4595 }
4596 
4598 
4599 void BitcodeWriter::writeBlob(unsigned Block, unsigned Record, StringRef Blob) {
4600  Stream->EnterSubblock(Block, 3);
4601 
4602  auto Abbv = std::make_shared<BitCodeAbbrev>();
4603  Abbv->Add(BitCodeAbbrevOp(Record));
4605  auto AbbrevNo = Stream->EmitAbbrev(std::move(Abbv));
4606 
4607  Stream->EmitRecordWithBlob(AbbrevNo, ArrayRef<uint64_t>{Record}, Blob);
4608 
4609  Stream->ExitBlock();
4610 }
4611 
4613  assert(!WroteStrtab && !WroteSymtab);
4614 
4615  // If any module has module-level inline asm, we will require a registered asm
4616  // parser for the target so that we can create an accurate symbol table for
4617  // the module.
4618  for (Module *M : Mods) {
4619  if (M->getModuleInlineAsm().empty())
4620  continue;
4621 
4622  std::string Err;
4623  const Triple TT(M->getTargetTriple());
4624  const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
4625  if (!T || !T->hasMCAsmParser())
4626  return;
4627  }
4628 
4629  WroteSymtab = true;
4630  SmallVector<char, 0> Symtab;
4631  // The irsymtab::build function may be unable to create a symbol table if the
4632  // module is malformed (e.g. it contains an invalid alias). Writing a symbol
4633  // table is not required for correctness, but we still want to be able to
4634  // write malformed modules to bitcode files, so swallow the error.
4635  if (Error E = irsymtab::build(Mods, Symtab, StrtabBuilder, Alloc)) {
4637  return;
4638  }
4639 
4641  {Symtab.data(), Symtab.size()});
4642 }
4643 
4645  assert(!WroteStrtab);
4646 
4647  std::vector<char> Strtab;
4648  StrtabBuilder.finalizeInOrder();
4649  Strtab.resize(StrtabBuilder.getSize());
4650  StrtabBuilder.write((uint8_t *)Strtab.data());
4651 
4653  {Strtab.data(), Strtab.size()});
4654 
4655  WroteStrtab = true;
4656 }
4657 
4659  writeBlob(bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB, Strtab);
4660  WroteStrtab = true;
4661 }
4662 
4664  bool ShouldPreserveUseListOrder,
4665  const ModuleSummaryIndex *Index,
4666  bool GenerateHash, ModuleHash *ModHash) {
4667  assert(!WroteStrtab);
4668 
4669  // The Mods vector is used by irsymtab::build, which requires non-const
4670  // Modules in case it needs to materialize metadata. But the bitcode writer
4671  // requires that the module is materialized, so we can cast to non-const here,
4672  // after checking that it is in fact materialized.
4673  assert(M.isMaterialized());
4674  Mods.push_back(const_cast<Module *>(&M));
4675 
4676  ModuleBitcodeWriter ModuleWriter(M, Buffer, StrtabBuilder, *Stream,
4677  ShouldPreserveUseListOrder, Index,
4678  GenerateHash, ModHash);
4679  ModuleWriter.write();
4680 }
4681 
4683  const ModuleSummaryIndex *Index,
4684  const std::map<std::string, GVSummaryMapTy> *ModuleToSummariesForIndex) {
4685  IndexBitcodeWriter IndexWriter(*Stream, StrtabBuilder, *Index,
4686  ModuleToSummariesForIndex);
4687  IndexWriter.write();
4688 }
4689 
4690 /// Write the specified module to the specified output stream.
4692  bool ShouldPreserveUseListOrder,
4693  const ModuleSummaryIndex *Index,
4694  bool GenerateHash, ModuleHash *ModHash) {
4695  SmallVector<char, 0> Buffer;
4696  Buffer.