From 11b420c0df7be8367e97fbe0b519d59e1d48c4a1 Mon Sep 17 00:00:00 2001 From: Kevin Kannammalil Date: Thu, 26 Nov 2026 18:46:53 -0500 Subject: [PATCH 1/2] optimize single argument round() --- mypyc/doc/float_operations.rst | 1 + mypyc/doc/int_operations.rst | 1 + mypyc/irbuild/specialize.py | 29 +++++++++++++++++++++++++++++ mypyc/lib-rt/CPy.h | 1 + mypyc/lib-rt/float_ops.c | 10 ++++++++++ mypyc/primitives/float_ops.py | 9 +++++++++ mypyc/test-data/fixtures/ir.py | 6 ++++++ 7 files changed, 57 insertions(+) diff --git a/mypyc/doc/float_operations.rst b/mypyc/doc/float_operations.rst index 0f66ec3b64a0c..d50359420ce83 100644 --- a/mypyc/doc/float_operations.rst +++ b/mypyc/doc/float_operations.rst @@ -47,6 +47,7 @@ Functions * ``u16(f)`` (convert to 16-bit unsigned integer) * ``u8(f)`` (convert to 8-bit unsigned integer) * ``abs(f)`` +* ``round(f)`` (with a single argument) * ``math.sin(f)`` * ``math.cos(f)`` * ``math.tan(f)`` diff --git a/mypyc/doc/int_operations.rst b/mypyc/doc/int_operations.rst index 92f9b161cb978..724b376474048 100644 --- a/mypyc/doc/int_operations.rst +++ b/mypyc/doc/int_operations.rst @@ -302,6 +302,7 @@ Functions --------- * ``abs(n)`` +* ``round(n)`` (``int`` only, with a single argument) Attributes ---------- diff --git a/mypyc/irbuild/specialize.py b/mypyc/irbuild/specialize.py index bbafe29d9e4f1..310b982e9577b 100644 --- a/mypyc/irbuild/specialize.py +++ b/mypyc/irbuild/specialize.py @@ -425,6 +425,35 @@ def translate_abs(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value return None +@specialize_function("builtins.round") +def translate_round(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None: + if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]: + arg_type = builder.node_type(expr.args[0]) + if is_int_rprimitive(arg_type): + arg = builder.accept(expr.args[0]) + # A long int can be an instance of an int subclass that overrides __round__. + arg_class = builder.primitive_op(type_of_int_op, [arg], expr.line) + int_class = builder.load_builtin("builtins.int", expr.line) + assert int_class is not None + is_exact_int = builder.translate_is_op(arg_class, int_class, "is", expr.line) + exact_block, subclass_block, next_block = BasicBlock(), BasicBlock(), BasicBlock() + result = Register(int_rprimitive) + builder.add_bool_branch(is_exact_int, exact_block, subclass_block) + + builder.activate_block(exact_block) + builder.assign(result, arg, expr.line) + builder.goto(next_block) + + builder.activate_block(subclass_block) + rounded = builder.call_refexpr_with_args(expr, callee, [arg]) + builder.assign(result, builder.coerce(rounded, int_rprimitive, expr.line), expr.line) + builder.goto(next_block) + + builder.activate_block(next_block) + return result + return None + + @specialize_function("builtins.len") def translate_len(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None: if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]: diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index 1e3874899d170..971499eaa00f1 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -812,6 +812,7 @@ double CPyFloat_Exp(double x); double CPyFloat_Log(double x); CPyTagged CPyFloat_Floor(double x); CPyTagged CPyFloat_Ceil(double x); +CPyTagged CPyFloat_Round(double x); double CPyFloat_FromTagged(CPyTagged x); bool CPyFloat_IsInf(double x); bool CPyFloat_IsNaN(double x); diff --git a/mypyc/lib-rt/float_ops.c b/mypyc/lib-rt/float_ops.c index 4210b84f33a98..a286ad85416aa 100644 --- a/mypyc/lib-rt/float_ops.c +++ b/mypyc/lib-rt/float_ops.c @@ -129,6 +129,16 @@ CPyTagged CPyFloat_Ceil(double x) { return CPyTagged_FromFloat(v); } +// Adapted from CPython 3.14, Objects/floatobject.c +CPyTagged CPyFloat_Round(double x) { + double rounded = round(x); + if (fabs(x - rounded) == 0.5) { + // Halfway case: round to even + rounded = 2.0 * round(x / 2.0); + } + return CPyTagged_FromFloat(rounded); +} + bool CPyFloat_IsInf(double x) { return isinf(x) != 0; } diff --git a/mypyc/primitives/float_ops.py b/mypyc/primitives/float_ops.py index 26d7127fe28fe..9cd164160a1a7 100644 --- a/mypyc/primitives/float_ops.py +++ b/mypyc/primitives/float_ops.py @@ -51,6 +51,15 @@ error_kind=ERR_NEVER, ) +# round(float) +function_op( + name="builtins.round", + arg_types=[float_rprimitive], + return_type=int_rprimitive, + c_function_name="CPyFloat_Round", + error_kind=ERR_MAGIC, +) + # math.sin(float) function_op( name="math.sin", diff --git a/mypyc/test-data/fixtures/ir.py b/mypyc/test-data/fixtures/ir.py index 86d5baa1a983a..9fda3c8ab92b3 100644 --- a/mypyc/test-data/fixtures/ir.py +++ b/mypyc/test-data/fixtures/ir.py @@ -449,6 +449,12 @@ def zip(x: Iterable[_T], y: Iterable[_S], z: Iterable[_V]) -> Iterator[Tuple[_T, def eval(e: str) -> Any: ... def abs(x: __SupportsAbs[_T]) -> _T: ... @overload +def round(number: int, ndigits: int | None = None) -> int: ... +@overload +def round(number: float, ndigits: None = None) -> int: ... +@overload +def round(number: float, ndigits: int) -> float: ... +@overload def divmod(x: __SupportsDivMod[T_contra, T_co], y: T_contra) -> T_co: ... @overload def divmod(x: T_contra, y: __SupportsRDivMod[T_contra, T_co]) -> T_co: ... From 7ba09b2f7212ff068883272f83687872a356097f Mon Sep 17 00:00:00 2001 From: Kevin Kannammalil Date: Thu, 26 Nov 2026 18:51:07 -0500 Subject: [PATCH 2/2] add tests --- mypyc/test-data/irbuild-float.test | 118 +++++++++++++++++++++++++++++ mypyc/test-data/run-floats.test | 115 ++++++++++++++++++++++++++++ 2 files changed, 233 insertions(+) diff --git a/mypyc/test-data/irbuild-float.test b/mypyc/test-data/irbuild-float.test index eda91504a2c6b..153880142c775 100644 --- a/mypyc/test-data/irbuild-float.test +++ b/mypyc/test-data/irbuild-float.test @@ -623,3 +623,121 @@ L0: r3 = cast(union[int, float], r2) r4 = (r1, r3) return r4 + +[case testFloatRound] +def f(x: float) -> int: + return round(x) +def g(n: int) -> int: + return round(n) +def h(x: float) -> float: + return round(x, 2) +[out] +def f(x): + x :: float + r0 :: int +L0: + r0 = CPyFloat_Round(x) + return r0 +def g(n): + n :: int + r0, r1 :: object + r2 :: bit + r3 :: int + r4 :: object + r5 :: str + r6, r7 :: object + r8 :: object[1] + r9 :: object_ptr + r10 :: object + r11 :: int +L0: + r0 = CPyTagged_Type(n) + r1 = load_address PyLong_Type + r2 = r0 == r1 + if r2 goto L1 else goto L2 :: bool +L1: + r3 = n + goto L3 +L2: + r4 = builtins :: module + r5 = 'round' + r6 = CPyObject_GetAttr(r4, r5) + r7 = box(int, n) + r8 = [r7] + r9 = load_address r8 + r10 = PyObject_Vectorcall(r6, r9, 1, 0) + keep_alive r7 + r11 = unbox(int, r10) + r3 = r11 +L3: + return r3 +def h(x): + x :: float + r0 :: object + r1 :: str + r2, r3, r4 :: object + r5 :: object[2] + r6 :: object_ptr + r7 :: object + r8 :: float +L0: + r0 = builtins :: module + r1 = 'round' + r2 = CPyObject_GetAttr(r0, r1) + r3 = box(float, x) + r4 = object 2 + r5 = [r3, r4] + r6 = load_address r5 + r7 = PyObject_Vectorcall(r2, r6, 2, 0) + keep_alive r3, r4 + r8 = unbox(float, r7) + return r8 + +[case testIntRoundDigits] +def digits(n: int, ndigits: int) -> int: + return round(n, ndigits) +def optional_digits(n: int, ndigits: int | None) -> int: + return round(n, ndigits) +[out] +def digits(n, ndigits): + n, ndigits :: int + r0 :: object + r1 :: str + r2, r3, r4 :: object + r5 :: object[2] + r6 :: object_ptr + r7 :: object + r8 :: int +L0: + r0 = builtins :: module + r1 = 'round' + r2 = CPyObject_GetAttr(r0, r1) + r3 = box(int, n) + r4 = box(int, ndigits) + r5 = [r3, r4] + r6 = load_address r5 + r7 = PyObject_Vectorcall(r2, r6, 2, 0) + keep_alive r3, r4 + r8 = unbox(int, r7) + return r8 +def optional_digits(n, ndigits): + n :: int + ndigits :: union[int, None] + r0 :: object + r1 :: str + r2, r3 :: object + r4 :: object[2] + r5 :: object_ptr + r6 :: object + r7 :: int +L0: + r0 = builtins :: module + r1 = 'round' + r2 = CPyObject_GetAttr(r0, r1) + r3 = box(int, n) + r4 = [r3, ndigits] + r5 = load_address r4 + r6 = PyObject_Vectorcall(r2, r5, 2, 0) + keep_alive r3, ndigits + r7 = unbox(int, r6) + return r7 diff --git a/mypyc/test-data/run-floats.test b/mypyc/test-data/run-floats.test index 11e23770a0f90..6767fa994d7aa 100644 --- a/mypyc/test-data/run-floats.test +++ b/mypyc/test-data/run-floats.test @@ -172,6 +172,80 @@ def test_explicit_conversion_from_int() -> None: for x in a: assert repr(float(x)) == repr(float_any(x)) +def round_float(x: float) -> int: + return round(x) + +def round_int(n: int) -> int: + return round(n) + +def test_round_float() -> None: + # Use a dynamic reference to avoid specializing round(). + round_any: Any = round + + # Halfway cases round to even + assert round_float(0.5) == 0 + assert round_float(1.5) == 2 + assert round_float(2.5) == 2 + assert round_float(3.5) == 4 + assert round_float(-0.5) == 0 + assert round_float(-1.5) == -2 + assert round_float(-2.5) == -2 + assert round_float(-3.5) == -4 + + assert round_float(0.49999999999999994) == 0 + assert round_float(0.5000000000000001) == 1 + assert round_float(-0.49999999999999994) == 0 + assert round_float(-0.5000000000000001) == -1 + + assert round_float(-0.0) == 0 + assert round_float(1.4) == 1 + assert round_float(-1.6) == -2 + + assert round_float(2.0**51 + 0.5) == 2**51 + assert round_float(2.0**51 + 1.5) == 2**51 + 2 + assert round_float(-2.0**51 - 0.5) == -2**51 + assert round_float(-2.0**51 - 1.5) == -2**51 - 2 + assert round_float(2.0**52 - 0.5) == 2**52 + assert round_float(2.0**52 + 1.0) == 2**52 + 1 + + # Short int limits on 32-bit platforms + assert round_float(2.0**30 - 1.0) == 2**30 - 1 + assert round_float(2.0**30 - 0.5) == 2**30 + assert round_float(-2.0**30 - 0.5) == -2**30 + assert round_float(-2.0**30 - 1.0) == -2**30 - 1 + + assert round_float(2.0**62) == 2**62 + assert round_float(-2.0**62) == -2**62 + assert round_float(1e300) == int(1e300) + assert round_float(-1e300) == int(-1e300) + + for x in float_vals: + if math.isinf(x): + with assertRaises(OverflowError, "cannot convert float infinity to integer"): + round_float(x) + elif math.isnan(x): + with assertRaises(ValueError, "cannot convert float NaN to integer"): + round_float(x) + else: + assert round_float(x) == round_any(x), x + assert type(round_float(x)) is int + + for n in range(-1000, 1000): + x = n / 8 + assert round_float(x) == round_any(x), x + + # Two-argument round() still works (generic implementation) + y = identity(2.675) + assert round(y, 2) == 2.67 + assert round(y, None) == 3 + +def test_round_int() -> None: + for n in [0, 1, -1, 2**62, -2**62, 2**63, -2**100, 10**400]: + assert round_int(n) == n + for b in (True, False): + assert round_int(b) == int(b) + assert type(round_int(b)) is int + def test_explicit_conversion_to_int() -> None: int_any: Any = int for x in float_vals: @@ -726,3 +800,44 @@ class BadIntReal(int): @property def real(self) -> Any: return "x" + +[case testRoundIntSubclass] +def round_int(n: int) -> int: + return round(n) + +def round_pop(values: list[int]) -> int: + return round(values.pop()) + +[file driver.py] +from native import round_int, round_pop +from testutil import assertRaises + +class PlainInt(int): + pass + +class OverrideRound(int): + def __round__(self): + return 42 + + def __getattribute__(self, name): + if name == "__round__": + raise AssertionError("round must use special method lookup") + return super().__getattribute__(name) + +class RaisingRound(int): + def __round__(self): + raise ValueError("custom round failed") + +# Large integer subclasses stay boxed and must retain their __round__ behavior. +big = 2**100 +assert round_int(OverrideRound(big)) == 42 +assert round_int(PlainInt(big)) == big +assert type(round_int(PlainInt(big))) is int +with assertRaises(ValueError, "custom round failed"): + round_int(RaisingRound(big)) + +# The argument is evaluated exactly once on both sides of the type guard. +for value, expected in [(3, 3), (big, big), (OverrideRound(big), 42)]: + values = [value] + assert round_pop(values) == expected + assert values == []