#include "jemalloc/internal/jemalloc_preamble.h"12#include "jemalloc/internal/div.h"34#include "jemalloc/internal/assert.h"56/*7* Suppose we have n = q * d, all integers. We know n and d, and want q = n / d.8*9* For any k, we have (here, all division is exact; not C-style rounding):10* floor(ceil(2^k / d) * n / 2^k) = floor((2^k + r) / d * n / 2^k), where11* r = (-2^k) mod d.12*13* Expanding this out:14* ... = floor(2^k / d * n / 2^k + r / d * n / 2^k)15* = floor(n / d + (r / d) * (n / 2^k)).16*17* The fractional part of n / d is 0 (because of the assumption that d divides n18* exactly), so we have:19* ... = n / d + floor((r / d) * (n / 2^k))20*21* So that our initial expression is equal to the quantity we seek, so long as22* (r / d) * (n / 2^k) < 1.23*24* r is a remainder mod d, so r < d and r / d < 1 always. We can make25* n / 2 ^ k < 1 by setting k = 32. This gets us a value of magic that works.26*/2728void29div_init(div_info_t *div_info, size_t d) {30/* Nonsensical. */31assert(d != 0);32/*33* This would make the value of magic too high to fit into a uint32_t34* (we would want magic = 2^32 exactly). This would mess with code gen35* on 32-bit machines.36*/37assert(d != 1);3839uint64_t two_to_k = ((uint64_t)1 << 32);40uint32_t magic = (uint32_t)(two_to_k / d);4142/*43* We want magic = ceil(2^k / d), but C gives us floor. We have to44* increment it unless the result was exact (i.e. unless d is a power of45* two).46*/47if (two_to_k % d != 0) {48magic++;49}50div_info->magic = magic;51#ifdef JEMALLOC_DEBUG52div_info->d = d;53#endif54}555657