m68k 0.18.1

A safe Rust M68000 family CPU emulator
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
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
//! FPU instruction decode and execution for 68881/68882, 68040, and 68060
//! configurations.
//!
//! Arithmetic uses the pure-Rust extended-precision engine, including FPCR
//! rounding, FPSR exception state, packed-decimal formats, transcendentals,
//! conditionals, register moves, and CPU-specific FSAVE/FRESTORE frames.

use super::packed;
use super::softfloat::{self, ExcFlags, FpCmp, Precision, RoundCtx, RoundMode};
use super::transcendental;
use crate::core::cpu::CpuCore;
use crate::core::ea::{AddressingMode, EaResult};
use crate::core::memory::AddressBus;
use crate::core::types::Size;
use crate::fpu::FloatX80;

/// FPCR bits that exist: the exception-enable byte (15-8) and the mode
/// control byte's rounding precision and mode (7-4).
const FPCR_IMPLEMENTED: u32 = 0x0000_FFF0;
/// FPSR bits that exist: condition codes (27-24), quotient (23-16),
/// exception status (15-8) and the accrued exceptions (7-3).
const FPSR_IMPLEMENTED: u32 = 0x0FFF_FFF8;

/// Where a resolved FPU operand lives.
pub(super) enum FpuEa {
    /// Data register (formats of 4 bytes or fewer only).
    DataReg(usize),
    /// Memory address.
    Memory(u32),
    /// Immediate data, to be consumed from the instruction stream.
    Immediate,
}

/// A source operand as fetched, before conversion to extended.
#[derive(Clone, Copy)]
pub(super) enum RawSource {
    Long(u32),
    Word(u16),
    Byte(u8),
    Single(u32),
    Double(u64),
    /// Sign and exponent word, mantissa.
    Extended(u16, u64),
    /// The three longs of a packed decimal real.
    Packed([u32; 3]),
}

impl RawSource {
    /// Widen to extended, raising the exceptions of the conversion: SNAN
    /// for a single or double signaling NaN, INEX1 for packed decimal.
    pub(super) fn to_x80(self, f: &mut ExcFlags) -> FloatX80 {
        match self {
            RawSource::Long(v) => FloatX80::from_f64(v as i32 as f64),
            RawSource::Word(v) => FloatX80::from_f64(v as i16 as f64),
            RawSource::Byte(v) => FloatX80::from_f64(v as i8 as f64),
            RawSource::Single(v) => single_to_x80(v, f),
            RawSource::Double(v) => double_to_x80(v, f),
            RawSource::Extended(exp_word, mantissa) => FloatX80::from_extended(exp_word, mantissa),
            RawSource::Packed(w) => packed::from_packed(words_to_bytes(w[0], w[1], w[2]), f),
        }
    }
}

/// Whether a general FP instruction (operation word `opcode`, command
/// word `w2`) uses an effective address the 68060 does not implement
/// (M68060UM 6.5.3): an extended-precision or packed immediate source,
/// FMOVEM.L #imm to more than one control register, or FMOVEM.X with its
/// register list in a data register.
fn fpu_060_unimplemented_ea(opcode: u16, w2: u16) -> bool {
    let immediate = opcode & 0x3F == 0x3C;
    match w2 >> 13 {
        0x2 => immediate && matches!((w2 >> 10) & 0x7, 2 | 3),
        0x4 => immediate && ((w2 >> 10) & 0x7).count_ones() >= 2,
        0x6 | 0x7 => w2 & 0x0800 != 0,
        _ => false,
    }
}

/// The FP opmodes the 68060 dropped from silicon, emulated by the 68060SP:
/// the transcendental set, FGETEXP/FGETMAN, FMOD/FREM/FSCALE, and FSINCOS
/// (FMOVECR is gated separately by encoding). FINT/FINTRZ, which the 68040
/// lacks, are back in 68060 hardware, as are FSGLMUL/FSGLDIV and every
/// rounded (FS/FD-prefixed) variant. Keep in sync with fpu_apply_op's table.
fn fpu_060_traps_opmode(opmode: u16) -> bool {
    matches!(
        opmode,
        0x02 | 0x06
            | 0x08
            | 0x09
            | 0x0A
            | 0x0C
            | 0x0D
            | 0x0E
            | 0x0F
            | 0x10
            | 0x11
            | 0x12
            | 0x14
            | 0x15
            | 0x16
            | 0x19
            | 0x1C
            | 0x1D
            | 0x1E
            | 0x1F
            | 0x21
            | 0x25
            | 0x26
            | 0x30..=0x37
    )
}

/// The FP opmodes the 68040 leaves to the M68040FPSP (M68040UM table 9-10,
/// section 9.6.1): the 68060's list plus FINT and FINTRZ. FLOG2 is missing from
/// that table but is emulated by the FPSP (Apple Technote HW 23) and is not
/// among the 68040's native instructions. FMOVECR is gated separately by
/// encoding. FSGLMUL/FSGLDIV and every rounded (FS/FD-prefixed) variant are in
/// hardware.
pub(super) fn fpu_040_traps_opmode(opmode: u16) -> bool {
    matches!(opmode, 0x01 | 0x03) || fpu_060_traps_opmode(opmode)
}

/// Truncate a finite operand's mantissa to its 24 most significant bits,
/// the FSGLMUL input reduction (M68000PM 3-157). NaNs keep their payload
/// and infinities their encoding.
fn sgl_truncate(v: FloatX80) -> FloatX80 {
    if v.is_nan() || v.is_inf() {
        return v;
    }
    FloatX80 {
        mantissa: v.mantissa & 0xFFFF_FF00_0000_0000,
        ..v
    }
}

/// An extended-precision operand as the FPU computes with it.
///
/// A zero mantissa is a zero whatever the exponent field holds (see
/// [`FloatX80::is_zero`]) and gets the zero exponent the arithmetic
/// returns and stores. An unnormalized number, one with a nonzero
/// exponent field and the integer bit clear, is normalized first
/// (MC68881/MC68882UM 3.5.1; the 68040's and 68060's packages do the same
/// for the part): its mantissa is shifted up and the exponent brought
/// down with it, as far as a zero exponent, where it is a denormalized
/// number. FMOVEM loads registers without conversion, so a register can
/// hold either.
#[inline(always)]
fn canonical_operand(v: FloatX80) -> FloatX80 {
    if is_canonical(v) {
        v
    } else {
        canonical_operand_slow(v)
    }
}

/// Whether [`canonical_operand`] leaves `v` as it is: a normalized number
/// (integer bit set), an infinity or NaN, or the canonical zero. The
/// common case, tested without touching the register file.
#[inline(always)]
fn is_canonical(v: FloatX80) -> bool {
    v.mantissa >> 63 != 0
        || v.biased_exp() == 0x7FFF
        || (v.mantissa == 0 && v.sign_exp & 0x7FFF == 0)
}

#[cold]
#[inline(never)]
fn canonical_operand_slow(v: FloatX80) -> FloatX80 {
    let exp = v.biased_exp();
    if exp == 0x7FFF {
        v
    } else if v.mantissa == 0 {
        FloatX80::zero(v.sign())
    } else {
        let shift = v.mantissa.leading_zeros().min(u32::from(exp));
        FloatX80 {
            sign_exp: v.sign_exp - shift as u16,
            mantissa: v.mantissa << shift,
        }
    }
}

/// Whether `v` is a denormalized number: nonzero, with a zero exponent
/// field and the integer bit clear. Such a result is an underflow whether
/// or not it is exact (MC68881/MC68882UM 6.1.5).
fn is_denormalized(v: FloatX80) -> bool {
    v.biased_exp() == 0 && v.mantissa != 0 && v.mantissa >> 63 == 0
}

/// Sign-extend a 7-bit FMOVE k-factor to i8.
fn sign_extend7(v: u16) -> i8 {
    let raw = (v & 0x7F) as i16;
    (if raw >= 0x40 { raw - 0x80 } else { raw }) as i8
}

/// Pack three big-endian longwords into the 12-byte packed-decimal layout.
fn words_to_bytes(w0: u32, w1: u32, w2: u32) -> [u8; 12] {
    let mut b = [0u8; 12];
    b[0..4].copy_from_slice(&w0.to_be_bytes());
    b[4..8].copy_from_slice(&w1.to_be_bytes());
    b[8..12].copy_from_slice(&w2.to_be_bytes());
    b
}

/// Widen a binary32 operand to extended. A signaling NaN raises SNAN and
/// is converted quiet with its payload kept (MC68881/MC68882UM 4.6.4); every
/// other value is exact in extended.
fn single_to_x80(bits: u32, f: &mut ExcFlags) -> FloatX80 {
    let frac = bits & 0x007F_FFFF;
    if (bits >> 23) & 0xFF == 0xFF && frac != 0 {
        if frac & 0x0040_0000 == 0 {
            f.raise(ExcFlags::SNAN);
        }
        return FloatX80 {
            sign_exp: (((bits >> 31) as u16) << 15) | 0x7FFF,
            mantissa: 0xC000_0000_0000_0000 | (u64::from(frac) << 40),
        };
    }
    FloatX80::from_f64(f64::from(f32::from_bits(bits)))
}

/// Widen a binary64 operand to extended, raising SNAN for a signaling NaN
/// (converted quiet, payload kept).
fn double_to_x80(bits: u64, f: &mut ExcFlags) -> FloatX80 {
    if (bits >> 52) & 0x7FF == 0x7FF && bits & 0x000F_FFFF_FFFF_FFFF != 0 && bits & (1 << 51) == 0 {
        f.raise(ExcFlags::SNAN);
    }
    // from_f64 reads the bit pattern: NaNs come out quiet with the payload.
    FloatX80::from_f64(f64::from_bits(bits))
}

/// FADD, FMUL, FSUB and FDIV with their single- and double-rounded forms:
/// `dst = dst op src` rounded per [`CpuCore::fpu_ctx`].
#[derive(Clone, Copy, PartialEq, Eq)]
enum Dyadic {
    Add,
    Mul,
    Sub,
    Div,
}

impl Dyadic {
    /// The opmodes: $20/$22/$23/$28 and their FS ($40 set) and FD ($44
    /// set) forms.
    const OPMODES: u128 = {
        let mut mask = 0u128;
        let base = [0x20, 0x22, 0x23, 0x28];
        let mut i = 0;
        while i < base.len() {
            mask |= (1 << base[i]) | (1 << (base[i] | 0x40)) | (1 << (base[i] | 0x44));
            i += 1;
        }
        mask
    };

    /// Classify with a mask and bit tests rather than a `match`, which
    /// the compiler turns into the jump table this path exists to avoid.
    #[inline(always)]
    fn of(opmode: u16) -> Option<Self> {
        if opmode > 0x7F || (Self::OPMODES >> opmode) & 1 == 0 {
            None
        } else if opmode & 0x08 != 0 {
            Some(Self::Sub)
        } else if opmode & 0x01 != 0 {
            Some(Self::Mul)
        } else if opmode & 0x02 != 0 {
            Some(Self::Add)
        } else {
            Some(Self::Div)
        }
    }
}

/// The FP data registers a general operation can write, as they were
/// before it: its destination and, for FSINCOS, the cosine's register.
/// An exception that stops the operation before it stores a result puts
/// them back. Saving two registers instead of all eight keeps the copy
/// off every FP instruction's path.
#[derive(Clone, Copy)]
pub(super) struct FprUndo {
    dst: usize,
    dst_value: FloatX80,
    cos: usize,
    cos_value: FloatX80,
}

impl FprUndo {
    /// The registers the operation of command word `w2` can write. Saving
    /// one it does not write is harmless (restoring it changes nothing),
    /// so FMOVECR, whose low bits are a ROM offset, needs no special case.
    #[inline(always)]
    pub(super) fn before(fpr: &[FloatX80; 8], w2: u16) -> Self {
        let dst = ((w2 >> 7) & 7) as usize;
        let cos = if (0x30..=0x37).contains(&(w2 & 0x7F)) {
            (w2 & 7) as usize
        } else {
            dst
        };
        Self {
            dst,
            dst_value: fpr[dst],
            cos,
            cos_value: fpr[cos],
        }
    }

    /// The destination register before the operation.
    #[inline(always)]
    pub(super) fn dst_before(&self) -> FloatX80 {
        self.dst_value
    }

    /// Put back every register the operation may have written.
    #[inline(always)]
    pub(super) fn restore(&self, fpr: &mut [FloatX80; 8]) {
        fpr[self.cos] = self.cos_value;
        fpr[self.dst] = self.dst_value;
    }
}

impl CpuCore {
    /// Execute a general 6888x/68040/68060 F-line operation (`0xF2xx`).
    ///
    /// Handles arithmetic, FMOVE, control, conditional, and save/restore
    /// operations according to the configured CPU model. Unsupported encodings
    /// return zero so the caller can raise the Line-F exception.
    pub fn exec_fpu_op0<B: AddressBus>(&mut self, bus: &mut B, opcode: u16) -> i32 {
        use crate::core::types::CpuType;

        // LC040 and EC040 don't have integrated FPUs - must trap as Line-F
        if matches!(self.cpu_type, CpuType::M68LC040 | CpuType::M68EC040) {
            return 0;
        }

        // IMPORTANT:
        // - PC currently points at the first extension word (w2).
        // - We must NOT consume w2 (or any EA extension) unless we handle the instruction.

        let w2 = self.read_16(bus, self.pc);
        let subop = (w2 >> 13) & 0x7;

        // An effective address the 68060 does not implement takes vector
        // 60 with a format $0 frame whose PC is the instruction's; FPIAR
        // is not written (M68060UM 6.5.3 and 8.2.4).
        let unimplemented_ea = self.trap_unimpl_060() && fpu_060_unimplemented_ea(opcode, w2);

        // 68060 with the FPU disabled through PCR.DFP (also how an LC/EC060
        // presents): every FP instruction takes the format $4 disabled
        // frame. The unimplemented effective address is recognised first
        // even then: the M68060SP's handler for it tests PCR.DFP itself
        // and builds the disabled frame.
        if self.is_060() && (self.pcr & crate::core::cpu::PCR_DFP) != 0 {
            if unimplemented_ea {
                return self
                    .take_exception(bus, crate::core::exceptions::vector::FP_UNIMPLEMENTED_EA);
            }
            return self.take_fp_disabled_060(bus);
        }

        // An exception the previous FPU operation left unreported is
        // taken now, before this instruction does anything. The moves of
        // the system control registers and FMOVEM do not report it
        // (MC68881/MC68882UM 4.6, "FMOVE system control register" and
        // "FMOVEM"): a handler uses them to read and repair the registers.
        // On the 68060 every instruction but FSAVE and FRESTORE reports
        // it (M68060UM 6.7), and an arithmetic or FMOVE instruction that
        // goes ahead replaces the state an earlier exception left.
        if (self.is_060() || !matches!(subop, 0x4..=0x7))
            && let Some(cycles) = self.fpu_take_pending_exception(bus)
        {
            return cycles;
        }
        // The unimplemented effective address also comes before the
        // unimplemented-instruction exception: the package's handler for
        // it emulates FSIN and the other instructions the 68060 lacks
        // when their source is such an immediate. The instruction has
        // not executed, so nothing of the FPU's state changes.
        if unimplemented_ea {
            return self.take_exception(bus, crate::core::exceptions::vector::FP_UNIMPLEMENTED_EA);
        }

        if matches!(subop, 0x0 | 0x2 | 0x3) {
            self.fpu_060_excp = None;
        }

        // Executing any general FPU instruction takes the 6888x out of
        // its reset NULL state (FSAVE then produces a real frame).
        self.fpu_just_reset = false;

        // A 68040 exception still held in the FPU's state is taken by the
        // next general instruction, before it executes: the result of an
        // E3 exception is not in its register until the handler has run,
        // so FMOVEM and the control-register moves report it too. Only an
        // arithmetic or FMOVE instruction that goes ahead replaces the
        // state the handler of an earlier exception may still save.
        if !self.fpu_040.is_idle() {
            let reported = if matches!(subop, 0x0 | 0x2 | 0x3) {
                self.fpu_040_pre_instruction(bus)
            } else {
                self.fpu_040_report_pending(bus)
            };
            if let Some(cycles) = reported {
                return cycles;
            }
        }

        match subop {
            0x2 => {
                // FPU ALU <ea>, FPn -- the memory/immediate-source form of
                // the full opmode set (FMOVE, the monadic ops, the
                // transcendentals, and the dyadic arithmetic). Shares the
                // fpu_apply_op dispatch table with the register-source path
                // below so the two cannot drift apart.
                let src_fmt = (w2 >> 10) & 0x7;
                let dst = ((w2 >> 7) & 7) as usize;
                let opmode = w2 & 0x7f;

                // The single/double-rounded opmodes are 68040/68060
                // additions; FMOVECR (format 7) carries a ROM offset there.
                if src_fmt != 7 && self.fpu_6888x_illegal_opmode(opmode) {
                    return 0;
                }

                // Consume w2 now that we're committed.
                let _w2 = self.read_imm_16(bus);

                if src_fmt == 7 {
                    // FMOVECR was dropped from 68060 silicon.
                    if self.trap_unimpl_060() {
                        return self.take_fp_unimp_060(bus, 0);
                    }
                    if self.trap_unimpl_040() {
                        // A non-zero <ea> field is a format $0 F-line
                        // exception, which the FPSP's fline handler decodes.
                        if opcode & 0x3F != 0 {
                            return self
                                .take_exception(bus, crate::core::exceptions::vector::LINE_1111);
                        }
                        return self.fpu_040_fmovecr_trap(bus, w2);
                    }
                    // FMOVECR - load constant from ROM. The opmode field is
                    // the ROM index; there is no <ea> source operand.
                    self.fpiar = self.ppc;
                    let registers = FprUndo::before(&self.fpr, w2);
                    let ctx = self.fpu_ctx(0);
                    let mut f = ExcFlags::default();
                    self.fpr[dst] = softfloat::fmovecr(opmode as usize, ctx, &mut f);
                    self.fpu_set_cc(self.fpr[dst]);
                    self.fpu_commit(f);
                    return self.fpu_op_exception(4, w2, FloatX80::default(), &registers);
                }

                if self.trap_unimpl_060() && fpu_060_traps_opmode(opmode) {
                    // Unimplemented FP instruction: resolve the operand EA
                    // (consuming its extension words - the frame needs the
                    // next-instruction PC) and take the format $2 trap.
                    let ea = self.fpu_060_trap_ea(bus, opcode, src_fmt);
                    return self.take_fp_unimp_060(bus, ea);
                }
                if self.trap_unimpl_060() && src_fmt == 3 {
                    // Packed decimal: unsupported data type in 060 hardware
                    // (the immediate form was an unimplemented <ea>, above).
                    // Format $2 frame with the operand's address: the
                    // M68060SP reads the packed number through it.
                    let ea = self.fpu_060_trap_ea(bus, opcode, src_fmt);
                    return self.take_fp_unsupp_packed_060(bus, ea);
                }

                // 68040 with traps: the instructions and data types left to
                // the M68040FPSP, and the state frames its handlers save.
                if self.trap_unimpl_040()
                    && let Some(cycles) = self.fpu_040_ea_source(bus, opcode, w2)
                {
                    return cycles;
                }

                self.fpiar = self.ppc;
                if self.is_060() {
                    // The 68060's EXCP frame holds the source operand,
                    // which for a single or double is not its value.
                    let Some((raw, _)) = self.fpu_fetch_source(bus, opcode, src_fmt) else {
                        return 0;
                    };
                    let mut flags = ExcFlags::default();
                    let src = raw.to_x80(&mut flags);
                    let operand = self.fpu_060_source_operand(raw, src);
                    if self
                        .fpu_060_unsupp_operands(w2, super::exceptions_060::source_unsupported(raw))
                    {
                        return self.fpu_060_take_unsupp(bus, operand);
                    }
                    let registers = FprUndo::before(&self.fpr, w2);
                    let cycles = self.fpu_apply_op(opmode, dst, src, flags);
                    return self.fpu_060_hold_exception(cycles, w2, operand, src, &registers);
                }
                let Some((src, src_flags)) = self.fpu_read_source(bus, opcode, src_fmt) else {
                    return 0;
                };
                self.fpu_general_op(w2, src, src_flags)
            }
            0x3 => {
                // FMOVE FP, <ea> - move FP register to memory/integer register
                let dst_fmt = (w2 >> 10) & 0x7;
                let src = ((w2 >> 7) & 7) as usize;

                // Packed-decimal output is an unsupported data type in 68060
                // hardware (both static and dynamic k-factor forms): the
                // format $2 frame with the destination's address.
                if self.trap_unimpl_060() && (dst_fmt == 3 || dst_fmt == 7) {
                    let _w2 = self.read_imm_16(bus);
                    let ea = self.fpu_060_trap_ea(bus, opcode, 3);
                    return self.take_fp_unsupp_packed_060(bus, ea);
                }

                if let Some(cycles) = self.fpu_060_move_out_unsupp(bus, opcode, w2) {
                    return cycles;
                }

                if self.trap_unimpl_040()
                    && let Some(cycles) = self.fpu_040_move_out(bus, opcode, w2)
                {
                    return cycles;
                }

                // Packed-decimal k-factor: static (fmt 3) in w2 bits 6-0;
                // dynamic (fmt 7) in bits 6-0 of the Dn named by w2 bits 6-4.
                let kfactor = match dst_fmt {
                    3 => sign_extend7(w2),
                    7 => sign_extend7(self.d(((w2 >> 4) & 7) as usize) as u16),
                    _ => 0,
                };

                // Consume w2 now that we're committed.
                let _w2 = self.read_imm_16(bus);

                let ea = (opcode & 0x3f) as u8;
                let ea_mode = (ea >> 3) & 7;
                let ea_reg = (ea & 7) as usize;

                self.fpiar = self.ppc;
                let Some(dest) =
                    self.fpu_write_dest(bus, ea_mode, ea_reg, dst_fmt, kfactor, self.fpr[src])
                else {
                    return 0;
                };
                // An enabled exception of the conversion is signalled by
                // the 6888x during the instruction, once the destination
                // is written: the 68020/030 stacks the mid-instruction
                // frame with the destination address. The 68040/68060
                // move-out exception reporting is not modelled; they
                // complete.
                if self.fpu_is_6888x()
                    && let Some(vector) = self.fpu_enabled_exception(0x7F)
                {
                    return self.take_fp_mid_instruction_exception(bus, vector, dest);
                }
                4
            }
            0x0 => {
                // FP register-to-register operations (FMOVE FPm,FPn, FADD, FSUB, FMUL, FDIV, FCMP, etc.)
                let src = ((w2 >> 10) & 7) as usize;
                let dst = ((w2 >> 7) & 7) as usize;
                let opmode = w2 & 0x7f;

                if self.fpu_6888x_illegal_opmode(opmode) {
                    return 0;
                }

                // Consume w2
                let _ = self.read_imm_16(bus);

                if opmode == 0x17 {
                    // FMOVECR was dropped from 68060 silicon.
                    if self.trap_unimpl_060() {
                        return self.take_fp_unimp_060(bus, 0);
                    }
                    if self.trap_unimpl_040() {
                        return self.fpu_040_fmovecr_trap(bus, w2);
                    }
                    // FMOVECR - load constant from ROM. In this register-form
                    // encoding the source-register field carries the ROM index.
                    self.fpiar = self.ppc;
                    let registers = FprUndo::before(&self.fpr, w2);
                    let ctx = self.fpu_ctx(0);
                    let mut f = ExcFlags::default();
                    self.fpr[dst] = softfloat::fmovecr(src, ctx, &mut f);
                    self.fpu_set_cc(self.fpr[dst]);
                    self.fpu_commit(f);
                    return self.fpu_op_exception(4, w2, FloatX80::default(), &registers);
                }
                if self.trap_unimpl_060() && fpu_060_traps_opmode(opmode) {
                    // Register-to-register form of an unimplemented FP
                    // instruction: no operand EA.
                    return self.take_fp_unimp_060(bus, 0);
                }
                if self.trap_unimpl_040()
                    && let Some(cycles) = self.fpu_040_register_source(bus, w2)
                {
                    return cycles;
                }
                if self.fpu_060_unsupp_operands(
                    w2,
                    super::exceptions_060::register_unsupported(self.fpr[src]),
                ) {
                    return self.fpu_060_take_unsupp(bus, self.fpr[src]);
                }
                self.fpiar = self.ppc;
                self.fpu_general_op(w2, self.fpr[src], ExcFlags::default())
            }
            0x6 | 0x7 => {
                // FMOVEM - move multiple FP registers to/from memory
                // subop 0x6: memory to FP registers (restore)
                // subop 0x7: FP registers to memory (save)
                let direction = subop;
                let reg_list = w2 & 0xFF;
                let mode_bits = (w2 >> 11) & 0x3;

                // Consume w2
                let _w2 = self.read_imm_16(bus);

                let ea = (opcode & 0x3f) as u8;
                let ea_mode = (ea >> 3) & 7;
                let ea_reg = (ea & 7) as usize;

                // MODE field (w2 bits 12-11): bit 11 selects a dynamic
                // register list (named by w2 bits 4-6), bit 12 selects the
                // postincrement/control mask order.
                let reg_list = if mode_bits & 0x1 != 0 {
                    (self.d(((w2 >> 4) & 7) as usize) & 0xFF) as u16
                } else {
                    reg_list
                };
                let reg_count = reg_list.count_ones();

                // Resolve the base. Pre-decrement applies the whole block;
                // every other mode (including indexed) resolves normally
                // and post-increment advances afterwards.
                let mut addr = if ea_mode == 4 {
                    let a = self.a(ea_reg).wrapping_sub(reg_count * 12);
                    self.set_a(ea_reg, a);
                    a
                } else {
                    match self.fpu_ea(bus, ea_mode, ea_reg, 0) {
                        Some(FpuEa::Memory(a)) => a,
                        _ => return 0,
                    }
                };

                // Registers transfer in 96-bit extended format, FP0 at
                // the lowest address. Mask order: predecrement lists carry
                // FPn in bit n; postincrement/control lists carry FPn in
                // bit 7-n -- so a -(An) save and an (An)+ restore with the
                // assembler's natural masks are mirror images.
                if direction == 0x6 {
                    // Memory to FP registers
                    for i in 0..8 {
                        let bit = if mode_bits & 0x2 != 0 {
                            1 << (7 - i)
                        } else {
                            1 << i
                        };
                        if reg_list & bit != 0 {
                            let exp_word = (self.read_32(bus, addr) >> 16) as u16;
                            let hi = self.read_32(bus, addr.wrapping_add(4)) as u64;
                            let lo = self.read_32(bus, addr.wrapping_add(8)) as u64;
                            self.fpr[i] = FloatX80::from_extended(exp_word, (hi << 32) | lo);
                            addr = addr.wrapping_add(12);
                        }
                    }
                } else {
                    // FP registers to memory
                    for i in 0..8 {
                        let bit = if mode_bits & 0x2 != 0 {
                            1 << (7 - i)
                        } else {
                            1 << i
                        };
                        if reg_list & bit != 0 {
                            let (exp_word, mantissa) = self.fpr[i].to_extended();
                            self.write_32(bus, addr, (exp_word as u32) << 16);
                            self.write_32(bus, addr.wrapping_add(4), (mantissa >> 32) as u32);
                            self.write_32(bus, addr.wrapping_add(8), mantissa as u32);
                            addr = addr.wrapping_add(12);
                        }
                    }
                }

                // Handle post-increment
                if ea_mode == 3 {
                    self.set_a(ea_reg, addr);
                }

                8
            }
            0x4 => {
                // FMOVE <ea>, control register (FPCR, FPSR, FPIAR)
                // or FMOVEM <ea>, control register list
                let ctrl_sel = (w2 >> 10) & 0x7;
                let _w2 = self.read_imm_16(bus);

                let ea = (opcode & 0x3f) as u8;
                let ea_mode = (ea >> 3) & 7;
                let ea_reg = (ea & 7) as usize;

                // Multi-register lists read consecutive longs in the
                // order FPCR, FPSR, FPIAR; a single Dn/immediate source
                // can only feed a single-register list.
                let count = (ctrl_sel & 4 != 0) as u32
                    + (ctrl_sel & 2 != 0) as u32
                    + (ctrl_sel & 1 != 0) as u32;
                let mut values = [0u32; 3];
                match self.fpu_ea(bus, ea_mode, ea_reg, 4 * count) {
                    Some(FpuEa::DataReg(r)) if count == 1 => values[0] = self.d(r),
                    Some(FpuEa::Immediate) => {
                        for v in values.iter_mut().take(count as usize) {
                            *v = self.read_imm_32(bus);
                        }
                    }
                    Some(FpuEa::Memory(addr)) => {
                        for (i, v) in values.iter_mut().enumerate().take(count as usize) {
                            *v = self.read_32(bus, addr.wrapping_add(4 * i as u32));
                        }
                    }
                    _ => return 0,
                }
                let mut next = values.iter();
                // Unused control-register bits are not implemented: FPCR
                // keeps only its exception-enable and mode-control bytes
                // (15-4), FPSR only its condition-code, quotient, exception
                // and accrued-exception bytes (27-3); the rest read back as
                // zero (MC68881/MC68882UM 1.5.1-1.5.2, M68040UM 9.2,
                // M68060UM 6.1.1-6.1.2).
                if ctrl_sel & 0x4 != 0 {
                    self.fpcr = *next.next().unwrap() & FPCR_IMPLEMENTED;
                }
                if ctrl_sel & 0x2 != 0 {
                    self.fpsr = *next.next().unwrap() & FPSR_IMPLEMENTED;
                }
                if ctrl_sel & 0x1 != 0 {
                    self.fpiar = *next.next().unwrap();
                }

                4
            }
            0x5 => {
                // FMOVE control register, <ea> (FPCR, FPSR, FPIAR)
                let ctrl_sel = (w2 >> 10) & 0x7;
                let _w2 = self.read_imm_16(bus);

                let ea = (opcode & 0x3f) as u8;
                let ea_mode = (ea >> 3) & 7;
                let ea_reg = (ea & 7) as usize;

                let count = (ctrl_sel & 4 != 0) as u32
                    + (ctrl_sel & 2 != 0) as u32
                    + (ctrl_sel & 1 != 0) as u32;
                match self.fpu_ea(bus, ea_mode, ea_reg, 4 * count) {
                    Some(FpuEa::DataReg(r)) if count == 1 => {
                        let value = if ctrl_sel & 0x4 != 0 {
                            self.fpcr
                        } else if ctrl_sel & 0x2 != 0 {
                            self.fpsr
                        } else {
                            self.fpiar
                        };
                        self.set_d(r, value);
                    }
                    Some(FpuEa::Memory(addr)) => {
                        // Multi-register lists write consecutive longs in
                        // the order FPCR, FPSR, FPIAR.
                        let mut cur_addr = addr;
                        if ctrl_sel & 0x4 != 0 {
                            self.write_32(bus, cur_addr, self.fpcr);
                            cur_addr = cur_addr.wrapping_add(4);
                        }
                        if ctrl_sel & 0x2 != 0 {
                            self.write_32(bus, cur_addr, self.fpsr);
                            cur_addr = cur_addr.wrapping_add(4);
                        }
                        if ctrl_sel & 0x1 != 0 {
                            self.write_32(bus, cur_addr, self.fpiar);
                        }
                    }
                    _ => return 0,
                }

                4
            }
            _ => 0,
        }
    }

    /// The highest-priority exception of `mask` (an FPSR exception-byte
    /// mask) that the instruction just raised with its FPCR enable bit set,
    /// as its vector: BSUN, SNAN, OPERR, OVFL, UNFL, DZ, then INEX2/INEX1
    /// sharing vector 49 (MC68881/MC68882UM 6.1 and 6.1.9, M68040UM 9.7,
    /// M68060UM 6.5). An overflow whose own exception is disabled takes
    /// the inexact exception when INEX2 is enabled, whether or not INEX2
    /// is set (MC68881/MC68882UM 6.1.7 and 6.1.10, M68040UM 9.7.7).
    pub(super) fn fpu_enabled_exception(&self, mask: u32) -> Option<u32> {
        use crate::core::exceptions::vector;
        let raised = self.fpsr >> 8;
        let inexact_on_overflow = (raised & 0x10) >> 3;
        let pending = (raised | inexact_on_overflow) & (self.fpcr >> 8) & mask;
        [
            (0x80, vector::FP_BSUN),
            (0x40, vector::FP_SNAN),
            (0x20, vector::FP_OPERR),
            (0x10, vector::FP_OVFL),
            (0x08, vector::FP_UNFL),
            (0x04, vector::FP_DZ),
            (0x03, vector::FP_INEX),
        ]
        .into_iter()
        .find(|&(bit, _)| pending & bit != 0)
        .map(|(_, v)| v)
    }

    /// Hold an enabled arithmetic exception of the operation that just
    /// completed (`cycles` != 0) for the next FPU instruction. The FPSR
    /// exception and accrued bytes are already updated and FPIAR holds
    /// the operation's address. The 6888x does not interrupt the main
    /// processor here: integer instructions keep running, and the
    /// exception is reported when the next FPU instruction starts
    /// (MC68881/MC68882UM 6.1). See [`Self::fpu_take_pending_exception`].
    ///
    /// 6888x only. The 68040 and the 68060 hold their exceptions with the
    /// state frame their handler saves ([`Self::fpu_040_hold_exception`],
    /// [`Self::fpu_060_hold_exception`]).
    fn fpu_hold_exception(&mut self, cycles: i32) -> i32 {
        if cycles != 0
            && self.fpu_is_6888x()
            && let Some(vector) = self.fpu_enabled_exception(0x7F)
        {
            self.fpu_exception_pending = vector as u8;
        }
        cycles
    }

    /// Report the exception a previous FPU operation left pending, as a
    /// pre-instruction exception of the FPU instruction now starting:
    /// that instruction does not execute, and the format $0 frame's PC
    /// restarts it after the handler returns. Called by the arithmetic,
    /// FMOVE and conditional FPU instructions; FMOVEM, the moves of the
    /// control registers, FSAVE and FRESTORE do not report it. `None` =
    /// nothing pending, the instruction proceeds.
    pub(crate) fn fpu_take_pending_exception<B: AddressBus>(&mut self, bus: &mut B) -> Option<i32> {
        let vector = std::mem::take(&mut self.fpu_exception_pending);
        (vector != 0).then(|| self.take_exception(bus, u32::from(vector)))
    }

    /// Run the general operation of command word `w2` on `src` into its
    /// FP register and hold the exception it raises.
    #[inline]
    fn fpu_general_op(&mut self, w2: u16, src: FloatX80, src_flags: ExcFlags) -> i32 {
        let registers = FprUndo::before(&self.fpr, w2);
        let cycles = self.fpu_apply_op(w2 & 0x7F, ((w2 >> 7) & 7) as usize, src, src_flags);
        self.fpu_op_exception(cycles, w2, src, &registers)
    }

    /// Hold the exception of the general operation that just completed
    /// (`cycles` != 0), given its command word, its source operand and
    /// the FP registers as they were before it. On a 6888x an enabled
    /// SNAN, OPERR or DZ stops the operation before it stores a result:
    /// the FP data registers keep their values, so the handler still
    /// finds the operands. An enabled OVFL, UNFL or INEX stores the
    /// result the disabled case stores (MC68881/MC68882UM 6.1.2 to
    /// 6.1.7).
    #[inline]
    fn fpu_op_exception(
        &mut self,
        cycles: i32,
        w2: u16,
        src: FloatX80,
        registers: &FprUndo,
    ) -> i32 {
        const SNAN_OPERR_DZ: u32 = 0x64;
        if cycles == 0 || !self.fpu_may_hold_exception() {
            return cycles;
        }
        if self.is_040() {
            return self.fpu_040_hold_exception(cycles, w2, src, registers);
        }
        if self.is_060() {
            return self.fpu_060_hold_exception(cycles, w2, src, src, registers);
        }
        if cycles != 0
            && self.fpu_is_6888x()
            && (self.fpsr >> 8) & (self.fpcr >> 8) & SNAN_OPERR_DZ != 0
        {
            registers.restore(&mut self.fpr);
        }
        self.fpu_hold_exception(cycles)
    }

    /// Whether the operation that just completed can have an exception to
    /// hold, from the FPSR exception byte it left: one it raised is
    /// enabled, or it raised an overflow or underflow, which the 68040 and
    /// 68060 can take without its enable. Every hold and restore condition
    /// implies this, so when it is false (no exception raised, or none
    /// of the raised flags enabled and no OVFL/UNFL)
    /// holding is skipped without the priority search.
    #[inline(always)]
    pub(super) fn fpu_may_hold_exception(&self) -> bool {
        #[cfg(test)]
        if super::fast_path_tests::FORCE_FULL_HOLD.get() {
            return true;
        }
        self.fpsr & ((self.fpcr & 0xFF00) | 0x1800) != 0
    }

    /// The vector of the arithmetic exception the operation that just
    /// completed takes on a 68040 or 68060, from the FPSR exception byte
    /// it left: the highest-priority enabled one, or, with `nonmaskable`,
    /// what the part itself takes. There an overflow or underflow is
    /// taken whether or not it is enabled, because the result a 6888x
    /// would store is the software package's to supply (M68040UM 9.7.4.2
    /// and 9.7.5.2, M68060UM 6.6.4 and 6.6.5).
    pub(super) fn fpu_arith_vector(&self, nonmaskable: bool) -> Option<u32> {
        use crate::core::exceptions::vector;
        let raised = self.fpsr >> 8;
        if nonmaskable && raised & (self.fpcr >> 8) & 0x60 == 0 {
            if raised & 0x10 != 0 {
                return Some(vector::FP_OVFL);
            }
            if raised & 0x08 != 0 {
                return Some(vector::FP_UNFL);
            }
        }
        self.fpu_enabled_exception(0x7F)
    }

    /// The result of an arithmetic instruction the 68040 and 68060 have
    /// in hardware as it was before rounding, for the state frame of its
    /// exception: `opmode` on `src` and, for a dyadic instruction, the
    /// register value `dst`. `None` for another instruction and when no
    /// finite result went through rounding.
    pub(super) fn fpu_unrounded_result(
        &self,
        opmode: u16,
        src: FloatX80,
        dst: FloatX80,
    ) -> Option<softfloat::Unrounded> {
        let src = canonical_operand(src);
        let dst = canonical_operand(dst);
        let ctx = self.fpu_ctx(opmode);
        let single = RoundCtx {
            prec: Precision::Single,
            ..ctx
        };
        let mut f = ExcFlags::default();
        match opmode {
            0x00 | 0x40 | 0x44 => softfloat::round_to_precision(src, ctx, &mut f),
            0x04 | 0x41 | 0x45 => softfloat::sqrt(src, ctx, &mut f),
            0x18 | 0x58 | 0x5C => softfloat::round_to_precision(softfloat::abs(src), ctx, &mut f),
            0x1A | 0x5A | 0x5E => softfloat::round_to_precision(softfloat::neg(src), ctx, &mut f),
            0x20 | 0x60 | 0x64 => softfloat::div(dst, src, ctx, &mut f),
            0x22 | 0x62 | 0x66 => softfloat::add(dst, src, ctx, &mut f),
            0x23 | 0x63 | 0x67 => softfloat::mul(dst, src, ctx, &mut f),
            0x24 => softfloat::div(dst, src, single, &mut f),
            0x27 => softfloat::mul(sgl_truncate(dst), sgl_truncate(src), single, &mut f),
            0x28 | 0x68 | 0x6C => softfloat::sub(dst, src, ctx, &mut f),
            _ => return None,
        };
        f.unrounded()
    }

    /// The FSxxx/FDxxx opmodes ($40-$7F: FSMOVE, FDADD, FSSQRT, ...) exist
    /// only on the 68040 and 68060 (M68040UM 9.4, M68000PRM 4.3). On a
    /// 6888x they are illegal coprocessor commands, which the 68020/030
    /// takes as an F-line exception with the format $0 frame
    /// (MC68881/MC68882UM 7.4.2, MC68020UM 10.4.2).
    fn fpu_6888x_illegal_opmode(&self, opmode: u16) -> bool {
        self.fpu_is_6888x() && opmode & 0x40 != 0
    }

    /// The BSUN exception of a conditional instruction: an IEEE-nonaware
    /// predicate ($10-$1F) with the NAN condition code set raises BSUN (see
    /// [`Self::fpu_condition`]); with BSUN enabled in FPCR the instruction
    /// does not execute and takes vector 48 as a pre-instruction exception,
    /// format $0 with the stacked PC restarting it (MC68881/MC68882UM 6.1.1,
    /// M68040UM 9.5.1, M68060UM 6.5.1). The handler must clear NAN or the
    /// enable before returning. `None` = the instruction proceeds.
    pub(crate) fn fpu_bsun_exception<B: AddressBus>(
        &mut self,
        bus: &mut B,
        condition: u8,
    ) -> Option<i32> {
        const FPCC_NAN: u32 = 0x0100_0000;
        if condition & 0x10 == 0 || self.fpsr & FPCC_NAN == 0 {
            return None;
        }
        self.fpsr |= 0x0000_8080; // BSUN, accrued IOP
        if self.fpcr & 0x8000 == 0 {
            return None;
        }
        if self.is_060() {
            // The handler's FSAVE finds the EXCP state (M68060UM 6.6.1.2);
            // the operand of a BSUN frame is undefined.
            self.fpu_060_excp = Some(super::Fpu060Excp::new(
                crate::core::exceptions::vector::FP_BSUN,
                FloatX80::default(),
            ));
        }
        Some(self.take_exception(bus, crate::core::exceptions::vector::FP_BSUN))
    }

    /// FBcc - FPU conditional branch.
    ///
    /// Note: The PC has already been advanced past the displacement when this is called.
    pub fn exec_fbcc(&mut self, condition: u8, disp: i32) -> i32 {
        let take_branch = self.fpu_condition(condition);

        if take_branch {
            self.change_of_flow = true;
            // PC was already advanced past displacement; adjust relative to that position
            // Compute target: (PC - disp_size) + disp
            // Since PC is after displacement, we compute: base_pc + disp
            // where base_pc is the address of the first extension word
            let base_pc = self.ppc.wrapping_add(2); // ppc is opcode, +2 is extension word
            self.pc = (base_pc as i32).wrapping_add(disp) as u32;
        }

        8
    }

    /// FScc - Set byte on FPU condition.
    pub fn exec_fscc<B: AddressBus>(
        &mut self,
        bus: &mut B,
        ea_mode: u8,
        ea_reg: usize,
        condition: u8,
    ) -> i32 {
        if let Some(cycles) = self.fpu_bsun_exception(bus, condition) {
            return cycles;
        }
        let value = if self.fpu_condition(condition) {
            0xFFu8
        } else {
            0x00u8
        };

        match self.fpu_ea(bus, ea_mode, ea_reg, 1) {
            Some(FpuEa::DataReg(r)) => {
                self.set_d(r, (self.d(r) & 0xFFFF_FF00) | value as u32);
            }
            Some(FpuEa::Memory(addr)) => {
                self.write_8(bus, addr, value);
            }
            _ => return 0,
        }

        4
    }

    /// FDBcc - decrement and branch on FPU condition false. The
    /// displacement is relative to its own extension word's address.
    pub fn exec_fdbcc<B: AddressBus>(&mut self, bus: &mut B, reg: usize, condition: u8) -> i32 {
        let disp_base = self.pc;
        let disp = self.read_imm_16(bus) as i16 as i32;
        if let Some(cycles) = self.fpu_bsun_exception(bus, condition) {
            return cycles;
        }
        if !self.fpu_condition(condition) {
            let count = (self.d(reg) as u16).wrapping_sub(1);
            self.set_d(reg, (self.d(reg) & 0xFFFF_0000) | u32::from(count));
            if count != 0xFFFF {
                self.change_of_flow = true;
                self.pc = (disp_base as i32).wrapping_add(disp) as u32;
            }
        }
        8
    }

    /// FTRAPcc - trap on FPU condition (with optional ignored operand
    /// word(s) already addressed by `imm_words`).
    pub fn exec_ftrapcc<B: AddressBus>(
        &mut self,
        bus: &mut B,
        condition: u8,
        imm_words: u32,
    ) -> i32 {
        for _ in 0..imm_words {
            let _ = self.read_imm_16(bus);
        }
        if let Some(cycles) = self.fpu_bsun_exception(bus, condition) {
            return cycles;
        }
        if self.fpu_condition(condition) {
            // FTRAPcc takes the TRAPcc/TRAPV exception vector (7).
            return self.take_group2_exception(bus, 7);
        }
        4
    }

    /// FPU "op1" entrypoint for the `0xF3xx` encoding group.
    ///
    /// This group contains `FSAVE <ea>` and `FRESTORE <ea>`; frame formats
    /// follow the configured CPU/FPU generation.
    pub fn exec_fpu_op1<B: AddressBus>(&mut self, bus: &mut B, opcode: u16) -> i32 {
        // FSAVE/FRESTORE also take the disabled trap when PCR.DFP is set.
        if self.is_060() && (self.pcr & crate::core::cpu::PCR_DFP) != 0 {
            return self.take_fp_disabled_060(bus);
        }

        let ea_mode = ((opcode >> 3) & 7) as u8;
        let ea_reg = (opcode & 7) as usize;
        let op = ((opcode >> 6) & 3) as u8;

        match op {
            0 => self.exec_fsave(bus, ea_mode, ea_reg),
            1 => self.exec_frestore(bus, ea_mode, ea_reg),
            _ => 0, // unsupported -> let caller raise LINE1111 without consuming extensions
        }
    }

    /// Resolve a control-mode effective address for FSAVE/FRESTORE,
    /// consuming any extension words: (An), (d16,An), (d8,An,Xn),
    /// (xxx).W/(xxx).L, and -- for FRESTORE, whose frame is a source
    /// operand -- (d16,PC)/(d8,PC,Xn). The register-direct, (An)+/-(An),
    /// and immediate modes are not control modes; the callers keep their
    /// own arms for the increment/decrement forms and everything else is
    /// an undefined encoding (None -> Line-F).
    pub(super) fn fpu_frame_control_ea<B: AddressBus>(
        &mut self,
        bus: &mut B,
        ea_mode: u8,
        ea_reg: usize,
        allow_pc_relative: bool,
    ) -> Option<u32> {
        let mode = AddressingMode::decode(ea_mode, ea_reg as u8)?;
        let control = matches!(
            mode,
            AddressingMode::AddressIndirect(_)
                | AddressingMode::Displacement(_)
                | AddressingMode::Index(_)
                | AddressingMode::AbsoluteShort
                | AddressingMode::AbsoluteLong
        ) || (allow_pc_relative
            && matches!(
                mode,
                AddressingMode::PcDisplacement | AddressingMode::PcIndex
            ));
        if !control {
            return None;
        }
        match self.resolve_ea(bus, mode, Size::Long) {
            EaResult::Memory(addr) => Some(addr),
            _ => None,
        }
    }

    fn exec_fsave<B: AddressBus>(&mut self, bus: &mut B, ea_mode: u8, ea_reg: usize) -> i32 {
        if self.is_060() {
            return self.exec_fsave_060(bus, ea_mode, ea_reg);
        }
        if !self.fpu_040.is_idle() {
            return self.fpu_040_fsave(bus, ea_mode, ea_reg);
        }
        match ea_mode {
            3 => {
                // (An)+
                let addr = self.a(ea_reg);
                self.set_a(ea_reg, addr.wrapping_add(4));

                if self.fpu_just_reset {
                    self.write_32(bus, addr, 0);
                } else {
                    // EA increment already did +4; cover the rest of the frame.
                    let extra = fsave_extra_longs(self);
                    self.set_a(ea_reg, self.a(ea_reg).wrapping_add(extra * 4));
                    perform_fsave(bus, self, addr, true);
                }
                8
            }
            4 => {
                // -(An)
                let addr_hi = self.a(ea_reg).wrapping_sub(4);
                self.set_a(ea_reg, addr_hi);

                if self.fpu_just_reset {
                    self.write_32(bus, addr_hi, 0);
                } else {
                    // One predecrement already happened (-4); cover the rest.
                    let extra = fsave_extra_longs(self);
                    self.set_a(ea_reg, self.a(ea_reg).wrapping_sub(extra * 4));
                    perform_fsave(bus, self, addr_hi, false);
                }
                8
            }
            // Control modes -- (An), (d16,An), (d8,An,Xn), (xxx).W/.L --
            // write the frame ascending from the resolved address with no
            // register update (Linux/m68k's bootstrap parks FPU state with
            // FSAVE/FRESTORE d16(sp)).
            _ => match self.fpu_frame_control_ea(bus, ea_mode, ea_reg, false) {
                Some(addr) => {
                    if self.fpu_just_reset {
                        self.write_32(bus, addr, 0);
                    } else {
                        perform_fsave(bus, self, addr, true);
                    }
                    8
                }
                None => 0,
            },
        }
    }

    /// 68060 FSAVE: the floating-point state frame carries its format in
    /// bits 15:8 of the first long word: $00 = NULL (FPU untouched since
    /// reset), $60 = IDLE. Every frame occupies three long words, including
    /// NULL (MC68060UM, section 6.7, pp. 6-35–6-36; appendix D, FSAVE).
    /// The four-byte
    /// NULL frame used by earlier FPUs does not apply to the 68060.
    /// With an exception in the FPU, taken or not, the frame is EXCP
    /// ($E0) with the exception operand, and the FPU is idle afterwards.
    fn exec_fsave_060<B: AddressBus>(&mut self, bus: &mut B, ea_mode: u8, ea_reg: usize) -> i32 {
        let frame = match self.fpu_060_excp {
            Some(excp) => excp.frame(),
            None if self.fpu_just_reset => [0; 3],
            None => [0x0000_6000, 0, 0],
        };
        let size = 12;
        let addr = match ea_mode {
            // (An) / (An)+
            2 | 3 => {
                let addr = self.a(ea_reg);
                if ea_mode == 3 {
                    self.set_a(ea_reg, addr.wrapping_add(size));
                }
                addr
            }
            // -(An)
            4 => {
                let addr = self.a(ea_reg).wrapping_sub(size);
                self.set_a(ea_reg, addr);
                addr
            }
            // Remaining control modes: frame written at the resolved
            // address, no register update.
            _ => match self.fpu_frame_control_ea(bus, ea_mode, ea_reg, false) {
                Some(addr) => addr,
                None => return 0,
            },
        };
        for (i, long) in frame.into_iter().enumerate() {
            self.write_32(bus, addr.wrapping_add(4 * i as u32), long);
        }
        self.fpu_060_excp = None;
        self.fpu_exception_pending = 0;
        8
    }

    /// 68060 FRESTORE always consumes three long words, including NULL
    /// (MC68060UM, appendix D, FRESTORE). Firmware must hide the 060 FPU
    /// from operating systems that construct earlier FPUs' four-byte frames
    /// until their 68060 support library installs compatible task contexts.
    /// The frame format byte (bits 15-8 of the first long) must be $00
    /// (NULL), $60 (IDLE) or $E0 (EXCP); any other value takes a format
    /// error exception with the address register unchanged (M68060UM 6.7).
    /// An EXCP frame puts the FPU back in the exception state: the next
    /// floating-point instruction other than FSAVE and FRESTORE takes the
    /// exception in its bits 2-0, and FSAVE gets the frame back with its
    /// operand. An IDLE or NULL frame leaves none.
    fn exec_frestore_060<B: AddressBus>(&mut self, bus: &mut B, ea_mode: u8, ea_reg: usize) -> i32 {
        let addr = match ea_mode {
            2 | 3 => self.a(ea_reg),
            // Remaining control modes, plus PC-relative (the frame is a
            // source operand): no register update.
            _ => match self.fpu_frame_control_ea(bus, ea_mode, ea_reg, true) {
                Some(addr) => addr,
                None => return 0,
            },
        };
        let header = self.read_32(bus, addr);
        if !matches!((header >> 8) & 0xFF, 0x00 | 0x60 | 0xE0) {
            return self.take_exception(bus, crate::core::exceptions::vector::FORMAT_ERROR);
        }
        let operand = [
            self.read_32(bus, addr.wrapping_add(4)),
            self.read_32(bus, addr.wrapping_add(8)),
        ];
        if ea_mode == 3 {
            self.set_a(ea_reg, addr.wrapping_add(12));
        }
        self.fpu_060_excp = None;
        self.fpu_exception_pending = 0;
        if (header & 0x0000_FF00) == 0 {
            self.do_frestore_null();
        } else {
            self.fpu_just_reset = false;
            if (header & 0x0000_FF00) == 0xE000 {
                let excp = super::Fpu060Excp::from_frame([header, operand[0], operand[1]]);
                self.fpu_exception_pending = excp.vector() as u8;
                self.fpu_060_excp = Some(excp);
            }
        }
        8
    }

    /// Whether a non-NULL 6888x/68040 state-frame header (version byte,
    /// size byte) is one this FPU family accepts. A 6888x checks the
    /// version against its own and the size against its IDLE and BUSY
    /// frames (MC68881/MC68882UM 6.4.2). The crate has one 6888x model,
    /// which saves the 68881's frames, so it accepts the sizes of both
    /// parts: $18/$B4 (68881) and $38/$D4 (68882). The 68040 accepts
    /// version $41 (or $40) with its IDLE ($00), UNIMP ($30; $28 for
    /// version $40) and BUSY ($60) sizes (M68040UM 9.8). Anything else is
    /// a format error.
    fn fpu_frame_header_valid(&self, header: u32) -> bool {
        let version = header >> 24;
        let size = (header >> 16) & 0xFF;
        if self.is_040() {
            matches!(version, 0x40 | 0x41) && matches!(size, 0x00 | 0x28 | 0x30 | 0x60)
        } else {
            version == FPU_6888X_VERSION >> 24 && matches!(size, 0x18 | 0x38 | 0xB4 | 0xD4)
        }
    }

    fn exec_frestore<B: AddressBus>(&mut self, bus: &mut B, ea_mode: u8, ea_reg: usize) -> i32 {
        if self.is_060() {
            return self.exec_frestore_060(bus, ea_mode, ea_reg);
        }
        let addr = match ea_mode {
            2 | 3 => self.a(ea_reg),
            // Remaining control modes, plus PC-relative (the frame is a
            // source operand): no register update. Linux/m68k's Amiga
            // bootstrap resets the FPU with FRESTORE d16(sp) before jumping
            // to the kernel.
            _ => match self.fpu_frame_control_ea(bus, ea_mode, ea_reg, true) {
                Some(addr) => addr,
                None => return 0,
            },
        };
        let header = self.read_32(bus, addr);
        if (header & 0xFF00_0000) == 0 {
            if ea_mode == 3 {
                self.set_a(ea_reg, addr.wrapping_add(4));
            }
            self.do_frestore_null();
            self.fpu_040.clear();
            return 8;
        }
        if !self.fpu_frame_header_valid(header) {
            // Format error: the frame is not restored and the address
            // register is not updated; the stacked PC restarts FRESTORE.
            return self.take_exception(bus, crate::core::exceptions::vector::FORMAT_ERROR);
        }
        self.fpu_just_reset = false;
        // The frame's size byte counts the state bytes after the header
        // long.
        let size = (header >> 16) & 0x00FF;
        // A 6888x IDLE frame ends with the BIU flags, whose bit 27 is
        // clear while an exception is unreported: restoring such a frame
        // makes the enabled exception in FPSR pending again
        // (MC68881/MC68882UM 6.4.2). Every other frame leaves none.
        self.fpu_exception_pending = 0;
        if self.fpu_is_6888x()
            && matches!(size, 0x18 | 0x38)
            && self.read_32(bus, addr.wrapping_add(size)) & BIU_NO_EXCEPTION_PENDING == 0
            && let Some(vector) = self.fpu_enabled_exception(0x7F)
        {
            self.fpu_exception_pending = vector as u8;
        }
        if ea_mode == 3 {
            // The postincrement covers header plus state.
            self.set_a(ea_reg, addr.wrapping_add(4 + size));
        }
        if self.is_040() {
            self.fpu_040_frestore(bus, addr, header);
        }
        8
    }

    fn do_frestore_null(&mut self) {
        self.fpu_exception_pending = 0;
        self.fpcr = 0;
        self.fpsr = 0;
        self.fpiar = 0;
        self.fpr = [FloatX80::default_nan(); 8];
        self.fpu_just_reset = true;
    }

    /// Set the FPSR condition-code byte (bits 24-27) from an extended value.
    /// N reflects the sign bit for every class (so -0 and -NaN set N).
    fn fpu_set_cc(&mut self, value: FloatX80) {
        const FPCC_N: u32 = 0x0800_0000;
        const FPCC_Z: u32 = 0x0400_0000;
        const FPCC_I: u32 = 0x0200_0000;
        const FPCC_NAN: u32 = 0x0100_0000;

        self.fpsr &= !(FPCC_N | FPCC_Z | FPCC_I | FPCC_NAN);
        if value.is_nan() {
            self.fpsr |= FPCC_NAN;
        } else if value.is_inf() {
            self.fpsr |= FPCC_I;
        } else if value.is_zero() {
            self.fpsr |= FPCC_Z;
        }
        if value.sign() {
            self.fpsr |= FPCC_N;
        }
    }

    /// Set the FPSR condition codes from an ordered comparison result.
    fn fpu_set_cc_cmp(&mut self, cmp: FpCmp) {
        const FPCC_N: u32 = 0x0800_0000;
        const FPCC_Z: u32 = 0x0400_0000;
        const FPCC_I: u32 = 0x0200_0000;
        const FPCC_NAN: u32 = 0x0100_0000;

        self.fpsr &= !(FPCC_N | FPCC_Z | FPCC_I | FPCC_NAN);
        match cmp {
            FpCmp::Less => self.fpsr |= FPCC_N,
            FpCmp::Equal => self.fpsr |= FPCC_Z,
            FpCmp::Greater => {}
            FpCmp::Unordered => self.fpsr |= FPCC_NAN,
        }
    }

    /// Rounding precision for `opmode`: the FSxxx/FDxxx variants (bit 6 set)
    /// force single (bit 2 clear) or double (bit 2 set); the base ops take the
    /// FPCR rounding-precision bits 7:6.
    fn opmode_precision(&self, opmode: u16) -> Precision {
        if opmode & 0x40 == 0 {
            Precision::from_fpcr(self.fpcr)
        } else if opmode & 0x04 == 0 {
            Precision::Single
        } else {
            Precision::Double
        }
    }

    /// Write the FPSR quotient byte: bits 22:16 = low 7 bits of |quotient|,
    /// bit 23 = quotient sign. Set by FMOD/FREM.
    fn fpu_set_quotient(&mut self, quotient: u8, sign: bool) {
        self.fpsr &= !0x00FF_0000;
        self.fpsr |= ((quotient & 0x7F) as u32) << 16;
        if sign {
            self.fpsr |= 1 << 23;
        }
    }

    /// Build the rounding context (mode from FPCR, precision from `opmode`).
    fn fpu_ctx(&self, opmode: u16) -> RoundCtx {
        RoundCtx {
            mode: RoundMode::from_fpcr(self.fpcr),
            prec: self.opmode_precision(opmode),
        }
    }

    /// Fold an operation's exception flags into FPSR. The exception-status
    /// (EXC) byte (bits 15:8) reflects only this instruction and is rebuilt
    /// each time; the accrued-exception (AEXC) byte (bits 7:0) is sticky.
    /// AEXC mapping (MC68881/68040): IOP = BSUN|SNAN|OPERR, OVFL, UNFL =
    /// UNFL&INEX2, DZ, INEX = OVFL|INEX2|INEX1.
    fn fpu_commit(&mut self, f: ExcFlags) {
        // ExcFlags bit k maps to FPSR EXC bit (8 + k): BSUN..INEX1.
        self.fpsr &= !0x0000_FF00;
        self.fpsr |= (f.0 as u32) << 8;

        let mut aexc = 0u32;
        if f.has(ExcFlags::BSUN | ExcFlags::SNAN | ExcFlags::OPERR) {
            aexc |= 1 << 7; // IOP
        }
        if f.has(ExcFlags::OVFL) {
            aexc |= 1 << 6;
        }
        if f.has(ExcFlags::UNFL) && f.has(ExcFlags::INEX2) {
            aexc |= 1 << 5;
        }
        if f.has(ExcFlags::DZ) {
            aexc |= 1 << 4;
        }
        if f.has(ExcFlags::OVFL | ExcFlags::INEX2 | ExcFlags::INEX1) {
            aexc |= 1 << 3; // INEX
        }
        self.fpsr |= aexc;
    }

    /// Evaluate an FBcc/FScc/FDBcc/FTRAPcc conditional predicate against
    /// FPSR.
    ///
    /// The IEEE-nonaware predicates ($10-$1F) test the same condition as
    /// their aware counterparts ($00-$0F), but with the NAN condition code
    /// set they also signal a branch/set on unordered: BSUN in the
    /// exception byte and IOP in the accrued byte, the rest of FPSR
    /// unchanged (MC68881/MC68882UM 4.5.1 and table 4-3, M68000PRM 3.6.2).
    fn fpu_condition(&mut self, condition: u8) -> bool {
        const FPCC_N: u32 = 0x0800_0000;
        const FPCC_Z: u32 = 0x0400_0000;
        const FPCC_NAN: u32 = 0x0100_0000;

        let n = (self.fpsr & FPCC_N) != 0;
        let z = (self.fpsr & FPCC_Z) != 0;
        let nan = (self.fpsr & FPCC_NAN) != 0;

        if condition & 0x10 != 0 && nan {
            self.fpsr |= 0x0000_8080; // BSUN, accrued IOP
        }

        match condition & 0x0F {
            0x0 => false,            // F
            0x1 => z,                // EQ
            0x2 => !(nan || z || n), // OGT
            0x3 => z || !(nan || n), // OGE
            0x4 => n && !(nan || z), // OLT
            0x5 => z || (n && !nan), // OLE
            0x6 => !(nan || z),      // OGL
            0x7 => !nan,             // OR
            0x8 => nan,              // UN
            0x9 => nan || z,         // UEQ
            0xA => nan || !(n || z), // UGT
            0xB => nan || z || !n,   // UGE
            0xC => nan || (n && !z), // ULT
            0xD => nan || n || z,    // ULE
            0xE => !z,               // NE
            _ => true,               // T
        }
    }

    /// Apply a general FPU ALU operation `opmode` to destination register
    /// `dst` using the source operand `src` (an FPm register or an
    /// `<ea>`/immediate operand). This is the single dispatch table shared by
    /// the register-source (`subop 0x0`) and memory/immediate-source (`subop
    /// 0x2`) paths so the two cannot drift apart. FMOVECR has no source
    /// operand and is handled by the callers. `src_flags` carries the
    /// exceptions raised converting the source to extended (SNAN for a
    /// single or double signaling NaN, INEX1 for packed decimal), which
    /// count as this instruction's.
    ///
    /// Arithmetic is evaluated by the extended-precision softfloat and
    /// transcendental engines. The 6888x single/double
    /// rounding-precision variants (FSxxx/FDxxx) select their specified
    /// result precision before the value is written back.
    pub(super) fn fpu_apply_op(
        &mut self,
        opmode: u16,
        dst: usize,
        src: FloatX80,
        src_flags: ExcFlags,
    ) -> i32 {
        // Operands that are zeros with a nonzero exponent field compute as
        // zeros, and unnormalized ones as the normalized number they
        // hold. FCMP and FTST do not write the destination register.
        let src = canonical_operand(src);
        if !matches!(opmode, 0x38 | 0x3A) && !is_canonical(self.fpr[dst]) {
            self.fpr[dst] = canonical_operand_slow(self.fpr[dst]);
        }
        // The dyadic arithmetic most FP code runs is dispatched here with
        // direct branches. Through the jump table of the match below, a
        // run of alternating FADD, FMUL and FSUB mispredicts the indirect
        // branch on nearly every instruction.
        if let Some(op) = Dyadic::of(opmode) {
            let ctx = self.fpu_ctx(opmode);
            let mut f = src_flags;
            let d = self.fpr[dst];
            self.fpr[dst] = if op == Dyadic::Add {
                softfloat::add(d, src, ctx, &mut f)
            } else if op == Dyadic::Mul {
                softfloat::mul(d, src, ctx, &mut f)
            } else if op == Dyadic::Sub {
                softfloat::sub(d, src, ctx, &mut f)
            } else {
                softfloat::div(d, src, ctx, &mut f)
            };
            self.fpu_set_cc(self.fpr[dst]);
            self.fpu_commit(f);
            return 4;
        }
        match opmode {
            0x00 | 0x40 | 0x44 => {
                // FMOVE / FSMOVE / FDMOVE
                let ctx = self.fpu_ctx(opmode);
                let mut f = src_flags;
                self.fpr[dst] = softfloat::round_to_precision(src, ctx, &mut f);
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            0x01 => {
                // FINT - round to integer using the FPCR rounding mode
                let mode = RoundMode::from_fpcr(self.fpcr);
                let mut f = src_flags;
                self.fpr[dst] = softfloat::round_to_int(src, mode, &mut f);
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            0x03 => {
                // FINTRZ - round to integer toward zero
                let mut f = src_flags;
                self.fpr[dst] = softfloat::round_to_int(src, RoundMode::Zero, &mut f);
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            0x04 | 0x41 | 0x45 => {
                // FSQRT / FSSQRT / FDSQRT
                let ctx = self.fpu_ctx(opmode);
                let mut f = src_flags;
                self.fpr[dst] = softfloat::sqrt(src, ctx, &mut f);
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            0x18 | 0x58 | 0x5C => {
                // FABS / FSABS / FDABS: the absolute value, then rounded to
                // the precision (M68000PRM FABS). The order matters under
                // RM/RP, which round a negative source the other way.
                let ctx = self.fpu_ctx(opmode);
                let mut f = src_flags;
                self.fpr[dst] = softfloat::round_to_precision(softfloat::abs(src), ctx, &mut f);
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            0x1A | 0x5A | 0x5E => {
                // FNEG / FSNEG / FDNEG: the negation, then rounded to the
                // precision (M68000PRM FNEG), as for FABS.
                let ctx = self.fpu_ctx(opmode);
                let mut f = src_flags;
                self.fpr[dst] = softfloat::round_to_precision(softfloat::neg(src), ctx, &mut f);
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            0x24 => {
                // FSGLDIV - dst = dst / src with the quotient mantissa
                // rounded to single precision but the extended exponent
                // range kept (M68000PM 3-155: only the accuracy drops, not
                // the range). In silicon on every part with an FPU -- gcc
                // -m68040 emits it for float divides, so Debian/m68k
                // binaries die with SIGILL if it Line-Fs (the kernel FPSP
                // has no emulation entry for a hardware instruction).
                let ctx = RoundCtx {
                    mode: RoundMode::from_fpcr(self.fpcr),
                    prec: Precision::Single,
                };
                let mut f = src_flags;
                self.fpr[dst] = softfloat::div(self.fpr[dst], src, ctx, &mut f);
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            0x27 => {
                // FSGLMUL - like FSGLDIV for the product; the operand
                // mantissas are truncated to 24 bits before the multiply
                // (M68000PM 3-157), which real code can observe in the
                // last bit of the result.
                let ctx = RoundCtx {
                    mode: RoundMode::from_fpcr(self.fpcr),
                    prec: Precision::Single,
                };
                let mut f = src_flags;
                let a = sgl_truncate(self.fpr[dst]);
                let b = sgl_truncate(src);
                self.fpr[dst] = softfloat::mul(a, b, ctx, &mut f);
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            0x38 => {
                // FCMP - ordered compare of dst with src, set condition codes only
                let mut f = src_flags;
                let d = canonical_operand(self.fpr[dst]);
                let cmp = softfloat::compare(d, src, &mut f);
                self.fpu_set_cc_cmp(cmp);
                // Two equal infinities compare equal with the infinity's
                // sign: -inf vs -inf sets N as well as Z (M68000PRM FCMP,
                // operation table).
                if cmp == FpCmp::Equal && d.is_inf() && src.is_inf() && d.sign() {
                    self.fpsr |= 0x0800_0000;
                }
                self.fpu_commit(f);
                4
            }
            0x3A => {
                // FTST - test src, set condition codes only (no dst write).
                // A signaling NaN operand raises SNAN like any operation.
                let mut f = src_flags;
                if src.is_signaling_nan() {
                    f.raise(ExcFlags::SNAN);
                }
                self.fpu_set_cc(src);
                self.fpu_commit(f);
                4
            }
            0x1E => {
                // FGETEXP - extract the unbiased exponent
                let mut f = src_flags;
                self.fpr[dst] = softfloat::getexp(src, &mut f);
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            0x1F => {
                // FGETMAN - extract the mantissa as a value in [1, 2)
                let mut f = src_flags;
                self.fpr[dst] = softfloat::getman(src, &mut f);
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            0x21 => {
                // FMOD - exact remainder, truncated quotient.
                let mut f = src_flags;
                let rem = transcendental::remainder(self.fpr[dst], src, false, &mut f);
                if is_denormalized(rem.value) {
                    f.raise(ExcFlags::UNFL);
                }
                self.fpr[dst] = rem.value;
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_set_quotient(rem.quotient, rem.quotient_sign);
                self.fpu_commit(f);
                4
            }
            0x25 => {
                // FREM - exact IEEE remainder, round-to-nearest quotient.
                let mut f = src_flags;
                let rem = transcendental::remainder(self.fpr[dst], src, true, &mut f);
                if is_denormalized(rem.value) {
                    f.raise(ExcFlags::UNFL);
                }
                self.fpr[dst] = rem.value;
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_set_quotient(rem.quotient, rem.quotient_sign);
                self.fpu_commit(f);
                4
            }
            0x26 => {
                // FSCALE - dst = dst * 2^trunc(src)
                let ctx = self.fpu_ctx(opmode);
                let mut f = src_flags;
                if self.fpr[dst].is_nan() || src.is_nan() {
                    // The NaN operand rule comes first (the destination
                    // NaN wins), ahead of the infinite-count OPERR.
                    self.fpr[dst] = softfloat::propagate_nan(self.fpr[dst], src, &mut f);
                } else if src.is_inf() {
                    f.raise(ExcFlags::OPERR);
                    self.fpr[dst] = FloatX80::default_nan();
                } else {
                    // A larger count overflows or underflows just the same.
                    let n = if src.to_f64().abs() >= 2147483648.0 {
                        if src.sign() { i32::MIN } else { i32::MAX }
                    } else {
                        // The scale factor is truncated to an integer
                        // without reporting it: only the scaled result's
                        // own rounding can be inexact.
                        softfloat::to_i64(
                            src,
                            RoundMode::Zero,
                            i32::MIN as i64,
                            i32::MAX as i64,
                            &mut ExcFlags::default(),
                        ) as i32
                    };
                    self.fpr[dst] = softfloat::scale(self.fpr[dst], n, ctx, &mut f);
                }
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            0x30..=0x37 => {
                // FSINCOS - sin to FPn, cos to the FPc named by opmode bits 2-0.
                let ctx = self.fpu_ctx(opmode);
                let mut f = src_flags;
                let cos_dst = (opmode & 7) as usize;
                let (sin, cos) = transcendental::sincos(src, ctx, &mut f);
                // Cosine first: with FPs == FPc the sine must win (M68000PM
                // FSINCOS description).
                self.fpr[cos_dst] = cos;
                self.fpr[dst] = sin;
                self.fpu_set_cc(self.fpr[dst]);
                self.fpu_commit(f);
                4
            }
            _ => {
                // The transcendentals (FSIN/FCOS/FETOX/FLOGN/...).
                let ctx = self.fpu_ctx(opmode);
                let mut f = src_flags;
                if let Some(r) = transcendental::eval_unary(opmode, src, ctx, &mut f) {
                    self.fpr[dst] = r;
                    self.fpu_set_cc(self.fpr[dst]);
                    self.fpu_commit(f);
                    4
                } else {
                    0 // Unimplemented opmode -> Line-F
                }
            }
        }
    }

    /// Resolve the effective address for an FPU operand of `bytes`
    /// (0 = control mode, no auto-adjust). Post-increment/pre-decrement
    /// apply the FPU operand width; every other mode -- including the
    /// 68020 indexed and full-extension forms -- goes through the core
    /// resolver. Address-register direct is not a legal FPU operand.
    /// Resolve the operand address of an FP instruction that traps to the
    /// software package: extension words are consumed (the trap frame
    /// carries the next-instruction PC). Returns the EA long for the
    /// frame (0 when the operand is not in memory).
    ///
    /// On the 68060 the address register of an (An)+ or -(An) operand is
    /// left as it was: the M68060SP advances it. The stacked address is
    /// the operand's, except that for an extended or packed -(An) operand
    /// it is 8 bytes above it. The package's _dcalc_ea and _calc_ea_fout
    /// state both rules and correct for them, so an address register the
    /// processor had already moved would be moved twice. On the 68040
    /// post-increment and pre-decrement commit.
    pub(super) fn fpu_060_trap_ea<B: AddressBus>(
        &mut self,
        bus: &mut B,
        opcode: u16,
        fmt: u16,
    ) -> u32 {
        let ea_mode = ((opcode >> 3) & 7) as u8;
        let ea_reg = (opcode & 7) as usize;
        let bytes: u32 = match fmt {
            4 => 2,      // word
            6 => 1,      // byte
            5 => 8,      // double
            2 | 3 => 12, // extended / packed
            _ => 4,      // long / single
        };
        if self.is_060() {
            // A7 stays word-aligned for byte operands.
            let step = if bytes == 1 && ea_reg == 7 { 2 } else { bytes };
            match ea_mode {
                3 => return self.a(ea_reg),
                4 => {
                    let ea = self.a(ea_reg).wrapping_sub(step);
                    return if bytes == 12 { ea.wrapping_add(8) } else { ea };
                }
                _ => {}
            }
        }
        match self.fpu_ea(bus, ea_mode, ea_reg, bytes) {
            Some(FpuEa::Memory(addr)) => addr,
            Some(FpuEa::Immediate) => {
                // Immediate operands live in the instruction stream; skip
                // them so the frame PC lands on the next instruction.
                let skip = bytes.max(2) & !1;
                self.pc = self.pc.wrapping_add(skip);
                0
            }
            _ => 0,
        }
    }

    /// The effective address field of the format $3 frame an `FMOVE
    /// FPn,<ea>` of an unsupported data type stacks on the 68060, with the
    /// extension words consumed. For a byte, word, long, single or double
    /// destination the address is the destination's and an (An)+ or -(An)
    /// register has been updated. An extended destination leaves the
    /// register to the M68060SP: (An)+ stacks An, and -(An) stacks the
    /// address eight above the destination's (its _calc_ea_fout). A data
    /// register destination has no address.
    pub(super) fn fpu_060_move_out_ea<B: AddressBus>(
        &mut self,
        bus: &mut B,
        opcode: u16,
        fmt: u16,
    ) -> u32 {
        let ea_mode = ((opcode >> 3) & 7) as u8;
        let ea_reg = (opcode & 7) as usize;
        let bytes: u32 = match fmt {
            4 => 2,  // word
            6 => 1,  // byte
            5 => 8,  // double
            2 => 12, // extended
            _ => 4,  // long / single
        };
        match (fmt, ea_mode) {
            (2, 3) => self.a(ea_reg),
            (2, 4) => self.a(ea_reg).wrapping_sub(4),
            _ => match self.fpu_ea(bus, ea_mode, ea_reg, bytes) {
                Some(FpuEa::Memory(addr)) => addr,
                _ => 0,
            },
        }
    }

    /// `FScc <ea>` trap on the 68060: the instruction is emulated by the
    /// 68060SP. Resolve the byte-sized destination EA for the frame.
    pub(crate) fn fpu_060_scc_trap<B: AddressBus>(
        &mut self,
        bus: &mut B,
        ea_mode: u8,
        ea_reg: usize,
    ) -> i32 {
        let ea = match self.fpu_ea(bus, ea_mode, ea_reg, 1) {
            Some(FpuEa::Memory(addr)) => addr,
            _ => 0,
        };
        self.take_fp_unimp_060(bus, ea)
    }

    fn fpu_ea<B: AddressBus>(
        &mut self,
        bus: &mut B,
        ea_mode: u8,
        ea_reg: usize,
        bytes: u32,
    ) -> Option<FpuEa> {
        let mode = AddressingMode::decode(ea_mode, ea_reg as u8)?;
        match mode {
            AddressingMode::DataDirect(r) => Some(FpuEa::DataReg(r as usize)),
            AddressingMode::AddressDirect(_) => None,
            AddressingMode::PostIncrement(r) => {
                let r = r as usize;
                // A7 stays word-aligned for byte operands.
                let inc = if bytes == 1 && r == 7 { 2 } else { bytes };
                let addr = self.a(r);
                self.set_a(r, addr.wrapping_add(inc));
                Some(FpuEa::Memory(addr))
            }
            AddressingMode::PreDecrement(r) => {
                let r = r as usize;
                let dec = if bytes == 1 && r == 7 { 2 } else { bytes };
                let addr = self.a(r).wrapping_sub(dec);
                self.set_a(r, addr);
                Some(FpuEa::Memory(addr))
            }
            AddressingMode::Immediate => Some(FpuEa::Immediate),
            other => match self.resolve_ea(bus, other, Size::Long) {
                EaResult::Memory(addr) => Some(FpuEa::Memory(addr)),
                _ => None,
            },
        }
    }

    /// Read the ALU/FMOVE source operand in `fmt` (0=long, 1=single,
    /// 2=extended, 4=word, 6=byte, 5=double) as an extended value, with the
    /// exceptions its conversion raised. The extended format (2) is read
    /// losslessly. Integer, binary32, and binary64 inputs are widened
    /// exactly to the extended register format; packed decimal (3) is
    /// decoded by the packed-decimal engine.
    fn fpu_read_source<B: AddressBus>(
        &mut self,
        bus: &mut B,
        opcode: u16,
        fmt: u16,
    ) -> Option<(FloatX80, ExcFlags)> {
        let (raw, _) = self.fpu_fetch_source(bus, opcode, fmt)?;
        let mut f = ExcFlags::default();
        let value = raw.to_x80(&mut f);
        Some((value, f))
    }

    /// Fetch the source operand in `fmt` as it is stored, before any
    /// conversion, with its memory address (0 for a data register or an
    /// immediate).
    pub(super) fn fpu_fetch_source<B: AddressBus>(
        &mut self,
        bus: &mut B,
        opcode: u16,
        fmt: u16,
    ) -> Option<(RawSource, u32)> {
        let ea_mode = ((opcode >> 3) & 7) as u8;
        let ea_reg = (opcode & 7) as usize;
        let bytes: u32 = match fmt {
            6 => 1,
            4 => 2,
            0 | 1 => 4,
            5 => 8,
            2 | 3 => 12, // extended and packed-decimal are 12 bytes
            _ => return None,
        };
        let fetched = match self.fpu_ea(bus, ea_mode, ea_reg, bytes)? {
            FpuEa::DataReg(r) => {
                let v = self.d(r);
                let raw = match fmt {
                    0 => RawSource::Long(v),
                    1 => RawSource::Single(v),
                    4 => RawSource::Word(v as u16),
                    6 => RawSource::Byte(v as u8),
                    _ => return None, // 8/12-byte operands cannot live in Dn
                };
                (raw, 0)
            }
            FpuEa::Immediate => {
                let raw = match fmt {
                    0 => RawSource::Long(self.read_imm_32(bus)),
                    1 => RawSource::Single(self.read_imm_32(bus)),
                    4 => RawSource::Word(self.read_imm_16(bus)),
                    6 => RawSource::Byte((self.read_imm_16(bus) & 0xFF) as u8),
                    5 => {
                        let hi = self.read_imm_32(bus) as u64;
                        let lo = self.read_imm_32(bus) as u64;
                        RawSource::Double((hi << 32) | lo)
                    }
                    2 => {
                        let exp_word = (self.read_imm_32(bus) >> 16) as u16;
                        let hi = self.read_imm_32(bus) as u64;
                        let lo = self.read_imm_32(bus) as u64;
                        RawSource::Extended(exp_word, (hi << 32) | lo)
                    }
                    3 => {
                        let w0 = self.read_imm_32(bus);
                        let w1 = self.read_imm_32(bus);
                        let w2 = self.read_imm_32(bus);
                        RawSource::Packed([w0, w1, w2])
                    }
                    _ => return None,
                };
                (raw, 0)
            }
            FpuEa::Memory(addr) => {
                let raw = match fmt {
                    0 => RawSource::Long(self.read_32(bus, addr)),
                    1 => RawSource::Single(self.read_32(bus, addr)),
                    4 => RawSource::Word(self.read_16(bus, addr)),
                    6 => RawSource::Byte(self.read_8(bus, addr)),
                    5 => {
                        let hi = self.read_32(bus, addr) as u64;
                        let lo = self.read_32(bus, addr.wrapping_add(4)) as u64;
                        RawSource::Double((hi << 32) | lo)
                    }
                    2 => {
                        let exp_word = self.read_16(bus, addr);
                        let hi = self.read_32(bus, addr.wrapping_add(4)) as u64;
                        let lo = self.read_32(bus, addr.wrapping_add(8)) as u64;
                        RawSource::Extended(exp_word, (hi << 32) | lo)
                    }
                    3 => {
                        let w0 = self.read_32(bus, addr);
                        let w1 = self.read_32(bus, addr.wrapping_add(4));
                        let w2 = self.read_32(bus, addr.wrapping_add(8));
                        RawSource::Packed([w0, w1, w2])
                    }
                    _ => return None,
                };
                (raw, addr)
            }
        };
        Some(fetched)
    }

    /// Write `value` to the FMOVE destination in `fmt`. Integer formats
    /// round per FPCR and saturate; packed-decimal formats 3 and 7 honor
    /// their static or dynamic k-factor. Returns the address written (0
    /// for a data register), or `None` if the format/EA combination is
    /// invalid.
    fn fpu_write_dest<B: AddressBus>(
        &mut self,
        bus: &mut B,
        ea_mode: u8,
        ea_reg: usize,
        fmt: u16,
        kfactor: i8,
        value: FloatX80,
    ) -> Option<u32> {
        let bytes: u32 = match fmt {
            6 => 1,
            4 => 2,
            0 | 1 => 4,
            5 => 8,
            2 | 3 | 7 => 12, // extended and packed-decimal (static/dynamic k)
            _ => return None,
        };
        let ea = self.fpu_ea(bus, ea_mode, ea_reg, bytes)?;
        let address = match ea {
            FpuEa::Memory(addr) => addr,
            _ => 0,
        };
        let value = canonical_operand(value);
        // Integer, single and double results are rounded once, straight
        // from the extended value, by the FPCR rounding mode, and report
        // their exceptions in FPSR like an arithmetic result.
        let mode = RoundMode::from_fpcr(self.fpcr);
        let mut f = ExcFlags::default();
        let written = match ea {
            FpuEa::DataReg(r) => match fmt {
                0 => {
                    let v =
                        softfloat::to_i64(value, mode, i32::MIN as i64, i32::MAX as i64, &mut f);
                    self.set_d(r, v as u32);
                    true
                }
                1 => {
                    let v = softfloat::to_f32_bits(value, mode, &mut f);
                    self.set_d(r, v);
                    true
                }
                4 => {
                    let v =
                        softfloat::to_i64(value, mode, i16::MIN as i64, i16::MAX as i64, &mut f);
                    self.set_d(r, (self.d(r) & 0xFFFF_0000) | (v as u16 as u32));
                    true
                }
                6 => {
                    let v = softfloat::to_i64(value, mode, i8::MIN as i64, i8::MAX as i64, &mut f);
                    self.set_d(r, (self.d(r) & 0xFFFF_FF00) | (v as u8 as u32));
                    true
                }
                _ => false,
            },
            FpuEa::Memory(addr) => match fmt {
                0 => {
                    let v =
                        softfloat::to_i64(value, mode, i32::MIN as i64, i32::MAX as i64, &mut f);
                    self.write_32(bus, addr, v as u32);
                    true
                }
                1 => {
                    let v = softfloat::to_f32_bits(value, mode, &mut f);
                    self.write_32(bus, addr, v);
                    true
                }
                4 => {
                    let v =
                        softfloat::to_i64(value, mode, i16::MIN as i64, i16::MAX as i64, &mut f);
                    self.write_16(bus, addr, v as u16);
                    true
                }
                6 => {
                    let v = softfloat::to_i64(value, mode, i8::MIN as i64, i8::MAX as i64, &mut f);
                    self.write_8(bus, addr, v as u8);
                    true
                }
                5 => {
                    let bits = softfloat::to_f64_bits(value, mode, &mut f);
                    self.write_32(bus, addr, (bits >> 32) as u32);
                    self.write_32(bus, addr.wrapping_add(4), bits as u32);
                    true
                }
                2 => {
                    // Not rounded, but a signaling NaN is stored quiet and
                    // raises SNAN like the other formats (MC68881/MC68882UM
                    // 4.6.4); the exception byte is rebuilt as for any
                    // FMOVE out.
                    let value = if value.is_signaling_nan() {
                        f.raise(ExcFlags::SNAN);
                        value.quiet()
                    } else {
                        value
                    };
                    // A denormalized number is below the normalized range
                    // of this format as of the others: an underflow, exact
                    // as it is (MC68881/MC68882UM 6.1.5).
                    if is_denormalized(value) {
                        f.raise(ExcFlags::UNFL);
                    }
                    let (exp_word, mantissa) = value.to_extended();
                    self.write_32(bus, addr, (exp_word as u32) << 16);
                    self.write_32(bus, addr.wrapping_add(4), (mantissa >> 32) as u32);
                    self.write_32(bus, addr.wrapping_add(8), mantissa as u32);
                    true
                }
                3 | 7 => {
                    // Packed decimal (static or dynamic k-factor), cut to
                    // its digits by the FPCR rounding mode.
                    let bytes = packed::to_packed(value, kfactor, mode, &mut f);
                    for (i, chunk) in bytes.chunks(4).enumerate() {
                        let w = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
                        self.write_32(bus, addr.wrapping_add(4 * i as u32), w);
                    }
                    true
                }
                _ => false,
            },
            FpuEa::Immediate => false,
        };
        if written {
            self.fpu_commit(f);
        }
        written.then_some(address)
    }
}

/// Version byte of the 6888x state frames this FPU saves (in bits 31-24).
const FPU_6888X_VERSION: u32 = 0x1F00_0000;

/// Bit 27 of the BIU flags, the last long of a 6888x IDLE frame: set when
/// no exception is waiting to be reported, clear while one is
/// (MC68881/MC68882UM 6.4.2). An exception handler sets it in the frame it
/// saved before restoring it.
const BIU_NO_EXCEPTION_PENDING: u32 = 0x0800_0000;

/// The FSAVE IDLE frame is CPU-specific: the 68040's on-chip FPU saves the
/// four-byte frame $41000000 (version $41, size $00; M68040UM 9.7), while
/// the 68881 coprocessor of 020/030 systems saves the $18-byte IDLE frame
/// (MC68881/MC68882UM 6.4.2), whose BIU flags say whether an exception is
/// still unreported. The size byte matters to guests: Linux/m68k
/// validates a signal frame's saved FPU state against the per-CPU size set
/// ($00/$28/$60 on the 040) before FRESTOREing it.
fn fsave_idle_frame(cpu: &CpuCore) -> (u32, u32, u32) {
    if cpu.is_040() {
        (0x4100_0000, 1, 0) // header, total longs, last long
    } else {
        let biu = if cpu.fpu_exception_pending == 0 {
            0x7000_0000 | BIU_NO_EXCEPTION_PENDING
        } else {
            0x7000_0000
        };
        (FPU_6888X_VERSION | 0x0018_0000, 7, biu)
    }
}

/// Longs the FSAVE EA register update covers beyond the header long.
pub(crate) fn fsave_extra_longs(cpu: &CpuCore) -> u32 {
    fsave_idle_frame(cpu).1 - 1
}

/// Write the IDLE frame. The state it saves includes an exception that is
/// still unreported, which is therefore no longer pending in the FPU: the
/// 6888x frame records it, and FRESTORE of that frame brings it back. The
/// 68040 frames that carry one are not modelled, so there it is dropped.
fn perform_fsave<B: AddressBus>(bus: &mut B, cpu: &mut CpuCore, addr: u32, inc: bool) {
    let (header, longs, last) = fsave_idle_frame(cpu);
    cpu.fpu_exception_pending = 0;
    if longs == 1 {
        cpu.write_32(bus, addr, header);
        return;
    }
    if inc {
        cpu.write_32(bus, addr, header);
        for i in 1..longs - 1 {
            cpu.write_32(bus, addr.wrapping_add(i * 4), 0);
        }
        cpu.write_32(bus, addr.wrapping_add((longs - 1) * 4), last);
    } else {
        cpu.write_32(bus, addr, last);
        for i in 1..longs - 1 {
            cpu.write_32(bus, addr.wrapping_sub(i * 4), 0);
        }
        cpu.write_32(bus, addr.wrapping_sub((longs - 1) * 4), header);
    }
}

#[cfg(test)]
mod tests {
    use super::Dyadic;

    #[test]
    fn dyadic_classification_matches_the_opmode_table() {
        for opmode in 0..=0x7Fu16 {
            let expected = match opmode {
                0x22 | 0x62 | 0x66 => Some(Dyadic::Add),
                0x23 | 0x63 | 0x67 => Some(Dyadic::Mul),
                0x28 | 0x68 | 0x6C => Some(Dyadic::Sub),
                0x20 | 0x60 | 0x64 => Some(Dyadic::Div),
                _ => None,
            };
            assert!(Dyadic::of(opmode) == expected, "opmode {opmode:#x}");
        }
    }
}