#ifndef LIBDIVIDE_H #define LIBDIVIDE_H #if defined(_MSC_VER) #pragma warning(disable: 4146) #define LIBDIVIDE_VC #endif #ifdef __cplusplus #include <cstdlib> #include <cstdio> #else #include <stdlib.h> #include <stdio.h> #endif #include <stdint.h> #if defined(LIBDIVIDE_USE_SSE2) #include <emmintrin.h> #endif #if defined(LIBDIVIDE_VC) #include <intrin.h> #endif #ifndef __has_builtin #define __has_builtin(x) 0 // Compatibility with non-clang compilers. #endif #if defined(__SIZEOF_INT128__) #define HAS_INT128_T #endif #if defined(__x86_64__) || defined(_WIN64) || defined(_M_X64) #define LIBDIVIDE_IS_X86_64 #endif #if defined(__i386__) #define LIBDIVIDE_IS_i386 #endif #if defined(__GNUC__) || defined(__clang__) #define LIBDIVIDE_GCC_STYLE_ASM #endif #if defined(__cplusplus) || defined(LIBDIVIDE_VC) #define LIBDIVIDE_FUNCTION __FUNCTION__ #else #define LIBDIVIDE_FUNCTION __func__ #endif #define LIBDIVIDE_ERROR(msg) \ do { \ fprintf(stderr, "libdivide.h:%d: %s(): Error: %s\n", \ __LINE__, LIBDIVIDE_FUNCTION, msg); \ exit(-1); \ } while (0) #if defined(LIBDIVIDE_ASSERTIONS_ON) #define LIBDIVIDE_ASSERT(x) \ do { \ if (!(x)) { \ fprintf(stderr, "libdivide.h:%d: %s(): Assertion failed: %s\n", \ __LINE__, LIBDIVIDE_FUNCTION, #x); \ exit(-1); \ } \ } while (0) #else #define LIBDIVIDE_ASSERT(x) #endif #ifdef LIBDIVIDE_USE_SSE4_1 #include <smmintrin.h> #endif #ifdef __cplusplus namespace { namespace libdivide { #endif enum { LIBDIVIDE_32_SHIFT_MASK = 0x1F, LIBDIVIDE_64_SHIFT_MASK = 0x3F, LIBDIVIDE_ADD_MARKER = 0x40, LIBDIVIDE_U32_SHIFT_PATH = 0x80, LIBDIVIDE_U64_SHIFT_PATH = 0x80, LIBDIVIDE_S32_SHIFT_PATH = 0x20, LIBDIVIDE_NEGATIVE_DIVISOR = 0x80 }; #pragma pack(push, 1) struct libdivide_u32_t { uint32_t magic; uint8_t more; }; struct libdivide_s32_t { int32_t magic; uint8_t more; }; struct libdivide_u64_t { uint64_t magic; uint8_t more; }; struct libdivide_s64_t { int64_t magic; uint8_t more; }; struct libdivide_u32_branchfree_t { uint32_t magic; uint8_t more; }; struct libdivide_s32_branchfree_t { int32_t magic; uint8_t more; }; struct libdivide_u64_branchfree_t { uint64_t magic; uint8_t more; }; struct libdivide_s64_branchfree_t { int64_t magic; uint8_t more; }; #pragma pack(pop) #ifndef LIBDIVIDE_API #ifdef __cplusplus // In C++, we don't want our public functions to be static, because // they are arguments to templates and static functions can't do that. // They get internal linkage through virtue of the anonymous namespace. // In C, they should be static. #define LIBDIVIDE_API #else #define LIBDIVIDE_API static inline #endif #endif LIBDIVIDE_API struct libdivide_s32_t libdivide_s32_gen(int32_t y); LIBDIVIDE_API struct libdivide_u32_t libdivide_u32_gen(uint32_t y); LIBDIVIDE_API struct libdivide_s64_t libdivide_s64_gen(int64_t y); LIBDIVIDE_API struct libdivide_u64_t libdivide_u64_gen(uint64_t y); LIBDIVIDE_API struct libdivide_s32_branchfree_t libdivide_s32_branchfree_gen(int32_t y); LIBDIVIDE_API struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t y); LIBDIVIDE_API struct libdivide_s64_branchfree_t libdivide_s64_branchfree_gen(int64_t y); LIBDIVIDE_API struct libdivide_u64_branchfree_t libdivide_u64_branchfree_gen(uint64_t y); LIBDIVIDE_API int32_t libdivide_s32_do(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do(int64_t numer, const struct libdivide_s64_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_do(uint64_t y, const struct libdivide_u64_t *denom); LIBDIVIDE_API int32_t libdivide_s32_branchfree_do(int32_t numer, const struct libdivide_s32_branchfree_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom); LIBDIVIDE_API int64_t libdivide_s64_branchfree_do(int64_t numer, const struct libdivide_s64_branchfree_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_branchfree_do(uint64_t y, const struct libdivide_u64_branchfree_t *denom); LIBDIVIDE_API int32_t libdivide_s32_recover(const struct libdivide_s32_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom); LIBDIVIDE_API int64_t libdivide_s64_recover(const struct libdivide_s64_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_recover(const struct libdivide_u64_t *denom); LIBDIVIDE_API int32_t libdivide_s32_branchfree_recover(const struct libdivide_s32_branchfree_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom); LIBDIVIDE_API int64_t libdivide_s64_branchfree_recover(const struct libdivide_s64_branchfree_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_branchfree_recover(const struct libdivide_u64_branchfree_t *denom); LIBDIVIDE_API int libdivide_u32_get_algorithm(const struct libdivide_u32_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_do_alg0(uint32_t numer, const struct libdivide_u32_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_do_alg1(uint32_t numer, const struct libdivide_u32_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_do_alg2(uint32_t numer, const struct libdivide_u32_t *denom); LIBDIVIDE_API int libdivide_u64_get_algorithm(const struct libdivide_u64_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_do_alg0(uint64_t numer, const struct libdivide_u64_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_do_alg1(uint64_t numer, const struct libdivide_u64_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_do_alg2(uint64_t numer, const struct libdivide_u64_t *denom); LIBDIVIDE_API int libdivide_s32_get_algorithm(const struct libdivide_s32_t *denom); LIBDIVIDE_API int32_t libdivide_s32_do_alg0(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API int32_t libdivide_s32_do_alg1(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API int32_t libdivide_s32_do_alg2(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API int32_t libdivide_s32_do_alg3(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API int32_t libdivide_s32_do_alg4(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API int libdivide_s64_get_algorithm(const struct libdivide_s64_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do_alg0(int64_t numer, const struct libdivide_s64_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do_alg1(int64_t numer, const struct libdivide_s64_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do_alg2(int64_t numer, const struct libdivide_s64_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do_alg3(int64_t numer, const struct libdivide_s64_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do_alg4(int64_t numer, const struct libdivide_s64_t *denom); #if defined(LIBDIVIDE_USE_SSE2) LIBDIVIDE_API __m128i libdivide_u32_do_vector(__m128i numers, const struct libdivide_u32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_u64_do_vector(__m128i numers, const struct libdivide_u64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_u32_do_vector_alg0(__m128i numers, const struct libdivide_u32_t *denom); LIBDIVIDE_API __m128i libdivide_u32_do_vector_alg1(__m128i numers, const struct libdivide_u32_t *denom); LIBDIVIDE_API __m128i libdivide_u32_do_vector_alg2(__m128i numers, const struct libdivide_u32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector_alg0(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector_alg1(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector_alg2(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector_alg3(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector_alg4(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_u64_do_vector_alg0(__m128i numers, const struct libdivide_u64_t *denom); LIBDIVIDE_API __m128i libdivide_u64_do_vector_alg1(__m128i numers, const struct libdivide_u64_t *denom); LIBDIVIDE_API __m128i libdivide_u64_do_vector_alg2(__m128i numers, const struct libdivide_u64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector_alg0(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector_alg1(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector_alg2(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector_alg3(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector_alg4(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_u32_branchfree_do_vector(__m128i numers, const struct libdivide_u32_branchfree_t *denom); LIBDIVIDE_API __m128i libdivide_s32_branchfree_do_vector(__m128i numers, const struct libdivide_s32_branchfree_t *denom); LIBDIVIDE_API __m128i libdivide_u64_branchfree_do_vector(__m128i numers, const struct libdivide_u64_branchfree_t *denom); LIBDIVIDE_API __m128i libdivide_s64_branchfree_do_vector(__m128i numers, const struct libdivide_s64_branchfree_t *denom); #endif static inline uint32_t libdivide__mullhi_u32(uint32_t x, uint32_t y) { uint64_t xl = x, yl = y; uint64_t rl = xl * yl; return (uint32_t)(rl >> 32); } static uint64_t libdivide__mullhi_u64(uint64_t x, uint64_t y) { #if defined(LIBDIVIDE_VC) && defined(LIBDIVIDE_IS_X86_64) return __umulh(x, y); #elif defined(HAS_INT128_T) __uint128_t xl = x, yl = y; __uint128_t rl = xl * yl; return (uint64_t)(rl >> 64); #else // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) uint32_t mask = 0xFFFFFFFF; uint32_t x0 = (uint32_t)(x & mask); uint32_t x1 = (uint32_t)(x >> 32); uint32_t y0 = (uint32_t)(y & mask); uint32_t y1 = (uint32_t)(y >> 32); uint32_t x0y0_hi = libdivide__mullhi_u32(x0, y0); uint64_t x0y1 = x0 * (uint64_t)y1; uint64_t x1y0 = x1 * (uint64_t)y0; uint64_t x1y1 = x1 * (uint64_t)y1; uint64_t temp = x1y0 + x0y0_hi; uint64_t temp_lo = temp & mask; uint64_t temp_hi = temp >> 32; return x1y1 + temp_hi + ((temp_lo + x0y1) >> 32); #endif } static inline int64_t libdivide__mullhi_s64(int64_t x, int64_t y) { #if defined(LIBDIVIDE_VC) && defined(LIBDIVIDE_IS_X86_64) return __mulh(x, y); #elif defined(HAS_INT128_T) __int128_t xl = x, yl = y; __int128_t rl = xl * yl; return (int64_t)(rl >> 64); #else // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) uint32_t mask = 0xFFFFFFFF; uint32_t x0 = (uint32_t)(x & mask); uint32_t y0 = (uint32_t)(y & mask); int32_t x1 = (int32_t)(x >> 32); int32_t y1 = (int32_t)(y >> 32); uint32_t x0y0_hi = libdivide__mullhi_u32(x0, y0); int64_t t = x1 * (int64_t)y0 + x0y0_hi; int64_t w1 = x0 * (int64_t)y1 + (t & mask); return x1 * (int64_t)y1 + (t >> 32) + (w1 >> 32); #endif } #if defined(LIBDIVIDE_USE_SSE2) static inline __m128i libdivide__u64_to_m128(uint64_t x) { #if defined(LIBDIVIDE_VC) && !defined(_WIN64) // 64 bit windows doesn't seem to have an implementation of any of these // load intrinsics, and 32 bit Visual C++ crashes _declspec(align(16)) uint64_t temp[2] = {x, x}; return _mm_load_si128((const __m128i*)temp); #else // everyone else gets it right return _mm_set1_epi64x(x); #endif } static inline __m128i libdivide_get_FFFFFFFF00000000(void) { // returns the same as _mm_set1_epi64(0xFFFFFFFF00000000ULL) // without touching memory. // optimizes to pcmpeqd on OS X __m128i result = _mm_set1_epi8(-1); return _mm_slli_epi64(result, 32); } static inline __m128i libdivide_get_00000000FFFFFFFF(void) { // returns the same as _mm_set1_epi64(0x00000000FFFFFFFFULL) // without touching memory. // optimizes to pcmpeqd on OS X __m128i result = _mm_set1_epi8(-1); result = _mm_srli_epi64(result, 32); return result; } static inline __m128i libdivide_s64_signbits(__m128i v) { // we want to compute v >> 63, that is, _mm_srai_epi64(v, 63). But there // is no 64 bit shift right arithmetic instruction in SSE2. So we have to // fake it by first duplicating the high 32 bit values, and then using a 32 // bit shift. Another option would be to use _mm_srli_epi64(v, 63) and // then subtract that from 0, but that approach appears to be substantially // slower for unknown reasons __m128i hiBitsDuped = _mm_shuffle_epi32(v, _MM_SHUFFLE(3, 3, 1, 1)); __m128i signBits = _mm_srai_epi32(hiBitsDuped, 31); return signBits; } static inline __m128i libdivide_u32_to_m128i(uint32_t amt) { return _mm_set_epi32(0, 0, 0, amt); } static inline __m128i libdivide_s64_shift_right_vector(__m128i v, int amt) { // implementation of _mm_sra_epi64. Here we have two 64 bit values which // are shifted right to logically become (64 - amt) values, and are then // sign extended from a (64 - amt) bit number. const int b = 64 - amt; __m128i m = libdivide__u64_to_m128(1ULL << (b - 1)); __m128i x = _mm_srl_epi64(v, libdivide_u32_to_m128i(amt)); __m128i result = _mm_sub_epi64(_mm_xor_si128(x, m), m); // result = x^m - m return result; } static inline __m128i libdivide__mullhi_u32_flat_vector(__m128i a, __m128i b) { __m128i hi_product_0Z2Z = _mm_srli_epi64(_mm_mul_epu32(a, b), 32); __m128i a1X3X = _mm_srli_epi64(a, 32); __m128i mask = libdivide_get_FFFFFFFF00000000(); __m128i hi_product_Z1Z3 = _mm_and_si128(_mm_mul_epu32(a1X3X, b), mask); return _mm_or_si128(hi_product_0Z2Z, hi_product_Z1Z3); // = hi_product_0123 } static inline __m128i libdivide_mullhi_u64_flat_vector(__m128i x, __m128i y) { // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) __m128i mask = libdivide_get_00000000FFFFFFFF(); // x0 is low half of 2 64 bit values, x1 is high half in low slots __m128i x0 = _mm_and_si128(x, mask); __m128i x1 = _mm_srli_epi64(x, 32); __m128i y0 = _mm_and_si128(y, mask); __m128i y1 = _mm_srli_epi64(y, 32); // x0 happens to have the low half of the two 64 bit values in 32 bit slots // 0 and 2, so _mm_mul_epu32 computes their full product, and then we shift // right by 32 to get just the high values __m128i x0y0_hi = _mm_srli_epi64(_mm_mul_epu32(x0, y0), 32); __m128i x0y1 = _mm_mul_epu32(x0, y1); __m128i x1y0 = _mm_mul_epu32(x1, y0); __m128i x1y1 = _mm_mul_epu32(x1, y1); __m128i temp = _mm_add_epi64(x1y0, x0y0_hi); __m128i temp_lo = _mm_and_si128(temp, mask); __m128i temp_hi = _mm_srli_epi64(temp, 32); temp_lo = _mm_srli_epi64(_mm_add_epi64(temp_lo, x0y1), 32); temp_hi = _mm_add_epi64(x1y1, temp_hi); return _mm_add_epi64(temp_lo, temp_hi); } static inline __m128i libdivide_mullhi_s64_flat_vector(__m128i x, __m128i y) { __m128i p = libdivide_mullhi_u64_flat_vector(x, y); __m128i t1 = _mm_and_si128(libdivide_s64_signbits(x), y); p = _mm_sub_epi64(p, t1); __m128i t2 = _mm_and_si128(libdivide_s64_signbits(y), x); p = _mm_sub_epi64(p, t2); return p; } #ifdef LIBDIVIDE_USE_SSE4_1 static inline __m128i libdivide_mullhi_s32_flat_vector(__m128i a, __m128i b) { __m128i hi_product_0Z2Z = _mm_srli_epi64(_mm_mul_epi32(a, b), 32); __m128i a1X3X = _mm_srli_epi64(a, 32); __m128i mask = libdivide_get_FFFFFFFF00000000(); __m128i hi_product_Z1Z3 = _mm_and_si128(_mm_mul_epi32(a1X3X, b), mask); return _mm_or_si128(hi_product_0Z2Z, hi_product_Z1Z3); // = hi_product_0123 } #else static inline __m128i libdivide_mullhi_s32_flat_vector(__m128i a, __m128i b) { __m128i p = libdivide__mullhi_u32_flat_vector(a, b); __m128i t1 = _mm_and_si128(_mm_srai_epi32(a, 31), b); // t1 = (a >> 31) & y, arithmetic shift __m128i t2 = _mm_and_si128(_mm_srai_epi32(b, 31), a); p = _mm_sub_epi32(p, t1); p = _mm_sub_epi32(p, t2); return p; } #endif // LIBDIVIDE_USE_SSE4_1 #endif // LIBDIVIDE_USE_SSE2 static inline int32_t libdivide__count_leading_zeros32(uint32_t val) { #if defined(__GNUC__) || __has_builtin(__builtin_clz) // Fast way to count leading zeros return __builtin_clz(val); #elif defined(LIBDIVIDE_VC) unsigned long result; if (_BitScanReverse(&result, val)) { return 31 - result; } return 0; #else int32_t result = 0; uint32_t hi = 1U << 31; while (~val & hi) { hi >>= 1; result++; } return result; #endif } static inline int32_t libdivide__count_leading_zeros64(uint64_t val) { #if defined(__GNUC__) || __has_builtin(__builtin_clzll) // Fast way to count leading zeros return __builtin_clzll(val); #elif defined(LIBDIVIDE_VC) && defined(_WIN64) unsigned long result; if (_BitScanReverse64(&result, val)) { return 63 - result; } return 0; #else uint32_t hi = val >> 32; uint32_t lo = val & 0xFFFFFFFF; if (hi != 0) return libdivide__count_leading_zeros32(hi); return 32 + libdivide__count_leading_zeros32(lo); #endif } #if (defined(LIBDIVIDE_IS_i386) || defined(LIBDIVIDE_IS_X86_64)) && \ defined(LIBDIVIDE_GCC_STYLE_ASM) static uint32_t libdivide_64_div_32_to_32(uint32_t u1, uint32_t u0, uint32_t v, uint32_t *r) { uint32_t result; __asm__("divl %[v]" : "=a"(result), "=d"(*r) : [v] "r"(v), "a"(u0), "d"(u1) ); return result; } #else static uint32_t libdivide_64_div_32_to_32(uint32_t u1, uint32_t u0, uint32_t v, uint32_t *r) { uint64_t n = (((uint64_t)u1) << 32) | u0; uint32_t result = (uint32_t)(n / v); *r = (uint32_t)(n - result * (uint64_t)v); return result; } #endif #if defined(LIBDIVIDE_IS_X86_64) && \ defined(LIBDIVIDE_GCC_STYLE_ASM) static uint64_t libdivide_128_div_64_to_64(uint64_t u1, uint64_t u0, uint64_t v, uint64_t *r) { // u0 -> rax // u1 -> rdx // divq uint64_t result; __asm__("divq %[v]" : "=a"(result), "=d"(*r) : [v] "r"(v), "a"(u0), "d"(u1) ); return result; } #else static uint64_t libdivide_128_div_64_to_64(uint64_t u1, uint64_t u0, uint64_t v, uint64_t *r) { const uint64_t b = (1ULL << 32); // Number base (16 bits) uint64_t un1, un0; // Norm. dividend LSD's uint64_t vn1, vn0; // Norm. divisor digits uint64_t q1, q0; // Quotient digits uint64_t un64, un21, un10; // Dividend digit pairs uint64_t rhat; // A remainder int32_t s; // Shift amount for norm // If overflow, set rem. to an impossible value, // and return the largest possible quotient if (u1 >= v) { if (r != NULL) *r = (uint64_t) -1; return (uint64_t) -1; } // count leading zeros s = libdivide__count_leading_zeros64(v); if (s > 0) { // Normalize divisor v = v << s; un64 = (u1 << s) | ((u0 >> (64 - s)) & (-s >> 31)); un10 = u0 << s; // Shift dividend left } else { // Avoid undefined behavior un64 = u1 | u0; un10 = u0; } // Break divisor up into two 32-bit digits vn1 = v >> 32; vn0 = v & 0xFFFFFFFF; // Break right half of dividend into two digits un1 = un10 >> 32; un0 = un10 & 0xFFFFFFFF; // Compute the first quotient digit, q1 q1 = un64 / vn1; rhat = un64 - q1 * vn1; while (q1 >= b || q1 * vn0 > b * rhat + un1) { q1 = q1 - 1; rhat = rhat + vn1; if (rhat >= b) break; } // Multiply and subtract un21 = un64 * b + un1 - q1 * v; // Compute the second quotient digit q0 = un21 / vn1; rhat = un21 - q0 * vn1; while (q0 >= b || q0 * vn0 > b * rhat + un0) { q0 = q0 - 1; rhat = rhat + vn1; if (rhat >= b) break; } // If remainder is wanted, return it if (r != NULL) *r = (un21 * b + un0 - q0 * v) >> s; return q1 * b + q0; } #endif static inline void libdivide_u128_shift(uint64_t *u1, uint64_t *u0, int32_t signed_shift) { if (signed_shift > 0) { uint32_t shift = signed_shift; *u1 <<= shift; *u1 |= *u0 >> (64 - shift); *u0 <<= shift; } else { uint32_t shift = -signed_shift; *u0 >>= shift; *u0 |= *u1 << (64 - shift); *u1 >>= shift; } } static uint64_t libdivide_128_div_128_to_64(uint64_t u_hi, uint64_t u_lo, uint64_t v_hi, uint64_t v_lo, uint64_t *r_hi, uint64_t *r_lo) { #if defined(HAS_INT128_T) __uint128_t ufull = u_hi; __uint128_t vfull = v_hi; ufull = (ufull << 64) | u_lo; vfull = (vfull << 64) | v_lo; uint64_t res = (uint64_t)(ufull / vfull); __uint128_t remainder = ufull - (vfull * res); *r_lo = (uint64_t)remainder; *r_hi = (uint64_t)(remainder >> 64); return res; #else // Adapted from "Unsigned Doubleword Division" in Hacker's Delight // We want to compute u / v typedef struct { uint64_t hi; uint64_t lo; } u128_t; u128_t u = {u_hi, u_lo}; u128_t v = {v_hi, v_lo}; if (v.hi == 0) { // divisor v is a 64 bit value, so we just need one 128/64 division // Note that we are simpler than Hacker's Delight here, because we know // the quotient fits in 64 bits whereas Hacker's Delight demands a full // 128 bit quotient *r_hi = 0; return libdivide_128_div_64_to_64(u.hi, u.lo, v.lo, r_lo); } // Here v >= 2**64 // We know that v.hi != 0, so count leading zeros is OK // We have 0 <= n <= 63 uint32_t n = libdivide__count_leading_zeros64(v.hi); // Normalize the divisor so its MSB is 1 u128_t v1t = v; libdivide_u128_shift(&v1t.hi, &v1t.lo, n); uint64_t v1 = v1t.hi; // i.e. v1 = v1t >> 64 // To ensure no overflow u128_t u1 = u; libdivide_u128_shift(&u1.hi, &u1.lo, -1); // Get quotient from divide unsigned insn. uint64_t rem_ignored; uint64_t q1 = libdivide_128_div_64_to_64(u1.hi, u1.lo, v1, &rem_ignored); // Undo normalization and division of u by 2. u128_t q0 = {0, q1}; libdivide_u128_shift(&q0.hi, &q0.lo, n); libdivide_u128_shift(&q0.hi, &q0.lo, -63); // Make q0 correct or too small by 1 // Equivalent to `if (q0 != 0) q0 = q0 - 1;` if (q0.hi != 0 || q0.lo != 0) { q0.hi -= (q0.lo == 0); // borrow q0.lo -= 1; } // Now q0 is correct. // Compute q0 * v as q0v // = (q0.hi << 64 + q0.lo) * (v.hi << 64 + v.lo) // = (q0.hi * v.hi << 128) + (q0.hi * v.lo << 64) + // (q0.lo * v.hi << 64) + q0.lo * v.lo) // Each term is 128 bit // High half of full product (upper 128 bits!) are dropped u128_t q0v = {0, 0}; q0v.hi = q0.hi*v.lo + q0.lo*v.hi + libdivide__mullhi_u64(q0.lo, v.lo); q0v.lo = q0.lo*v.lo; // Compute u - q0v as u_q0v // This is the remainder u128_t u_q0v = u; u_q0v.hi -= q0v.hi + (u.lo < q0v.lo); // second term is borrow u_q0v.lo -= q0v.lo; // Check if u_q0v >= v // This checks if our remainder is larger than the divisor if ((u_q0v.hi > v.hi) || (u_q0v.hi == v.hi && u_q0v.lo >= v.lo)) { // Increment q0 q0.lo += 1; q0.hi += (q0.lo == 0); // carry // Subtract v from remainder u_q0v.hi -= v.hi + (u_q0v.lo < v.lo); u_q0v.lo -= v.lo; } *r_hi = u_q0v.hi; *r_lo = u_q0v.lo; LIBDIVIDE_ASSERT(q0.hi == 0); return q0.lo; #endif } static inline struct libdivide_u32_t libdivide_internal_u32_gen(uint32_t d, int branchfree) { if (d == 0) { LIBDIVIDE_ERROR("divider must be != 0"); } struct libdivide_u32_t result; uint32_t floor_log_2_d = 31 - libdivide__count_leading_zeros32(d); if ((d & (d - 1)) == 0) { // Power of 2 if (! branchfree) { result.magic = 0; result.more = floor_log_2_d | LIBDIVIDE_U32_SHIFT_PATH; } else { // We want a magic number of 2**32 and a shift of floor_log_2_d // but one of the shifts is taken up by LIBDIVIDE_ADD_MARKER, // so we subtract 1 from the shift result.magic = 0; result.more = (floor_log_2_d-1) | LIBDIVIDE_ADD_MARKER; } } else { uint8_t more; uint32_t rem, proposed_m; proposed_m = libdivide_64_div_32_to_32(1U << floor_log_2_d, 0, d, &rem); LIBDIVIDE_ASSERT(rem > 0 && rem < d); const uint32_t e = d - rem; // This power works if e < 2**floor_log_2_d. if (!branchfree && (e < (1U << floor_log_2_d))) { // This power works more = floor_log_2_d; } else { // We have to use the general 33-bit algorithm. We need to compute // (2**power) / d. However, we already have (2**(power-1))/d and // its remainder. By doubling both, and then correcting the // remainder, we can compute the larger division. // don't care about overflow here - in fact, we expect it proposed_m += proposed_m; const uint32_t twice_rem = rem + rem; if (twice_rem >= d || twice_rem < rem) proposed_m += 1; more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; } result.magic = 1 + proposed_m; result.more = more; // result.more's shift should in general be ceil_log_2_d. But if we // used the smaller power, we subtract one from the shift because we're // using the smaller power. If we're using the larger power, we // subtract one from the shift because it's taken care of by the add // indicator. So floor_log_2_d happens to be correct in both cases. } return result; } struct libdivide_u32_t libdivide_u32_gen(uint32_t d) { return libdivide_internal_u32_gen(d, 0); } struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t d) { if (d == 1) { LIBDIVIDE_ERROR("branchfree divider must be != 1"); } struct libdivide_u32_t tmp = libdivide_internal_u32_gen(d, 1); struct libdivide_u32_branchfree_t ret = {tmp.magic, (uint8_t)(tmp.more & LIBDIVIDE_32_SHIFT_MASK)}; return ret; } uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U32_SHIFT_PATH) { return numer >> (more & LIBDIVIDE_32_SHIFT_MASK); } else { uint32_t q = libdivide__mullhi_u32(denom->magic, numer); if (more & LIBDIVIDE_ADD_MARKER) { uint32_t t = ((numer - q) >> 1) + q; return t >> (more & LIBDIVIDE_32_SHIFT_MASK); } else { // all upper bits are 0 - don't need to mask them off return q >> more; } } } uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom) { uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; if (more & LIBDIVIDE_U32_SHIFT_PATH) { return 1U << shift; } else if (!(more & LIBDIVIDE_ADD_MARKER)) { // We compute q = n/d = n*m / 2^(32 + shift) // Therefore we have d = 2^(32 + shift) / m // We need to ceil it. // We know d is not a power of 2, so m is not a power of 2, // so we can just add 1 to the floor uint32_t hi_dividend = 1U << shift; uint32_t rem_ignored; return 1 + libdivide_64_div_32_to_32(hi_dividend, 0, denom->magic, &rem_ignored); } else { // Here we wish to compute d = 2^(32+shift+1)/(m+2^32). // Notice (m + 2^32) is a 33 bit number. Use 64 bit division for now // Also note that shift may be as high as 31, so shift + 1 will // overflow. So we have to compute it as 2^(32+shift)/(m+2^32), and // then double the quotient and remainder. uint64_t half_n = 1ULL << (32 + shift); uint64_t d = (1ULL << 32) | denom->magic; // Note that the quotient is guaranteed <= 32 bits, but the remainder // may need 33! uint32_t half_q = (uint32_t)(half_n / d); uint64_t rem = half_n % d; // We computed 2^(32+shift)/(m+2^32) // Need to double it, and then add 1 to the quotient if doubling th // remainder would increase the quotient. // Note that rem<<1 cannot overflow, since rem < d and d is 33 bits uint32_t full_q = half_q + half_q + ((rem<<1) >= d); // We rounded down in gen unless we're a power of 2 (i.e. in branchfree case) // We can detect that by looking at m. If m zero, we're a power of 2 return full_q + (denom->magic != 0); } } uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom) { struct libdivide_u32_t denom_u32 = {denom->magic, (uint8_t)(denom->more | LIBDIVIDE_ADD_MARKER)}; return libdivide_u32_recover(&denom_u32); } int libdivide_u32_get_algorithm(const struct libdivide_u32_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U32_SHIFT_PATH) return 0; else if (!(more & LIBDIVIDE_ADD_MARKER)) return 1; else return 2; } uint32_t libdivide_u32_do_alg0(uint32_t numer, const struct libdivide_u32_t *denom) { return numer >> (denom->more & LIBDIVIDE_32_SHIFT_MASK); } uint32_t libdivide_u32_do_alg1(uint32_t numer, const struct libdivide_u32_t *denom) { uint32_t q = libdivide__mullhi_u32(denom->magic, numer); return q >> denom->more; } uint32_t libdivide_u32_do_alg2(uint32_t numer, const struct libdivide_u32_t *denom) { // denom->add != 0 uint32_t q = libdivide__mullhi_u32(denom->magic, numer); uint32_t t = ((numer - q) >> 1) + q; // Note that this mask is typically free. Only the low bits are meaningful // to a shift, so compilers can optimize out this AND. return t >> (denom->more & LIBDIVIDE_32_SHIFT_MASK); } uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom) { uint32_t q = libdivide__mullhi_u32(denom->magic, numer); uint32_t t = ((numer - q) >> 1) + q; return t >> denom->more; } #if defined(LIBDIVIDE_USE_SSE2) __m128i libdivide_u32_do_vector(__m128i numers, const struct libdivide_u32_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U32_SHIFT_PATH) { return _mm_srl_epi32(numers, libdivide_u32_to_m128i(more & LIBDIVIDE_32_SHIFT_MASK)); } else { __m128i q = libdivide__mullhi_u32_flat_vector(numers, _mm_set1_epi32(denom->magic)); if (more & LIBDIVIDE_ADD_MARKER) { // uint32_t t = ((numer - q) >> 1) + q; // return t >> denom->shift; __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q); return _mm_srl_epi32(t, libdivide_u32_to_m128i(more & LIBDIVIDE_32_SHIFT_MASK)); } else { // q >> denom->shift return _mm_srl_epi32(q, libdivide_u32_to_m128i(more)); } } } __m128i libdivide_u32_do_vector_alg0(__m128i numers, const struct libdivide_u32_t *denom) { return _mm_srl_epi32(numers, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_32_SHIFT_MASK)); } __m128i libdivide_u32_do_vector_alg1(__m128i numers, const struct libdivide_u32_t *denom) { __m128i q = libdivide__mullhi_u32_flat_vector(numers, _mm_set1_epi32(denom->magic)); return _mm_srl_epi32(q, libdivide_u32_to_m128i(denom->more)); } __m128i libdivide_u32_do_vector_alg2(__m128i numers, const struct libdivide_u32_t *denom) { __m128i q = libdivide__mullhi_u32_flat_vector(numers, _mm_set1_epi32(denom->magic)); __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q); return _mm_srl_epi32(t, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_32_SHIFT_MASK)); } LIBDIVIDE_API __m128i libdivide_u32_branchfree_do_vector(__m128i numers, const struct libdivide_u32_branchfree_t *denom) { __m128i q = libdivide__mullhi_u32_flat_vector(numers, _mm_set1_epi32(denom->magic)); __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q); return _mm_srl_epi32(t, libdivide_u32_to_m128i(denom->more)); } #endif static inline struct libdivide_u64_t libdivide_internal_u64_gen(uint64_t d, int branchfree) { if (d == 0) { LIBDIVIDE_ERROR("divider must be != 0"); } struct libdivide_u64_t result; uint32_t floor_log_2_d = 63 - libdivide__count_leading_zeros64(d); if ((d & (d - 1)) == 0) { // Power of 2 if (! branchfree) { result.magic = 0; result.more = floor_log_2_d | LIBDIVIDE_U64_SHIFT_PATH; } else { // We want a magic number of 2**64 and a shift of floor_log_2_d // but one of the shifts is taken up by LIBDIVIDE_ADD_MARKER, // so we subtract 1 from the shift result.magic = 0; result.more = (floor_log_2_d-1) | LIBDIVIDE_ADD_MARKER; } } else { uint64_t proposed_m, rem; uint8_t more; // (1 << (64 + floor_log_2_d)) / d proposed_m = libdivide_128_div_64_to_64(1ULL << floor_log_2_d, 0, d, &rem); LIBDIVIDE_ASSERT(rem > 0 && rem < d); const uint64_t e = d - rem; // This power works if e < 2**floor_log_2_d. if (!branchfree && e < (1ULL << floor_log_2_d)) { // This power works more = floor_log_2_d; } else { // We have to use the general 65-bit algorithm. We need to compute // (2**power) / d. However, we already have (2**(power-1))/d and // its remainder. By doubling both, and then correcting the // remainder, we can compute the larger division. // don't care about overflow here - in fact, we expect it proposed_m += proposed_m; const uint64_t twice_rem = rem + rem; if (twice_rem >= d || twice_rem < rem) proposed_m += 1; more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; } result.magic = 1 + proposed_m; result.more = more; // result.more's shift should in general be ceil_log_2_d. But if we // used the smaller power, we subtract one from the shift because we're // using the smaller power. If we're using the larger power, we // subtract one from the shift because it's taken care of by the add // indicator. So floor_log_2_d happens to be correct in both cases, // which is why we do it outside of the if statement. } return result; } struct libdivide_u64_t libdivide_u64_gen(uint64_t d) { return libdivide_internal_u64_gen(d, 0); } struct libdivide_u64_branchfree_t libdivide_u64_branchfree_gen(uint64_t d) { if (d == 1) { LIBDIVIDE_ERROR("branchfree divider must be != 1"); } struct libdivide_u64_t tmp = libdivide_internal_u64_gen(d, 1); struct libdivide_u64_branchfree_t ret = {tmp.magic, (uint8_t)(tmp.more & LIBDIVIDE_64_SHIFT_MASK)}; return ret; } uint64_t libdivide_u64_do(uint64_t numer, const struct libdivide_u64_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U64_SHIFT_PATH) { return numer >> (more & LIBDIVIDE_64_SHIFT_MASK); } else { uint64_t q = libdivide__mullhi_u64(denom->magic, numer); if (more & LIBDIVIDE_ADD_MARKER) { uint64_t t = ((numer - q) >> 1) + q; return t >> (more & LIBDIVIDE_64_SHIFT_MASK); } else { // all upper bits are 0 - don't need to mask them off return q >> more; } } } uint64_t libdivide_u64_recover(const struct libdivide_u64_t *denom) { uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; if (more & LIBDIVIDE_U64_SHIFT_PATH) { return 1ULL << shift; } else if (!(more & LIBDIVIDE_ADD_MARKER)) { // We compute q = n/d = n*m / 2^(64 + shift) // Therefore we have d = 2^(64 + shift) / m // We need to ceil it. // We know d is not a power of 2, so m is not a power of 2, // so we can just add 1 to the floor uint64_t hi_dividend = 1ULL << shift; uint64_t rem_ignored; return 1 + libdivide_128_div_64_to_64(hi_dividend, 0, denom->magic, &rem_ignored); } else { // Here we wish to compute d = 2^(64+shift+1)/(m+2^64). // Notice (m + 2^64) is a 65 bit number. This gets hairy. See // libdivide_u32_recover for more on what we do here. // TODO: do something better than 128 bit math // Hack: if d is not a power of 2, this is a 128/128->64 divide // If d is a power of 2, this may be a bigger divide // However we can optimize that easily if (denom->magic == 0) { // 2^(64 + shift + 1) / (2^64) == 2^(shift + 1) return 1ULL << (shift + 1); } // Full n is a (potentially) 129 bit value // half_n is a 128 bit value // Compute the hi half of half_n. Low half is 0. uint64_t half_n_hi = 1ULL << shift, half_n_lo = 0; // d is a 65 bit value. The high bit is always set to 1. const uint64_t d_hi = 1, d_lo = denom->magic; // Note that the quotient is guaranteed <= 64 bits, // but the remainder may need 65! uint64_t r_hi, r_lo; uint64_t half_q = libdivide_128_div_128_to_64(half_n_hi, half_n_lo, d_hi, d_lo, &r_hi, &r_lo); // We computed 2^(64+shift)/(m+2^64) // Double the remainder ('dr') and check if that is larger than d // Note that d is a 65 bit value, so r1 is small and so r1 + r1 cannot // overflow uint64_t dr_lo = r_lo + r_lo; uint64_t dr_hi = r_hi + r_hi + (dr_lo < r_lo); // last term is carry int dr_exceeds_d = (dr_hi > d_hi) || (dr_hi == d_hi && dr_lo >= d_lo); uint64_t full_q = half_q + half_q + (dr_exceeds_d ? 1 : 0); return full_q + 1; } } uint64_t libdivide_u64_branchfree_recover(const struct libdivide_u64_branchfree_t *denom) { struct libdivide_u64_t denom_u64 = {denom->magic, (uint8_t)(denom->more | LIBDIVIDE_ADD_MARKER)}; return libdivide_u64_recover(&denom_u64); } int libdivide_u64_get_algorithm(const struct libdivide_u64_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U64_SHIFT_PATH) return 0; else if (!(more & LIBDIVIDE_ADD_MARKER)) return 1; else return 2; } uint64_t libdivide_u64_do_alg0(uint64_t numer, const struct libdivide_u64_t *denom) { return numer >> (denom->more & LIBDIVIDE_64_SHIFT_MASK); } uint64_t libdivide_u64_do_alg1(uint64_t numer, const struct libdivide_u64_t *denom) { uint64_t q = libdivide__mullhi_u64(denom->magic, numer); return q >> denom->more; } uint64_t libdivide_u64_do_alg2(uint64_t numer, const struct libdivide_u64_t *denom) { uint64_t q = libdivide__mullhi_u64(denom->magic, numer); uint64_t t = ((numer - q) >> 1) + q; return t >> (denom->more & LIBDIVIDE_64_SHIFT_MASK); } uint64_t libdivide_u64_branchfree_do(uint64_t numer, const struct libdivide_u64_branchfree_t *denom) { uint64_t q = libdivide__mullhi_u64(denom->magic, numer); uint64_t t = ((numer - q) >> 1) + q; return t >> denom->more; } #if defined(LIBDIVIDE_USE_SSE2) __m128i libdivide_u64_do_vector(__m128i numers, const struct libdivide_u64_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U64_SHIFT_PATH) { return _mm_srl_epi64(numers, libdivide_u32_to_m128i(more & LIBDIVIDE_64_SHIFT_MASK)); } else { __m128i q = libdivide_mullhi_u64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); if (more & LIBDIVIDE_ADD_MARKER) { // uint32_t t = ((numer - q) >> 1) + q; // return t >> denom->shift; __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q); return _mm_srl_epi64(t, libdivide_u32_to_m128i(more & LIBDIVIDE_64_SHIFT_MASK)); } else { // q >> denom->shift return _mm_srl_epi64(q, libdivide_u32_to_m128i(more)); } } } __m128i libdivide_u64_do_vector_alg0(__m128i numers, const struct libdivide_u64_t *denom) { return _mm_srl_epi64(numers, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_64_SHIFT_MASK)); } __m128i libdivide_u64_do_vector_alg1(__m128i numers, const struct libdivide_u64_t *denom) { __m128i q = libdivide_mullhi_u64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); return _mm_srl_epi64(q, libdivide_u32_to_m128i(denom->more)); } __m128i libdivide_u64_do_vector_alg2(__m128i numers, const struct libdivide_u64_t *denom) { __m128i q = libdivide_mullhi_u64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q); return _mm_srl_epi64(t, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_64_SHIFT_MASK)); } __m128i libdivide_u64_branchfree_do_vector(__m128i numers, const struct libdivide_u64_branchfree_t *denom) { __m128i q = libdivide_mullhi_u64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q); return _mm_srl_epi64(t, libdivide_u32_to_m128i(denom->more)); } #endif static inline int32_t libdivide__mullhi_s32(int32_t x, int32_t y) { int64_t xl = x, yl = y; int64_t rl = xl * yl; // needs to be arithmetic shift return (int32_t)(rl >> 32); } static inline struct libdivide_s32_t libdivide_internal_s32_gen(int32_t d, int branchfree) { if (d == 0) { LIBDIVIDE_ERROR("divider must be != 0"); } struct libdivide_s32_t result; // If d is a power of 2, or negative a power of 2, we have to use a shift. // This is especially important because the magic algorithm fails for -1. // To check if d is a power of 2 or its inverse, it suffices to check // whether its absolute value has exactly one bit set. This works even for // INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set // and is a power of 2. uint32_t ud = (uint32_t)d; uint32_t absD = (d < 0) ? -ud : ud; uint32_t floor_log_2_d = 31 - libdivide__count_leading_zeros32(absD); // check if exactly one bit is set, // don't care if absD is 0 since that's divide by zero if ((absD & (absD - 1)) == 0) { // Branchfree and normal paths are exactly the same result.magic = 0; result.more = floor_log_2_d | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0) | LIBDIVIDE_S32_SHIFT_PATH; } else { LIBDIVIDE_ASSERT(floor_log_2_d >= 1); uint8_t more; // the dividend here is 2**(floor_log_2_d + 31), so the low 32 bit word // is 0 and the high word is floor_log_2_d - 1 uint32_t rem, proposed_m; proposed_m = libdivide_64_div_32_to_32(1U << (floor_log_2_d - 1), 0, absD, &rem); const uint32_t e = absD - rem; // We are going to start with a power of floor_log_2_d - 1. // This works if works if e < 2**floor_log_2_d. if (!branchfree && e < (1U << floor_log_2_d)) { // This power works more = floor_log_2_d - 1; } else { // We need to go one higher. This should not make proposed_m // overflow, but it will make it negative when interpreted as an // int32_t. proposed_m += proposed_m; const uint32_t twice_rem = rem + rem; if (twice_rem >= absD || twice_rem < rem) proposed_m += 1; more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; } proposed_m += 1; int32_t magic = (int32_t)proposed_m; // Mark if we are negative. Note we only negate the magic number in the // branchfull case. if (d < 0) { more |= LIBDIVIDE_NEGATIVE_DIVISOR; if (!branchfree) { magic = -magic; } } result.more = more; result.magic = magic; } return result; } LIBDIVIDE_API struct libdivide_s32_t libdivide_s32_gen(int32_t d) { return libdivide_internal_s32_gen(d, 0); } LIBDIVIDE_API struct libdivide_s32_branchfree_t libdivide_s32_branchfree_gen(int32_t d) { if (d == 1) { LIBDIVIDE_ERROR("branchfree divider must be != 1"); } if (d == -1) { LIBDIVIDE_ERROR("branchfree divider must be != -1"); } struct libdivide_s32_t tmp = libdivide_internal_s32_gen(d, 1); struct libdivide_s32_branchfree_t result = {tmp.magic, tmp.more}; return result; } int32_t libdivide_s32_do(int32_t numer, const struct libdivide_s32_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_S32_SHIFT_PATH) { uint32_t sign = (int8_t)more >> 7; uint8_t shifter = more & LIBDIVIDE_32_SHIFT_MASK; uint32_t uq = (uint32_t)(numer + ((numer >> 31) & ((1U << shifter) - 1))); int32_t q = (int32_t)uq; q = q >> shifter; q = (q ^ sign) - sign; return q; } else { uint32_t uq = (uint32_t)libdivide__mullhi_s32(denom->magic, numer); if (more & LIBDIVIDE_ADD_MARKER) { // must be arithmetic shift and then sign extend int32_t sign = (int8_t)more >> 7; // q += (more < 0 ? -numer : numer), casts to avoid UB uq += ((uint32_t)numer ^ sign) - sign; } int32_t q = (int32_t)uq; q >>= more & LIBDIVIDE_32_SHIFT_MASK; q += (q < 0); return q; } } int32_t libdivide_s32_branchfree_do(int32_t numer, const struct libdivide_s32_branchfree_t *denom) { uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; // must be arithmetic shift and then sign extend int32_t sign = (int8_t)more >> 7; int32_t magic = denom->magic; int32_t q = libdivide__mullhi_s32(magic, numer); q += numer; // If q is non-negative, we have nothing to do // If q is negative, we want to add either (2**shift)-1 if d is a power of // 2, or (2**shift) if it is not a power of 2 uint32_t is_power_of_2 = !!(more & LIBDIVIDE_S32_SHIFT_PATH); uint32_t q_sign = (uint32_t)(q >> 31); q += q_sign & ((1 << shift) - is_power_of_2); // Now arithmetic right shift q >>= shift; // Negate if needed q = (q ^ sign) - sign; return q; } int32_t libdivide_s32_recover(const struct libdivide_s32_t *denom) { uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; if (more & LIBDIVIDE_S32_SHIFT_PATH) { uint32_t absD = 1U << shift; if (more & LIBDIVIDE_NEGATIVE_DIVISOR) { absD = -absD; } return (int32_t)absD; } else { // Unsigned math is much easier // We negate the magic number only in the branchfull case, and we don't // know which case we're in. However we have enough information to // determine the correct sign of the magic number. The divisor was // negative if LIBDIVIDE_NEGATIVE_DIVISOR is set. If ADD_MARKER is set, // the magic number's sign is opposite that of the divisor. // We want to compute the positive magic number. int negative_divisor = (more & LIBDIVIDE_NEGATIVE_DIVISOR); int magic_was_negated = (more & LIBDIVIDE_ADD_MARKER) ? denom->magic > 0 : denom->magic < 0; // Handle the power of 2 case (including branchfree) if (denom->magic == 0) { int32_t result = 1 << shift; return negative_divisor ? -result : result; } uint32_t d = (uint32_t)(magic_was_negated ? -denom->magic : denom->magic); uint64_t n = 1ULL << (32 + shift); // this shift cannot exceed 30 uint32_t q = (uint32_t)(n / d); int32_t result = (int32_t)q; result += 1; return negative_divisor ? -result : result; } } int32_t libdivide_s32_branchfree_recover(const struct libdivide_s32_branchfree_t *denom) { return libdivide_s32_recover((const struct libdivide_s32_t *)denom); } int libdivide_s32_get_algorithm(const struct libdivide_s32_t *denom) { uint8_t more = denom->more; int positiveDivisor = !(more & LIBDIVIDE_NEGATIVE_DIVISOR); if (more & LIBDIVIDE_S32_SHIFT_PATH) return (positiveDivisor ? 0 : 1); else if (more & LIBDIVIDE_ADD_MARKER) return (positiveDivisor ? 2 : 3); else return 4; } int32_t libdivide_s32_do_alg0(int32_t numer, const struct libdivide_s32_t *denom) { uint8_t shifter = denom->more & LIBDIVIDE_32_SHIFT_MASK; int32_t q = numer + ((numer >> 31) & ((1U << shifter) - 1)); return q >> shifter; } int32_t libdivide_s32_do_alg1(int32_t numer, const struct libdivide_s32_t *denom) { uint8_t shifter = denom->more & LIBDIVIDE_32_SHIFT_MASK; int32_t q = numer + ((numer >> 31) & ((1U << shifter) - 1)); return - (q >> shifter); } int32_t libdivide_s32_do_alg2(int32_t numer, const struct libdivide_s32_t *denom) { int32_t q = libdivide__mullhi_s32(denom->magic, numer); q += numer; q >>= denom->more & LIBDIVIDE_32_SHIFT_MASK; q += (q < 0); return q; } int32_t libdivide_s32_do_alg3(int32_t numer, const struct libdivide_s32_t *denom) { int32_t q = libdivide__mullhi_s32(denom->magic, numer); q -= numer; q >>= denom->more & LIBDIVIDE_32_SHIFT_MASK; q += (q < 0); return q; } int32_t libdivide_s32_do_alg4(int32_t numer, const struct libdivide_s32_t *denom) { int32_t q = libdivide__mullhi_s32(denom->magic, numer); q >>= denom->more & LIBDIVIDE_32_SHIFT_MASK; q += (q < 0); return q; } #if defined(LIBDIVIDE_USE_SSE2) __m128i libdivide_s32_do_vector(__m128i numers, const struct libdivide_s32_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_S32_SHIFT_PATH) { uint32_t shifter = more & LIBDIVIDE_32_SHIFT_MASK; __m128i roundToZeroTweak = _mm_set1_epi32((1U << shifter) - 1); // could use _mm_srli_epi32 with an all -1 register __m128i q = _mm_add_epi32(numers, _mm_and_si128(_mm_srai_epi32(numers, 31), roundToZeroTweak)); //q = numer + ((numer >> 31) & roundToZeroTweak); q = _mm_sra_epi32(q, libdivide_u32_to_m128i(shifter)); // q = q >> shifter __m128i shiftMask = _mm_set1_epi32((int32_t)((int8_t)more >> 7)); // set all bits of shift mask = to the sign bit of more q = _mm_sub_epi32(_mm_xor_si128(q, shiftMask), shiftMask); // q = (q ^ shiftMask) - shiftMask; return q; } else { __m128i q = libdivide_mullhi_s32_flat_vector(numers, _mm_set1_epi32(denom->magic)); if (more & LIBDIVIDE_ADD_MARKER) { __m128i sign = _mm_set1_epi32((int32_t)(int8_t)more >> 7); // must be arithmetic shift q = _mm_add_epi32(q, _mm_sub_epi32(_mm_xor_si128(numers, sign), sign)); // q += ((numer ^ sign) - sign); } q = _mm_sra_epi32(q, libdivide_u32_to_m128i(more & LIBDIVIDE_32_SHIFT_MASK)); // q >>= shift q = _mm_add_epi32(q, _mm_srli_epi32(q, 31)); // q += (q < 0) return q; } } __m128i libdivide_s32_do_vector_alg0(__m128i numers, const struct libdivide_s32_t *denom) { uint8_t shifter = denom->more & LIBDIVIDE_32_SHIFT_MASK; __m128i roundToZeroTweak = _mm_set1_epi32((1U << shifter) - 1); __m128i q = _mm_add_epi32(numers, _mm_and_si128(_mm_srai_epi32(numers, 31), roundToZeroTweak)); return _mm_sra_epi32(q, libdivide_u32_to_m128i(shifter)); } __m128i libdivide_s32_do_vector_alg1(__m128i numers, const struct libdivide_s32_t *denom) { uint8_t shifter = denom->more & LIBDIVIDE_32_SHIFT_MASK; __m128i roundToZeroTweak = _mm_set1_epi32((1U << shifter) - 1); __m128i q = _mm_add_epi32(numers, _mm_and_si128(_mm_srai_epi32(numers, 31), roundToZeroTweak)); return _mm_sub_epi32(_mm_setzero_si128(), _mm_sra_epi32(q, libdivide_u32_to_m128i(shifter))); } __m128i libdivide_s32_do_vector_alg2(__m128i numers, const struct libdivide_s32_t *denom) { __m128i q = libdivide_mullhi_s32_flat_vector(numers, _mm_set1_epi32(denom->magic)); q = _mm_add_epi32(q, numers); q = _mm_sra_epi32(q, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_32_SHIFT_MASK)); q = _mm_add_epi32(q, _mm_srli_epi32(q, 31)); return q; } __m128i libdivide_s32_do_vector_alg3(__m128i numers, const struct libdivide_s32_t *denom) { __m128i q = libdivide_mullhi_s32_flat_vector(numers, _mm_set1_epi32(denom->magic)); q = _mm_sub_epi32(q, numers); q = _mm_sra_epi32(q, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_32_SHIFT_MASK)); q = _mm_add_epi32(q, _mm_srli_epi32(q, 31)); return q; } __m128i libdivide_s32_do_vector_alg4(__m128i numers, const struct libdivide_s32_t *denom) { uint8_t more = denom->more; __m128i q = libdivide_mullhi_s32_flat_vector(numers, _mm_set1_epi32(denom->magic)); q = _mm_sra_epi32(q, libdivide_u32_to_m128i(more & LIBDIVIDE_32_SHIFT_MASK)); //q >>= shift q = _mm_add_epi32(q, _mm_srli_epi32(q, 31)); // q += (q < 0) return q; } __m128i libdivide_s32_branchfree_do_vector(__m128i numers, const struct libdivide_s32_branchfree_t *denom) { int32_t magic = denom->magic; uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; // must be arithmetic shift __m128i sign = _mm_set1_epi32((int32_t)(int8_t)more >> 7); // libdivide__mullhi_s32(numers, magic); __m128i q = libdivide_mullhi_s32_flat_vector(numers, _mm_set1_epi32(magic)); q = _mm_add_epi32(q, numers); // q += numers // If q is non-negative, we have nothing to do // If q is negative, we want to add either (2**shift)-1 if d is a power of // 2, or (2**shift) if it is not a power of 2 uint32_t is_power_of_2 = (magic == 0); __m128i q_sign = _mm_srai_epi32(q, 31); // q_sign = q >> 31 __m128i mask = _mm_set1_epi32((1 << shift) - is_power_of_2); q = _mm_add_epi32(q, _mm_and_si128(q_sign, mask)); // q = q + (q_sign & mask) q = _mm_srai_epi32(q, shift); //q >>= shift q = _mm_sub_epi32(_mm_xor_si128(q, sign), sign); // q = (q ^ sign) - sign return q; } #endif static inline struct libdivide_s64_t libdivide_internal_s64_gen(int64_t d, int branchfree) { if (d == 0) { LIBDIVIDE_ERROR("divider must be != 0"); } struct libdivide_s64_t result; // If d is a power of 2, or negative a power of 2, we have to use a shift. // This is especially important because the magic algorithm fails for -1. // To check if d is a power of 2 or its inverse, it suffices to check // whether its absolute value has exactly one bit set. This works even for // INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set // and is a power of 2. uint64_t ud = (uint64_t)d; uint64_t absD = (d < 0) ? -ud : ud; uint32_t floor_log_2_d = 63 - libdivide__count_leading_zeros64(absD); // check if exactly one bit is set, // don't care if absD is 0 since that's divide by zero if ((absD & (absD - 1)) == 0) { // Branchfree and non-branchfree cases are the same result.magic = 0; result.more = floor_log_2_d | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); } else { // the dividend here is 2**(floor_log_2_d + 63), so the low 64 bit word // is 0 and the high word is floor_log_2_d - 1 uint8_t more; uint64_t rem, proposed_m; proposed_m = libdivide_128_div_64_to_64(1ULL << (floor_log_2_d - 1), 0, absD, &rem); const uint64_t e = absD - rem; // We are going to start with a power of floor_log_2_d - 1. // This works if works if e < 2**floor_log_2_d. if (!branchfree && e < (1ULL << floor_log_2_d)) { // This power works more = floor_log_2_d - 1; } else { // We need to go one higher. This should not make proposed_m // overflow, but it will make it negative when interpreted as an // int32_t. proposed_m += proposed_m; const uint64_t twice_rem = rem + rem; if (twice_rem >= absD || twice_rem < rem) proposed_m += 1; // note that we only set the LIBDIVIDE_NEGATIVE_DIVISOR bit if we // also set ADD_MARKER this is an annoying optimization that // enables algorithm #4 to avoid the mask. However we always set it // in the branchfree case more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; } proposed_m += 1; int64_t magic = (int64_t)proposed_m; // Mark if we are negative if (d < 0) { more |= LIBDIVIDE_NEGATIVE_DIVISOR; if (!branchfree) { magic = -magic; } } result.more = more; result.magic = magic; } return result; } struct libdivide_s64_t libdivide_s64_gen(int64_t d) { return libdivide_internal_s64_gen(d, 0); } struct libdivide_s64_branchfree_t libdivide_s64_branchfree_gen(int64_t d) { if (d == 1) { LIBDIVIDE_ERROR("branchfree divider must be != 1"); } if (d == -1) { LIBDIVIDE_ERROR("branchfree divider must be != -1"); } struct libdivide_s64_t tmp = libdivide_internal_s64_gen(d, 1); struct libdivide_s64_branchfree_t ret = {tmp.magic, tmp.more}; return ret; } int64_t libdivide_s64_do(int64_t numer, const struct libdivide_s64_t *denom) { uint8_t more = denom->more; int64_t magic = denom->magic; if (magic == 0) { //shift path uint32_t shifter = more & LIBDIVIDE_64_SHIFT_MASK; uint64_t uq = (uint64_t)numer + ((numer >> 63) & ((1ULL << shifter) - 1)); int64_t q = (int64_t)uq; q = q >> shifter; // must be arithmetic shift and then sign-extend int64_t shiftMask = (int8_t)more >> 7; q = (q ^ shiftMask) - shiftMask; return q; } else { uint64_t uq = (uint64_t)libdivide__mullhi_s64(magic, numer); if (more & LIBDIVIDE_ADD_MARKER) { // must be arithmetic shift and then sign extend int64_t sign = (int8_t)more >> 7; uq += ((uint64_t)numer ^ sign) - sign; } int64_t q = (int64_t)uq; q >>= more & LIBDIVIDE_64_SHIFT_MASK; q += (q < 0); return q; } } int64_t libdivide_s64_branchfree_do(int64_t numer, const struct libdivide_s64_branchfree_t *denom) { uint8_t more = denom->more; uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; // must be arithmetic shift and then sign extend int64_t sign = (int8_t)more >> 7; int64_t magic = denom->magic; int64_t q = libdivide__mullhi_s64(magic, numer); q += numer; // If q is non-negative, we have nothing to do. // If q is negative, we want to add either (2**shift)-1 if d is a power of // 2, or (2**shift) if it is not a power of 2. uint32_t is_power_of_2 = (magic == 0); uint64_t q_sign = (uint64_t)(q >> 63); q += q_sign & ((1ULL << shift) - is_power_of_2); // Arithmetic right shift q >>= shift; // Negate if needed q = (q ^ sign) - sign; return q; } int64_t libdivide_s64_recover(const struct libdivide_s64_t *denom) { uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; if (denom->magic == 0) { // shift path uint64_t absD = 1ULL << shift; if (more & LIBDIVIDE_NEGATIVE_DIVISOR) { absD = -absD; } return (int64_t)absD; } else { // Unsigned math is much easier int negative_divisor = (more & LIBDIVIDE_NEGATIVE_DIVISOR); int magic_was_negated = (more & LIBDIVIDE_ADD_MARKER) ? denom->magic > 0 : denom->magic < 0; uint64_t d = (uint64_t)(magic_was_negated ? -denom->magic : denom->magic); uint64_t n_hi = 1ULL << shift, n_lo = 0; uint64_t rem_ignored; uint64_t q = libdivide_128_div_64_to_64(n_hi, n_lo, d, &rem_ignored); int64_t result = (int64_t)(q + 1); if (negative_divisor) { result = -result; } return result; } } int64_t libdivide_s64_branchfree_recover(const struct libdivide_s64_branchfree_t *denom) { return libdivide_s64_recover((const struct libdivide_s64_t *)denom); } int libdivide_s64_get_algorithm(const struct libdivide_s64_t *denom) { uint8_t more = denom->more; int positiveDivisor = !(more & LIBDIVIDE_NEGATIVE_DIVISOR); if (denom->magic == 0) return (positiveDivisor ? 0 : 1); // shift path else if (more & LIBDIVIDE_ADD_MARKER) return (positiveDivisor ? 2 : 3); else return 4; } int64_t libdivide_s64_do_alg0(int64_t numer, const struct libdivide_s64_t *denom) { uint32_t shifter = denom->more & LIBDIVIDE_64_SHIFT_MASK; int64_t q = numer + ((numer >> 63) & ((1ULL << shifter) - 1)); return q >> shifter; } int64_t libdivide_s64_do_alg1(int64_t numer, const struct libdivide_s64_t *denom) { // denom->shifter != -1 && demo->shiftMask != 0 uint32_t shifter = denom->more & LIBDIVIDE_64_SHIFT_MASK; int64_t q = numer + ((numer >> 63) & ((1ULL << shifter) - 1)); return - (q >> shifter); } int64_t libdivide_s64_do_alg2(int64_t numer, const struct libdivide_s64_t *denom) { int64_t q = libdivide__mullhi_s64(denom->magic, numer); q += numer; q >>= denom->more & LIBDIVIDE_64_SHIFT_MASK; q += (q < 0); return q; } int64_t libdivide_s64_do_alg3(int64_t numer, const struct libdivide_s64_t *denom) { int64_t q = libdivide__mullhi_s64(denom->magic, numer); q -= numer; q >>= denom->more & LIBDIVIDE_64_SHIFT_MASK; q += (q < 0); return q; } int64_t libdivide_s64_do_alg4(int64_t numer, const struct libdivide_s64_t *denom) { int64_t q = libdivide__mullhi_s64(denom->magic, numer); q >>= denom->more & LIBDIVIDE_64_SHIFT_MASK; q += (q < 0); return q; } #if defined(LIBDIVIDE_USE_SSE2) __m128i libdivide_s64_do_vector(__m128i numers, const struct libdivide_s64_t *denom) { uint8_t more = denom->more; int64_t magic = denom->magic; if (magic == 0) { // shift path uint32_t shifter = more & LIBDIVIDE_64_SHIFT_MASK; __m128i roundToZeroTweak = libdivide__u64_to_m128((1ULL << shifter) - 1); __m128i q = _mm_add_epi64(numers, _mm_and_si128(libdivide_s64_signbits(numers), roundToZeroTweak)); // q = numer + ((numer >> 63) & roundToZeroTweak); q = libdivide_s64_shift_right_vector(q, shifter); // q = q >> shifter __m128i shiftMask = _mm_set1_epi32((int32_t)((int8_t)more >> 7)); q = _mm_sub_epi64(_mm_xor_si128(q, shiftMask), shiftMask); // q = (q ^ shiftMask) - shiftMask; return q; } else { __m128i q = libdivide_mullhi_s64_flat_vector(numers, libdivide__u64_to_m128(magic)); if (more & LIBDIVIDE_ADD_MARKER) { __m128i sign = _mm_set1_epi32((int32_t)((int8_t)more >> 7)); // must be arithmetic shift q = _mm_add_epi64(q, _mm_sub_epi64(_mm_xor_si128(numers, sign), sign)); // q += ((numer ^ sign) - sign); } // q >>= denom->mult_path.shift q = libdivide_s64_shift_right_vector(q, more & LIBDIVIDE_64_SHIFT_MASK); q = _mm_add_epi64(q, _mm_srli_epi64(q, 63)); // q += (q < 0) return q; } } __m128i libdivide_s64_do_vector_alg0(__m128i numers, const struct libdivide_s64_t *denom) { uint32_t shifter = denom->more & LIBDIVIDE_64_SHIFT_MASK; __m128i roundToZeroTweak = libdivide__u64_to_m128((1ULL << shifter) - 1); __m128i q = _mm_add_epi64(numers, _mm_and_si128(libdivide_s64_signbits(numers), roundToZeroTweak)); q = libdivide_s64_shift_right_vector(q, shifter); return q; } __m128i libdivide_s64_do_vector_alg1(__m128i numers, const struct libdivide_s64_t *denom) { uint32_t shifter = denom->more & LIBDIVIDE_64_SHIFT_MASK; __m128i roundToZeroTweak = libdivide__u64_to_m128((1ULL << shifter) - 1); __m128i q = _mm_add_epi64(numers, _mm_and_si128(libdivide_s64_signbits(numers), roundToZeroTweak)); q = libdivide_s64_shift_right_vector(q, shifter); return _mm_sub_epi64(_mm_setzero_si128(), q); } __m128i libdivide_s64_do_vector_alg2(__m128i numers, const struct libdivide_s64_t *denom) { __m128i q = libdivide_mullhi_s64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); q = _mm_add_epi64(q, numers); q = libdivide_s64_shift_right_vector(q, denom->more & LIBDIVIDE_64_SHIFT_MASK); q = _mm_add_epi64(q, _mm_srli_epi64(q, 63)); // q += (q < 0) return q; } __m128i libdivide_s64_do_vector_alg3(__m128i numers, const struct libdivide_s64_t *denom) { __m128i q = libdivide_mullhi_s64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); q = _mm_sub_epi64(q, numers); q = libdivide_s64_shift_right_vector(q, denom->more & LIBDIVIDE_64_SHIFT_MASK); q = _mm_add_epi64(q, _mm_srli_epi64(q, 63)); // q += (q < 0) return q; } __m128i libdivide_s64_do_vector_alg4(__m128i numers, const struct libdivide_s64_t *denom) { __m128i q = libdivide_mullhi_s64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); q = libdivide_s64_shift_right_vector(q, denom->more & LIBDIVIDE_64_SHIFT_MASK); q = _mm_add_epi64(q, _mm_srli_epi64(q, 63)); return q; } __m128i libdivide_s64_branchfree_do_vector(__m128i numers, const struct libdivide_s64_branchfree_t *denom) { int64_t magic = denom->magic; uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; // must be arithmetic shift __m128i sign = _mm_set1_epi32((int32_t)(int8_t)more >> 7); // libdivide__mullhi_s64(numers, magic); __m128i q = libdivide_mullhi_s64_flat_vector(numers, libdivide__u64_to_m128(magic)); q = _mm_add_epi64(q, numers); // q += numers // If q is non-negative, we have nothing to do. // If q is negative, we want to add either (2**shift)-1 if d is a power of // 2, or (2**shift) if it is not a power of 2. uint32_t is_power_of_2 = (magic == 0); __m128i q_sign = libdivide_s64_signbits(q); // q_sign = q >> 63 __m128i mask = libdivide__u64_to_m128((1ULL << shift) - is_power_of_2); q = _mm_add_epi64(q, _mm_and_si128(q_sign, mask)); // q = q + (q_sign & mask) q = libdivide_s64_shift_right_vector(q, shift); // q >>= shift q = _mm_sub_epi64(_mm_xor_si128(q, sign), sign); // q = (q ^ sign) - sign return q; } #endif #ifdef __cplusplus enum { BRANCHFULL = -1, BRANCHFREE = -2, ALGORITHM0 = 0, ALGORITHM1 = 1, ALGORITHM2 = 2, ALGORITHM3 = 3, ALGORITHM4 = 4 }; namespace libdivide_internal { #if defined(LIBDIVIDE_USE_SSE2) #define MAYBE_VECTOR(X) X #define MAYBE_VECTOR_PARAM(X) __m128i vector_func(__m128i, const X *) #else #define MAYBE_VECTOR(X) 0 #define MAYBE_VECTOR_PARAM(X) int unused #endif #define BRANCHFULL_DIVIDER(INT, TYPE) \ typedef base<INT, \ libdivide_##TYPE##_t, \ libdivide_##TYPE##_gen, \ libdivide_##TYPE##_do, \ MAYBE_VECTOR(libdivide_##TYPE##_do_vector)> #define BRANCHFREE_DIVIDER(INT, TYPE) \ typedef base<INT, \ libdivide_##TYPE##_branchfree_t, \ libdivide_##TYPE##_branchfree_gen, \ libdivide_##TYPE##_branchfree_do, \ MAYBE_VECTOR(libdivide_##TYPE##_branchfree_do_vector)> #define ALGORITHM_DIVIDER(INT, TYPE, ALGO) \ typedef base<INT, \ libdivide_##TYPE##_t, \ libdivide_##TYPE##_gen, \ libdivide_##TYPE##_do_##ALGO, \ MAYBE_VECTOR(libdivide_##TYPE##_do_vector_##ALGO)> #define CRASH_DIVIDER(INT, TYPE) \ typedef base<INT, \ libdivide_##TYPE##_t, \ libdivide_##TYPE##_gen, \ libdivide_##TYPE##_crash, \ MAYBE_VECTOR(libdivide_##TYPE##_crash_vector)> // Base divider, provides storage for the actual divider. // @IntType: e.g. uint32_t // @DenomType: e.g. libdivide_u32_t // @gen_func(): e.g. libdivide_u32_gen // @do_func(): e.g. libdivide_u32_do // @MAYBE_VECTOR_PARAM: e.g. libdivide_u32_do_vector template<typename IntType, typename DenomType, DenomType gen_func(IntType), IntType do_func(IntType, const DenomType *), MAYBE_VECTOR_PARAM(DenomType)> struct base { // Storage for the actual divider DenomType denom; // Constructor that takes a divisor value, and applies the gen function base(IntType d) : denom(gen_func(d)) { } // Default constructor to allow uninitialized uses in e.g. arrays base() {} // Needed for unswitch base(const DenomType& d) : denom(d) { } IntType perform_divide(IntType val) const { return do_func(val, &denom); } #if defined(LIBDIVIDE_USE_SSE2) __m128i perform_divide_vector(__m128i val) const { return vector_func(val, &denom); } #endif }; // Functions that will never be called but are required to be able // to use unswitch in C++ template code. Unsigned has fewer algorithms // than signed i.e. alg3 and alg4 are not defined for unsigned. In // order to make templates compile we need to define unsigned alg3 and // alg4 as crash functions. uint32_t libdivide_u32_crash(uint32_t, const libdivide_u32_t *) { exit(-1); } uint64_t libdivide_u64_crash(uint64_t, const libdivide_u64_t *) { exit(-1); } #if defined(LIBDIVIDE_USE_SSE2) __m128i libdivide_u32_crash_vector(__m128i, const libdivide_u32_t *) { exit(-1); } __m128i libdivide_u64_crash_vector(__m128i, const libdivide_u64_t *) { exit(-1); } #endif template<typename T, int ALGO> struct dispatcher { }; // Templated dispatch using partial specialization template<> struct dispatcher<int32_t, BRANCHFULL> { BRANCHFULL_DIVIDER(int32_t, s32) divider; }; template<> struct dispatcher<int32_t, BRANCHFREE> { BRANCHFREE_DIVIDER(int32_t, s32) divider; }; template<> struct dispatcher<int32_t, ALGORITHM0> { ALGORITHM_DIVIDER(int32_t, s32, alg0) divider; }; template<> struct dispatcher<int32_t, ALGORITHM1> { ALGORITHM_DIVIDER(int32_t, s32, alg1) divider; }; template<> struct dispatcher<int32_t, ALGORITHM2> { ALGORITHM_DIVIDER(int32_t, s32, alg2) divider; }; template<> struct dispatcher<int32_t, ALGORITHM3> { ALGORITHM_DIVIDER(int32_t, s32, alg3) divider; }; template<> struct dispatcher<int32_t, ALGORITHM4> { ALGORITHM_DIVIDER(int32_t, s32, alg4) divider; }; template<> struct dispatcher<uint32_t, BRANCHFULL> { BRANCHFULL_DIVIDER(uint32_t, u32) divider; }; template<> struct dispatcher<uint32_t, BRANCHFREE> { BRANCHFREE_DIVIDER(uint32_t, u32) divider; }; template<> struct dispatcher<uint32_t, ALGORITHM0> { ALGORITHM_DIVIDER(uint32_t, u32, alg0) divider; }; template<> struct dispatcher<uint32_t, ALGORITHM1> { ALGORITHM_DIVIDER(uint32_t, u32, alg1) divider; }; template<> struct dispatcher<uint32_t, ALGORITHM2> { ALGORITHM_DIVIDER(uint32_t, u32, alg2) divider; }; template<> struct dispatcher<uint32_t, ALGORITHM3> { CRASH_DIVIDER(uint32_t, u32) divider; }; template<> struct dispatcher<uint32_t, ALGORITHM4> { CRASH_DIVIDER(uint32_t, u32) divider; }; template<> struct dispatcher<int64_t, BRANCHFULL> { BRANCHFULL_DIVIDER(int64_t, s64) divider; }; template<> struct dispatcher<int64_t, BRANCHFREE> { BRANCHFREE_DIVIDER(int64_t, s64) divider; }; template<> struct dispatcher<int64_t, ALGORITHM0> { ALGORITHM_DIVIDER (int64_t, s64, alg0) divider; }; template<> struct dispatcher<int64_t, ALGORITHM1> { ALGORITHM_DIVIDER (int64_t, s64, alg1) divider; }; template<> struct dispatcher<int64_t, ALGORITHM2> { ALGORITHM_DIVIDER (int64_t, s64, alg2) divider; }; template<> struct dispatcher<int64_t, ALGORITHM3> { ALGORITHM_DIVIDER (int64_t, s64, alg3) divider; }; template<> struct dispatcher<int64_t, ALGORITHM4> { ALGORITHM_DIVIDER (int64_t, s64, alg4) divider; }; template<> struct dispatcher<uint64_t, BRANCHFULL> { BRANCHFULL_DIVIDER(uint64_t, u64) divider; }; template<> struct dispatcher<uint64_t, BRANCHFREE> { BRANCHFREE_DIVIDER(uint64_t, u64) divider; }; template<> struct dispatcher<uint64_t, ALGORITHM0> { ALGORITHM_DIVIDER(uint64_t, u64, alg0) divider; }; template<> struct dispatcher<uint64_t, ALGORITHM1> { ALGORITHM_DIVIDER(uint64_t, u64, alg1) divider; }; template<> struct dispatcher<uint64_t, ALGORITHM2> { ALGORITHM_DIVIDER(uint64_t, u64, alg2) divider; }; template<> struct dispatcher<uint64_t, ALGORITHM3> { CRASH_DIVIDER(uint64_t, u64) divider; }; template<> struct dispatcher<uint64_t, ALGORITHM4> { CRASH_DIVIDER(uint64_t, u64) divider; }; // Overloads that don't depend on the algorithm inline int32_t recover(const libdivide_s32_t *s) { return libdivide_s32_recover(s); } inline uint32_t recover(const libdivide_u32_t *s) { return libdivide_u32_recover(s); } inline int64_t recover(const libdivide_s64_t *s) { return libdivide_s64_recover(s); } inline uint64_t recover(const libdivide_u64_t *s) { return libdivide_u64_recover(s); } inline int32_t recover(const libdivide_s32_branchfree_t *s) { return libdivide_s32_branchfree_recover(s); } inline uint32_t recover(const libdivide_u32_branchfree_t *s) { return libdivide_u32_branchfree_recover(s); } inline int64_t recover(const libdivide_s64_branchfree_t *s) { return libdivide_s64_branchfree_recover(s); } inline uint64_t recover(const libdivide_u64_branchfree_t *s) { return libdivide_u64_branchfree_recover(s); } inline int get_algorithm(const libdivide_s32_t *s) { return libdivide_s32_get_algorithm(s); } inline int get_algorithm(const libdivide_u32_t *s) { return libdivide_u32_get_algorithm(s); } inline int get_algorithm(const libdivide_s64_t *s) { return libdivide_s64_get_algorithm(s); } inline int get_algorithm(const libdivide_u64_t *s) { return libdivide_u64_get_algorithm(s); } // Fallback for branchfree variants, which do not support unswitching template<typename T> int get_algorithm(const T *) { return -1; } } template<typename T, int ALGO = BRANCHFULL> class divider { private: // Here's the actual divider typedef typename libdivide_internal::dispatcher<T, ALGO>::divider div_t; div_t div; // unswitch() friend declaration template<int NEW_ALGO, typename S> friend divider<S, NEW_ALGO> unswitch(const divider<S, BRANCHFULL> & d); // Constructor used by the unswitch friend divider(const div_t& denom) : div(denom) { } public: // Ordinary constructor that takes the divisor as a parameter divider(T n) : div(n) { } // Default constructor. We leave this deliberately undefined so that // creating an array of divider and then initializing them // doesn't slow us down. divider() { } // Divides the parameter by the divisor, returning the quotient T perform_divide(T val) const { return div.perform_divide(val); } // Recovers the divisor that was used to initialize the divider T recover_divisor() const { return libdivide_internal::recover(&div.denom); } #if defined(LIBDIVIDE_USE_SSE2) // Treats the vector as either two or four packed values (depending on the // size), and divides each of them by the divisor, // returning the packed quotients. __m128i perform_divide_vector(__m128i val) const { return div.perform_divide_vector(val); } #endif // Returns the index of algorithm, for use in the unswitch function. Does // not apply to branchfree variant. // Returns the algorithm for unswitching. int get_algorithm() const { return libdivide_internal::get_algorithm(&div.denom); } bool operator==(const divider<T, ALGO>& him) const { return div.denom.magic == him.div.denom.magic && div.denom.more == him.div.denom.more; } bool operator!=(const divider<T, ALGO>& him) const { return !(*this == him); } }; #if __cplusplus >= 201103L || \ (defined(_MSC_VER) && _MSC_VER >= 1800) template <typename T> using branchfree_divider = divider<T, BRANCHFREE>; #endif template<int NEW_ALGO, typename T> divider<T, NEW_ALGO> unswitch(const divider<T, BRANCHFULL>& d) { return divider<T, NEW_ALGO>(d.div.denom); } template<typename int_type, int ALGO> int_type operator/(int_type numer, const divider<int_type, ALGO>& denom) { return denom.perform_divide(numer); } template<typename int_type, int ALGO> int_type operator/=(int_type& numer, const divider<int_type, ALGO>& denom) { numer = denom.perform_divide(numer); return numer; } #if defined(LIBDIVIDE_USE_SSE2) template<typename int_type, int ALGO> __m128i operator/(__m128i numer, const divider<int_type, ALGO>& denom) { return denom.perform_divide_vector(numer); } template<typename int_type, int ALGO> __m128i operator/=(__m128i& numer, const divider<int_type, ALGO>& denom) { numer = denom.perform_divide_vector(numer); return numer; } #endif } // namespace libdivide } // anonymous namespace #endif // __cplusplus #endif // LIBDIVIDE_H #ifndef LOCAL #pragma GCC optimize ("O3") #endif #include <bits/stdc++.h> #include "message.h" using namespace std; #define sim template < class c #define ris return * this #define dor > debug & operator << #define eni(x) sim > typename \ enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) { sim > struct rge { c b, e; }; sim > rge<c> range(c i, c j) { return {i, j}; } sim > auto dud(c* x) -> decltype(cerr << *x, 0); sim > char dud(...); struct debug { #ifdef LOCAL ~debug() { cerr << endl; } eni(!=) cerr << boolalpha << i; ris; } eni(==) ris << range(begin(i), end(i)); } sim, class b dor(pair < b, c > d) { ris << "(" << d.first << ", " << d.second << ")"; } sim dor(rge<c> d) { *this << "["; for (c it = d.b; it != d.e; ++it) *this << ", " + 2 * (it == d.b) << *it; ris << "]"; } #else sim dor(const c&) { ris; } #endif }; #define imie(x...) " [" #x ": " << (x) << "] " #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> template <typename A, typename B> using unordered_map2 = __gnu_pbds::gp_hash_table<A, B>; using namespace __gnu_pbds; template <typename T> using ordered_set = __gnu_pbds::tree<T, __gnu_pbds::null_type, less<T>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>; using ld = long double; using ll = long long; int mod = 1000 * 1000 * 1000 + 7; libdivide::libdivide_u64_t fast_mod; int Moduluj(uint64_t x) { return x - mod * libdivide::libdivide_u64_do(x, &fast_mod); } void OdejmijOd(int& a, int b) { a -= b; if (a < 0) a += mod; } int Odejmij(int a, int b) { OdejmijOd(a, b); return a; } void DodajDo(int& a, int b) { a += b; if (a >= mod) a -= mod; } int Dodaj(int a, int b) { DodajDo(a, b); return a; } int Mnoz(int a, int b) { return Moduluj((ll) a * b); } void MnozDo(int& a, int b) { a = Mnoz(a, b); } int Pot(int a, ll b) { int res = 1; while (b) { if (b % 2 == 1) MnozDo(res, a); a = Mnoz(a, a); b /= 2; } return res; } int Odw(int a) { if (a == 0) return 0; return Pot(a, mod - 2); } void PodzielDo(int& a, int b) { MnozDo(a, Odw(b)); } int Podziel(int a, int b) { return Mnoz(a, Odw(b)); } template <typename T> T Maxi(T& a, T b) { return a = max(a, b); } template <typename T> T Mini(T& a, T b) { return a = min(a, b); } template <typename T> typename make_signed<T>::type ToSigned(T t) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-compare" using ST = typename make_signed<T>::type; if (t <= numeric_limits<ST>::max()) { return static_cast<ST>(t); } else if (t >= numeric_limits<ST>::min()) { return static_cast<ST>(t - numeric_limits<ST>::min()) + numeric_limits<ST>::min(); } else { abort(); } #pragma GCC diagnostic pop } using LengthType = uint32_t; class SendMessage; namespace SendMessageInternal { template <typename T> struct __Helper { static void Put(SendMessage& sm, const T& t); }; #define SM_SIMPLE_TYPE(type) \ template <> \ struct __Helper<type> { \ static void Put(SendMessage& sm, const type& t); \ }; SM_SIMPLE_TYPE(bool); SM_SIMPLE_TYPE(char); SM_SIMPLE_TYPE(signed char); SM_SIMPLE_TYPE(unsigned char); SM_SIMPLE_TYPE(signed int); SM_SIMPLE_TYPE(unsigned int); SM_SIMPLE_TYPE(signed long); SM_SIMPLE_TYPE(unsigned long); SM_SIMPLE_TYPE(signed long long); SM_SIMPLE_TYPE(unsigned long long); #undef SM_SIMPLE_TYPE template <typename A, typename B> struct __Helper<pair<A, B>> { static void Put(SendMessage& sm, const pair<A, B>& p); }; template <typename T> struct __Helper<rge<T>> { static void Put(SendMessage& sm, const rge<T>& d); }; } // namespace SendMessageInternal class SendMessage { private: int id_; bool is_sent_; static int nodes_; static int nodes(); template <typename T> using CleanT = typename remove_reference<typename remove_cv<T>::type>::type; public: SendMessage(int target) : id_(target), is_sent_(false) { assert(0 <= id_ and id_ < nodes()); } ~SendMessage() { if (!is_sent_) { Send(); } } int id() const { return id_; } template <typename T> SendMessage& Put(const T& t) { SendMessageInternal::__Helper<CleanT<T>>::Put(*this, t); return *this; } void Send() { assert(!is_sent_); is_sent_ = true; ::Send(id_); } }; int SendMessage::nodes_ = -1; int SendMessage::nodes() { if (nodes_ == -1) nodes_ = NumberOfNodes(); return nodes_; } namespace SendMessageInternal { template <typename T> void __PutResolver(SendMessage& sm, const T& t) {} template <typename T, typename Ptr1, typename ...Ptrs> void __PutResolver(SendMessage& sm, const T& t, Ptr1 ptr1, Ptrs ...ptrs) { sm.Put(t.*ptr1); __PutResolver(sm, t, ptrs...); } template <typename T> void __Helper<T>::Put(SendMessage& sm, const T& t) { sm.Put(range(begin(t), end(t))); } #define SM_SIMPLE_TYPE(type, func1, func2) \ void __Helper<type>::Put(SendMessage& sm, const type& t) { \ func2(sm.id(), func1(t)); \ } SM_SIMPLE_TYPE(bool, static_cast<char>, PutChar); SM_SIMPLE_TYPE(char, , PutChar); SM_SIMPLE_TYPE(signed char, , PutChar); SM_SIMPLE_TYPE(unsigned char, , PutChar); SM_SIMPLE_TYPE(signed int, , PutInt); SM_SIMPLE_TYPE(unsigned int, ToSigned, PutInt); SM_SIMPLE_TYPE(signed long, , PutLL); SM_SIMPLE_TYPE(unsigned long, ToSigned, PutLL); SM_SIMPLE_TYPE(signed long long, , PutLL); SM_SIMPLE_TYPE(unsigned long long, ToSigned, PutLL); #undef SM_SIMPLE_TYPE template <typename A, typename B> void __Helper<pair<A, B>>::Put(SendMessage& sm, const pair<A, B>& p) { sm.Put(p.first); sm.Put(p.second); } template <typename T> void __Helper<rge<T>>::Put(SendMessage& sm, const rge<T>& d) { sm.Put(static_cast<LengthType>(distance(d.b, d.e))); for (T it = d.b; it != d.e; ++it) { sm.Put(*it); } } } // namespace SendMessageInternal class ReceiveMessage; namespace ReceiveMessageInternal { template <typename T> struct __Helper { static T Get(ReceiveMessage& rm); }; #define RM_SIMPLE_TYPE(type) \ template <> \ struct __Helper<type> { \ static type Get(ReceiveMessage& rm); \ } RM_SIMPLE_TYPE(bool); RM_SIMPLE_TYPE(char); RM_SIMPLE_TYPE(signed char); RM_SIMPLE_TYPE(unsigned char); RM_SIMPLE_TYPE(signed int); RM_SIMPLE_TYPE(unsigned int); RM_SIMPLE_TYPE(signed long); RM_SIMPLE_TYPE(unsigned long); RM_SIMPLE_TYPE(signed long long); RM_SIMPLE_TYPE(unsigned long long); #undef RM_SIMPLE_TYPE template <typename A, typename B> struct __Helper<pair<A, B>> { static pair<A, B> Get(ReceiveMessage& rm); }; } // namespace ReceiveMessageInternal class ReceiveMessage { private: int id_; static int nodes_; static int nodes(); template <typename T> using CleanT = typename remove_reference<typename remove_cv<T>::type>::type; public: int id() const { return id_; } ReceiveMessage(int source) : id_(source) { assert(-1 <= id_ and id_ < nodes()); id_ = Receive(id_); assert(0 <= id_ and id_ < nodes()); } template <typename T> CleanT<T> Get() { return ReceiveMessageInternal::__Helper<CleanT<T>>::Get(*this); } }; int ReceiveMessage::nodes_ = -1; int ReceiveMessage::nodes() { if (nodes_ == -1) nodes_ = NumberOfNodes(); return nodes_; } namespace ReceiveMessageInternal { template <typename T> void __GetResolver(ReceiveMessage& rm, T& t) {} template <typename T, typename Ptr1, typename ...Ptrs> void __GetResolver(ReceiveMessage& rm, T& t, Ptr1 ptr1, Ptrs ...ptrs) { t.*ptr1 = rm.Get<decltype(t.*ptr1)>(); __GetResolver(rm, t, ptrs...); } template <typename T> T __Helper<T>::Get(ReceiveMessage& rm) { T t; auto it = inserter(t, end(t)); const LengthType len = rm.Get<LengthType>(); for (LengthType i = 0; i < len; i++) { *it = rm.Get<typename T::value_type>(); } return t; } #define RM_SIMPLE_TYPE(type, func1, func2) \ type __Helper<type>::Get(ReceiveMessage& rm) { \ return func1(func2(rm.id())); \ } RM_SIMPLE_TYPE(bool, static_cast<char>, GetChar); RM_SIMPLE_TYPE(char, , GetChar); RM_SIMPLE_TYPE(signed char, ToSigned, GetChar); RM_SIMPLE_TYPE(unsigned char, , GetChar); RM_SIMPLE_TYPE(signed int, , GetInt); RM_SIMPLE_TYPE(unsigned int, , GetInt); RM_SIMPLE_TYPE(signed long, , GetLL); RM_SIMPLE_TYPE(unsigned long, , GetLL); RM_SIMPLE_TYPE(signed long long, , GetLL); RM_SIMPLE_TYPE(unsigned long long, , GetLL); #undef RM_SIMPLE_TYPE template <typename A, typename B> pair<A, B> __Helper<pair<A, B>>::Get(ReceiveMessage& rm) { A a = rm.Get<A>(); B b = rm.Get<B>(); return {a, b}; } } // namespace ReceiveMessageInternal #define REGISTER_MESSAGE(type, fields...) \ namespace SendMessageInternal { \ template <> \ struct __Helper<type> { \ static void Put(SendMessage& sm, const type& d) { \ __PutResolver(sm, d, fields); \ } \ }; \ } \ namespace ReceiveMessageInternal { \ template <> \ struct __Helper<type> { \ static type Get(ReceiveMessage& rm) { \ type t; \ __GetResolver(rm, t, fields); \ return t; \ } \ }; \ } #define REGISTER_MESSAGE_CLASS(type, mclass) \ namespace SendMessageInternal { \ template <> struct __Helper<type> : public mclass {}; \ } \ namespace ReceiveMessageInternal { \ template <> struct __Helper<type> : public mclass {}; \ } template <typename T> class Range { private: T a_, b_; public: Range() : Range(T(1), T(0)) {} Range(T a, T b) : a_(a), b_(b) {} Range GetPart(int i, int n) const { assert(0 <= i and i < n); const T len = length(); const T part = len / n; const int ile_duzych = len % n; auto PartBeginning = [this, part, ile_duzych, n](int j) -> T { return a_ + j * part + min(ile_duzych, j); }; return Range(PartBeginning(i), PartBeginning(i + 1) - 1); } vector<Range> Divide(int n) const { assert(0 < n); vector<Range> res(n); for (int i = 0; i < n; i++) { res[i] = GetPart(i, n); } return res; } T a() const { return a_; } T b() const { return b_; } bool empty() const { return a_ > b_; } const T length() const { if (empty()) return 0; else return b_ - a_ + 1; } Range& operator&=(const Range& r) { Maxi(a_, r.a_); Mini(b_, r.b_); return *this; } Range operator&(const Range& r) const { return Range(*this) &= r; } friend debug& operator<<(debug& deb, const Range& r) { if (r.empty()) return deb << "[empty]"; else return deb << "[" << r.a() << ", " << r.b() << "]"; } }; template <typename T> struct RangeMessageHelper { static void Put(SendMessage& sm, const Range<T>& r) { sm.Put(r.a()).Put(r.b()); } static Range<T> Get(ReceiveMessage& rm) { const int a = rm.Get<int>(); const int b = rm.Get<int>(); return Range<T>(a, b); } }; REGISTER_MESSAGE_CLASS(Range<int>, RangeMessageHelper<int>); REGISTER_MESSAGE_CLASS(Range<ll>, RangeMessageHelper<ll>); namespace Fft { /* Prec. error max_ans/1e15 (2.5e18) for (long) doubles, so int rounding works for doubles with answers 0.5e15, e.g. for sizes 2^20 and RANDOM ints in [0,45k], assuming DBL_MANT_DIG=53 and LDBL_MANT_DIG=64. Consider normalizing and brute.*/ #define REP(i,n) for(int i = 0; i < int(n); ++i) typedef double ld; // 'long double' is 2.2 times slower struct C { ld real, imag; C operator * (const C & he) const { return C{real * he.real - imag * he.imag, real * he.imag + imag * he.real}; } void operator += (const C & he) { real += he.real; imag += he.imag; } }; void dft(vector<C> & a, bool rev) { const int n = a.size(); for(int i = 1, k = 0; i < n; ++i) { for(int bit = n / 2; (k ^= bit) < bit; bit /= 2);;; if(i < k) swap(a[i], a[k]); } for(int len = 1, who = 0; len < n; len *= 2, ++who) { static vector<C> t[30]; vector<C> & om = t[who]; if(om.empty()) { om.resize(len); const ld ang = 2 * acosl(0) / len; REP(i, len) om[i] = i%2 || !who ? C{cos(i*ang), sin(i*ang)} : t[who-1][i/2]; } for(int i = 0; i < n; i += 2 * len) REP(k, len) { const C x = a[i+k], y = a[i+k+len] * C{om[k].real, om[k].imag * (rev ? -1 : 1)}; a[i+k] += y; a[i+k+len] = C{x.real - y.real, x.imag - y.imag}; } } if(rev) REP(i, n) a[i].real /= n; } template<typename T>vector<T> multiply(const vector<T> & a, const vector<T> & b, bool split = false, bool normalize = false) { if(a.empty() || b.empty()) return {}; T big = 0; if(normalize) { // [0,B] into [-B/2, B/2] assert(a.size() == b.size()); // equal size!!! for(T x : a) big = max(big, x); for(T x : b) big = max(big, x); big /= 2; } int n = a.size() + b.size(); vector<T> ans(n - 1); if(min(a.size(),b.size()) < 190) { // BRUTE FORCE REP(i, a.size()) REP(j, b.size()) ans[i+j] = Moduluj(ans[i+j] + a[i]*b[j]); return ans; } while(n&(n-1)) ++n; auto speed = [&](const vector<C> & w, int i, int k) { int j = i ? n - i : 0, r = k ? -1 : 1; return C{w[i].real + w[j].real * r, w[i].imag - w[j].imag * r} * (k ? C{0, -0.5} : C{0.5, 0}); }; if(!split) { // standard fast version vector<C> in(n), done(n); REP(i, a.size()) in[i].real = a[i] - big; REP(i, b.size()) in[i].imag = b[i] - big; dft(in, false); REP(i, n) done[i] = speed(in, i, 0) * speed(in, i, 1); dft(done, true); REP(i, ans.size()) ans[i] = is_integral<T>::value ? llround(done[i].real) : done[i].real; //REP(i,ans.size())err=max(err,abs(done[i].real-ans[i])); } else { // Split big INTEGERS into pairs a1*M+a2, const T M = 1<<15; // where M = sqrt(max_absvalue). vector<C> t[2]; // This version is 2.2-2.5 times slower. REP(x, 2) { t[x].resize(n); auto & in = x ? b : a; // below use (in[i]-big) if normalized REP(i, in.size()) t[x][i]=C{ld(in[i]%M), ld(in[i]/M)}; dft(t[x], false); } T mul = 1; for(int s = 0; s < 3; ++s, mul *= M) { vector<C> prod(n); REP(x, 2) REP(y, 2) if(x + y == s) REP(i, n) prod[i] += speed(t[0], i, x) * speed(t[1], i, y); dft(prod, true); // remember: llround(prod[i].real)%MOD*mul !!! REP(i, ans.size()) ans[i]+= Moduluj(llround(prod[i].real))*mul; } } if(normalize) { T so_far = 0; REP(i, ans.size()) { if(i < (int) a.size()) so_far += a[i] + b[i]; else so_far -= a[i-a.size()] + b[i-a.size()]; ans[i] += big * so_far - big * big * min(i + 1, (int) ans.size() - i); } } return ans; } vector<int> Mul(const vector<int>& a, const vector<int>& b) { vector<ll> A(a.begin(), a.end()), B(b.begin(), b.end()); auto res = multiply(A, B, true); vector<int> wyn; wyn.reserve(res.size()); for (ll x : res) wyn.push_back(Moduluj(x)); return wyn; } const ll M = 1 << 17; // M can be smaller if vectors are small vector<ll> compress(const vector<ll> & a) { vector<ll> tmp((a.size() + 1) / 2); for(int i = 0; 2 * i + 1 < (int) a.size(); ++i) tmp[i] += a[2 * i] + a[2 * i + 1] * M; if(a.size() % 2) tmp.back() = a.back(); return tmp; } vector<ll> my_mul(const vector<ll> & a, const vector<ll> & b) { vector<ll> tmp = multiply(compress(a), compress(b), false); vector<ll> r(2 * tmp.size() + 1); for(int i = 0; i < (int) tmp.size(); ++i) { r[2*i] += tmp[i] % M; // can be sped-up with bit shifting r[2*i+1] += tmp[i] / M % M; r[2*i+2] += tmp[i] / M / M; } r.resize(a.size() + b.size() - 1); return r; } #undef REP } // namespace Fft namespace Karatsuba { uint64_t tmp[1 << 18]; uint64_t mod_wielok; constexpr uint64_t prog = 17e18; void Init() { mod_wielok = (prog / mod) * mod; } #define REP(i, n) for(int i = 0; i < (n); ++i) template<typename T> void rec_kara(T* a, int one, T* b, int two, T* r) { if(min(one, two) <= 10) { // must be at least "<= 1" REP(i, one) REP(j, two) { r[i+j] = Moduluj(ll(a[i]) * b[j] + r[i+j]); } return; } const int x = min(one, two); if(one < two) rec_kara(a, x, b + x, two - x, r + x); if(two < one) rec_kara(a + x, one - x, b, x, r + x); const int n = (x + 1) / 2, right = x / 2; vector<T> tu(2 * n); rec_kara(a, n, b, n, tu.data()); REP(i, 2 * n - 1) { //r[i] += tu[i]; DodajDo(r[i], tu[i]); //r[i+n] -= tu[i]; OdejmijOd(r[i+n], tu[i]); tu[i] = 0; } rec_kara(a + n, right, b + n, right, tu.data()); REP(i, 2 * right - 1) { OdejmijOd(r[i+n], tu[i]); //r[i+n] -= tu[i]; DodajDo(r[i+2*n], tu[i]); //r[i+2*n] += tu[i]; } tu[n-1] = a[n-1]; tu[2*n-1] = b[n-1]; REP(i, right) { tu[i] = Dodaj(a[i],a[i+n]); tu[i+n] = Dodaj(b[i],b[i+n]); } rec_kara(tu.data(), n, tu.data() + n, n, r + n); } template<typename T> vector<T> karatsuba(vector<T> a, vector<T> b) { if(a.empty() || b.empty()) return {}; vector<T> r(a.size() + b.size() - 1); rec_kara(a.data(), a.size(), b.data(), b.size(), r.data()); return r; } #undef REP } // namespace Karatsuba struct Poly { vector<int> wsp; friend debug& operator<<(debug& deb, const Poly& p); Poly() = default; explicit Poly(vector<int>&& w) : wsp(move(w)) { while (!wsp.empty() and wsp.back() == 0) { wsp.pop_back(); } } static Poly Jednomian(int i) { vector<int> res(i + 1); res.back() = 1; return Poly(move(res)); } int Deg() const { return (int) wsp.size() - 1; } int operator()(int x) const { int res = 0; for (int i = (int) wsp.size() - 1; i >= 0; i--) { res = Dodaj(Mnoz(res, x), wsp[i]); } return res; } Poly operator-() const { vector<int> res = wsp; for (int& x : res) { x = Odejmij(0, x); } return Poly(move(res)); } Poly operator+(const Poly& p) const { vector<int> res(max(wsp.size(), p.wsp.size())); for (int i = 0; i < (int) res.size(); i++) { if (i < (int) wsp.size()) { res[i] = wsp[i]; } if (i < (int) p.wsp.size()) { DodajDo(res[i], p.wsp[i]); } } return Poly(move(res)); } Poly operator-(const Poly& p) const { vector<int> res(max(wsp.size(), p.wsp.size())); for (int i = 0; i < (int) res.size(); i++) { if (i < (int) wsp.size()) { res[i] = wsp[i]; } if (i < (int) p.wsp.size()) { OdejmijOd(res[i], p.wsp[i]); } } return Poly(move(res)); } Poly operator*(const Poly& p) const { //return Poly(Karatsuba::karatsuba(wsp, p.wsp)); return Poly(Fft::Mul(wsp, p.wsp)); } Poly operator*(int c) const { vector<int> res = wsp; for (int& x : res) { MnozDo(x, c); } return Poly(move(res)); } Poly Utnij(int len) const { vector<int> kopia = wsp; if ((int) kopia.size() > len) { kopia.resize(len); } return Poly(move(kopia)); } Poly Zjedz(int len) const { vector<int> res = wsp; if ((int) res.size() <= len) { res.clear(); } else { res.erase(res.begin(), res.begin() + len); } return Poly(move(res)); } Poly Rev() const { vector<int> res = wsp; reverse(res.begin(), res.end()); return Poly(move(res)); } Poly Inverse(int l) const { debug() << imie(*this) << ".Inverse(" imie(l) ")"; #ifdef LOCAL assert((*this)(0) == 1); #endif Poly g(vector<int>{1}); int n = 1; while (n < l) { n = 2 * n; if (n > l) n = l; Poly h = Utnij(n); h = (h * g).Utnij(n); g = (g * (Poly(vector<int>{Moduluj(2)}) - h)).Utnij(n); } #ifdef LOCAL debug() << imie(*this) imie(g); debug() << imie((*this * g).Utnij(l)); assert((*this * g).Utnij(l) == Poly(vector<int>{1})); #endif return g; } Poly operator/(const Poly& b) const { assert(!b.wsp.empty() and b.wsp.back() == 1); const int n = Deg(); const int m = b.Deg(); if (n < m) { return *this; } Poly f = b.Rev(); Poly g = f.Inverse(n - m + 1).Utnij(n - m + 1); Poly q = (Rev() * g).Utnij(n - m + 1); return q.Rev(); } Poly operator%(const Poly& b) const { assert(!b.wsp.empty() and b.wsp.back() == 1); const int n = Deg(); const int m = b.Deg(); if (n < m) { return *this; } Poly f = b.Rev(); Poly g = f.Inverse(n - m + 1).Utnij(n - m + 1); Poly q = (Rev() * g).Utnij(n - m + 1); return *this - b * q.Rev(); } bool operator==(const Poly& p) const { return wsp == p.wsp; } bool operator!=(const Poly& p) const { return wsp != p.wsp; } }; struct PolyTree { vector<int> xs; bool wyznaczone; Poly poly; unique_ptr<PolyTree> left, right; PolyTree(vector<int> xs_) : xs(move(xs_)), wyznaczone(false) { assert(!xs.empty()); if ((int) xs.size() == 1) { poly = Poly(vector<int>{Odejmij(0, xs[0]), 1}); } else { const int s = (int) xs.size() / 2; left = unique_ptr<PolyTree>(new PolyTree( vector<int>(xs.begin(), xs.begin() + s))); right = unique_ptr<PolyTree>(new PolyTree( vector<int>(xs.begin() + s, xs.end()))); } } void Wyznacz() { if (wyznaczone) return; wyznaczone = true; if (left) { left->Wyznacz(); right->Wyznacz(); poly = left->poly * right->poly; } } void Evaluate(const Poly& p, vector<int>& result) { if ((int) xs.size() <= 1000) { for (int x : xs) { result.push_back(p(x)); } return; } //Poly q = p % poly; assert(left and right); left->Wyznacz(); right->Wyznacz(); left->Evaluate(p % left->poly, result); right->Evaluate(p % right->poly, result); } }; vector<int> Evaluate(const Poly& poly, const vector<int>& xs) { vector<int> res; if (xs.empty()) return res; PolyTree tree(xs); res.reserve(xs.size()); tree.Evaluate(poly, res); #ifdef LOCAL assert(res.size() == xs.size()); for (int i = 0; i < (int) res.size(); i++) { assert(res[i] == poly(xs[i])); } #endif return res; } debug& operator<<(debug& deb, const Poly& p) { return deb << "Poly{" << p.wsp << "}"; } Poly PolyPrzedzial(int a, int b) { if (a == b) return Poly(vector<int>{a, 1}); const int s = (a + b) / 2; return PolyPrzedzial(a, s) * PolyPrzedzial(s + 1, b); } constexpr int MaxN = 1000 * 1000 * 1000 + 10; vector<int> Factorial(const vector<int>& ns) { debug() << "Factorial(" imie(ns) ")"; constexpr int Skok = 31 * 1000; Poly p = PolyPrzedzial(1, Skok); vector<int> punkty; for (int i = 0; i < MaxN; i += Skok) { punkty.push_back(i); } vector<int> wart = Evaluate(p, punkty); assert(punkty.size() == wart.size()); auto Oblicz = [&](int n) -> int { if (n < 0) return 0; int res = 1; int mam_do = 0; for (int i = 0; i < (int) punkty.size(); i++) { if (punkty[i] + Skok <= n) { MnozDo(res, wart[i]); mam_do = punkty[i] + Skok; } else { break; } } for (int i = mam_do + 1; i <= n; i++) { MnozDo(res, i); } return res; }; vector<int> res; for (int n : ns) { res.push_back(Oblicz(n)); } debug() << imie(res); return res; } int FactorialBrut(int n) { int res = 1; for (int i = 1; i <= n; i++) { MnozDo(res, i); } return res; } int CBrut(int n, int k) { if (0 <= k and k <= n) { return Podziel(FactorialBrut(n), Mnoz(FactorialBrut(n - k), FactorialBrut(k))); } return 0; } vector<int> Oblicz(int a, int b, int k) { debug() << "Oblicz(" imie(a) imie(b) imie(k) ")"; // Dla każdego i in [a..b] zwraca C(i, k). vector<int> res(b - a + 1); vector<int> silnie = Factorial({a, b - k, k}); assert((int) silnie.size() == 3); int Licznik = silnie[0]; int Mianownik = Podziel(1, silnie[1]); const int ksilnia = Podziel(1, silnie[2]); debug() << imie(Licznik) imie(Mianownik) imie(ksilnia); for (int i = a; i < b; i++) { res[i - a] = Mnoz(Licznik, ksilnia); MnozDo(Licznik, i + 1); } res[b - a] = Mnoz(Licznik, ksilnia); for (int i = b; i > a; i--) { MnozDo(res[i - a], Mianownik); MnozDo(Mianownik, i - k); } MnozDo(res[a - a], Mianownik); return res; } pair<int, int> ObliczFunkcje(const vector<int>& v) { pair<int, int> res = {1, 0}; for (int x : v) { res = {Dodaj(res.first, res.first), Dodaj(res.second, res.second)}; OdejmijOd(res.second, x); } return res; } #include "futbol.h" int N, me; int main() { N = NumberOfNodes(); me = MyNodeId(); mod = GetP(); Mini(N, mod); if (me >= N) return 0; const int k = GetK(); fast_mod = libdivide::libdivide_u64_gen(mod); debug() << imie(mod) imie(k) imie(MaxN); auto ranges = Range<int>(0, mod - 1).Divide(N); vector<int> v = Oblicz(ranges[me].a(), ranges[me].b(), k); debug() << imie(v); auto fun = ObliczFunkcje(v); debug() << imie(fun); debug() << imie(ranges); int lewo, n; if (me == 0) { lewo = 1; n = GetN() - 1; assert(0 <= n and n < MaxN); } else { ReceiveMessage msg(me - 1); lewo = msg.Get<int>(); n = msg.Get<int>(); } debug() << imie(lewo) imie(n); if (n < ranges[me].a()) { if (me + 1 < N) { SendMessage(me + 1).Put(lewo).Put(n); } } else if (n <= ranges[me].b()) { if (me + 1 < N) { SendMessage(me + 1).Put(lewo).Put(n); } const int a = ranges[me].a(); for (int i = a; i <= n; i++) { lewo = Odejmij(Dodaj(lewo, lewo), v[i - a]); } cout << lewo << endl; //assert(lewo == 2998413); } else { assert(ranges[me].b() < n); lewo = Dodaj(Mnoz(fun.first, lewo), fun.second); assert(me + 1 < N); SendMessage(me + 1).Put(lewo).Put(n); } return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 | #ifndef LIBDIVIDE_H #define LIBDIVIDE_H #if defined(_MSC_VER) #pragma warning(disable: 4146) #define LIBDIVIDE_VC #endif #ifdef __cplusplus #include <cstdlib> #include <cstdio> #else #include <stdlib.h> #include <stdio.h> #endif #include <stdint.h> #if defined(LIBDIVIDE_USE_SSE2) #include <emmintrin.h> #endif #if defined(LIBDIVIDE_VC) #include <intrin.h> #endif #ifndef __has_builtin #define __has_builtin(x) 0 // Compatibility with non-clang compilers. #endif #if defined(__SIZEOF_INT128__) #define HAS_INT128_T #endif #if defined(__x86_64__) || defined(_WIN64) || defined(_M_X64) #define LIBDIVIDE_IS_X86_64 #endif #if defined(__i386__) #define LIBDIVIDE_IS_i386 #endif #if defined(__GNUC__) || defined(__clang__) #define LIBDIVIDE_GCC_STYLE_ASM #endif #if defined(__cplusplus) || defined(LIBDIVIDE_VC) #define LIBDIVIDE_FUNCTION __FUNCTION__ #else #define LIBDIVIDE_FUNCTION __func__ #endif #define LIBDIVIDE_ERROR(msg) \ do { \ fprintf(stderr, "libdivide.h:%d: %s(): Error: %s\n", \ __LINE__, LIBDIVIDE_FUNCTION, msg); \ exit(-1); \ } while (0) #if defined(LIBDIVIDE_ASSERTIONS_ON) #define LIBDIVIDE_ASSERT(x) \ do { \ if (!(x)) { \ fprintf(stderr, "libdivide.h:%d: %s(): Assertion failed: %s\n", \ __LINE__, LIBDIVIDE_FUNCTION, #x); \ exit(-1); \ } \ } while (0) #else #define LIBDIVIDE_ASSERT(x) #endif #ifdef LIBDIVIDE_USE_SSE4_1 #include <smmintrin.h> #endif #ifdef __cplusplus namespace { namespace libdivide { #endif enum { LIBDIVIDE_32_SHIFT_MASK = 0x1F, LIBDIVIDE_64_SHIFT_MASK = 0x3F, LIBDIVIDE_ADD_MARKER = 0x40, LIBDIVIDE_U32_SHIFT_PATH = 0x80, LIBDIVIDE_U64_SHIFT_PATH = 0x80, LIBDIVIDE_S32_SHIFT_PATH = 0x20, LIBDIVIDE_NEGATIVE_DIVISOR = 0x80 }; #pragma pack(push, 1) struct libdivide_u32_t { uint32_t magic; uint8_t more; }; struct libdivide_s32_t { int32_t magic; uint8_t more; }; struct libdivide_u64_t { uint64_t magic; uint8_t more; }; struct libdivide_s64_t { int64_t magic; uint8_t more; }; struct libdivide_u32_branchfree_t { uint32_t magic; uint8_t more; }; struct libdivide_s32_branchfree_t { int32_t magic; uint8_t more; }; struct libdivide_u64_branchfree_t { uint64_t magic; uint8_t more; }; struct libdivide_s64_branchfree_t { int64_t magic; uint8_t more; }; #pragma pack(pop) #ifndef LIBDIVIDE_API #ifdef __cplusplus // In C++, we don't want our public functions to be static, because // they are arguments to templates and static functions can't do that. // They get internal linkage through virtue of the anonymous namespace. // In C, they should be static. #define LIBDIVIDE_API #else #define LIBDIVIDE_API static inline #endif #endif LIBDIVIDE_API struct libdivide_s32_t libdivide_s32_gen(int32_t y); LIBDIVIDE_API struct libdivide_u32_t libdivide_u32_gen(uint32_t y); LIBDIVIDE_API struct libdivide_s64_t libdivide_s64_gen(int64_t y); LIBDIVIDE_API struct libdivide_u64_t libdivide_u64_gen(uint64_t y); LIBDIVIDE_API struct libdivide_s32_branchfree_t libdivide_s32_branchfree_gen(int32_t y); LIBDIVIDE_API struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t y); LIBDIVIDE_API struct libdivide_s64_branchfree_t libdivide_s64_branchfree_gen(int64_t y); LIBDIVIDE_API struct libdivide_u64_branchfree_t libdivide_u64_branchfree_gen(uint64_t y); LIBDIVIDE_API int32_t libdivide_s32_do(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do(int64_t numer, const struct libdivide_s64_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_do(uint64_t y, const struct libdivide_u64_t *denom); LIBDIVIDE_API int32_t libdivide_s32_branchfree_do(int32_t numer, const struct libdivide_s32_branchfree_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom); LIBDIVIDE_API int64_t libdivide_s64_branchfree_do(int64_t numer, const struct libdivide_s64_branchfree_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_branchfree_do(uint64_t y, const struct libdivide_u64_branchfree_t *denom); LIBDIVIDE_API int32_t libdivide_s32_recover(const struct libdivide_s32_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom); LIBDIVIDE_API int64_t libdivide_s64_recover(const struct libdivide_s64_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_recover(const struct libdivide_u64_t *denom); LIBDIVIDE_API int32_t libdivide_s32_branchfree_recover(const struct libdivide_s32_branchfree_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom); LIBDIVIDE_API int64_t libdivide_s64_branchfree_recover(const struct libdivide_s64_branchfree_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_branchfree_recover(const struct libdivide_u64_branchfree_t *denom); LIBDIVIDE_API int libdivide_u32_get_algorithm(const struct libdivide_u32_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_do_alg0(uint32_t numer, const struct libdivide_u32_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_do_alg1(uint32_t numer, const struct libdivide_u32_t *denom); LIBDIVIDE_API uint32_t libdivide_u32_do_alg2(uint32_t numer, const struct libdivide_u32_t *denom); LIBDIVIDE_API int libdivide_u64_get_algorithm(const struct libdivide_u64_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_do_alg0(uint64_t numer, const struct libdivide_u64_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_do_alg1(uint64_t numer, const struct libdivide_u64_t *denom); LIBDIVIDE_API uint64_t libdivide_u64_do_alg2(uint64_t numer, const struct libdivide_u64_t *denom); LIBDIVIDE_API int libdivide_s32_get_algorithm(const struct libdivide_s32_t *denom); LIBDIVIDE_API int32_t libdivide_s32_do_alg0(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API int32_t libdivide_s32_do_alg1(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API int32_t libdivide_s32_do_alg2(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API int32_t libdivide_s32_do_alg3(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API int32_t libdivide_s32_do_alg4(int32_t numer, const struct libdivide_s32_t *denom); LIBDIVIDE_API int libdivide_s64_get_algorithm(const struct libdivide_s64_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do_alg0(int64_t numer, const struct libdivide_s64_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do_alg1(int64_t numer, const struct libdivide_s64_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do_alg2(int64_t numer, const struct libdivide_s64_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do_alg3(int64_t numer, const struct libdivide_s64_t *denom); LIBDIVIDE_API int64_t libdivide_s64_do_alg4(int64_t numer, const struct libdivide_s64_t *denom); #if defined(LIBDIVIDE_USE_SSE2) LIBDIVIDE_API __m128i libdivide_u32_do_vector(__m128i numers, const struct libdivide_u32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_u64_do_vector(__m128i numers, const struct libdivide_u64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_u32_do_vector_alg0(__m128i numers, const struct libdivide_u32_t *denom); LIBDIVIDE_API __m128i libdivide_u32_do_vector_alg1(__m128i numers, const struct libdivide_u32_t *denom); LIBDIVIDE_API __m128i libdivide_u32_do_vector_alg2(__m128i numers, const struct libdivide_u32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector_alg0(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector_alg1(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector_alg2(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector_alg3(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_s32_do_vector_alg4(__m128i numers, const struct libdivide_s32_t *denom); LIBDIVIDE_API __m128i libdivide_u64_do_vector_alg0(__m128i numers, const struct libdivide_u64_t *denom); LIBDIVIDE_API __m128i libdivide_u64_do_vector_alg1(__m128i numers, const struct libdivide_u64_t *denom); LIBDIVIDE_API __m128i libdivide_u64_do_vector_alg2(__m128i numers, const struct libdivide_u64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector_alg0(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector_alg1(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector_alg2(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector_alg3(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_s64_do_vector_alg4(__m128i numers, const struct libdivide_s64_t *denom); LIBDIVIDE_API __m128i libdivide_u32_branchfree_do_vector(__m128i numers, const struct libdivide_u32_branchfree_t *denom); LIBDIVIDE_API __m128i libdivide_s32_branchfree_do_vector(__m128i numers, const struct libdivide_s32_branchfree_t *denom); LIBDIVIDE_API __m128i libdivide_u64_branchfree_do_vector(__m128i numers, const struct libdivide_u64_branchfree_t *denom); LIBDIVIDE_API __m128i libdivide_s64_branchfree_do_vector(__m128i numers, const struct libdivide_s64_branchfree_t *denom); #endif static inline uint32_t libdivide__mullhi_u32(uint32_t x, uint32_t y) { uint64_t xl = x, yl = y; uint64_t rl = xl * yl; return (uint32_t)(rl >> 32); } static uint64_t libdivide__mullhi_u64(uint64_t x, uint64_t y) { #if defined(LIBDIVIDE_VC) && defined(LIBDIVIDE_IS_X86_64) return __umulh(x, y); #elif defined(HAS_INT128_T) __uint128_t xl = x, yl = y; __uint128_t rl = xl * yl; return (uint64_t)(rl >> 64); #else // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) uint32_t mask = 0xFFFFFFFF; uint32_t x0 = (uint32_t)(x & mask); uint32_t x1 = (uint32_t)(x >> 32); uint32_t y0 = (uint32_t)(y & mask); uint32_t y1 = (uint32_t)(y >> 32); uint32_t x0y0_hi = libdivide__mullhi_u32(x0, y0); uint64_t x0y1 = x0 * (uint64_t)y1; uint64_t x1y0 = x1 * (uint64_t)y0; uint64_t x1y1 = x1 * (uint64_t)y1; uint64_t temp = x1y0 + x0y0_hi; uint64_t temp_lo = temp & mask; uint64_t temp_hi = temp >> 32; return x1y1 + temp_hi + ((temp_lo + x0y1) >> 32); #endif } static inline int64_t libdivide__mullhi_s64(int64_t x, int64_t y) { #if defined(LIBDIVIDE_VC) && defined(LIBDIVIDE_IS_X86_64) return __mulh(x, y); #elif defined(HAS_INT128_T) __int128_t xl = x, yl = y; __int128_t rl = xl * yl; return (int64_t)(rl >> 64); #else // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) uint32_t mask = 0xFFFFFFFF; uint32_t x0 = (uint32_t)(x & mask); uint32_t y0 = (uint32_t)(y & mask); int32_t x1 = (int32_t)(x >> 32); int32_t y1 = (int32_t)(y >> 32); uint32_t x0y0_hi = libdivide__mullhi_u32(x0, y0); int64_t t = x1 * (int64_t)y0 + x0y0_hi; int64_t w1 = x0 * (int64_t)y1 + (t & mask); return x1 * (int64_t)y1 + (t >> 32) + (w1 >> 32); #endif } #if defined(LIBDIVIDE_USE_SSE2) static inline __m128i libdivide__u64_to_m128(uint64_t x) { #if defined(LIBDIVIDE_VC) && !defined(_WIN64) // 64 bit windows doesn't seem to have an implementation of any of these // load intrinsics, and 32 bit Visual C++ crashes _declspec(align(16)) uint64_t temp[2] = {x, x}; return _mm_load_si128((const __m128i*)temp); #else // everyone else gets it right return _mm_set1_epi64x(x); #endif } static inline __m128i libdivide_get_FFFFFFFF00000000(void) { // returns the same as _mm_set1_epi64(0xFFFFFFFF00000000ULL) // without touching memory. // optimizes to pcmpeqd on OS X __m128i result = _mm_set1_epi8(-1); return _mm_slli_epi64(result, 32); } static inline __m128i libdivide_get_00000000FFFFFFFF(void) { // returns the same as _mm_set1_epi64(0x00000000FFFFFFFFULL) // without touching memory. // optimizes to pcmpeqd on OS X __m128i result = _mm_set1_epi8(-1); result = _mm_srli_epi64(result, 32); return result; } static inline __m128i libdivide_s64_signbits(__m128i v) { // we want to compute v >> 63, that is, _mm_srai_epi64(v, 63). But there // is no 64 bit shift right arithmetic instruction in SSE2. So we have to // fake it by first duplicating the high 32 bit values, and then using a 32 // bit shift. Another option would be to use _mm_srli_epi64(v, 63) and // then subtract that from 0, but that approach appears to be substantially // slower for unknown reasons __m128i hiBitsDuped = _mm_shuffle_epi32(v, _MM_SHUFFLE(3, 3, 1, 1)); __m128i signBits = _mm_srai_epi32(hiBitsDuped, 31); return signBits; } static inline __m128i libdivide_u32_to_m128i(uint32_t amt) { return _mm_set_epi32(0, 0, 0, amt); } static inline __m128i libdivide_s64_shift_right_vector(__m128i v, int amt) { // implementation of _mm_sra_epi64. Here we have two 64 bit values which // are shifted right to logically become (64 - amt) values, and are then // sign extended from a (64 - amt) bit number. const int b = 64 - amt; __m128i m = libdivide__u64_to_m128(1ULL << (b - 1)); __m128i x = _mm_srl_epi64(v, libdivide_u32_to_m128i(amt)); __m128i result = _mm_sub_epi64(_mm_xor_si128(x, m), m); // result = x^m - m return result; } static inline __m128i libdivide__mullhi_u32_flat_vector(__m128i a, __m128i b) { __m128i hi_product_0Z2Z = _mm_srli_epi64(_mm_mul_epu32(a, b), 32); __m128i a1X3X = _mm_srli_epi64(a, 32); __m128i mask = libdivide_get_FFFFFFFF00000000(); __m128i hi_product_Z1Z3 = _mm_and_si128(_mm_mul_epu32(a1X3X, b), mask); return _mm_or_si128(hi_product_0Z2Z, hi_product_Z1Z3); // = hi_product_0123 } static inline __m128i libdivide_mullhi_u64_flat_vector(__m128i x, __m128i y) { // full 128 bits are x0 * y0 + (x0 * y1 << 32) + (x1 * y0 << 32) + (x1 * y1 << 64) __m128i mask = libdivide_get_00000000FFFFFFFF(); // x0 is low half of 2 64 bit values, x1 is high half in low slots __m128i x0 = _mm_and_si128(x, mask); __m128i x1 = _mm_srli_epi64(x, 32); __m128i y0 = _mm_and_si128(y, mask); __m128i y1 = _mm_srli_epi64(y, 32); // x0 happens to have the low half of the two 64 bit values in 32 bit slots // 0 and 2, so _mm_mul_epu32 computes their full product, and then we shift // right by 32 to get just the high values __m128i x0y0_hi = _mm_srli_epi64(_mm_mul_epu32(x0, y0), 32); __m128i x0y1 = _mm_mul_epu32(x0, y1); __m128i x1y0 = _mm_mul_epu32(x1, y0); __m128i x1y1 = _mm_mul_epu32(x1, y1); __m128i temp = _mm_add_epi64(x1y0, x0y0_hi); __m128i temp_lo = _mm_and_si128(temp, mask); __m128i temp_hi = _mm_srli_epi64(temp, 32); temp_lo = _mm_srli_epi64(_mm_add_epi64(temp_lo, x0y1), 32); temp_hi = _mm_add_epi64(x1y1, temp_hi); return _mm_add_epi64(temp_lo, temp_hi); } static inline __m128i libdivide_mullhi_s64_flat_vector(__m128i x, __m128i y) { __m128i p = libdivide_mullhi_u64_flat_vector(x, y); __m128i t1 = _mm_and_si128(libdivide_s64_signbits(x), y); p = _mm_sub_epi64(p, t1); __m128i t2 = _mm_and_si128(libdivide_s64_signbits(y), x); p = _mm_sub_epi64(p, t2); return p; } #ifdef LIBDIVIDE_USE_SSE4_1 static inline __m128i libdivide_mullhi_s32_flat_vector(__m128i a, __m128i b) { __m128i hi_product_0Z2Z = _mm_srli_epi64(_mm_mul_epi32(a, b), 32); __m128i a1X3X = _mm_srli_epi64(a, 32); __m128i mask = libdivide_get_FFFFFFFF00000000(); __m128i hi_product_Z1Z3 = _mm_and_si128(_mm_mul_epi32(a1X3X, b), mask); return _mm_or_si128(hi_product_0Z2Z, hi_product_Z1Z3); // = hi_product_0123 } #else static inline __m128i libdivide_mullhi_s32_flat_vector(__m128i a, __m128i b) { __m128i p = libdivide__mullhi_u32_flat_vector(a, b); __m128i t1 = _mm_and_si128(_mm_srai_epi32(a, 31), b); // t1 = (a >> 31) & y, arithmetic shift __m128i t2 = _mm_and_si128(_mm_srai_epi32(b, 31), a); p = _mm_sub_epi32(p, t1); p = _mm_sub_epi32(p, t2); return p; } #endif // LIBDIVIDE_USE_SSE4_1 #endif // LIBDIVIDE_USE_SSE2 static inline int32_t libdivide__count_leading_zeros32(uint32_t val) { #if defined(__GNUC__) || __has_builtin(__builtin_clz) // Fast way to count leading zeros return __builtin_clz(val); #elif defined(LIBDIVIDE_VC) unsigned long result; if (_BitScanReverse(&result, val)) { return 31 - result; } return 0; #else int32_t result = 0; uint32_t hi = 1U << 31; while (~val & hi) { hi >>= 1; result++; } return result; #endif } static inline int32_t libdivide__count_leading_zeros64(uint64_t val) { #if defined(__GNUC__) || __has_builtin(__builtin_clzll) // Fast way to count leading zeros return __builtin_clzll(val); #elif defined(LIBDIVIDE_VC) && defined(_WIN64) unsigned long result; if (_BitScanReverse64(&result, val)) { return 63 - result; } return 0; #else uint32_t hi = val >> 32; uint32_t lo = val & 0xFFFFFFFF; if (hi != 0) return libdivide__count_leading_zeros32(hi); return 32 + libdivide__count_leading_zeros32(lo); #endif } #if (defined(LIBDIVIDE_IS_i386) || defined(LIBDIVIDE_IS_X86_64)) && \ defined(LIBDIVIDE_GCC_STYLE_ASM) static uint32_t libdivide_64_div_32_to_32(uint32_t u1, uint32_t u0, uint32_t v, uint32_t *r) { uint32_t result; __asm__("divl %[v]" : "=a"(result), "=d"(*r) : [v] "r"(v), "a"(u0), "d"(u1) ); return result; } #else static uint32_t libdivide_64_div_32_to_32(uint32_t u1, uint32_t u0, uint32_t v, uint32_t *r) { uint64_t n = (((uint64_t)u1) << 32) | u0; uint32_t result = (uint32_t)(n / v); *r = (uint32_t)(n - result * (uint64_t)v); return result; } #endif #if defined(LIBDIVIDE_IS_X86_64) && \ defined(LIBDIVIDE_GCC_STYLE_ASM) static uint64_t libdivide_128_div_64_to_64(uint64_t u1, uint64_t u0, uint64_t v, uint64_t *r) { // u0 -> rax // u1 -> rdx // divq uint64_t result; __asm__("divq %[v]" : "=a"(result), "=d"(*r) : [v] "r"(v), "a"(u0), "d"(u1) ); return result; } #else static uint64_t libdivide_128_div_64_to_64(uint64_t u1, uint64_t u0, uint64_t v, uint64_t *r) { const uint64_t b = (1ULL << 32); // Number base (16 bits) uint64_t un1, un0; // Norm. dividend LSD's uint64_t vn1, vn0; // Norm. divisor digits uint64_t q1, q0; // Quotient digits uint64_t un64, un21, un10; // Dividend digit pairs uint64_t rhat; // A remainder int32_t s; // Shift amount for norm // If overflow, set rem. to an impossible value, // and return the largest possible quotient if (u1 >= v) { if (r != NULL) *r = (uint64_t) -1; return (uint64_t) -1; } // count leading zeros s = libdivide__count_leading_zeros64(v); if (s > 0) { // Normalize divisor v = v << s; un64 = (u1 << s) | ((u0 >> (64 - s)) & (-s >> 31)); un10 = u0 << s; // Shift dividend left } else { // Avoid undefined behavior un64 = u1 | u0; un10 = u0; } // Break divisor up into two 32-bit digits vn1 = v >> 32; vn0 = v & 0xFFFFFFFF; // Break right half of dividend into two digits un1 = un10 >> 32; un0 = un10 & 0xFFFFFFFF; // Compute the first quotient digit, q1 q1 = un64 / vn1; rhat = un64 - q1 * vn1; while (q1 >= b || q1 * vn0 > b * rhat + un1) { q1 = q1 - 1; rhat = rhat + vn1; if (rhat >= b) break; } // Multiply and subtract un21 = un64 * b + un1 - q1 * v; // Compute the second quotient digit q0 = un21 / vn1; rhat = un21 - q0 * vn1; while (q0 >= b || q0 * vn0 > b * rhat + un0) { q0 = q0 - 1; rhat = rhat + vn1; if (rhat >= b) break; } // If remainder is wanted, return it if (r != NULL) *r = (un21 * b + un0 - q0 * v) >> s; return q1 * b + q0; } #endif static inline void libdivide_u128_shift(uint64_t *u1, uint64_t *u0, int32_t signed_shift) { if (signed_shift > 0) { uint32_t shift = signed_shift; *u1 <<= shift; *u1 |= *u0 >> (64 - shift); *u0 <<= shift; } else { uint32_t shift = -signed_shift; *u0 >>= shift; *u0 |= *u1 << (64 - shift); *u1 >>= shift; } } static uint64_t libdivide_128_div_128_to_64(uint64_t u_hi, uint64_t u_lo, uint64_t v_hi, uint64_t v_lo, uint64_t *r_hi, uint64_t *r_lo) { #if defined(HAS_INT128_T) __uint128_t ufull = u_hi; __uint128_t vfull = v_hi; ufull = (ufull << 64) | u_lo; vfull = (vfull << 64) | v_lo; uint64_t res = (uint64_t)(ufull / vfull); __uint128_t remainder = ufull - (vfull * res); *r_lo = (uint64_t)remainder; *r_hi = (uint64_t)(remainder >> 64); return res; #else // Adapted from "Unsigned Doubleword Division" in Hacker's Delight // We want to compute u / v typedef struct { uint64_t hi; uint64_t lo; } u128_t; u128_t u = {u_hi, u_lo}; u128_t v = {v_hi, v_lo}; if (v.hi == 0) { // divisor v is a 64 bit value, so we just need one 128/64 division // Note that we are simpler than Hacker's Delight here, because we know // the quotient fits in 64 bits whereas Hacker's Delight demands a full // 128 bit quotient *r_hi = 0; return libdivide_128_div_64_to_64(u.hi, u.lo, v.lo, r_lo); } // Here v >= 2**64 // We know that v.hi != 0, so count leading zeros is OK // We have 0 <= n <= 63 uint32_t n = libdivide__count_leading_zeros64(v.hi); // Normalize the divisor so its MSB is 1 u128_t v1t = v; libdivide_u128_shift(&v1t.hi, &v1t.lo, n); uint64_t v1 = v1t.hi; // i.e. v1 = v1t >> 64 // To ensure no overflow u128_t u1 = u; libdivide_u128_shift(&u1.hi, &u1.lo, -1); // Get quotient from divide unsigned insn. uint64_t rem_ignored; uint64_t q1 = libdivide_128_div_64_to_64(u1.hi, u1.lo, v1, &rem_ignored); // Undo normalization and division of u by 2. u128_t q0 = {0, q1}; libdivide_u128_shift(&q0.hi, &q0.lo, n); libdivide_u128_shift(&q0.hi, &q0.lo, -63); // Make q0 correct or too small by 1 // Equivalent to `if (q0 != 0) q0 = q0 - 1;` if (q0.hi != 0 || q0.lo != 0) { q0.hi -= (q0.lo == 0); // borrow q0.lo -= 1; } // Now q0 is correct. // Compute q0 * v as q0v // = (q0.hi << 64 + q0.lo) * (v.hi << 64 + v.lo) // = (q0.hi * v.hi << 128) + (q0.hi * v.lo << 64) + // (q0.lo * v.hi << 64) + q0.lo * v.lo) // Each term is 128 bit // High half of full product (upper 128 bits!) are dropped u128_t q0v = {0, 0}; q0v.hi = q0.hi*v.lo + q0.lo*v.hi + libdivide__mullhi_u64(q0.lo, v.lo); q0v.lo = q0.lo*v.lo; // Compute u - q0v as u_q0v // This is the remainder u128_t u_q0v = u; u_q0v.hi -= q0v.hi + (u.lo < q0v.lo); // second term is borrow u_q0v.lo -= q0v.lo; // Check if u_q0v >= v // This checks if our remainder is larger than the divisor if ((u_q0v.hi > v.hi) || (u_q0v.hi == v.hi && u_q0v.lo >= v.lo)) { // Increment q0 q0.lo += 1; q0.hi += (q0.lo == 0); // carry // Subtract v from remainder u_q0v.hi -= v.hi + (u_q0v.lo < v.lo); u_q0v.lo -= v.lo; } *r_hi = u_q0v.hi; *r_lo = u_q0v.lo; LIBDIVIDE_ASSERT(q0.hi == 0); return q0.lo; #endif } static inline struct libdivide_u32_t libdivide_internal_u32_gen(uint32_t d, int branchfree) { if (d == 0) { LIBDIVIDE_ERROR("divider must be != 0"); } struct libdivide_u32_t result; uint32_t floor_log_2_d = 31 - libdivide__count_leading_zeros32(d); if ((d & (d - 1)) == 0) { // Power of 2 if (! branchfree) { result.magic = 0; result.more = floor_log_2_d | LIBDIVIDE_U32_SHIFT_PATH; } else { // We want a magic number of 2**32 and a shift of floor_log_2_d // but one of the shifts is taken up by LIBDIVIDE_ADD_MARKER, // so we subtract 1 from the shift result.magic = 0; result.more = (floor_log_2_d-1) | LIBDIVIDE_ADD_MARKER; } } else { uint8_t more; uint32_t rem, proposed_m; proposed_m = libdivide_64_div_32_to_32(1U << floor_log_2_d, 0, d, &rem); LIBDIVIDE_ASSERT(rem > 0 && rem < d); const uint32_t e = d - rem; // This power works if e < 2**floor_log_2_d. if (!branchfree && (e < (1U << floor_log_2_d))) { // This power works more = floor_log_2_d; } else { // We have to use the general 33-bit algorithm. We need to compute // (2**power) / d. However, we already have (2**(power-1))/d and // its remainder. By doubling both, and then correcting the // remainder, we can compute the larger division. // don't care about overflow here - in fact, we expect it proposed_m += proposed_m; const uint32_t twice_rem = rem + rem; if (twice_rem >= d || twice_rem < rem) proposed_m += 1; more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; } result.magic = 1 + proposed_m; result.more = more; // result.more's shift should in general be ceil_log_2_d. But if we // used the smaller power, we subtract one from the shift because we're // using the smaller power. If we're using the larger power, we // subtract one from the shift because it's taken care of by the add // indicator. So floor_log_2_d happens to be correct in both cases. } return result; } struct libdivide_u32_t libdivide_u32_gen(uint32_t d) { return libdivide_internal_u32_gen(d, 0); } struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t d) { if (d == 1) { LIBDIVIDE_ERROR("branchfree divider must be != 1"); } struct libdivide_u32_t tmp = libdivide_internal_u32_gen(d, 1); struct libdivide_u32_branchfree_t ret = {tmp.magic, (uint8_t)(tmp.more & LIBDIVIDE_32_SHIFT_MASK)}; return ret; } uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U32_SHIFT_PATH) { return numer >> (more & LIBDIVIDE_32_SHIFT_MASK); } else { uint32_t q = libdivide__mullhi_u32(denom->magic, numer); if (more & LIBDIVIDE_ADD_MARKER) { uint32_t t = ((numer - q) >> 1) + q; return t >> (more & LIBDIVIDE_32_SHIFT_MASK); } else { // all upper bits are 0 - don't need to mask them off return q >> more; } } } uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom) { uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; if (more & LIBDIVIDE_U32_SHIFT_PATH) { return 1U << shift; } else if (!(more & LIBDIVIDE_ADD_MARKER)) { // We compute q = n/d = n*m / 2^(32 + shift) // Therefore we have d = 2^(32 + shift) / m // We need to ceil it. // We know d is not a power of 2, so m is not a power of 2, // so we can just add 1 to the floor uint32_t hi_dividend = 1U << shift; uint32_t rem_ignored; return 1 + libdivide_64_div_32_to_32(hi_dividend, 0, denom->magic, &rem_ignored); } else { // Here we wish to compute d = 2^(32+shift+1)/(m+2^32). // Notice (m + 2^32) is a 33 bit number. Use 64 bit division for now // Also note that shift may be as high as 31, so shift + 1 will // overflow. So we have to compute it as 2^(32+shift)/(m+2^32), and // then double the quotient and remainder. uint64_t half_n = 1ULL << (32 + shift); uint64_t d = (1ULL << 32) | denom->magic; // Note that the quotient is guaranteed <= 32 bits, but the remainder // may need 33! uint32_t half_q = (uint32_t)(half_n / d); uint64_t rem = half_n % d; // We computed 2^(32+shift)/(m+2^32) // Need to double it, and then add 1 to the quotient if doubling th // remainder would increase the quotient. // Note that rem<<1 cannot overflow, since rem < d and d is 33 bits uint32_t full_q = half_q + half_q + ((rem<<1) >= d); // We rounded down in gen unless we're a power of 2 (i.e. in branchfree case) // We can detect that by looking at m. If m zero, we're a power of 2 return full_q + (denom->magic != 0); } } uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom) { struct libdivide_u32_t denom_u32 = {denom->magic, (uint8_t)(denom->more | LIBDIVIDE_ADD_MARKER)}; return libdivide_u32_recover(&denom_u32); } int libdivide_u32_get_algorithm(const struct libdivide_u32_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U32_SHIFT_PATH) return 0; else if (!(more & LIBDIVIDE_ADD_MARKER)) return 1; else return 2; } uint32_t libdivide_u32_do_alg0(uint32_t numer, const struct libdivide_u32_t *denom) { return numer >> (denom->more & LIBDIVIDE_32_SHIFT_MASK); } uint32_t libdivide_u32_do_alg1(uint32_t numer, const struct libdivide_u32_t *denom) { uint32_t q = libdivide__mullhi_u32(denom->magic, numer); return q >> denom->more; } uint32_t libdivide_u32_do_alg2(uint32_t numer, const struct libdivide_u32_t *denom) { // denom->add != 0 uint32_t q = libdivide__mullhi_u32(denom->magic, numer); uint32_t t = ((numer - q) >> 1) + q; // Note that this mask is typically free. Only the low bits are meaningful // to a shift, so compilers can optimize out this AND. return t >> (denom->more & LIBDIVIDE_32_SHIFT_MASK); } uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom) { uint32_t q = libdivide__mullhi_u32(denom->magic, numer); uint32_t t = ((numer - q) >> 1) + q; return t >> denom->more; } #if defined(LIBDIVIDE_USE_SSE2) __m128i libdivide_u32_do_vector(__m128i numers, const struct libdivide_u32_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U32_SHIFT_PATH) { return _mm_srl_epi32(numers, libdivide_u32_to_m128i(more & LIBDIVIDE_32_SHIFT_MASK)); } else { __m128i q = libdivide__mullhi_u32_flat_vector(numers, _mm_set1_epi32(denom->magic)); if (more & LIBDIVIDE_ADD_MARKER) { // uint32_t t = ((numer - q) >> 1) + q; // return t >> denom->shift; __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q); return _mm_srl_epi32(t, libdivide_u32_to_m128i(more & LIBDIVIDE_32_SHIFT_MASK)); } else { // q >> denom->shift return _mm_srl_epi32(q, libdivide_u32_to_m128i(more)); } } } __m128i libdivide_u32_do_vector_alg0(__m128i numers, const struct libdivide_u32_t *denom) { return _mm_srl_epi32(numers, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_32_SHIFT_MASK)); } __m128i libdivide_u32_do_vector_alg1(__m128i numers, const struct libdivide_u32_t *denom) { __m128i q = libdivide__mullhi_u32_flat_vector(numers, _mm_set1_epi32(denom->magic)); return _mm_srl_epi32(q, libdivide_u32_to_m128i(denom->more)); } __m128i libdivide_u32_do_vector_alg2(__m128i numers, const struct libdivide_u32_t *denom) { __m128i q = libdivide__mullhi_u32_flat_vector(numers, _mm_set1_epi32(denom->magic)); __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q); return _mm_srl_epi32(t, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_32_SHIFT_MASK)); } LIBDIVIDE_API __m128i libdivide_u32_branchfree_do_vector(__m128i numers, const struct libdivide_u32_branchfree_t *denom) { __m128i q = libdivide__mullhi_u32_flat_vector(numers, _mm_set1_epi32(denom->magic)); __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_sub_epi32(numers, q), 1), q); return _mm_srl_epi32(t, libdivide_u32_to_m128i(denom->more)); } #endif static inline struct libdivide_u64_t libdivide_internal_u64_gen(uint64_t d, int branchfree) { if (d == 0) { LIBDIVIDE_ERROR("divider must be != 0"); } struct libdivide_u64_t result; uint32_t floor_log_2_d = 63 - libdivide__count_leading_zeros64(d); if ((d & (d - 1)) == 0) { // Power of 2 if (! branchfree) { result.magic = 0; result.more = floor_log_2_d | LIBDIVIDE_U64_SHIFT_PATH; } else { // We want a magic number of 2**64 and a shift of floor_log_2_d // but one of the shifts is taken up by LIBDIVIDE_ADD_MARKER, // so we subtract 1 from the shift result.magic = 0; result.more = (floor_log_2_d-1) | LIBDIVIDE_ADD_MARKER; } } else { uint64_t proposed_m, rem; uint8_t more; // (1 << (64 + floor_log_2_d)) / d proposed_m = libdivide_128_div_64_to_64(1ULL << floor_log_2_d, 0, d, &rem); LIBDIVIDE_ASSERT(rem > 0 && rem < d); const uint64_t e = d - rem; // This power works if e < 2**floor_log_2_d. if (!branchfree && e < (1ULL << floor_log_2_d)) { // This power works more = floor_log_2_d; } else { // We have to use the general 65-bit algorithm. We need to compute // (2**power) / d. However, we already have (2**(power-1))/d and // its remainder. By doubling both, and then correcting the // remainder, we can compute the larger division. // don't care about overflow here - in fact, we expect it proposed_m += proposed_m; const uint64_t twice_rem = rem + rem; if (twice_rem >= d || twice_rem < rem) proposed_m += 1; more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; } result.magic = 1 + proposed_m; result.more = more; // result.more's shift should in general be ceil_log_2_d. But if we // used the smaller power, we subtract one from the shift because we're // using the smaller power. If we're using the larger power, we // subtract one from the shift because it's taken care of by the add // indicator. So floor_log_2_d happens to be correct in both cases, // which is why we do it outside of the if statement. } return result; } struct libdivide_u64_t libdivide_u64_gen(uint64_t d) { return libdivide_internal_u64_gen(d, 0); } struct libdivide_u64_branchfree_t libdivide_u64_branchfree_gen(uint64_t d) { if (d == 1) { LIBDIVIDE_ERROR("branchfree divider must be != 1"); } struct libdivide_u64_t tmp = libdivide_internal_u64_gen(d, 1); struct libdivide_u64_branchfree_t ret = {tmp.magic, (uint8_t)(tmp.more & LIBDIVIDE_64_SHIFT_MASK)}; return ret; } uint64_t libdivide_u64_do(uint64_t numer, const struct libdivide_u64_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U64_SHIFT_PATH) { return numer >> (more & LIBDIVIDE_64_SHIFT_MASK); } else { uint64_t q = libdivide__mullhi_u64(denom->magic, numer); if (more & LIBDIVIDE_ADD_MARKER) { uint64_t t = ((numer - q) >> 1) + q; return t >> (more & LIBDIVIDE_64_SHIFT_MASK); } else { // all upper bits are 0 - don't need to mask them off return q >> more; } } } uint64_t libdivide_u64_recover(const struct libdivide_u64_t *denom) { uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; if (more & LIBDIVIDE_U64_SHIFT_PATH) { return 1ULL << shift; } else if (!(more & LIBDIVIDE_ADD_MARKER)) { // We compute q = n/d = n*m / 2^(64 + shift) // Therefore we have d = 2^(64 + shift) / m // We need to ceil it. // We know d is not a power of 2, so m is not a power of 2, // so we can just add 1 to the floor uint64_t hi_dividend = 1ULL << shift; uint64_t rem_ignored; return 1 + libdivide_128_div_64_to_64(hi_dividend, 0, denom->magic, &rem_ignored); } else { // Here we wish to compute d = 2^(64+shift+1)/(m+2^64). // Notice (m + 2^64) is a 65 bit number. This gets hairy. See // libdivide_u32_recover for more on what we do here. // TODO: do something better than 128 bit math // Hack: if d is not a power of 2, this is a 128/128->64 divide // If d is a power of 2, this may be a bigger divide // However we can optimize that easily if (denom->magic == 0) { // 2^(64 + shift + 1) / (2^64) == 2^(shift + 1) return 1ULL << (shift + 1); } // Full n is a (potentially) 129 bit value // half_n is a 128 bit value // Compute the hi half of half_n. Low half is 0. uint64_t half_n_hi = 1ULL << shift, half_n_lo = 0; // d is a 65 bit value. The high bit is always set to 1. const uint64_t d_hi = 1, d_lo = denom->magic; // Note that the quotient is guaranteed <= 64 bits, // but the remainder may need 65! uint64_t r_hi, r_lo; uint64_t half_q = libdivide_128_div_128_to_64(half_n_hi, half_n_lo, d_hi, d_lo, &r_hi, &r_lo); // We computed 2^(64+shift)/(m+2^64) // Double the remainder ('dr') and check if that is larger than d // Note that d is a 65 bit value, so r1 is small and so r1 + r1 cannot // overflow uint64_t dr_lo = r_lo + r_lo; uint64_t dr_hi = r_hi + r_hi + (dr_lo < r_lo); // last term is carry int dr_exceeds_d = (dr_hi > d_hi) || (dr_hi == d_hi && dr_lo >= d_lo); uint64_t full_q = half_q + half_q + (dr_exceeds_d ? 1 : 0); return full_q + 1; } } uint64_t libdivide_u64_branchfree_recover(const struct libdivide_u64_branchfree_t *denom) { struct libdivide_u64_t denom_u64 = {denom->magic, (uint8_t)(denom->more | LIBDIVIDE_ADD_MARKER)}; return libdivide_u64_recover(&denom_u64); } int libdivide_u64_get_algorithm(const struct libdivide_u64_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U64_SHIFT_PATH) return 0; else if (!(more & LIBDIVIDE_ADD_MARKER)) return 1; else return 2; } uint64_t libdivide_u64_do_alg0(uint64_t numer, const struct libdivide_u64_t *denom) { return numer >> (denom->more & LIBDIVIDE_64_SHIFT_MASK); } uint64_t libdivide_u64_do_alg1(uint64_t numer, const struct libdivide_u64_t *denom) { uint64_t q = libdivide__mullhi_u64(denom->magic, numer); return q >> denom->more; } uint64_t libdivide_u64_do_alg2(uint64_t numer, const struct libdivide_u64_t *denom) { uint64_t q = libdivide__mullhi_u64(denom->magic, numer); uint64_t t = ((numer - q) >> 1) + q; return t >> (denom->more & LIBDIVIDE_64_SHIFT_MASK); } uint64_t libdivide_u64_branchfree_do(uint64_t numer, const struct libdivide_u64_branchfree_t *denom) { uint64_t q = libdivide__mullhi_u64(denom->magic, numer); uint64_t t = ((numer - q) >> 1) + q; return t >> denom->more; } #if defined(LIBDIVIDE_USE_SSE2) __m128i libdivide_u64_do_vector(__m128i numers, const struct libdivide_u64_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_U64_SHIFT_PATH) { return _mm_srl_epi64(numers, libdivide_u32_to_m128i(more & LIBDIVIDE_64_SHIFT_MASK)); } else { __m128i q = libdivide_mullhi_u64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); if (more & LIBDIVIDE_ADD_MARKER) { // uint32_t t = ((numer - q) >> 1) + q; // return t >> denom->shift; __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q); return _mm_srl_epi64(t, libdivide_u32_to_m128i(more & LIBDIVIDE_64_SHIFT_MASK)); } else { // q >> denom->shift return _mm_srl_epi64(q, libdivide_u32_to_m128i(more)); } } } __m128i libdivide_u64_do_vector_alg0(__m128i numers, const struct libdivide_u64_t *denom) { return _mm_srl_epi64(numers, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_64_SHIFT_MASK)); } __m128i libdivide_u64_do_vector_alg1(__m128i numers, const struct libdivide_u64_t *denom) { __m128i q = libdivide_mullhi_u64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); return _mm_srl_epi64(q, libdivide_u32_to_m128i(denom->more)); } __m128i libdivide_u64_do_vector_alg2(__m128i numers, const struct libdivide_u64_t *denom) { __m128i q = libdivide_mullhi_u64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q); return _mm_srl_epi64(t, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_64_SHIFT_MASK)); } __m128i libdivide_u64_branchfree_do_vector(__m128i numers, const struct libdivide_u64_branchfree_t *denom) { __m128i q = libdivide_mullhi_u64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); __m128i t = _mm_add_epi64(_mm_srli_epi64(_mm_sub_epi64(numers, q), 1), q); return _mm_srl_epi64(t, libdivide_u32_to_m128i(denom->more)); } #endif static inline int32_t libdivide__mullhi_s32(int32_t x, int32_t y) { int64_t xl = x, yl = y; int64_t rl = xl * yl; // needs to be arithmetic shift return (int32_t)(rl >> 32); } static inline struct libdivide_s32_t libdivide_internal_s32_gen(int32_t d, int branchfree) { if (d == 0) { LIBDIVIDE_ERROR("divider must be != 0"); } struct libdivide_s32_t result; // If d is a power of 2, or negative a power of 2, we have to use a shift. // This is especially important because the magic algorithm fails for -1. // To check if d is a power of 2 or its inverse, it suffices to check // whether its absolute value has exactly one bit set. This works even for // INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set // and is a power of 2. uint32_t ud = (uint32_t)d; uint32_t absD = (d < 0) ? -ud : ud; uint32_t floor_log_2_d = 31 - libdivide__count_leading_zeros32(absD); // check if exactly one bit is set, // don't care if absD is 0 since that's divide by zero if ((absD & (absD - 1)) == 0) { // Branchfree and normal paths are exactly the same result.magic = 0; result.more = floor_log_2_d | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0) | LIBDIVIDE_S32_SHIFT_PATH; } else { LIBDIVIDE_ASSERT(floor_log_2_d >= 1); uint8_t more; // the dividend here is 2**(floor_log_2_d + 31), so the low 32 bit word // is 0 and the high word is floor_log_2_d - 1 uint32_t rem, proposed_m; proposed_m = libdivide_64_div_32_to_32(1U << (floor_log_2_d - 1), 0, absD, &rem); const uint32_t e = absD - rem; // We are going to start with a power of floor_log_2_d - 1. // This works if works if e < 2**floor_log_2_d. if (!branchfree && e < (1U << floor_log_2_d)) { // This power works more = floor_log_2_d - 1; } else { // We need to go one higher. This should not make proposed_m // overflow, but it will make it negative when interpreted as an // int32_t. proposed_m += proposed_m; const uint32_t twice_rem = rem + rem; if (twice_rem >= absD || twice_rem < rem) proposed_m += 1; more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; } proposed_m += 1; int32_t magic = (int32_t)proposed_m; // Mark if we are negative. Note we only negate the magic number in the // branchfull case. if (d < 0) { more |= LIBDIVIDE_NEGATIVE_DIVISOR; if (!branchfree) { magic = -magic; } } result.more = more; result.magic = magic; } return result; } LIBDIVIDE_API struct libdivide_s32_t libdivide_s32_gen(int32_t d) { return libdivide_internal_s32_gen(d, 0); } LIBDIVIDE_API struct libdivide_s32_branchfree_t libdivide_s32_branchfree_gen(int32_t d) { if (d == 1) { LIBDIVIDE_ERROR("branchfree divider must be != 1"); } if (d == -1) { LIBDIVIDE_ERROR("branchfree divider must be != -1"); } struct libdivide_s32_t tmp = libdivide_internal_s32_gen(d, 1); struct libdivide_s32_branchfree_t result = {tmp.magic, tmp.more}; return result; } int32_t libdivide_s32_do(int32_t numer, const struct libdivide_s32_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_S32_SHIFT_PATH) { uint32_t sign = (int8_t)more >> 7; uint8_t shifter = more & LIBDIVIDE_32_SHIFT_MASK; uint32_t uq = (uint32_t)(numer + ((numer >> 31) & ((1U << shifter) - 1))); int32_t q = (int32_t)uq; q = q >> shifter; q = (q ^ sign) - sign; return q; } else { uint32_t uq = (uint32_t)libdivide__mullhi_s32(denom->magic, numer); if (more & LIBDIVIDE_ADD_MARKER) { // must be arithmetic shift and then sign extend int32_t sign = (int8_t)more >> 7; // q += (more < 0 ? -numer : numer), casts to avoid UB uq += ((uint32_t)numer ^ sign) - sign; } int32_t q = (int32_t)uq; q >>= more & LIBDIVIDE_32_SHIFT_MASK; q += (q < 0); return q; } } int32_t libdivide_s32_branchfree_do(int32_t numer, const struct libdivide_s32_branchfree_t *denom) { uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; // must be arithmetic shift and then sign extend int32_t sign = (int8_t)more >> 7; int32_t magic = denom->magic; int32_t q = libdivide__mullhi_s32(magic, numer); q += numer; // If q is non-negative, we have nothing to do // If q is negative, we want to add either (2**shift)-1 if d is a power of // 2, or (2**shift) if it is not a power of 2 uint32_t is_power_of_2 = !!(more & LIBDIVIDE_S32_SHIFT_PATH); uint32_t q_sign = (uint32_t)(q >> 31); q += q_sign & ((1 << shift) - is_power_of_2); // Now arithmetic right shift q >>= shift; // Negate if needed q = (q ^ sign) - sign; return q; } int32_t libdivide_s32_recover(const struct libdivide_s32_t *denom) { uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; if (more & LIBDIVIDE_S32_SHIFT_PATH) { uint32_t absD = 1U << shift; if (more & LIBDIVIDE_NEGATIVE_DIVISOR) { absD = -absD; } return (int32_t)absD; } else { // Unsigned math is much easier // We negate the magic number only in the branchfull case, and we don't // know which case we're in. However we have enough information to // determine the correct sign of the magic number. The divisor was // negative if LIBDIVIDE_NEGATIVE_DIVISOR is set. If ADD_MARKER is set, // the magic number's sign is opposite that of the divisor. // We want to compute the positive magic number. int negative_divisor = (more & LIBDIVIDE_NEGATIVE_DIVISOR); int magic_was_negated = (more & LIBDIVIDE_ADD_MARKER) ? denom->magic > 0 : denom->magic < 0; // Handle the power of 2 case (including branchfree) if (denom->magic == 0) { int32_t result = 1 << shift; return negative_divisor ? -result : result; } uint32_t d = (uint32_t)(magic_was_negated ? -denom->magic : denom->magic); uint64_t n = 1ULL << (32 + shift); // this shift cannot exceed 30 uint32_t q = (uint32_t)(n / d); int32_t result = (int32_t)q; result += 1; return negative_divisor ? -result : result; } } int32_t libdivide_s32_branchfree_recover(const struct libdivide_s32_branchfree_t *denom) { return libdivide_s32_recover((const struct libdivide_s32_t *)denom); } int libdivide_s32_get_algorithm(const struct libdivide_s32_t *denom) { uint8_t more = denom->more; int positiveDivisor = !(more & LIBDIVIDE_NEGATIVE_DIVISOR); if (more & LIBDIVIDE_S32_SHIFT_PATH) return (positiveDivisor ? 0 : 1); else if (more & LIBDIVIDE_ADD_MARKER) return (positiveDivisor ? 2 : 3); else return 4; } int32_t libdivide_s32_do_alg0(int32_t numer, const struct libdivide_s32_t *denom) { uint8_t shifter = denom->more & LIBDIVIDE_32_SHIFT_MASK; int32_t q = numer + ((numer >> 31) & ((1U << shifter) - 1)); return q >> shifter; } int32_t libdivide_s32_do_alg1(int32_t numer, const struct libdivide_s32_t *denom) { uint8_t shifter = denom->more & LIBDIVIDE_32_SHIFT_MASK; int32_t q = numer + ((numer >> 31) & ((1U << shifter) - 1)); return - (q >> shifter); } int32_t libdivide_s32_do_alg2(int32_t numer, const struct libdivide_s32_t *denom) { int32_t q = libdivide__mullhi_s32(denom->magic, numer); q += numer; q >>= denom->more & LIBDIVIDE_32_SHIFT_MASK; q += (q < 0); return q; } int32_t libdivide_s32_do_alg3(int32_t numer, const struct libdivide_s32_t *denom) { int32_t q = libdivide__mullhi_s32(denom->magic, numer); q -= numer; q >>= denom->more & LIBDIVIDE_32_SHIFT_MASK; q += (q < 0); return q; } int32_t libdivide_s32_do_alg4(int32_t numer, const struct libdivide_s32_t *denom) { int32_t q = libdivide__mullhi_s32(denom->magic, numer); q >>= denom->more & LIBDIVIDE_32_SHIFT_MASK; q += (q < 0); return q; } #if defined(LIBDIVIDE_USE_SSE2) __m128i libdivide_s32_do_vector(__m128i numers, const struct libdivide_s32_t *denom) { uint8_t more = denom->more; if (more & LIBDIVIDE_S32_SHIFT_PATH) { uint32_t shifter = more & LIBDIVIDE_32_SHIFT_MASK; __m128i roundToZeroTweak = _mm_set1_epi32((1U << shifter) - 1); // could use _mm_srli_epi32 with an all -1 register __m128i q = _mm_add_epi32(numers, _mm_and_si128(_mm_srai_epi32(numers, 31), roundToZeroTweak)); //q = numer + ((numer >> 31) & roundToZeroTweak); q = _mm_sra_epi32(q, libdivide_u32_to_m128i(shifter)); // q = q >> shifter __m128i shiftMask = _mm_set1_epi32((int32_t)((int8_t)more >> 7)); // set all bits of shift mask = to the sign bit of more q = _mm_sub_epi32(_mm_xor_si128(q, shiftMask), shiftMask); // q = (q ^ shiftMask) - shiftMask; return q; } else { __m128i q = libdivide_mullhi_s32_flat_vector(numers, _mm_set1_epi32(denom->magic)); if (more & LIBDIVIDE_ADD_MARKER) { __m128i sign = _mm_set1_epi32((int32_t)(int8_t)more >> 7); // must be arithmetic shift q = _mm_add_epi32(q, _mm_sub_epi32(_mm_xor_si128(numers, sign), sign)); // q += ((numer ^ sign) - sign); } q = _mm_sra_epi32(q, libdivide_u32_to_m128i(more & LIBDIVIDE_32_SHIFT_MASK)); // q >>= shift q = _mm_add_epi32(q, _mm_srli_epi32(q, 31)); // q += (q < 0) return q; } } __m128i libdivide_s32_do_vector_alg0(__m128i numers, const struct libdivide_s32_t *denom) { uint8_t shifter = denom->more & LIBDIVIDE_32_SHIFT_MASK; __m128i roundToZeroTweak = _mm_set1_epi32((1U << shifter) - 1); __m128i q = _mm_add_epi32(numers, _mm_and_si128(_mm_srai_epi32(numers, 31), roundToZeroTweak)); return _mm_sra_epi32(q, libdivide_u32_to_m128i(shifter)); } __m128i libdivide_s32_do_vector_alg1(__m128i numers, const struct libdivide_s32_t *denom) { uint8_t shifter = denom->more & LIBDIVIDE_32_SHIFT_MASK; __m128i roundToZeroTweak = _mm_set1_epi32((1U << shifter) - 1); __m128i q = _mm_add_epi32(numers, _mm_and_si128(_mm_srai_epi32(numers, 31), roundToZeroTweak)); return _mm_sub_epi32(_mm_setzero_si128(), _mm_sra_epi32(q, libdivide_u32_to_m128i(shifter))); } __m128i libdivide_s32_do_vector_alg2(__m128i numers, const struct libdivide_s32_t *denom) { __m128i q = libdivide_mullhi_s32_flat_vector(numers, _mm_set1_epi32(denom->magic)); q = _mm_add_epi32(q, numers); q = _mm_sra_epi32(q, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_32_SHIFT_MASK)); q = _mm_add_epi32(q, _mm_srli_epi32(q, 31)); return q; } __m128i libdivide_s32_do_vector_alg3(__m128i numers, const struct libdivide_s32_t *denom) { __m128i q = libdivide_mullhi_s32_flat_vector(numers, _mm_set1_epi32(denom->magic)); q = _mm_sub_epi32(q, numers); q = _mm_sra_epi32(q, libdivide_u32_to_m128i(denom->more & LIBDIVIDE_32_SHIFT_MASK)); q = _mm_add_epi32(q, _mm_srli_epi32(q, 31)); return q; } __m128i libdivide_s32_do_vector_alg4(__m128i numers, const struct libdivide_s32_t *denom) { uint8_t more = denom->more; __m128i q = libdivide_mullhi_s32_flat_vector(numers, _mm_set1_epi32(denom->magic)); q = _mm_sra_epi32(q, libdivide_u32_to_m128i(more & LIBDIVIDE_32_SHIFT_MASK)); //q >>= shift q = _mm_add_epi32(q, _mm_srli_epi32(q, 31)); // q += (q < 0) return q; } __m128i libdivide_s32_branchfree_do_vector(__m128i numers, const struct libdivide_s32_branchfree_t *denom) { int32_t magic = denom->magic; uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK; // must be arithmetic shift __m128i sign = _mm_set1_epi32((int32_t)(int8_t)more >> 7); // libdivide__mullhi_s32(numers, magic); __m128i q = libdivide_mullhi_s32_flat_vector(numers, _mm_set1_epi32(magic)); q = _mm_add_epi32(q, numers); // q += numers // If q is non-negative, we have nothing to do // If q is negative, we want to add either (2**shift)-1 if d is a power of // 2, or (2**shift) if it is not a power of 2 uint32_t is_power_of_2 = (magic == 0); __m128i q_sign = _mm_srai_epi32(q, 31); // q_sign = q >> 31 __m128i mask = _mm_set1_epi32((1 << shift) - is_power_of_2); q = _mm_add_epi32(q, _mm_and_si128(q_sign, mask)); // q = q + (q_sign & mask) q = _mm_srai_epi32(q, shift); //q >>= shift q = _mm_sub_epi32(_mm_xor_si128(q, sign), sign); // q = (q ^ sign) - sign return q; } #endif static inline struct libdivide_s64_t libdivide_internal_s64_gen(int64_t d, int branchfree) { if (d == 0) { LIBDIVIDE_ERROR("divider must be != 0"); } struct libdivide_s64_t result; // If d is a power of 2, or negative a power of 2, we have to use a shift. // This is especially important because the magic algorithm fails for -1. // To check if d is a power of 2 or its inverse, it suffices to check // whether its absolute value has exactly one bit set. This works even for // INT_MIN, because abs(INT_MIN) == INT_MIN, and INT_MIN has one bit set // and is a power of 2. uint64_t ud = (uint64_t)d; uint64_t absD = (d < 0) ? -ud : ud; uint32_t floor_log_2_d = 63 - libdivide__count_leading_zeros64(absD); // check if exactly one bit is set, // don't care if absD is 0 since that's divide by zero if ((absD & (absD - 1)) == 0) { // Branchfree and non-branchfree cases are the same result.magic = 0; result.more = floor_log_2_d | (d < 0 ? LIBDIVIDE_NEGATIVE_DIVISOR : 0); } else { // the dividend here is 2**(floor_log_2_d + 63), so the low 64 bit word // is 0 and the high word is floor_log_2_d - 1 uint8_t more; uint64_t rem, proposed_m; proposed_m = libdivide_128_div_64_to_64(1ULL << (floor_log_2_d - 1), 0, absD, &rem); const uint64_t e = absD - rem; // We are going to start with a power of floor_log_2_d - 1. // This works if works if e < 2**floor_log_2_d. if (!branchfree && e < (1ULL << floor_log_2_d)) { // This power works more = floor_log_2_d - 1; } else { // We need to go one higher. This should not make proposed_m // overflow, but it will make it negative when interpreted as an // int32_t. proposed_m += proposed_m; const uint64_t twice_rem = rem + rem; if (twice_rem >= absD || twice_rem < rem) proposed_m += 1; // note that we only set the LIBDIVIDE_NEGATIVE_DIVISOR bit if we // also set ADD_MARKER this is an annoying optimization that // enables algorithm #4 to avoid the mask. However we always set it // in the branchfree case more = floor_log_2_d | LIBDIVIDE_ADD_MARKER; } proposed_m += 1; int64_t magic = (int64_t)proposed_m; // Mark if we are negative if (d < 0) { more |= LIBDIVIDE_NEGATIVE_DIVISOR; if (!branchfree) { magic = -magic; } } result.more = more; result.magic = magic; } return result; } struct libdivide_s64_t libdivide_s64_gen(int64_t d) { return libdivide_internal_s64_gen(d, 0); } struct libdivide_s64_branchfree_t libdivide_s64_branchfree_gen(int64_t d) { if (d == 1) { LIBDIVIDE_ERROR("branchfree divider must be != 1"); } if (d == -1) { LIBDIVIDE_ERROR("branchfree divider must be != -1"); } struct libdivide_s64_t tmp = libdivide_internal_s64_gen(d, 1); struct libdivide_s64_branchfree_t ret = {tmp.magic, tmp.more}; return ret; } int64_t libdivide_s64_do(int64_t numer, const struct libdivide_s64_t *denom) { uint8_t more = denom->more; int64_t magic = denom->magic; if (magic == 0) { //shift path uint32_t shifter = more & LIBDIVIDE_64_SHIFT_MASK; uint64_t uq = (uint64_t)numer + ((numer >> 63) & ((1ULL << shifter) - 1)); int64_t q = (int64_t)uq; q = q >> shifter; // must be arithmetic shift and then sign-extend int64_t shiftMask = (int8_t)more >> 7; q = (q ^ shiftMask) - shiftMask; return q; } else { uint64_t uq = (uint64_t)libdivide__mullhi_s64(magic, numer); if (more & LIBDIVIDE_ADD_MARKER) { // must be arithmetic shift and then sign extend int64_t sign = (int8_t)more >> 7; uq += ((uint64_t)numer ^ sign) - sign; } int64_t q = (int64_t)uq; q >>= more & LIBDIVIDE_64_SHIFT_MASK; q += (q < 0); return q; } } int64_t libdivide_s64_branchfree_do(int64_t numer, const struct libdivide_s64_branchfree_t *denom) { uint8_t more = denom->more; uint32_t shift = more & LIBDIVIDE_64_SHIFT_MASK; // must be arithmetic shift and then sign extend int64_t sign = (int8_t)more >> 7; int64_t magic = denom->magic; int64_t q = libdivide__mullhi_s64(magic, numer); q += numer; // If q is non-negative, we have nothing to do. // If q is negative, we want to add either (2**shift)-1 if d is a power of // 2, or (2**shift) if it is not a power of 2. uint32_t is_power_of_2 = (magic == 0); uint64_t q_sign = (uint64_t)(q >> 63); q += q_sign & ((1ULL << shift) - is_power_of_2); // Arithmetic right shift q >>= shift; // Negate if needed q = (q ^ sign) - sign; return q; } int64_t libdivide_s64_recover(const struct libdivide_s64_t *denom) { uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; if (denom->magic == 0) { // shift path uint64_t absD = 1ULL << shift; if (more & LIBDIVIDE_NEGATIVE_DIVISOR) { absD = -absD; } return (int64_t)absD; } else { // Unsigned math is much easier int negative_divisor = (more & LIBDIVIDE_NEGATIVE_DIVISOR); int magic_was_negated = (more & LIBDIVIDE_ADD_MARKER) ? denom->magic > 0 : denom->magic < 0; uint64_t d = (uint64_t)(magic_was_negated ? -denom->magic : denom->magic); uint64_t n_hi = 1ULL << shift, n_lo = 0; uint64_t rem_ignored; uint64_t q = libdivide_128_div_64_to_64(n_hi, n_lo, d, &rem_ignored); int64_t result = (int64_t)(q + 1); if (negative_divisor) { result = -result; } return result; } } int64_t libdivide_s64_branchfree_recover(const struct libdivide_s64_branchfree_t *denom) { return libdivide_s64_recover((const struct libdivide_s64_t *)denom); } int libdivide_s64_get_algorithm(const struct libdivide_s64_t *denom) { uint8_t more = denom->more; int positiveDivisor = !(more & LIBDIVIDE_NEGATIVE_DIVISOR); if (denom->magic == 0) return (positiveDivisor ? 0 : 1); // shift path else if (more & LIBDIVIDE_ADD_MARKER) return (positiveDivisor ? 2 : 3); else return 4; } int64_t libdivide_s64_do_alg0(int64_t numer, const struct libdivide_s64_t *denom) { uint32_t shifter = denom->more & LIBDIVIDE_64_SHIFT_MASK; int64_t q = numer + ((numer >> 63) & ((1ULL << shifter) - 1)); return q >> shifter; } int64_t libdivide_s64_do_alg1(int64_t numer, const struct libdivide_s64_t *denom) { // denom->shifter != -1 && demo->shiftMask != 0 uint32_t shifter = denom->more & LIBDIVIDE_64_SHIFT_MASK; int64_t q = numer + ((numer >> 63) & ((1ULL << shifter) - 1)); return - (q >> shifter); } int64_t libdivide_s64_do_alg2(int64_t numer, const struct libdivide_s64_t *denom) { int64_t q = libdivide__mullhi_s64(denom->magic, numer); q += numer; q >>= denom->more & LIBDIVIDE_64_SHIFT_MASK; q += (q < 0); return q; } int64_t libdivide_s64_do_alg3(int64_t numer, const struct libdivide_s64_t *denom) { int64_t q = libdivide__mullhi_s64(denom->magic, numer); q -= numer; q >>= denom->more & LIBDIVIDE_64_SHIFT_MASK; q += (q < 0); return q; } int64_t libdivide_s64_do_alg4(int64_t numer, const struct libdivide_s64_t *denom) { int64_t q = libdivide__mullhi_s64(denom->magic, numer); q >>= denom->more & LIBDIVIDE_64_SHIFT_MASK; q += (q < 0); return q; } #if defined(LIBDIVIDE_USE_SSE2) __m128i libdivide_s64_do_vector(__m128i numers, const struct libdivide_s64_t *denom) { uint8_t more = denom->more; int64_t magic = denom->magic; if (magic == 0) { // shift path uint32_t shifter = more & LIBDIVIDE_64_SHIFT_MASK; __m128i roundToZeroTweak = libdivide__u64_to_m128((1ULL << shifter) - 1); __m128i q = _mm_add_epi64(numers, _mm_and_si128(libdivide_s64_signbits(numers), roundToZeroTweak)); // q = numer + ((numer >> 63) & roundToZeroTweak); q = libdivide_s64_shift_right_vector(q, shifter); // q = q >> shifter __m128i shiftMask = _mm_set1_epi32((int32_t)((int8_t)more >> 7)); q = _mm_sub_epi64(_mm_xor_si128(q, shiftMask), shiftMask); // q = (q ^ shiftMask) - shiftMask; return q; } else { __m128i q = libdivide_mullhi_s64_flat_vector(numers, libdivide__u64_to_m128(magic)); if (more & LIBDIVIDE_ADD_MARKER) { __m128i sign = _mm_set1_epi32((int32_t)((int8_t)more >> 7)); // must be arithmetic shift q = _mm_add_epi64(q, _mm_sub_epi64(_mm_xor_si128(numers, sign), sign)); // q += ((numer ^ sign) - sign); } // q >>= denom->mult_path.shift q = libdivide_s64_shift_right_vector(q, more & LIBDIVIDE_64_SHIFT_MASK); q = _mm_add_epi64(q, _mm_srli_epi64(q, 63)); // q += (q < 0) return q; } } __m128i libdivide_s64_do_vector_alg0(__m128i numers, const struct libdivide_s64_t *denom) { uint32_t shifter = denom->more & LIBDIVIDE_64_SHIFT_MASK; __m128i roundToZeroTweak = libdivide__u64_to_m128((1ULL << shifter) - 1); __m128i q = _mm_add_epi64(numers, _mm_and_si128(libdivide_s64_signbits(numers), roundToZeroTweak)); q = libdivide_s64_shift_right_vector(q, shifter); return q; } __m128i libdivide_s64_do_vector_alg1(__m128i numers, const struct libdivide_s64_t *denom) { uint32_t shifter = denom->more & LIBDIVIDE_64_SHIFT_MASK; __m128i roundToZeroTweak = libdivide__u64_to_m128((1ULL << shifter) - 1); __m128i q = _mm_add_epi64(numers, _mm_and_si128(libdivide_s64_signbits(numers), roundToZeroTweak)); q = libdivide_s64_shift_right_vector(q, shifter); return _mm_sub_epi64(_mm_setzero_si128(), q); } __m128i libdivide_s64_do_vector_alg2(__m128i numers, const struct libdivide_s64_t *denom) { __m128i q = libdivide_mullhi_s64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); q = _mm_add_epi64(q, numers); q = libdivide_s64_shift_right_vector(q, denom->more & LIBDIVIDE_64_SHIFT_MASK); q = _mm_add_epi64(q, _mm_srli_epi64(q, 63)); // q += (q < 0) return q; } __m128i libdivide_s64_do_vector_alg3(__m128i numers, const struct libdivide_s64_t *denom) { __m128i q = libdivide_mullhi_s64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); q = _mm_sub_epi64(q, numers); q = libdivide_s64_shift_right_vector(q, denom->more & LIBDIVIDE_64_SHIFT_MASK); q = _mm_add_epi64(q, _mm_srli_epi64(q, 63)); // q += (q < 0) return q; } __m128i libdivide_s64_do_vector_alg4(__m128i numers, const struct libdivide_s64_t *denom) { __m128i q = libdivide_mullhi_s64_flat_vector(numers, libdivide__u64_to_m128(denom->magic)); q = libdivide_s64_shift_right_vector(q, denom->more & LIBDIVIDE_64_SHIFT_MASK); q = _mm_add_epi64(q, _mm_srli_epi64(q, 63)); return q; } __m128i libdivide_s64_branchfree_do_vector(__m128i numers, const struct libdivide_s64_branchfree_t *denom) { int64_t magic = denom->magic; uint8_t more = denom->more; uint8_t shift = more & LIBDIVIDE_64_SHIFT_MASK; // must be arithmetic shift __m128i sign = _mm_set1_epi32((int32_t)(int8_t)more >> 7); // libdivide__mullhi_s64(numers, magic); __m128i q = libdivide_mullhi_s64_flat_vector(numers, libdivide__u64_to_m128(magic)); q = _mm_add_epi64(q, numers); // q += numers // If q is non-negative, we have nothing to do. // If q is negative, we want to add either (2**shift)-1 if d is a power of // 2, or (2**shift) if it is not a power of 2. uint32_t is_power_of_2 = (magic == 0); __m128i q_sign = libdivide_s64_signbits(q); // q_sign = q >> 63 __m128i mask = libdivide__u64_to_m128((1ULL << shift) - is_power_of_2); q = _mm_add_epi64(q, _mm_and_si128(q_sign, mask)); // q = q + (q_sign & mask) q = libdivide_s64_shift_right_vector(q, shift); // q >>= shift q = _mm_sub_epi64(_mm_xor_si128(q, sign), sign); // q = (q ^ sign) - sign return q; } #endif #ifdef __cplusplus enum { BRANCHFULL = -1, BRANCHFREE = -2, ALGORITHM0 = 0, ALGORITHM1 = 1, ALGORITHM2 = 2, ALGORITHM3 = 3, ALGORITHM4 = 4 }; namespace libdivide_internal { #if defined(LIBDIVIDE_USE_SSE2) #define MAYBE_VECTOR(X) X #define MAYBE_VECTOR_PARAM(X) __m128i vector_func(__m128i, const X *) #else #define MAYBE_VECTOR(X) 0 #define MAYBE_VECTOR_PARAM(X) int unused #endif #define BRANCHFULL_DIVIDER(INT, TYPE) \ typedef base<INT, \ libdivide_##TYPE##_t, \ libdivide_##TYPE##_gen, \ libdivide_##TYPE##_do, \ MAYBE_VECTOR(libdivide_##TYPE##_do_vector)> #define BRANCHFREE_DIVIDER(INT, TYPE) \ typedef base<INT, \ libdivide_##TYPE##_branchfree_t, \ libdivide_##TYPE##_branchfree_gen, \ libdivide_##TYPE##_branchfree_do, \ MAYBE_VECTOR(libdivide_##TYPE##_branchfree_do_vector)> #define ALGORITHM_DIVIDER(INT, TYPE, ALGO) \ typedef base<INT, \ libdivide_##TYPE##_t, \ libdivide_##TYPE##_gen, \ libdivide_##TYPE##_do_##ALGO, \ MAYBE_VECTOR(libdivide_##TYPE##_do_vector_##ALGO)> #define CRASH_DIVIDER(INT, TYPE) \ typedef base<INT, \ libdivide_##TYPE##_t, \ libdivide_##TYPE##_gen, \ libdivide_##TYPE##_crash, \ MAYBE_VECTOR(libdivide_##TYPE##_crash_vector)> // Base divider, provides storage for the actual divider. // @IntType: e.g. uint32_t // @DenomType: e.g. libdivide_u32_t // @gen_func(): e.g. libdivide_u32_gen // @do_func(): e.g. libdivide_u32_do // @MAYBE_VECTOR_PARAM: e.g. libdivide_u32_do_vector template<typename IntType, typename DenomType, DenomType gen_func(IntType), IntType do_func(IntType, const DenomType *), MAYBE_VECTOR_PARAM(DenomType)> struct base { // Storage for the actual divider DenomType denom; // Constructor that takes a divisor value, and applies the gen function base(IntType d) : denom(gen_func(d)) { } // Default constructor to allow uninitialized uses in e.g. arrays base() {} // Needed for unswitch base(const DenomType& d) : denom(d) { } IntType perform_divide(IntType val) const { return do_func(val, &denom); } #if defined(LIBDIVIDE_USE_SSE2) __m128i perform_divide_vector(__m128i val) const { return vector_func(val, &denom); } #endif }; // Functions that will never be called but are required to be able // to use unswitch in C++ template code. Unsigned has fewer algorithms // than signed i.e. alg3 and alg4 are not defined for unsigned. In // order to make templates compile we need to define unsigned alg3 and // alg4 as crash functions. uint32_t libdivide_u32_crash(uint32_t, const libdivide_u32_t *) { exit(-1); } uint64_t libdivide_u64_crash(uint64_t, const libdivide_u64_t *) { exit(-1); } #if defined(LIBDIVIDE_USE_SSE2) __m128i libdivide_u32_crash_vector(__m128i, const libdivide_u32_t *) { exit(-1); } __m128i libdivide_u64_crash_vector(__m128i, const libdivide_u64_t *) { exit(-1); } #endif template<typename T, int ALGO> struct dispatcher { }; // Templated dispatch using partial specialization template<> struct dispatcher<int32_t, BRANCHFULL> { BRANCHFULL_DIVIDER(int32_t, s32) divider; }; template<> struct dispatcher<int32_t, BRANCHFREE> { BRANCHFREE_DIVIDER(int32_t, s32) divider; }; template<> struct dispatcher<int32_t, ALGORITHM0> { ALGORITHM_DIVIDER(int32_t, s32, alg0) divider; }; template<> struct dispatcher<int32_t, ALGORITHM1> { ALGORITHM_DIVIDER(int32_t, s32, alg1) divider; }; template<> struct dispatcher<int32_t, ALGORITHM2> { ALGORITHM_DIVIDER(int32_t, s32, alg2) divider; }; template<> struct dispatcher<int32_t, ALGORITHM3> { ALGORITHM_DIVIDER(int32_t, s32, alg3) divider; }; template<> struct dispatcher<int32_t, ALGORITHM4> { ALGORITHM_DIVIDER(int32_t, s32, alg4) divider; }; template<> struct dispatcher<uint32_t, BRANCHFULL> { BRANCHFULL_DIVIDER(uint32_t, u32) divider; }; template<> struct dispatcher<uint32_t, BRANCHFREE> { BRANCHFREE_DIVIDER(uint32_t, u32) divider; }; template<> struct dispatcher<uint32_t, ALGORITHM0> { ALGORITHM_DIVIDER(uint32_t, u32, alg0) divider; }; template<> struct dispatcher<uint32_t, ALGORITHM1> { ALGORITHM_DIVIDER(uint32_t, u32, alg1) divider; }; template<> struct dispatcher<uint32_t, ALGORITHM2> { ALGORITHM_DIVIDER(uint32_t, u32, alg2) divider; }; template<> struct dispatcher<uint32_t, ALGORITHM3> { CRASH_DIVIDER(uint32_t, u32) divider; }; template<> struct dispatcher<uint32_t, ALGORITHM4> { CRASH_DIVIDER(uint32_t, u32) divider; }; template<> struct dispatcher<int64_t, BRANCHFULL> { BRANCHFULL_DIVIDER(int64_t, s64) divider; }; template<> struct dispatcher<int64_t, BRANCHFREE> { BRANCHFREE_DIVIDER(int64_t, s64) divider; }; template<> struct dispatcher<int64_t, ALGORITHM0> { ALGORITHM_DIVIDER (int64_t, s64, alg0) divider; }; template<> struct dispatcher<int64_t, ALGORITHM1> { ALGORITHM_DIVIDER (int64_t, s64, alg1) divider; }; template<> struct dispatcher<int64_t, ALGORITHM2> { ALGORITHM_DIVIDER (int64_t, s64, alg2) divider; }; template<> struct dispatcher<int64_t, ALGORITHM3> { ALGORITHM_DIVIDER (int64_t, s64, alg3) divider; }; template<> struct dispatcher<int64_t, ALGORITHM4> { ALGORITHM_DIVIDER (int64_t, s64, alg4) divider; }; template<> struct dispatcher<uint64_t, BRANCHFULL> { BRANCHFULL_DIVIDER(uint64_t, u64) divider; }; template<> struct dispatcher<uint64_t, BRANCHFREE> { BRANCHFREE_DIVIDER(uint64_t, u64) divider; }; template<> struct dispatcher<uint64_t, ALGORITHM0> { ALGORITHM_DIVIDER(uint64_t, u64, alg0) divider; }; template<> struct dispatcher<uint64_t, ALGORITHM1> { ALGORITHM_DIVIDER(uint64_t, u64, alg1) divider; }; template<> struct dispatcher<uint64_t, ALGORITHM2> { ALGORITHM_DIVIDER(uint64_t, u64, alg2) divider; }; template<> struct dispatcher<uint64_t, ALGORITHM3> { CRASH_DIVIDER(uint64_t, u64) divider; }; template<> struct dispatcher<uint64_t, ALGORITHM4> { CRASH_DIVIDER(uint64_t, u64) divider; }; // Overloads that don't depend on the algorithm inline int32_t recover(const libdivide_s32_t *s) { return libdivide_s32_recover(s); } inline uint32_t recover(const libdivide_u32_t *s) { return libdivide_u32_recover(s); } inline int64_t recover(const libdivide_s64_t *s) { return libdivide_s64_recover(s); } inline uint64_t recover(const libdivide_u64_t *s) { return libdivide_u64_recover(s); } inline int32_t recover(const libdivide_s32_branchfree_t *s) { return libdivide_s32_branchfree_recover(s); } inline uint32_t recover(const libdivide_u32_branchfree_t *s) { return libdivide_u32_branchfree_recover(s); } inline int64_t recover(const libdivide_s64_branchfree_t *s) { return libdivide_s64_branchfree_recover(s); } inline uint64_t recover(const libdivide_u64_branchfree_t *s) { return libdivide_u64_branchfree_recover(s); } inline int get_algorithm(const libdivide_s32_t *s) { return libdivide_s32_get_algorithm(s); } inline int get_algorithm(const libdivide_u32_t *s) { return libdivide_u32_get_algorithm(s); } inline int get_algorithm(const libdivide_s64_t *s) { return libdivide_s64_get_algorithm(s); } inline int get_algorithm(const libdivide_u64_t *s) { return libdivide_u64_get_algorithm(s); } // Fallback for branchfree variants, which do not support unswitching template<typename T> int get_algorithm(const T *) { return -1; } } template<typename T, int ALGO = BRANCHFULL> class divider { private: // Here's the actual divider typedef typename libdivide_internal::dispatcher<T, ALGO>::divider div_t; div_t div; // unswitch() friend declaration template<int NEW_ALGO, typename S> friend divider<S, NEW_ALGO> unswitch(const divider<S, BRANCHFULL> & d); // Constructor used by the unswitch friend divider(const div_t& denom) : div(denom) { } public: // Ordinary constructor that takes the divisor as a parameter divider(T n) : div(n) { } // Default constructor. We leave this deliberately undefined so that // creating an array of divider and then initializing them // doesn't slow us down. divider() { } // Divides the parameter by the divisor, returning the quotient T perform_divide(T val) const { return div.perform_divide(val); } // Recovers the divisor that was used to initialize the divider T recover_divisor() const { return libdivide_internal::recover(&div.denom); } #if defined(LIBDIVIDE_USE_SSE2) // Treats the vector as either two or four packed values (depending on the // size), and divides each of them by the divisor, // returning the packed quotients. __m128i perform_divide_vector(__m128i val) const { return div.perform_divide_vector(val); } #endif // Returns the index of algorithm, for use in the unswitch function. Does // not apply to branchfree variant. // Returns the algorithm for unswitching. int get_algorithm() const { return libdivide_internal::get_algorithm(&div.denom); } bool operator==(const divider<T, ALGO>& him) const { return div.denom.magic == him.div.denom.magic && div.denom.more == him.div.denom.more; } bool operator!=(const divider<T, ALGO>& him) const { return !(*this == him); } }; #if __cplusplus >= 201103L || \ (defined(_MSC_VER) && _MSC_VER >= 1800) template <typename T> using branchfree_divider = divider<T, BRANCHFREE>; #endif template<int NEW_ALGO, typename T> divider<T, NEW_ALGO> unswitch(const divider<T, BRANCHFULL>& d) { return divider<T, NEW_ALGO>(d.div.denom); } template<typename int_type, int ALGO> int_type operator/(int_type numer, const divider<int_type, ALGO>& denom) { return denom.perform_divide(numer); } template<typename int_type, int ALGO> int_type operator/=(int_type& numer, const divider<int_type, ALGO>& denom) { numer = denom.perform_divide(numer); return numer; } #if defined(LIBDIVIDE_USE_SSE2) template<typename int_type, int ALGO> __m128i operator/(__m128i numer, const divider<int_type, ALGO>& denom) { return denom.perform_divide_vector(numer); } template<typename int_type, int ALGO> __m128i operator/=(__m128i& numer, const divider<int_type, ALGO>& denom) { numer = denom.perform_divide_vector(numer); return numer; } #endif } // namespace libdivide } // anonymous namespace #endif // __cplusplus #endif // LIBDIVIDE_H #ifndef LOCAL #pragma GCC optimize ("O3") #endif #include <bits/stdc++.h> #include "message.h" using namespace std; #define sim template < class c #define ris return * this #define dor > debug & operator << #define eni(x) sim > typename \ enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) { sim > struct rge { c b, e; }; sim > rge<c> range(c i, c j) { return {i, j}; } sim > auto dud(c* x) -> decltype(cerr << *x, 0); sim > char dud(...); struct debug { #ifdef LOCAL ~debug() { cerr << endl; } eni(!=) cerr << boolalpha << i; ris; } eni(==) ris << range(begin(i), end(i)); } sim, class b dor(pair < b, c > d) { ris << "(" << d.first << ", " << d.second << ")"; } sim dor(rge<c> d) { *this << "["; for (c it = d.b; it != d.e; ++it) *this << ", " + 2 * (it == d.b) << *it; ris << "]"; } #else sim dor(const c&) { ris; } #endif }; #define imie(x...) " [" #x ": " << (x) << "] " #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> template <typename A, typename B> using unordered_map2 = __gnu_pbds::gp_hash_table<A, B>; using namespace __gnu_pbds; template <typename T> using ordered_set = __gnu_pbds::tree<T, __gnu_pbds::null_type, less<T>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update>; using ld = long double; using ll = long long; int mod = 1000 * 1000 * 1000 + 7; libdivide::libdivide_u64_t fast_mod; int Moduluj(uint64_t x) { return x - mod * libdivide::libdivide_u64_do(x, &fast_mod); } void OdejmijOd(int& a, int b) { a -= b; if (a < 0) a += mod; } int Odejmij(int a, int b) { OdejmijOd(a, b); return a; } void DodajDo(int& a, int b) { a += b; if (a >= mod) a -= mod; } int Dodaj(int a, int b) { DodajDo(a, b); return a; } int Mnoz(int a, int b) { return Moduluj((ll) a * b); } void MnozDo(int& a, int b) { a = Mnoz(a, b); } int Pot(int a, ll b) { int res = 1; while (b) { if (b % 2 == 1) MnozDo(res, a); a = Mnoz(a, a); b /= 2; } return res; } int Odw(int a) { if (a == 0) return 0; return Pot(a, mod - 2); } void PodzielDo(int& a, int b) { MnozDo(a, Odw(b)); } int Podziel(int a, int b) { return Mnoz(a, Odw(b)); } template <typename T> T Maxi(T& a, T b) { return a = max(a, b); } template <typename T> T Mini(T& a, T b) { return a = min(a, b); } template <typename T> typename make_signed<T>::type ToSigned(T t) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-compare" using ST = typename make_signed<T>::type; if (t <= numeric_limits<ST>::max()) { return static_cast<ST>(t); } else if (t >= numeric_limits<ST>::min()) { return static_cast<ST>(t - numeric_limits<ST>::min()) + numeric_limits<ST>::min(); } else { abort(); } #pragma GCC diagnostic pop } using LengthType = uint32_t; class SendMessage; namespace SendMessageInternal { template <typename T> struct __Helper { static void Put(SendMessage& sm, const T& t); }; #define SM_SIMPLE_TYPE(type) \ template <> \ struct __Helper<type> { \ static void Put(SendMessage& sm, const type& t); \ }; SM_SIMPLE_TYPE(bool); SM_SIMPLE_TYPE(char); SM_SIMPLE_TYPE(signed char); SM_SIMPLE_TYPE(unsigned char); SM_SIMPLE_TYPE(signed int); SM_SIMPLE_TYPE(unsigned int); SM_SIMPLE_TYPE(signed long); SM_SIMPLE_TYPE(unsigned long); SM_SIMPLE_TYPE(signed long long); SM_SIMPLE_TYPE(unsigned long long); #undef SM_SIMPLE_TYPE template <typename A, typename B> struct __Helper<pair<A, B>> { static void Put(SendMessage& sm, const pair<A, B>& p); }; template <typename T> struct __Helper<rge<T>> { static void Put(SendMessage& sm, const rge<T>& d); }; } // namespace SendMessageInternal class SendMessage { private: int id_; bool is_sent_; static int nodes_; static int nodes(); template <typename T> using CleanT = typename remove_reference<typename remove_cv<T>::type>::type; public: SendMessage(int target) : id_(target), is_sent_(false) { assert(0 <= id_ and id_ < nodes()); } ~SendMessage() { if (!is_sent_) { Send(); } } int id() const { return id_; } template <typename T> SendMessage& Put(const T& t) { SendMessageInternal::__Helper<CleanT<T>>::Put(*this, t); return *this; } void Send() { assert(!is_sent_); is_sent_ = true; ::Send(id_); } }; int SendMessage::nodes_ = -1; int SendMessage::nodes() { if (nodes_ == -1) nodes_ = NumberOfNodes(); return nodes_; } namespace SendMessageInternal { template <typename T> void __PutResolver(SendMessage& sm, const T& t) {} template <typename T, typename Ptr1, typename ...Ptrs> void __PutResolver(SendMessage& sm, const T& t, Ptr1 ptr1, Ptrs ...ptrs) { sm.Put(t.*ptr1); __PutResolver(sm, t, ptrs...); } template <typename T> void __Helper<T>::Put(SendMessage& sm, const T& t) { sm.Put(range(begin(t), end(t))); } #define SM_SIMPLE_TYPE(type, func1, func2) \ void __Helper<type>::Put(SendMessage& sm, const type& t) { \ func2(sm.id(), func1(t)); \ } SM_SIMPLE_TYPE(bool, static_cast<char>, PutChar); SM_SIMPLE_TYPE(char, , PutChar); SM_SIMPLE_TYPE(signed char, , PutChar); SM_SIMPLE_TYPE(unsigned char, , PutChar); SM_SIMPLE_TYPE(signed int, , PutInt); SM_SIMPLE_TYPE(unsigned int, ToSigned, PutInt); SM_SIMPLE_TYPE(signed long, , PutLL); SM_SIMPLE_TYPE(unsigned long, ToSigned, PutLL); SM_SIMPLE_TYPE(signed long long, , PutLL); SM_SIMPLE_TYPE(unsigned long long, ToSigned, PutLL); #undef SM_SIMPLE_TYPE template <typename A, typename B> void __Helper<pair<A, B>>::Put(SendMessage& sm, const pair<A, B>& p) { sm.Put(p.first); sm.Put(p.second); } template <typename T> void __Helper<rge<T>>::Put(SendMessage& sm, const rge<T>& d) { sm.Put(static_cast<LengthType>(distance(d.b, d.e))); for (T it = d.b; it != d.e; ++it) { sm.Put(*it); } } } // namespace SendMessageInternal class ReceiveMessage; namespace ReceiveMessageInternal { template <typename T> struct __Helper { static T Get(ReceiveMessage& rm); }; #define RM_SIMPLE_TYPE(type) \ template <> \ struct __Helper<type> { \ static type Get(ReceiveMessage& rm); \ } RM_SIMPLE_TYPE(bool); RM_SIMPLE_TYPE(char); RM_SIMPLE_TYPE(signed char); RM_SIMPLE_TYPE(unsigned char); RM_SIMPLE_TYPE(signed int); RM_SIMPLE_TYPE(unsigned int); RM_SIMPLE_TYPE(signed long); RM_SIMPLE_TYPE(unsigned long); RM_SIMPLE_TYPE(signed long long); RM_SIMPLE_TYPE(unsigned long long); #undef RM_SIMPLE_TYPE template <typename A, typename B> struct __Helper<pair<A, B>> { static pair<A, B> Get(ReceiveMessage& rm); }; } // namespace ReceiveMessageInternal class ReceiveMessage { private: int id_; static int nodes_; static int nodes(); template <typename T> using CleanT = typename remove_reference<typename remove_cv<T>::type>::type; public: int id() const { return id_; } ReceiveMessage(int source) : id_(source) { assert(-1 <= id_ and id_ < nodes()); id_ = Receive(id_); assert(0 <= id_ and id_ < nodes()); } template <typename T> CleanT<T> Get() { return ReceiveMessageInternal::__Helper<CleanT<T>>::Get(*this); } }; int ReceiveMessage::nodes_ = -1; int ReceiveMessage::nodes() { if (nodes_ == -1) nodes_ = NumberOfNodes(); return nodes_; } namespace ReceiveMessageInternal { template <typename T> void __GetResolver(ReceiveMessage& rm, T& t) {} template <typename T, typename Ptr1, typename ...Ptrs> void __GetResolver(ReceiveMessage& rm, T& t, Ptr1 ptr1, Ptrs ...ptrs) { t.*ptr1 = rm.Get<decltype(t.*ptr1)>(); __GetResolver(rm, t, ptrs...); } template <typename T> T __Helper<T>::Get(ReceiveMessage& rm) { T t; auto it = inserter(t, end(t)); const LengthType len = rm.Get<LengthType>(); for (LengthType i = 0; i < len; i++) { *it = rm.Get<typename T::value_type>(); } return t; } #define RM_SIMPLE_TYPE(type, func1, func2) \ type __Helper<type>::Get(ReceiveMessage& rm) { \ return func1(func2(rm.id())); \ } RM_SIMPLE_TYPE(bool, static_cast<char>, GetChar); RM_SIMPLE_TYPE(char, , GetChar); RM_SIMPLE_TYPE(signed char, ToSigned, GetChar); RM_SIMPLE_TYPE(unsigned char, , GetChar); RM_SIMPLE_TYPE(signed int, , GetInt); RM_SIMPLE_TYPE(unsigned int, , GetInt); RM_SIMPLE_TYPE(signed long, , GetLL); RM_SIMPLE_TYPE(unsigned long, , GetLL); RM_SIMPLE_TYPE(signed long long, , GetLL); RM_SIMPLE_TYPE(unsigned long long, , GetLL); #undef RM_SIMPLE_TYPE template <typename A, typename B> pair<A, B> __Helper<pair<A, B>>::Get(ReceiveMessage& rm) { A a = rm.Get<A>(); B b = rm.Get<B>(); return {a, b}; } } // namespace ReceiveMessageInternal #define REGISTER_MESSAGE(type, fields...) \ namespace SendMessageInternal { \ template <> \ struct __Helper<type> { \ static void Put(SendMessage& sm, const type& d) { \ __PutResolver(sm, d, fields); \ } \ }; \ } \ namespace ReceiveMessageInternal { \ template <> \ struct __Helper<type> { \ static type Get(ReceiveMessage& rm) { \ type t; \ __GetResolver(rm, t, fields); \ return t; \ } \ }; \ } #define REGISTER_MESSAGE_CLASS(type, mclass) \ namespace SendMessageInternal { \ template <> struct __Helper<type> : public mclass {}; \ } \ namespace ReceiveMessageInternal { \ template <> struct __Helper<type> : public mclass {}; \ } template <typename T> class Range { private: T a_, b_; public: Range() : Range(T(1), T(0)) {} Range(T a, T b) : a_(a), b_(b) {} Range GetPart(int i, int n) const { assert(0 <= i and i < n); const T len = length(); const T part = len / n; const int ile_duzych = len % n; auto PartBeginning = [this, part, ile_duzych, n](int j) -> T { return a_ + j * part + min(ile_duzych, j); }; return Range(PartBeginning(i), PartBeginning(i + 1) - 1); } vector<Range> Divide(int n) const { assert(0 < n); vector<Range> res(n); for (int i = 0; i < n; i++) { res[i] = GetPart(i, n); } return res; } T a() const { return a_; } T b() const { return b_; } bool empty() const { return a_ > b_; } const T length() const { if (empty()) return 0; else return b_ - a_ + 1; } Range& operator&=(const Range& r) { Maxi(a_, r.a_); Mini(b_, r.b_); return *this; } Range operator&(const Range& r) const { return Range(*this) &= r; } friend debug& operator<<(debug& deb, const Range& r) { if (r.empty()) return deb << "[empty]"; else return deb << "[" << r.a() << ", " << r.b() << "]"; } }; template <typename T> struct RangeMessageHelper { static void Put(SendMessage& sm, const Range<T>& r) { sm.Put(r.a()).Put(r.b()); } static Range<T> Get(ReceiveMessage& rm) { const int a = rm.Get<int>(); const int b = rm.Get<int>(); return Range<T>(a, b); } }; REGISTER_MESSAGE_CLASS(Range<int>, RangeMessageHelper<int>); REGISTER_MESSAGE_CLASS(Range<ll>, RangeMessageHelper<ll>); namespace Fft { /* Prec. error max_ans/1e15 (2.5e18) for (long) doubles, so int rounding works for doubles with answers 0.5e15, e.g. for sizes 2^20 and RANDOM ints in [0,45k], assuming DBL_MANT_DIG=53 and LDBL_MANT_DIG=64. Consider normalizing and brute.*/ #define REP(i,n) for(int i = 0; i < int(n); ++i) typedef double ld; // 'long double' is 2.2 times slower struct C { ld real, imag; C operator * (const C & he) const { return C{real * he.real - imag * he.imag, real * he.imag + imag * he.real}; } void operator += (const C & he) { real += he.real; imag += he.imag; } }; void dft(vector<C> & a, bool rev) { const int n = a.size(); for(int i = 1, k = 0; i < n; ++i) { for(int bit = n / 2; (k ^= bit) < bit; bit /= 2);;; if(i < k) swap(a[i], a[k]); } for(int len = 1, who = 0; len < n; len *= 2, ++who) { static vector<C> t[30]; vector<C> & om = t[who]; if(om.empty()) { om.resize(len); const ld ang = 2 * acosl(0) / len; REP(i, len) om[i] = i%2 || !who ? C{cos(i*ang), sin(i*ang)} : t[who-1][i/2]; } for(int i = 0; i < n; i += 2 * len) REP(k, len) { const C x = a[i+k], y = a[i+k+len] * C{om[k].real, om[k].imag * (rev ? -1 : 1)}; a[i+k] += y; a[i+k+len] = C{x.real - y.real, x.imag - y.imag}; } } if(rev) REP(i, n) a[i].real /= n; } template<typename T>vector<T> multiply(const vector<T> & a, const vector<T> & b, bool split = false, bool normalize = false) { if(a.empty() || b.empty()) return {}; T big = 0; if(normalize) { // [0,B] into [-B/2, B/2] assert(a.size() == b.size()); // equal size!!! for(T x : a) big = max(big, x); for(T x : b) big = max(big, x); big /= 2; } int n = a.size() + b.size(); vector<T> ans(n - 1); if(min(a.size(),b.size()) < 190) { // BRUTE FORCE REP(i, a.size()) REP(j, b.size()) ans[i+j] = Moduluj(ans[i+j] + a[i]*b[j]); return ans; } while(n&(n-1)) ++n; auto speed = [&](const vector<C> & w, int i, int k) { int j = i ? n - i : 0, r = k ? -1 : 1; return C{w[i].real + w[j].real * r, w[i].imag - w[j].imag * r} * (k ? C{0, -0.5} : C{0.5, 0}); }; if(!split) { // standard fast version vector<C> in(n), done(n); REP(i, a.size()) in[i].real = a[i] - big; REP(i, b.size()) in[i].imag = b[i] - big; dft(in, false); REP(i, n) done[i] = speed(in, i, 0) * speed(in, i, 1); dft(done, true); REP(i, ans.size()) ans[i] = is_integral<T>::value ? llround(done[i].real) : done[i].real; //REP(i,ans.size())err=max(err,abs(done[i].real-ans[i])); } else { // Split big INTEGERS into pairs a1*M+a2, const T M = 1<<15; // where M = sqrt(max_absvalue). vector<C> t[2]; // This version is 2.2-2.5 times slower. REP(x, 2) { t[x].resize(n); auto & in = x ? b : a; // below use (in[i]-big) if normalized REP(i, in.size()) t[x][i]=C{ld(in[i]%M), ld(in[i]/M)}; dft(t[x], false); } T mul = 1; for(int s = 0; s < 3; ++s, mul *= M) { vector<C> prod(n); REP(x, 2) REP(y, 2) if(x + y == s) REP(i, n) prod[i] += speed(t[0], i, x) * speed(t[1], i, y); dft(prod, true); // remember: llround(prod[i].real)%MOD*mul !!! REP(i, ans.size()) ans[i]+= Moduluj(llround(prod[i].real))*mul; } } if(normalize) { T so_far = 0; REP(i, ans.size()) { if(i < (int) a.size()) so_far += a[i] + b[i]; else so_far -= a[i-a.size()] + b[i-a.size()]; ans[i] += big * so_far - big * big * min(i + 1, (int) ans.size() - i); } } return ans; } vector<int> Mul(const vector<int>& a, const vector<int>& b) { vector<ll> A(a.begin(), a.end()), B(b.begin(), b.end()); auto res = multiply(A, B, true); vector<int> wyn; wyn.reserve(res.size()); for (ll x : res) wyn.push_back(Moduluj(x)); return wyn; } const ll M = 1 << 17; // M can be smaller if vectors are small vector<ll> compress(const vector<ll> & a) { vector<ll> tmp((a.size() + 1) / 2); for(int i = 0; 2 * i + 1 < (int) a.size(); ++i) tmp[i] += a[2 * i] + a[2 * i + 1] * M; if(a.size() % 2) tmp.back() = a.back(); return tmp; } vector<ll> my_mul(const vector<ll> & a, const vector<ll> & b) { vector<ll> tmp = multiply(compress(a), compress(b), false); vector<ll> r(2 * tmp.size() + 1); for(int i = 0; i < (int) tmp.size(); ++i) { r[2*i] += tmp[i] % M; // can be sped-up with bit shifting r[2*i+1] += tmp[i] / M % M; r[2*i+2] += tmp[i] / M / M; } r.resize(a.size() + b.size() - 1); return r; } #undef REP } // namespace Fft namespace Karatsuba { uint64_t tmp[1 << 18]; uint64_t mod_wielok; constexpr uint64_t prog = 17e18; void Init() { mod_wielok = (prog / mod) * mod; } #define REP(i, n) for(int i = 0; i < (n); ++i) template<typename T> void rec_kara(T* a, int one, T* b, int two, T* r) { if(min(one, two) <= 10) { // must be at least "<= 1" REP(i, one) REP(j, two) { r[i+j] = Moduluj(ll(a[i]) * b[j] + r[i+j]); } return; } const int x = min(one, two); if(one < two) rec_kara(a, x, b + x, two - x, r + x); if(two < one) rec_kara(a + x, one - x, b, x, r + x); const int n = (x + 1) / 2, right = x / 2; vector<T> tu(2 * n); rec_kara(a, n, b, n, tu.data()); REP(i, 2 * n - 1) { //r[i] += tu[i]; DodajDo(r[i], tu[i]); //r[i+n] -= tu[i]; OdejmijOd(r[i+n], tu[i]); tu[i] = 0; } rec_kara(a + n, right, b + n, right, tu.data()); REP(i, 2 * right - 1) { OdejmijOd(r[i+n], tu[i]); //r[i+n] -= tu[i]; DodajDo(r[i+2*n], tu[i]); //r[i+2*n] += tu[i]; } tu[n-1] = a[n-1]; tu[2*n-1] = b[n-1]; REP(i, right) { tu[i] = Dodaj(a[i],a[i+n]); tu[i+n] = Dodaj(b[i],b[i+n]); } rec_kara(tu.data(), n, tu.data() + n, n, r + n); } template<typename T> vector<T> karatsuba(vector<T> a, vector<T> b) { if(a.empty() || b.empty()) return {}; vector<T> r(a.size() + b.size() - 1); rec_kara(a.data(), a.size(), b.data(), b.size(), r.data()); return r; } #undef REP } // namespace Karatsuba struct Poly { vector<int> wsp; friend debug& operator<<(debug& deb, const Poly& p); Poly() = default; explicit Poly(vector<int>&& w) : wsp(move(w)) { while (!wsp.empty() and wsp.back() == 0) { wsp.pop_back(); } } static Poly Jednomian(int i) { vector<int> res(i + 1); res.back() = 1; return Poly(move(res)); } int Deg() const { return (int) wsp.size() - 1; } int operator()(int x) const { int res = 0; for (int i = (int) wsp.size() - 1; i >= 0; i--) { res = Dodaj(Mnoz(res, x), wsp[i]); } return res; } Poly operator-() const { vector<int> res = wsp; for (int& x : res) { x = Odejmij(0, x); } return Poly(move(res)); } Poly operator+(const Poly& p) const { vector<int> res(max(wsp.size(), p.wsp.size())); for (int i = 0; i < (int) res.size(); i++) { if (i < (int) wsp.size()) { res[i] = wsp[i]; } if (i < (int) p.wsp.size()) { DodajDo(res[i], p.wsp[i]); } } return Poly(move(res)); } Poly operator-(const Poly& p) const { vector<int> res(max(wsp.size(), p.wsp.size())); for (int i = 0; i < (int) res.size(); i++) { if (i < (int) wsp.size()) { res[i] = wsp[i]; } if (i < (int) p.wsp.size()) { OdejmijOd(res[i], p.wsp[i]); } } return Poly(move(res)); } Poly operator*(const Poly& p) const { //return Poly(Karatsuba::karatsuba(wsp, p.wsp)); return Poly(Fft::Mul(wsp, p.wsp)); } Poly operator*(int c) const { vector<int> res = wsp; for (int& x : res) { MnozDo(x, c); } return Poly(move(res)); } Poly Utnij(int len) const { vector<int> kopia = wsp; if ((int) kopia.size() > len) { kopia.resize(len); } return Poly(move(kopia)); } Poly Zjedz(int len) const { vector<int> res = wsp; if ((int) res.size() <= len) { res.clear(); } else { res.erase(res.begin(), res.begin() + len); } return Poly(move(res)); } Poly Rev() const { vector<int> res = wsp; reverse(res.begin(), res.end()); return Poly(move(res)); } Poly Inverse(int l) const { debug() << imie(*this) << ".Inverse(" imie(l) ")"; #ifdef LOCAL assert((*this)(0) == 1); #endif Poly g(vector<int>{1}); int n = 1; while (n < l) { n = 2 * n; if (n > l) n = l; Poly h = Utnij(n); h = (h * g).Utnij(n); g = (g * (Poly(vector<int>{Moduluj(2)}) - h)).Utnij(n); } #ifdef LOCAL debug() << imie(*this) imie(g); debug() << imie((*this * g).Utnij(l)); assert((*this * g).Utnij(l) == Poly(vector<int>{1})); #endif return g; } Poly operator/(const Poly& b) const { assert(!b.wsp.empty() and b.wsp.back() == 1); const int n = Deg(); const int m = b.Deg(); if (n < m) { return *this; } Poly f = b.Rev(); Poly g = f.Inverse(n - m + 1).Utnij(n - m + 1); Poly q = (Rev() * g).Utnij(n - m + 1); return q.Rev(); } Poly operator%(const Poly& b) const { assert(!b.wsp.empty() and b.wsp.back() == 1); const int n = Deg(); const int m = b.Deg(); if (n < m) { return *this; } Poly f = b.Rev(); Poly g = f.Inverse(n - m + 1).Utnij(n - m + 1); Poly q = (Rev() * g).Utnij(n - m + 1); return *this - b * q.Rev(); } bool operator==(const Poly& p) const { return wsp == p.wsp; } bool operator!=(const Poly& p) const { return wsp != p.wsp; } }; struct PolyTree { vector<int> xs; bool wyznaczone; Poly poly; unique_ptr<PolyTree> left, right; PolyTree(vector<int> xs_) : xs(move(xs_)), wyznaczone(false) { assert(!xs.empty()); if ((int) xs.size() == 1) { poly = Poly(vector<int>{Odejmij(0, xs[0]), 1}); } else { const int s = (int) xs.size() / 2; left = unique_ptr<PolyTree>(new PolyTree( vector<int>(xs.begin(), xs.begin() + s))); right = unique_ptr<PolyTree>(new PolyTree( vector<int>(xs.begin() + s, xs.end()))); } } void Wyznacz() { if (wyznaczone) return; wyznaczone = true; if (left) { left->Wyznacz(); right->Wyznacz(); poly = left->poly * right->poly; } } void Evaluate(const Poly& p, vector<int>& result) { if ((int) xs.size() <= 1000) { for (int x : xs) { result.push_back(p(x)); } return; } //Poly q = p % poly; assert(left and right); left->Wyznacz(); right->Wyznacz(); left->Evaluate(p % left->poly, result); right->Evaluate(p % right->poly, result); } }; vector<int> Evaluate(const Poly& poly, const vector<int>& xs) { vector<int> res; if (xs.empty()) return res; PolyTree tree(xs); res.reserve(xs.size()); tree.Evaluate(poly, res); #ifdef LOCAL assert(res.size() == xs.size()); for (int i = 0; i < (int) res.size(); i++) { assert(res[i] == poly(xs[i])); } #endif return res; } debug& operator<<(debug& deb, const Poly& p) { return deb << "Poly{" << p.wsp << "}"; } Poly PolyPrzedzial(int a, int b) { if (a == b) return Poly(vector<int>{a, 1}); const int s = (a + b) / 2; return PolyPrzedzial(a, s) * PolyPrzedzial(s + 1, b); } constexpr int MaxN = 1000 * 1000 * 1000 + 10; vector<int> Factorial(const vector<int>& ns) { debug() << "Factorial(" imie(ns) ")"; constexpr int Skok = 31 * 1000; Poly p = PolyPrzedzial(1, Skok); vector<int> punkty; for (int i = 0; i < MaxN; i += Skok) { punkty.push_back(i); } vector<int> wart = Evaluate(p, punkty); assert(punkty.size() == wart.size()); auto Oblicz = [&](int n) -> int { if (n < 0) return 0; int res = 1; int mam_do = 0; for (int i = 0; i < (int) punkty.size(); i++) { if (punkty[i] + Skok <= n) { MnozDo(res, wart[i]); mam_do = punkty[i] + Skok; } else { break; } } for (int i = mam_do + 1; i <= n; i++) { MnozDo(res, i); } return res; }; vector<int> res; for (int n : ns) { res.push_back(Oblicz(n)); } debug() << imie(res); return res; } int FactorialBrut(int n) { int res = 1; for (int i = 1; i <= n; i++) { MnozDo(res, i); } return res; } int CBrut(int n, int k) { if (0 <= k and k <= n) { return Podziel(FactorialBrut(n), Mnoz(FactorialBrut(n - k), FactorialBrut(k))); } return 0; } vector<int> Oblicz(int a, int b, int k) { debug() << "Oblicz(" imie(a) imie(b) imie(k) ")"; // Dla każdego i in [a..b] zwraca C(i, k). vector<int> res(b - a + 1); vector<int> silnie = Factorial({a, b - k, k}); assert((int) silnie.size() == 3); int Licznik = silnie[0]; int Mianownik = Podziel(1, silnie[1]); const int ksilnia = Podziel(1, silnie[2]); debug() << imie(Licznik) imie(Mianownik) imie(ksilnia); for (int i = a; i < b; i++) { res[i - a] = Mnoz(Licznik, ksilnia); MnozDo(Licznik, i + 1); } res[b - a] = Mnoz(Licznik, ksilnia); for (int i = b; i > a; i--) { MnozDo(res[i - a], Mianownik); MnozDo(Mianownik, i - k); } MnozDo(res[a - a], Mianownik); return res; } pair<int, int> ObliczFunkcje(const vector<int>& v) { pair<int, int> res = {1, 0}; for (int x : v) { res = {Dodaj(res.first, res.first), Dodaj(res.second, res.second)}; OdejmijOd(res.second, x); } return res; } #include "futbol.h" int N, me; int main() { N = NumberOfNodes(); me = MyNodeId(); mod = GetP(); Mini(N, mod); if (me >= N) return 0; const int k = GetK(); fast_mod = libdivide::libdivide_u64_gen(mod); debug() << imie(mod) imie(k) imie(MaxN); auto ranges = Range<int>(0, mod - 1).Divide(N); vector<int> v = Oblicz(ranges[me].a(), ranges[me].b(), k); debug() << imie(v); auto fun = ObliczFunkcje(v); debug() << imie(fun); debug() << imie(ranges); int lewo, n; if (me == 0) { lewo = 1; n = GetN() - 1; assert(0 <= n and n < MaxN); } else { ReceiveMessage msg(me - 1); lewo = msg.Get<int>(); n = msg.Get<int>(); } debug() << imie(lewo) imie(n); if (n < ranges[me].a()) { if (me + 1 < N) { SendMessage(me + 1).Put(lewo).Put(n); } } else if (n <= ranges[me].b()) { if (me + 1 < N) { SendMessage(me + 1).Put(lewo).Put(n); } const int a = ranges[me].a(); for (int i = a; i <= n; i++) { lewo = Odejmij(Dodaj(lewo, lewo), v[i - a]); } cout << lewo << endl; //assert(lewo == 2998413); } else { assert(ranges[me].b() < n); lewo = Dodaj(Mnoz(fun.first, lewo), fun.second); assert(me + 1 < N); SendMessage(me + 1).Put(lewo).Put(n); } return 0; } |