gh-144140: Optimize len for string constants in optimizer (GH-144142)

This commit is contained in:
Yi Yang 2026-01-25 00:09:29 +08:00 committed by GitHub
parent 27246c3482
commit 979d92fefc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 53 additions and 10 deletions

View file

@ -1455,15 +1455,28 @@ dummy_func(void) {
op(_CALL_LEN, (callable, null, arg -- res, a, c)) {
res = sym_new_type(ctx, &PyLong_Type);
Py_ssize_t tuple_length = sym_tuple_length(arg);
if (tuple_length >= 0) {
PyObject *temp = PyLong_FromSsize_t(tuple_length);
Py_ssize_t length = sym_tuple_length(arg);
// Not a tuple, check if it's a const string
if (length < 0 && sym_is_const(ctx, arg)) {
PyObject *const_val = sym_get_const(ctx, arg);
if (const_val != NULL) {
if (PyUnicode_CheckExact(const_val)) {
length = PyUnicode_GET_LENGTH(const_val);
}
else if (PyBytes_CheckExact(const_val)) {
length = PyBytes_GET_SIZE(const_val);
}
}
}
if (length >= 0) {
PyObject *temp = PyLong_FromSsize_t(length);
if (temp == NULL) {
goto error;
}
if (_Py_IsImmortal(temp)) {
ADD_OP(_SHUFFLE_3_LOAD_CONST_INLINE_BORROW,
0, (uintptr_t)temp);
ADD_OP(_SHUFFLE_3_LOAD_CONST_INLINE_BORROW, 0, (uintptr_t)temp);
}
res = sym_new_const(ctx, temp);
Py_DECREF(temp);