Skip to content

[mypyc] feat: new primitive for int.bit_length #19673

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions mypyc/lib-rt/CPy.h
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ CPyTagged CPyTagged_Remainder_(CPyTagged left, CPyTagged right);
CPyTagged CPyTagged_BitwiseLongOp_(CPyTagged a, CPyTagged b, char op);
CPyTagged CPyTagged_Rshift_(CPyTagged left, CPyTagged right);
CPyTagged CPyTagged_Lshift_(CPyTagged left, CPyTagged right);
CPyTagged CPyTagged_BitLength(CPyTagged self);

PyObject *CPyTagged_Str(CPyTagged n);
CPyTagged CPyTagged_FromFloat(double f);
Expand Down
53 changes: 53 additions & 0 deletions mypyc/lib-rt/int_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@
#define CPyLong_FromSsize_t PyLong_FromSsize_t
#endif

#if defined(__GNUC__) || defined(__clang__)
# if defined(__x86_64__) || defined(_M_X64) || defined(__aarch64__) || (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 8)
# define CPY_CLZ(x) __builtin_clzll((unsigned long long)(x))
# define CPY_BITS 64
# else
# define CPY_CLZ(x) __builtin_clz((unsigned int)(x))
# define CPY_BITS 32
# endif
#endif


CPyTagged CPyTagged_FromSsize_t(Py_ssize_t value) {
// We use a Python object if the value shifted left by 1 is too
// large for Py_ssize_t
Expand Down Expand Up @@ -581,3 +592,45 @@ double CPyTagged_TrueDivide(CPyTagged x, CPyTagged y) {
}
return 1.0;
}

// int.bit_length()
CPyTagged CPyTagged_BitLength(CPyTagged self) {
// Handle zero
if (self == 0) {
return 0;
}

// Fast path for small (tagged) ints
if (CPyTagged_CheckShort(self)) {
Py_ssize_t val = CPyTagged_ShortAsSsize_t(self);
Py_ssize_t absval = val < 0 ? -val : val;
int bits = 0;
if (absval) {
#if defined(__GNUC__) || defined(__clang__)
bits = (int)(CPY_BITS - CPY_CLZ(absval));
#else
// Fallback to loop if no builtin
while (absval) {
absval >>= 1;
bits++;
}
#endif
}
return bits << 1;
}

// Slow path for big ints
PyObject *pyint = CPyTagged_StealAsObject(self);
Copy link
Contributor Author

@BobTheBuidler BobTheBuidler Aug 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need this PyLong_Check?

if (!PyLong_Check(pyint)) {
Py_DECREF(pyint);
PyErr_SetString(PyExc_TypeError, "self must be int");
return CPY_INT_TAG;
}
int bits = _PyLong_NumBits(pyint);
Py_DECREF(pyint);
if (bits < 0) {
// _PyLong_NumBits sets an error on failure
return CPY_INT_TAG;
}
return bits << 1;
}
18 changes: 17 additions & 1 deletion mypyc/primitives/int_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,14 @@
str_rprimitive,
void_rtype,
)
from mypyc.primitives.registry import binary_op, custom_op, function_op, load_address_op, unary_op
from mypyc.primitives.registry import (
binary_op,
custom_op,
function_op,
load_address_op,
method_op,
unary_op,
)

# Constructors for builtins.int and native int types have the same behavior. In
# interpreted mode, native int types are just aliases to 'int'.
Expand Down Expand Up @@ -305,3 +312,12 @@ def int_unary_op(name: str, c_function_name: str) -> PrimitiveDescription:
c_function_name="PyLong_Check",
error_kind=ERR_NEVER,
)

# int.bit_length()
method_op(
name="bit_length",
arg_types=[int_rprimitive],
return_type=int_rprimitive,
c_function_name="CPyTagged_BitLength",
error_kind=ERR_MAGIC,
)
1 change: 1 addition & 0 deletions mypyc/test-data/fixtures/ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ def __lt__(self, n: int) -> bool: pass
def __gt__(self, n: int) -> bool: pass
def __le__(self, n: int) -> bool: pass
def __ge__(self, n: int) -> bool: pass
def bit_length(self) -> int: pass

class str:
@overload
Expand Down
10 changes: 10 additions & 0 deletions mypyc/test-data/irbuild-int.test
Original file line number Diff line number Diff line change
Expand Up @@ -210,3 +210,13 @@ L0:
r0 = CPyTagged_Invert(n)
x = r0
return x

[case testIntBitLength]
def f(x: int) -> int:
return x.bit_length()
[out]
def f(x):
x, r0 :: int
L0:
r0 = CPyTagged_BitLength(x)
return r0
16 changes: 16 additions & 0 deletions mypyc/test-data/run-integers.test
Original file line number Diff line number Diff line change
Expand Up @@ -572,3 +572,19 @@ class subc(int):
[file userdefinedint.py]
class int:
pass

[case testBitLength]
def bit_length(n: int) -> int:
return n.bit_length()
def test_bit_length() -> None:
assert bit_length(0) == 0
assert bit_length(1) == 1
assert bit_length(255) == 8
assert bit_length(256) == 9
assert bit_length(-256) == 9
# Large positive int
assert bit_length(1 << 70) == 71
# Large negative int
assert bit_length(-(1 << 70)) == 71
# Large int with all bits set
assert bit_length((1 << 100) - 1) == 100
Loading