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
//! FPU operations (68040/68881-class).
//!
//! Note: This is currently a **minimal bring-up** focused on plumbing + a few
//! OS-critical operations. Expect expansion over time.
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;
/// Where a resolved FPU operand lives.
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,
}
/// Round an f64 to an integer using the FPCR rounding mode and saturate
/// into the destination integer width, as the 6888x does for FMOVE to an
/// integer format (out-of-range and NaN produce the most negative value
/// and would set OPERR, which the emulated FPU does not raise).
fn f64_to_int_saturating(value: f64, fpcr: u32, min: i64, max: i64) -> i64 {
if value.is_nan() {
return min;
}
// FPCR rounding mode, bits 4-5: 0=nearest, 1=zero, 2=minus, 3=plus.
let rounded = match (fpcr >> 4) & 3 {
1 => value.trunc(),
2 => value.floor(),
3 => value.ceil(),
_ => {
// Round to nearest, ties to even.
let r = value.round();
if (value - value.trunc()).abs() == 0.5 && r % 2.0 != 0.0 {
r - value.signum()
} else {
r
}
}
};
if rounded < min as f64 {
min
} else if rounded > max as f64 {
max
} else {
rounded as i64
}
}
/// The FP opmodes the 68060 dropped from silicon, emulated by the 68060SP:
/// the transcendental set, FINT/FINTRZ, FGETEXP/FGETMAN, FMOD/FREM/FSCALE,
/// and FSINCOS (FMOVECR is gated separately by encoding). FSGLMUL/FSGLDIV
/// and every rounded (FS/FD-prefixed) variant remain in hardware. Keep in
/// sync with fpu_apply_op's table.
fn fpu_060_traps_opmode(opmode: u16) -> bool {
matches!(
opmode,
0x01 | 0x02
| 0x03
| 0x06
| 0x08
| 0x09
| 0x0A
| 0x0C
| 0x0D
| 0x0E
| 0x0F
| 0x10
| 0x11
| 0x12
| 0x14
| 0x15
| 0x16
| 0x19
| 0x1C
| 0x1D
| 0x1E
| 0x1F
| 0x21
| 0x25
| 0x26
| 0x30..=0x37
)
}
/// 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
}
}
/// 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
}
impl CpuCore {
/// 68040 FPU "op0" entrypoint (opcode pattern 0xF2xx in Musashi: `040fpu0`).
///
/// Handles the implemented 6888x/68040 ALU, FMOVE, control, and condition-code subset.
/// Unsupported encodings return 0 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;
}
// 68060 with the FPU disabled through PCR.DFP (also how an LC/EC060
// presents): every FP instruction takes the format $4 disabled frame.
if self.is_060() && (self.pcr & crate::core::cpu::PCR_DFP) != 0 {
return self.take_fp_disabled_060(bus);
}
// 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;
// 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;
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;
// 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);
}
// FMOVECR - load constant from ROM. The opmode field is
// the ROM index; there is no <ea> source operand.
self.fpr[dst] = softfloat::const_rom(opmode as usize);
self.fpu_set_cc(self.fpr[dst]);
return 4;
}
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 is an unimplemented <ea> instead.
let vector = if (opcode & 0x3F) == 0x3C {
crate::core::exceptions::vector::FP_UNIMPLEMENTED_EA
} else {
crate::core::exceptions::vector::FP_UNSUPP_DATA_TYPE
};
return self.take_exception(bus, vector);
}
let Some(src) = self.fpu_read_source(bus, opcode, src_fmt) else {
return 0;
};
self.fpu_apply_op(opmode, dst, src)
}
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).
if self.trap_unimpl_060() && (dst_fmt == 3 || dst_fmt == 7) {
return self
.take_exception(bus, crate::core::exceptions::vector::FP_UNSUPP_DATA_TYPE);
}
// 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;
if self.fpu_write_dest(bus, ea_mode, ea_reg, dst_fmt, kfactor, self.fpr[src]) {
4
} else {
0
}
}
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;
// 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);
}
// FMOVECR - load constant from ROM. In this register-form
// encoding the source-register field carries the ROM index.
self.fpr[dst] = softfloat::const_rom(src);
self.fpu_set_cc(self.fpr[dst]);
return 4;
}
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);
}
self.fpu_apply_op(opmode, dst, self.fpr[src])
}
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;
// A dynamic register list was dropped from 68060 silicon
// (unimplemented <ea>).
if self.trap_unimpl_060() && (mode_bits & 0x1) != 0 {
return self
.take_exception(bus, crate::core::exceptions::vector::FP_UNIMPLEMENTED_EA);
}
// 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;
// FMOVEM.L #imm to two or three control registers was
// dropped from 68060 silicon (unimplemented <ea>).
if self.trap_unimpl_060() && count >= 2 && (opcode & 0x3F) == 0x3C {
return self
.take_exception(bus, crate::core::exceptions::vector::FP_UNIMPLEMENTED_EA);
}
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();
if ctrl_sel & 0x4 != 0 {
self.fpcr = *next.next().unwrap();
}
if ctrl_sel & 0x2 != 0 {
self.fpsr = *next.next().unwrap();
}
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,
}
}
/// 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 {
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 !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 self.fpu_condition(condition) {
// FTRAPcc takes the TRAPcc/TRAPV exception vector (7).
return self.take_group2_exception(bus, 7);
}
4
}
/// 68040 FPU "op1" entrypoint (opcode pattern 0xF3xx in Musashi: `040fpu1`).
///
/// Implements a minimal subset: `FSAVE <ea>` and `FRESTORE <ea>` for a NULL/IDLE frame.
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).
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);
}
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. A NULL frame is a single long word - the same
/// one-long NULL every part since the 68881 has used, and the size
/// AmigaOS's hand-built task contexts rely on - while IDLE occupies
/// the full three long words. The EXCP frame ($E0, carrying pending-
/// exception operands) is not modeled: the softfloat FPU completes
/// every operation before retiring.
fn exec_fsave_060<B: AddressBus>(&mut self, bus: &mut B, ea_mode: u8, ea_reg: usize) -> i32 {
let (header, size): (u32, u32) = if self.fpu_just_reset {
(0x0000_0000, 4)
} else {
(0x0000_6000, 12)
};
match ea_mode {
2 | 3 => {
// (An) / (An)+
let addr = self.a(ea_reg);
if ea_mode == 3 {
self.set_a(ea_reg, addr.wrapping_add(size));
}
self.write_32(bus, addr, header);
for off in (4..size).step_by(4) {
self.write_32(bus, addr.wrapping_add(off), 0);
}
8
}
4 => {
// -(An)
let addr = self.a(ea_reg).wrapping_sub(size);
self.set_a(ea_reg, addr);
self.write_32(bus, addr, header);
for off in (4..size).step_by(4) {
self.write_32(bus, addr.wrapping_add(off), 0);
}
8
}
// 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) => {
self.write_32(bus, addr, header);
for off in (4..size).step_by(4) {
self.write_32(bus, addr.wrapping_add(off), 0);
}
8
}
None => 0,
},
}
}
/// 68060 FRESTORE: size the frame from the format byte - one long word
/// for NULL (resetting the FPU), three for anything else. Kickstart's
/// exec builds initial task contexts by hand with a one-long NULL frame
/// and launches them through FRESTORE (An)+, so a fixed 12-byte read
/// would skew the context walk and launch the first task at PC 0.
fn exec_frestore_060<B: AddressBus>(&mut self, bus: &mut B, ea_mode: u8, ea_reg: usize) -> i32 {
match ea_mode {
2 | 3 => {
let addr = self.a(ea_reg);
let header = self.read_32(bus, addr);
let null_frame = (header & 0x0000_FF00) == 0;
if ea_mode == 3 {
let size = if null_frame { 4 } else { 12 };
self.set_a(ea_reg, addr.wrapping_add(size));
}
if null_frame {
self.do_frestore_null();
} else {
self.fpu_just_reset = false;
}
8
}
// Remaining control modes, plus PC-relative (the frame is a
// source operand): read the header at the resolved address,
// no register update.
_ => match self.fpu_frame_control_ea(bus, ea_mode, ea_reg, true) {
Some(addr) => {
let header = self.read_32(bus, addr);
if (header & 0x0000_FF00) == 0 {
self.do_frestore_null();
} else {
self.fpu_just_reset = false;
}
8
}
None => 0,
},
}
}
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);
}
match ea_mode {
2 => {
// (An)
let addr = self.a(ea_reg);
let header = self.read_32(bus, addr);
if (header & 0xFF00_0000) == 0 {
self.do_frestore_null();
} else {
self.fpu_just_reset = false;
}
8
}
3 => {
// (An)+
let addr = self.a(ea_reg);
self.set_a(ea_reg, addr.wrapping_add(4));
let header = self.read_32(bus, addr);
if (header & 0xFF00_0000) == 0 {
self.do_frestore_null();
} else {
self.fpu_just_reset = false;
// The frame's size byte counts the state bytes after the
// header long ($18 6888x idle, $38 unimp, $B4 busy, $28
// 68040 idle, $60 68040 busy); the postincrement covers
// header plus state. (EA macro already did +4.)
let extra = (header >> 16) & 0x00FF;
self.set_a(ea_reg, self.a(ea_reg).wrapping_add(extra));
}
8
}
// Remaining control modes, plus PC-relative (the frame is a
// source operand): read the header at the resolved address,
// 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) => {
let header = self.read_32(bus, addr);
if (header & 0xFF00_0000) == 0 {
self.do_frestore_null();
} else {
self.fpu_just_reset = false;
}
8
}
None => 0,
},
}
}
fn do_frestore_null(&mut self) {
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 a 6888x conditional predicate against FPSR. The upper
/// half of the condition space (bit 5 (actually bit 4 of the 5-bit
/// field)) only differs by signalling BSUN on NaN, which the emulated
/// FPU does not raise, so it folds onto the lower half.
fn fpu_condition(&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;
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.
///
/// Phase 0: arithmetic is still computed via an f64 bridge
/// (`src.to_f64()` ... `FloatX80::from_f64(result)`) so results match the
/// previous core exactly while the register file is the extended type;
/// Phase 1 swaps each arm onto the softfloat engine. The 6888x
/// single/double rounding-precision variants (FSxxx/FDxxx) still fold
/// onto their base op here.
fn fpu_apply_op(&mut self, opmode: u16, dst: usize, src: FloatX80) -> i32 {
match opmode {
0x00 | 0x40 | 0x44 => {
// FMOVE / FSMOVE / FDMOVE (lossless copy)
self.fpr[dst] = src;
self.fpu_set_cc(src);
4
}
0x01 => {
// FINT - round to integer using the FPCR rounding mode
let mode = RoundMode::from_fpcr(self.fpcr);
let mut f = ExcFlags::default();
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 = ExcFlags::default();
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 = ExcFlags::default();
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
self.fpr[dst] = softfloat::abs(src);
self.fpu_set_cc(self.fpr[dst]);
4
}
0x1A | 0x5A | 0x5E => {
// FNEG / FSNEG / FDNEG
self.fpr[dst] = softfloat::neg(src);
self.fpu_set_cc(self.fpr[dst]);
4
}
0x20 | 0x60 | 0x64 => {
// FDIV / FSDIV / FDDIV - dst = dst / src
let ctx = self.fpu_ctx(opmode);
let mut f = ExcFlags::default();
self.fpr[dst] = softfloat::div(self.fpr[dst], src, ctx, &mut f);
self.fpu_set_cc(self.fpr[dst]);
self.fpu_commit(f);
4
}
0x22 | 0x62 | 0x66 => {
// FADD / FSADD / FDADD
let ctx = self.fpu_ctx(opmode);
let mut f = ExcFlags::default();
self.fpr[dst] = softfloat::add(self.fpr[dst], src, ctx, &mut f);
self.fpu_set_cc(self.fpr[dst]);
self.fpu_commit(f);
4
}
0x23 | 0x63 | 0x67 => {
// FMUL / FSMUL / FDMUL
let ctx = self.fpu_ctx(opmode);
let mut f = ExcFlags::default();
self.fpr[dst] = softfloat::mul(self.fpr[dst], 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 = ExcFlags::default();
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 = ExcFlags::default();
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
}
0x28 | 0x68 | 0x6C => {
// FSUB / FSSUB / FDSUB
let ctx = self.fpu_ctx(opmode);
let mut f = ExcFlags::default();
self.fpr[dst] = softfloat::sub(self.fpr[dst], src, 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 = ExcFlags::default();
let cmp = softfloat::compare(self.fpr[dst], src, &mut f);
self.fpu_set_cc_cmp(cmp);
self.fpu_commit(f);
4
}
0x3A => {
// FTST - test src, set condition codes only (no dst write)
self.fpu_set_cc(src);
4
}
0x1E => {
// FGETEXP - extract the unbiased exponent
let mut f = ExcFlags::default();
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 = ExcFlags::default();
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 = ExcFlags::default();
let rem = transcendental::remainder(self.fpr[dst], src, false, &mut f);
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 = ExcFlags::default();
let rem = transcendental::remainder(self.fpr[dst], src, true, &mut f);
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 = ExcFlags::default();
let n = softfloat::to_i64(
src,
RoundMode::Zero,
i32::MIN as i64,
i32::MAX as i64,
&mut f,
) 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 = ExcFlags::default();
let cos_dst = (opmode & 7) as usize;
let (sin, cos) = transcendental::sincos(src, ctx, &mut f);
self.fpr[dst] = sin;
self.fpr[cos_dst] = cos;
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 = ExcFlags::default();
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 as
/// unimplemented on the 68060: extension words are consumed (the trap
/// frame carries the next-instruction PC) and post-increment /
/// pre-decrement commit, matching the calculated-EA semantics of the
/// format $2 frame. Returns the EA long for the frame (0 when the
/// operand is not in memory).
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
};
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,
}
}
/// 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. The
/// extended format (2) is read losslessly; the others go through an f64
/// bridge for now (Phase 1 replaces these with exact widening). Packed
/// decimal (3) is unimplemented and reports as unhandled (F-line).
fn fpu_read_source<B: AddressBus>(
&mut self,
bus: &mut B,
opcode: u16,
fmt: u16,
) -> Option<FloatX80> {
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,
};
match self.fpu_ea(bus, ea_mode, ea_reg, bytes)? {
FpuEa::DataReg(r) => {
let v = self.d(r);
match fmt {
0 => Some(FloatX80::from_f64(v as i32 as f64)),
1 => Some(FloatX80::from_f64(f32::from_bits(v) as f64)),
4 => Some(FloatX80::from_f64(v as u16 as i16 as f64)),
6 => Some(FloatX80::from_f64(v as u8 as i8 as f64)),
_ => None, // 8/12-byte operands cannot live in Dn
}
}
FpuEa::Immediate => match fmt {
0 => Some(FloatX80::from_f64(self.read_imm_32(bus) as i32 as f64)),
1 => Some(FloatX80::from_f64(
f32::from_bits(self.read_imm_32(bus)) as f64
)),
4 => Some(FloatX80::from_f64(self.read_imm_16(bus) as i16 as f64)),
6 => Some(FloatX80::from_f64(
(self.read_imm_16(bus) & 0xFF) as u8 as i8 as f64,
)),
5 => {
let hi = self.read_imm_32(bus) as u64;
let lo = self.read_imm_32(bus) as u64;
Some(FloatX80::from_f64(f64::from_bits((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;
Some(FloatX80::from_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);
Some(packed::from_packed(
words_to_bytes(w0, w1, w2),
&mut ExcFlags::default(),
))
}
_ => None,
},
FpuEa::Memory(addr) => match fmt {
0 => Some(FloatX80::from_f64(self.read_32(bus, addr) as i32 as f64)),
1 => Some(FloatX80::from_f64(
f32::from_bits(self.read_32(bus, addr)) as f64
)),
4 => Some(FloatX80::from_f64(self.read_16(bus, addr) as i16 as f64)),
6 => Some(FloatX80::from_f64(self.read_8(bus, addr) as i8 as f64)),
5 => {
let hi = self.read_32(bus, addr) as u64;
let lo = self.read_32(bus, addr.wrapping_add(4)) as u64;
Some(FloatX80::from_f64(f64::from_bits((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;
Some(FloatX80::from_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));
Some(packed::from_packed(
words_to_bytes(w0, w1, w2),
&mut ExcFlags::default(),
))
}
_ => None,
},
}
}
/// Write `value` to the FMOVE destination in `fmt`. Integer formats
/// round per FPCR and saturate; packed decimal (3 and 7) is
/// unimplemented and reports as unhandled (F-line). Returns false if
/// the format/EA combination cannot be carried out.
fn fpu_write_dest<B: AddressBus>(
&mut self,
bus: &mut B,
ea_mode: u8,
ea_reg: usize,
fmt: u16,
kfactor: i8,
value: FloatX80,
) -> bool {
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 false,
};
let Some(ea) = self.fpu_ea(bus, ea_mode, ea_reg, bytes) else {
return false;
};
// Bridge: integer/single/double formats round through f64 for now;
// the extended format is written losslessly. Phase 1 replaces the
// bridge with exact softfloat conversions.
let fv = value.to_f64();
match ea {
FpuEa::DataReg(r) => match fmt {
0 => {
let v = f64_to_int_saturating(fv, self.fpcr, i32::MIN as i64, i32::MAX as i64);
self.set_d(r, v as u32);
true
}
1 => {
self.set_d(r, (fv as f32).to_bits());
true
}
4 => {
let v = f64_to_int_saturating(fv, self.fpcr, i16::MIN as i64, i16::MAX as i64);
self.set_d(r, (self.d(r) & 0xFFFF_0000) | (v as u16 as u32));
true
}
6 => {
let v = f64_to_int_saturating(fv, self.fpcr, i8::MIN as i64, i8::MAX as i64);
self.set_d(r, (self.d(r) & 0xFFFF_FF00) | (v as u8 as u32));
true
}
_ => false,
},
FpuEa::Memory(addr) => match fmt {
0 => {
let v = f64_to_int_saturating(fv, self.fpcr, i32::MIN as i64, i32::MAX as i64);
self.write_32(bus, addr, v as u32);
true
}
1 => {
self.write_32(bus, addr, (fv as f32).to_bits());
true
}
4 => {
let v = f64_to_int_saturating(fv, self.fpcr, i16::MIN as i64, i16::MAX as i64);
self.write_16(bus, addr, v as u16);
true
}
6 => {
let v = f64_to_int_saturating(fv, self.fpcr, i8::MIN as i64, i8::MAX as i64);
self.write_8(bus, addr, v as u8);
true
}
5 => {
let bits = fv.to_bits();
self.write_32(bus, addr, (bits >> 32) as u32);
self.write_32(bus, addr.wrapping_add(4), bits as u32);
true
}
2 => {
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).
let bytes = packed::to_packed(value, kfactor, &mut ExcFlags::default());
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,
}
}
}
/// The FSAVE IDLE frame is CPU-specific: the 68040's on-chip FPU saves a
/// version-$41 frame with size byte $28 ($2C bytes in total), while the
/// 68881 co-processor of 020/030 systems saves the $18-byte IDLE frame.
/// 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, and kills the process with SIGSEGV on any other
/// value -- a 68881 frame from a 68040 FSAVE turns every signal-handler
/// return into a fault.
fn fsave_idle_frame(cpu: &CpuCore) -> (u32, u32, u32) {
if cpu.is_040() {
(0x4128_0000, 11, 0) // header, total longs, last long
} else {
(0x1F18_0000, 7, 0x7000_0000)
}
}
/// 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
}
fn perform_fsave<B: AddressBus>(bus: &mut B, cpu: &mut CpuCore, addr: u32, inc: bool) {
let (header, longs, last) = fsave_idle_frame(cpu);
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);
}
}