# SPDX-License-Identifier: MIT AND Zlib """Multiplies: MUL, MLA, UMULL, UMLAL, SMULL, SMLAL and Thumb's MUL (DS 4.7, 4.8, 5.4). Timing (TRM 6.20, timing.md tables 6-5 to 6-8): the prefetch, then ``m`` internal cycles at pc+12 for MUL, one more at pc+8 first for MLA, ``m + 1`` for UMULL and SMULL and ``m + 2`` for the accumulating long forms. ``m`` counts the multiplier's significant bytes: 1 to 4 as its bits 31:8, 31:16 or 31:24 are all zeros (or all ones, for the signed forms); UMULL and UMLAL stop early only on zeros (DS 4.8.3, U11). The next fetch is S (merged IS, C1). Flags with S set: N and Z from the result (bit 63 and all 64 bits for the long forms); V is unchanged (DS 4.7.2, 4.8.2). C, which the data sheet calls "meaningless", is the carry the multiplier array leaves: :func:`booth_multiply` computes it with zaydlang's model of the ARM7TDMI's Booth multiplier, fuzzed against a GBA ("Multiplication Algorithm" research, reference/docs/bmchtech-multiply.html; rung 4 judges the core against the model's own C code). R15 as an operand of a multiply reads pc+12: the operands are read after the PC has advanced past the first internal cycle (U12; DS 4.7.3 forbids R15 as an operand; OBSERVED, the SingleStepTests corpus v1 shows +12 for every such case). ---- :func:`booth_multiply` is a Python transcription of ``booths_multiplication`` and its helpers in zaydlang's ``multiplication-algorithm`` (``impl.h``, ``bitwise.h``, commit 29cef09), altered from its original form: C translated to Python, globals made locals, renamed, and the result split from the carry. The original carries this notice: Copyright (c) 2024 zaydlang This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. """ from __future__ import annotations from arm7tdmi_python._core import MASK32, CoreMixin from arm7tdmi_python._modes import FLAG_C, FLAG_N, FLAG_Z S_BIT = 1 << 20 MASK64 = (1 << 64) - 1 SHORT, LONG_SIGNED, LONG_UNSIGNED = range(3) def sign_extend(value: int, bits: int) -> int: """``value`` (``bits`` wide) as a Python int with its sign.""" value &= (1 << bits) - 1 return value - (1 << bits) if value >> (bits - 1) & 1 else value def multiply_cycles(multiplier: int, signed: bool) -> int: """``m``, the multiplier's significant bytes (TRM 6.20, DS 4.8.3, U11).""" multiplier &= MASK32 for m, shift in ((1, 8), (2, 16), (3, 24)): top = multiplier >> shift if top == 0 or (signed and top == MASK32 >> shift): return m return 4 # --------------------------------------------------------------------------- zaydlang's model # (zlib; altered, see the module docstring) def _extend(value: int, from_size: int, to_size: int) -> int: """bitwise.h ``sign_extend``: copy bit ``from_size - 1`` up to bit ``to_size - 1``.""" if value >> (from_size - 1) & 1: value |= ((1 << (to_size - from_size)) - 1) << from_size return value def _asr(value: int, shift: int, size: int) -> int: """bitwise.h ``asr``: arithmetic shift right within ``size`` bits.""" extended = _extend(value, size, 64) if extended >> 63: extended -= 1 << 64 return (extended >> shift) & ((1 << size) - 1) def _booth_recode(value: int, chunk: int) -> tuple[int, int]: """One radix-4 Booth digit: (the recoded addend, its carry), 34 bits.""" if chunk in (1, 2): out, carry = value, 0 elif chunk == 3: out, carry = 2 * value, 0 elif chunk == 4: out, carry = ~(2 * value) & MASK64, 1 elif chunk in (5, 6): out, carry = ~value & MASK64, 1 else: # 0 and 7 out, carry = 0, 0 return out & 0x3FFFFFFFF, carry def _csa_array(total: int, carry: int, addends: list[tuple[int, int]], acc: int): """Four carry-save adders; returns (sum, carry, the accumulator shift register).""" final_total = final_carry = 0 for i, (addend, booth_carry) in enumerate(addends): total &= 0x1FFFFFFFF carry &= 0x1FFFFFFFF b = addend & 0x1FFFFFFFF out = total ^ b ^ carry out_carry = (total & b) | (b & carry) | (carry & total) out_carry = ((out_carry << 1) | booth_carry) & MASK64 final_total |= (out & 3) << (2 * i) final_carry |= (out_carry & 3) << (2 * i) out >>= 2 out_carry >>= 2 magic = (acc & 1) + (0 if carry >> 32 & 1 else 1) + (0 if addend >> 33 & 1 else 1) out |= magic << 31 out_carry |= (0 if acc >> 1 & 1 else 1) << 32 acc >>= 2 total, carry = out, out_carry final_total = (final_total | (total << 8)) & MASK64 final_carry = (final_carry | (carry << 8)) & MASK64 return final_total, final_carry, acc def _add32(a: int, b: int, carry: int) -> tuple[int, int]: total = (a & MASK32) + (b & MASK32) + carry return total & MASK32, total >> 32 def booth_multiply(flavor: int, multiplicand: int, multiplier: int, accumulator: int) -> int: """The carry flag the ARM7TDMI's multiplier leaves (0 or 1), by zaydlang's model. ``flavor`` is ``SHORT`` (MUL, MLA: signed operands), ``LONG_SIGNED`` or ``LONG_UNSIGNED``; ``multiplicand`` is Rm, ``multiplier`` Rs, ``accumulator`` Rn or RdHi:RdLo (0 without). Only the carry is kept. The model collects each iteration's low carry byte and the last iteration's remainder into a 128-bit register, rotates it, and returns bit 127 (bit 95 for a four-iteration MUL/MLA). Following those rotations back, that bit is always one bit of the last iteration's carry vector: bit ``38 - 8 * iterations`` for one to three iterations, bit 38 (bit 6 for MUL/MLA) for four. The function reads that bit directly instead of building the register (equal to the model on rung 4's 7,000,000 cases). """ signed = flavor != LONG_UNSIGNED if signed: multiplier = _extend(multiplier & MASK32, 32, 34) multiplicand = _extend(multiplicand & MASK32, 32, 34) else: multiplier &= 0x1FFFFFFFF multiplicand &= 0x1FFFFFFFF carry = ~multiplicand & MASK64 if multiplier & 1 else 0 total = accumulator & MASK64 acc = total >> 34 total >>= 1 carry >>= 1 iterations = 0 while True: addends = [_booth_recode(multiplicand, (multiplier >> (2 * i)) & 7) for i in range(4)] total, carry, acc = _csa_array(total, carry, addends, acc) multiplier = _asr(multiplier, 8, 33) iterations += 1 if multiplier == 0 or (signed and multiplier == 0x1FFFFFFFF): break total >>= 8 carry >>= 8 if iterations == 4: return carry >> (6 if flavor == SHORT else 38) & 1 return carry >> (38 - 8 * iterations) & 1 # --------------------------------------------------------------------------- the instructions class MultiplyMixin(CoreMixin): def _multiply_flags(self, negative: bool, zero: bool, carry: int) -> None: self.cpsr = ( (self.cpsr & ~(FLAG_N | FLAG_Z | FLAG_C)) | (FLAG_N if negative else 0) | (FLAG_Z if zero else 0) | (FLAG_C if carry else 0) ) def _multiply_short(self, op: int, accumulate: bool) -> None: # Register reads follow the cycle that makes them (U7): MLA reads Rn in its first # cycle and Rm, Rs after its extra internal cycle at pc+8; MUL reads Rm, Rs first. rn = 0 if accumulate: rn = self._reg((op >> 12) & 0xF) if (op >> 12) & 0xF == 15: rn = (rn + 4) & MASK32 # R15 as Rn reads pc+12 (U12) self._idle(self.r[15]) self.r[15] = (self.r[15] + 4) & MASK32 rm = self._reg(op & 0xF) rs = self._reg((op >> 8) & 0xF) for _ in range(multiply_cycles(rs, signed=True)): self._idle(self.r[15]) result = (rm * rs + rn) & MASK32 if op & S_BIT: carry = booth_multiply(SHORT, rm, rs, rn) self._multiply_flags(bool(result >> 31), result == 0, carry) rd = (op >> 16) & 0xF self._set_reg(rd, result) self.next_fetch_seq = True # merged IS (C1) if rd == 15: self._refill() # DS 4.7.3 forbids it; the corpus refills (OBSERVED corpus v1) def _multiply_long(self, op: int, signed: bool, accumulate: bool) -> None: self.r[15] = (self.r[15] + 4) & MASK32 rd_lo, rd_hi = (op >> 12) & 0xF, (op >> 16) & 0xF # The accumulating forms read RdHi:RdLo in their first cycle and Rm, Rs in the next; # the others read Rm, Rs first (U7). accumulator = 0 if accumulate: accumulator = self._reg(rd_hi) << 32 | self._reg(rd_lo) self._idle(self.r[15]) rm = self._reg(op & 0xF) rs = self._reg((op >> 8) & 0xF) for _ in range(multiply_cycles(rs, signed) + 1): self._idle(self.r[15]) product = sign_extend(rm, 32) * sign_extend(rs, 32) if signed else rm * rs result = (product + accumulator) & MASK64 if op & S_BIT: flavor = LONG_SIGNED if signed else LONG_UNSIGNED carry = booth_multiply(flavor, rm, rs, accumulator) self._multiply_flags(bool(result >> 63), result == 0, carry) self._set_reg(rd_lo, result & MASK32) self._set_reg(rd_hi, result >> 32) self.next_fetch_seq = True # merged IS (C1) if 15 in (rd_lo, rd_hi): self._refill() # DS 4.8.3 forbids it; the corpus refills (OBSERVED corpus v1) def _arm_mul(self, op: int) -> None: """MUL -- Rd = Rm x Rs (DS 4.7, TRM 6.20).""" self._multiply_short(op, accumulate=False) def _arm_mla(self, op: int) -> None: """MLA -- Rd = Rm x Rs + Rn (DS 4.7, TRM 6.20).""" self._multiply_short(op, accumulate=True) def _arm_umull(self, op: int) -> None: """UMULL -- RdHi:RdLo = Rm x Rs, unsigned (DS 4.8, U11).""" self._multiply_long(op, signed=False, accumulate=False) def _arm_umlal(self, op: int) -> None: """UMLAL -- RdHi:RdLo += Rm x Rs, unsigned (DS 4.8, U11).""" self._multiply_long(op, signed=False, accumulate=True) def _arm_smull(self, op: int) -> None: """SMULL -- RdHi:RdLo = Rm x Rs, signed (DS 4.8).""" self._multiply_long(op, signed=True, accumulate=False) def _arm_smlal(self, op: int) -> None: """SMLAL -- RdHi:RdLo += Rm x Rs, signed (DS 4.8).""" self._multiply_long(op, signed=True, accumulate=True) def _thumb_mul(self, op: int) -> None: """MUL Rd,Rs -- format 4: Rd = Rs x Rd; N, Z and the multiplier's C (DS 5.4, TRM 6.20).""" rd = op & 7 multiplicand, multiplier = self.r[(op >> 3) & 7], self.r[rd] self.r[15] = (self.r[15] + 2) & MASK32 for _ in range(multiply_cycles(multiplier, signed=True)): self._idle(self.r[15]) result = (multiplicand * multiplier) & MASK32 carry = booth_multiply(SHORT, multiplicand, multiplier, 0) self._multiply_flags(bool(result >> 31), result == 0, carry) self.r[rd] = result self.next_fetch_seq = True # merged IS (C1)