ed25519-simd 0.1.0

Verification-only, AVX-512 IFMA batch Ed25519 signature verification, acceptance-compatible with solana-ed25519
Documentation
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
use super::{LANES, mask_to_lanes};
use crate::edwards::POINT_ENCODING_LEN;
use crate::field::{Fe51, LIMB_COUNT};
use std::arch::x86_64::*;

const LIMB_MASK: u64 = (1u64 << 51) - 1;

/// Eight field elements packed by limb for AVX-512 IFMA arithmetic.
///
/// `limbs[0]` contains the low limb of eight independent values,
/// so one vector multiply advances eight point operations at once.
#[derive(Clone, Copy)]
pub(super) struct WideFe {
    pub(super) limbs: [__m512i; LIMB_COUNT],
}

/// Two independent SIMD field values processed as one interleaved power chain.
///
/// Alternating the squarings for two point decompressions fills
/// the IFMA latency gap that a single dependent chain would leave idle.
#[derive(Clone, Copy)]
pub(super) struct WideFePair(WideFe, WideFe);

/// Arithmetic interface shared by the single and interleaved exponentiation chains.
///
/// `WideFePair` maps each chain step over two values so their
/// independent IFMA instructions can be scheduled together.
trait PowChainValue: Copy {
    fn chain_square(self) -> Self;
    fn chain_square_repeat<const N: usize>(self) -> Self;
    fn chain_multiply(self, rhs: Self) -> Self;
}

/// The `(p-5)/8` addition chain, shared by both the single-value and
/// latency-interleaved pair implementations.
#[inline(always)]
fn pow_p_minus_5_over_8_chain<T: PowChainValue>(z: T) -> T {
    let t0 = z.chain_square();
    let t1 = t0.chain_square_repeat::<2>().chain_multiply(z);
    let t0 = t0.chain_multiply(t1);
    let t0 = t0.chain_square().chain_multiply(t1);
    let t1 = t0.chain_square_repeat::<5>();
    let t0 = t1.chain_multiply(t0);
    let t1 = t0.chain_square_repeat::<10>().chain_multiply(t0);
    let t2 = t1.chain_square_repeat::<20>();
    let t1 = t2.chain_multiply(t1);
    let t1 = t1.chain_square_repeat::<10>();
    let t0 = t1.chain_multiply(t0);
    let t1 = t0.chain_square_repeat::<50>().chain_multiply(t0);
    let t2 = t1.chain_square_repeat::<100>();
    let t1 = t2.chain_multiply(t1);
    let t1 = t1.chain_square_repeat::<50>();
    let t0 = t1.chain_multiply(t0);
    t0.chain_square_repeat::<2>().chain_multiply(z)
}
impl WideFe {
    pub(super) fn zero() -> Self {
        unsafe {
            let z = _mm512_setzero_si512();
            Self {
                limbs: [z; LIMB_COUNT],
            }
        }
    }
    pub(super) fn one() -> Self {
        unsafe {
            let z = _mm512_setzero_si512();
            Self {
                limbs: [_mm512_set1_epi64(1), z, z, z, z],
            }
        }
    }
    /// Transpose eight lanes of scalar limbs. Inlined so both entry points
    /// below cost the same as an open-coded loop.
    #[inline(always)]
    pub(super) fn from_limbs_per_lane(limbs_of: impl Fn(usize) -> [u64; LIMB_COUNT]) -> Self {
        let mut by_limb = [[0u64; LANES]; LIMB_COUNT];
        let mut lane = 0;
        while lane < LANES {
            let limbs = limbs_of(lane);
            let mut limb = 0;
            while limb < LIMB_COUNT {
                by_limb[limb][lane] = limbs[limb];
                limb += 1;
            }
            lane += 1;
        }

        Self {
            limbs: [
                loadu(by_limb[0]),
                loadu(by_limb[1]),
                loadu(by_limb[2]),
                loadu(by_limb[3]),
                loadu(by_limb[4]),
            ],
        }
    }
    pub(super) fn from_fields(fields: &[Fe51; LANES]) -> Self {
        Self::from_limbs_per_lane(|lane| fields[lane].loose_limbs())
    }
    pub(super) fn from_field_refs(fields: &[&Fe51; LANES]) -> Self {
        Self::from_limbs_per_lane(|lane| fields[lane].loose_limbs())
    }
    pub(super) fn lane0(self) -> Fe51 {
        unsafe {
            Fe51::from_limbs_unchecked(core::array::from_fn(|i| {
                _mm_cvtsi128_si64(_mm512_castsi512_si128(self.limbs[i])) as u64
            }))
        }
    }
    /// Like `to_fields` but stores loosely-reduced limbs (no canonicalize);
    /// valid because a reduce leaves each limb `< 2^52`.
    pub(super) fn to_fields_loose(self) -> [Fe51; LANES] {
        let mut by_limb = [[0u64; LANES]; LIMB_COUNT];
        storeu(self.limbs[0], &mut by_limb[0]);
        storeu(self.limbs[1], &mut by_limb[1]);
        storeu(self.limbs[2], &mut by_limb[2]);
        storeu(self.limbs[3], &mut by_limb[3]);
        storeu(self.limbs[4], &mut by_limb[4]);

        core::array::from_fn(|lane| {
            Fe51::from_limbs_unchecked([
                by_limb[0][lane],
                by_limb[1][lane],
                by_limb[2][lane],
                by_limb[3][lane],
                by_limb[4][lane],
            ])
        })
    }
    pub(super) fn to_bytes_lanes(self) -> [[u8; POINT_ENCODING_LEN]; LANES] {
        unsafe {
            let c = self.canonical();
            // Packing overlaps unless canonical limb 0 is below 2^51.
            debug_assert!(
                c.limb_below(0, 51),
                "to_bytes_lanes needs a canonical limb 0 below 2^51"
            );
            let packed = [
                _mm512_or_si512(c.limbs[0], _mm512_slli_epi64(c.limbs[1], 51)),
                _mm512_or_si512(
                    _mm512_srli_epi64(c.limbs[1], 13),
                    _mm512_slli_epi64(c.limbs[2], 38),
                ),
                _mm512_or_si512(
                    _mm512_srli_epi64(c.limbs[2], 26),
                    _mm512_slli_epi64(c.limbs[3], 25),
                ),
                _mm512_or_si512(
                    _mm512_srli_epi64(c.limbs[3], 39),
                    _mm512_slli_epi64(c.limbs[4], 12),
                ),
            ];
            let mut words = [[0u64; LANES]; 4];
            storeu(packed[0], &mut words[0]);
            storeu(packed[1], &mut words[1]);
            storeu(packed[2], &mut words[2]);
            storeu(packed[3], &mut words[3]);

            core::array::from_fn(|lane| {
                let mut bytes = [0u8; POINT_ENCODING_LEN];
                let mut word = 0;
                while word < 4 {
                    bytes[word * 8..word * 8 + 8].copy_from_slice(&words[word][lane].to_le_bytes());
                    word += 1;
                }
                bytes
            })
        }
    }
    // Full reduction keeps results strict enough for small-bias subtracts.
    pub(super) fn add(&self, rhs: &Self) -> Self {
        unsafe {
            let h = [
                _mm512_add_epi64(self.limbs[0], rhs.limbs[0]),
                _mm512_add_epi64(self.limbs[1], rhs.limbs[1]),
                _mm512_add_epi64(self.limbs[2], rhs.limbs[2]),
                _mm512_add_epi64(self.limbs[3], rhs.limbs[3]),
                _mm512_add_epi64(self.limbs[4], rhs.limbs[4]),
            ];
            let reduced = Self::reduce_loose(h);
            Self::carry_limb0(reduced.limbs)
        }
    }
    pub(super) fn add_loose(&self, rhs: &Self) -> Self {
        unsafe {
            let h = [
                _mm512_add_epi64(self.limbs[0], rhs.limbs[0]),
                _mm512_add_epi64(self.limbs[1], rhs.limbs[1]),
                _mm512_add_epi64(self.limbs[2], rhs.limbs[2]),
                _mm512_add_epi64(self.limbs[3], rhs.limbs[3]),
                _mm512_add_epi64(self.limbs[4], rhs.limbs[4]),
            ];
            Self::reduce_loose(h)
        }
    }
    // The 4*p bias is only enough for strict subtrahends (`< 2^52` limbs);
    // loose limb0 can reach < 2^60, so those callers use `subtract_loose`.
    //
    // Note the suffix convention split: on `multiply`/`square`/`add`,
    // `_loose` marks a looser *result*; on the subtraction family below it
    // marks looser *operands* (the results are equally loose either way).
    pub(super) fn subtract(&self, rhs: &Self) -> Self {
        unsafe {
            let bias = [
                _mm512_set1_epi64(((4 * LIMB_MASK) - 18 * 4) as i64),
                _mm512_set1_epi64((4 * LIMB_MASK) as i64),
                _mm512_set1_epi64((4 * LIMB_MASK) as i64),
                _mm512_set1_epi64((4 * LIMB_MASK) as i64),
                _mm512_set1_epi64((4 * LIMB_MASK) as i64),
            ];
            let h = [
                _mm512_sub_epi64(_mm512_add_epi64(self.limbs[0], bias[0]), rhs.limbs[0]),
                _mm512_sub_epi64(_mm512_add_epi64(self.limbs[1], bias[1]), rhs.limbs[1]),
                _mm512_sub_epi64(_mm512_add_epi64(self.limbs[2], bias[2]), rhs.limbs[2]),
                _mm512_sub_epi64(_mm512_add_epi64(self.limbs[3], bias[3]), rhs.limbs[3]),
                _mm512_sub_epi64(_mm512_add_epi64(self.limbs[4], bias[4]), rhs.limbs[4]),
            ];
            Self::reduce_loose(h)
        }
    }
    /// Accumulate `self^2` as unreduced `(lo, hi)` column pairs.
    ///
    /// Unlike [`multiply_accum`](Self::multiply_accum), this accepts a loose
    /// limb 0 (`< 2^60`) because it carries limb 0 itself. The two are not
    /// interchangeable in that respect: handing a `*_loose` result straight to
    /// `multiply_accum` truncates its limb 0 to 52 bits.
    pub(super) fn square_accum(&self) -> ([__m512i; LIMB_COUNT], [__m512i; LIMB_COUNT]) {
        unsafe {
            let z = _mm512_setzero_si512();
            let mut lo = [z; LIMB_COUNT];
            let mut hi = [z; LIMB_COUNT];

            // Carry only loose limb0. The remaining limbs may be just over
            // 51 bits, but are still valid IFMA52 inputs. Cross-products
            // are doubled in their accumulators instead of doubling an
            // input and forcing a full carry chain.
            let limbs = {
                let mask = _mm512_set1_epi64(LIMB_MASK as i64);
                let mut l = self.limbs;
                let carry = _mm512_srli_epi64(l[0], 51);
                l[0] = _mm512_and_si512(l[0], mask);
                l[1] = _mm512_add_epi64(l[1], carry);
                l
            };
            // The carry lands in limb 1, so this covers both the incoming
            // limbs 1..4 and the widened limb 1.
            #[cfg(debug_assertions)]
            debug_assert!(
                limbs_are_ifma_operands(&limbs),
                "square_accum operand exceeds 52 bits after carrying limb 0"
            );

            madd_one(&mut lo[0], &mut hi[0], limbs[0], limbs[0]);
            let (mut wlo, mut whi) = (z, z);
            madd_one(&mut wlo, &mut whi, limbs[1], limbs[4]);
            madd_one(&mut wlo, &mut whi, limbs[2], limbs[3]);
            double_accum(&mut wlo, &mut whi);
            add_wrap19(&mut lo[0], &mut hi[0], wlo, whi);

            madd_one(&mut lo[1], &mut hi[1], limbs[0], limbs[1]);
            double_accum(&mut lo[1], &mut hi[1]);
            let (mut wlo, mut whi) = (z, z);
            madd_one(&mut wlo, &mut whi, limbs[2], limbs[4]);
            double_accum(&mut wlo, &mut whi);
            madd_one(&mut wlo, &mut whi, limbs[3], limbs[3]);
            add_wrap19(&mut lo[1], &mut hi[1], wlo, whi);

            madd_one(&mut lo[2], &mut hi[2], limbs[0], limbs[2]);
            double_accum(&mut lo[2], &mut hi[2]);
            madd_one(&mut lo[2], &mut hi[2], limbs[1], limbs[1]);
            let (mut wlo, mut whi) = (z, z);
            madd_one(&mut wlo, &mut whi, limbs[3], limbs[4]);
            double_accum(&mut wlo, &mut whi);
            add_wrap19(&mut lo[2], &mut hi[2], wlo, whi);

            madd_one(&mut lo[3], &mut hi[3], limbs[0], limbs[3]);
            madd_one(&mut lo[3], &mut hi[3], limbs[1], limbs[2]);
            double_accum(&mut lo[3], &mut hi[3]);
            let (mut wlo, mut whi) = (z, z);
            madd_one(&mut wlo, &mut whi, limbs[4], limbs[4]);
            add_wrap19(&mut lo[3], &mut hi[3], wlo, whi);

            madd_one(&mut lo[4], &mut hi[4], limbs[0], limbs[4]);
            madd_one(&mut lo[4], &mut hi[4], limbs[1], limbs[3]);
            double_accum(&mut lo[4], &mut hi[4]);
            madd_one(&mut lo[4], &mut hi[4], limbs[2], limbs[2]);

            (lo, hi)
        }
    }
    pub(super) fn square_loose(&self) -> Self {
        let (lo, hi) = self.square_accum();
        Self::reduce_ifma_loose(lo, hi)
    }
    /// Accumulate `self * rhs` as unreduced `(lo, hi)` column pairs.
    ///
    /// Strict and loose multiplication differ only in final reduction.
    ///
    /// Both operands feed `vpmadd52` directly, so every limb must already be
    /// `< 2^52`. A loose limb 0 (`< 2^60`, what `*_loose` and `reduce_ifma_loose`
    /// produce) must pass through [`carry_limb0`](Self::carry_limb0) or an
    /// additive op first. This is what makes `square_repeat`'s last iteration a
    /// strict `square()`: it restores the bound before the next multiply.
    pub(super) fn multiply_accum(
        &self,
        rhs: &Self,
    ) -> ([__m512i; LIMB_COUNT], [__m512i; LIMB_COUNT]) {
        #[cfg(debug_assertions)]
        debug_assert!(
            limbs_are_ifma_operands(&self.limbs) && limbs_are_ifma_operands(&rhs.limbs),
            "multiply_accum operand exceeds 52 bits; a loose limb 0 needs carry_limb0 first"
        );
        unsafe {
            let z = _mm512_setzero_si512();
            let mut lo = [z; LIMB_COUNT];
            let mut hi = [z; LIMB_COUNT];

            madd_one(&mut lo[0], &mut hi[0], self.limbs[0], rhs.limbs[0]);
            let (mut wlo, mut whi) = (z, z);
            madd_one(&mut wlo, &mut whi, self.limbs[1], rhs.limbs[4]);
            madd_one(&mut wlo, &mut whi, self.limbs[2], rhs.limbs[3]);
            madd_one(&mut wlo, &mut whi, self.limbs[3], rhs.limbs[2]);
            madd_one(&mut wlo, &mut whi, self.limbs[4], rhs.limbs[1]);
            add_wrap19(&mut lo[0], &mut hi[0], wlo, whi);

            madd_one(&mut lo[1], &mut hi[1], self.limbs[0], rhs.limbs[1]);
            madd_one(&mut lo[1], &mut hi[1], self.limbs[1], rhs.limbs[0]);
            let (mut wlo, mut whi) = (z, z);
            madd_one(&mut wlo, &mut whi, self.limbs[2], rhs.limbs[4]);
            madd_one(&mut wlo, &mut whi, self.limbs[3], rhs.limbs[3]);
            madd_one(&mut wlo, &mut whi, self.limbs[4], rhs.limbs[2]);
            add_wrap19(&mut lo[1], &mut hi[1], wlo, whi);

            madd_one(&mut lo[2], &mut hi[2], self.limbs[0], rhs.limbs[2]);
            madd_one(&mut lo[2], &mut hi[2], self.limbs[1], rhs.limbs[1]);
            madd_one(&mut lo[2], &mut hi[2], self.limbs[2], rhs.limbs[0]);
            let (mut wlo, mut whi) = (z, z);
            madd_one(&mut wlo, &mut whi, self.limbs[3], rhs.limbs[4]);
            madd_one(&mut wlo, &mut whi, self.limbs[4], rhs.limbs[3]);
            add_wrap19(&mut lo[2], &mut hi[2], wlo, whi);

            madd_one(&mut lo[3], &mut hi[3], self.limbs[0], rhs.limbs[3]);
            madd_one(&mut lo[3], &mut hi[3], self.limbs[1], rhs.limbs[2]);
            madd_one(&mut lo[3], &mut hi[3], self.limbs[2], rhs.limbs[1]);
            madd_one(&mut lo[3], &mut hi[3], self.limbs[3], rhs.limbs[0]);
            let (mut wlo, mut whi) = (z, z);
            madd_one(&mut wlo, &mut whi, self.limbs[4], rhs.limbs[4]);
            add_wrap19(&mut lo[3], &mut hi[3], wlo, whi);

            madd_one(&mut lo[4], &mut hi[4], self.limbs[0], rhs.limbs[4]);
            madd_one(&mut lo[4], &mut hi[4], self.limbs[1], rhs.limbs[3]);
            madd_one(&mut lo[4], &mut hi[4], self.limbs[2], rhs.limbs[2]);
            madd_one(&mut lo[4], &mut hi[4], self.limbs[3], rhs.limbs[1]);
            madd_one(&mut lo[4], &mut hi[4], self.limbs[4], rhs.limbs[0]);

            (lo, hi)
        }
    }
    pub(super) fn multiply_loose(&self, rhs: &Self) -> Self {
        let (lo, hi) = self.multiply_accum(rhs);
        Self::reduce_ifma_loose(lo, hi)
    }

    // One IFMA carry pass leaves limb0 < 2^60 and limbs 1..4 < 2^51.
    pub(super) fn reduce_ifma_loose(
        mut lo: [__m512i; LIMB_COUNT],
        hi: [__m512i; LIMB_COUNT],
    ) -> Self {
        unsafe {
            let mask = _mm512_set1_epi64(LIMB_MASK as i64);
            let nineteen = _mm512_set1_epi64(19);

            let mut i = 0;
            while i < 4 {
                let carry =
                    _mm512_add_epi64(_mm512_srli_epi64(lo[i], 51), _mm512_slli_epi64(hi[i], 1));
                lo[i] = _mm512_and_si512(lo[i], mask);
                lo[i + 1] = _mm512_add_epi64(lo[i + 1], carry);
                i += 1;
            }

            let carry = _mm512_add_epi64(_mm512_srli_epi64(lo[4], 51), _mm512_slli_epi64(hi[4], 1));
            lo[4] = _mm512_and_si512(lo[4], mask);
            lo[0] = _mm512_add_epi64(lo[0], _mm512_mullo_epi64(carry, nineteen));

            Self { limbs: lo }
        }
    }

    // `self + 2048*p - rhs`. These loose-input forms use a 2048*p bias,
    // enough for two loose subtrahends (limb0 < 2^60); `subtract`'s 4*p is not.
    pub(super) fn subtract_loose(&self, rhs: &Self) -> Self {
        unsafe {
            let b0 = _mm512_set1_epi64((2048 * (LIMB_MASK - 18)) as i64);
            let bn = _mm512_set1_epi64((2048 * LIMB_MASK) as i64);
            let h = [
                _mm512_sub_epi64(_mm512_add_epi64(self.limbs[0], b0), rhs.limbs[0]),
                _mm512_sub_epi64(_mm512_add_epi64(self.limbs[1], bn), rhs.limbs[1]),
                _mm512_sub_epi64(_mm512_add_epi64(self.limbs[2], bn), rhs.limbs[2]),
                _mm512_sub_epi64(_mm512_add_epi64(self.limbs[3], bn), rhs.limbs[3]),
                _mm512_sub_epi64(_mm512_add_epi64(self.limbs[4], bn), rhs.limbs[4]),
            ];
            Self::reduce_loose(h)
        }
    }

    // `self + 2048*p - lhs - rhs`, with all three possibly loose.
    pub(super) fn subtract_loose_sum(&self, lhs: &Self, rhs: &Self) -> Self {
        unsafe {
            let b0 = _mm512_set1_epi64((2048 * (LIMB_MASK - 18)) as i64);
            let bn = _mm512_set1_epi64((2048 * LIMB_MASK) as i64);
            let bias = [b0, bn, bn, bn, bn];
            let h = core::array::from_fn(|i| {
                _mm512_sub_epi64(
                    _mm512_sub_epi64(_mm512_add_epi64(self.limbs[i], bias[i]), lhs.limbs[i]),
                    rhs.limbs[i],
                )
            });
            Self::reduce_loose(h)
        }
    }

    // Fold `2*rhs` into the loose-input subtraction to avoid a carry pass.
    pub(super) fn subtract_loose_sum_with_doubled_rhs(&self, lhs: &Self, rhs: &Self) -> Self {
        unsafe {
            let b0 = _mm512_set1_epi64((2048 * (LIMB_MASK - 18)) as i64);
            let bn = _mm512_set1_epi64((2048 * LIMB_MASK) as i64);
            let bias = [b0, bn, bn, bn, bn];
            let h = core::array::from_fn(|i| {
                _mm512_sub_epi64(
                    _mm512_sub_epi64(_mm512_add_epi64(self.limbs[i], bias[i]), lhs.limbs[i]),
                    _mm512_slli_epi64(rhs.limbs[i], 1),
                )
            });
            Self::reduce_loose(h)
        }
    }

    // `2048*p - lhs - rhs`, with `lhs`/`rhs` possibly loose.
    pub(super) fn negate_loose_sum(lhs: &Self, rhs: &Self) -> Self {
        unsafe {
            let b0 = _mm512_set1_epi64((2048 * (LIMB_MASK - 18)) as i64);
            let bn = _mm512_set1_epi64((2048 * LIMB_MASK) as i64);
            let bias = [b0, bn, bn, bn, bn];
            let h = core::array::from_fn(|i| {
                _mm512_sub_epi64(_mm512_sub_epi64(bias[i], lhs.limbs[i]), rhs.limbs[i])
            });
            Self::reduce_loose(h)
        }
    }
    pub(super) fn negate(&self) -> Self {
        Self::zero().subtract(self)
    }
    pub(super) fn double(&self) -> Self {
        self.add(self)
    }
    pub(super) fn double_loose(&self) -> Self {
        self.add_loose(self)
    }
    pub(super) fn square(&self) -> Self {
        let (lo, hi) = self.square_accum();
        Self::reduce_ifma(lo, hi)
    }
    pub(super) fn multiply(&self, rhs: &Self) -> Self {
        let (lo, hi) = self.multiply_accum(rhs);
        Self::reduce_ifma(lo, hi)
    }
    pub(super) fn pow_p_minus_5_over_8(&self) -> Self {
        pow_p_minus_5_over_8_chain(*self)
    }

    /// Initialization-only copy. The out-of-line wrapper keeps setup call
    /// sites from perturbing the hot path's inlining.
    #[inline(never)]
    pub(super) fn cold_pow_p_minus_5_over_8(&self) -> Self {
        pow_p_minus_5_over_8_chain(*self)
    }

    /// The inversion addition chain, shared by both entry points.
    #[inline(always)]
    pub(super) fn invert_chain(&self) -> Self {
        let z = self;
        let t0 = z.square();
        let t1 = t0.square_repeat::<2>().multiply(z);
        let z11 = t0.multiply(&t1);
        let a = z11.square().multiply(&t1);
        let b = a.square_repeat::<5>().multiply(&a);
        let c = b.square_repeat::<10>().multiply(&b);
        let d = c.square_repeat::<20>().multiply(&c);
        let e = d.square_repeat::<10>().multiply(&b);
        let f = e.square_repeat::<50>().multiply(&e);
        let g = f.square_repeat::<100>().multiply(&f);
        let h = g.square_repeat::<50>().multiply(&e);
        h.square_repeat::<5>().multiply(&z11)
    }
    pub(super) fn invert(&self) -> Self {
        self.invert_chain()
    }

    /// Initialization-only copy; see [`cold_pow_p_minus_5_over_8`](Self::cold_pow_p_minus_5_over_8).
    #[inline(never)]
    pub(super) fn cold_invert(&self) -> Self {
        self.invert_chain()
    }
    // Keep intermediates loose; reduce only the final result for multiplication.
    pub(super) fn square_repeat<const N: usize>(&self) -> Self {
        let mut out = *self;
        for i in 0..N {
            out = if i + 1 < N {
                out.square_loose()
            } else {
                out.square()
            };
        }
        out
    }

    // Interleave two exponentiation chains to hide IFMA latency.
    pub(super) fn square_repeat_x2<const N: usize>(a: &Self, b: &Self) -> (Self, Self) {
        let (mut x, mut y) = (*a, *b);
        for i in 0..N {
            if i + 1 < N {
                x = x.square_loose();
                y = y.square_loose();
            } else {
                x = x.square();
                y = y.square();
            }
        }
        (x, y)
    }

    pub(super) fn pow_p_minus_5_over_8_x2(a: &Self, b: &Self) -> (Self, Self) {
        let pair = pow_p_minus_5_over_8_chain(WideFePair(*a, *b));
        (pair.0, pair.1)
    }
    pub(super) fn equals_lanes(self, rhs: &Self) -> [bool; LANES] {
        mask_to_lanes(self.equals_mask(rhs))
    }
    pub(super) fn equals_mask(self, rhs: &Self) -> u8 {
        self.subtract(rhs).is_zero_mask()
    }
    pub(super) fn is_zero_lanes(self) -> [bool; LANES] {
        mask_to_lanes(self.is_zero_mask())
    }
    pub(super) fn is_zero_mask(self) -> u8 {
        self.canonical().canonical_zero_mask()
    }
    /// Zero mask of an already-canonicalized value.
    #[inline(always)]
    pub(super) fn canonical_zero_mask(&self) -> u8 {
        unsafe {
            let zero = _mm512_setzero_si512();
            _mm512_cmpeq_epu64_mask(self.limbs[0], zero)
                & _mm512_cmpeq_epu64_mask(self.limbs[1], zero)
                & _mm512_cmpeq_epu64_mask(self.limbs[2], zero)
                & _mm512_cmpeq_epu64_mask(self.limbs[3], zero)
                & _mm512_cmpeq_epu64_mask(self.limbs[4], zero)
        }
    }
    #[cfg(test)]
    pub(super) fn is_odd_lanes(self) -> [bool; LANES] {
        mask_to_lanes(self.is_odd_mask())
    }
    pub(super) fn limb_below(&self, index: usize, bits: u32) -> bool {
        let mut lanes = [0u64; LANES];
        storeu(self.limbs[index], &mut lanes);
        lanes.iter().all(|&limb| limb < (1u64 << bits))
    }

    pub(super) fn is_odd_mask(self) -> u8 {
        unsafe {
            let c = self.canonical();
            let one = _mm512_set1_epi64(1);
            _mm512_test_epi64_mask(c.limbs[0], one)
        }
    }
    /// Return parity and zero masks from one canonicalization.
    pub(super) fn odd_and_zero_masks(self) -> (u8, u8) {
        unsafe {
            let c = self.canonical();
            let one = _mm512_set1_epi64(1);
            (
                _mm512_test_epi64_mask(c.limbs[0], one),
                c.canonical_zero_mask(),
            )
        }
    }
    /// Vectorized `Fe51::canonical`; bounded high limbs reduce `>= p` to a
    /// high-limb check and limb-0 threshold.
    pub(super) fn canonical(&self) -> Self {
        unsafe {
            let reduced = Self::carry_reduce_twice(self.limbs);
            let mask = _mm512_set1_epi64(LIMB_MASK as i64);
            let p0 = _mm512_set1_epi64((LIMB_MASK - 18) as i64);

            let ge_high = _mm512_cmpeq_epu64_mask(reduced.limbs[1], mask)
                & _mm512_cmpeq_epu64_mask(reduced.limbs[2], mask)
                & _mm512_cmpeq_epu64_mask(reduced.limbs[3], mask)
                & _mm512_cmpeq_epu64_mask(reduced.limbs[4], mask);
            let ge_p = ge_high & _mm512_cmpge_epu64_mask(reduced.limbs[0], p0);

            let zero = _mm512_setzero_si512();
            let sub0 = _mm512_sub_epi64(reduced.limbs[0], p0);
            Self {
                limbs: [
                    _mm512_mask_blend_epi64(ge_p, reduced.limbs[0], sub0),
                    _mm512_mask_blend_epi64(ge_p, reduced.limbs[1], zero),
                    _mm512_mask_blend_epi64(ge_p, reduced.limbs[2], zero),
                    _mm512_mask_blend_epi64(ge_p, reduced.limbs[3], zero),
                    _mm512_mask_blend_epi64(ge_p, reduced.limbs[4], zero),
                ],
            }
        }
    }
    pub(super) fn blend(&self, mask: u8, rhs: &Self) -> Self {
        unsafe {
            let mask = mask as __mmask8;
            Self {
                limbs: [
                    _mm512_mask_blend_epi64(mask, self.limbs[0], rhs.limbs[0]),
                    _mm512_mask_blend_epi64(mask, self.limbs[1], rhs.limbs[1]),
                    _mm512_mask_blend_epi64(mask, self.limbs[2], rhs.limbs[2]),
                    _mm512_mask_blend_epi64(mask, self.limbs[3], rhs.limbs[3]),
                    _mm512_mask_blend_epi64(mask, self.limbs[4], rhs.limbs[4]),
                ],
            }
        }
    }
    pub(super) fn reduce_ifma(lo: [__m512i; LIMB_COUNT], hi: [__m512i; LIMB_COUNT]) -> Self {
        // Only limb 0 retains a residual; carry it to restore IFMA bounds.
        Self::carry_limb0(Self::reduce_ifma_loose(lo, hi).limbs)
    }
    /// Carry loose limb 0, restoring the `< 2^52` IFMA input bound.
    pub(super) fn carry_limb0(mut h: [__m512i; LIMB_COUNT]) -> Self {
        unsafe {
            let mask = _mm512_set1_epi64(LIMB_MASK as i64);
            let carry = _mm512_srli_epi64(h[0], 51);
            h[0] = _mm512_and_si512(h[0], mask);
            h[1] = _mm512_add_epi64(h[1], carry);
            Self { limbs: h }
        }
    }
    /// One carry pass: limbs 1..4 become `< 2^51`; limb 0 may keep the
    /// small wraparound residual needed by additive consumers.
    pub(super) fn reduce_loose(mut h: [__m512i; LIMB_COUNT]) -> Self {
        unsafe {
            let mask = _mm512_set1_epi64(LIMB_MASK as i64);
            let nineteen = _mm512_set1_epi64(19);

            let mut i = 0;
            while i < 4 {
                let carry = _mm512_srli_epi64(h[i], 51);
                h[i] = _mm512_and_si512(h[i], mask);
                h[i + 1] = _mm512_add_epi64(h[i + 1], carry);
                i += 1;
            }

            let carry = _mm512_srli_epi64(h[4], 51);
            h[4] = _mm512_and_si512(h[4], mask);
            h[0] = _mm512_add_epi64(h[0], _mm512_mullo_epi64(carry, nineteen));

            Self { limbs: h }
        }
    }
    /// Two carry passes, used when `add`/`canonical` need near-strict limbs.
    pub(super) fn carry_reduce_twice(h: [__m512i; LIMB_COUNT]) -> Self {
        Self::reduce_loose(Self::reduce_loose(h).limbs)
    }
}
impl WideFe {
    pub(super) fn constant(limbs: [u64; LIMB_COUNT]) -> Self {
        unsafe {
            Self {
                limbs: [
                    _mm512_set1_epi64(limbs[0] as i64),
                    _mm512_set1_epi64(limbs[1] as i64),
                    _mm512_set1_epi64(limbs[2] as i64),
                    _mm512_set1_epi64(limbs[3] as i64),
                    _mm512_set1_epi64(limbs[4] as i64),
                ],
            }
        }
    }
    // Broadcast the shared scalar/SIMD constants from `field.rs`.
    pub(super) fn d() -> Self {
        Self::constant(crate::field::D_LIMBS)
    }
    pub(super) fn sqrt_m1() -> Self {
        Self::constant(crate::field::SQRT_M1_LIMBS)
    }
    pub(super) fn two_d() -> Self {
        Self::constant(crate::field::TWO_D_LIMBS)
    }
}
impl PowChainValue for WideFe {
    #[inline(always)]
    fn chain_square(self) -> Self {
        self.square()
    }

    #[inline(always)]
    fn chain_square_repeat<const N: usize>(self) -> Self {
        self.square_repeat::<N>()
    }

    #[inline(always)]
    fn chain_multiply(self, rhs: Self) -> Self {
        self.multiply(&rhs)
    }
}

impl PowChainValue for WideFePair {
    #[inline(always)]
    fn chain_square(self) -> Self {
        Self(self.0.square(), self.1.square())
    }

    #[inline(always)]
    fn chain_square_repeat<const N: usize>(self) -> Self {
        let (a, b) = WideFe::square_repeat_x2::<N>(&self.0, &self.1);
        Self(a, b)
    }

    #[inline(always)]
    fn chain_multiply(self, rhs: Self) -> Self {
        Self(self.0.multiply(&rhs.0), self.1.multiply(&rhs.1))
    }
}

/// Whether every limb in every lane is a valid `vpmadd52` operand.
///
/// `vpmadd52lo/hi` read only the low 52 bits of each source, so a limb at or
/// above `2^52` is silently truncated and the product is wrong with no trap.
/// Debug-only: the callers below assert their operands rather than trusting a
/// prose invariant.
#[cfg(debug_assertions)]
fn limbs_are_ifma_operands(limbs: &[__m512i; LIMB_COUNT]) -> bool {
    limbs.iter().all(|&limb| {
        let mut lanes = [0u64; LANES];
        storeu(limb, &mut lanes);
        lanes.iter().all(|&lane| lane < (1u64 << 52))
    })
}

fn madd_one(lo: &mut __m512i, hi: &mut __m512i, a: __m512i, b: __m512i) {
    unsafe {
        *lo = _mm512_madd52lo_epu64(*lo, a, b);
        *hi = _mm512_madd52hi_epu64(*hi, a, b);
    }
}
#[inline(always)]
fn double_accum(lo: &mut __m512i, hi: &mut __m512i) {
    unsafe {
        *lo = _mm512_add_epi64(*lo, *lo);
        *hi = _mm512_add_epi64(*hi, *hi);
    }
}
fn add_wrap19(lo: &mut __m512i, hi: &mut __m512i, wrap_lo: __m512i, wrap_hi: __m512i) {
    unsafe {
        let nineteen = _mm512_set1_epi64(19);
        *lo = _mm512_add_epi64(*lo, _mm512_mullo_epi64(wrap_lo, nineteen));
        *hi = _mm512_add_epi64(*hi, _mm512_mullo_epi64(wrap_hi, nineteen));
    }
}
pub(super) fn loadu(values: [u64; LANES]) -> __m512i {
    unsafe { _mm512_loadu_si512(values.as_ptr() as *const __m512i) }
}
pub(super) fn storeu(value: __m512i, out: &mut [u64; LANES]) {
    unsafe { _mm512_storeu_si512(out.as_mut_ptr() as *mut __m512i, value) }
}