BranchProbability.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- BranchProbability.h - Branch Probability Wrapper ---------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // Definition of BranchProbability shared by IR and Machine Instructions.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_SUPPORT_BRANCHPROBABILITY_H
  18. #define LLVM_SUPPORT_BRANCHPROBABILITY_H
  19. #include "llvm/Support/DataTypes.h"
  20. #include <algorithm>
  21. #include <cassert>
  22. #include <numeric>
  23. namespace llvm {
  24. class raw_ostream;
  25. // This class represents Branch Probability as a non-negative fraction that is
  26. // no greater than 1. It uses a fixed-point-like implementation, in which the
  27. // denominator is always a constant value (here we use 1<<31 for maximum
  28. // precision).
  29. class BranchProbability {
  30. // Numerator
  31. uint32_t N;
  32. // Denominator, which is a constant value.
  33. static constexpr uint32_t D = 1u << 31;
  34. static constexpr uint32_t UnknownN = UINT32_MAX;
  35. // Construct a BranchProbability with only numerator assuming the denominator
  36. // is 1<<31. For internal use only.
  37. explicit BranchProbability(uint32_t n) : N(n) {}
  38. public:
  39. BranchProbability() : N(UnknownN) {}
  40. BranchProbability(uint32_t Numerator, uint32_t Denominator);
  41. bool isZero() const { return N == 0; }
  42. bool isUnknown() const { return N == UnknownN; }
  43. static BranchProbability getZero() { return BranchProbability(0); }
  44. static BranchProbability getOne() { return BranchProbability(D); }
  45. static BranchProbability getUnknown() { return BranchProbability(UnknownN); }
  46. // Create a BranchProbability object with the given numerator and 1<<31
  47. // as denominator.
  48. static BranchProbability getRaw(uint32_t N) { return BranchProbability(N); }
  49. // Create a BranchProbability object from 64-bit integers.
  50. static BranchProbability getBranchProbability(uint64_t Numerator,
  51. uint64_t Denominator);
  52. // Normalize given probabilties so that the sum of them becomes approximate
  53. // one.
  54. template <class ProbabilityIter>
  55. static void normalizeProbabilities(ProbabilityIter Begin,
  56. ProbabilityIter End);
  57. uint32_t getNumerator() const { return N; }
  58. static uint32_t getDenominator() { return D; }
  59. // Return (1 - Probability).
  60. BranchProbability getCompl() const { return BranchProbability(D - N); }
  61. raw_ostream &print(raw_ostream &OS) const;
  62. void dump() const;
  63. /// Scale a large integer.
  64. ///
  65. /// Scales \c Num. Guarantees full precision. Returns the floor of the
  66. /// result.
  67. ///
  68. /// \return \c Num times \c this.
  69. uint64_t scale(uint64_t Num) const;
  70. /// Scale a large integer by the inverse.
  71. ///
  72. /// Scales \c Num by the inverse of \c this. Guarantees full precision.
  73. /// Returns the floor of the result.
  74. ///
  75. /// \return \c Num divided by \c this.
  76. uint64_t scaleByInverse(uint64_t Num) const;
  77. BranchProbability &operator+=(BranchProbability RHS) {
  78. assert(N != UnknownN && RHS.N != UnknownN &&
  79. "Unknown probability cannot participate in arithmetics.");
  80. // Saturate the result in case of overflow.
  81. N = (uint64_t(N) + RHS.N > D) ? D : N + RHS.N;
  82. return *this;
  83. }
  84. BranchProbability &operator-=(BranchProbability RHS) {
  85. assert(N != UnknownN && RHS.N != UnknownN &&
  86. "Unknown probability cannot participate in arithmetics.");
  87. // Saturate the result in case of underflow.
  88. N = N < RHS.N ? 0 : N - RHS.N;
  89. return *this;
  90. }
  91. BranchProbability &operator*=(BranchProbability RHS) {
  92. assert(N != UnknownN && RHS.N != UnknownN &&
  93. "Unknown probability cannot participate in arithmetics.");
  94. N = (static_cast<uint64_t>(N) * RHS.N + D / 2) / D;
  95. return *this;
  96. }
  97. BranchProbability &operator*=(uint32_t RHS) {
  98. assert(N != UnknownN &&
  99. "Unknown probability cannot participate in arithmetics.");
  100. N = (uint64_t(N) * RHS > D) ? D : N * RHS;
  101. return *this;
  102. }
  103. BranchProbability &operator/=(BranchProbability RHS) {
  104. assert(N != UnknownN && RHS.N != UnknownN &&
  105. "Unknown probability cannot participate in arithmetics.");
  106. N = (static_cast<uint64_t>(N) * D + RHS.N / 2) / RHS.N;
  107. return *this;
  108. }
  109. BranchProbability &operator/=(uint32_t RHS) {
  110. assert(N != UnknownN &&
  111. "Unknown probability cannot participate in arithmetics.");
  112. assert(RHS > 0 && "The divider cannot be zero.");
  113. N /= RHS;
  114. return *this;
  115. }
  116. BranchProbability operator+(BranchProbability RHS) const {
  117. BranchProbability Prob(*this);
  118. Prob += RHS;
  119. return Prob;
  120. }
  121. BranchProbability operator-(BranchProbability RHS) const {
  122. BranchProbability Prob(*this);
  123. Prob -= RHS;
  124. return Prob;
  125. }
  126. BranchProbability operator*(BranchProbability RHS) const {
  127. BranchProbability Prob(*this);
  128. Prob *= RHS;
  129. return Prob;
  130. }
  131. BranchProbability operator*(uint32_t RHS) const {
  132. BranchProbability Prob(*this);
  133. Prob *= RHS;
  134. return Prob;
  135. }
  136. BranchProbability operator/(BranchProbability RHS) const {
  137. BranchProbability Prob(*this);
  138. Prob /= RHS;
  139. return Prob;
  140. }
  141. BranchProbability operator/(uint32_t RHS) const {
  142. BranchProbability Prob(*this);
  143. Prob /= RHS;
  144. return Prob;
  145. }
  146. bool operator==(BranchProbability RHS) const { return N == RHS.N; }
  147. bool operator!=(BranchProbability RHS) const { return !(*this == RHS); }
  148. bool operator<(BranchProbability RHS) const {
  149. assert(N != UnknownN && RHS.N != UnknownN &&
  150. "Unknown probability cannot participate in comparisons.");
  151. return N < RHS.N;
  152. }
  153. bool operator>(BranchProbability RHS) const {
  154. assert(N != UnknownN && RHS.N != UnknownN &&
  155. "Unknown probability cannot participate in comparisons.");
  156. return RHS < *this;
  157. }
  158. bool operator<=(BranchProbability RHS) const {
  159. assert(N != UnknownN && RHS.N != UnknownN &&
  160. "Unknown probability cannot participate in comparisons.");
  161. return !(RHS < *this);
  162. }
  163. bool operator>=(BranchProbability RHS) const {
  164. assert(N != UnknownN && RHS.N != UnknownN &&
  165. "Unknown probability cannot participate in comparisons.");
  166. return !(*this < RHS);
  167. }
  168. };
  169. inline raw_ostream &operator<<(raw_ostream &OS, BranchProbability Prob) {
  170. return Prob.print(OS);
  171. }
  172. template <class ProbabilityIter>
  173. void BranchProbability::normalizeProbabilities(ProbabilityIter Begin,
  174. ProbabilityIter End) {
  175. if (Begin == End)
  176. return;
  177. unsigned UnknownProbCount = 0;
  178. uint64_t Sum = std::accumulate(Begin, End, uint64_t(0),
  179. [&](uint64_t S, const BranchProbability &BP) {
  180. if (!BP.isUnknown())
  181. return S + BP.N;
  182. UnknownProbCount++;
  183. return S;
  184. });
  185. if (UnknownProbCount > 0) {
  186. BranchProbability ProbForUnknown = BranchProbability::getZero();
  187. // If the sum of all known probabilities is less than one, evenly distribute
  188. // the complement of sum to unknown probabilities. Otherwise, set unknown
  189. // probabilities to zeros and continue to normalize known probabilities.
  190. if (Sum < BranchProbability::getDenominator())
  191. ProbForUnknown = BranchProbability::getRaw(
  192. (BranchProbability::getDenominator() - Sum) / UnknownProbCount);
  193. std::replace_if(Begin, End,
  194. [](const BranchProbability &BP) { return BP.isUnknown(); },
  195. ProbForUnknown);
  196. if (Sum <= BranchProbability::getDenominator())
  197. return;
  198. }
  199. if (Sum == 0) {
  200. BranchProbability BP(1, std::distance(Begin, End));
  201. std::fill(Begin, End, BP);
  202. return;
  203. }
  204. for (auto I = Begin; I != End; ++I)
  205. I->N = (I->N * uint64_t(D) + Sum / 2) / Sum;
  206. }
  207. }
  208. #endif
  209. #ifdef __GNUC__
  210. #pragma GCC diagnostic pop
  211. #endif