m68k 0.8.1

A safe Rust M68000 family CPU emulator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
//! MC68020 integer instruction timing.
//!
//! The MC68020 User's Manual section 8.2 publishes three timing columns:
//! best case (instruction overlap), cache case (cached instruction stream
//! without overlap), and worst case (uncached stream without overlap).
//! The core does not model the 020 execution-stage overlap, so an
//! instruction selects Cache Case only when all of its opcode, extension,
//! and immediate words hit the instruction cache; any miss selects Worst
//! Case.
//!
//! The published totals include zero-wait, aligned transfers on a 32-bit
//! bus. The core bills transfers through [`AddressBus`](super::memory::AddressBus)
//! while an instruction executes and charges only the portion of the table
//! total not already consumed by those accesses. Consequently wait states and
//! narrower buses can extend a table time, but a table entry never hides a
//! real wait.
//!
//! Full-format indexed extension words cannot be distinguished from the
//! brief form after the instruction has retired. Indexed entries therefore
//! use the manual's brief-form row; the host still bills every extension and
//! indirect operand access that actually occurred.
//!
//! A taken branch additionally pays `TAKEN_BRANCH_REFILL`. The section-8.2
//! entries are written for an instruction whose successor is already in the
//! three-stage pipeline; a taken branch invalidates the decode and execute
//! stages, so the target instruction cannot begin until the pipe refills from
//! the cache. The manual accounts for that in the *following* instruction's
//! head, which a per-instruction model with no overlap stage cannot express,
//! so the cost is charged where the flush happens.
//!
//! The refill cost is calibrated against real hardware: a 68EC020 at
//! 14.19 MHz (Amiga 1200), measured over thirty cached loops referenced to
//! the CIA E-clock, pays it only when the branch opcode word is
//! longword-aligned. A cached taken `dbra` costs 7 clocks at `pc % 4 == 0`
//! and 6 clocks - the manual's cache case - at `pc % 4 == 2`. Every measured
//! loop follows `6 + 2 * body_instructions + refill`, with no exception among
//! the thirty, and the loop *head* alignment varies freely within each refill
//! class, so it is the branch's own alignment that decides the cost and not
//! the target's. The mechanism is presumed to be the longword granularity of
//! instruction fetch: a branch whose opcode and displacement straddle two
//! longwords has already had the second one fetched when it retires.
//!
//! Only `DBcc` was measured. `Bcc`/`BSR` keep the flat refill until a probe
//! covers them; see `TAKEN_BRANCH_REFILL`.

use super::cpu::CpuCore;
use super::types::Size;

/// Clocks a taken branch loses refilling the 020's instruction pipeline when
/// its alignment is unmeasured (`Bcc`, `BSR`). Real hardware shows the cost is
/// alignment dependent for `DBcc` ([`CpuCore::taken_branch_refill`]); these
/// forms are billed the longword-aligned cost until a probe measures them.
const TAKEN_BRANCH_REFILL: i32 = 1;

#[derive(Clone, Copy)]
struct Case {
    cache: i32,
    worst: i32,
}

impl Case {
    const fn new(cache: i32, worst: i32) -> Self {
        Self { cache, worst }
    }

    #[inline]
    const fn pick(self, cached: bool) -> i32 {
        if cached { self.cache } else { self.worst }
    }
}

#[inline]
const fn size_00(bits: u16) -> Size {
    match bits {
        0 => Size::Byte,
        1 => Size::Word,
        _ => Size::Long,
    }
}

/// Table 8-1, "Fetch Effective Address Timing".
const fn fetch_ea(mode: u16, reg: u16, size: Size) -> Case {
    match (mode, reg) {
        (0 | 1, _) => Case::new(0, 0),
        (2 | 3, _) => Case::new(4, 4),
        (4, _) => Case::new(5, 5),
        (5, _) | (7, 2) => Case::new(5, 6),
        (6, _) | (7, 3) => Case::new(7, 8),
        (7, 0) => Case::new(4, 6),
        (7, 1) => Case::new(4, 7),
        (7, 4) if matches!(size, Size::Long) => Case::new(4, 5),
        (7, 4) => Case::new(2, 3),
        _ => Case::new(0, 0),
    }
}

/// Table 8-1, "Fetch Immediate Effective Address Timing".
const fn fetch_immediate_ea(mode: u16, reg: u16, size: Size) -> Case {
    let long = matches!(size, Size::Long);
    match (mode, reg, long) {
        (0 | 1, _, false) => Case::new(2, 3),
        (0 | 1, _, true) => Case::new(4, 5),
        (2, _, false) => Case::new(4, 4),
        (2, _, true) => Case::new(4, 7),
        (3, _, false) => Case::new(6, 7),
        (3, _, true) => Case::new(8, 9),
        (4, _, false) => Case::new(5, 6),
        (4, _, true) => Case::new(7, 8),
        (5, _, false) | (7, 0, false) => Case::new(5, 7),
        (5, _, true) | (7, 0, true) => Case::new(7, 10),
        (6, _, false) | (7, 3, false) => Case::new(9, 11),
        (6, _, true) | (7, 3, true) => Case::new(11, 13),
        (7, 1, false) => Case::new(6, 10),
        (7, 1, true) => Case::new(8, 12),
        _ => Case::new(0, 0),
    }
}

/// Table 8-1, "Calculate Effective Address Timing".
const fn calculate_ea(mode: u16, reg: u16) -> Case {
    match (mode, reg) {
        (0 | 1, _) => Case::new(0, 0),
        (2..=4, _) => Case::new(2, 2),
        (5, _) | (7, 0 | 2) => Case::new(2, 3),
        (6, _) | (7, 3) => Case::new(4, 5),
        (7, 1) => Case::new(4, 5),
        _ => Case::new(0, 0),
    }
}

/// Table 8-1, "Jump Effective Address Timing".
const fn jump_ea(mode: u16, reg: u16) -> Case {
    match (mode, reg) {
        (2, _) => Case::new(2, 2),
        (5, _) | (7, 2) => Case::new(4, 4),
        (6, _) | (7, 3) => Case::new(6, 6),
        (7, 0 | 1) => Case::new(2, 2),
        _ => Case::new(0, 0),
    }
}

/// Table 8-1, "Calculate Immediate Effective Address Timing".
const fn calculate_immediate_ea(mode: u16, reg: u16, size: Size) -> Case {
    let long = matches!(size, Size::Long);
    match (mode, reg, long) {
        (0 | 1, _, false) => Case::new(2, 3),
        (0 | 1, _, true) => Case::new(4, 5),
        (2, _, false) => Case::new(2, 3),
        (2, _, true) => Case::new(4, 5),
        (3 | 4, _, false) => Case::new(4, 5),
        (3 | 4, _, true) => Case::new(6, 7),
        (5, _, false) | (7, 0, false) => Case::new(4, 5),
        (5, _, true) | (7, 0, true) => Case::new(6, 8),
        (6, _, false) | (7, 3, false) => Case::new(6, 8),
        (6, _, true) | (7, 3, true) => Case::new(8, 10),
        (7, 1, false) => Case::new(4, 6),
        (7, 1, true) => Case::new(8, 10),
        _ => Case::new(0, 0),
    }
}

#[inline]
fn add(base: Case, ea: Case) -> Case {
    Case::new(base.cache + ea.cache, base.worst + ea.worst)
}

#[inline]
const fn move_source_row(mode: u16, reg: u16, size: Size) -> usize {
    match (mode, reg) {
        (0 | 1, _) => 0,
        (2, _) => 3,
        (3, _) => 4,
        (4, _) => 5,
        (5, _) | (7, 2) => 6,
        (7, 0) => 7,
        (7, 1) => 8,
        (6, _) | (7, 3) => 9,
        (7, 4) if matches!(size, Size::Long) => 2,
        (7, 4) => 1,
        _ => 0,
    }
}

#[inline]
const fn move_destination_col(mode: u16, reg: u16) -> usize {
    match (mode, reg) {
        (0 | 1, _) => 0,
        (2, _) => 1,
        (3, _) => 2,
        (4, _) => 3,
        (5, _) => 4,
        (7, 0) => 5,
        (7, 1) => 6,
        (6, _) => 7,
        _ => 0,
    }
}

/// Tables 8-4 through 8-9, restricted to standard opcode-visible EAs.
const MOVE_CACHE: [[i32; 8]; 10] = [
    [2, 4, 4, 5, 5, 4, 6, 7],
    [4, 6, 6, 7, 7, 6, 8, 7],
    [6, 8, 8, 9, 9, 8, 10, 9],
    [6, 7, 7, 7, 7, 7, 9, 9],
    [6, 7, 7, 7, 7, 7, 9, 9],
    [7, 8, 8, 8, 8, 8, 10, 10],
    [7, 8, 8, 8, 8, 8, 10, 10],
    [6, 7, 7, 7, 7, 7, 9, 9],
    [6, 7, 7, 7, 7, 7, 9, 9],
    [9, 10, 10, 10, 10, 10, 12, 12],
];

const MOVE_WORST: [[i32; 8]; 10] = [
    [3, 5, 5, 6, 7, 7, 9, 9],
    [3, 5, 8, 6, 7, 7, 9, 9],
    [5, 7, 7, 8, 9, 9, 11, 11],
    [7, 9, 9, 9, 11, 11, 13, 11],
    [7, 9, 9, 9, 11, 11, 13, 11],
    [8, 10, 10, 10, 12, 12, 14, 12],
    [9, 11, 11, 11, 13, 13, 15, 13],
    [8, 10, 10, 10, 12, 12, 14, 12],
    [10, 12, 12, 12, 14, 14, 16, 14],
    [11, 13, 13, 13, 15, 15, 17, 15],
];

fn move_cycles(op: u16, size: Size, cached: bool) -> i32 {
    let src_mode = (op >> 3) & 7;
    let src_reg = op & 7;
    let dst_mode = (op >> 6) & 7;
    let dst_reg = (op >> 9) & 7;
    let row = move_source_row(src_mode, src_reg, size);
    let col = move_destination_col(dst_mode, dst_reg);
    if cached {
        MOVE_CACHE[row][col]
    } else {
        MOVE_WORST[row][col]
    }
}

#[inline]
fn legacy_fallback(raw: i32) -> i32 {
    ((raw * 5 + 7) / 8).max(2)
}

fn exception_cycles(cpu: &CpuCore, raw: i32, cached: bool) -> Option<i32> {
    let vector = cpu.instruction_exception_vector?;
    let op = cpu.ir as u16;
    let cycles = match vector {
        // Table 8-17: these share the same format-$0 entry cost.
        4 | 8 | 10 | 11 => Case::new(20, 27).pick(cached),
        // Group-2 TRAPV/TRAPcc uses a six-word format-$2 frame.
        7 if op == 0x4E76 => Case::new(25, 32).pick(cached),
        7 if op >> 12 == 5 => {
            let submode = op & 7;
            match submode {
                2 | 3 => Case::new(25, 33).pick(cached),
                _ => Case::new(25, 32).pick(cached),
            }
        }
        // CHK and divide-by-zero timing is not specified as a complete trap
        // path in section 8.2; retain the prior conservative calibration.
        _ => legacy_fallback(raw),
    };
    Some(cycles)
}

fn group_0(cpu: &CpuCore, op: u16, cached: bool) -> Option<i32> {
    let mode = (op >> 3) & 7;
    let reg = op & 7;

    // CAS2.W/L.
    if op == 0x0CFC || op == 0x0EFC {
        let base = if cpu.flag_z() {
            Case::new(25, 28)
        } else {
            Case::new(22, 25)
        };
        return Some(base.pick(cached));
    }

    // CAS.B/W/L.
    if matches!(op & 0x0FC0, 0x0AC0 | 0x0CC0 | 0x0EC0) {
        let base = if cpu.flag_z() {
            Case::new(15, 16)
        } else {
            Case::new(12, 13)
        };
        return Some(add(base, calculate_immediate_ea(mode, reg, Size::Word)).pick(cached));
    }

    // MOVES: the direction bit is in the consumed extension word. Use the
    // slower EA->Rn base; both directions still use the exact EA component.
    if op & 0xFF00 == 0x0E00 {
        return Some(
            add(
                Case::new(7, 8),
                calculate_immediate_ea(mode, reg, Size::Word),
            )
            .pick(cached),
        );
    }

    // CALLM/RTM are 68020-only and encode information not retained after
    // retirement. Use the slower documented type-1 paths.
    if op & 0xFFF0 == 0x06C0 {
        return Some(Case::new(32, 35).pick(cached));
    }
    if op & 0xFFC0 == 0x06C0 {
        return Some(
            add(Case::new(57, 64), fetch_immediate_ea(mode, reg, Size::Word)).pick(cached),
        );
    }

    // CMP2/CHK2. Both have the same section-8.2 base time.
    if op & 0x0800 == 0 && op & 0x0100 == 0 && op & 0x00C0 == 0x00C0 && (op >> 9) & 3 != 3 {
        return Some(
            add(Case::new(18, 18), fetch_immediate_ea(mode, reg, Size::Word)).pick(cached),
        );
    }

    // MOVEP.
    if op & 0xF138 == 0x0108 {
        let long = op & 0x0040 != 0;
        let reg_to_mem = op & 0x0080 != 0;
        let case = match (long, reg_to_mem) {
            (false, true) => Case::new(11, 11),
            (true, true) => Case::new(17, 17),
            (false, false) => Case::new(12, 12),
            (true, false) => Case::new(18, 18),
        };
        return Some(case.pick(cached));
    }

    let dynamic_bit = op & 0x0100 != 0;
    let static_bit = op & 0x0F00 == 0x0800;
    if dynamic_bit || static_bit {
        if mode == 0 {
            return Some(Case::new(4, 5).pick(cached));
        }
        let ea = if static_bit {
            fetch_immediate_ea(mode, reg, Size::Word)
        } else {
            fetch_ea(mode, reg, Size::Byte)
        };
        return Some(add(Case::new(4, 5), ea).pick(cached));
    }

    // ORI/ANDI/EORI to CCR/SR.
    if matches!(op, 0x003C | 0x007C | 0x023C | 0x027C | 0x0A3C | 0x0A7C) {
        return Some(Case::new(12, 15).pick(cached));
    }

    // Immediate arithmetic/logical instructions.
    let subop = (op >> 8) & 0xF;
    if matches!(subop, 0x0 | 0x2 | 0x4 | 0x6 | 0xA | 0xC) {
        let size = size_00((op >> 6) & 3);
        let base = if mode == 0 || subop == 0xC {
            Case::new(2, 3)
        } else {
            Case::new(4, 6)
        };
        return Some(add(base, fetch_immediate_ea(mode, reg, size)).pick(cached));
    }

    None
}

fn group_4(op: u16, raw: i32, cached: bool) -> Option<i32> {
    let mode = (op >> 3) & 7;
    let reg = op & 7;

    if op & 0xFFC0 == 0x4C00 {
        return Some(
            add(Case::new(43, 44), fetch_immediate_ea(mode, reg, Size::Word)).pick(cached),
        );
    }
    if op & 0xFFC0 == 0x4C40 {
        // Signedness lives in the consumed extension word; DIVS.L is the
        // conservative choice and differs from DIVU.L by twelve clocks.
        return Some(
            add(Case::new(90, 91), fetch_immediate_ea(mode, reg, Size::Word)).pick(cached),
        );
    }

    // MOVE from SR/CCR.
    if matches!(op & 0xFFC0, 0x40C0 | 0x42C0) {
        let case = if mode == 0 {
            Case::new(4, 5)
        } else {
            add(Case::new(5, 7), calculate_ea(mode, reg))
        };
        return Some(case.pick(cached));
    }
    // MOVE to CCR/SR.
    if matches!(op & 0xFFC0, 0x44C0 | 0x46C0) {
        let base = if op & 0x0200 == 0 {
            Case::new(4, 5)
        } else {
            Case::new(8, 11)
        };
        return Some(add(base, fetch_ea(mode, reg, Size::Word)).pick(cached));
    }

    // MOVEM (long multiply/divide was decoded above).
    if op & 0xFB80 == 0x4880 && mode != 0 {
        let long = op & 0x0040 != 0;
        let to_register = op & 0x0400 != 0;
        let transfer_cost = if long { 8 } else { 4 };
        let count = if to_register {
            raw.saturating_sub(12) / transfer_cost
        } else {
            raw.saturating_sub(8) / transfer_cost
        };
        let base = if to_register {
            Case::new(8 + 4 * count, 9 + 4 * count)
        } else {
            Case::new(4 + 3 * count, 5 + 3 * count)
        };
        return Some(add(base, calculate_immediate_ea(mode, reg, Size::Word)).pick(cached));
    }

    // LEA / CHK.
    if op & 0xF1C0 == 0x41C0 {
        return Some(add(Case::new(2, 3), calculate_ea(mode, reg)).pick(cached));
    }
    let chk_opmode = (op >> 6) & 7;
    if matches!(chk_opmode, 0b100 | 0b110) {
        let size = if chk_opmode == 0b100 {
            Size::Long
        } else {
            Size::Word
        };
        return Some(add(Case::new(8, 8), fetch_ea(mode, reg, size)).pick(cached));
    }

    // JSR / JMP.
    if op & 0xFFC0 == 0x4E80 {
        return Some(add(Case::new(5, 11), jump_ea(mode, reg)).pick(cached));
    }
    if op & 0xFFC0 == 0x4EC0 {
        return Some(add(Case::new(4, 7), jump_ea(mode, reg)).pick(cached));
    }

    // LINK.L / LINK.W / UNLK.
    if op & 0xFFF8 == 0x4808 {
        return Some(Case::new(6, 10).pick(cached));
    }
    if op & 0xFFF8 == 0x4E50 {
        return Some(Case::new(5, 7).pick(cached));
    }
    if op & 0xFFF8 == 0x4E58 {
        return Some(Case::new(6, 7).pick(cached));
    }

    // MOVE USP and MOVEC.
    if op & 0xFFF0 == 0x4E60 {
        return Some(Case::new(2, 3).pick(cached));
    }
    if op == 0x4E7A {
        return Some(Case::new(6, 7).pick(cached));
    }
    if op == 0x4E7B {
        return Some(Case::new(12, 13).pick(cached));
    }

    match op {
        0x4E70 => return Some(Case::new(518, 519).pick(cached)),
        0x4E71 => return Some(Case::new(2, 3).pick(cached)),
        0x4E72 => return Some(Case::new(8, 8).pick(cached)),
        0x4E73 => {
            let case = match raw {
                15 => Case::new(16, 39),
                31 => Case::new(32, 33),
                42 => Case::new(43, 45),
                91 => Case::new(92, 94),
                _ => Case::new(21, 24),
            };
            return Some(case.pick(cached));
        }
        0x4E74 => return Some(Case::new(10, 12).pick(cached)),
        0x4E75 => return Some(Case::new(10, 12).pick(cached)),
        0x4E76 => return Some(Case::new(4, 5).pick(cached)),
        0x4E77 => return Some(Case::new(14, 15).pick(cached)),
        _ => {}
    }

    // PEA (after SWAP's register-direct overlap).
    if op & 0xFFC0 == 0x4840 && mode != 0 {
        return Some(add(Case::new(5, 6), calculate_ea(mode, reg)).pick(cached));
    }
    if op & 0xFFF8 == 0x4840 {
        return Some(Case::new(4, 4).pick(cached)); // SWAP
    }

    // EXT.W/EXT.L/EXTB.L.
    if matches!(op & 0xFFF8, 0x4880 | 0x48C0 | 0x49C0) {
        return Some(Case::new(4, 4).pick(cached));
    }

    // TAS.
    if op & 0xFFC0 == 0x4AC0 {
        let base = if mode == 0 {
            Case::new(4, 4)
        } else {
            add(Case::new(12, 13), calculate_ea(mode, reg))
        };
        return Some(base.pick(cached));
    }

    // TST.
    if op & 0xFF00 == 0x4A00 {
        let size = size_00((op >> 6) & 3);
        return Some(add(Case::new(2, 3), fetch_ea(mode, reg, size)).pick(cached));
    }

    // CLR, NEGX, NEG, NOT.
    if matches!(op & 0xFF00, 0x4000 | 0x4200 | 0x4400 | 0x4600) {
        let size = size_00((op >> 6) & 3);
        if mode == 0 {
            return Some(Case::new(2, 3).pick(cached));
        }
        let ea = if op & 0xFF00 == 0x4200 {
            calculate_ea(mode, reg)
        } else {
            fetch_ea(mode, reg, size)
        };
        return Some(add(Case::new(4, 6), ea).pick(cached));
    }

    // NBCD is fully specified only for Dn in the manual.
    if op & 0xFFC0 == 0x4800 && mode == 0 {
        return Some(Case::new(6, 6).pick(cached));
    }

    None
}

fn dyadic(op: u16, cached: bool) -> Option<i32> {
    let group = op >> 12;
    let opmode = (op >> 6) & 7;
    let mode = (op >> 3) & 7;
    let reg = op & 7;

    // BCD, extend, and paired-memory forms.
    if group == 0x8 && opmode == 4 && mode <= 1 {
        return Some(
            if mode == 0 {
                Case::new(4, 5)
            } else {
                Case::new(16, 17)
            }
            .pick(cached),
        );
    }
    if group == 0xC && opmode == 4 && mode <= 1 {
        return Some(
            if mode == 0 {
                Case::new(4, 5)
            } else {
                Case::new(16, 17)
            }
            .pick(cached),
        );
    }
    if matches!(group, 0x9 | 0xD) && (4..=6).contains(&opmode) && mode <= 1 {
        return Some(
            if mode == 0 {
                Case::new(2, 3)
            } else {
                Case::new(12, 13)
            }
            .pick(cached),
        );
    }
    if group == 0xB && (4..=6).contains(&opmode) && mode == 1 {
        return Some(Case::new(9, 10).pick(cached));
    }
    if group == 0xB && (4..=6).contains(&opmode) && mode == 0 {
        return Some(Case::new(2, 3).pick(cached)); // EOR Dn,Dn
    }
    if group == 0x8 && opmode == 5 && mode <= 1 {
        return Some(
            if mode == 0 {
                Case::new(6, 7)
            } else {
                Case::new(13, 13)
            }
            .pick(cached),
        );
    }
    if group == 0x8 && opmode == 6 && mode <= 1 {
        return Some(
            if mode == 0 {
                Case::new(8, 9)
            } else {
                Case::new(13, 13)
            }
            .pick(cached),
        );
    }

    // EXG.
    if group == 0xC && (4..=6).contains(&opmode) && matches!((op >> 3) & 0x1F, 0x08 | 0x09 | 0x11) {
        return Some(Case::new(2, 3).pick(cached));
    }

    // Word multiply/divide.
    if group == 0xC && matches!(opmode, 3 | 7) {
        return Some(add(Case::new(27, 28), fetch_ea(mode, reg, Size::Word)).pick(cached));
    }
    if group == 0x8 && opmode == 3 {
        return Some(add(Case::new(44, 44), fetch_ea(mode, reg, Size::Word)).pick(cached));
    }
    if group == 0x8 && opmode == 7 {
        return Some(add(Case::new(56, 57), fetch_ea(mode, reg, Size::Word)).pick(cached));
    }

    match opmode {
        0..=2 => Some(add(Case::new(2, 3), fetch_ea(mode, reg, size_00(opmode))).pick(cached)),
        3 | 7 if matches!(group, 0x9 | 0xB | 0xD) => {
            let base = if group == 0xB {
                Case::new(4, 4) // CMPA
            } else {
                Case::new(2, 3) // ADDA/SUBA
            };
            let size = if opmode == 3 { Size::Word } else { Size::Long };
            Some(add(base, fetch_ea(mode, reg, size)).pick(cached))
        }
        4..=6 => Some(add(Case::new(4, 6), fetch_ea(mode, reg, size_00(opmode - 4))).pick(cached)),
        _ => None,
    }
}

fn group_5(cpu: &CpuCore, op: u16, cached: bool) -> Option<i32> {
    let mode = (op >> 3) & 7;
    let reg = op & 7;
    let size_bits = (op >> 6) & 3;

    if size_bits == 3 && mode == 7 && matches!(reg, 2..=4) {
        // TRAPcc, no-trap path. The trap path is caught before classification.
        let case = match reg {
            2 => Case::new(6, 7),
            3 => Case::new(8, 10),
            _ => Case::new(4, 5),
        };
        return Some(case.pick(cached));
    }
    if size_bits == 3 && mode == 1 {
        let condition = ((op >> 8) & 0xF) as u8;
        // Both exits fall through with the pipeline intact; only the looping
        // arm branches, so only it pays the refill.
        let case = if cpu.test_condition(condition) {
            Case::new(6, 7)
        } else if cpu.d(reg as usize) as u16 == 0xFFFF {
            Case::new(10, 10)
        } else {
            let refill = cpu.taken_branch_refill();
            Case::new(6 + refill, 9 + refill)
        };
        return Some(case.pick(cached));
    }
    if size_bits == 3 {
        if mode == 0 {
            return Some(Case::new(4, 4).pick(cached));
        }
        return Some(add(Case::new(6, 6), calculate_ea(mode, reg)).pick(cached));
    }

    let size = size_00(size_bits);
    if mode <= 1 {
        Some(Case::new(2, 3).pick(cached))
    } else {
        Some(add(Case::new(4, 6), fetch_ea(mode, reg, size)).pick(cached))
    }
}

fn group_6(cpu: &CpuCore, op: u16, cached: bool) -> i32 {
    let condition = (op >> 8) & 0xF;
    if condition == 1 {
        return Case::new(7, 13).pick(cached) + TAKEN_BRANCH_REFILL; // BSR
    }
    if condition == 0 || cpu.change_of_flow {
        return Case::new(6, 9).pick(cached) + TAKEN_BRANCH_REFILL;
    }
    match op as u8 {
        0 => Case::new(6, 7).pick(cached),
        0xFF => Case::new(6, 9).pick(cached),
        _ => Case::new(4, 5).pick(cached),
    }
}

fn group_e(cpu: &CpuCore, op: u16, cached: bool) -> Option<i32> {
    let mode = (op >> 3) & 7;
    let reg = op & 7;

    if op & 0x00C0 == 0x00C0 && (op >> 8) & 0xF >= 8 {
        let selector = (op >> 8) & 0xF;
        // Internal (non-bus) costs calibrated against the real-A1200
        // bfprobe column (Copperline timing-test/bfprobe.asm, 2026-08-03).
        // A memory form whose field lies within four bytes performs one
        // operand cycle - a read, plus a write for the modify forms - and
        // a five-byte span adds a second one; the host bills those
        // accesses, so these rows carry only the remainder. On the
        // reference A1200 an 8192-iteration BFSET (An){0:1} + DBcc loop
        // measures 28.10 clocks (BFTST 24.12, BFEXTU and BFINS 28.10, the
        // five-byte BFSET 44.32, register-form BFSET 20.02), with the
        // dynamic offset free and the DBcc alignment clock absorbed by
        // the operand access.
        //
        // The rows are independent of the operand's transfer width: the
        // A1200 moves any span up to four bytes across its 32-bit chip
        // bus in one cycle, so they hold whether the executor asks for a
        // byte, a word, three bytes or a long. Every span is one access,
        // three bytes included (AddressBus::try_read_three_bytes), so a
        // host that bills per access bills one operand cycle for all four.
        //
        // BFFFO and the five-byte rows of the non-BFSET forms keep the
        // MC68020UM relative deltas and are not yet hardware-measured.
        let base = if mode == 0 {
            match selector {
                0x8 => Case::new(6, 7),
                0x9 | 0xB => Case::new(8, 8),
                0xA | 0xC | 0xE => Case::new(14, 14), // real: BFSET Dn loop 20.02
                0xD => Case::new(18, 18),
                0xF => Case::new(10, 10),
                _ => return None,
            }
        } else if cpu.bitfield_mem_wide_span {
            match selector {
                0x8 => Case::new(26, 27),             // BFTST: <5B + 12
                0x9 | 0xB => Case::new(30, 30),       // BFEXT: <5B + 12
                0xA | 0xC | 0xE => Case::new(34, 34), // real: 44.32 clk loop
                0xD => Case::new(42, 42),             // BFFFO: <5B + 12
                0xF => Case::new(34, 34),             // BFINS: <5B + 12
                _ => return None,
            }
        } else {
            match selector {
                0x8 => Case::new(14, 15),             // real: 24.12 clk loop
                0x9 | 0xB => Case::new(18, 18),       // real: 28.10 clk loop
                0xA | 0xC | 0xE => Case::new(22, 22), // real: 28.10 clk loop
                0xD => Case::new(30, 30),             // BFFFO: UM +8 over SET
                0xF => Case::new(22, 22),             // real: 28.10 clk loop
                _ => return None,
            }
        };
        return Some(
            if mode == 0 {
                base
            } else {
                add(base, calculate_immediate_ea(mode, reg, Size::Word))
            }
            .pick(cached),
        );
    }

    if (op >> 6) & 3 == 3 {
        let kind = (op >> 9) & 3;
        let base = match kind {
            0 if op & 0x0100 != 0 => Case::new(6, 7), // ASL
            0 => Case::new(5, 6),                     // ASR
            1 => Case::new(5, 6),                     // LSL/LSR
            2 => Case::new(5, 6),                     // ROXL/ROXR
            _ => Case::new(7, 7),                     // ROL/ROR
        };
        return Some(add(base, fetch_ea(mode, reg, Size::Word)).pick(cached));
    }

    let kind = (op >> 3) & 3;
    let case = match kind {
        0 if op & 0x0100 != 0 => Case::new(8, 8), // ASL
        0 => Case::new(6, 6),                     // ASR
        1 if op & 0x0020 != 0 => Case::new(6, 6), // dynamic LS
        1 => Case::new(4, 4),                     // static LS
        2 => Case::new(12, 12),                   // ROXL/ROXR
        _ => Case::new(8, 8),                     // ROL/ROR
    };
    Some(case.pick(cached))
}

impl CpuCore {
    /// Return the section-8.2 timing for the 68020/68EC020 instruction that
    /// just retired. Instructions not covered by the integer tables (notably
    /// coprocessor operations and full-format indexed detail) retain the old
    /// conservative scale until a dedicated model exists.
    pub(crate) fn cycles_020(&mut self, raw: i32, fetch_cached: bool) -> i32 {
        if let Some(cycles) = exception_cycles(self, raw, fetch_cached) {
            return cycles;
        }

        let op = self.ir as u16;
        let cycles = match op >> 12 {
            0x0 => group_0(self, op, fetch_cached),
            0x1 => Some(move_cycles(op, Size::Byte, fetch_cached)),
            0x2 => Some(move_cycles(op, Size::Long, fetch_cached)),
            0x3 => Some(move_cycles(op, Size::Word, fetch_cached)),
            0x4 => group_4(op, raw, fetch_cached),
            0x5 => group_5(self, op, fetch_cached),
            0x6 => Some(group_6(self, op, fetch_cached)),
            0x7 => Some(Case::new(2, 3).pick(fetch_cached)),
            0x8 | 0x9 | 0xB | 0xC | 0xD => dyadic(op, fetch_cached),
            0xE => group_e(self, op, fetch_cached),
            _ => None,
        };
        cycles.unwrap_or_else(|| legacy_fallback(raw))
    }

    /// Refill clocks for a taken `DBcc`, which real hardware charges only when
    /// the branch opcode word is longword-aligned.
    ///
    /// `ppc` is the address of the instruction being timed: the execution loop
    /// latches it before the fetch and the PC has already moved on by the time
    /// the instruction retires.
    fn taken_branch_refill(&self) -> i32 {
        i32::from(self.ppc.is_multiple_of(4))
    }
}

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

    fn timed(op: u16, raw: i32, cached: bool) -> i32 {
        let mut cpu = CpuCore::new();
        cpu.ir = u32::from(op);
        cpu.cycles_020(raw, cached)
    }

    #[test]
    fn register_and_move_timings_follow_cache_and_worst_tables() {
        assert_eq!(timed(0x7001, 4, true), 2); // MOVEQ #1,D0
        assert_eq!(timed(0x7001, 4, false), 3);
        assert_eq!(timed(0x2284, 8, true), 4); // MOVE.L D4,(A1)
        assert_eq!(timed(0x2284, 8, false), 5);
        assert_eq!(timed(0x2501, 12, true), 5); // MOVE.L D1,-(A2)
        assert_eq!(timed(0x2501, 12, false), 6);
    }

    #[test]
    fn arithmetic_and_expensive_integer_ops_use_manual_bases() {
        assert_eq!(timed(0xD280, 4, true), 2); // ADD.L D0,D1
        assert_eq!(timed(0xD280, 4, false), 3);
        assert_eq!(timed(0x0650, 12, true), 8); // ADDI.W #imm,(A0)
        assert_eq!(timed(0x0650, 12, false), 10);
        assert_eq!(timed(0x0680, 16, true), 6); // ADDI.L #imm,D0
        assert_eq!(timed(0x0680, 16, false), 8);
        assert_eq!(timed(0x0C50, 12, true), 6); // CMPI.W #imm,(A0)
        assert_eq!(timed(0x0C50, 12, false), 7);
        assert_eq!(timed(0xB100, 4, true), 2); // EOR.B D0,D0
        assert_eq!(timed(0xB100, 4, false), 3);
        assert_eq!(timed(0xC0C1, 42, true), 27); // MULU.W D1,D0
        assert_eq!(timed(0xC0C1, 42, false), 28);
        assert_eq!(timed(0x81C1, 90, true), 56); // DIVS.W D1,D0
        assert_eq!(timed(0x81C1, 90, false), 57);
    }

    #[test]
    fn barrel_shifter_cost_is_count_independent() {
        assert_eq!(timed(0xE108, 6, true), 4); // LSL.B #8,D0
        assert_eq!(timed(0xE368, 6, true), 6); // LSL.W D1,D0
        assert_eq!(timed(0xE570, 6, true), 12); // ROXL.W D2,D0
    }

    #[test]
    fn taken_dbcc_pays_the_refill_only_when_longword_aligned() {
        // Real-A1200 measurement: a cached taken dbra costs 7 clocks with the
        // opcode at pc % 4 == 0 and 6 with it at pc % 4 == 2. Thirty measured
        // loops fit `6 + 2 * body_instructions + refill` with no exception.
        let mut cpu = CpuCore::new();
        cpu.ir = 0x51C8; // DBF D0,<disp>
        cpu.dar[0] = 7;

        cpu.ppc = 0x3000;
        assert_eq!(cpu.cycles_020(12, true), 7);
        cpu.ppc = 0x3002;
        assert_eq!(cpu.cycles_020(12, true), 6);

        // The alignment rides on the branch itself, not on its target: an
        // aligned dbra keeps the refill wherever the loop head sits.
        cpu.ppc = 0x3004;
        assert_eq!(cpu.cycles_020(12, true), 7);
        cpu.ppc = 0x3006;
        assert_eq!(cpu.cycles_020(12, true), 6);
    }

    #[test]
    fn dbcc_distinguishes_loop_expiry_and_true_condition() {
        let mut cpu = CpuCore::new();
        // Looping: the branch is taken, so it also pays the pipeline refill.
        cpu.ir = 0x51C8; // DBF D0,<disp>
        cpu.dar[0] = 7;
        cpu.ppc = 0;
        assert_eq!(cpu.cycles_020(12, true), 6 + 1);
        assert_eq!(cpu.cycles_020(12, false), 9 + 1);

        // Both fall-through exits leave the pipeline intact: table entry only.
        cpu.dar[0] = 0xFFFF;
        assert_eq!(cpu.cycles_020(14, true), 10);
        assert_eq!(cpu.cycles_020(14, false), 10);

        cpu.ir = 0x50C8; // DBT: condition true
        assert_eq!(cpu.cycles_020(12, true), 6);
        assert_eq!(cpu.cycles_020(12, false), 7);
    }

    #[test]
    fn only_taken_branches_pay_the_pipeline_refill() {
        let mut cpu = CpuCore::new();
        // BRA is unconditional, so it always flushes.
        cpu.ir = 0x6002;
        cpu.change_of_flow = false;
        assert_eq!(cpu.cycles_020(10, true), 6 + TAKEN_BRANCH_REFILL);

        // BSR likewise.
        cpu.ir = 0x6102;
        assert_eq!(cpu.cycles_020(18, true), 7 + TAKEN_BRANCH_REFILL);

        // A conditional branch pays it only when it is actually taken.
        cpu.ir = 0x6702; // BEQ.B
        cpu.change_of_flow = true;
        assert_eq!(cpu.cycles_020(10, true), 6 + TAKEN_BRANCH_REFILL);
        cpu.change_of_flow = false;
        assert_eq!(cpu.cycles_020(10, true), 4);
    }

    fn bitfield_timed(op: u16, cached: bool, wide_span: bool) -> i32 {
        let mut cpu = CpuCore::new();
        cpu.ir = u32::from(op);
        cpu.bitfield_mem_wide_span = wide_span;
        cpu.cycles_020(12, cached)
    }

    #[test]
    fn bitfield_register_rows_hold_the_measured_internal_cost() {
        // Register forms perform no operand access, so the row is the whole
        // instruction. Real A1200: a BFSET Dn{0:1} + DBcc loop is 20.02
        // clocks (bfprobe row 4), against 14 here plus the taken DBcc.
        for cached in [true, false] {
            assert_eq!(bitfield_timed(0xEEC0, cached, false), 14); // BFSET Dn
            assert_eq!(bitfield_timed(0xEAC0, cached, false), 14); // BFCHG Dn
            assert_eq!(bitfield_timed(0xECC0, cached, false), 14); // BFCLR Dn
        }
        assert_eq!(bitfield_timed(0xE8C0, true, false), 6); // BFTST Dn
        assert_eq!(bitfield_timed(0xE8C0, false, false), 7);
        assert_eq!(bitfield_timed(0xE9C0, true, false), 8); // BFEXTU Dn
        assert_eq!(bitfield_timed(0xEBC0, true, false), 8); // BFEXTS Dn
        assert_eq!(bitfield_timed(0xEDC0, true, false), 18); // BFFFO Dn
        assert_eq!(bitfield_timed(0xEFC0, true, false), 10); // BFINS Dn

        // The span flag is a memory-operand property and must not reach the
        // register rows, whatever the previous memory bit-field left behind.
        assert_eq!(bitfield_timed(0xEEC0, true, true), 14);
    }

    #[test]
    fn bitfield_memory_rows_within_four_bytes_hold_the_measured_cost() {
        // (A0) adds the mode-2 word EA, Case(2, 3). Real A1200 loops:
        // BFSET/BFINS/BFEXTU 28.10 clocks, BFTST 24.12 (bfprobe rows 2, 11,
        // 10, 9). The remainder below is what the core charges on top of the
        // one operand cycle the host bills.
        assert_eq!(bitfield_timed(0xEED0, true, false), 24); // BFSET (A0)
        assert_eq!(bitfield_timed(0xEED0, false, false), 25);
        assert_eq!(bitfield_timed(0xEAD0, true, false), 24); // BFCHG (A0)
        assert_eq!(bitfield_timed(0xECD0, true, false), 24); // BFCLR (A0)
        assert_eq!(bitfield_timed(0xEFD0, true, false), 24); // BFINS (A0)
        assert_eq!(bitfield_timed(0xEFD0, false, false), 25);
        assert_eq!(bitfield_timed(0xE8D0, true, false), 16); // BFTST (A0)
        assert_eq!(bitfield_timed(0xE8D0, false, false), 18);
        assert_eq!(bitfield_timed(0xE9D0, true, false), 20); // BFEXTU (A0)
        assert_eq!(bitfield_timed(0xE9D0, false, false), 21);
        assert_eq!(bitfield_timed(0xEBD0, true, false), 20); // BFEXTS (A0)
        assert_eq!(bitfield_timed(0xEDD0, true, false), 32); // BFFFO (A0)
        assert_eq!(bitfield_timed(0xEDD0, false, false), 33);
    }

    #[test]
    fn bitfield_five_byte_span_costs_one_operand_cycle_more() {
        // Real A1200: the five-byte BFSET loop is 44.32 clocks against 28.10
        // for a span within four bytes (bfprobe rows 7 and 2). The extra
        // operand cycle the span needs is billed by the host; the internal
        // remainder rises by 12 across every form.
        assert_eq!(bitfield_timed(0xEED0, true, true), 36); // BFSET (A0)
        assert_eq!(bitfield_timed(0xEED0, false, true), 37);
        assert_eq!(bitfield_timed(0xEAD0, true, true), 36); // BFCHG (A0)
        assert_eq!(bitfield_timed(0xECD0, true, true), 36); // BFCLR (A0)
        assert_eq!(bitfield_timed(0xEFD0, true, true), 36); // BFINS (A0)
        assert_eq!(bitfield_timed(0xE8D0, true, true), 28); // BFTST (A0)
        assert_eq!(bitfield_timed(0xE8D0, false, true), 30);
        assert_eq!(bitfield_timed(0xE9D0, true, true), 32); // BFEXTU (A0)
        assert_eq!(bitfield_timed(0xEBD0, true, true), 32); // BFEXTS (A0)
        assert_eq!(bitfield_timed(0xEDD0, true, true), 44); // BFFFO (A0)

        // Every form pays exactly one operand cycle's worth more than its
        // within-four-bytes row, which is the shape the UM publishes.
        for op in [
            0xEED0u16, 0xEAD0, 0xECD0, 0xEFD0, 0xE8D0, 0xE9D0, 0xEBD0, 0xEDD0,
        ] {
            assert_eq!(
                bitfield_timed(op, true, true) - bitfield_timed(op, true, false),
                12,
                "opcode {op:04X} five-byte delta"
            );
        }
    }

    #[test]
    fn control_and_save_restore_use_complete_table_entries() {
        assert_eq!(timed(0x4E71, 4, true), 2); // NOP
        assert_eq!(timed(0x4E71, 4, false), 3);
        assert_eq!(timed(0x4E75, 16, true), 10); // RTS
        assert_eq!(timed(0x4E75, 16, false), 12);
        assert_eq!(timed(0x4E73, 20, true), 21); // RTE, normal frame
        assert_eq!(timed(0x4E73, 20, false), 24);
        assert_eq!(timed(0x4E70, 132, true), 518); // RESET
    }

    #[test]
    fn model_dispatch_uses_tables_only_for_the_020_family() {
        use crate::core::types::CpuType;

        let mut cpu = CpuCore::new();
        cpu.ir = 0x4E71; // NOP
        cpu.set_cpu_type(CpuType::M68EC020);
        assert_eq!(cpu.finalize_cycles(4, true), 2);
        cpu.set_cpu_type(CpuType::M68020);
        assert_eq!(cpu.finalize_cycles(4, false), 3);
        cpu.set_cpu_type(CpuType::M68030);
        assert_eq!(cpu.finalize_cycles(4, true), 3);
    }
}