rvsim-core 2.0.0

A cycle-level RISC-V 64-bit system simulator.
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
//! Vector reduction operations.
//!
//! Implements all RISC-V Vector Extension (RVV 1.0) reduction instructions.
//! Reductions fold a vector register group (vs2) and an initial scalar
//! accumulator (element 0 of vs1) into a single result in element 0 of vd.
//!
//! Operations handled:
//! - **Integer:** `vredsum`, `vredand`, `vredor`, `vredxor`, `vredminu`,
//!   `vredmin`, `vredmaxu`, `vredmax`
//! - **Widening integer:** `vwredsumu`, `vwredsum`
//! - **FP:** `vfredosum`, `vfredusum`, `vfredmax`, `vfredmin`
//! - **FP widening:** `vfwredosum`, `vfwredusum`
//!
//! All reductions read the initial accumulator from `vs1[0]` and write the
//! result to `vd[0]`; remaining elements of `vd` follow the tail policy.

// IEEE 754 FEQ requires exact bit-pattern comparison — float_cmp is intentional here.
#![allow(clippy::float_cmp)]

use crate::exec::compute::fpu::half::{CANONICAL_NAN_F16, f16_to_f32, f64_to_f16, is_snan_f16};
use crate::exec::compute::fpu::host::{
    clear_host_fp_flags, read_host_fp_flags, restore_host_round_mode, set_host_round_mode,
};
use crate::exec::compute::fpu::nan_handling::{
    box_f32_canon, canonicalize_f64_bits, fmax_f32, fmax_f64, fmin_f32, fmin_f64,
};
use crate::exec::compute::fpu::nan_handling::{is_snan_f32, is_snan_f64};
use crate::exec::compute::vector::context::{
    FpSew, FpWiden, VecExecCtx, VecExecResult, mask_active, sign_extend, widen_sew,
};
use crate::exec::compute::vector::regfile::VectorRegFile;
use crate::isa::fp::{FpFlags, RoundingMode};
use crate::isa::op::{
    FpReduceOp, FpWidenReduceOp, IntReduceOp, ReduceOp, VectorOp, WidenIntReduceOp,
};
use crate::isa::rvv::{ElemIdx, Sew, VRegIdx, Vlmax, Vlmul};

/// Returns `true` if `op` is a reduction handled by this module.
pub const fn is_reduction(op: VectorOp) -> bool {
    matches!(
        op,
        VectorOp::VRedSum
            | VectorOp::VRedAnd
            | VectorOp::VRedOr
            | VectorOp::VRedXor
            | VectorOp::VRedMinU
            | VectorOp::VRedMin
            | VectorOp::VRedMaxU
            | VectorOp::VRedMax
            | VectorOp::VWRedSumU
            | VectorOp::VWRedSum
            | VectorOp::VFRedOSum
            | VectorOp::VFRedUSum
            | VectorOp::VFRedMax
            | VectorOp::VFRedMin
            | VectorOp::VFWRedOSum
            | VectorOp::VFWRedUSum
    )
}

/// Execute a reduction of `vs2` seeded from `vs1[0]`.
///
/// Results are written to `vd[0]` in the VPR; remaining elements follow the
/// tail policy.
///
/// # Integer reductions
///
/// Operate at SEW width.
///
/// # Widening integer reductions
///
/// Read source elements at SEW, extend to 2*SEW, and accumulate at 2*SEW.
///
/// # FP reductions
///
/// Operate at SEW (16 with Zvfh, 32 or 64). Ordered sums process elements
/// sequentially; unordered sums use the same sequential ordering for
/// deterministic results.
///
/// # FP widening reductions
///
/// Read source elements at SEW, widen, and accumulate at 2*SEW.
pub fn vec_reduce(
    op: ReduceOp,
    vpr: &mut impl VectorRegFile,
    vd: VRegIdx,
    vs2: VRegIdx,
    vs1: VRegIdx,
    ctx: &VecExecCtx,
) -> VecExecResult {
    match op {
        ReduceOp::Int(op) => exec_int_reduction(op, vpr, vd, vs2, vs1, ctx),
        ReduceOp::WidenInt(op) => exec_widen_int_reduction(op, vpr, vd, vs2, vs1, ctx),
        ReduceOp::Fp(op) => exec_fp_reduction(op, vpr, vd, vs2, vs1, ctx),
        ReduceOp::FpWiden(op) => exec_fp_widen_reduction(op, vpr, vd, vs2, vs1, ctx),
    }
}

/// The initial accumulator: element 0 of `vs1` at `sew`.
#[inline]
fn read_initial_accum(vpr: &impl VectorRegFile, vs1: VRegIdx, sew: Sew) -> u64 {
    vpr.read_element(vs1, ElemIdx::new(0), sew)
}

/// Execute an integer reduction at SEW width.
///
/// Folds all active elements of `vs2` into a single accumulator (initialized
/// from `vs1[0]`) using the operation specified by `op`. The result is written
/// to `vd[0]`; elements `1..vlmax` of `vd` follow the tail policy.
fn exec_int_reduction(
    op: IntReduceOp,
    vpr: &mut impl VectorRegFile,
    vd: VRegIdx,
    vs2: VRegIdx,
    vs1: VRegIdx,
    ctx: &VecExecCtx,
) -> VecExecResult {
    let sew = ctx.sew;
    let mask = sew.mask();

    let mut acc = read_initial_accum(vpr, vs1, sew);

    for i in ctx.vstart..ctx.vl {
        if !ctx.vm && !mask_active(vpr, i) {
            continue;
        }
        let elem = vpr.read_element(vs2, ElemIdx::new(i), sew);
        acc = int_reduce_step(op, acc, elem, sew, mask);
    }

    vpr.write_element(vd, ElemIdx::new(0), sew, acc & mask);

    if ctx.vta.is_agnostic() {
        let vlmax = Vlmax::compute(vpr.vlen(), sew, Vlmul::M1).as_usize();
        for i in 1..vlmax {
            vpr.write_element(vd, ElemIdx::new(i), sew, sew.ones());
        }
    }

    VecExecResult { vxsat: false, scalar_result: None, fp_flags: FpFlags::NONE }
}

/// Perform one step of an integer reduction.
///
/// Combines the current accumulator with a new element according to the
/// reduction operation.
#[inline]
const fn int_reduce_step(op: IntReduceOp, acc: u64, elem: u64, sew: Sew, mask: u64) -> u64 {
    match op {
        IntReduceOp::Sum => acc.wrapping_add(elem) & mask,
        IntReduceOp::And => acc & elem,
        IntReduceOp::Or => acc | elem,
        IntReduceOp::Xor => acc ^ elem,
        IntReduceOp::MinU => {
            if elem < acc {
                elem
            } else {
                acc
            }
        }
        IntReduceOp::Min => {
            let sa = sign_extend(acc, sew);
            let se = sign_extend(elem, sew);
            if se < sa { elem } else { acc }
        }
        IntReduceOp::MaxU => {
            if elem > acc {
                elem
            } else {
                acc
            }
        }
        IntReduceOp::Max => {
            let sa = sign_extend(acc, sew);
            let se = sign_extend(elem, sew);
            if se > sa { elem } else { acc }
        }
    }
}

/// Execute a widening integer reduction.
///
/// Source elements are read at SEW and extended to 2*SEW before accumulation.
/// The accumulator (from `vs1[0]`) and the result are at 2*SEW width.
fn exec_widen_int_reduction(
    op: WidenIntReduceOp,
    vpr: &mut impl VectorRegFile,
    vd: VRegIdx,
    vs2: VRegIdx,
    vs1: VRegIdx,
    ctx: &VecExecCtx,
) -> VecExecResult {
    let src_sew = ctx.sew;
    let Some(dst_sew) = widen_sew(src_sew) else {
        return VecExecResult { vxsat: false, scalar_result: None, fp_flags: FpFlags::NONE };
    };
    let dst_mask = dst_sew.mask();

    let mut acc = read_initial_accum(vpr, vs1, dst_sew);

    for i in ctx.vstart..ctx.vl {
        if !ctx.vm && !mask_active(vpr, i) {
            continue;
        }
        let elem = vpr.read_element(vs2, ElemIdx::new(i), src_sew);

        let wide = match op {
            WidenIntReduceOp::SumU => elem,
            WidenIntReduceOp::Sum => (sign_extend(elem, src_sew) as u64) & dst_mask,
        };

        acc = acc.wrapping_add(wide) & dst_mask;
    }

    vpr.write_element(vd, ElemIdx::new(0), dst_sew, acc);

    if ctx.vta.is_agnostic() {
        let vlmax = Vlmax::compute(vpr.vlen(), dst_sew, Vlmul::M1).as_usize();
        for i in 1..vlmax {
            vpr.write_element(vd, ElemIdx::new(i), dst_sew, dst_sew.ones());
        }
    }

    VecExecResult { vxsat: false, scalar_result: None, fp_flags: FpFlags::NONE }
}

/// Execute a floating-point reduction at SEW width (32 or 64).
///
/// For ordered sums (`VFRedOSum`) elements are processed sequentially from
/// element 0 to `vl-1`. Unordered sums (`VFRedUSum`) use the same sequential
/// ordering for deterministic results.
///
/// FP min/max reductions (`VFRedMin`, `VFRedMax`) use IEEE 754-2008 minNum/maxNum
/// semantics, matching the scalar `fmin`/`fmax` helpers.
fn exec_fp_reduction(
    op: FpReduceOp,
    vpr: &mut impl VectorRegFile,
    vd: VRegIdx,
    vs2: VRegIdx,
    vs1: VRegIdx,
    ctx: &VecExecCtx,
) -> VecExecResult {
    let sew = ctx.sew;
    let Some(fp_sew) = FpSew::of(sew, ctx.zvfh) else {
        return VecExecResult { vxsat: false, scalar_result: None, fp_flags: FpFlags::NONE };
    };

    let saved_rm = set_host_round_mode(ctx.frm);
    let (result_bits, flags) = match fp_sew {
        FpSew::F16 => fp_reduce_f16(op, vpr, vs2, vs1, ctx),
        FpSew::F32 => fp_reduce_f32(op, vpr, vs2, vs1, ctx),
        FpSew::F64 => fp_reduce_f64(op, vpr, vs2, vs1, ctx),
    };
    vpr.write_element(vd, ElemIdx::new(0), sew, result_bits);
    restore_host_round_mode(saved_rm);

    if ctx.vta.is_agnostic() {
        let vlmax = Vlmax::compute(vpr.vlen(), sew, Vlmul::M1).as_usize();
        for i in 1..vlmax {
            vpr.write_element(vd, ElemIdx::new(i), sew, sew.ones());
        }
    }

    VecExecResult { vxsat: false, scalar_result: None, fp_flags: flags }
}

/// Single-precision (f32) reduction loop.
///
/// Returns `(result_bits, fp_flags)` where `result_bits` is the NaN-boxed
/// canonical f32 result suitable for writing at SEW=32.
fn fp_reduce_f32(
    op: FpReduceOp,
    vpr: &impl VectorRegFile,
    vs2: VRegIdx,
    vs1: VRegIdx,
    ctx: &VecExecCtx,
) -> (u64, FpFlags) {
    let sew = ctx.sew;
    let init_bits = read_initial_accum(vpr, vs1, sew);
    let mut acc = f32::from_bits(init_bits as u32);
    let mut flags = FpFlags::NONE;

    for i in ctx.vstart..ctx.vl {
        if !ctx.vm && !mask_active(vpr, i) {
            continue;
        }
        let elem_bits = vpr.read_element(vs2, ElemIdx::new(i), sew);
        let elem = f32::from_bits(elem_bits as u32);

        match op {
            FpReduceOp::OSum | FpReduceOp::USum => {
                clear_host_fp_flags();
                acc = std::hint::black_box(std::hint::black_box(acc) + std::hint::black_box(elem));
                flags = flags | read_host_fp_flags();
            }
            FpReduceOp::Min => {
                if is_snan_f32(acc) || is_snan_f32(elem) {
                    flags = flags | FpFlags::NV;
                }
                acc = fmin_f32(acc, elem);
            }
            FpReduceOp::Max => {
                if is_snan_f32(acc) || is_snan_f32(elem) {
                    flags = flags | FpFlags::NV;
                }
                acc = fmax_f32(acc, elem);
            }
        }
    }

    (box_f32_canon(acc), flags)
}

/// Double-precision (f64) reduction loop.
///
/// Returns `(result_bits, fp_flags)` where `result_bits` is the canonicalized
/// f64 bit pattern suitable for writing at SEW=64.
fn fp_reduce_f64(
    op: FpReduceOp,
    vpr: &impl VectorRegFile,
    vs2: VRegIdx,
    vs1: VRegIdx,
    ctx: &VecExecCtx,
) -> (u64, FpFlags) {
    let sew = ctx.sew;
    let init_bits = read_initial_accum(vpr, vs1, sew);
    let mut acc = f64::from_bits(init_bits);
    let mut flags = FpFlags::NONE;

    for i in ctx.vstart..ctx.vl {
        if !ctx.vm && !mask_active(vpr, i) {
            continue;
        }
        let elem_bits = vpr.read_element(vs2, ElemIdx::new(i), sew);
        let elem = f64::from_bits(elem_bits);

        match op {
            FpReduceOp::OSum | FpReduceOp::USum => {
                clear_host_fp_flags();
                acc = std::hint::black_box(std::hint::black_box(acc) + std::hint::black_box(elem));
                flags = flags | read_host_fp_flags();
            }
            FpReduceOp::Min => {
                if is_snan_f64(acc) || is_snan_f64(elem) {
                    flags = flags | FpFlags::NV;
                }
                acc = fmin_f64(acc, elem);
            }
            FpReduceOp::Max => {
                if is_snan_f64(acc) || is_snan_f64(elem) {
                    flags = flags | FpFlags::NV;
                }
                acc = fmax_f64(acc, elem);
            }
        }
    }

    (canonicalize_f64_bits(acc), flags)
}

/// Half-precision (f16, Zvfh) reduction loop.
///
/// Per V 1.0 §14.2 and Zvfh, ordered FP reductions accumulate at the
/// destination precision; for SEW=E16 each step is rounded to f16. Inputs
/// are widened to f32 (lossless), the host performs the arithmetic, and the
/// result is rounded back to f16 with the current rounding mode (`ctx.frm`).
///
/// Returns `(result_bits, fp_flags)` where the f16 bit pattern is in the low
/// 16 bits of the u64 (upper bits zero).
fn fp_reduce_f16(
    op: FpReduceOp,
    vpr: &impl VectorRegFile,
    vs2: VRegIdx,
    vs1: VRegIdx,
    ctx: &VecExecCtx,
) -> (u64, FpFlags) {
    let sew = ctx.sew;
    let init_bits = read_initial_accum(vpr, vs1, sew) as u16;
    let mut acc_bits: u16 = init_bits;
    let mut flags = FpFlags::NONE;

    for i in ctx.vstart..ctx.vl {
        if !ctx.vm && !mask_active(vpr, i) {
            continue;
        }
        let elem_bits = vpr.read_element(vs2, ElemIdx::new(i), sew) as u16;

        match op {
            FpReduceOp::OSum | FpReduceOp::USum => {
                if is_snan_f16(acc_bits) || is_snan_f16(elem_bits) {
                    flags = flags | FpFlags::NV;
                }
                let acc_f64 = f16_to_f32(acc_bits) as f64;
                let elem_f64 = f16_to_f32(elem_bits) as f64;
                clear_host_fp_flags();
                let sum = std::hint::black_box(
                    std::hint::black_box(acc_f64) + std::hint::black_box(elem_f64),
                );
                let host_flags = read_host_fp_flags();
                let (rounded, round_flags) = f64_to_f16(sum, ctx.frm);
                acc_bits = rounded;
                flags = flags | host_flags | round_flags;
            }
            FpReduceOp::Min => {
                if is_snan_f16(acc_bits) || is_snan_f16(elem_bits) {
                    flags = flags | FpFlags::NV;
                }
                let a = f16_to_f32(acc_bits);
                let b = f16_to_f32(elem_bits);
                let r = fmin_f32(a, b);
                acc_bits = if r.is_nan() {
                    CANONICAL_NAN_F16
                } else {
                    let (bits, _) = f64_to_f16(r as f64, RoundingMode::Rne);
                    bits
                };
            }
            FpReduceOp::Max => {
                if is_snan_f16(acc_bits) || is_snan_f16(elem_bits) {
                    flags = flags | FpFlags::NV;
                }
                let a = f16_to_f32(acc_bits);
                let b = f16_to_f32(elem_bits);
                let r = fmax_f32(a, b);
                acc_bits = if r.is_nan() {
                    CANONICAL_NAN_F16
                } else {
                    let (bits, _) = f64_to_f16(r as f64, RoundingMode::Rne);
                    bits
                };
            }
        }
    }

    (acc_bits as u64, flags)
}

/// Execute a widening FP reduction.
///
/// Source elements are at SEW; accumulator and result are at 2*SEW. Per
/// V 1.0 §14.4: each step rounds the running sum to the destination
/// precision. Supported widenings: E32→E64, and E16→E32 when Zvfh is
/// enabled.
fn exec_fp_widen_reduction(
    op: FpWidenReduceOp,
    vpr: &mut impl VectorRegFile,
    vd: VRegIdx,
    vs2: VRegIdx,
    vs1: VRegIdx,
    ctx: &VecExecCtx,
) -> VecExecResult {
    let Some(widen) = FpSew::of(ctx.sew, ctx.zvfh).and_then(FpSew::widening) else {
        return VecExecResult { vxsat: false, scalar_result: None, fp_flags: FpFlags::NONE };
    };
    let dst_sew = widen.dst();
    let saved_rm = set_host_round_mode(ctx.frm);

    let (result_bits, flags) = match widen {
        FpWiden::F32ToF64 => fp_widen_reduce_f32_to_f64(op, vpr, vs2, vs1, ctx, dst_sew),
        FpWiden::F16ToF32 => fp_widen_reduce_f16_to_f32(op, vpr, vs2, vs1, ctx, dst_sew),
    };

    vpr.write_element(vd, ElemIdx::new(0), dst_sew, result_bits);

    restore_host_round_mode(saved_rm);

    if ctx.vta.is_agnostic() {
        let vlmax = Vlmax::compute(vpr.vlen(), dst_sew, Vlmul::M1).as_usize();
        for i in 1..vlmax {
            vpr.write_element(vd, ElemIdx::new(i), dst_sew, dst_sew.ones());
        }
    }

    VecExecResult { vxsat: false, scalar_result: None, fp_flags: flags }
}

/// E32→E64 widening FP reduction. Accumulator is f64, source elements f32.
fn fp_widen_reduce_f32_to_f64(
    op: FpWidenReduceOp,
    vpr: &impl VectorRegFile,
    vs2: VRegIdx,
    vs1: VRegIdx,
    ctx: &VecExecCtx,
    dst_sew: Sew,
) -> (u64, FpFlags) {
    let init_bits = read_initial_accum(vpr, vs1, dst_sew);
    let mut acc = f64::from_bits(init_bits);
    let mut flags = FpFlags::NONE;
    for i in ctx.vstart..ctx.vl {
        if !ctx.vm && !mask_active(vpr, i) {
            continue;
        }
        let elem_bits = vpr.read_element(vs2, ElemIdx::new(i), Sew::E32) as u32;
        let wide = f32::from_bits(elem_bits) as f64;
        match op {
            FpWidenReduceOp::OSum | FpWidenReduceOp::USum => {
                clear_host_fp_flags();
                acc = std::hint::black_box(std::hint::black_box(acc) + std::hint::black_box(wide));
                flags = flags | read_host_fp_flags();
            }
        }
    }
    (canonicalize_f64_bits(acc), flags)
}

/// E16→E32 widening FP reduction (Zvfh). Accumulator is f32, source elements f16.
fn fp_widen_reduce_f16_to_f32(
    op: FpWidenReduceOp,
    vpr: &impl VectorRegFile,
    vs2: VRegIdx,
    vs1: VRegIdx,
    ctx: &VecExecCtx,
    dst_sew: Sew,
) -> (u64, FpFlags) {
    let init_bits = read_initial_accum(vpr, vs1, dst_sew) as u32;
    let mut acc = f32::from_bits(init_bits);
    let mut flags = FpFlags::NONE;
    for i in ctx.vstart..ctx.vl {
        if !ctx.vm && !mask_active(vpr, i) {
            continue;
        }
        let elem_bits = vpr.read_element(vs2, ElemIdx::new(i), Sew::E16) as u16;
        let wide = f16_to_f32(elem_bits);
        match op {
            FpWidenReduceOp::OSum | FpWidenReduceOp::USum => {
                if is_snan_f16(elem_bits) {
                    flags = flags | FpFlags::NV;
                }
                clear_host_fp_flags();
                acc = std::hint::black_box(std::hint::black_box(acc) + std::hint::black_box(wide));
                flags = flags | read_host_fp_flags();
            }
        }
    }
    (box_f32_canon(acc), flags)
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::isa::op::VecClass;

    /// The reduction `op` decodes to.
    fn reduce_op(op: VectorOp) -> ReduceOp {
        match op.class() {
            VecClass::Reduce(reduce) => reduce,
            other => panic!("{op:?} is not a reduction: {other:?}"),
        }
    }
    use crate::arch::regs::vpr::Vpr;
    use crate::isa::fp::RoundingMode;
    use crate::isa::rvv::{MaskPolicy, TailPolicy, Vlen, Vlmul, Vxrm};

    /// Create a standard execution context with the given SEW and vl.
    fn make_ctx(sew: Sew, vl: usize) -> VecExecCtx {
        VecExecCtx {
            sew,
            vl,
            vstart: 0,
            vma: MaskPolicy::Undisturbed,
            vta: TailPolicy::Undisturbed,
            vlmul: Vlmul::M1,
            vm: true,
            vxrm: Vxrm::RoundToNearestUp,
            frm: RoundingMode::Rne,
            zvfh: false,
        }
    }

    /// Create a 128-bit VLEN vector register file.
    fn vpr128() -> Vpr {
        Vpr::new(Vlen::new_unchecked(128))
    }

    #[test]
    fn test_vredsum() {
        let mut vpr = vpr128();
        let ctx = make_ctx(Sew::E32, 4);
        let vd = VRegIdx::new(1);
        let vs2 = VRegIdx::new(2);
        let vs1 = VRegIdx::new(3);

        // vs2 = [10, 20, 30, 40], vs1[0] = 100 (accumulator)
        for i in 0..4 {
            vpr.write_element(vs2, ElemIdx::new(i), Sew::E32, (i as u64 + 1) * 10);
        }
        vpr.write_element(vs1, ElemIdx::new(0), Sew::E32, 100);

        let _result = vec_reduce(reduce_op(VectorOp::VRedSum), &mut vpr, vd, vs2, vs1, &ctx);
        // 100 + 10 + 20 + 30 + 40 = 200
        assert_eq!(vpr.read_element(vd, ElemIdx::new(0), Sew::E32), 200);
    }

    #[test]
    fn test_vredand() {
        let mut vpr = vpr128();
        let ctx = make_ctx(Sew::E32, 4);
        let vd = VRegIdx::new(1);
        let vs2 = VRegIdx::new(2);
        let vs1 = VRegIdx::new(3);

        for i in 0..4 {
            vpr.write_element(vs2, ElemIdx::new(i), Sew::E32, 0xFF);
        }
        vpr.write_element(vs1, ElemIdx::new(0), Sew::E32, 0xFFFF_FFFF);

        let _result = vec_reduce(reduce_op(VectorOp::VRedAnd), &mut vpr, vd, vs2, vs1, &ctx);
        assert_eq!(vpr.read_element(vd, ElemIdx::new(0), Sew::E32), 0xFF);
    }

    #[test]
    fn test_vredmin_signed() {
        let mut vpr = vpr128();
        let ctx = make_ctx(Sew::E32, 4);
        let vd = VRegIdx::new(1);
        let vs2 = VRegIdx::new(2);
        let vs1 = VRegIdx::new(3);

        // vs2 = [5, -3, 10, 1] as signed i32
        vpr.write_element(vs2, ElemIdx::new(0), Sew::E32, 5);
        vpr.write_element(vs2, ElemIdx::new(1), Sew::E32, (-3i32 as u32) as u64);
        vpr.write_element(vs2, ElemIdx::new(2), Sew::E32, 10);
        vpr.write_element(vs2, ElemIdx::new(3), Sew::E32, 1);
        // accumulator = 100
        vpr.write_element(vs1, ElemIdx::new(0), Sew::E32, 100);

        let _result = vec_reduce(reduce_op(VectorOp::VRedMin), &mut vpr, vd, vs2, vs1, &ctx);
        // min(100, 5, -3, 10, 1) = -3
        let val = vpr.read_element(vd, ElemIdx::new(0), Sew::E32);
        assert_eq!(val as u32, (-3i32) as u32);
    }

    #[test]
    fn test_vfredosum_f32() {
        let mut vpr = vpr128();
        let ctx = make_ctx(Sew::E32, 4);
        let vd = VRegIdx::new(1);
        let vs2 = VRegIdx::new(2);
        let vs1 = VRegIdx::new(3);

        // vs2 = [1.0, 2.0, 3.0, 4.0], accum = 10.0
        for i in 0..4 {
            vpr.write_element(vs2, ElemIdx::new(i), Sew::E32, ((i as f32 + 1.0).to_bits()) as u64);
        }
        vpr.write_element(vs1, ElemIdx::new(0), Sew::E32, 10.0f32.to_bits() as u64);

        let _result = vec_reduce(reduce_op(VectorOp::VFRedOSum), &mut vpr, vd, vs2, vs1, &ctx);
        let val = f32::from_bits(vpr.read_element(vd, ElemIdx::new(0), Sew::E32) as u32);
        assert_eq!(val, 20.0); // 10 + 1 + 2 + 3 + 4
    }
}