-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathdiv_limb.rs
More file actions
369 lines (312 loc) · 13.8 KB
/
div_limb.rs
File metadata and controls
369 lines (312 loc) · 13.8 KB
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
//! Implementation of constant-time division via reciprocal precomputation, as described in
//! "Improved Division by Invariant Integers" by Niels Möller and Torbjorn Granlund
//! (DOI: 10.1109/TC.2010.143, <https://gmplib.org/~tege/division-paper.pdf>).
use crate::{
Choice, CtSelect, Limb, NonZero, Uint, WideWord, Word, primitives::widening_mul, word,
};
cpubits::cpubits! {
32 => {
/// Calculates the reciprocal of the given 32-bit divisor with the highmost bit set.
///
/// This method corresponds to Algorithm 3
pub const fn reciprocal(d: Word) -> Word {
debug_assert!(d >= (1 << (Word::BITS - 1)));
let d0 = d & 1;
let d10 = d >> 22;
let d21 = (d >> 11) + 1;
let d31 = (d >> 1) + d0;
let v0 = short_div((1 << 24) - (1 << 14) + (1 << 9), 24, d10, 10);
let (_lo, hi) = widening_mul(v0 * v0, d21);
let v1 = (v0 << 4) - hi - 1;
// Checks that the expression for `e` can be simplified in the way we did below.
debug_assert!(widening_mul(v1, d31).1 == (1 << 16) - 1);
let e = Word::MAX - v1.wrapping_mul(d31) + 1 + (v1 >> 1) * d0;
let (_lo, hi) = widening_mul(v1, e);
// Note: the paper does not mention a wrapping add here,
// but the 64-bit version has it at this stage, and the function panics without it
// when calculating a reciprocal for `Word::MAX`.
let v2 = (v1 << 15).wrapping_add(hi >> 1);
// The paper has `(v2 + 1) * d / 2^32` (there's another 2^32, but it's accounted for later).
// If `v2 == 2^32-1` this should give `d`, but we can't achieve this in our wrapping arithmetic.
// Hence the `word::select()`.
let x = v2.wrapping_add(1);
let (_lo, hi) = widening_mul(x, d);
let hi = word::select(d, hi, Choice::from_u32_nz(x));
v2.wrapping_sub(hi).wrapping_sub(d)
}
}
64 => {
/// Calculates the reciprocal of the given 64-bit divisor with the highmost bit set.
///
/// This method corresponds to Algorithm 2
pub const fn reciprocal(d: Word) -> Word {
debug_assert!(d >= (1 << (Word::BITS - 1)));
let d0 = d & 1;
let d9 = d >> 55;
let d40 = (d >> 24) + 1;
let d63 = (d >> 1) + d0;
let v0 = short_div((1 << 19) - 3 * (1 << 8), 19, d9 as u32, 9) as u64;
let v1 = (v0 << 11) - ((v0 * v0 * d40) >> 40) - 1;
let v2 = (v1 << 13) + ((v1 * ((1 << 60) - v1 * d40)) >> 47);
// Checks that the expression for `e` can be simplified in the way we did below.
debug_assert!(widening_mul(v2, d63).1 == (1 << 32) - 1);
let e = Word::MAX - v2.wrapping_mul(d63) + 1 + (v2 >> 1) * d0;
let (_lo, hi) = widening_mul(v2, e);
let v3 = (v2 << 31).wrapping_add(hi >> 1);
// The paper has `(v3 + 1) * d / 2^64` (there's another 2^64, but it's accounted for later).
// If `v3 == 2^64-1` this should give `d`, but we can't achieve this in our wrapping arithmetic.
// Hence the `word::select()`.
let x = v3.wrapping_add(1);
let (_lo, hi) = widening_mul(x, d);
let hi = word::select(d, hi, word::choice_from_nz(x));
v3.wrapping_sub(hi).wrapping_sub(d)
}
}
}
/// Calculates `dividend / divisor`, given `dividend` and `divisor`
/// along with their maximum bitsizes.
#[inline(always)]
const fn short_div(mut dividend: u32, dividend_bits: u32, divisor: u32, divisor_bits: u32) -> u32 {
// TODO: this may be sped up even more using the fact that `dividend` is a known constant.
// In the paper this is a table lookup, but since we want it to be constant-time,
// we have to access all the elements of the table, which is quite large.
// So this shift-and-subtract approach is actually faster.
// Passing `dividend_bits` and `divisor_bits` because calling `.leading_zeros()`
// causes a significant slowdown, and we know those values anyway.
let mut divisor = divisor << (dividend_bits - divisor_bits);
let mut quotient: u32 = 0;
let mut i = dividend_bits - divisor_bits + 1;
while i > 0 {
i -= 1;
let bit = Choice::from_u32_lt(dividend, divisor);
dividend = bit.select_u32(dividend.wrapping_sub(divisor), dividend);
divisor >>= 1;
quotient |= bit.not().select_u32(0, 1 << i);
}
quotient
}
/// Calculate the quotient and the remainder of the division of a wide word
/// (supplied as high and low words) by `d`, with a precalculated reciprocal `v`.
///
/// This method corresponds to Algorithm 4
#[inline(always)]
pub(crate) const fn div2by1(u0: Word, u1: Word, reciprocal: &Reciprocal) -> (Word, Word) {
let d = reciprocal.divisor_normalized;
let v = reciprocal.reciprocal;
debug_assert!(d >= (1 << (Word::BITS - 1)), "divisor top bit unset");
debug_assert!(u1 < d, "dividend >= divisor");
let q = (v as WideWord * u1 as WideWord) + word::join(u0, u1);
let (q0, q1) = word::split_wide(q);
let q1 = q1.wrapping_add(1);
let r = u0.wrapping_sub(q1.wrapping_mul(d));
let r_gt_q0 = word::choice_from_lt(q0, r);
let q1 = word::select(q1, q1.wrapping_sub(1), r_gt_q0);
let r = word::select(r, r.wrapping_add(d), r_gt_q0);
// If this was a normal `if`, we wouldn't need wrapping ops, because there would be no overflow.
// But since we calculate both results either way, we have to wrap.
// Added an assert to still check the lack of overflow in debug mode.
debug_assert!(r < d || q1 < Word::MAX);
let r_ge_d = word::choice_from_le(d, r);
let q1 = word::select(q1, q1.wrapping_add(1), r_ge_d);
let r = word::select(r, r.wrapping_sub(d), r_ge_d);
(q1, r)
}
/// Given two long integers `u = (..., u0, u1, u2)` and `v = (..., v0, v1)`
/// (where `u2` and `v1` are the most significant limbs), where `floor(u / v) <= Limb::MAX`,
/// calculates `q` such that `q - 1 <= floor(u / v) <= q`.
/// In place of `v1` takes its reciprocal, and assumes that `v` was already pre-shifted
/// so that v1 has its most significant bit set (that is, the reciprocal's `shift` is 0).
///
// This method corresponds to Algorithm 5
#[inline(always)]
#[allow(clippy::cast_possible_truncation)]
pub(crate) const fn div3by2(
(u0, u1, u2): (Word, Word, Word),
(d0, d1): (Word, Word),
v: Word,
) -> (Word, WideWord) {
let d = word::join(d0, d1);
let u_hi = word::join(u1, u2);
debug_assert!(d >= (1 << (WideWord::BITS - 1)), "divisor top bit unset");
debug_assert!(u_hi <= d, "dividend > divisor");
let q = (v as WideWord * u2 as WideWord) + u_hi;
let q1w = q >> Word::BITS;
let r1 = u1.wrapping_sub((q1w as Word).wrapping_mul(d1));
let t = d0 as WideWord * q1w;
let r = word::join(u0, r1).wrapping_sub(t).wrapping_sub(d);
let r1_ge_q0 = word::choice_from_le(q as Word, (r >> Word::BITS) as Word);
let q1 = q1w as Word;
let q1 = word::select(q1.wrapping_add(1), q1, r1_ge_q0);
let r = word::select_wide(r, r.wrapping_add(d), r1_ge_q0);
let r_ge_d = word::choice_from_wide_le(d, r);
let q1 = word::select(q1, q1.wrapping_add(1), r_ge_d);
let r = word::select_wide(r, r.wrapping_sub(d), r_ge_d);
// When the leading dividend word equals the leading divisor word, cap the quotient
// at WideWord::MAX and update the remainder. This differs from the original algorithm
// but is required for multi-word division.
let maxed = word::choice_from_wide_eq(u_hi, d);
let q1 = word::select(q1, Word::MAX, maxed);
let r = word::select_wide(r, d.saturating_add(u0 as WideWord), maxed);
(q1, r)
}
/// A pre-calculated reciprocal for division by a single limb.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Reciprocal {
divisor_normalized: Word,
shift: u32,
reciprocal: Word,
}
impl Reciprocal {
/// Pre-calculates a reciprocal for a known divisor,
/// to be used in the single-limb division later.
#[must_use]
pub const fn new(divisor: NonZero<Limb>) -> Self {
let divisor = divisor.get_copy();
// Assuming this is constant-time for primitive types.
let shift = divisor.0.leading_zeros();
// Will not panic since divisor is non-zero
let divisor_normalized = divisor.0 << shift;
Self {
divisor_normalized,
shift,
reciprocal: reciprocal(divisor_normalized),
}
}
/// Returns a default instance of this object.
/// It is a self-consistent `Reciprocal` that will not cause panics in functions that take it.
///
/// NOTE: intended for using it as a placeholder during compile-time array generation,
/// don't rely on the contents.
#[must_use]
pub const fn default() -> Self {
Self {
divisor_normalized: Word::MAX,
shift: 0,
// The result of calling `reciprocal(Word::MAX)`
// This holds both for 32- and 64-bit versions.
reciprocal: 1,
}
}
/// Get the shift value
#[must_use]
pub const fn shift(&self) -> u32 {
self.shift
}
/// Adjusted reciprocal for 3x2 division
///
/// This method corresponds to Algorithm 6
#[must_use]
pub const fn reciprocal_3by2(&self, d0: Word, d1: Word) -> Word {
debug_assert!(self.shift == 0 && d1 == self.divisor_normalized);
let v = self.reciprocal;
let p = d1.wrapping_mul(v).wrapping_add(d0);
let p_lt_d0 = word::choice_from_lt(p, d0);
let v = word::select(v, v.wrapping_sub(1), p_lt_d0);
let p_ge_d1 = word::choice_from_le(d1, p).and(p_lt_d0);
let v = word::select(v, v.wrapping_sub(1), p_ge_d1);
let p = word::select(p, p.wrapping_sub(d1), p_ge_d1);
let p = word::select(p, p.wrapping_sub(d1), p_lt_d0);
let (t0, t1) = widening_mul(v, d0);
let p = p.wrapping_add(t1);
let p_lt_t1 = word::choice_from_lt(p, t1);
let v = word::select(v, v.wrapping_sub(1), p_lt_t1);
let d = word::join(d0, d1);
let t0p = word::join(t0, p);
let t0p_ge_d = word::choice_from_wide_le(d, t0p).and(p_lt_t1);
word::select(v, v.wrapping_sub(1), t0p_ge_d)
}
}
impl CtSelect for Reciprocal {
fn ct_select(&self, other: &Self, choice: Choice) -> Self {
Self {
divisor_normalized: Word::ct_select(
&self.divisor_normalized,
&other.divisor_normalized,
choice,
),
shift: u32::ct_select(&self.shift, &other.shift, choice),
reciprocal: Word::ct_select(&self.reciprocal, &other.reciprocal, choice),
}
}
}
// `CtOption.map()` needs this; for some reason it doesn't use the value it already has
// for the `None` branch.
impl Default for Reciprocal {
fn default() -> Self {
Self::default()
}
}
/// Divides `u` by the divisor encoded in the `reciprocal`, and returns the remainder.
#[inline(always)]
pub(crate) const fn rem_limb_with_reciprocal<const L: usize>(
u: &Uint<L>,
reciprocal: &Reciprocal,
) -> Limb {
let (u_shifted, u_hi) = u.shl_limb_with_carry(reciprocal.shift, Limb::ZERO);
let mut r = u_hi.0;
let mut j = L;
while j > 0 {
j -= 1;
let (_, rj) = div2by1(u_shifted.as_limbs()[j].0, r, reciprocal);
r = rj;
}
Limb(r >> reciprocal.shift)
}
/// Computes `(a * b) % d`.
#[inline(always)]
pub(crate) const fn mul_rem(a: Limb, b: Limb, d: NonZero<Limb>) -> Limb {
let rec = Reciprocal::new(d);
let (lo, hi) = widening_mul(a.0, b.0);
rem_limb_with_reciprocal(&Uint::from_words([lo, hi]), &rec)
}
#[cfg(test)]
mod tests {
use super::{Reciprocal, div2by1, reciprocal};
use crate::{Limb, NonZero, Uint, WideWord, Word, word};
#[test]
fn reciprocal_valid() {
#![allow(clippy::integer_division_remainder_used, reason = "test")]
fn test(d: Word) {
let v = reciprocal(d);
// the reciprocal must be equal to floor((β^2 - 1) / d) - β
// v = floor((β^2 - 1) / d) - β = floor((β - 1 - d)*β + β - 1>/d)
let expected = WideWord::MAX / WideWord::from(d) - WideWord::from(Word::MAX) - 1;
assert_eq!(WideWord::from(v), expected);
}
test(Word::MAX);
test(1 << (Word::BITS - 1));
test((1 << (Word::BITS - 1)) | 1);
}
#[test]
fn reciprocal_3by2_valid() {
fn test(d: WideWord) {
let (d0, d1) = word::split_wide(d);
let v0 = Reciprocal::new(NonZero::<Limb>::new_unwrap(Limb(d1)));
let v = v0.reciprocal_3by2(d0, d1);
// the reciprocal must be equal to v = floor((β^3 − 1)/d) − β
// (β^3 − βd - 1)/d - 1 < v <= (β^3 − βd - 1)/d
// β^3 − βd - 1 - d < v*d <= β^3 − βd - 1
// β^3-1 - d < (v+β)d <= β^3-1
let actual = (Uint::<3>::from_word(v)
+ Uint::<3>::ZERO.set_bit_vartime(Word::BITS, true))
.checked_mul(&Uint::<3>::from_wide_word(d))
.expect("overflow");
let min = Uint::<3>::MAX - Uint::<3>::from_wide_word(d);
assert!(actual > min, "{actual} <= {min}");
}
test(WideWord::MAX);
test(1 << (WideWord::BITS - 1));
test((1 << (WideWord::BITS - 1)) | 1);
}
#[test]
fn div2by1_overflow() {
// A regression test for a situation when in div2by1() an operation (`q1 + 1`)
// that is protected from overflowing by a condition in the original paper (`r >= d`)
// still overflows because we're calculating the results for both branches.
let r = Reciprocal::new(NonZero::new(Limb(Word::MAX - 1)).unwrap());
assert_eq!(
div2by1(Word::MAX - 63, Word::MAX - 2, &r),
(Word::MAX, Word::MAX - 65)
);
}
}