SyntheticCountsPropagation.cpp 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. //=- SyntheticCountsPropagation.cpp - Propagate function counts --*- C++ -*-=//
  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. // This file implements a transformation that synthesizes entry counts for
  10. // functions and attaches !prof metadata to functions with the synthesized
  11. // counts. The presence of !prof metadata with counter name set to
  12. // 'synthesized_function_entry_count' indicate that the value of the counter is
  13. // an estimation of the likely execution count of the function. This transform
  14. // is applied only in non PGO mode as functions get 'real' profile-based
  15. // function entry counts in the PGO mode.
  16. //
  17. // The transformation works by first assigning some initial values to the entry
  18. // counts of all functions and then doing a top-down traversal of the
  19. // callgraph-scc to propagate the counts. For each function the set of callsites
  20. // and their relative block frequency is gathered. The relative block frequency
  21. // multiplied by the entry count of the caller and added to the callee's entry
  22. // count. For non-trivial SCCs, the new counts are computed from the previous
  23. // counts and updated in one shot.
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
  27. #include "llvm/ADT/DenseSet.h"
  28. #include "llvm/ADT/STLExtras.h"
  29. #include "llvm/Analysis/BlockFrequencyInfo.h"
  30. #include "llvm/Analysis/CallGraph.h"
  31. #include "llvm/Analysis/ProfileSummaryInfo.h"
  32. #include "llvm/Analysis/SyntheticCountsUtils.h"
  33. #include "llvm/IR/Function.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/Module.h"
  36. #include "llvm/Support/CommandLine.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. using namespace llvm;
  40. using Scaled64 = ScaledNumber<uint64_t>;
  41. using ProfileCount = Function::ProfileCount;
  42. #define DEBUG_TYPE "synthetic-counts-propagation"
  43. namespace llvm {
  44. cl::opt<int>
  45. InitialSyntheticCount("initial-synthetic-count", cl::Hidden, cl::init(10),
  46. cl::ZeroOrMore,
  47. cl::desc("Initial value of synthetic entry count"));
  48. } // namespace llvm
  49. /// Initial synthetic count assigned to inline functions.
  50. static cl::opt<int> InlineSyntheticCount(
  51. "inline-synthetic-count", cl::Hidden, cl::init(15), cl::ZeroOrMore,
  52. cl::desc("Initial synthetic entry count for inline functions."));
  53. /// Initial synthetic count assigned to cold functions.
  54. static cl::opt<int> ColdSyntheticCount(
  55. "cold-synthetic-count", cl::Hidden, cl::init(5), cl::ZeroOrMore,
  56. cl::desc("Initial synthetic entry count for cold functions."));
  57. // Assign initial synthetic entry counts to functions.
  58. static void
  59. initializeCounts(Module &M, function_ref<void(Function *, uint64_t)> SetCount) {
  60. auto MayHaveIndirectCalls = [](Function &F) {
  61. for (auto *U : F.users()) {
  62. if (!isa<CallInst>(U) && !isa<InvokeInst>(U))
  63. return true;
  64. }
  65. return false;
  66. };
  67. for (Function &F : M) {
  68. uint64_t InitialCount = InitialSyntheticCount;
  69. if (F.isDeclaration())
  70. continue;
  71. if (F.hasFnAttribute(Attribute::AlwaysInline) ||
  72. F.hasFnAttribute(Attribute::InlineHint)) {
  73. // Use a higher value for inline functions to account for the fact that
  74. // these are usually beneficial to inline.
  75. InitialCount = InlineSyntheticCount;
  76. } else if (F.hasLocalLinkage() && !MayHaveIndirectCalls(F)) {
  77. // Local functions without inline hints get counts only through
  78. // propagation.
  79. InitialCount = 0;
  80. } else if (F.hasFnAttribute(Attribute::Cold) ||
  81. F.hasFnAttribute(Attribute::NoInline)) {
  82. // Use a lower value for noinline and cold functions.
  83. InitialCount = ColdSyntheticCount;
  84. }
  85. SetCount(&F, InitialCount);
  86. }
  87. }
  88. PreservedAnalyses SyntheticCountsPropagation::run(Module &M,
  89. ModuleAnalysisManager &MAM) {
  90. FunctionAnalysisManager &FAM =
  91. MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
  92. DenseMap<Function *, Scaled64> Counts;
  93. // Set initial entry counts.
  94. initializeCounts(
  95. M, [&](Function *F, uint64_t Count) { Counts[F] = Scaled64(Count, 0); });
  96. // Edge includes information about the source. Hence ignore the first
  97. // parameter.
  98. auto GetCallSiteProfCount = [&](const CallGraphNode *,
  99. const CallGraphNode::CallRecord &Edge) {
  100. Optional<Scaled64> Res = None;
  101. if (!Edge.first)
  102. return Res;
  103. CallBase &CB = *cast<CallBase>(*Edge.first);
  104. Function *Caller = CB.getCaller();
  105. auto &BFI = FAM.getResult<BlockFrequencyAnalysis>(*Caller);
  106. // Now compute the callsite count from relative frequency and
  107. // entry count:
  108. BasicBlock *CSBB = CB.getParent();
  109. Scaled64 EntryFreq(BFI.getEntryFreq(), 0);
  110. Scaled64 BBCount(BFI.getBlockFreq(CSBB).getFrequency(), 0);
  111. BBCount /= EntryFreq;
  112. BBCount *= Counts[Caller];
  113. return Optional<Scaled64>(BBCount);
  114. };
  115. CallGraph CG(M);
  116. // Propgate the entry counts on the callgraph.
  117. SyntheticCountsUtils<const CallGraph *>::propagate(
  118. &CG, GetCallSiteProfCount, [&](const CallGraphNode *N, Scaled64 New) {
  119. auto F = N->getFunction();
  120. if (!F || F->isDeclaration())
  121. return;
  122. Counts[F] += New;
  123. });
  124. // Set the counts as metadata.
  125. for (auto Entry : Counts) {
  126. Entry.first->setEntryCount(ProfileCount(
  127. Entry.second.template toInt<uint64_t>(), Function::PCT_Synthetic));
  128. }
  129. return PreservedAnalyses::all();
  130. }