gh-148083: Constant-fold _CONTAINS_OP_SET for frozenset (gh-148084)

This commit is contained in:
Donghee Na 2026-04-04 21:32:12 +09:00 committed by GitHub
parent fe9befc1ca
commit 289f19adb0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 70 additions and 2 deletions

View file

@ -30,6 +30,7 @@
#include "pycore_unicodeobject.h"
#include "pycore_ceval.h"
#include "pycore_floatobject.h"
#include "pycore_setobject.h"
#include <stdarg.h>
#include <stdbool.h>

View file

@ -706,6 +706,9 @@ dummy_func(void) {
b = sym_new_type(ctx, &PyBool_Type);
l = left;
r = right;
if (sym_matches_type(right, &PyFrozenSet_Type)) {
REPLACE_OPCODE_IF_EVALUATES_PURE(left, right, b);
}
}
op(_CONTAINS_OP_DICT, (left, right -- b, l, r)) {

View file

@ -2993,6 +2993,50 @@
b = sym_new_type(ctx, &PyBool_Type);
l = left;
r = right;
if (sym_matches_type(right, &PyFrozenSet_Type)) {
if (
sym_is_safe_const(ctx, left) &&
sym_is_safe_const(ctx, right)
) {
JitOptRef left_sym = left;
JitOptRef right_sym = right;
_PyStackRef left = sym_get_const_as_stackref(ctx, left_sym);
_PyStackRef right = sym_get_const_as_stackref(ctx, right_sym);
_PyStackRef b_stackref;
_PyStackRef l_stackref;
_PyStackRef r_stackref;
/* Start of uop copied from bytecodes for constant evaluation */
PyObject *left_o = PyStackRef_AsPyObjectBorrow(left);
PyObject *right_o = PyStackRef_AsPyObjectBorrow(right);
assert(PyAnySet_CheckExact(right_o));
STAT_INC(CONTAINS_OP, hit);
int res = _PySet_Contains((PySetObject *)right_o, left_o);
if (res < 0) {
JUMP_TO_LABEL(error);
}
b_stackref = (res ^ oparg) ? PyStackRef_True : PyStackRef_False;
l_stackref = left;
r_stackref = right;
/* End of uop copied from bytecodes for constant evaluation */
(void)l_stackref;
(void)r_stackref;
b = sym_new_const_steal(ctx, PyStackRef_AsPyObjectSteal(b_stackref));
if (sym_is_const(ctx, b)) {
PyObject *result = sym_get_const(ctx, b);
if (_Py_IsImmortal(result)) {
// Replace with _INSERT_2_LOAD_CONST_INLINE_BORROW since we have two inputs and an immortal result
ADD_OP(_INSERT_2_LOAD_CONST_INLINE_BORROW, 0, (uintptr_t)result);
}
}
CHECK_STACK_BOUNDS(1);
stack_pointer[-2] = b;
stack_pointer[-1] = l;
stack_pointer[0] = r;
stack_pointer += 1;
ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__);
break;
}
}
CHECK_STACK_BOUNDS(1);
stack_pointer[-2] = b;
stack_pointer[-1] = l;

View file

@ -283,7 +283,8 @@ _Py_uop_sym_is_safe_const(JitOptContext *ctx, JitOptRef sym)
(typ == &PyFloat_Type) ||
(typ == &_PyNone_Type) ||
(typ == &PyBool_Type) ||
(typ == &PyFrozenDict_Type);
(typ == &PyFrozenDict_Type) ||
(typ == &PyFrozenSet_Type);
}
void