MySQL 8.4.3
Source Code Documentation
ut0math.h
Go to the documentation of this file.
1/*****************************************************************************
2
3Copyright (c) 2021, 2024, Oracle and/or its affiliates.
4
5This program is free software; you can redistribute it and/or modify it under
6the terms of the GNU General Public License, version 2.0, as published by the
7Free Software Foundation.
8
9This program is designed to work with certain software (including
10but not limited to OpenSSL) that is licensed under separate terms,
11as designated in a particular file or component or in included license
12documentation. The authors of MySQL hereby grant you an additional
13permission to link the program and your derivative works with the
14separately licensed software that they have either included with
15the program or referenced in the documentation.
16
17This program is distributed in the hope that it will be useful, but WITHOUT
18ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20for more details.
21
22You should have received a copy of the GNU General Public License along with
23this program; if not, write to the Free Software Foundation, Inc.,
2451 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26*****************************************************************************/
27
28/** @file include/ut0math.h
29 Math functions.
30
31 ***********************************************************************/
32
33#ifndef ut0math_h
34#define ut0math_h
35
36#include <atomic>
37#include <cstdint>
38#include "ut0class_life_cycle.h"
39#include "ut0dbg.h"
40#include "ut0seq_lock.h"
41
42namespace ut {
43/** Computes the result of division rounded towards positive infinity.
44@param[in] numerator The number you want to be divided
45@param[in] denominator The number you want to divide by
46@return ceil(numerator/denominator). */
47template <typename T>
48constexpr T div_ceil(T numerator, T denominator) {
49 static_assert(std::is_integral_v<T>, "div_ceil<T> needs integral T");
50 /* see https://gist.github.com/Eisenwave/2a7d7a4e74e99bbb513984107a6c63ef
51 for list of common pitfalls, and this beautiful solution which compiles to
52 - branchless code with one division operation for unsigned ints,
53 - branchless (but longer) code with one division operation for signed ints,
54 - branchless code with just shifts and adds for constant d=constexpr 2^k,
55 - branchless code with multiplication instead of division for constexpr d
56 All that correctly handling negative numerators, denominators, and values
57 close to or equal to the max() or min(). */
58 const bool quotient_not_negative{(numerator < 0) == (denominator < 0)};
59 return numerator / denominator +
60 (quotient_not_negative && numerator % denominator != 0);
61}
62
63/** Calculates the 128bit result of multiplication of the two specified 64bit
64integers. May use CPU native instructions for speed of standard uint64_t
65multiplication.
66@param[in] x First number to multiply.
67@param[in] y Second number to multiply.
68@param[out] hi A reference to 64bit integer that will store higher 64bits of the
69result.
70@return The lower 64bit of the result. */
71[[nodiscard]] static inline uint64_t multiply_uint64(uint64_t x, uint64_t y,
72 uint64_t &hi);
73
74/*Calculates the 64bit result of division of the specified 128bit integer by the
75specified 64bit integer. The result must fit in 64bit or else the behavior is
76undefined. Currently does not use native CPU instructions and can be quite slow.
77@param[in] high High 64bits of the number to divide.
78@param[in] low Low 64bits of the number to divide.
79@param[in] div The number to divide by.
80@return The lower 64bit of the result. */
81[[nodiscard]] static inline uint64_t divide_128(uint64_t high, uint64_t low,
82 uint64_t div);
83class fast_modulo_t;
84
85/** Looks for a prime number slightly greater than the given argument.
86The prime is chosen so that it is not near any power of 2.
87@param[in] n positive number > 100
88@return prime */
89[[nodiscard]] uint64_t find_prime(uint64_t n);
90
91namespace detail {
92/** Calculates the 128bit result of multiplication of the two specified 64bit
93integers.
94@param[in] x First number to multiply.
95@param[in] y Second number to multiply.
96@param[out] hi A reference to 64bit integer that will store higher 64bits of the
97result.
98@return The lower 64bit of the result. */
99[[nodiscard]] constexpr uint64_t multiply_uint64_portable(uint64_t x,
100 uint64_t y,
101 uint64_t &hi) {
102 uint32_t x_hi = static_cast<uint32_t>(x >> 32);
103 uint32_t x_lo = static_cast<uint32_t>(x);
104 uint32_t y_hi = static_cast<uint32_t>(y >> 32);
105 uint32_t y_lo = static_cast<uint32_t>(y);
106
107 uint64_t hi_lo = static_cast<uint64_t>(x_hi) * y_lo;
108
109 uint64_t low = static_cast<uint64_t>(x_lo) * y_lo;
110 /* This will not overflow, as (2^32 -1)^2 = 2^64 - 1 - 2 * 2^32, so there is
111 still a place for two 32bit integers to be added. */
112 uint64_t mid = (low >> 32) + static_cast<uint64_t>(x_lo) * y_hi +
113 static_cast<uint32_t>(hi_lo);
114 hi = (mid >> 32) + static_cast<uint64_t>(x_hi) * y_hi + (hi_lo >> 32);
115 return static_cast<uint32_t>(low) + (mid << 32);
116}
117} // namespace detail
118
119#if defined(_MSC_VER) && defined(_M_X64) && !defined(_M_ARM64EC)
120/* MSVC x86 supports native uint64_t -> uint128_t multiplication */
121#include <intrin.h>
122#pragma intrinsic(_umul128)
123[[nodiscard]] static inline uint64_t multiply_uint64(uint64_t x, uint64_t y,
124 uint64_t &hi) {
125 return _umul128(x, y, &hi);
126}
127#elif defined(__SIZEOF_INT128__)
128/* Compiler supports 128-bit values (GCC/Clang) */
129
130[[nodiscard]] static inline uint64_t multiply_uint64(uint64_t x, uint64_t y,
131 uint64_t &hi) {
132 unsigned __int128 res = (unsigned __int128)x * y;
133 hi = static_cast<uint64_t>(res >> 64);
134 return static_cast<uint64_t>(res);
135}
136#else
137[[nodiscard]] static inline uint64_t multiply_uint64(uint64_t x, uint64_t y,
138 uint64_t &hi) {
139 return detail::multiply_uint64_portable(x, y, hi);
140}
141#endif
142
143[[nodiscard]] static inline uint64_t divide_128(uint64_t high, uint64_t low,
144 uint64_t div) {
145 uint64_t res = 0;
146 for (auto current_bit = 63; current_bit >= 0; current_bit--) {
147 const auto div_hi = current_bit ? (div >> (64 - current_bit)) : 0;
148 const auto div_lo = div << current_bit;
149 if (div_hi < high || (div_hi == high && div_lo <= low)) {
150 high -= div_hi;
151 if (low < div_lo) {
152 high--;
153 }
154 low -= div_lo;
155 res += 1ULL << current_bit;
156 }
157 }
158 return res;
159}
160
161/** Allows to execute x % mod for a specified mod in a fast way, without using a
162slow operation of division. The additional cost is hidden in constructor to
163preprocess the mod constant. */
165 /* Idea behind this implementation is following: (division sign in all
166 equations below is to be treated as mathematical division on reals)
167
168 x % mod = x - floor(x/mod)*mod
169
170 and...
171
172 x / mod = x * 1/mod = (x * (BIG/mod)) /BIG
173
174 and..
175
176 floor(x/mod) = x / mod - epsilon, where 0<=epsilon<1
177
178 Now, lets define:
179
180 M = floor(BIG/mod)
181
182 And take a look at the value of following expression:
183
184 floor( x*M / BIG) * mod =
185
186 floor(x * floor(BIG/mod) / BIG) * mod =
187 floor(x * ((BIG/mod)-epsilon1) / BIG) * mod =
188 ((x*((BIG/mod)-epsilon1)/BIG - epsilon2) * mod
189
190 This sure looks ugly, but it has interesting properties:
191 (1) is divisible by mod, which you can see, because it has a form (...)*
192 mod
193 (2) is smaller or equal to x, which you can see by setting epsilons to 0
194 (3) assuming BIG>x, the expression is strictly larger than x - 2*mod,
195 because it must be larger than the value for epsilons=1, which is:
196 ((x*((BIG/mod)-1))/BIG - 1) * mod =
197 ((x*BIG/mod - x)/BIG -1) * mod =
198 ((x/mod - x/BIG) - 1) * mod =
199 (x - x/BIG*mod - mod)
200 (4) we can compute it without using division at all, if BIG is 1<<k,
201 as it simplifies to
202 (( x * M ) >> k ) * mod
203
204 So, assuming BIG>x, and is a power of two (say BIG=1<<64), we get an
205 expression, which is divisible by mod, and if we subtract it from x, we get
206 something in the range [0...,2mod). What is left is to compare against mod,
207 and subtract it if it is higher.
208 */
209
210 public:
211 fast_modulo_t() = default;
212 explicit fast_modulo_t(uint64_t mod)
213 : m_mod(mod), m_inv(precompute_inv(mod)) {}
214 explicit fast_modulo_t(uint64_t mod, uint64_t inv) : m_mod(mod), m_inv(inv) {}
215
216 /** Computes the value of x % mod. */
217 uint64_t compute(uint64_t x) const {
218 uint64_t hi;
219 (void)multiply_uint64(x, m_inv, hi);
220
221 const uint64_t guess = hi * m_mod;
222 const uint64_t rest = x - guess;
223
224 return rest - (m_mod <= rest) * m_mod;
225 }
226
227 /** Gets the precomputed value of inverse. */
228 uint64_t get_inverse() const { return m_inv; }
229
230 /** Gets the modulo value. */
231 uint64_t get_mod() const { return m_mod; }
232
233 /** Precomputes the inverse needed for fast modulo operations. */
234 static uint64_t precompute_inv(uint64_t mod) {
235 /* pedantic matter: for mod=1 -- you can remove it if you never plan to use
236 it for 1. */
237 if (mod == 1) {
238 /* According to equations we want M to be 1<<64, but this overflows
239 uint64_t, so, let's do the second best thing we can, which is 1<<64-1,
240 this means that our `guess` will be ((x<<64 - x) >> 64)*mod, which for
241 x=0, is 0 (good), and for x>0 is (x-1)*mod = (x-1)*1 = x-1, and then
242 rest=1, which is also good enough (<2*mod). */
243 return ~uint64_t{0};
244 } else {
245 return divide_128(1, 0, mod);
246 }
247 }
248
249 private:
250 uint64_t m_mod{0};
251 uint64_t m_inv{0};
252};
253
254/** A class that allows to atomically set new modulo value for fast modulo
255computations. */
257 public:
258 mt_fast_modulo_t() : m_data{0ULL, 0ULL} {}
259 explicit mt_fast_modulo_t(uint64_t mod)
260 : m_data{mod, fast_modulo_t::precompute_inv(mod)} {}
261 /* This class can be made copyable, but this requires additional constructors.
262 */
263
265 return m_data.read([](const data_t &stored_data) {
266 return fast_modulo_t{stored_data.m_mod.load(std::memory_order_relaxed),
267 stored_data.m_inv.load(std::memory_order_relaxed)};
268 });
269 }
270
271 void store(uint64_t new_mod) {
272 const fast_modulo_t new_fast_modulo{new_mod};
273 const auto inv = new_fast_modulo.get_inverse();
274 m_data.write([&](data_t &data) {
275 data.m_mod.store(new_mod, std::memory_order_relaxed);
276 data.m_inv.store(inv, std::memory_order_relaxed);
277 });
278 }
279
280 private:
281 struct data_t {
282 std::atomic<uint64_t> m_mod;
283 std::atomic<uint64_t> m_inv;
284 };
285
287};
288
289} // namespace ut
290
291static inline uint64_t operator%(uint64_t x, const ut::fast_modulo_t &fm) {
292 return fm.compute(x);
293}
294
295#endif
A utility class which, if inherited from, prevents the descendant class from being copied,...
Definition: ut0class_life_cycle.h:41
A class that allows to read value of variable of some type T atomically and allows the value to be ch...
Definition: ut0seq_lock.h:49
Allows to execute x % mod for a specified mod in a fast way, without using a slow operation of divisi...
Definition: ut0math.h:164
uint64_t get_inverse() const
Gets the precomputed value of inverse.
Definition: ut0math.h:228
uint64_t m_inv
Definition: ut0math.h:251
uint64_t compute(uint64_t x) const
Computes the value of x % mod.
Definition: ut0math.h:217
fast_modulo_t(uint64_t mod)
Definition: ut0math.h:212
static uint64_t precompute_inv(uint64_t mod)
Precomputes the inverse needed for fast modulo operations.
Definition: ut0math.h:234
uint64_t m_mod
Definition: ut0math.h:250
fast_modulo_t(uint64_t mod, uint64_t inv)
Definition: ut0math.h:214
uint64_t get_mod() const
Gets the modulo value.
Definition: ut0math.h:231
fast_modulo_t()=default
A class that allows to atomically set new modulo value for fast modulo computations.
Definition: ut0math.h:256
mt_fast_modulo_t()
Definition: ut0math.h:258
mt_fast_modulo_t(uint64_t mod)
Definition: ut0math.h:259
void store(uint64_t new_mod)
Definition: ut0math.h:271
Seq_lock< data_t > m_data
Definition: ut0math.h:286
fast_modulo_t load() const
Definition: ut0math.h:264
Definition: ut0tuple.h:57
constexpr uint64_t multiply_uint64_portable(uint64_t x, uint64_t y, uint64_t &hi)
Calculates the 128bit result of multiplication of the two specified 64bit integers.
Definition: ut0math.h:99
This file contains a set of libraries providing overloads for regular dynamic allocation routines whi...
Definition: aligned_alloc.h:48
constexpr T div_ceil(T numerator, T denominator)
Computes the result of division rounded towards positive infinity.
Definition: ut0math.h:48
uint64_t find_prime(uint64_t n)
Looks for a prime number slightly greater than the given argument.
Definition: ut0math.cc:36
static uint64_t multiply_uint64(uint64_t x, uint64_t y, uint64_t &hi)
Calculates the 128bit result of multiplication of the two specified 64bit integers.
Definition: ut0math.h:137
static uint64_t divide_128(uint64_t high, uint64_t low, uint64_t div)
Definition: ut0math.h:143
Definition: ut0math.h:281
std::atomic< uint64_t > m_mod
Definition: ut0math.h:282
std::atomic< uint64_t > m_inv
Definition: ut0math.h:283
Utilities related to class lifecycle.
Debug utilities for Innobase.
static uint64_t operator%(uint64_t x, const ut::fast_modulo_t &fm)
Definition: ut0math.h:291
Implements a sequential lock structure for non-locking atomic read/write operations on a complex stru...
int n
Definition: xcom_base.cc:509