Blame jemalloc/src/div.c

Packit 345191
#include "jemalloc/internal/jemalloc_preamble.h"
Packit 345191
Packit 345191
#include "jemalloc/internal/div.h"
Packit 345191
Packit 345191
#include "jemalloc/internal/assert.h"
Packit 345191
Packit 345191
/*
Packit 345191
 * Suppose we have n = q * d, all integers. We know n and d, and want q = n / d.
Packit 345191
 *
Packit 345191
 * For any k, we have (here, all division is exact; not C-style rounding):
Packit 345191
 * floor(ceil(2^k / d) * n / 2^k) = floor((2^k + r) / d * n / 2^k), where
Packit 345191
 * r = (-2^k) mod d.
Packit 345191
 *
Packit 345191
 * Expanding this out:
Packit 345191
 * ... = floor(2^k / d * n / 2^k + r / d * n / 2^k)
Packit 345191
 *     = floor(n / d + (r / d) * (n / 2^k)).
Packit 345191
 *
Packit 345191
 * The fractional part of n / d is 0 (because of the assumption that d divides n
Packit 345191
 * exactly), so we have:
Packit 345191
 * ... = n / d + floor((r / d) * (n / 2^k))
Packit 345191
 *
Packit 345191
 * So that our initial expression is equal to the quantity we seek, so long as
Packit 345191
 * (r / d) * (n / 2^k) < 1.
Packit 345191
 *
Packit 345191
 * r is a remainder mod d, so r < d and r / d < 1 always. We can make
Packit 345191
 * n / 2 ^ k < 1 by setting k = 32. This gets us a value of magic that works.
Packit 345191
 */
Packit 345191
Packit 345191
void
Packit 345191
div_init(div_info_t *div_info, size_t d) {
Packit 345191
	/* Nonsensical. */
Packit 345191
	assert(d != 0);
Packit 345191
	/*
Packit 345191
	 * This would make the value of magic too high to fit into a uint32_t
Packit 345191
	 * (we would want magic = 2^32 exactly). This would mess with code gen
Packit 345191
	 * on 32-bit machines.
Packit 345191
	 */
Packit 345191
	assert(d != 1);
Packit 345191
Packit 345191
	uint64_t two_to_k = ((uint64_t)1 << 32);
Packit 345191
	uint32_t magic = (uint32_t)(two_to_k / d);
Packit 345191
Packit 345191
	/*
Packit 345191
	 * We want magic = ceil(2^k / d), but C gives us floor. We have to
Packit 345191
	 * increment it unless the result was exact (i.e. unless d is a power of
Packit 345191
	 * two).
Packit 345191
	 */
Packit 345191
	if (two_to_k % d != 0) {
Packit 345191
		magic++;
Packit 345191
	}
Packit 345191
	div_info->magic = magic;
Packit 345191
#ifdef JEMALLOC_DEBUG
Packit 345191
	div_info->d = d;
Packit 345191
#endif
Packit 345191
}