miden-crypto/src/hash/rescue/arch/x86_64_avx2.rs
src/hash/rescue/arch/x86_64_avx2.rsRaw
1use core::arch::x86_64::*;
2
3// The following AVX2 implementation has been copied from plonky2:
4// https://github.com/0xPolygonZero/plonky2/blob/main/plonky2/src/hash/arch/x86_64/poseidon_goldilocks_avx2_bmi2.rs
5
6// Preliminary notes:
7// 1. AVX does not support addition with carry but 128-bit (2-word) addition can be easily emulated.
8// The method recognizes that for a + b overflowed iff (a + b) < a: i. res_lo = a_lo + b_lo ii.
9// carry_mask = res_lo < a_lo iii. res_hi = a_hi + b_hi - carry_mask Notice that carry_mask is
10// subtracted, not added. This is because AVX comparison instructions return -1 (all bits 1) for
11// true and 0 for false.
12//
13// 2. AVX does not have unsigned 64-bit comparisons. Those can be emulated with signed comparisons
14// by recognizing that a <u b iff a + (1 << 63) <s b + (1 << 63), where the addition wraps around
15// and the comparisons are unsigned and signed respectively. The shift function adds/subtracts 1
16// << 63 to enable this trick. Example: addition with carry. i. a_lo_s = shift(a_lo) ii. res_lo_s
17// = a_lo_s + b_lo iii. carry_mask = res_lo_s <s a_lo_s iv. res_lo = shift(res_lo_s) v. res_hi =
18// a_hi + b_hi - carry_mask The suffix _s denotes a value that has been shifted by 1 << 63. The
19// result of addition is shifted if exactly one of the operands is shifted, as is the case on
20// line ii. Line iii. performs a signed comparison res_lo_s <s a_lo_s on shifted values to
21// emulate unsigned comparison res_lo <u a_lo on unshifted values. Finally, line iv. reverses the
22// shift so the result can be returned. When performing a chain of calculations, we can often
23// save instructions by letting the shift propagate through and only undoing it when necessary.
24// For example, to compute the addition of three two-word (128-bit) numbers we can do: i. a_lo_s
25// = shift(a_lo) ii. tmp_lo_s = a_lo_s + b_lo iii. tmp_carry_mask = tmp_lo_s <s a_lo_s iv. tmp_hi
26// = a_hi + b_hi - tmp_carry_mask v. res_lo_s = tmp_lo_s + c_lo vi. res_carry_mask = res_lo_s <s
27// tmp_lo_s vii. res_lo = shift(res_lo_s) viii. res_hi = tmp_hi + c_hi - res_carry_mask Notice
28// that the above 3-value addition still only requires two calls to shift, just like our 2-value
29// addition.
30
31#[inline(always)]
32pub fn branch_hint() {
33 // NOTE: These are the currently supported assembly architectures. See the
34 // [nightly reference](https://doc.rust-lang.org/nightly/reference/inline-assembly.html) for
35 // the most up-to-date list.
36 #[cfg(any(
37 target_arch = "aarch64",
38 target_arch = "arm",
39 target_arch = "riscv32",
40 target_arch = "riscv64",
41 target_arch = "x86",
42 target_arch = "x86_64",
43 ))]
44 unsafe {
45 core::arch::asm!("", options(nomem, nostack, preserves_flags));
46 }
47}
48
49macro_rules! map3 {
50 ($f:ident:: < $l:literal > , $v:ident) => {
51 ($f::<$l>($v.0), $f::<$l>($v.1), $f::<$l>($v.2))
52 };
53 ($f:ident:: < $l:literal > , $v1:ident, $v2:ident) => {
54 ($f::<$l>($v1.0, $v2.0), $f::<$l>($v1.1, $v2.1), $f::<$l>($v1.2, $v2.2))
55 };
56 ($f:ident, $v:ident) => {
57 ($f($v.0), $f($v.1), $f($v.2))
58 };
59 ($f:ident, $v0:ident, $v1:ident) => {
60 ($f($v0.0, $v1.0), $f($v0.1, $v1.1), $f($v0.2, $v1.2))
61 };
62 ($f:ident,rep $v0:ident, $v1:ident) => {
63 ($f($v0, $v1.0), $f($v0, $v1.1), $f($v0, $v1.2))
64 };
65
66 ($f:ident, $v0:ident,rep $v1:ident) => {
67 ($f($v0.0, $v1), $f($v0.1, $v1), $f($v0.2, $v1))
68 };
69}
70
71#[inline(always)]
72unsafe fn square3(
73 x: (__m256i, __m256i, __m256i),
74) -> ((__m256i, __m256i, __m256i), (__m256i, __m256i, __m256i)) {
75 let x_hi = {
76 // Move high bits to low position. The high bits of x_hi are ignored. Swizzle is faster than
77 // bitshift. This instruction only has a floating-point flavor, so we cast to/from float.
78 // This is safe and free.
79 let x_ps = map3!(_mm256_castsi256_ps, x);
80 let x_hi_ps = map3!(_mm256_movehdup_ps, x_ps);
81 map3!(_mm256_castps_si256, x_hi_ps)
82 };
83
84 // All pairwise multiplications.
85 let mul_ll = map3!(_mm256_mul_epu32, x, x);
86 let mul_lh = map3!(_mm256_mul_epu32, x, x_hi);
87 let mul_hh = map3!(_mm256_mul_epu32, x_hi, x_hi);
88
89 // Bignum addition, but mul_lh is shifted by 33 bits (not 32).
90 let mul_ll_hi = map3!(_mm256_srli_epi64::<33>, mul_ll);
91 let t0 = map3!(_mm256_add_epi64, mul_lh, mul_ll_hi);
92 let t0_hi = map3!(_mm256_srli_epi64::<31>, t0);
93 let res_hi = map3!(_mm256_add_epi64, mul_hh, t0_hi);
94
95 // Form low result by adding the mul_ll and the low 31 bits of mul_lh (shifted to the high
96 // position).
97 let mul_lh_lo = map3!(_mm256_slli_epi64::<33>, mul_lh);
98 let res_lo = map3!(_mm256_add_epi64, mul_ll, mul_lh_lo);
99
100 (res_lo, res_hi)
101}
102
103#[inline(always)]
104unsafe fn mul3(
105 x: (__m256i, __m256i, __m256i),
106 y: (__m256i, __m256i, __m256i),
107) -> ((__m256i, __m256i, __m256i), (__m256i, __m256i, __m256i)) {
108 let epsilon = _mm256_set1_epi64x(0xffffffff);
109 let x_hi = {
110 // Move high bits to low position. The high bits of x_hi are ignored. Swizzle is faster than
111 // bitshift. This instruction only has a floating-point flavor, so we cast to/from float.
112 // This is safe and free.
113 let x_ps = map3!(_mm256_castsi256_ps, x);
114 let x_hi_ps = map3!(_mm256_movehdup_ps, x_ps);
115 map3!(_mm256_castps_si256, x_hi_ps)
116 };
117 let y_hi = {
118 let y_ps = map3!(_mm256_castsi256_ps, y);
119 let y_hi_ps = map3!(_mm256_movehdup_ps, y_ps);
120 map3!(_mm256_castps_si256, y_hi_ps)
121 };
122
123 // All four pairwise multiplications
124 let mul_ll = map3!(_mm256_mul_epu32, x, y);
125 let mul_lh = map3!(_mm256_mul_epu32, x, y_hi);
126 let mul_hl = map3!(_mm256_mul_epu32, x_hi, y);
127 let mul_hh = map3!(_mm256_mul_epu32, x_hi, y_hi);
128
129 // Bignum addition
130 // Extract high 32 bits of mul_ll and add to mul_hl. This cannot overflow.
131 let mul_ll_hi = map3!(_mm256_srli_epi64::<32>, mul_ll);
132 let t0 = map3!(_mm256_add_epi64, mul_hl, mul_ll_hi);
133 // Extract low 32 bits of t0 and add to mul_lh. Again, this cannot overflow.
134 // Also, extract high 32 bits of t0 and add to mul_hh.
135 let t0_lo = map3!(_mm256_and_si256, t0, rep epsilon);
136 let t0_hi = map3!(_mm256_srli_epi64::<32>, t0);
137 let t1 = map3!(_mm256_add_epi64, mul_lh, t0_lo);
138 let t2 = map3!(_mm256_add_epi64, mul_hh, t0_hi);
139 // Lastly, extract the high 32 bits of t1 and add to t2.
140 let t1_hi = map3!(_mm256_srli_epi64::<32>, t1);
141 let res_hi = map3!(_mm256_add_epi64, t2, t1_hi);
142
143 // Form res_lo by combining the low half of mul_ll with the low half of t1 (shifted into high
144 // position).
145 let t1_lo = {
146 let t1_ps = map3!(_mm256_castsi256_ps, t1);
147 let t1_lo_ps = map3!(_mm256_moveldup_ps, t1_ps);
148 map3!(_mm256_castps_si256, t1_lo_ps)
149 };
150 let res_lo = map3!(_mm256_blend_epi32::<0xaa>, mul_ll, t1_lo);
151
152 (res_lo, res_hi)
153}
154
155/// Addition, where the second operand is `0 <= y < 0xffffffff00000001`.
156#[inline(always)]
157unsafe fn add_small(
158 x_s: (__m256i, __m256i, __m256i),
159 y: (__m256i, __m256i, __m256i),
160) -> (__m256i, __m256i, __m256i) {
161 let res_wrapped_s = map3!(_mm256_add_epi64, x_s, y);
162 let mask = map3!(_mm256_cmpgt_epi32, x_s, res_wrapped_s);
163 let wrapback_amt = map3!(_mm256_srli_epi64::<32>, mask); // EPSILON if overflowed else 0.
164 let res_s = map3!(_mm256_add_epi64, res_wrapped_s, wrapback_amt);
165 res_s
166}
167
168#[inline(always)]
169unsafe fn maybe_adj_sub(res_wrapped_s: __m256i, mask: __m256i) -> __m256i {
170 // The subtraction is very unlikely to overflow so we're best off branching.
171 // The even u32s in `mask` are meaningless, so we want to ignore them. `_mm256_testz_pd`
172 // branches depending on the sign bit of double-precision (64-bit) floats. Bit cast `mask` to
173 // floating-point (this is free).
174 let mask_pd = _mm256_castsi256_pd(mask);
175 // `_mm256_testz_pd(mask_pd, mask_pd) == 1` iff all sign bits are 0, meaning that underflow
176 // did not occur for any of the vector elements.
177 if _mm256_testz_pd(mask_pd, mask_pd) == 1 {
178 res_wrapped_s
179 } else {
180 branch_hint();
181 // Highly unlikely: underflow did occur. Find adjustment per element and apply it.
182 let adj_amount = _mm256_srli_epi64::<32>(mask); // EPSILON if underflow.
183 _mm256_sub_epi64(res_wrapped_s, adj_amount)
184 }
185}
186
187/// Addition, where the second operand is much smaller than `0xffffffff00000001`.
188#[inline(always)]
189unsafe fn sub_tiny(
190 x_s: (__m256i, __m256i, __m256i),
191 y: (__m256i, __m256i, __m256i),
192) -> (__m256i, __m256i, __m256i) {
193 let res_wrapped_s = map3!(_mm256_sub_epi64, x_s, y);
194 let mask = map3!(_mm256_cmpgt_epi32, res_wrapped_s, x_s);
195 let res_s = map3!(maybe_adj_sub, res_wrapped_s, mask);
196 res_s
197}
198
199#[inline(always)]
200unsafe fn reduce3(
201 (lo0, hi0): ((__m256i, __m256i, __m256i), (__m256i, __m256i, __m256i)),
202) -> (__m256i, __m256i, __m256i) {
203 let sign_bit = _mm256_set1_epi64x(i64::MIN);
204 let epsilon = _mm256_set1_epi64x(0xffffffff);
205 let lo0_s = map3!(_mm256_xor_si256, lo0, rep sign_bit);
206 let hi_hi0 = map3!(_mm256_srli_epi64::<32>, hi0);
207 let lo1_s = sub_tiny(lo0_s, hi_hi0);
208 let t1 = map3!(_mm256_mul_epu32, hi0, rep epsilon);
209 let lo2_s = add_small(lo1_s, t1);
210 let lo2 = map3!(_mm256_xor_si256, lo2_s, rep sign_bit);
211 lo2
212}
213
214#[inline(always)]
215unsafe fn mul_reduce(
216 a: (__m256i, __m256i, __m256i),
217 b: (__m256i, __m256i, __m256i),
218) -> (__m256i, __m256i, __m256i) {
219 reduce3(mul3(a, b))
220}
221
222#[inline(always)]
223unsafe fn square_reduce(state: (__m256i, __m256i, __m256i)) -> (__m256i, __m256i, __m256i) {
224 reduce3(square3(state))
225}
226
227#[inline(always)]
228unsafe fn exp_acc(
229 high: (__m256i, __m256i, __m256i),
230 low: (__m256i, __m256i, __m256i),
231 exp: usize,
232) -> (__m256i, __m256i, __m256i) {
233 let mut result = high;
234 for _ in 0..exp {
235 result = square_reduce(result);
236 }
237 mul_reduce(result, low)
238}
239
240#[inline(always)]
241unsafe fn do_apply_sbox(state: (__m256i, __m256i, __m256i)) -> (__m256i, __m256i, __m256i) {
242 let state2 = square_reduce(state);
243 let state4_unreduced = square3(state2);
244 let state3_unreduced = mul3(state2, state);
245 let state4 = reduce3(state4_unreduced);
246 let state3 = reduce3(state3_unreduced);
247 let state7_unreduced = mul3(state3, state4);
248 let state7 = reduce3(state7_unreduced);
249 state7
250}
251
252#[inline(always)]
253unsafe fn do_apply_inv_sbox(state: (__m256i, __m256i, __m256i)) -> (__m256i, __m256i, __m256i) {
254 // compute base^10540996611094048183 using 72 multiplications per array element
255 // 10540996611094048183 = b1001001001001001001001001001000110110110110110110110110110110111
256
257 // compute base^10
258 let t1 = square_reduce(state);
259
260 // compute base^100
261 let t2 = square_reduce(t1);
262
263 // compute base^100100
264 let t3 = exp_acc(t2, t2, 3);
265
266 // compute base^100100100100
267 let t4 = exp_acc(t3, t3, 6);
268
269 // compute base^100100100100100100100100
270 let t5 = exp_acc(t4, t4, 12);
271
272 // compute base^100100100100100100100100100100
273 let t6 = exp_acc(t5, t3, 6);
274
275 // compute base^1001001001001001001001001001000100100100100100100100100100100
276 let t7 = exp_acc(t6, t6, 31);
277
278 // compute base^1001001001001001001001001001000110110110110110110110110110110111
279 let a = square_reduce(square_reduce(mul_reduce(square_reduce(t7), t6)));
280 let b = mul_reduce(t1, mul_reduce(t2, state));
281 mul_reduce(a, b)
282}
283
284#[inline(always)]
285unsafe fn avx2_load(state: &[u64; 12]) -> (__m256i, __m256i, __m256i) {
286 (
287 _mm256_loadu_si256((&state[0..4]).as_ptr().cast::<__m256i>()),
288 _mm256_loadu_si256((&state[4..8]).as_ptr().cast::<__m256i>()),
289 _mm256_loadu_si256((&state[8..12]).as_ptr().cast::<__m256i>()),
290 )
291}
292
293#[inline(always)]
294unsafe fn avx2_store(buf: &mut [u64; 12], state: (__m256i, __m256i, __m256i)) {
295 _mm256_storeu_si256((&mut buf[0..4]).as_mut_ptr().cast::<__m256i>(), state.0);
296 _mm256_storeu_si256((&mut buf[4..8]).as_mut_ptr().cast::<__m256i>(), state.1);
297 _mm256_storeu_si256((&mut buf[8..12]).as_mut_ptr().cast::<__m256i>(), state.2);
298}
299
300#[inline(always)]
301pub unsafe fn apply_sbox(buffer: &mut [u64; 12]) {
302 let mut state = avx2_load(&buffer);
303 state = do_apply_sbox(state);
304 avx2_store(buffer, state);
305}
306
307#[inline(always)]
308pub unsafe fn apply_inv_sbox(buffer: &mut [u64; 12]) {
309 let mut state = avx2_load(&buffer);
310 state = do_apply_inv_sbox(state);
311 avx2_store(buffer, state);
312}