m68k 0.17.3

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
//! Pure-Rust 80-bit extended-precision (floatx80) software FPU engine.
//!
//! Operates purely on [`FloatX80`] values plus a [`RoundCtx`] (rounding mode +
//! precision) and an [`ExcFlags`] out-accumulator. No `CpuCore` dependency, so
//! it is unit-testable in isolation. The glue in `operations.rs` decodes the
//! instruction, calls these functions, and folds the returned flags into FPSR.
//!
//! Internal representation: a finite value is carried as a 128-bit significand
//! `m` with its leading integer bit normalized to bit 127, and an exponent
//! `e` such that the value magnitude is `m * 2^(e - 127)`. The low 64 bits of
//! `m` are guard/round/sticky room. [`round_pack`] is the single normalize +
//! round + pack path every arithmetic op funnels through.

use super::types::FloatX80;

/// Exponent bias of the 80-bit extended format.
const BIAS: i32 = 16383;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RoundMode {
    Nearest,
    Zero,
    NegInf,
    PosInf,
}

impl RoundMode {
    /// Decode FPCR bits 5:4.
    pub fn from_fpcr(fpcr: u32) -> Self {
        match (fpcr >> 4) & 3 {
            1 => RoundMode::Zero,
            2 => RoundMode::NegInf,
            3 => RoundMode::PosInf,
            _ => RoundMode::Nearest,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Precision {
    Extended,
    Single,
    Double,
}

impl Precision {
    /// Decode FPCR bits 7:6 (rounding precision).
    pub fn from_fpcr(fpcr: u32) -> Self {
        match (fpcr >> 6) & 3 {
            1 => Precision::Single,
            2 => Precision::Double,
            _ => Precision::Extended,
        }
    }

    /// Number of significand bits kept (including the integer bit).
    const fn bits(self) -> u32 {
        match self {
            Precision::Extended => 64,
            Precision::Double => 53,
            Precision::Single => 24,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct RoundCtx {
    pub mode: RoundMode,
    pub prec: Precision,
}

impl RoundCtx {
    /// Round-to-nearest, extended precision (the internal default).
    pub const NEAREST_EXT: RoundCtx = RoundCtx {
        mode: RoundMode::Nearest,
        prec: Precision::Extended,
    };
}

/// FPU exception accumulator. Bit layout matches the FPSR exception-status
/// byte shifted down to bits 7:0 (BSUN=7, SNAN=6, OPERR=5, OVFL=4, UNFL=3,
/// DZ=2, INEX2=1, INEX1=0).
///
/// It also carries the last finite result that went through rounding, as
/// it was before that step ([`Unrounded`]).
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
pub struct ExcFlags(pub u8, Option<Unrounded>);

/// A finite result as it reaches the rounding step: normalized, with an
/// exponent that is not yet confined to the format. This is the
/// "intermediate result" of the manuals, which the 68040 exposes in its
/// state frame when the result overflows, underflows or is inexact
/// (M68040UM 9.4.1 and table 9-16).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Unrounded {
    pub sign: bool,
    /// Biased exponent of the integer bit: below 0 or above $7FFE when the
    /// result is out of the extended range.
    pub exp: i32,
    /// Significand with the integer bit at bit 127.
    mant: u128,
    ctx: RoundCtx,
}

impl Unrounded {
    /// The 64-bit mantissa cut off without rounding, and the guard, round
    /// and sticky bits below it (bits 2, 1 and 0).
    pub fn truncated(self) -> (u64, u8) {
        let low = self.mant as u64;
        let sticky = u8::from(low << 2 != 0);
        ((self.mant >> 64) as u64, ((low >> 62) as u8) << 1 | sticky)
    }

    /// The exponent and mantissa rounded to the operation's precision in
    /// its rounding mode, the exponent still unconfined.
    pub fn rounded(self) -> (i32, u64) {
        self.rounded_to(self.ctx.prec)
    }

    /// The exponent and mantissa rounded to extended precision in the
    /// operation's rounding mode, the exponent still unconfined.
    pub fn rounded_extended(self) -> (i32, u64) {
        self.rounded_to(Precision::Extended)
    }

    fn rounded_to(self, prec: Precision) -> (i32, u64) {
        let p = prec.bits();
        let shift = 128 - p;
        let q = (self.mant >> shift) as u64;
        let rem = self.mant & ((1u128 << shift) - 1);
        let mut q = q as u128 + u128::from(rounds_up(self.sign, q, rem, shift, self.ctx.mode));
        let mut exp = self.exp;
        if (q >> p) != 0 {
            q >>= 1;
            exp += 1;
        }
        (exp, (q as u64) << (64 - p))
    }
}

impl ExcFlags {
    /// Flags from an FPSR exception-status byte.
    pub const fn from_bits(bits: u8) -> Self {
        Self(bits, None)
    }

    /// The result of the last rounding step before it was rounded, if a
    /// finite result went through one.
    pub fn unrounded(self) -> Option<Unrounded> {
        self.1
    }

    // BSUN and INEX1 are produced by the glue (FBcc / packed decimal), not by
    // the value engine itself.
    pub const BSUN: u8 = 0x80;
    pub const SNAN: u8 = 0x40;
    pub const OPERR: u8 = 0x20;
    pub const OVFL: u8 = 0x10;
    pub const UNFL: u8 = 0x08;
    pub const DZ: u8 = 0x04;
    pub const INEX2: u8 = 0x02;
    pub const INEX1: u8 = 0x01;

    #[inline]
    pub fn raise(&mut self, bits: u8) {
        self.0 |= bits;
    }

    #[inline]
    pub fn has(self, bits: u8) -> bool {
        self.0 & bits != 0
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum FpCmp {
    Less,
    Equal,
    Greater,
    Unordered,
}

// ============================== constructors ==============================

const fn one(sign: bool) -> FloatX80 {
    FloatX80 {
        sign_exp: ((sign as u16) << 15) | (BIAS as u16),
        mantissa: 0x8000_0000_0000_0000,
    }
}

// ============================== unpacking =================================

/// A finite, nonzero operand decomposed for arithmetic: sign, the exponent of
/// the integer bit (so magnitude ~ 2^exp), and a normalized 64-bit significand
/// with the integer bit at bit 63. Denormals are normalized (exp goes below
/// the format minimum, which round_pack re-denormalizes on output).
struct Unpacked {
    sign: bool,
    exp: i32,
    mant: u64,
}

fn unpack(x: FloatX80) -> Unpacked {
    let sign = x.sign();
    let biased = x.biased_exp();
    if biased == 0 {
        // Denormal: normalize so the integer bit reaches bit 63. Unlike the
        // x87, the MC68881 does not treat a biased exponent of 0 as 1: the
        // value is mantissa * 2^(-BIAS-63), integer bit included.
        let lz = x.mantissa.leading_zeros();
        Unpacked {
            sign,
            exp: -BIAS - lz as i32,
            mant: x.mantissa << lz,
        }
    } else {
        Unpacked {
            sign,
            exp: biased as i32 - BIAS,
            mant: x.mantissa,
        }
    }
}

// ============================== round + pack ==============================

/// Shift `m` right by `sh`, OR-ing any bits shifted out into bit 0 (sticky).
fn shift_right_sticky(m: u128, sh: u32) -> u128 {
    if sh == 0 {
        m
    } else if sh >= 128 {
        u128::from(m != 0)
    } else {
        let lost = m & ((1u128 << sh) - 1);
        (m >> sh) | u128::from(lost != 0)
    }
}

fn overflow_result(sign: bool, mode: RoundMode) -> FloatX80 {
    let to_inf = match mode {
        RoundMode::Nearest => true,
        RoundMode::Zero => false,
        RoundMode::PosInf => !sign,
        RoundMode::NegInf => sign,
    };
    if to_inf {
        FloatX80::infinity(sign)
    } else {
        // Largest finite magnitude.
        FloatX80 {
            sign_exp: ((sign as u16) << 15) | 0x7FFE,
            mantissa: 0xFFFF_FFFF_FFFF_FFFF,
        }
    }
}

/// Whether discarding `rem`, the `shift` bits below the quotient `q`, rounds
/// the magnitude up in `mode`.
fn rounds_up(sign: bool, q: u64, rem: u128, shift: u32, mode: RoundMode) -> bool {
    let halfway = 1u128 << (shift - 1);
    match mode {
        RoundMode::Nearest => rem > halfway || (rem == halfway && (q & 1) == 1),
        RoundMode::Zero => false,
        RoundMode::PosInf => !sign && rem != 0,
        RoundMode::NegInf => sign && rem != 0,
    }
}

/// Normalize, round to `ctx.prec`, and pack a finite result. `m` is a 128-bit
/// significand and `exp` is the exponent of bit 127 (value = m * 2^(exp-127)).
fn round_pack(sign: bool, mut exp: i32, mut m: u128, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if m == 0 {
        return FloatX80::zero(sign);
    }
    // Normalize the integer bit up to bit 127.
    let lz = m.leading_zeros();
    m <<= lz;
    exp -= lz as i32;

    let mut biased = exp + BIAS;
    f.1 = Some(Unrounded {
        sign,
        exp: biased,
        mant: m,
        ctx,
    });

    // Denormalize if the exponent is below the format minimum. That is a
    // biased exponent of 0, which holds the integer bit like any other.
    if biased < 0 {
        // Too small to be a normalized number: that is the underflow,
        // whether or not denormalizing it loses anything (MC68881/
        // MC68882UM 6.1.5, M68040UM 9.7.5, M68060UM 6.6.5). The accrued
        // bit waits for the inexact result as well.
        f.raise(ExcFlags::UNFL);
        let sh = (-biased) as u32;
        m = shift_right_sticky(m, sh);
        biased = 0;
    }

    let p = ctx.prec.bits();
    let shift = 128 - p; // discarded low bits
    let q = (m >> shift) as u64; // p significant bits, integer bit at bit p-1
    let rem = m & ((1u128 << shift) - 1);
    let round_up = rounds_up(sign, q, rem, shift, ctx.mode);
    if rem != 0 {
        f.raise(ExcFlags::INEX2);
    }

    let mut q = q as u128;
    if round_up {
        q += 1;
        if (q >> p) != 0 {
            // Carried out of the significand: renormalize.
            q >>= 1;
            biased += 1;
        }
    }

    let integer_bit_set = (q >> (p - 1)) & 1 != 0;
    if !integer_bit_set {
        // Result is subnormal (or zero).
        if q == 0 {
            return FloatX80::zero(sign);
        }
        let mantissa = (q as u64) << (64 - p);
        return FloatX80 {
            sign_exp: (sign as u16) << 15,
            mantissa,
        };
    }

    if biased >= 0x7FFF {
        // INEX2 is for the mantissa's rounding alone, raised above: an
        // overflow is recorded as inexact in the accrued byte, not here
        // (MC68881/MC68882UM 6.1.7, M68040UM 9.7.7, M68060UM 6.6.7).
        f.raise(ExcFlags::OVFL);
        return overflow_result(sign, ctx.mode);
    }

    let mantissa = (q as u64) << (64 - p);
    FloatX80 {
        sign_exp: ((sign as u16) << 15) | (biased as u16),
        mantissa,
    }
}

// ============================== NaN handling ==============================

/// NaN operand rule (MC68881/MC68882UM 4.6.4, M68040UM 9.5.2): the result
/// is the destination NaN if the destination is one, else the source NaN,
/// returned quiet. A signaling NaN operand raises SNAN only: the 6888x
/// splits IEEE invalid-operation into SNAN and OPERR, and OPERR is for
/// operations that are invalid on non-NaN operands (inf - inf, 0 * inf,
/// sqrt(-x), ...).
pub fn propagate_nan(a: FloatX80, b: FloatX80, f: &mut ExcFlags) -> FloatX80 {
    if a.is_signaling_nan() || b.is_signaling_nan() {
        f.raise(ExcFlags::SNAN);
    }
    if a.is_nan() { a.quiet() } else { b.quiet() }
}

// ============================== sign ops ==================================

pub fn neg(a: FloatX80) -> FloatX80 {
    FloatX80 {
        sign_exp: a.sign_exp ^ 0x8000,
        mantissa: a.mantissa,
    }
}

pub fn abs(a: FloatX80) -> FloatX80 {
    FloatX80 {
        sign_exp: a.sign_exp & 0x7FFF,
        mantissa: a.mantissa,
    }
}

// ============================== add / sub ================================

pub fn add(a: FloatX80, b: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if a.is_nan() || b.is_nan() {
        return propagate_nan(a, b, f);
    }
    if a.is_inf() || b.is_inf() {
        if a.is_inf() && b.is_inf() && a.sign() != b.sign() {
            f.raise(ExcFlags::OPERR);
            return FloatX80::default_nan();
        }
        return if a.is_inf() { a } else { b };
    }
    if a.is_zero() && b.is_zero() {
        // Zeros of one sign keep it. Opposite ones give +0, or -0 when
        // rounding toward minus infinity.
        let sign = if a.sign() == b.sign() {
            a.sign()
        } else {
            ctx.mode == RoundMode::NegInf
        };
        return FloatX80::zero(sign);
    }
    if a.is_zero() {
        return round_pack(b.sign(), b_exp_hi(b).0, b_exp_hi(b).1, ctx, f);
    }
    if b.is_zero() {
        return round_pack(a.sign(), b_exp_hi(a).0, b_exp_hi(a).1, ctx, f);
    }

    let ua = unpack(a);
    let ub = unpack(b);
    // Significands with integer bit at bit 127.
    let (hs, he, hm, ls, _le, lm) = if ua.exp >= ub.exp {
        (
            ua.sign,
            ua.exp,
            (ua.mant as u128) << 64,
            ub.sign,
            ub.exp,
            (ub.mant as u128) << 64,
        )
    } else {
        (
            ub.sign,
            ub.exp,
            (ub.mant as u128) << 64,
            ua.sign,
            ua.exp,
            (ua.mant as u128) << 64,
        )
    };
    let diff = (he - if ua.exp >= ub.exp { ub.exp } else { ua.exp }) as u32;
    let lm = shift_right_sticky(lm, diff);

    if hs == ls {
        let (sum, carry) = hm.overflowing_add(lm);
        if carry {
            let sticky = sum & 1;
            round_pack(hs, he + 1, (sum >> 1) | (1u128 << 127) | sticky, ctx, f)
        } else {
            round_pack(hs, he, sum, ctx, f)
        }
    } else if hm >= lm {
        let m = hm - lm;
        if m == 0 {
            return FloatX80::zero(ctx.mode == RoundMode::NegInf);
        }
        round_pack(hs, he, m, ctx, f)
    } else {
        round_pack(ls, he, lm - hm, ctx, f)
    }
}

/// Return (exp-of-bit-127, significand<<64) for a finite operand.
fn b_exp_hi(x: FloatX80) -> (i32, u128) {
    let u = unpack(x);
    (u.exp, (u.mant as u128) << 64)
}

pub fn sub(a: FloatX80, b: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    // The NaN operand rule applies before the subtrahend is negated: a NaN
    // comes out with its own sign.
    if a.is_nan() || b.is_nan() {
        return propagate_nan(a, b, f);
    }
    add(a, neg(b), ctx, f)
}

// ============================== mul / div ================================

pub fn mul(a: FloatX80, b: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if a.is_nan() || b.is_nan() {
        return propagate_nan(a, b, f);
    }
    let sign = a.sign() ^ b.sign();
    if a.is_inf() || b.is_inf() {
        if a.is_zero() || b.is_zero() {
            f.raise(ExcFlags::OPERR);
            return FloatX80::default_nan();
        }
        return FloatX80::infinity(sign);
    }
    if a.is_zero() || b.is_zero() {
        return FloatX80::zero(sign);
    }
    let ua = unpack(a);
    let ub = unpack(b);
    let prod = (ua.mant as u128) * (ub.mant as u128);
    // value = prod * 2^((ua.exp-63)+(ub.exp-63)); round_pack wants exp of bit127.
    round_pack(sign, ua.exp + ub.exp + 1, prod, ctx, f)
}

pub fn div(a: FloatX80, b: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if a.is_nan() || b.is_nan() {
        return propagate_nan(a, b, f);
    }
    let sign = a.sign() ^ b.sign();
    if a.is_inf() {
        if b.is_inf() {
            f.raise(ExcFlags::OPERR);
            return FloatX80::default_nan();
        }
        return FloatX80::infinity(sign);
    }
    if b.is_inf() {
        return FloatX80::zero(sign);
    }
    if b.is_zero() {
        if a.is_zero() {
            f.raise(ExcFlags::OPERR);
            return FloatX80::default_nan();
        }
        f.raise(ExcFlags::DZ);
        return FloatX80::infinity(sign);
    }
    if a.is_zero() {
        return FloatX80::zero(sign);
    }
    let ua = unpack(a);
    let ub = unpack(b);
    // The ratio of two normalized mantissas is in (1/2, 2). 64 fraction bits
    // leave no guard bit when it is below 1, so divide the remainder again:
    // q1 = floor(ratio * 2^64), q2 = the next 64 bits.
    let mb = ub.mant as u128;
    let num = (ua.mant as u128) << 64;
    let q1 = num / mb;
    let r1 = num % mb;
    let q2 = (r1 << 64) / mb;
    let r2 = (r1 << 64) % mb;
    // q1 has at most 65 bits: m = ratio * 2^126, so bit 127 stands for 2^1.
    let mut m = (q1 << 62) | (q2 >> 2);
    if (q2 & 3) != 0 || r2 != 0 {
        m |= 1;
    }
    round_pack(sign, ua.exp - ub.exp + 1, m, ctx, f)
}

// ============================== sqrt =====================================

/// Floor integer square root of a u128, returning (root, remainder).
fn isqrt128(n: u128) -> (u128, u128) {
    if n == 0 {
        return (0, 0);
    }
    let mut x = n;
    let mut c: u128 = 0;
    // Highest power of four <= n.
    let mut d: u128 = 1u128 << (126 - (n.leading_zeros() & !1));
    while d > x {
        d >>= 2;
    }
    while d != 0 {
        if x >= c + d {
            x -= c + d;
            c = (c >> 1) + d;
        } else {
            c >>= 1;
        }
        d >>= 2;
    }
    (c, x)
}

pub fn sqrt(a: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if a.is_nan() {
        return propagate_nan(a, a, f);
    }
    if a.is_zero() {
        return FloatX80::zero(a.sign()); // sqrt(-0) = -0
    }
    if a.sign() {
        f.raise(ExcFlags::OPERR); // sqrt of a negative
        return FloatX80::default_nan();
    }
    if a.is_inf() {
        return a; // +inf
    }
    let ua = unpack(a);
    let e = ua.exp - 63; // value = mant * 2^e, mant in [2^63, 2^64)
    // Choose a shift s in {63, 64} so that (e - s) is even and the radicand
    // mant<<s lands in [2^126, 2^128) -> root in [2^63, 2^64).
    let (s, big_e) = if (e & 1) == 0 {
        (64u32, e - 64)
    } else {
        (63u32, e - 63)
    };
    let radicand = (ua.mant as u128) << s;
    let (root, remb) = isqrt128(radicand);
    let mut m = root << 64; // integer bit at bit 127
    // The root has no guard bit: sqrt > root + 1/2 exactly when the
    // remainder exceeds root ((root + 1/2)^2 = root^2 + root + 1/4), and
    // there are no ties.
    if remb > root {
        m |= (1u128 << 63) | 1; // above half
    } else if remb != 0 {
        m |= 1; // below half
    }
    // value = root * 2^(big_e/2); round_pack wants exp of bit127 = big_e/2 + 63.
    round_pack(false, big_e / 2 + 63, m, ctx, f)
}

// ============================== constant ROM =============================

/// One FMOVECR ROM constant: its sign/exponent word, the mantissa
/// delivered under RN, under RZ and RM, and under RP, and whether the
/// value is inexact (sets INEX2).
struct RomConstant {
    sign_exp: u16,
    rn: u64,
    rzrm: u64,
    rp: u64,
    inexact: bool,
}

const fn rom(sign_exp: u16, rn: u64, rzrm: u64, rp: u64, inexact: bool) -> RomConstant {
    RomConstant {
        sign_exp,
        rn,
        rzrm,
        rp,
        inexact,
    }
}

/// The MC68881/MC68882 constant ROM as Motorola's M68040 FPSP reproduces it
/// for the 68040 (smovecr.sa, tables PIRN..BIGRP in get_op.sa): every
/// constant comes in an RN, an RZ/RM and an RP extended pattern, and the
/// FPSP reports INEX2 for the same set the 6888x does. Note the ROM's RN
/// patterns for log10(2) and e are the truncated values, and log10(e) is
/// delivered without INEX2.
fn rom_constant(offset: usize) -> Option<&'static RomConstant> {
    const PI: RomConstant = rom(
        0x4000,
        0xC90F_DAA2_2168_C235,
        0xC90F_DAA2_2168_C234,
        0xC90F_DAA2_2168_C235,
        true,
    );
    // $0B-$0E: log10(2), e, log2(e), log10(e).
    const SMALL: [RomConstant; 4] = [
        rom(
            0x3FFD,
            0x9A20_9A84_FBCF_F798,
            0x9A20_9A84_FBCF_F798,
            0x9A20_9A84_FBCF_F799,
            true,
        ),
        rom(
            0x4000,
            0xADF8_5458_A2BB_4A9A,
            0xADF8_5458_A2BB_4A9A,
            0xADF8_5458_A2BB_4A9B,
            true,
        ),
        rom(
            0x3FFF,
            0xB8AA_3B29_5C17_F0BC,
            0xB8AA_3B29_5C17_F0BB,
            0xB8AA_3B29_5C17_F0BC,
            true,
        ),
        rom(
            0x3FFD,
            0xDE5B_D8A9_3728_7195,
            0xDE5B_D8A9_3728_7195,
            0xDE5B_D8A9_3728_7195,
            false,
        ),
    ];
    // $30-$3F: ln(2), ln(10), 10^0, 10^1, 10^2, 10^4, ..., 10^4096.
    const BIG: [RomConstant; 16] = [
        rom(
            0x3FFE,
            0xB172_17F7_D1CF_79AC,
            0xB172_17F7_D1CF_79AB,
            0xB172_17F7_D1CF_79AC,
            true,
        ),
        rom(
            0x4000,
            0x935D_8DDD_AAA8_AC17,
            0x935D_8DDD_AAA8_AC16,
            0x935D_8DDD_AAA8_AC17,
            true,
        ),
        rom(
            0x3FFF,
            0x8000_0000_0000_0000,
            0x8000_0000_0000_0000,
            0x8000_0000_0000_0000,
            false,
        ),
        rom(
            0x4002,
            0xA000_0000_0000_0000,
            0xA000_0000_0000_0000,
            0xA000_0000_0000_0000,
            false,
        ),
        rom(
            0x4005,
            0xC800_0000_0000_0000,
            0xC800_0000_0000_0000,
            0xC800_0000_0000_0000,
            false,
        ),
        rom(
            0x400C,
            0x9C40_0000_0000_0000,
            0x9C40_0000_0000_0000,
            0x9C40_0000_0000_0000,
            false,
        ),
        rom(
            0x4019,
            0xBEBC_2000_0000_0000,
            0xBEBC_2000_0000_0000,
            0xBEBC_2000_0000_0000,
            false,
        ),
        rom(
            0x4034,
            0x8E1B_C9BF_0400_0000,
            0x8E1B_C9BF_0400_0000,
            0x8E1B_C9BF_0400_0000,
            false,
        ),
        rom(
            0x4069,
            0x9DC5_ADA8_2B70_B59E,
            0x9DC5_ADA8_2B70_B59D,
            0x9DC5_ADA8_2B70_B59E,
            true,
        ),
        rom(
            0x40D3,
            0xC278_1F49_FFCF_A6D5,
            0xC278_1F49_FFCF_A6D5,
            0xC278_1F49_FFCF_A6D6,
            true,
        ),
        rom(
            0x41A8,
            0x93BA_47C9_80E9_8CE0,
            0x93BA_47C9_80E9_8CDF,
            0x93BA_47C9_80E9_8CE0,
            true,
        ),
        rom(
            0x4351,
            0xAA7E_EBFB_9DF9_DE8E,
            0xAA7E_EBFB_9DF9_DE8D,
            0xAA7E_EBFB_9DF9_DE8E,
            true,
        ),
        rom(
            0x46A3,
            0xE319_A0AE_A60E_91C7,
            0xE319_A0AE_A60E_91C6,
            0xE319_A0AE_A60E_91C7,
            true,
        ),
        rom(
            0x4D48,
            0xC976_7586_8175_0C17,
            0xC976_7586_8175_0C17,
            0xC976_7586_8175_0C18,
            true,
        ),
        rom(
            0x5A92,
            0x9E8B_3B5D_C53D_5DE5,
            0x9E8B_3B5D_C53D_5DE5,
            0x9E8B_3B5D_C53D_5DE6,
            true,
        ),
        rom(
            0x7525,
            0xC460_5202_8A20_979B,
            0xC460_5202_8A20_979A,
            0xC460_5202_8A20_979B,
            true,
        ),
    ];
    match offset {
        0x00 => Some(&PI),
        0x0B..=0x0E => Some(&SMALL[offset - 0x0B]),
        0x30..=0x3F => Some(&BIG[offset - 0x30]),
        _ => None,
    }
}

/// FMOVECR: the constant at ROM `offset`, as delivered under the FPCR
/// rounding mode and precision of `ctx`. The mode picks one of the ROM's
/// three patterns, which a single or double precision then rounds in that
/// mode; INEX2 is set for an inexact constant or a precision rounding that
/// discards bits. Offsets with no constant ($01-$0A, $0F, $10-$2F, $40+)
/// return +0.0 exactly (M68000PRM FMOVECR, M68040 FPSP smovecr.sa).
pub fn fmovecr(offset: usize, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    let Some(c) = rom_constant(offset) else {
        return FloatX80::zero(false);
    };
    let mantissa = match ctx.mode {
        RoundMode::Nearest => c.rn,
        RoundMode::Zero | RoundMode::NegInf => c.rzrm,
        RoundMode::PosInf => c.rp,
    };
    if c.inexact {
        f.raise(ExcFlags::INEX2);
    }
    round_to_precision(
        FloatX80 {
            sign_exp: c.sign_exp,
            mantissa,
        },
        ctx,
        f,
    )
}

/// The FMOVECR constant at `offset` as delivered in RN, extended precision.
#[cfg(test)]
pub fn const_rom(offset: usize) -> FloatX80 {
    fmovecr(offset, RoundCtx::NEAREST_EXT, &mut ExcFlags::default())
}

// ============================== int <-> x80 ==============================

/// Build an exact extended value from a u64 magnitude and a sign.
pub fn from_u64(v: u64, sign: bool) -> FloatX80 {
    if v == 0 {
        return FloatX80::zero(sign);
    }
    round_pack(
        sign,
        63,
        (v as u128) << 64,
        RoundCtx::NEAREST_EXT,
        &mut ExcFlags::default(),
    )
}

/// Round `x` to an integer in `[min, max]`, saturating on overflow/NaN/Inf
/// (raising OPERR) and raising INEX on a fractional discard.
pub fn to_i64(x: FloatX80, mode: RoundMode, min: i64, max: i64, f: &mut ExcFlags) -> i64 {
    if x.is_nan() {
        f.raise(ExcFlags::OPERR);
        return min;
    }
    if x.is_inf() {
        f.raise(ExcFlags::OPERR);
        return if x.sign() { min } else { max };
    }
    let r = round_to_int(x, mode, f);
    if r.is_zero() {
        return 0;
    }
    let u = unpack(r);
    if u.exp > 63 {
        f.raise(ExcFlags::OPERR);
        return if u.sign { min } else { max };
    }
    let mag = (u.mant >> (63 - u.exp)) as u128;
    let val = if u.sign { -(mag as i128) } else { mag as i128 };
    if val < min as i128 {
        f.raise(ExcFlags::OPERR);
        min
    } else if val > max as i128 {
        f.raise(ExcFlags::OPERR);
        max
    } else {
        val as i64
    }
}

/// Shift `m` right by `sh` and round the result by `mode`, as for a value of
/// sign `sign`. Returns the rounded quotient and whether bits were lost.
fn shift_round(m: u64, sh: u32, sign: bool, mode: RoundMode) -> (u64, bool) {
    if sh == 0 {
        return (m, false);
    }
    let m = m as u128;
    let (q, rem, half) = if sh >= 128 {
        (0, m, u128::MAX)
    } else {
        (m >> sh, m & ((1u128 << sh) - 1), 1u128 << (sh - 1))
    };
    let round_up = match mode {
        RoundMode::Nearest => rem > half || (rem == half && (q & 1) == 1),
        RoundMode::Zero => false,
        RoundMode::PosInf => !sign && rem != 0,
        RoundMode::NegInf => sign && rem != 0,
    };
    ((q + u128::from(round_up)) as u64, rem != 0)
}

/// Convert `x` to an IEEE binary format with `frac_bits` fraction bits and
/// `exp_bits` exponent bits, rounding by `mode` (FMOVE to `.s`/`.d`). The
/// result is rounded once, straight from the extended significand, with the
/// destination's exponent range: denormals below it, and overflow to
/// infinity or the largest finite value as the mode dictates. Raises INEX2,
/// UNFL and OVFL like an arithmetic result (UNFL for any value below the
/// normalized range, INEX2 only for digits lost), and SNAN for a signaling
/// NaN, which is stored quiet.
fn to_ieee_bits(
    x: FloatX80,
    frac_bits: u32,
    exp_bits: u32,
    mode: RoundMode,
    f: &mut ExcFlags,
) -> u64 {
    let sign = x.sign();
    let sign_bit = (sign as u64) << (frac_bits + exp_bits);
    let exp_max = (1u64 << exp_bits) - 1;
    let frac_mask = (1u64 << frac_bits) - 1;
    let quiet = 1u64 << (frac_bits - 1);

    if x.is_nan() {
        if x.is_signaling_nan() {
            f.raise(ExcFlags::SNAN);
        }
        let frac = ((x.mantissa << 1) >> (64 - frac_bits)) | quiet;
        return sign_bit | (exp_max << frac_bits) | frac;
    }
    if x.is_inf() {
        return sign_bit | (exp_max << frac_bits);
    }
    if x.mantissa == 0 {
        // Zero, or a pseudo-zero with a nonzero exponent.
        return sign_bit;
    }

    // Normalize, so unnormals (integer bit clear, exponent nonzero) round
    // like the value they hold.
    let u = unpack(x);
    let lz = u.mant.leading_zeros();
    let mant = u.mant << lz;
    let bias = (exp_max >> 1) as i32;
    let p = frac_bits + 1; // significand bits, integer bit included
    let mut e = u.exp - lz as i32 + bias;
    let (q, inexact) = if e >= 1 {
        let (mut q, inexact) = shift_round(mant, 64 - p, sign, mode);
        if q >> p != 0 {
            // Rounded up to the next power of two.
            q >>= 1;
            e += 1;
        }
        (q, inexact)
    } else {
        // Below the normal range: denormalize. A quotient that rounds up to
        // 2^(p-1) carries into the exponent field, giving the smallest
        // normal number, which is right.
        let (q, inexact) = shift_round(mant, (64 - p) + (1 - e) as u32, sign, mode);
        f.raise(ExcFlags::UNFL);
        e = 0;
        (q, inexact)
    };
    if inexact {
        f.raise(ExcFlags::INEX2);
    }

    if e as u64 >= exp_max {
        f.raise(ExcFlags::OVFL);
        let to_inf = match mode {
            RoundMode::Nearest => true,
            RoundMode::Zero => false,
            RoundMode::PosInf => !sign,
            RoundMode::NegInf => sign,
        };
        return if to_inf {
            sign_bit | (exp_max << frac_bits)
        } else {
            sign_bit | ((exp_max - 1) << frac_bits) | frac_mask
        };
    }
    if e == 0 {
        // Denormal, or the smallest normal after rounding up (see above).
        return sign_bit | q;
    }
    sign_bit | ((e as u64) << frac_bits) | (q & frac_mask)
}

/// Convert to binary64 bits, rounding by `mode` (FMOVE.D to memory).
pub fn to_f64_bits(x: FloatX80, mode: RoundMode, f: &mut ExcFlags) -> u64 {
    to_ieee_bits(x, 52, 11, mode, f)
}

/// Convert to binary32 bits, rounding by `mode` (FMOVE.S).
pub fn to_f32_bits(x: FloatX80, mode: RoundMode, f: &mut ExcFlags) -> u32 {
    to_ieee_bits(x, 23, 8, mode, f) as u32
}

// ============================== compare ==================================

/// Compare magnitudes of two finite/inf operands as (biased exp, mantissa).
fn cmp_mag(a: FloatX80, b: FloatX80) -> core::cmp::Ordering {
    (a.biased_exp(), a.mantissa).cmp(&(b.biased_exp(), b.mantissa))
}

pub fn compare(a: FloatX80, b: FloatX80, f: &mut ExcFlags) -> FpCmp {
    if a.is_nan() || b.is_nan() {
        // A signaling NaN raises SNAN (not OPERR), as for arithmetic.
        if a.is_signaling_nan() || b.is_signaling_nan() {
            f.raise(ExcFlags::SNAN);
        }
        return FpCmp::Unordered;
    }
    if a.is_zero() && b.is_zero() {
        return FpCmp::Equal; // +0 == -0
    }
    let asign = a.sign();
    let bsign = b.sign();
    if asign != bsign {
        return if asign { FpCmp::Less } else { FpCmp::Greater };
    }
    // Same sign: order by magnitude, then flip for negatives.
    let ord = cmp_mag(a, b);
    use core::cmp::Ordering::*;
    match (ord, asign) {
        (Equal, _) => FpCmp::Equal,
        (Greater, false) | (Less, true) => FpCmp::Greater,
        _ => FpCmp::Less,
    }
}

// ============================== round to int =============================

pub fn round_to_int(a: FloatX80, mode: RoundMode, f: &mut ExcFlags) -> FloatX80 {
    if a.is_nan() {
        return propagate_nan(a, a, f);
    }
    if a.is_inf() || a.is_zero() {
        return a;
    }
    let ua = unpack(a);
    if ua.exp >= 63 {
        return a; // no fractional bits in the 64-bit significand
    }
    let neg = ua.sign;
    if ua.exp < 0 {
        // |value| < 1: result is 0 or +/-1.
        let inc = match mode {
            // exp == -1 => value in [0.5, 1); >0.5 rounds to 1, 0.5 ties to even (0).
            RoundMode::Nearest => ua.exp == -1 && ua.mant > (1u64 << 63),
            RoundMode::Zero => false,
            RoundMode::PosInf => !neg,
            RoundMode::NegInf => neg,
        };
        f.raise(ExcFlags::INEX2);
        return if inc { one(neg) } else { FloatX80::zero(neg) };
    }
    let fbits = (63 - ua.exp) as u32; // 1..=63 fractional bits
    let int_part = ua.mant >> fbits;
    let frac = ua.mant & ((1u64 << fbits) - 1);
    if frac != 0 {
        f.raise(ExcFlags::INEX2);
    }
    let half = 1u64 << (fbits - 1);
    let inc = match mode {
        RoundMode::Nearest => frac > half || (frac == half && (int_part & 1) == 1),
        RoundMode::Zero => false,
        RoundMode::PosInf => !neg && frac != 0,
        RoundMode::NegInf => neg && frac != 0,
    };
    let int_part = int_part + u64::from(inc);
    if int_part == 0 {
        return FloatX80::zero(neg);
    }
    // The integer value is exact: build it with round-to-nearest (no rounding
    // happens since it fits in <= 64 bits).
    round_pack(
        neg,
        63,
        (int_part as u128) << 64,
        RoundCtx::NEAREST_EXT,
        &mut ExcFlags::default(),
    )
}

// ============================== misc unary ===============================

/// FSCALE: a * 2^n (n already extracted as a truncated integer).
pub fn scale(a: FloatX80, n: i32, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if a.is_nan() {
        return propagate_nan(a, a, f);
    }
    if a.is_inf() || a.is_zero() {
        return a;
    }
    let ua = unpack(a);
    // Far outside the range either way, which keeps the exponent in an i32.
    let n = n.clamp(-100_000, 100_000);
    round_pack(ua.sign, ua.exp + n, (ua.mant as u128) << 64, ctx, f)
}

/// FMOVE: `a` at the result precision. Rounding is all it does to a number,
/// but it does round, with the flags that go with that.
pub fn round_to_precision(a: FloatX80, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    if a.is_nan() {
        return propagate_nan(a, a, f);
    }
    if a.is_inf() || a.is_zero() {
        return a;
    }
    let ua = unpack(a);
    round_pack(ua.sign, ua.exp, (ua.mant as u128) << 64, ctx, f)
}

/// A finite nonzero `a` moved off its value by less than half a unit in
/// its last place, away from zero or toward it, and rounded: always
/// inexact, and an underflow where that is too small to be normalized.
pub fn round_inexact(a: FloatX80, away: bool, ctx: RoundCtx, f: &mut ExcFlags) -> FloatX80 {
    let ua = unpack(a);
    let m = (ua.mant as u128) << 64;
    round_pack(ua.sign, ua.exp, if away { m | 1 } else { m - 1 }, ctx, f)
}

/// FGETEXP: the unbiased exponent as an integer-valued extended number.
pub fn getexp(a: FloatX80, f: &mut ExcFlags) -> FloatX80 {
    if a.is_nan() {
        return propagate_nan(a, a, f);
    }
    if a.is_inf() {
        f.raise(ExcFlags::OPERR);
        return FloatX80::default_nan();
    }
    if a.is_zero() {
        return a;
    }
    let ua = unpack(a);
    let e = ua.exp as i64;
    let sign = e < 0;
    let mag = e.unsigned_abs();
    if mag == 0 {
        return FloatX80::zero(false);
    }
    round_pack(
        sign,
        63,
        (mag as u128) << 64,
        RoundCtx::NEAREST_EXT,
        &mut ExcFlags::default(),
    )
}

/// FGETMAN: the mantissa as a value in [1, 2) with the sign of `a`.
pub fn getman(a: FloatX80, f: &mut ExcFlags) -> FloatX80 {
    if a.is_nan() {
        return propagate_nan(a, a, f);
    }
    if a.is_inf() {
        f.raise(ExcFlags::OPERR);
        return FloatX80::default_nan();
    }
    if a.is_zero() {
        return a;
    }
    let ua = unpack(a);
    FloatX80 {
        sign_exp: ((ua.sign as u16) << 15) | (BIAS as u16),
        mantissa: ua.mant,
    }
}

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

    fn x(v: f64) -> FloatX80 {
        FloatX80::from_f64(v)
    }
    fn rn() -> RoundCtx {
        RoundCtx::NEAREST_EXT
    }

    /// For exactly-representable operands the extended result, narrowed to
    /// f64, must equal the f64 computation.
    #[test]
    fn arithmetic_matches_f64_for_exact_values() {
        let mut f = ExcFlags::default();
        let cases = [
            (3.0_f64, 4.0_f64),
            (1.5, 0.25),
            (-2.0, 8.0),
            (100.0, 0.0625),
            (-7.5, -0.5),
        ];
        for (a, b) in cases {
            assert_eq!(add(x(a), x(b), rn(), &mut f).to_f64(), a + b, "{a}+{b}");
            assert_eq!(sub(x(a), x(b), rn(), &mut f).to_f64(), a - b, "{a}-{b}");
            assert_eq!(mul(x(a), x(b), rn(), &mut f).to_f64(), a * b, "{a}*{b}");
            if b != 0.0 {
                assert_eq!(div(x(a), x(b), rn(), &mut f).to_f64(), a / b, "{a}/{b}");
            }
        }
    }

    /// A biased exponent of 0 is 2^-16383 on the MC68881 (no x87-style bump
    /// to 1), and it holds normal numbers with the integer bit set.
    #[test]
    fn biased_exponent_zero_is_two_to_minus_16383() {
        let mut f = ExcFlags::default();
        let fx = |sign_exp: u16, mantissa: u64| FloatX80 { sign_exp, mantissa };
        let m = fx(0, 0x8000_0000_0000_0000); // 2^-16383
        let e1 = fx(1, 0x8000_0000_0000_0000); // 2^-16382
        let tiny = fx(0, 1); // 2^-16446
        let one = x(1.0);
        assert_eq!(mul(m, one, rn(), &mut f), m);
        assert_eq!(mul(e1, x(0.5), rn(), &mut f), m);
        assert_eq!(add(m, m, rn(), &mut f), e1);
        assert_eq!(div(m, x(0.5), rn(), &mut f), e1);
        assert_eq!(mul(tiny, one, rn(), &mut f), tiny);
        assert_eq!(mul(tiny, x(2.0), rn(), &mut f), fx(0, 2));
        assert_eq!(sub(e1, tiny, rn(), &mut f), fx(0, 0xFFFF_FFFF_FFFF_FFFF));
    }

    /// Quotients below 1 and square roots have no guard bit in a 64-bit
    /// first step; both must still round to nearest, not truncate.
    #[test]
    fn the_unrounded_result_rides_along_with_the_flags() {
        // 1 / 3: mantissa 1010...10 and then 1, 0, 1, 0, ... below it.
        let mut f = ExcFlags::default();
        let third = div(x(1.0), x(3.0), rn(), &mut f);
        let u = f.unrounded().expect("a finite result was rounded");
        assert!(!u.sign);
        assert_eq!(u.exp, 0x3FFD);
        assert_eq!(u.truncated(), (0xAAAA_AAAA_AAAA_AAAA, 0b101));
        assert_eq!(u.rounded(), (0x3FFD, third.mantissa));

        // Out of range, the exponent is not confined: max * 2, and the
        // square of the smallest normalized number.
        let max = FloatX80::from_extended(0x7FFE, 0xFFFF_FFFF_FFFF_FFFF);
        let mut f = ExcFlags::default();
        mul(max, x(2.0), rn(), &mut f);
        assert!(f.has(ExcFlags::OVFL));
        assert_eq!(f.unrounded().unwrap().rounded(), (0x7FFF, u64::MAX));
        let tiny = FloatX80::from_extended(0x0001, 1 << 63);
        let mut f = ExcFlags::default();
        mul(tiny, tiny, rn(), &mut f);
        assert!(f.has(ExcFlags::UNFL));
        let u = f.unrounded().unwrap();
        assert_eq!((u.exp, u.truncated()), (2 - 0x3FFF, (1 << 63, 0)));

        // A carry out of the rounded mantissa moves to the next exponent.
        let single = RoundCtx {
            mode: RoundMode::Nearest,
            prec: Precision::Single,
        };
        let mut f = ExcFlags::default();
        round_to_precision(FloatX80::from_extended(0x3FFF, u64::MAX), single, &mut f);
        assert_eq!(f.unrounded().unwrap().rounded(), (0x4000, 1 << 63));

        // A result that needs no rounding step leaves none.
        let mut f = ExcFlags::default();
        add(FloatX80::infinity(false), x(1.0), rn(), &mut f);
        assert_eq!(f.unrounded(), None);
    }

    #[test]
    fn div_and_sqrt_round_to_nearest() {
        let mut f = ExcFlags::default();
        let fx = |sign_exp: u16, mantissa: u64| FloatX80 { sign_exp, mantissa };
        assert_eq!(
            div(x(1.0), x(3.0), rn(), &mut f),
            fx(0x3FFD, 0xAAAA_AAAA_AAAA_AAAB)
        );
        assert_eq!(
            div(x(2.0), x(3.0), rn(), &mut f),
            fx(0x3FFE, 0xAAAA_AAAA_AAAA_AAAB)
        );
        assert_eq!(
            sqrt(x(3.0), rn(), &mut f),
            fx(0x3FFF, 0xDDB3_D742_C265_539E)
        );
    }

    #[test]
    fn sqrt_exact_squares() {
        let mut f = ExcFlags::default();
        for v in [1.0_f64, 4.0, 9.0, 16.0, 100.0, 0.25, 2.5 * 2.5] {
            assert_eq!(sqrt(x(v), rn(), &mut f).to_f64(), v.sqrt(), "sqrt {v}");
        }
    }

    #[test]
    fn sqrt_two_is_more_precise_than_f64() {
        // sqrt(2) to 64-bit extended: 1.6A09E667F3BCC908 (integer bit + frac).
        let mut f = ExcFlags::default();
        let r = sqrt(x(2.0), rn(), &mut f);
        assert_eq!(r.biased_exp(), BIAS as u16); // exponent 0 -> [1,2)
        assert_eq!(r.mantissa, 0xB504_F333_F9DE_6484);
        assert!(f.has(ExcFlags::INEX2));
    }

    #[test]
    fn add_extended_precision_beyond_f64() {
        // 1.0 + 2^-60: f64 has only 52 fraction bits so it collapses to 1.0,
        // but extended's 63 fraction bits retain it.
        let mut f = ExcFlags::default();
        let tiny = FloatX80 {
            sign_exp: (BIAS - 60) as u16,
            mantissa: 0x8000_0000_0000_0000,
        };
        let r = add(one(false), tiny, rn(), &mut f);
        assert_ne!(r.mantissa, 0x8000_0000_0000_0000); // not just 1.0
        assert_eq!(r.to_f64(), 1.0); // but rounds back to 1.0 in f64
    }

    #[test]
    fn compare_inf_and_nan() {
        let mut f = ExcFlags::default();
        let inf = FloatX80::infinity(false);
        assert_eq!(compare(inf, inf, &mut f), FpCmp::Equal); // fixes Inf==Inf
        assert_eq!(
            compare(FloatX80::default_nan(), x(1.0), &mut f),
            FpCmp::Unordered
        );
        assert_eq!(compare(x(-0.0), x(0.0), &mut f), FpCmp::Equal);
        assert_eq!(compare(x(-1.0), x(1.0), &mut f), FpCmp::Less);
        assert_eq!(compare(x(2.0), x(1.0), &mut f), FpCmp::Greater);
        assert_eq!(compare(x(-2.0), x(-1.0), &mut f), FpCmp::Less);
    }

    #[test]
    fn div_by_zero_and_operr() {
        let mut f = ExcFlags::default();
        let r = div(x(1.0), x(0.0), rn(), &mut f);
        assert!(r.is_inf() && !r.sign());
        assert!(f.has(ExcFlags::DZ));

        let mut f = ExcFlags::default();
        let r = div(x(0.0), x(0.0), rn(), &mut f);
        assert!(r.is_nan());
        assert!(f.has(ExcFlags::OPERR));

        let mut f = ExcFlags::default();
        let r = add(
            FloatX80::infinity(false),
            FloatX80::infinity(true),
            rn(),
            &mut f,
        );
        assert!(r.is_nan());
        assert!(f.has(ExcFlags::OPERR));
    }

    #[test]
    fn round_to_int_modes() {
        let mut f = ExcFlags::default();
        assert_eq!(round_to_int(x(1.5), RoundMode::Zero, &mut f).to_f64(), 1.0);
        assert_eq!(
            round_to_int(x(1.5), RoundMode::NegInf, &mut f).to_f64(),
            1.0
        );
        assert_eq!(
            round_to_int(x(1.5), RoundMode::PosInf, &mut f).to_f64(),
            2.0
        );
        assert_eq!(
            round_to_int(x(1.5), RoundMode::Nearest, &mut f).to_f64(),
            2.0
        );
        assert_eq!(
            round_to_int(x(2.5), RoundMode::Nearest, &mut f).to_f64(),
            2.0
        ); // ties to even
        assert_eq!(
            round_to_int(x(-1.5), RoundMode::Zero, &mut f).to_f64(),
            -1.0
        );
        assert_eq!(
            round_to_int(x(0.4), RoundMode::Nearest, &mut f).to_f64(),
            0.0
        );
        assert_eq!(
            round_to_int(x(0.5), RoundMode::Nearest, &mut f).to_f64(),
            0.0
        ); // ties to even
        assert_eq!(
            round_to_int(x(0.6), RoundMode::Nearest, &mut f).to_f64(),
            1.0
        );
    }

    #[test]
    fn zeros_of_one_sign_keep_it_when_rounding_down() {
        let mut f = ExcFlags::default();
        let down = RoundCtx {
            prec: Precision::Extended,
            mode: RoundMode::NegInf,
        };
        let p = FloatX80::zero(false);
        let m = FloatX80::zero(true);
        assert!(!add(p, p, down, &mut f).sign());
        assert!(add(m, m, down, &mut f).sign());
        assert!(add(p, m, down, &mut f).sign());
        assert!(!add(p, m, RoundCtx::NEAREST_EXT, &mut f).sign());
    }

    #[test]
    fn rounding_to_zero_underflows() {
        let mut f = ExcFlags::default();
        let r = scale(x(1.0), -20000, RoundCtx::NEAREST_EXT, &mut f);
        assert!(r.is_zero());
        assert!(f.0 & ExcFlags::UNFL != 0 && f.0 & ExcFlags::INEX2 != 0);
    }

    #[test]
    fn a_result_below_the_normalized_range_underflows_even_when_exact() {
        // 2^-16390 is a denormalized number, held exactly.
        let mut f = ExcFlags::default();
        let r = scale(x(1.0), -16390, rn(), &mut f);
        assert_eq!((r.sign_exp, r.mantissa), (0, 0x0100_0000_0000_0000));
        assert_eq!(f.0, ExcFlags::UNFL);
        // So is the product of two normalized numbers, and a denormalized
        // number that is only moved.
        let mut f = ExcFlags::default();
        let half = scale(x(1.0), -8195, rn(), &mut ExcFlags::default());
        assert_eq!(mul(half, half, rn(), &mut f), r);
        assert_eq!(f.0, ExcFlags::UNFL);
        let mut f = ExcFlags::default();
        assert_eq!(round_to_precision(r, rn(), &mut f), r);
        assert_eq!(f.0, ExcFlags::UNFL);
        // Losing bits on the way makes it inexact as well.
        let mut f = ExcFlags::default();
        let third = div(x(1.0), x(3.0), rn(), &mut ExcFlags::default());
        scale(third, -16390, rn(), &mut f);
        assert_eq!(f.0, ExcFlags::UNFL | ExcFlags::INEX2);
        // A zero exponent field with the integer bit set is a normalized
        // number: 2^-16383 does not underflow.
        let mut f = ExcFlags::default();
        let r = scale(x(1.0), -16383, rn(), &mut f);
        assert_eq!((r.sign_exp, r.mantissa), (0, 0x8000_0000_0000_0000));
        assert_eq!(f.0, 0);
        // One that rounds up to it was still too small before rounding.
        let mut f = ExcFlags::default();
        let below = FloatX80 {
            sign_exp: 0x3FFE,
            mantissa: 0xFFFF_FFFF_FFFF_FFFF,
        };
        let r = scale(below, -16383, rn(), &mut f);
        assert_eq!((r.sign_exp, r.mantissa), (0, 0x8000_0000_0000_0000));
        assert_eq!(f.0, ExcFlags::UNFL | ExcFlags::INEX2);
    }

    #[test]
    fn an_overflow_is_inexact_only_when_its_mantissa_was_rounded() {
        let max = FloatX80 {
            sign_exp: 0x7FFE,
            mantissa: 0xFFFF_FFFF_FFFF_FFFF,
        };
        // 2^16384, and twice the largest number: nothing to round.
        let mut f = ExcFlags::default();
        assert!(scale(x(1.0), 16384, rn(), &mut f).is_inf());
        assert_eq!(f.0, ExcFlags::OVFL);
        let mut f = ExcFlags::default();
        assert!(add(max, max, rn(), &mut f).is_inf());
        assert_eq!(f.0, ExcFlags::OVFL);
        // Its square has 128 mantissa bits.
        let mut f = ExcFlags::default();
        assert!(mul(max, max, rn(), &mut f).is_inf());
        assert_eq!(f.0, ExcFlags::OVFL | ExcFlags::INEX2);
        // The same for a move to single or double.
        let mut f = ExcFlags::default();
        let big = scale(x(1.0), 2000, rn(), &mut ExcFlags::default());
        assert_eq!(to_f32_bits(big, RoundMode::Nearest, &mut f), 0x7F80_0000);
        assert_eq!(f.0, ExcFlags::OVFL);
        let mut f = ExcFlags::default();
        to_f64_bits(max, RoundMode::Nearest, &mut f);
        assert_eq!(f.0, ExcFlags::OVFL | ExcFlags::INEX2);
    }

    #[test]
    fn moves_round_to_the_precision() {
        let double = RoundCtx {
            prec: Precision::Double,
            mode: RoundMode::Nearest,
        };
        let third = div(
            x(1.0),
            x(3.0),
            RoundCtx::NEAREST_EXT,
            &mut ExcFlags::default(),
        );
        let mut f = ExcFlags::default();
        let r = round_to_precision(third, double, &mut f);
        assert_eq!(r.to_f64(), 1.0 / 3.0);
        assert_eq!(r.mantissa & 0x7FF, 0);
        assert!(f.0 & ExcFlags::INEX2 != 0);
        let mut f = ExcFlags::default();
        assert_eq!(
            round_to_precision(third, RoundCtx::NEAREST_EXT, &mut f),
            third
        );
        assert_eq!(f.0, 0);
    }

    #[test]
    fn scale_getexp_getman() {
        let mut f = ExcFlags::default();
        assert_eq!(scale(x(3.0), 4, rn(), &mut f).to_f64(), 48.0);
        assert_eq!(scale(x(3.0), -1, rn(), &mut f).to_f64(), 1.5);
        assert_eq!(getexp(x(8.0), &mut f).to_f64(), 3.0);
        assert_eq!(getexp(x(0.5), &mut f).to_f64(), -1.0);
        assert_eq!(getman(x(6.0), &mut f).to_f64(), 1.5);
        assert_eq!(getman(x(-6.0), &mut f).to_f64(), -1.5);
    }

    #[test]
    fn const_rom_values() {
        // pi is the exact 80-bit ROM pattern.
        let pi = const_rom(0x00);
        assert_eq!(pi.sign_exp, 0x4000);
        assert_eq!(pi.mantissa, 0xC90F_DAA2_2168_C235);
        // 0x0D is log2(e) (~1.4427), not ln(2) as the old f64 table had it.
        assert!((const_rom(0x0D).to_f64() - std::f64::consts::LOG2_E).abs() < 1e-15);
        // Powers of ten.
        assert_eq!(const_rom(0x32).to_f64(), 1.0);
        assert_eq!(const_rom(0x34).to_f64(), 100.0);
        // 10^512 is finite in extended (an f64 ROM returned infinity here).
        assert!(const_rom(0x3C).to_f64().is_infinite()); // 10^512 > f64 max, finite in x80
        assert!(!const_rom(0x3C).is_inf()); // ... but the extended value is finite
    }

    #[test]
    fn rounding_mode_directions() {
        // 1/3 is inexact; check the rounded extended significand differs by mode.
        let mut f = ExcFlags::default();
        let down = div(
            x(1.0),
            x(3.0),
            RoundCtx {
                mode: RoundMode::Zero,
                prec: Precision::Extended,
            },
            &mut f,
        );
        let up = div(
            x(1.0),
            x(3.0),
            RoundCtx {
                mode: RoundMode::PosInf,
                prec: Precision::Extended,
            },
            &mut f,
        );
        assert!(f.has(ExcFlags::INEX2));
        assert_eq!(up.mantissa, down.mantissa + 1);
    }

    /// FMOVE.D rounds the extended value once, by the FPCR mode: 1/10 is
    /// 0x3fb999999999999a to nearest, ...9999 toward zero.
    #[test]
    fn to_f64_rounds_by_mode() {
        let tenth = div(x(1.0), x(10.0), rn(), &mut ExcFlags::default());
        assert_eq!(tenth.mantissa, 0xCCCC_CCCC_CCCC_CCCD);
        let cases = [
            (RoundMode::Nearest, 0x3FB9_9999_9999_999A_u64),
            (RoundMode::Zero, 0x3FB9_9999_9999_9999),
            (RoundMode::PosInf, 0x3FB9_9999_9999_999A),
            (RoundMode::NegInf, 0x3FB9_9999_9999_9999),
        ];
        for (mode, want) in cases {
            let mut f = ExcFlags::default();
            assert_eq!(to_f64_bits(tenth, mode, &mut f), want, "{mode:?}");
            assert!(f.has(ExcFlags::INEX2));
            assert!(!f.has(ExcFlags::UNFL | ExcFlags::OVFL));
            let mut f = ExcFlags::default();
            assert_eq!(
                to_f64_bits(neg(tenth), mode, &mut f) & !(1 << 63),
                match mode {
                    RoundMode::PosInf => 0x3FB9_9999_9999_9999,
                    RoundMode::NegInf => 0x3FB9_9999_9999_999A,
                    _ => want,
                }
            );
        }
    }

    /// Pseudo-random f64 bit patterns: every class from denormals to
    /// infinity, both signs.
    fn sample_f64s() -> impl Iterator<Item = f64> {
        let mut s = 0x2545_F491_4F6C_DD1D_u64;
        (0..20000).map(move |_| {
            s ^= s << 13;
            s ^= s >> 7;
            s ^= s << 17;
            f64::from_bits(s)
        })
    }

    /// Every f64 survives FMOVE.D exactly. A denormal one underflows,
    /// without being inexact; nothing else raises anything.
    #[test]
    fn to_f64_is_exact_for_f64_values() {
        for v in sample_f64s().filter(|v| !v.is_nan()) {
            let mut f = ExcFlags::default();
            assert_eq!(
                to_f64_bits(x(v), RoundMode::Nearest, &mut f),
                v.to_bits(),
                "{v:e}"
            );
            let want = if v.is_subnormal() { ExcFlags::UNFL } else { 0 };
            assert_eq!(f.0, want, "{v:e}");
        }
    }

    /// FMOVE.S of an f64 value rounds like Rust's `as f32` (to nearest,
    /// ties to even, with f32 denormals and overflow to infinity).
    #[test]
    fn to_f32_matches_rust_rounding() {
        for v in sample_f64s().filter(|v| !v.is_nan()) {
            let want = v as f32;
            let mut f = ExcFlags::default();
            assert_eq!(
                to_f32_bits(x(v), RoundMode::Nearest, &mut f),
                want.to_bits(),
                "{v:e}"
            );
            assert_eq!(
                f.has(ExcFlags::INEX2),
                want as f64 != v && v.is_finite(),
                "{v:e}"
            );
            assert_eq!(
                f.has(ExcFlags::OVFL),
                want.is_infinite() && v.is_finite(),
                "{v:e}"
            );
        }
    }

    #[test]
    fn to_f64_underflow_and_overflow() {
        // 0.75 * 2^-1022 is an exact f64 denormal.
        let mut f = ExcFlags::default();
        let d = mul(x(f64::MIN_POSITIVE), x(0.75), rn(), &mut f);
        let mut f = ExcFlags::default();
        assert_eq!(
            to_f64_bits(d, RoundMode::Nearest, &mut f),
            0x000C_0000_0000_0000
        );
        // Below the normalized range, so an underflow, but exact.
        assert_eq!(f.0, ExcFlags::UNFL);
        // The smallest normalized double is not one.
        let mut f = ExcFlags::default();
        to_f64_bits(x(f64::MIN_POSITIVE), RoundMode::Nearest, &mut f);
        assert_eq!(f.0, 0);

        // 1e-600 is far below the f64 range: zero, or the smallest
        // denormal when rounding up.
        let tiny = mul(x(1e-300), x(1e-300), rn(), &mut ExcFlags::default());
        let mut f = ExcFlags::default();
        assert_eq!(to_f64_bits(tiny, RoundMode::Nearest, &mut f), 0);
        assert!(f.has(ExcFlags::UNFL) && f.has(ExcFlags::INEX2));
        assert_eq!(to_f64_bits(tiny, RoundMode::PosInf, &mut f), 1);

        // 1e600 overflows to infinity, or to the largest finite value.
        let huge = mul(x(1e300), x(1e300), rn(), &mut ExcFlags::default());
        let mut f = ExcFlags::default();
        assert_eq!(
            to_f64_bits(huge, RoundMode::Nearest, &mut f),
            f64::INFINITY.to_bits()
        );
        assert!(f.has(ExcFlags::OVFL) && f.has(ExcFlags::INEX2));
        assert_eq!(
            to_f64_bits(huge, RoundMode::Zero, &mut f),
            f64::MAX.to_bits()
        );
        assert_eq!(
            to_f64_bits(neg(huge), RoundMode::PosInf, &mut f),
            (-f64::MAX).to_bits()
        );

        // The largest f64 plus half an ulp rounds up into infinity.
        let edge = FloatX80 {
            sign_exp: 0x43FE,
            mantissa: 0xFFFF_FFFF_FFFF_FC00,
        };
        let mut f = ExcFlags::default();
        assert_eq!(
            to_f64_bits(edge, RoundMode::Nearest, &mut f),
            f64::INFINITY.to_bits()
        );
        assert!(f.has(ExcFlags::OVFL));
    }

    #[test]
    fn to_f64_nans() {
        // A signaling NaN is stored quiet, keeping its payload, and raises SNAN.
        let snan = FloatX80 {
            sign_exp: 0xFFFF,
            mantissa: 0x8000_0000_0000_0800,
        };
        let mut f = ExcFlags::default();
        assert_eq!(
            to_f64_bits(snan, RoundMode::Nearest, &mut f),
            0xFFF8_0000_0000_0001
        );
        assert!(f.has(ExcFlags::SNAN));
        let mut f = ExcFlags::default();
        let qnan = FloatX80 {
            sign_exp: 0x7FFF,
            mantissa: 0xC000_0000_0000_0000,
        };
        assert_eq!(to_f32_bits(qnan, RoundMode::Nearest, &mut f), 0x7FC0_0000);
        assert_eq!(f, ExcFlags::default());
    }
}