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