rigless 0.1.0

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a CPU core of its own that translates the firmware's instructions to host code
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The 16-bit data processing instructions, DDI 0403E.b A5.2.
//!
//! Most of them set the flags only outside an IT block, A7.3.3. The translator knows which when it
//! translates, so `setflags` is settled then and never reaches the code.

use cranelift_codegen::ir::{InstBuilder, Value, types};

use super::alu::{ShiftType, add_with_carry, decode_imm_shift, shift_c, shift_c_register};
use super::{Emitter, Flag, Translated, Undefined, bits};

/// What an instruction writes: `R[d]` when it has a `d`, and the flags when its `setflags` holds.
#[derive(Clone, Copy)]
struct Writes {
    destination: Option<u32>,
    setflags: bool,
}

impl Writes {
    /// A compare's, which writes only the flags, inside an IT block too.
    const FLAGS: Self = Self {
        destination: None,
        setflags: true,
    };

    fn register(d: u32, setflags: bool) -> Self {
        Self {
            destination: Some(d),
            setflags,
        }
    }
}

/// Writes `result`, and N and Z from it when `setflags`, which every instruction here shares.
fn write(e: &mut Emitter<'_, '_>, writes: Writes, result: Value) {
    if let Some(d) = writes.destination {
        e.set_reg(d, result);
    }
    if writes.setflags {
        e.set_nz(result);
    }
}

/// A5.2.1, shift (immediate), add, subtract, move, and compare.
pub(super) fn shift_add_subtract_move_compare(e: &mut Emitter<'_, '_>, hw: u16) {
    let hw = u32::from(hw);
    let setflags = !e.in_it();
    let (low, middle, high) = (bits(hw, 2, 0), bits(hw, 5, 3), bits(hw, 10, 8));
    let imm8 = bits(hw, 7, 0);
    match bits(hw, 13, 11) {
        // MOV (register) T2, A7.7.76, is the LSL by 0. It's UNPREDICTABLE in an IT block, and
        // you get its flags there too, since its pseudocode sets `setflags` whatever the block.
        0b000 if bits(hw, 10, 6) == 0 => {
            let result = e.reg(middle);
            write(e, Writes::register(low, true), result);
        }
        shift @ 0b000..=0b010 => {
            shift_immediate(e, hw, shift, Writes::register(low, setflags));
        }
        0b011 => {
            let x = e.reg(middle);
            let operand = bits(hw, 8, 6);
            let y = if bits(hw, 10, 10) == 0 {
                e.reg(operand)
            } else {
                e.constant(operand)
            };
            let writes = Writes::register(low, setflags);
            add_or_subtract(e, writes, x, y, bits(hw, 9, 9) == 1);
        }
        // MOV (immediate) T1, A7.7.75. Its carry is `APSR.C`, so only N and Z can change.
        0b100 => {
            let result = e.constant(imm8);
            write(e, Writes::register(high, setflags), result);
        }
        0b101 => {
            let (x, y) = (e.reg(high), e.constant(imm8));
            add_or_subtract(e, Writes::FLAGS, x, y, true);
        }
        op => {
            let (x, y) = (e.reg(high), e.constant(imm8));
            add_or_subtract(e, Writes::register(high, setflags), x, y, op == 0b111);
        }
    }
}

/// LSL, LSR and ASR (immediate) T1, A7.7.67, A7.7.69 and A7.7.10, with `shift` their `op`.
fn shift_immediate(e: &mut Emitter<'_, '_>, hw: u32, shift: u32, writes: Writes) {
    let (shift_type, amount) = decode_imm_shift(shift, bits(hw, 10, 6));
    let value = e.reg(bits(hw, 5, 3));
    let carry_in = e.flag(Flag::C);
    let (result, carry) = shift_c(e, value, shift_type, amount, carry_in);
    write(e, writes, result);
    if writes.setflags {
        e.set_flag(Flag::C, carry);
    }
}

/// ADD and SUB (register and immediate) and CMP, A7.7.3, A7.7.4, A7.7.171, A7.7.172 and A7.7.27:
/// `AddWithCarry(x, y, '0')`, or `AddWithCarry(x, NOT(y), '1')` to subtract, A2.2.1.
fn add_or_subtract(e: &mut Emitter<'_, '_>, writes: Writes, x: Value, y: Value, subtract: bool) {
    let (y, carry_in) = if subtract {
        (e.b.ins().bnot(y), e.constant(1))
    } else {
        (y, e.constant(0))
    };
    add_with_flags(e, writes, x, y, carry_in);
}

/// `AddWithCarry(x, y, carry_in)`, A2.2.1, setting all four flags.
fn add_with_flags(e: &mut Emitter<'_, '_>, writes: Writes, x: Value, y: Value, carry_in: Value) {
    let (result, carry, overflow) = add_with_carry(e, x, y, carry_in);
    write(e, writes, result);
    if writes.setflags {
        e.set_flag(Flag::C, carry);
        e.set_flag(Flag::V, overflow);
    }
}

/// A5.2.2, data processing, Table A5-3.
///
/// AND, EOR, ORR, BIC, MVN and TST (register), A7.7.9, A7.7.35, A7.7.91, A7.7.16, A7.7.85 and
/// A7.7.186, take their carry from `Shift_C` by an LSL of 0, which is `APSR.C` as it was, so only
/// N and Z change. MUL, A7.7.83, leaves C and V too, since its low 32 bits are the same signed or
/// unsigned. TST, CMP and CMN set the flags inside an IT block as well.
pub(super) fn data_processing(e: &mut Emitter<'_, '_>, hw: u16) {
    let hw = u32::from(hw);
    let (dn, m) = (bits(hw, 2, 0), bits(hw, 5, 3));
    let writes = Writes::register(dn, !e.in_it());
    let first = e.reg(dn);
    let second = e.reg(m);
    let (zero, one) = (e.constant(0), e.constant(1));
    let result = match bits(hw, 9, 6) {
        0b0000 => e.b.ins().band(first, second),
        0b0001 => e.b.ins().bxor(first, second),
        op @ (0b0010 | 0b0011 | 0b0100 | 0b0111) => {
            let shift_type = match op {
                0b0010 => ShiftType::Lsl,
                0b0011 => ShiftType::Lsr,
                0b0100 => ShiftType::Asr,
                _ => ShiftType::Ror,
            };
            shift_register(e, writes, first, shift_type, second);
            return;
        }
        0b0101 => {
            let carry = e.flag(Flag::C);
            add_with_flags(e, writes, first, second, carry);
            return;
        }
        0b0110 => {
            let carry = e.flag(Flag::C);
            let inverted = e.b.ins().bnot(second);
            add_with_flags(e, writes, first, inverted, carry);
            return;
        }
        0b1000 => {
            let result = e.b.ins().band(first, second);
            write(e, Writes::FLAGS, result);
            return;
        }
        // RSB (immediate) T1, A7.7.117, is `0 - R[n]` with `n` in bits 5 to 3.
        0b1001 => {
            let inverted = e.b.ins().bnot(second);
            add_with_flags(e, writes, inverted, zero, one);
            return;
        }
        0b1010 => {
            let inverted = e.b.ins().bnot(second);
            add_with_flags(e, Writes::FLAGS, first, inverted, one);
            return;
        }
        0b1011 => {
            add_with_flags(e, Writes::FLAGS, first, second, zero);
            return;
        }
        0b1100 => e.b.ins().bor(first, second),
        0b1101 => e.b.ins().imul(second, first),
        0b1110 => e.b.ins().band_not(first, second),
        _ => e.b.ins().bnot(second),
    };
    write(e, writes, result);
}

/// LSL, LSR, ASR and ROR (register) T1, A7.7.68, A7.7.70, A7.7.11 and A7.7.115, which shift by
/// `UInt(R[m]<7:0>)` and leave V alone.
fn shift_register(
    e: &mut Emitter<'_, '_>,
    writes: Writes,
    value: Value,
    shift_type: ShiftType,
    by: Value,
) {
    let amount = e.b.ins().band_imm_u(by, 0xFF);
    let carry_in = e.flag(Flag::C);
    let (result, carry) = shift_c_register(e, value, shift_type, amount, carry_in);
    write(e, writes, result);
    if writes.setflags {
        e.set_flag(Flag::C, carry);
    }
}

/// A5.2.3, special data instructions and branch and exchange, Table A5-4: ADD (register) T2 and
/// ADD (SP plus register) T1 and T2, A7.7.4 and A7.7.6, CMP (register) T2, A7.7.28, MOV
/// (register) T1, A7.7.76, BX, A7.7.20, and BLX (register), A7.7.19.
///
/// The ADD forms all add `R[m]` to the register they write, and only CMP sets flags. The manual
/// calls a few uses UNPREDICTABLE: a PC write inside an IT block but not last in it, ADD with the
/// PC on both sides, CMP of two low registers or of the PC, BLX of the PC, and BX or BLX with any
/// of bits 2 to 0 set. Each runs as its pseudocode reads, the simplest thing it suggests, A5.1.1.
pub(super) fn special_data_branch_exchange(e: &mut Emitter<'_, '_>, hw: u16) {
    let hw = u32::from(hw);
    let m = bits(hw, 6, 3);
    let dn = bits(hw, 7, 7) << 3 | bits(hw, 2, 0);
    match bits(hw, 9, 8) {
        0b00 => {
            let (x, y) = (e.reg(dn), e.reg(m));
            let result = e.b.ins().iadd(x, y);
            alu_write(e, dn, result);
        }
        0b01 => {
            let (x, y) = (e.reg(dn), e.reg(m));
            add_or_subtract(e, Writes::FLAGS, x, y, true);
        }
        0b10 => {
            let result = e.reg(m);
            alu_write(e, dn, result);
        }
        _ if bits(hw, 7, 7) == 0 => {
            let target = e.reg(m);
            e.branch_exchange(target);
        }
        _ => branch_link_exchange(e, m),
    }
}

/// Writes an ALU result to `R[d]` for the forms that can name any register. The PC takes it as
/// `ALUWritePC()`, A2.3.1, which ends the block, and SP drops bits 1 and 0 as the `R[]`
/// assignment does, B1.4.7.
fn alu_write(e: &mut Emitter<'_, '_>, d: u32, result: Value) {
    match d {
        15 => e.branch(result),
        13 => {
            let aligned = e.b.ins().band_imm_s(result, !3);
            e.set_reg(13, aligned);
        }
        _ => e.set_reg(d, result),
    }
}

/// BLX (register), A7.7.19. `BLXWritePC()`, A2.3.1, is `BXWritePC()` without the exception
/// return, so a Handler mode BLX to `0xFxxxxxxx` is a plain branch there.
fn branch_link_exchange(e: &mut Emitter<'_, '_>, m: u32) {
    let target = e.reg(m);
    let link = e.constant(e.next_pc() | 1);
    e.set_reg(14, link);
    e.blx_write_pc(target);
}

/// ADR, A7.7.7 encoding T1: `Align(PC, 4)` plus `imm8:'00'`, which is known when it translates.
pub(super) fn adr(e: &mut Emitter<'_, '_>, hw: u16) {
    let hw = u32::from(hw);
    let aligned = e.pc().wrapping_add(4) & !3;
    let result = e.constant(aligned.wrapping_add(bits(hw, 7, 0) << 2));
    e.set_reg(bits(hw, 10, 8), result);
}

/// ADD (SP plus immediate), A7.7.5 encoding T1.
pub(super) fn add_sp_immediate(e: &mut Emitter<'_, '_>, hw: u16) {
    let hw = u32::from(hw);
    let sp = e.reg(13);
    let result = e.b.ins().iadd_imm_u(sp, i64::from(bits(hw, 7, 0) << 2));
    e.set_reg(bits(hw, 10, 8), result);
}

/// ADD (SP plus immediate) T2 and SUB (SP minus immediate) T1, A7.7.5 and A7.7.173, Table A5-6.
pub(super) fn adjust_sp(e: &mut Emitter<'_, '_>, hw: u16) {
    let hw = u32::from(hw);
    let imm32 = i64::from(bits(hw, 6, 0) << 2);
    let sp = e.reg(13);
    let by = if bits(hw, 7, 7) == 1 { -imm32 } else { imm32 };
    let result = e.b.ins().iadd_imm_s(sp, by);
    alu_write(e, 13, result);
}

/// SXTH, SXTB, UXTH and UXTB T1, A7.7.181, A7.7.179, A7.7.220 and A7.7.218, Table A5-6. T1
/// rotates by 0.
pub(super) fn extend(e: &mut Emitter<'_, '_>, hw: u16) {
    let hw = u32::from(hw);
    let value = e.reg(bits(hw, 5, 3));
    let result = match bits(hw, 7, 6) {
        0b00 => {
            let half = e.b.ins().ireduce(types::I16, value);
            e.b.ins().sextend(types::I32, half)
        }
        0b01 => {
            let byte = e.b.ins().ireduce(types::I8, value);
            e.b.ins().sextend(types::I32, byte)
        }
        0b10 => e.b.ins().band_imm_u(value, 0xFFFF),
        _ => e.b.ins().band_imm_u(value, 0xFF),
    };
    e.set_reg(bits(hw, 2, 0), result);
}

/// REV, REV16 and REVSH T1, A7.7.111 to A7.7.113, Table A5-6, whose `101010x` is UNDEFINED.
pub(super) fn reverse(e: &mut Emitter<'_, '_>, hw: u16) -> Translated {
    let hw = u32::from(hw);
    let value = e.reg(bits(hw, 5, 3));
    let result = match bits(hw, 7, 6) {
        0b00 => e.b.ins().bswap(value),
        0b01 => {
            let swapped = e.b.ins().bswap(value);
            e.b.ins().rotr_imm_u(swapped, 16)
        }
        0b11 => {
            let half = e.b.ins().ireduce(types::I16, value);
            let swapped = e.b.ins().bswap(half);
            e.b.ins().sextend(types::I32, swapped)
        }
        _ => return Err(Undefined),
    };
    e.set_reg(bits(hw, 2, 0), result);
    Ok(())
}

#[cfg(test)]
mod tests {
    use cranelift_codegen::ir;
    use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext};

    use super::super::super::state::State;
    use super::super::testing::{Bench, RAM, SIZE};
    use super::*;
    use crate::emulator::Exit;

    /// `ITSTATE` for the only instruction of `IT AL`, A7.3.2: in the block, last in it, and run
    /// whatever the flags say.
    const LAST_OF_IT_AL: u32 = 0xE8;
    /// `ITSTATE` for the first instruction of `ITT AL`, which isn't the last.
    const FIRST_OF_ITT_AL: u32 = 0xE4;

    fn top_of_stack() -> u32 {
        RAM + u32::try_from(SIZE).unwrap()
    }

    /// Runs `code`, every instruction of it once, with `set` applied to the state first, and
    /// answers the state it leaves.
    fn run(code: &[u16], set: impl FnOnce(&mut State)) -> State {
        let mut bench = Bench::new(code);
        set(&mut bench.core.state);
        let count = u32::try_from(code.len()).unwrap();
        assert_eq!(bench.run(count), (Exit::Budget, u64::from(count)));
        bench.core.state.clone()
    }

    fn nzcv(state: &State) -> [u32; 4] {
        [state.n, state.z, state.c, state.v]
    }

    fn set_nzcv(state: &mut State, [n, z, c, v]: [u32; 4]) {
        (state.n, state.z, state.c, state.v) = (n, z, c, v);
    }

    /// LSL, LSR and ASR (immediate) T1, by `op` 0, 1 and 2.
    fn shift_immediate(op: u16, imm5: u16, m: u16, d: u16) -> u16 {
        op << 11 | imm5 << 6 | m << 3 | d
    }

    /// ADD and SUB (register), then ADD and SUB (immediate) T1, by `op` 0 to 3.
    fn three_register(op: u16, operand: u16, n: u16, d: u16) -> u16 {
        0x1800 | op << 9 | operand << 6 | n << 3 | d
    }

    /// MOV, CMP, ADD and SUB with an 8-bit immediate, by `op` 0 to 3.
    fn with_imm8(op: u16, dn: u16, imm8: u16) -> u16 {
        0x2000 | op << 11 | dn << 8 | imm8
    }

    /// Table A5-3's instruction `opcode`.
    fn data(opcode: u16, m: u16, dn: u16) -> u16 {
        0x4000 | opcode << 6 | m << 3 | dn
    }

    /// Table A5-4's ADD, CMP and MOV, by `op` 0 to 2, on any registers.
    fn high(op: u16, dn: u16, m: u16) -> u16 {
        0x4400 | op << 8 | (dn >> 3) << 7 | m << 3 | (dn & 7)
    }

    fn bx(m: u16) -> u16 {
        0x4700 | m << 3
    }

    fn blx(m: u16) -> u16 {
        0x4780 | m << 3
    }

    /// SXTH, SXTB, UXTH and UXTB T1, by `op` 0 to 3.
    fn extend_hw(op: u16, m: u16, d: u16) -> u16 {
        0xB200 | op << 6 | m << 3 | d
    }

    /// REV, REV16, the gap and REVSH T1, by `op` 0 to 3.
    fn reverse_hw(op: u16, m: u16, d: u16) -> u16 {
        0xBA00 | op << 6 | m << 3 | d
    }

    /// What translating `hw` with `translate` answers, on a function nothing runs.
    fn translated(translate: fn(&mut Emitter<'_, '_>, u16) -> Translated, hw: u16) -> Translated {
        let mut function = ir::Function::new();
        function
            .signature
            .params
            .push(ir::AbiParam::new(types::I64));
        let mut context = FunctionBuilderContext::new();
        let mut builder = FunctionBuilder::new(&mut function, &mut context);
        let entry = builder.create_block();
        builder.append_block_params_for_function_params(entry);
        builder.switch_to_block(entry);
        let mut e = Emitter::new(&mut builder, types::I64);
        translate(&mut e, hw)
    }

    /// LSL (immediate) T1, A7.7.67: C is the last bit shifted out, and V stays.
    #[test]
    fn lsl_immediate_shifts_and_sets_n_z_c() {
        let state = run(&[shift_immediate(0, 4, 1, 0)], |state| {
            state.r[1] = 0x1800_0001;
            set_nzcv(state, [0, 1, 0, 1]);
        });
        assert_eq!(state.r[0], 0x8000_0010);
        assert_eq!(nzcv(&state), [1, 0, 1, 1]);
    }

    /// LSR (immediate) T1, A7.7.69: an `imm5` of 0 shifts by 32, A7.4.2.
    #[test]
    fn lsr_immediate_of_zero_shifts_by_32() {
        let state = run(
            &[shift_immediate(1, 0, 1, 0), shift_immediate(1, 1, 3, 2)],
            |state| {
                state.r[1] = 0x8000_0000;
                state.r[3] = 0x8000_0003;
            },
        );
        assert_eq!(state.r[0], 0);
        assert_eq!(state.r[2], 0x4000_0001);
        assert_eq!(nzcv(&state), [0, 0, 1, 0]);
        let state = run(&[shift_immediate(1, 0, 1, 0)], |state| {
            state.r[1] = 0x8000_0000;
        });
        assert_eq!(nzcv(&state), [0, 1, 1, 0]);
    }

    /// ASR (immediate) T1, A7.7.10: an `imm5` of 0 shifts by 32, which fills with the sign.
    #[test]
    fn asr_immediate_shifts_in_the_sign() {
        let state = run(&[shift_immediate(2, 0, 1, 0)], |state| {
            state.r[1] = 0x8000_0000;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0xFFFF_FFFF, [1, 0, 1, 0]));
        let state = run(&[shift_immediate(2, 4, 1, 0)], |state| {
            state.r[1] = 0x8000_0018;
            state.c = 0;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0xF800_0001, [1, 0, 1, 0]));
    }

    /// MOV (register) T2, A7.7.76, is LSL by 0: N and Z from the value, C and V kept.
    #[test]
    fn movs_register_sets_n_and_z_and_keeps_c_and_v() {
        let state = run(&[shift_immediate(0, 0, 1, 0)], |state| {
            state.r[0] = 5;
            set_nzcv(state, [1, 0, 1, 1]);
        });
        assert_eq!((state.r[0], nzcv(&state)), (0, [0, 1, 1, 1]));
    }

    /// MOV (register) T2 inside an IT block is UNPREDICTABLE, and its pseudocode sets the flags.
    #[test]
    fn movs_register_inside_an_it_block_still_sets_the_flags() {
        let state = run(&[shift_immediate(0, 0, 1, 0)], |state| {
            state.r[1] = 0x8000_0000;
            state.it = LAST_OF_IT_AL;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0x8000_0000, [1, 0, 0, 0]));
    }

    /// ADD (register) T1, A7.7.4, sets C on unsigned overflow and V on signed.
    #[test]
    fn add_register_sets_carry_and_overflow() {
        let state = run(&[three_register(0, 2, 1, 0)], |state| {
            state.r[1] = 0x7FFF_FFFF;
            state.r[2] = 1;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0x8000_0000, [1, 0, 0, 1]));
        let state = run(&[three_register(0, 2, 1, 0)], |state| {
            state.r[1] = 0xFFFF_FFFF;
            state.r[2] = 1;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0, [0, 1, 1, 0]));
    }

    /// SUB (register) T1, A7.7.172: C is NOT borrow.
    #[test]
    fn sub_register_sets_carry_as_not_borrow() {
        let state = run(&[three_register(1, 2, 1, 0)], |state| {
            state.r[1] = 3;
            state.r[2] = 5;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0xFFFF_FFFE, [1, 0, 0, 0]));
        let state = run(&[three_register(1, 2, 1, 0)], |state| {
            state.r[1] = 0x8000_0000;
            state.r[2] = 1;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0x7FFF_FFFF, [0, 0, 1, 1]));
    }

    /// ADD and SUB (immediate) T1, A7.7.3 and A7.7.171, with a 3-bit immediate.
    #[test]
    fn add_and_sub_take_a_3_bit_immediate() {
        let state = run(
            &[three_register(2, 7, 1, 0), three_register(3, 7, 3, 2)],
            |state| {
                state.r[1] = 0xFFFF_FFF9;
                state.r[3] = 7;
            },
        );
        assert_eq!((state.r[0], state.r[2]), (0, 0));
        assert_eq!(nzcv(&state), [0, 1, 1, 0], "7 - 7 borrows nothing");
    }

    /// MOV (immediate) T1, A7.7.75, keeps C and V.
    #[test]
    fn mov_immediate_sets_n_and_z_only() {
        let state = run(&[with_imm8(0, 3, 0), with_imm8(0, 4, 0xFF)], |state| {
            state.r[3] = 9;
            set_nzcv(state, [1, 0, 1, 1]);
        });
        assert_eq!((state.r[3], state.r[4]), (0, 0xFF));
        assert_eq!(nzcv(&state), [0, 0, 1, 1]);
    }

    /// Runs `hw` with R0 to R2 at `registers` and the flags at `preset`, outside an IT block and
    /// then inside one. It has to write `result` to R0 both times, but set `flags` only outside,
    /// A7.3.3. Each case moves N and Z, so a `setflags` that forgot the IT block can't pass.
    fn sets_flags_only_outside_it(
        hw: u16,
        registers: [u32; 3],
        preset: [u32; 4],
        result: u32,
        flags: [u32; 4],
    ) {
        assert!(
            preset[0] != flags[0] && preset[1] != flags[1],
            "{hw:#06x} has to move N and Z"
        );
        for (it, expected) in [(0, flags), (LAST_OF_IT_AL, preset)] {
            let state = run(&[hw], |state| {
                state.r[..3].copy_from_slice(&registers);
                set_nzcv(state, preset);
                state.it = it;
            });
            assert_eq!(
                (state.r[0], nzcv(&state)),
                (result, expected),
                "{hw:#06x} with ITSTATE {it:#04x}"
            );
        }
    }

    /// LSL, LSR and ASR (immediate), ADD and SUB (register and immediate) and MOV (immediate),
    /// A5.2.1, all take `setflags = !InITBlock()`, A7.7.67, A7.7.69, A7.7.10, A7.7.4, A7.7.172,
    /// A7.7.3, A7.7.171 and A7.7.75.
    #[test]
    fn shift_add_subtract_and_move_set_flags_only_outside_an_it_block() {
        let cases = [
            (
                shift_immediate(0, 1, 1, 0),
                [0, 0x8000_0001, 0],
                [1, 1, 0, 1],
                2,
                [0, 0, 1, 1],
            ),
            (
                shift_immediate(1, 1, 1, 0),
                [0, 3, 0],
                [1, 1, 0, 0],
                1,
                [0, 0, 1, 0],
            ),
            (
                shift_immediate(2, 1, 1, 0),
                [0, 3, 0],
                [1, 1, 0, 0],
                1,
                [0, 0, 1, 0],
            ),
            (
                three_register(0, 2, 1, 0),
                [0, 0x8000_0000, 0x8000_0001],
                [1, 1, 0, 0],
                1,
                [0, 0, 1, 1],
            ),
            (
                three_register(1, 2, 1, 0),
                [0, 0x8000_0000, 1],
                [1, 1, 0, 0],
                0x7FFF_FFFF,
                [0, 0, 1, 1],
            ),
            (
                three_register(2, 2, 1, 0),
                [0, 0xFFFF_FFFF, 0],
                [1, 1, 0, 1],
                1,
                [0, 0, 1, 0],
            ),
            (
                three_register(3, 1, 1, 0),
                [0, 0x8000_0000, 0],
                [1, 1, 0, 0],
                0x7FFF_FFFF,
                [0, 0, 1, 1],
            ),
            (with_imm8(0, 0, 5), [0, 0, 0], [1, 1, 1, 1], 5, [0, 0, 1, 1]),
            (
                with_imm8(2, 0, 2),
                [0xFFFF_FFFF, 0, 0],
                [1, 1, 0, 1],
                1,
                [0, 0, 1, 0],
            ),
            (
                with_imm8(3, 0, 1),
                [0x8000_0000, 0, 0],
                [1, 1, 0, 0],
                0x7FFF_FFFF,
                [0, 0, 1, 1],
            ),
        ];
        for (hw, registers, preset, result, flags) in cases {
            sets_flags_only_outside_it(hw, registers, preset, result, flags);
        }
    }

    /// CMP (immediate) T1, A7.7.27, sets the flags and writes nothing, inside an IT block too.
    #[test]
    fn cmp_immediate_sets_the_flags_even_inside_an_it_block() {
        let state = run(&[with_imm8(1, 2, 5)], |state| {
            state.r[2] = 5;
            state.it = LAST_OF_IT_AL;
        });
        assert_eq!((state.r[2], nzcv(&state)), (5, [0, 1, 1, 0]));
        let state = run(&[with_imm8(1, 2, 0xFF)], |state| state.r[2] = 0x8000_0000);
        assert_eq!(nzcv(&state), [0, 0, 1, 1]);
    }

    /// ADD and SUB (immediate) T2, A7.7.3 and A7.7.171, with an 8-bit immediate.
    #[test]
    fn add_and_sub_take_an_8_bit_immediate() {
        let state = run(&[with_imm8(2, 7, 0xFF)], |state| state.r[7] = 1);
        assert_eq!((state.r[7], nzcv(&state)), (0x100, [0, 0, 0, 0]));
        let state = run(&[with_imm8(3, 7, 1)], |state| state.r[7] = 0);
        assert_eq!((state.r[7], nzcv(&state)), (0xFFFF_FFFF, [1, 0, 0, 0]));
    }

    /// AND, EOR, ORR, BIC and MVN (register) T1: N and Z from the result, C and V kept.
    #[test]
    fn the_logical_operations_set_n_and_z_and_keep_c_and_v() {
        let cases = [
            (0b0000, 0xFF00_FF00, 0x0F0F_0F0F, 0x0F00_0F00),
            (0b0001, 0xFF00_FF00, 0x0F0F_0F0F, 0xF00F_F00F),
            (0b1100, 0xFF00_FF00, 0x0F0F_0F0F, 0xFF0F_FF0F),
            (0b1110, 0xFF00_FF00, 0x0F0F_0F0F, 0xF000_F000),
            (0b1111, 0, 0x0F0F_0F0F, 0xF0F0_F0F0),
            (0b0000, 0xFF00_FF00, 0x00FF_00FF, 0),
        ];
        for (opcode, first, second, result) in cases {
            let state = run(&[data(opcode, 1, 0)], |state| {
                state.r[0] = first;
                state.r[1] = second;
                set_nzcv(state, [0, 0, 1, 1]);
            });
            assert_eq!(state.r[0], result, "opcode {opcode:#06b}");
            let flags = [result >> 31, u32::from(result == 0), 1, 1];
            assert_eq!(nzcv(&state), flags, "opcode {opcode:#06b}");
        }
    }

    /// TST (register) T1, A7.7.186, sets N and Z and writes nothing, inside an IT block too.
    #[test]
    fn tst_sets_n_and_z_and_writes_nothing() {
        let state = run(&[data(0b1000, 1, 0)], |state| {
            state.r[0] = 0x8000_0001;
            state.r[1] = 0x8000_0000;
            state.it = LAST_OF_IT_AL;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0x8000_0001, [1, 0, 0, 0]));
    }

    /// The register shifts, A7.7.68, A7.7.70, A7.7.11 and A7.7.115, take the bottom byte of
    /// `R[m]`, so 0x104 shifts by 4.
    #[test]
    fn a_register_shift_takes_the_bottom_byte() {
        let cases = [
            (0b0010, 0x1800_0001, 0x104, 0x8000_0010, [1, 0, 1, 0]),
            (0b0011, 0x8000_0018, 0x104, 0x0800_0001, [0, 0, 1, 0]),
            (0b0100, 0x8000_0018, 0x104, 0xF800_0001, [1, 0, 1, 0]),
            (0b0111, 0x0000_0018, 0x104, 0x8000_0001, [1, 0, 1, 0]),
        ];
        for (opcode, value, by, result, flags) in cases {
            let state = run(&[data(opcode, 1, 0)], |state| {
                state.r[0] = value;
                state.r[1] = by;
            });
            assert_eq!((state.r[0], nzcv(&state)), (result, flags), "{opcode:#06b}");
        }
    }

    /// `Shift_C`, A7.4.2: by 0 keeps C, LSL by 32 takes C from bit 0, and past 32 gives zero with
    /// C clear. ROR by 32 is the value, with C from bit 31.
    #[test]
    fn a_register_shift_by_0_32_or_more_follows_shift_c() {
        let cases = [
            (0b0010, 0x8000_0001, 0x100, 0x8000_0001, [1, 0, 1, 1]),
            (0b0010, 0x0000_0001, 32, 0, [0, 1, 1, 1]),
            (0b0010, 0xFFFF_FFFF, 33, 0, [0, 1, 0, 1]),
            (0b0011, 0x8000_0000, 32, 0, [0, 1, 1, 1]),
            (0b0011, 0xFFFF_FFFF, 0xFF, 0, [0, 1, 0, 1]),
            (0b0100, 0x8000_0000, 0xFF, 0xFFFF_FFFF, [1, 0, 1, 1]),
            (0b0100, 0x7FFF_FFFF, 40, 0, [0, 1, 0, 1]),
            (0b0111, 0x8000_0000, 32, 0x8000_0000, [1, 0, 1, 1]),
            (0b0111, 0x7000_0000, 64, 0x7000_0000, [0, 0, 0, 1]),
        ];
        for (opcode, value, by, result, flags) in cases {
            let state = run(&[data(opcode, 1, 0)], |state| {
                state.r[0] = value;
                state.r[1] = by;
                set_nzcv(state, [0, 0, 1, 1]);
            });
            assert_eq!(
                (state.r[0], nzcv(&state)),
                (result, flags),
                "{opcode:#06b} {value:#x} by {by}"
            );
        }
    }

    /// ADC (register) T1, A7.7.2, adds C.
    #[test]
    fn adc_adds_the_carry() {
        let state = run(&[data(0b0101, 1, 0)], |state| {
            state.r[0] = 0xFFFF_FFFF;
            state.r[1] = 0;
            state.c = 1;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0, [0, 1, 1, 0]));
        let state = run(&[data(0b0101, 1, 0)], |state| {
            state.r[0] = 0x7FFF_FFFF;
            state.r[1] = 0;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0x7FFF_FFFF, [0, 0, 0, 0]));
    }

    /// SBC (register) T1, A7.7.123, takes one more when C is clear.
    #[test]
    fn sbc_takes_not_carry_more() {
        let state = run(&[data(0b0110, 1, 0)], |state| {
            state.r[0] = 5;
            state.r[1] = 5;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0xFFFF_FFFF, [1, 0, 0, 0]));
        let state = run(&[data(0b0110, 1, 0)], |state| {
            state.r[0] = 5;
            state.r[1] = 5;
            state.c = 1;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0, [0, 1, 1, 0]));
    }

    /// RSB (immediate) T1, A7.7.117, negates `R[n]`, bits 5 to 3, into `R[d]`.
    #[test]
    fn rsb_negates() {
        let cases = [
            (0, 0, [0, 1, 1, 0]),
            (1, 0xFFFF_FFFF, [1, 0, 0, 0]),
            (0x8000_0000, 0x8000_0000, [1, 0, 0, 1]),
        ];
        for (value, result, flags) in cases {
            let state = run(&[data(0b1001, 1, 0)], |state| {
                state.r[0] = 0x1234;
                state.r[1] = value;
            });
            assert_eq!((state.r[0], nzcv(&state)), (result, flags), "-{value:#x}");
            assert_eq!(state.r[1], value);
        }
    }

    /// CMP and CMN (register) T1, A7.7.28 and A7.7.26, set the flags and write nothing.
    #[test]
    fn cmp_and_cmn_register_set_the_flags_and_write_nothing() {
        let state = run(&[data(0b1010, 1, 0)], |state| {
            state.r[0] = 3;
            state.r[1] = 5;
        });
        assert_eq!((state.r[0], nzcv(&state)), (3, [1, 0, 0, 0]));
        let state = run(&[data(0b1011, 1, 0)], |state| {
            state.r[0] = 0xFFFF_FFFB;
            state.r[1] = 5;
            state.it = LAST_OF_IT_AL;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0xFFFF_FFFB, [0, 1, 1, 0]));
    }

    /// MUL T1, A7.7.83: the low 32 bits of the product, N and Z from them, C and V kept.
    #[test]
    fn mul_keeps_the_low_word_and_c_and_v() {
        let state = run(&[data(0b1101, 1, 0)], |state| {
            state.r[0] = 0x1_0001;
            state.r[1] = 0xFFFF;
            set_nzcv(state, [0, 1, 1, 1]);
        });
        assert_eq!((state.r[0], nzcv(&state)), (0xFFFF_FFFF, [1, 0, 1, 1]));
        let state = run(&[data(0b1101, 1, 0)], |state| {
            state.r[0] = 0x1_0000;
            state.r[1] = 0x1_0000;
        });
        assert_eq!((state.r[0], nzcv(&state)), (0, [0, 1, 0, 0]));
    }

    /// Every Table A5-3 instruction that writes a register takes `setflags = !InITBlock()`, A7.7.9,
    /// A7.7.35, A7.7.68, A7.7.70, A7.7.11, A7.7.2, A7.7.123, A7.7.115, A7.7.117, A7.7.91, A7.7.83,
    /// A7.7.16 and A7.7.85. Each case gives `[R0, R1]`.
    #[test]
    fn data_processing_sets_flags_only_outside_an_it_block() {
        let cases = [
            (0b0000, [0x0F, 0x0B], [1, 1, 1, 1], 0x0B, [0, 0, 1, 1]),
            (0b0001, [0x0F, 0x01], [1, 1, 1, 1], 0x0E, [0, 0, 1, 1]),
            (0b0010, [0x8000_0001, 1], [1, 1, 0, 1], 2, [0, 0, 1, 1]),
            (0b0011, [3, 1], [1, 1, 0, 0], 1, [0, 0, 1, 0]),
            (0b0100, [3, 1], [1, 1, 0, 0], 1, [0, 0, 1, 0]),
            (0b0101, [0xFFFF_FFFF, 2], [1, 1, 0, 1], 1, [0, 0, 1, 0]),
            (0b0110, [5, 3], [1, 1, 0, 1], 1, [0, 0, 1, 0]),
            (0b0111, [6, 1], [1, 1, 1, 0], 3, [0, 0, 0, 0]),
            (0b1001, [0x1234, 0xFFFF_FFFF], [1, 1, 1, 1], 1, [0, 0, 0, 0]),
            (0b1100, [0x10, 0x01], [1, 1, 1, 1], 0x11, [0, 0, 1, 1]),
            (0b1101, [3, 5], [1, 1, 1, 1], 15, [0, 0, 1, 1]),
            (0b1110, [0x0F, 0x01], [1, 1, 1, 1], 0x0E, [0, 0, 1, 1]),
            (0b1111, [0, 0xFFFF_FFF0], [1, 1, 1, 1], 0x0F, [0, 0, 1, 1]),
        ];
        for (opcode, [first, second], preset, result, flags) in cases {
            let registers = [first, second, 0];
            sets_flags_only_outside_it(data(opcode, 1, 0), registers, preset, result, flags);
        }
    }

    /// ADD (register) T2, A7.7.4, adds high registers without setting flags, and reads the PC as
    /// this instruction's address plus 4, unaligned.
    #[test]
    fn add_high_registers_sets_no_flags_and_reads_the_pc_plus_4() {
        let state = run(&[high(0, 8, 1), high(0, 0, 15)], |state| {
            state.r[8] = 0xFFFF_FFFF;
            state.r[1] = 1;
            state.r[0] = 0x100;
        });
        assert_eq!((state.r[8], nzcv(&state)), (0, [0, 0, 0, 0]));
        assert_eq!(state.r[0], 0x100 + 2 + 4);
    }

    /// ADD (SP plus register) T1 and T2, A7.7.6. A write to SP drops bits 1 and 0, B1.4.7.
    #[test]
    fn add_sp_plus_register_writes_either_side_and_keeps_sp_aligned() {
        let state = run(&[high(0, 1, 13), high(0, 13, 2)], |state| {
            state.r[1] = 0x10;
            state.r[2] = 0x7;
        });
        assert_eq!(state.r[1], top_of_stack() + 0x10);
        assert_eq!(state.r[13], top_of_stack() + 4);
    }

    /// ADD (register) T2 to the PC is `ALUWritePC()`, A2.3.1, which drops bit 0 and keeps T.
    #[test]
    fn add_to_the_pc_branches() {
        let state = run(&[high(0, 15, 1)], |state| state.r[1] = 0x101);
        assert_eq!((state.r[15], state.t), (0x104, 1));
    }

    /// ADD with the PC on both sides is UNPREDICTABLE, A7.7.4, and branches to their sum.
    #[test]
    fn add_pc_to_the_pc_branches_to_the_sum() {
        let state = run(&[high(0, 15, 15)], |_| {});
        assert_eq!(state.r[15], 8);
    }

    /// CMP (register) T2, A7.7.28, compares high registers, and two low ones as its pseudocode
    /// does where Table A5-4 calls it UNPREDICTABLE.
    #[test]
    fn cmp_high_registers_sets_the_flags() {
        let state = run(&[high(1, 8, 9)], |state| {
            state.r[8] = 0x8000_0000;
            state.r[9] = 1;
        });
        assert_eq!(nzcv(&state), [0, 0, 1, 1]);
        let state = run(&[high(1, 1, 2)], |state| {
            state.r[1] = 7;
            state.r[2] = 7;
        });
        assert_eq!(nzcv(&state), [0, 1, 1, 0]);
        let state = run(&[high(1, 15, 0)], |state| state.r[0] = 4);
        assert_eq!(nzcv(&state), [0, 1, 1, 0], "the PC reads as 4");
    }

    /// MOV (register) T1, A7.7.76, moves any register and sets no flags.
    #[test]
    fn mov_high_registers_sets_no_flags() {
        let state = run(&[high(2, 8, 1), high(2, 0, 15), high(2, 13, 2)], |state| {
            state.r[1] = 0;
            state.r[2] = 0x2000_1003;
            set_nzcv(state, [1, 0, 1, 0]);
        });
        assert_eq!(
            (state.r[8], state.r[0], state.r[13]),
            (0, 2 + 4, 0x2000_1000)
        );
        assert_eq!(nzcv(&state), [1, 0, 1, 0]);
    }

    /// MOV (register) T1 to the PC is `ALUWritePC()`, A2.3.1.
    #[test]
    fn mov_to_the_pc_branches() {
        let state = run(&[high(2, 15, 1)], |state| state.r[1] = 0x201);
        assert_eq!((state.r[15], state.t), (0x200, 1));
    }

    /// A write to the PC inside an IT block, not last in it, is UNPREDICTABLE, A7.7.76, and
    /// branches all the same.
    #[test]
    fn a_pc_write_inside_an_it_block_not_last_branches() {
        for hw in [high(2, 15, 1), high(0, 15, 1), bx(1), blx(1)] {
            let state = run(&[hw], |state| {
                state.r[1] = 0x41;
                state.it = FIRST_OF_ITT_AL;
            });
            let at = if hw == high(0, 15, 1) { 0x44 } else { 0x40 };
            assert_eq!(state.r[15], at, "{hw:#06x}");
        }
    }

    /// BX, A7.7.20, sets `EPSR.T` from bit 0 and branches to the rest.
    #[test]
    fn bx_takes_t_from_bit_0() {
        let state = run(&[bx(1)], |state| state.r[1] = 0x301);
        assert_eq!((state.r[15], state.t), (0x300, 1));
        let state = run(&[bx(1)], |state| state.r[1] = 0x300);
        assert_eq!((state.r[15], state.t), (0x300, 0));
    }

    /// BX with any of bits 2 to 0 set is UNPREDICTABLE, A5.1.1, and runs as BX.
    #[test]
    fn bx_ignores_its_should_be_zero_bits() {
        let state = run(&[bx(1) | 0b111], |state| state.r[1] = 0x301);
        assert_eq!((state.r[15], state.t, state.r[14]), (0x300, 1, 0));
    }

    /// BLX (register), A7.7.19, links the next instruction's address with bit 0 set, and reads
    /// its target before it writes LR.
    #[test]
    fn blx_links_and_branches() {
        let state = run(&[high(2, 0, 0), blx(14)], |state| state.r[14] = 0x401);
        assert_eq!((state.r[15], state.t, state.r[14]), (0x400, 1, 0x5));
        let state = run(&[blx(1) | 0b111], |state| state.r[1] = 0x400);
        assert_eq!((state.r[15], state.t, state.r[14]), (0x400, 0, 0x3));
    }

    /// `BLXWritePC()`, A2.3.1, has no exception return, so BLX to `0xFFFF_FFF9` in Handler mode
    /// branches there.
    #[test]
    fn blx_in_handler_mode_is_never_an_exception_return() {
        let state = run(&[blx(1)], |state| {
            state.r[1] = 0xFFFF_FFF9;
            state.ipsr = 3;
        });
        assert_eq!((state.r[15], state.t, state.r[14]), (0xFFFF_FFF8, 1, 0x3));
    }

    /// BLX of the PC is UNPREDICTABLE, A7.7.19, and goes to this address plus 4 with T clear.
    #[test]
    fn blx_of_the_pc_clears_t() {
        let state = run(&[blx(15)], |_| {});
        assert_eq!((state.r[15], state.t, state.r[14]), (4, 0, 3));
    }

    /// ADR T1, A7.7.7, adds to `Align(PC, 4)`.
    #[test]
    fn adr_adds_to_the_aligned_pc() {
        let state = run(&[0xA000 | 1 << 8, 0xA000 | 2 << 8 | 0xFF], |_| {});
        assert_eq!((state.r[1], state.r[2]), (4, 4 + 0x3FC));
    }

    /// ADD (SP plus immediate) T1, A7.7.5, writes SP plus `imm8:'00'` and sets no flags. They start
    /// where the sum would move every one of them.
    #[test]
    fn add_sp_immediate_adds_a_word_offset() {
        let state = run(&[0xA800 | 3 << 8 | 0xFF], |state| {
            set_nzcv(state, [1, 1, 1, 1]);
        });
        assert_eq!(
            (state.r[3], nzcv(&state)),
            (top_of_stack() + 0x3FC, [1, 1, 1, 1])
        );
    }

    /// ADD (SP plus immediate) T2 and SUB (SP minus immediate) T1, A7.7.5 and A7.7.173, set no
    /// flags. They start where the sum or difference would move every one of them.
    #[test]
    fn sp_moves_by_a_word_multiple() {
        let state = run(&[0xB000 | 0x7F], |state| set_nzcv(state, [1, 1, 1, 1]));
        assert_eq!(
            (state.r[13], nzcv(&state)),
            (top_of_stack() + 0x1FC, [1, 1, 1, 1])
        );
        let state = run(&[0xB080 | 0x7F], |state| set_nzcv(state, [1, 1, 0, 1]));
        assert_eq!(
            (state.r[13], nzcv(&state)),
            (top_of_stack() - 0x1FC, [1, 1, 0, 1])
        );
        let state = run(&[0xB000 | 0x7F, 0xB080 | 1], |_| {});
        assert_eq!(state.r[13], top_of_stack() + 0x1FC - 4);
    }

    /// SXTH, SXTB, UXTH and UXTB T1, A7.7.181, A7.7.179, A7.7.220 and A7.7.218.
    #[test]
    fn the_extends_take_the_low_byte_or_halfword() {
        let cases = [
            (0b00, 0x1234_8001, 0xFFFF_8001),
            (0b00, 0x8765_7001, 0x7001),
            (0b01, 0x1234_5680, 0xFFFF_FF80),
            (0b01, 0x8765_437F, 0x7F),
            (0b10, 0xFFFF_8001, 0x8001),
            (0b11, 0x1234_56F0, 0xF0),
        ];
        for (op, value, result) in cases {
            let state = run(&[extend_hw(op, 1, 0)], |state| {
                state.r[1] = value;
                set_nzcv(state, [0, 1, 0, 1]);
            });
            assert_eq!(state.r[0], result, "{op:#04b} of {value:#x}");
            assert_eq!(nzcv(&state), [0, 1, 0, 1]);
        }
    }

    /// REV, REV16 and REVSH T1, A7.7.111 to A7.7.113.
    #[test]
    fn the_reverses_swap_bytes() {
        let cases = [
            (0b00, 0x1234_5678, 0x7856_3412),
            (0b01, 0x1234_5678, 0x3412_7856),
            (0b11, 0x1234_5680, 0xFFFF_8056),
            (0b11, 0x1234_8070, 0x7080),
        ];
        for (op, value, result) in cases {
            let state = run(&[reverse_hw(op, 1, 0)], |state| {
                state.r[1] = value;
            });
            assert_eq!(state.r[0], result, "{op:#04b} of {value:#x}");
        }
    }

    /// Table A5-6 allocates nothing to `101010x`, so it's UNDEFINED, A5.2.5.
    #[test]
    fn the_gap_among_the_reverses_is_undefined() {
        for hw in [reverse_hw(0b10, 0, 0), reverse_hw(0b10, 7, 7)] {
            assert_eq!(translated(reverse, hw), Err(Undefined), "{hw:#06x}");
            assert_eq!(translated(super::super::decode16, hw), Err(Undefined));
        }
        assert_eq!(translated(reverse, reverse_hw(0b11, 0, 0)), Ok(()));
    }
}