From 6afce5ce0bc90efae81d13b1eba701b7b860dcfd Mon Sep 17 00:00:00 2001 From: Ryan Heard Date: Wed, 11 Nov 2026 10:36:37 -0500 Subject: [PATCH] [mypyc] Multiply short ints with negative operands inline --- mypyc/lib-rt/CPy.h | 12 ++++++++++-- mypyc/test-data/run-integers.test | 32 +++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index d4bd2d8938ce1..19337d2291fae 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -341,8 +341,16 @@ static inline bool CPyTagged_IsSubtractOverflow(CPyTagged diff, CPyTagged left, } static inline bool CPyTagged_IsMultiplyOverflow(CPyTagged left, CPyTagged right) { - // This is conservative -- return false only in a small number of all non-overflow cases - return left >= (1U << (CPY_INT_BITS/2 - 1)) || right >= (1U << (CPY_INT_BITS/2 - 1)); + // This is conservative -- return false only in a small number of all non-overflow cases. + // Both operands (as tagged values) have to fit in a signed integer of half the width of + // CPyTagged, so the tagged product is at most 2**(N-3) in magnitude (N is CPY_INT_BITS). +#if SIZEOF_SIZE_T == 4 + return (Py_ssize_t)(int16_t)left != (Py_ssize_t)left + || (Py_ssize_t)(int16_t)right != (Py_ssize_t)right; +#else + return (Py_ssize_t)(int32_t)left != (Py_ssize_t)left + || (Py_ssize_t)(int32_t)right != (Py_ssize_t)right; +#endif } static inline bool CPyTagged_MaybeFloorDivideFault(CPyTagged left, CPyTagged right) { diff --git a/mypyc/test-data/run-integers.test b/mypyc/test-data/run-integers.test index 524bd283d24f7..48325bfdc1a67 100644 --- a/mypyc/test-data/run-integers.test +++ b/mypyc/test-data/run-integers.test @@ -78,6 +78,38 @@ except ZeroDivisionError: else: assert False, "Expected ZeroDivisionError" +[case testIntMultiplySigns] +def multiply(x: int, y: int) -> int: + return x * y + +def multiply_by_constants(x: int) -> tuple[int, int, int, int, int, int, int, int]: + return ( + x * 3, x * -3, -3 * x, x * (2**14 - 1), x * -(2**14), x * (2**30 - 1), x * -(2**30), + x * 2**30, + ) + +[file driver.py] +from native import multiply, multiply_by_constants + +# Two ints are multiplied inline if both are in [-2**14, 2**14) (32-bit) or [-2**30, 2**30) +# (64-bit). Short ints are in [-2**30, 2**30) or [-2**62, 2**62). +magnitudes = ( + 0, 1, 3, 2**14 - 1, 2**14, 2**15, 2**29, 2**30 - 1, 2**30, 2**31 - 1, 2**31, 2**32, + 2**61, 2**62 - 1, 2**62, 10**20, +) +for x in magnitudes: + for y in magnitudes: + for sx in (1, -1): + for sy in (1, -1): + assert multiply(sx * x, sy * y) == sx * x * sy * y, (sx * x, sy * y) +for x in magnitudes: + for v in (x, -x): + expected = ( + v * 3, v * -3, -3 * v, v * (2**14 - 1), v * -(2**14), v * (2**30 - 1), v * -(2**30), + v * 2**30, + ) + assert multiply_by_constants(v) == expected, v + [case testBigIntLiteral] def big_int() -> None: a_62_bit = 4611686018427387902