huc6280/
alu.rs

1//! Arithmetic, logic, compare and bit test: ADC SBC AND ORA EOR CMP CPX CPY
2//! BIT (`_alu.py`).
3//!
4//! `ORA`, `AND`, `EOR` and `ADC` honour the T flag (U4): with T set the
5//! accumulator is replaced by the zero-page byte at X (logical `$2000 + X`),
6//! the result goes back there, A is untouched and the instruction takes three
7//! more cycles (read, internal, write). `SBC` does not (C5: SW's entry has no
8//! T clause; MAME's yes is a guess), unless `sbc_honours_t` is set.
9//!
10//! Decimal mode (U14, HW HB-4, SW `ADC`): one more cycle, N, Z and C taken
11//! from the decimal result, **V left alone**. How invalid digits adjust is
12//! C13: neither manual says. `decimal_formula` picks the digit adjust. The
13//! default, `Mednafen`, gives the results Mednafen's HuC6280 gives
14//! ("corrected ... per tests on a HuC6280", its ChangeLog, 2015-04-29: the
15//! one author statement of hardware testing); `Mesen` gives Mesen's, the
16//! results the 640,000-case SingleStepTests corpus was made with. They
17//! differ only with an invalid BCD digit (the reference's docs/issues/0004).
18//! Both are transcribed from the reference's own routines, which were
19//! written from the rules stated in words there and checked against recorded
20//! result tables; neither emulator's code is copied.
21//!
22//! Differences forced by Rust: the digit arithmetic is done in `i32`, with
23//! `rem_euclid` where the reference's `%` meets a negative number (Python's
24//! `%` takes the sign of the divisor); an unknown formula cannot be named,
25//! so the reference's `ValueError` has no counterpart.
26
27use crate::core::{Bus, HuC6280, C, D, N, V, Z, ZERO_PAGE};
28use crate::dispatch::Mode;
29
30/// C13: the decimal digit adjust of ADC and SBC (`decimal_formula`).
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum DecimalFormula {
33    /// The default: the results Mednafen gives.
34    Mednafen,
35    /// The results Mesen gives, which the SingleStepTests corpus records.
36    Mesen,
37}
38
39/// N and Z for a result that has not been masked to 8 bits yet.
40fn nz(value: i32) -> u8 {
41    (value as u8 & N) | if value & 0xFF != 0 { 0 } else { Z }
42}
43
44/// The decimal sum before masking: 256 and up is the carry out.
45///
46/// Written from the rule each emulator's result table follows (the
47/// reference's docs/issues/0004 states both in words), digit by digit; no
48/// emulator's source is reproduced here.
49fn decimal_add(a: i32, operand: i32, carry: i32, formula: DecimalFormula) -> i32 {
50    let mut ones = a % 16 + operand % 16 + carry;
51    let sixteens = a / 16 + operand / 16;
52    if ones >= 10 {
53        ones += 6; // a digit past 9 skips the six unused codes
54    }
55    let mut total = match formula {
56        // Everything the ones digit overflowed by is carried, however much that is.
57        DecimalFormula::Mednafen => 16 * sixteens + ones,
58        // One carry at most, and only the low four bits of the ones digit are kept.
59        DecimalFormula::Mesen => 16 * (sixteens + if ones >= 16 { 1 } else { 0 }) + ones % 16,
60    };
61    if total >= 0xA0 {
62        total += 0x60;
63    }
64    total
65}
66
67/// The decimal difference: 256 and up means no borrow (carry out). Written as above.
68fn decimal_subtract(a: i32, operand: i32, carry: i32, formula: DecimalFormula) -> i32 {
69    match formula {
70        DecimalFormula::Mednafen => {
71            // Digit differences with a borrow between them; each digit that
72            // borrowed is corrected (by 6, by $60) on the assembled byte,
73            // modulo 256.
74            let ones = a % 16 - operand % 16 - (1 - carry);
75            let sixteens = a / 16 - operand / 16 - if ones < 0 { 1 } else { 0 };
76            let mut byte = 16 * sixteens.rem_euclid(16) + ones.rem_euclid(16);
77            if ones < 0 {
78                byte -= 0x06;
79            }
80            if sixteens < 0 {
81                byte -= 0x60;
82            }
83            byte.rem_euclid(256) + if sixteens < 0 { 0 } else { 256 }
84        }
85        DecimalFormula::Mesen => {
86            // The sum with the operand's complement; a digit that produced no
87            // carry is corrected before the next is formed, and the
88            // correction is not reduced modulo 256 here.
89            let complement = 255 - operand;
90            let mut ones = a % 16 + complement % 16 + carry;
91            if ones < 16 {
92                ones -= 6;
93            }
94            let mut total = 16 * (a / 16 + complement / 16 + if ones >= 16 { 1 } else { 0 })
95                + ones.rem_euclid(16);
96            if total < 256 {
97                total -= 0x60;
98            }
99            total
100        }
101    }
102}
103
104/// A + operand + C, binary or decimal; return (result, P).
105pub fn add(a: u8, operand: u8, p: u8, formula: DecimalFormula) -> (u8, u8) {
106    let (a, operand) = (a as i32, operand as i32);
107    let carry = (p & C) as i32;
108    let mut p = p;
109    let result;
110    if p & D != 0 {
111        result = decimal_add(a, operand, carry, formula);
112        p &= !(N | Z | C); // V is unchanged in decimal mode (U14)
113    } else {
114        result = a + operand + carry;
115        p &= !(N | V | Z | C);
116        if !(a ^ operand) & (a ^ result) & 0x80 != 0 {
117            p |= V;
118        }
119    }
120    if result > 0xFF {
121        p |= C;
122    }
123    (result as u8, p | nz(result))
124}
125
126/// A - operand - (1 - C), binary or decimal; return (result, P).
127pub fn subtract(a: u8, operand: u8, p: u8, formula: DecimalFormula) -> (u8, u8) {
128    let (a, operand) = (a as i32, operand as i32);
129    let carry = (p & C) as i32;
130    let mut p = p;
131    let result;
132    if p & D != 0 {
133        result = decimal_subtract(a, operand, carry, formula);
134        p &= !(N | Z | C);
135    } else {
136        let inverted = !operand & 0xFF;
137        result = a + inverted + carry;
138        p &= !(N | V | Z | C);
139        if !(a ^ inverted) & (a ^ result) & 0x80 != 0 {
140            p |= V;
141        }
142    }
143    if result > 0xFF {
144        p |= C;
145    }
146    (result as u8, p | nz(result))
147}
148
149/// ADC's or SBC's arithmetic: [`add`] or [`subtract`].
150type Arithmetic = fn(u8, u8, u8, DecimalFormula) -> (u8, u8);
151
152impl<B: Bus> HuC6280<B> {
153    /// U4: T set, so the operation's other operand is M($2000 + X) and the
154    /// result goes back.
155    ///
156    /// The three extra cycles are a read, an internal cycle (two in decimal
157    /// mode, where the adjust takes one more) and a write.
158    fn memory_mode(
159        &mut self,
160        operand: u8,
161        operation: impl FnOnce(&mut Self, u8, u8) -> u8,
162        extra_cycle: bool,
163    ) {
164        let address = ZERO_PAGE | self.x as u16;
165        let memory = self.cycle_read(address);
166        self.io();
167        if extra_cycle {
168            self.io();
169        }
170        let result = operation(self, memory, operand);
171        self.set_nz(result);
172        self.cycle_write(address, result);
173    }
174
175    /// ORA -- A OR M -> A, or M(X) OR M -> M(X) with T set (SW SB-58).
176    pub(crate) fn op_ora(&mut self, mode: Mode) {
177        let address = self.ea(mode);
178        let operand = self.load(address);
179        if self.t != 0 {
180            self.memory_mode(operand, |_, memory, value| memory | value, false);
181        } else {
182            self.a = self.set_nz(self.a | operand);
183        }
184    }
185
186    /// AND -- A AND M -> A, or M(X) AND M -> M(X) with T set (SW SB-18).
187    pub(crate) fn op_and(&mut self, mode: Mode) {
188        let address = self.ea(mode);
189        let operand = self.load(address);
190        if self.t != 0 {
191            self.memory_mode(operand, |_, memory, value| memory & value, false);
192        } else {
193            self.a = self.set_nz(self.a & operand);
194        }
195    }
196
197    /// EOR -- A EOR M -> A, or M(X) EOR M -> M(X) with T set (SW SB-47).
198    pub(crate) fn op_eor(&mut self, mode: Mode) {
199        let address = self.ea(mode);
200        let operand = self.load(address);
201        if self.t != 0 {
202            self.memory_mode(operand, |_, memory, value| memory ^ value, false);
203        } else {
204            self.a = self.set_nz(self.a ^ operand);
205        }
206    }
207
208    fn arithmetic(&mut self, mode: Mode, operation: Arithmetic, uses_t: bool) {
209        let address = self.ea(mode);
210        let operand = self.load(address);
211        let decimal = self.p & D != 0;
212        if uses_t && self.t != 0 {
213            // The adjust's extra cycle (U14) sits among the memory-mode cycles.
214            self.memory_mode(
215                operand,
216                |cpu, memory, value| {
217                    let (result, p) = operation(memory, value, cpu.p, cpu.decimal_formula);
218                    cpu.p = p;
219                    result
220                },
221                decimal,
222            );
223            return;
224        }
225        if decimal {
226            // U14: the extra cycle. A dummy read at the next opcode, or an
227            // internal cycle for SBC while T is set (it does not use the
228            // memory mode but keeps its cycle; Mesen).
229            if self.t != 0 {
230                self.io();
231            } else {
232                self.dummy(self.pc);
233            }
234        }
235        (self.a, self.p) = operation(self.a, operand, self.p, self.decimal_formula);
236    }
237
238    /// ADC -- A + M + C -> A, or M(X) + M + C -> M(X) with T set (SW SB-17).
239    pub(crate) fn op_adc(&mut self, mode: Mode) {
240        self.arithmetic(mode, add, true);
241    }
242
243    /// SBC -- A - M - (1 - C) -> A; T is ignored (C5) (SW SB-74).
244    pub(crate) fn op_sbc(&mut self, mode: Mode) {
245        self.arithmetic(mode, subtract, self.sbc_honours_t);
246    }
247
248    fn compare(&mut self, register: u8, operand: u8) {
249        let difference = register.wrapping_sub(operand);
250        let mut p = self.p & !(N | Z | C);
251        if register >= operand {
252            p |= C;
253        }
254        self.p = p | crate::core::nz(difference);
255    }
256
257    /// CMP -- A - M, flags only (SW SB-41).
258    pub(crate) fn op_cmp(&mut self, mode: Mode) {
259        let address = self.ea(mode);
260        let operand = self.load(address);
261        self.compare(self.a, operand);
262    }
263
264    /// CPX -- X - M, flags only (SW SB-42).
265    pub(crate) fn op_cpx(&mut self, mode: Mode) {
266        let address = self.ea(mode);
267        let operand = self.load(address);
268        self.compare(self.x, operand);
269    }
270
271    /// CPY -- Y - M, flags only (SW SB-43).
272    pub(crate) fn op_cpy(&mut self, mode: Mode) {
273        let address = self.ea(mode);
274        let operand = self.load(address);
275        self.compare(self.y, operand);
276    }
277
278    fn bit_flags(&mut self, operand: u8, mask_with: u8) {
279        // U19: N and V come from the operand, Z from the AND; HW HB-5, SW BIT.
280        let mut p = (self.p & !(N | V | Z)) | (operand & (N | V));
281        if mask_with & operand == 0 {
282            p |= Z;
283        }
284        self.p = p;
285    }
286
287    /// BIT -- A AND M sets Z; M bits 7 and 6 -> N and V, immediate form too
288    /// (U19) (SW SB-25).
289    pub(crate) fn op_bit(&mut self, mode: Mode) {
290        let address = self.ea(mode);
291        let operand = self.load(address);
292        self.bit_flags(operand, self.a);
293    }
294}