This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-12232-ab1751ead80b24cb2b919d7eaaaf4b739c7fd355 in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 2a3fcfd70b9b0147b3b2737b3e324f20e73e9f94 Author: Matt Butrovich <[email protected]> AuthorDate: Fri Nov 20 13:10:34 2026 +0000 perf(arrow-buffer): add precomputed divisors for `i128` and `i256` (#12232) # Which issue does this PR close? - Closes #12167. - Part of #11421. # Rationale for this change The decimal kernels in #11421 divide `i128` and `i256` values by a scalar. This PR adds the divisors they need, with the API that #11467 settled. # What changes are included in this PR? - `DivisorI128` and `DivisorI256` in `arrow-buffer`. No kernel uses them yet. - Each is a `#[non_exhaustive]` enum with the variants of `DivisorI64`, and each variant is its own type. A kernel matches on the variant once, outside the loop, as with the 32-bit and 64-bit divisors. - `new` picks the variant from the divisor: - `PowerOfTwo` shifts and masks. - `AddIndicator` uses figure 5.1 of Granlund and Montgomery for any other divisor. There is no wider type to compute `MULSH` in, so it computes `n + MULSH(m', n)` as `MULUH(m', n) - AND(m', XSIGN(n))`, from the identity in section 3 of the paper and because `m'` is negative. - The signed remainder comes from the quotient before the sign fix and `|divisor|`, as in #11467. - `new` isn't a `const fn`, because it divides with `i256`, so neither are `wrapping_div_rem` and `checked_div_rem`. All three can become `const` together without breaking callers. - There is no separate variant for batches whose values fit in a narrower type. A kernel divides those with `DivisorI64` or `DivisorI128`, and the rustdoc says when the results match, which excludes a divisor of -1. - There is no `DivisorU128` or `u256` form, because every kernel in #11421 divides signed values. - The `i256` variants branch on the shift, unlike the other divisor types, because a branch-free shift was slower. `AddIndicatorDivisorI256::wrapping_div_rem` is `#[inline(always)]`, because at `#[inline]` LLVM called it out of line for each value. # Are these changes tested? - Unit tests and doctests in `arrow-buffer/src/divisor.rs` compare both types with the standard integer operators. They include each side of every power of two and power of ten, both ends of the last quotient steps, and the variant `new` picks for each divisor. - The `divisor` benchmark in `arrow-buffer/benches/divisor.rs` divides 8192 random values by 7, 16 and 10^18 for `i128` or 10^38 for `i256`, with `/` and `%` and with the divisor. It runs on full-width values and on values that fit in the next narrower type, where `/` and `%` take a faster path. - The benchmark bot ran it on [x86_64](https://github.com/apache/arrow-rs/pull/12232#issuecomment-6855016822) (Xeon Platinum 8581C) at the default target and at [`x86-64-v3`](https://github.com/apache/arrow-rs/pull/12232#issuecomment-6855019875), and on [arm64](https://github.com/apache/arrow-rs/pull/12232#issuecomment-6854966033) (Neoverse-V2). Each run compares 2bdc7f3b5e with itself, so the charts show `operator` time divided by `divisor` time from the changed column. <img width="1600" height="1764" alt="divisor-wide-bot-x86-v3" src="https://github.com/user-attachments/assets/a037b776-fc66-4695-ace6-4fdbb98911d5" /> <img width="1600" height="1764" alt="divisor-wide-bot-x86" src="https://github.com/user-attachments/assets/2d9a680b-5b1b-4912-a81a-85be4644921b" /> <img width="1600" height="1764" alt="divisor-wide-bot-arm" src="https://github.com/user-attachments/assets/c703a2cb-dd00-4ff4-971a-1bd48f066ec8" /> - On full-width values, `wrapping_div_rem` is faster than `/` and `%` in 35 of 36 cases. The exception is `i256 % 7` on the Xeon at the default target, at 0.97x, where `i256::wrapping_div_rem` divides by a one-word divisor with a hardware divide per word. - On values that fit in the next narrower type, `/`, `%` and `i256::wrapping_div_rem` take a faster path, and the divisor is slower in 11 of 36 cases, down to 0.55x for `i256 % 10^38` on Neoverse-V2. A kernel would divide those batches with `DivisorI64` or `DivisorI128`. - Building a divisor takes 1.7 to 23 ns for `i128` and 7.4 to 145 ns for `i256` in the `new` cases. On full-width values, the divisor saves that within three values. - In the `divisor` benchmark binary built with the bot's thin LTO for aarch64, x86_64 and `x86-64-v3`, no inner loop calls out to divide, and the `i128` loops have no branch but the loop's own. The `i256` loops branch on the divisor's shift for each value. # Are there any significant user-facing changes? No existing API changes. The PR adds `DivisorI128` and `DivisorI256` to `arrow-buffer`. They are used as the 32-bit and 64-bit divisors are. When every value of a batch fits in `i64`, a kernel can divide in `i64` instead: ```rust use arrow_buffer::{DivisorI64, DivisorI128}; let values: Vec<i128> = vec![-12_345, 678]; let divisor: i128 = 100; let narrow = values.iter().all(|n| i64::try_from(*n).is_ok()); // `i64::MIN / -1` overflows in `i64` but not in `i128` let quotients: Vec<i128> = match i64::try_from(divisor) { Ok(d) if narrow && d != -1 => { let d = DivisorI64::new(d).unwrap(); values.iter().map(|n| d.wrapping_div_rem(*n as i64).0 as i128).collect() } _ => match DivisorI128::new(divisor).unwrap() { DivisorI128::PowerOfTwo(d) => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(), DivisorI128::AddIndicator(d) => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(), d => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(), }, }; assert_eq!(quotients, [-123, 6]); ``` ## AI Disclosure I wrote this PR with help from Claude but understand and support the core approach, implementation, and test coverage. --- arrow-buffer/benches/divisor.rs | 66 ++++- arrow-buffer/src/bigint/mod.rs | 19 +- arrow-buffer/src/divisor.rs | 572 ++++++++++++++++++++++++++++++++++++---- 3 files changed, 605 insertions(+), 52 deletions(-) diff --git a/arrow-buffer/benches/divisor.rs b/arrow-buffer/benches/divisor.rs index e3edff3356..4bb6ee53ef 100644 --- a/arrow-buffer/benches/divisor.rs +++ b/arrow-buffer/benches/divisor.rs @@ -2,7 +2,9 @@ // SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements -use arrow_buffer::{DivisorI32, DivisorI64, DivisorU32, DivisorU64}; +use arrow_buffer::{ + DivisorI32, DivisorI64, DivisorI128, DivisorI256, DivisorU32, DivisorU64, i256, +}; use criterion::*; use rand::rngs::StdRng; use rand::{RngExt, SeedableRng}; @@ -57,11 +59,73 @@ macro_rules! bench_divisor { }}; } +/// Divides `SIZE` values by a divisor of each variant and by a power of ten that a decimal kernel +/// divides by, with `/` and `%`, and with the divisor type. `full` values use every bit, and +/// `narrow` values fit in the next narrower type, where `/` and `%` take a faster path. `new` +/// builds one divisor, which a kernel does once per batch +macro_rules! bench_wide { + ($c:expr, $divisor:ident, $t:ty, $full:expr, $narrow:expr, $divisors:expr, $variants:tt) => {{ + let mut rng = StdRng::seed_from_u64(42); + let full: Vec<$t> = (0..SIZE).map(|_| $full(&mut rng)).collect(); + let narrow: Vec<$t> = (0..SIZE).map(|_| $narrow(&mut rng)).collect(); + let mut group = $c.benchmark_group(concat!("divisor_", stringify!($t))); + group.throughput(Throughput::Elements(SIZE as u64)); + for (width, values) in [("full", &full), ("narrow", &narrow)] { + for (label, d) in $divisors { + let d: $t = hint::black_box(d); + let divisor = $divisor::new(d).unwrap(); + group.bench_function(format!("div {label} {width}/operator"), |b| { + b.iter(|| values.iter().map(move |x| *x / d).collect::<Vec<_>>()) + }); + group.bench_function(format!("div {label} {width}/divisor"), |b| { + b.iter(|| div_rem_all!(values, divisor, $divisor, 0, $variants)) + }); + group.bench_function(format!("rem {label} {width}/operator"), |b| { + b.iter(|| values.iter().map(move |x| *x % d).collect::<Vec<_>>()) + }); + group.bench_function(format!("rem {label} {width}/divisor"), |b| { + b.iter(|| div_rem_all!(values, divisor, $divisor, 1, $variants)) + }); + } + } + group.throughput(Throughput::Elements(1)); + for (label, d) in $divisors { + group.bench_function(format!("new {label}"), |b| { + b.iter(|| $divisor::new(hint::black_box(d))) + }); + } + group.finish(); + }}; +} + fn criterion_benchmark(c: &mut Criterion) { bench_divisor!(c, DivisorU32, u32, [PowerOfTwo, Up, Down, AddIndicator]); bench_divisor!(c, DivisorI32, i32, [PowerOfTwo, AddIndicator]); bench_divisor!(c, DivisorU64, u64, [PowerOfTwo, Up, AddIndicator]); bench_divisor!(c, DivisorI64, i64, [PowerOfTwo, AddIndicator]); + bench_wide!( + c, + DivisorI128, + i128, + |rng: &mut StdRng| rng.random::<i128>(), + |rng: &mut StdRng| rng.random::<i64>() as i128, + [("7", 7), ("16", 16), ("1e18", 10i128.pow(18))], + [PowerOfTwo, AddIndicator] + ); + let i256_of = i256::from_i128; + bench_wide!( + c, + DivisorI256, + i256, + |rng: &mut StdRng| i256::from_parts(rng.random(), rng.random()), + |rng: &mut StdRng| i256::from_i128(rng.random()), + [ + ("7", i256_of(7)), + ("16", i256_of(16)), + ("1e38", i256_of(10i128.pow(38))) + ], + [PowerOfTwo, AddIndicator] + ); } criterion_group!(benches, criterion_benchmark); diff --git a/arrow-buffer/src/bigint/mod.rs b/arrow-buffer/src/bigint/mod.rs index 36f5a42a12..ea2ea4786f 100644 --- a/arrow-buffer/src/bigint/mod.rs +++ b/arrow-buffer/src/bigint/mod.rs @@ -16,7 +16,7 @@ use std::num::ParseIntError; use std::ops::{BitAnd, BitOr, BitXor, Neg, Not, Shl, Shr}; use std::str::FromStr; -mod div; +pub(crate) mod div; /// An opaque error similar to [`std::num::ParseIntError`] #[derive(Debug)] @@ -332,9 +332,7 @@ impl i256 { /// Computes the absolute value of this i256 #[inline] pub const fn wrapping_abs(self) -> Self { - // -1 if negative, otherwise 0 - let sa = self.high >> 127; - let sa = Self::from_parts(sa as u128, sa); + let sa = self.sign_mask(); // Inverted if negative Self::from_parts(self.low ^ sa.low, self.high ^ sa.high).wrapping_sub(sa) @@ -418,6 +416,13 @@ impl i256 { (self.high == other.high) && (self.low == other.low) } + /// Returns -1 if `self` is negative, otherwise 0 + #[inline] + pub(crate) const fn sign_mask(self) -> Self { + let s = self.high >> 127; + Self::from_parts(s as u128, s) + } + /// Performs checked multiplication #[inline] pub const fn checked_mul(self, other: Self) -> Option<Self> { @@ -509,7 +514,7 @@ impl i256 { } /// Interpret this [`i256`] as 4 `u64` digits, least significant first - fn as_digits(self) -> [u64; 4] { + pub(crate) fn as_digits(self) -> [u64; 4] { [ self.low as u64, (self.low >> 64) as u64, @@ -519,7 +524,7 @@ impl i256 { } /// Interpret 4 `u64` digits, least significant first, as a [`i256`] - fn from_digits(digits: [u64; 4]) -> Self { + pub(crate) fn from_digits(digits: [u64; 4]) -> Self { Self::from_parts( digits[0] as u128 | ((digits[1] as u128) << 64), digits[2] as i128 | ((digits[3] as i128) << 64), @@ -910,7 +915,7 @@ const fn split_array<const N: usize, const M: usize>(vals: [u8; N]) -> ([u8; M], /// /// This mirrors the x86 mulx instruction but for 128-bit types #[inline] -const fn mulx(a: u128, b: u128) -> (u128, u128) { +pub(crate) const fn mulx(a: u128, b: u128) -> (u128, u128) { const fn split(a: u128) -> (u128, u128) { (a & (u64::MAX as u128), a >> 64) } diff --git a/arrow-buffer/src/divisor.rs b/arrow-buffer/src/divisor.rs index d1f5521ea3..f4b8799479 100644 --- a/arrow-buffer/src/divisor.rs +++ b/arrow-buffer/src/divisor.rs @@ -2,6 +2,10 @@ // SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements +use crate::bigint::div::div_rem; +use crate::bigint::mulx; +use crate::i256; + /// Whether a saturating increment on `u32` lanes is cheap: one `uqadd` on aarch64, and `pminud` /// from SSE4.1 and a subtract on x86. Baseline x86-64 has no unsigned 32-bit min and emulates it /// with compares, so there the saturating increment of [`DivisorU32::Down`] costs more than the @@ -15,7 +19,47 @@ const CHEAP_SATURATION: bool = cfg!(any( )); macro_rules! divisor_enum { - ($name:ident, $t:ty, $($(#[$doc:meta])* $variant:ident($inner:ident),)+) => { + ( + $name:ident, + $t:ty, + [$($c:tt)?], + [$(#[$enum_doc:meta])*], + $($(#[$doc:meta])* $variant:ident($inner:ident),)+ + ) => { + divisor_enum!( + $name, + $t, + [$($c)?], + concat!( + "# use arrow_buffer::", stringify!($name), ";\n", + "let values: Vec<", stringify!($t), "> = vec![100, 7, 64];\n", + "let quotients: Vec<_> = match ", stringify!($name), "::new(7).unwrap() {\n", + " ", stringify!($name), "::PowerOfTwo(d) => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(),\n", + " ", stringify!($name), "::AddIndicator(d) => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(),\n", + " d => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(),\n", + "};\n", + "assert_eq!(quotients, [14, 1, 9]);", + ), + concat!( + "# use arrow_buffer::", stringify!($name), ";\n", + "let divisor = ", stringify!($name), "::new(7).unwrap();\n", + "assert_eq!(divisor.wrapping_div_rem(100), (14, 2));", + ), + "They don't branch on the divisor, so the loop doesn't depend on the compiler moving a branch out of it.", + [$(#[$enum_doc])*], + $($(#[$doc])* $variant($inner),)+ + ); + }; + ( + $name:ident, + $t:ty, + [$($c:tt)?], + $example:expr, + $div_rem_example:expr, + $branch_doc:expr, + [$(#[$enum_doc:meta])*], + $($(#[$doc:meta])* $variant:ident($inner:ident),)+ + ) => { #[doc = concat!("A `", stringify!($t), "` divisor, precomputed once to divide many values by it")] /// /// Division by a divisor that is only known at run time needs a divide instruction. @@ -24,22 +68,17 @@ macro_rules! divisor_enum { /// shifts and additions. [`Self::new`] picks the variant from the divisor and the target. /// /// To divide many values, match on the variant once, before the loop, and call the - /// variant's methods in the loop. They don't branch on the divisor, so the loop doesn't - /// depend on the compiler moving a branch out of it. Move the variant into the loop's - /// closure, so that the compiler doesn't reload its fields through a reference for each - /// value. [`Self::wrapping_div_rem`] matches on each call, so a match can fall back to it - /// for the variants it doesn't specialize, including variants added later. + /// variant's methods in the loop. + #[doc = $branch_doc] + /// Move the variant into the loop's closure, so that the compiler doesn't reload its + /// fields through a reference for each value. [`Self::wrapping_div_rem`] matches on each + /// call, so a match can fall back to it for the variants it doesn't specialize, including + /// variants added later. + $(#[$enum_doc])* /// /// # Example /// ``` - #[doc = concat!("# use arrow_buffer::", stringify!($name), ";")] - #[doc = concat!("let values: Vec<", stringify!($t), "> = vec![100, 7, 64];")] - #[doc = concat!("let quotients: Vec<_> = match ", stringify!($name), "::new(7).unwrap() {")] - #[doc = concat!(" ", stringify!($name), "::PowerOfTwo(d) => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(),")] - #[doc = concat!(" ", stringify!($name), "::AddIndicator(d) => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(),")] - /// d => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(), - /// }; - /// assert_eq!(quotients, [14, 1, 9]); + #[doc = $example] /// ``` #[derive(Debug, Clone, Copy)] #[non_exhaustive] @@ -52,12 +91,10 @@ macro_rules! divisor_enum { /// /// # Example /// ``` - #[doc = concat!("# use arrow_buffer::", stringify!($name), ";")] - #[doc = concat!("let divisor = ", stringify!($name), "::new(7).unwrap();")] - /// assert_eq!(divisor.wrapping_div_rem(100), (14, 2)); + #[doc = $div_rem_example] /// ``` #[inline] - pub const fn wrapping_div_rem(self, n: $t) -> ($t, $t) { + pub $($c)? fn wrapping_div_rem(self, n: $t) -> ($t, $t) { match self { $(Self::$variant(d) => d.wrapping_div_rem(n),)+ } @@ -105,6 +142,8 @@ macro_rules! unsigned_divisor { divisor_enum!( $name, $t, + [const], + [], /// A divisor that is a power of two PowerOfTwo($power_of_two), /// A divisor whose rounded-up multiplier is exact in N bits @@ -274,11 +313,25 @@ macro_rules! unsigned_divisor { }; } +/// `$multiplier` computes `m - 2^N` from figure 5.1 for `|divisor|` and `l`, and `$high` computes +/// `n + MULSH(m - 2^N, n)`, which is `floor(m * n / 2^N)`. `[const]` makes `new` and the +/// division methods `const fn`s macro_rules! signed_divisor { - ($name:ident, $power_of_two:ident, $add:ident, $t:ty, $wide:ty) => { + ( + $name:ident, + $power_of_two:ident, + $add:ident, + $t:ty, + [$($c:tt)?], + |$magnitude:ident, $l:ident| $multiplier:expr, + |$m:ident, $n:ident| $high:expr, + [$(#[$enum_doc:meta])*] + ) => { divisor_enum!( $name, $t, + [$($c)?], + [$(#[$enum_doc])*], /// A divisor whose magnitude is a power of two PowerOfTwo($power_of_two), /// Any other divisor @@ -291,10 +344,10 @@ macro_rules! signed_divisor { /// # Example /// ``` #[doc = concat!("# use arrow_buffer::", stringify!($name), ";")] - #[doc = concat!("const SEVEN: ", stringify!($name), " = ", stringify!($name), "::new(7).unwrap();")] + $(#[doc = concat!(stringify!($c), " SEVEN: ", stringify!($name), " = ", stringify!($name), "::new(7).unwrap();")])? #[doc = concat!("assert!(", stringify!($name), "::new(0).is_none());")] /// ``` - pub const fn new(divisor: $t) -> Option<Self> { + pub $($c)? fn new(divisor: $t) -> Option<Self> { if divisor == 0 { return None; } @@ -318,7 +371,7 @@ macro_rules! signed_divisor { #[doc = concat!("assert_eq!(minus_one.checked_div_rem(", stringify!($t), "::MIN), None);")] /// ``` #[inline] - pub const fn checked_div_rem(self, n: $t) -> Option<($t, $t)> { + pub $($c)? fn checked_div_rem(self, n: $t) -> Option<($t, $t)> { match self { Self::PowerOfTwo(d) => d.checked_div_rem(n), Self::AddIndicator(d) => Some(d.wrapping_div_rem(n)), @@ -366,7 +419,7 @@ macro_rules! signed_divisor { #[doc = concat!("assert_eq!(minus_one.wrapping_div_rem(", stringify!($t), "::MIN), (", stringify!($t), "::MIN, 0));")] /// ``` #[inline] - pub const fn wrapping_div_rem(self, n: $t) -> ($t, $t) { + pub $($c)? fn wrapping_div_rem(self, n: $t) -> ($t, $t) { // Adding `|divisor| - 1` to a negative `n` makes the shift round toward zero let t = n + ((n >> (<$t>::BITS - 1)) & self.mask); let q = t >> self.shift; @@ -387,7 +440,7 @@ macro_rules! signed_divisor { #[doc = concat!("assert_eq!(minus_one.checked_div_rem(", stringify!($t), "::MIN), None);")] /// ``` #[inline] - pub const fn checked_div_rem(self, n: $t) -> Option<($t, $t)> { + pub $($c)? fn checked_div_rem(self, n: $t) -> Option<($t, $t)> { // -1 is the only divisor with a negative sign and a zero mask if n == <$t>::MIN && self.sign == -1 && self.mask == 0 { None @@ -412,18 +465,15 @@ macro_rules! signed_divisor { impl $add { /// `|divisor|` must be at least 3 and not a power of two - const fn new(divisor: $t) -> Self { - let magnitude = divisor.unsigned_abs(); + $($c)? fn new(divisor: $t) -> Self { + let $magnitude = divisor.unsigned_abs(); // ceil(log2(|divisor|)), which is at least 2 because |divisor| >= 3, so figure // 5.1's `max(..., 1)` isn't needed - let l = <$t>::BITS - (magnitude - 1).leading_zeros(); - // m = 1 + floor(2^(N + l - 1) / |divisor|) is between 2^(N - 1) and 2^N, so - // m - 2^N fits in the narrow type - let m = 1 + (1 << (<$t>::BITS + l - 1)) / magnitude as $wide; + let $l = <$t>::BITS - ($magnitude - 1).leading_zeros(); Self { divisor, - multiplier: (m - (1 << <$t>::BITS)) as $t, - shift: l - 1, + multiplier: $multiplier, + shift: $l - 1, } } @@ -436,11 +486,10 @@ macro_rules! signed_divisor { /// assert_eq!(divisor.wrapping_div_rem(-100), (14, -2)); /// ``` #[inline] - pub const fn wrapping_div_rem(self, n: $t) -> ($t, $t) { - // `MULSH(m', n)` in figure 5.1 - let high = ((self.multiplier as $wide * n as $wide) >> <$t>::BITS) as $t; + pub $($c)? fn wrapping_div_rem(self, n: $t) -> ($t, $t) { + let ($m, $n) = (self.multiplier, n); // The shift rounds down, and subtracting the sign of `n` rounds toward zero instead - let q = ((n + high) >> self.shift) - (n >> (<$t>::BITS - 1)); + let q = ($high >> self.shift) - (n >> (<$t>::BITS - 1)); let sign = self.divisor >> (<$t>::BITS - 1); // The remainder doesn't depend on the sign of the divisor, as section 3.1 of // Lemire, Kaser and Kurz, "Faster Remainder by Direct Computation", @@ -470,20 +519,335 @@ unsigned_divisor!( u64, u128 ); -signed_divisor!( +/// Expands to the arguments of `signed_divisor!` that compute with `$wide`, a type twice as wide +/// as `$t` +macro_rules! signed_divisor_wide { + ($name:ident, $power_of_two:ident, $add:ident, $t:ty, $wide:ty) => { + signed_divisor!( + $name, + $power_of_two, + $add, + $t, + [const], + // m = 1 + floor(2^(N + l - 1) / |divisor|) is between 2^(N - 1) and 2^N, so m - 2^N + // fits in the narrow type + |magnitude, l| { + let m = 1 + (1 << (<$t>::BITS + l - 1)) / magnitude as $wide; + (m - (1 << <$t>::BITS)) as $t + }, + // `n + MULSH(m', n)` in figure 5.1 + |m, n| n + ((m as $wide * n as $wide) >> <$t>::BITS) as $t, + [] + ); + }; +} + +signed_divisor_wide!( DivisorI32, PowerOfTwoDivisorI32, AddIndicatorDivisorI32, i32, i64 ); -signed_divisor!( +signed_divisor_wide!( DivisorI64, PowerOfTwoDivisorI64, AddIndicatorDivisorI64, i64, i128 ); +signed_divisor!( + DivisorI128, + PowerOfTwoDivisorI128, + AddIndicatorDivisorI128, + i128, + [], + // m = 1 + floor(2^(127 + l) / |divisor|), as for the narrower types. 2^(127 + l) is at most + // 2^254, so `i256` holds it, and the quotient is below 2^128 + |magnitude, l| { + let pow = i256::ONE << (127 + l) as u8; + let (q, _) = pow.wrapping_div(i256::from_parts(magnitude, 0)).to_parts(); + q.wrapping_add(1) as i128 + }, + // Figure 5.1 computes `n + MULSH(m', n)`, and `i128` has no wider type to compute `MULSH` + // in. Section 3 of the paper gives `MULSH(x, y) = MULUH(x, y) - AND(x, XSIGN(y)) + // - AND(y, XSIGN(x))`, which is program (1) in section 8-3 of Warren, "Hacker's Delight", 2nd + // edition. `m'` is negative for every divisor but 1 and -1, which are powers of two, so + // `AND(n, XSIGN(m'))` is `n` and cancels the add, leaving `MULUH(m', n) - AND(m', XSIGN(n))` + |m, n| (mulx(m as u128, n as u128).1 as i128).wrapping_sub((n >> 127) & m), + [ + /// + /// When every value of a batch fits in `i64`, dividing in `i64` with [`DivisorI64`] gives + /// the same results, except for a divisor of -1, because `i64::MIN / -1` overflows in + /// `i64` but not in `i128`. A divisor that doesn't fit in `i64` gives a quotient of 0 and + /// leaves the value as the remainder, except that `i64::MIN / 2^63` is -1 with a + /// remainder of 0. + /// + /// ``` + /// # use arrow_buffer::{DivisorI128, DivisorI64}; + /// let values: Vec<i128> = vec![-12_345, 678, i64::MIN as i128]; + /// let divisor: i128 = 100; + /// let narrow = values.iter().all(|n| i64::try_from(*n).is_ok()); + /// let quotients: Vec<i128> = match i64::try_from(divisor) { + /// Ok(d) if narrow && d != -1 => { + /// let d = DivisorI64::new(d).unwrap(); + /// values.iter().map(|n| d.wrapping_div_rem(*n as i64).0 as i128).collect() + /// } + /// _ => { + /// let d = DivisorI128::new(divisor).unwrap(); + /// values.iter().map(|n| d.wrapping_div_rem(*n).0).collect() + /// } + /// }; + /// assert_eq!(quotients, [-123, 6, -92233720368547758]); + /// ``` + ] +); + +// `signed_divisor!` can't build `DivisorI256`, because `i256` has no `BITS` or `unsigned_abs` +divisor_enum!( + DivisorI256, + i256, + [], + concat!( + "# use arrow_buffer::{i256, DivisorI256};\n", + "let values: Vec<i256> = [100, 7, 64].map(i256::from_i128).to_vec();\n", + "let quotients: Vec<_> = match DivisorI256::new(i256::from_i128(7)).unwrap() {\n", + " DivisorI256::PowerOfTwo(d) => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(),\n", + " DivisorI256::AddIndicator(d) => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(),\n", + " d => values.iter().map(move |n| d.wrapping_div_rem(*n).0).collect(),\n", + "};\n", + "assert_eq!(quotients, [14, 1, 9].map(i256::from_i128));", + ), + concat!( + "# use arrow_buffer::{i256, DivisorI256};\n", + "let divisor = DivisorI256::new(i256::from_i128(7)).unwrap();\n", + "let (q, r) = divisor.wrapping_div_rem(i256::from_i128(100));\n", + "assert_eq!((q, r), (i256::from_i128(14), i256::from_i128(2)));", + ), + "Unlike those of the other divisor types, they branch on the divisor's shift. The shift is the same for every value, so the branch is predicted, and a form without it was slower.", + [ + /// + /// When every value of a batch fits in `i128`, dividing in `i128` with [`DivisorI128`] + /// gives the same results, except for a divisor of -1, because `i128::MIN / -1` overflows + /// in `i128` but not in `i256`. A divisor that doesn't fit in `i128` gives a quotient of 0 + /// and leaves the value as the remainder, except that `i128::MIN / 2^127` is -1 with a + /// remainder of 0. + ], + /// A divisor whose magnitude is a power of two + PowerOfTwo(PowerOfTwoDivisorI256), + /// Any other divisor + AddIndicator(AddIndicatorDivisorI256), +); + +impl DivisorI256 { + /// Returns a divisor for `divisor`, or `None` if `divisor` is zero + /// + /// # Example + /// ``` + /// # use arrow_buffer::{i256, DivisorI256}; + /// assert!(DivisorI256::new(i256::ZERO).is_none()); + /// ``` + pub fn new(divisor: i256) -> Option<Self> { + if divisor == i256::ZERO { + return None; + } + Some(match PowerOfTwoDivisorI256::new(divisor) { + Some(d) => Self::PowerOfTwo(d), + None => Self::AddIndicator(AddIndicatorDivisorI256::new(divisor)), + }) + } + + /// Returns `(n / divisor, n % divisor)`, or `None` for `i256::MIN / -1` + /// + /// It matches on the variant on each call. Only [`Self::PowerOfTwo`] can return `None`. + /// + /// # Example + /// ``` + /// # use arrow_buffer::{i256, DivisorI256}; + /// let divisor = DivisorI256::new(i256::from_i128(-7)).unwrap(); + /// let qr = divisor.checked_div_rem(i256::from_i128(-100)); + /// assert_eq!(qr, Some((i256::from_i128(14), i256::from_i128(-2)))); + /// + /// let minus_one = DivisorI256::new(i256::MINUS_ONE).unwrap(); + /// assert_eq!(minus_one.checked_div_rem(i256::MIN), None); + /// ``` + #[inline] + pub fn checked_div_rem(self, n: i256) -> Option<(i256, i256)> { + match self { + Self::PowerOfTwo(d) => d.checked_div_rem(n), + Self::AddIndicator(d) => Some(d.wrapping_div_rem(n)), + } + } +} + +/// The high 256 bits of the unsigned product of the bits of `a` and `b` +#[inline] +fn mul_high_u256(a: i256, b: i256) -> i256 { + let ((a0, a1), (b0, b1)) = (a.to_parts(), b.to_parts()); + let (a1, b1) = (a1 as u128, b1 as u128); + let (_, p00) = mulx(a0, b0); + let (p01_low, p01_high) = mulx(a0, b1); + let (p10_low, p10_high) = mulx(a1, b0); + let (p11_low, p11_high) = mulx(a1, b1); + // Bits 128 to 255 of the product, of which only the carries matter + let (s, c1) = p00.overflowing_add(p01_low); + let (_, c2) = s.overflowing_add(p10_low); + let (low, c3) = p01_high.overflowing_add(p10_high); + let (low, c4) = low.overflowing_add(p11_low); + let (low, c5) = low.overflowing_add(c1 as u128 + c2 as u128); + // The product is below 2^512, so this doesn't overflow + let high = p11_high + c3 as u128 + c4 as u128 + c5 as u128; + i256::from_parts(low, high as i128) +} + +/// An `i256` divisor whose magnitude is a power of two, see [`DivisorI256`] +/// +/// The quotient and remainder follow sections 10-1 and 10-2 of Warren, "Hacker's Delight", 2nd +/// edition. Those sections compute the addend `2^k - 1` for a negative `n` with two shifts. This +/// type computes it with one shift that spreads the sign bit of `n` and an AND with `2^k - 1`, +/// which it computes once for the divisor. +#[derive(Debug, Clone, Copy)] +pub struct PowerOfTwoDivisorI256 { + /// Below 256, so it fits the `u8` that `i256` shifts by + shift: u8, + /// `|divisor| - 1` + mask: i256, + /// -1 if the divisor is negative, otherwise 0 + sign: i256, +} + +impl PowerOfTwoDivisorI256 { + fn new(divisor: i256) -> Option<Self> { + // `wrapping_abs` leaves `MIN` as it is, whose bits are those of its magnitude, 2^255 + let magnitude = divisor.wrapping_abs(); + let mask = magnitude.wrapping_sub(i256::ONE); + if magnitude & mask != i256::ZERO { + return None; + } + Some(Self { + // The magnitude is a nonzero `i256`, so it has at most 255 trailing zeros + shift: magnitude.trailing_zeros() as u8, + mask, + sign: divisor.sign_mask(), + }) + } + + /// Returns `(n.wrapping_div(divisor), n.wrapping_rem(divisor))`, so `i256::MIN / -1` returns + /// `(i256::MIN, 0)` + /// + /// # Example + /// ``` + /// # use arrow_buffer::{i256, DivisorI256}; + /// let DivisorI256::PowerOfTwo(divisor) = DivisorI256::new(i256::from_i128(-8)).unwrap() else { unreachable!() }; + /// let (q, r) = divisor.wrapping_div_rem(i256::from_i128(-100)); + /// assert_eq!((q, r), (i256::from_i128(12), i256::from_i128(-4))); + /// + /// let DivisorI256::PowerOfTwo(minus_one) = DivisorI256::new(i256::MINUS_ONE).unwrap() else { unreachable!() }; + /// assert_eq!(minus_one.wrapping_div_rem(i256::MIN), (i256::MIN, i256::ZERO)); + /// ``` + #[inline] + pub fn wrapping_div_rem(self, n: i256) -> (i256, i256) { + // Adding `|divisor| - 1` to a negative `n` makes the shift round toward zero + let t = n.wrapping_add(n.sign_mask() & self.mask); + let q = t >> self.shift; + // `(x ^ sign) - sign` negates `x` when `sign` is -1, and wraps only for `MIN / -1` + // `t & !mask` is `n` rounded toward zero to a multiple of `|divisor|` + ( + (q ^ self.sign).wrapping_sub(self.sign), + n.wrapping_sub(t & !self.mask), + ) + } + + /// Returns `(n / divisor, n % divisor)`, or `None` for `i256::MIN / -1` + /// + /// # Example + /// ``` + /// # use arrow_buffer::{i256, DivisorI256}; + /// let DivisorI256::PowerOfTwo(divisor) = DivisorI256::new(i256::from_i128(-8)).unwrap() else { unreachable!() }; + /// let qr = divisor.checked_div_rem(i256::from_i128(-100)); + /// assert_eq!(qr, Some((i256::from_i128(12), i256::from_i128(-4)))); + /// + /// let DivisorI256::PowerOfTwo(minus_one) = DivisorI256::new(i256::MINUS_ONE).unwrap() else { unreachable!() }; + /// assert_eq!(minus_one.checked_div_rem(i256::MIN), None); + /// ``` + #[inline] + pub fn checked_div_rem(self, n: i256) -> Option<(i256, i256)> { + // -1 is the only divisor with a negative sign and a zero mask + if n == i256::MIN && self.sign == i256::MINUS_ONE && self.mask == i256::ZERO { + None + } else { + Some(self.wrapping_div_rem(n)) + } + } +} + +/// An `i256` divisor whose magnitude isn't a power of two, see [`DivisorI256`] +/// +/// It uses the signed multiplier from figure 5.1 of +/// [Granlund and Montgomery, "Division by Invariant Integers using Multiplication" (1994)](https://gmplib.org/~tege/divcnst-pldi94.pdf), +/// as [`AddIndicatorDivisorI64`] does. +#[derive(Debug, Clone, Copy)] +pub struct AddIndicatorDivisorI256 { + divisor: i256, + /// `m'` in figure 5.1 + multiplier: i256, + /// `sh_post` in figure 5.1, below 255, so it fits the `u8` that `i256` shifts by + shift: u8, +} + +impl AddIndicatorDivisorI256 { + /// `|divisor|` must be at least 3 and not a power of two + fn new(divisor: i256) -> Self { + let magnitude = divisor.wrapping_abs(); + // ceil(log2(|divisor|)), between 2 and 255 + let l = 256 - magnitude.wrapping_sub(i256::ONE).leading_zeros(); + // m = 1 + floor(2^(255 + l) / |divisor|) is between 2^255 and 2^256, so its bits fit in + // an `i256`, and they are the bits of m - 2^256 + let bit = 255 + l as usize; + let mut pow = [0u64; 8]; + pow[bit / 64] = 1 << (bit % 64); + let [d0, d1, d2, d3] = magnitude.as_digits(); + let ([q0, q1, q2, q3, ..], _) = div_rem(&pow, &[d0, d1, d2, d3, 0, 0, 0, 0]); + let q = i256::from_digits([q0, q1, q2, q3]); + Self { + divisor, + multiplier: q.wrapping_add(i256::ONE), + // `l` is at most 255 + shift: (l - 1) as u8, + } + } + + /// Returns `(n / divisor, n % divisor)`, which can't overflow + /// + /// # Example + /// ``` + /// # use arrow_buffer::{i256, DivisorI256}; + /// let DivisorI256::AddIndicator(divisor) = DivisorI256::new(i256::from_i128(-7)).unwrap() else { unreachable!() }; + /// let (q, r) = divisor.wrapping_div_rem(i256::from_i128(-100)); + /// assert_eq!((q, r), (i256::from_i128(14), i256::from_i128(-2))); + /// ``` + // At `#[inline]`, LLVM calls this out of line for each value, without LTO and with thin or + // fat LTO, at 16 codegen units and at 1 + #[inline(always)] + pub fn wrapping_div_rem(self, n: i256) -> (i256, i256) { + // `n + MULSH(m', n)` from figure 5.1, computed as `MULUH(m', n) - AND(m', XSIGN(n))`, + // because `m'` is negative. See the identity in section 3 and `DivisorI128` + let high = mul_high_u256(self.multiplier, n).wrapping_sub(n.sign_mask() & self.multiplier); + // The shift rounds down, and subtracting the sign of `n` rounds toward zero instead + let q = (high >> self.shift).wrapping_sub(n.sign_mask()); + let divisor_sign = self.divisor.sign_mask(); + // Figure 5.1 gives only the quotient. The remainder doesn't depend on the sign of the + // divisor, as section 3.1 of Lemire, Kaser and Kurz, "Faster Remainder by Direct + // Computation", https://arxiv.org/abs/1902.01961, states, so it uses `q` before the sign + // fix and `|divisor|`, which saves negating `q` before the multiply. `divisor` is never + // `MIN`, whose magnitude is a power of two + let magnitude = (self.divisor ^ divisor_sign).wrapping_sub(divisor_sign); + ( + (q ^ divisor_sign).wrapping_sub(divisor_sign), + n.wrapping_sub(q.wrapping_mul(magnitude)), + ) + } +} n_bit_divisor!( /// A `u32` divisor whose rounded-up multiplier isn't exact in N bits, see [`DivisorU32`] @@ -567,16 +931,18 @@ mod tests { let mut rng = StdRng::seed_from_u64(42); let bits = <$t>::BITS; - let mut magnitudes: Vec<$t> = (1..=1000).collect(); - for k in 0..bits - 1 { - let p: $t = 1 << k; - magnitudes.extend([p, p - 1, p + 1]); - } + // Every power of two and ten. Each side of them includes the 64-bit limbs of the + // multiply, the edges of the narrower types a kernel may divide in instead, and + // the largest values of each decimal precision + let mut edges: Vec<$t> = (0..bits - 1).map(|k| 1 << k).collect(); let mut p: $t = 10; while let Some(next) = p.checked_mul(10) { - magnitudes.extend([p - 1, p, p + 1]); + edges.push(p); p = next; } + + let mut magnitudes: Vec<$t> = (1..=1000).collect(); + magnitudes.extend(edges.iter().flat_map(|&p| [p - 1, p, p + 1])); magnitudes.extend( (0..200).map(|_| (rng.random::<$u>() >> rng.random_range(1..bits)) as $t), ); @@ -586,6 +952,11 @@ mod tests { divisors.retain(|d| *d != 0); let mut values: Vec<$t> = vec![0, 1, -1, <$t>::MIN, <$t>::MAX, <$t>::MIN + 1]; + values.extend( + edges + .iter() + .flat_map(|&p| [p - 1, p, p + 1, 1 - p, -p, -p - 1]), + ); values.extend((0..200).flat_map(|_| { let v = (rng.random::<$u>() >> rng.random_range(1..bits)) as $t; [v, -v] @@ -625,6 +996,93 @@ mod tests { test_unsigned!(test_divisor_u64, DivisorU64, u64); test_signed!(test_divisor_i32, DivisorI32, i32, u32); test_signed!(test_divisor_i64, DivisorI64, i64, u64); + test_signed!(test_divisor_i128, DivisorI128, i128, u128); + + /// `test_signed!` for `i256`, which has no unsigned type for magnitudes and no literals + #[test] + #[cfg_attr(miri, ignore)] // Takes too long + fn test_divisor_i256() { + let mut rng = StdRng::seed_from_u64(42); + let one = i256::ONE; + // A non-negative value with a random number of significant bits + let mut random = || { + let v = i256::from_parts(rng.random(), rng.random::<i128>() & i128::MAX); + v >> rng.random_range(1..=254u8) + }; + + let mut edges: Vec<i256> = (0..255u8).map(|k| one << k).collect(); + let ten = i256::from_i128(10); + let mut p = ten; + while let Some(next) = p.checked_mul(ten) { + edges.push(p); + p = next; + } + + let mut magnitudes: Vec<i256> = (1..=1000).map(i256::from_i128).collect(); + magnitudes.extend(edges.iter().flat_map(|&p| [p - one, p, p + one])); + magnitudes.extend((0..200).map(|_| random())); + + let mut divisors: Vec<i256> = magnitudes.iter().flat_map(|d| [*d, -*d]).collect(); + divisors.extend([i256::MIN, i256::MAX, i256::MINUS_ONE, one]); + divisors.retain(|d| *d != i256::ZERO); + + let mut values = vec![ + i256::ZERO, + one, + i256::MINUS_ONE, + i256::MIN, + i256::MAX, + i256::MIN + one, + ]; + values.extend( + edges + .iter() + .flat_map(|&p| [p - one, p, p + one, one - p, -p, -p - one]), + ); + values.extend((0..200).flat_map(|_| { + let v = random(); + [v, -v] + })); + + assert!(DivisorI256::new(i256::ZERO).is_none()); + for d in divisors { + let divisor = DivisorI256::new(d).unwrap(); + // `wrapping_abs` leaves `MIN` as it is, and `MIN & MAX` is zero + let ad = d.wrapping_abs(); + let power_of_two = ad & ad.wrapping_sub(one) == i256::ZERO; + assert_eq!( + matches!(divisor, DivisorI256::PowerOfTwo(_)), + power_of_two, + "{d}" + ); + // The ends of the last quotient steps on each side of zero, as in `test_signed!` + let top = i256::MAX.wrapping_div(d).wrapping_mul(d); + let bottom = i256::MIN.wrapping_div(d).wrapping_mul(d); + let ends = [ + top, + top.wrapping_sub(one), + top.wrapping_sub(ad), + bottom, + bottom.wrapping_add(one), + bottom.wrapping_add(ad), + ]; + let near = [ + d.wrapping_sub(one), + d, + d.wrapping_add(one), + d.wrapping_mul(i256::from_i128(7)), + ]; + for &n in values.iter().chain(&near).chain(&ends) { + let expected = n.wrapping_div_rem(d); + assert_eq!(divisor.wrapping_div_rem(n), expected, "{n} / {d}"); + assert_eq!( + divisor.checked_div_rem(n), + n.checked_div_rem(d), + "{n} / {d}" + ); + } + } + } /// Checks which variant `new` picks: `Up` when theorem 4.2 holds at `p = floor(log2(d))`, /// otherwise `Down` when `$down` is true, otherwise `AddIndicator`. `$is_down` checks for `Down`, @@ -751,6 +1209,32 @@ mod tests { matches!(DivisorI64::new(d).unwrap(), DivisorI64::AddIndicator(_)), "{d}" ); + let d = d as i128; + assert!( + matches!(DivisorI128::new(d).unwrap(), DivisorI128::AddIndicator(_)), + "{d}" + ); + let d = i256::from_i128(d); + assert!( + matches!(DivisorI256::new(d).unwrap(), DivisorI256::AddIndicator(_)), + "{d}" + ); + } + for d in [i128::MAX, i128::MIN + 1, 10i128.pow(38), -(10i128.pow(18))] { + assert!( + matches!(DivisorI128::new(d).unwrap(), DivisorI128::AddIndicator(_)), + "{d}" + ); + } + for d in [ + i256::MAX, + i256::MIN + i256::ONE, + i256::from_i128(10).wrapping_pow(76), + ] { + assert!( + matches!(DivisorI256::new(d).unwrap(), DivisorI256::AddIndicator(_)), + "{d}" + ); } }
