Skip to content

Commit 85bc489

Browse files
authored
GH-131798: Narrow the result of _CONTAINS_OP_SET to bool in the JIT (GH-132057)
1 parent ad6a032 commit 85bc489

File tree

4 files changed

+35
-3
lines changed

4 files changed

+35
-3
lines changed

Lib/test/test_capi/test_opt.py

+26
Original file line numberDiff line numberDiff line change
@@ -1603,6 +1603,32 @@ def testfunc(n):
16031603
self.assertNotIn("_COMPARE_OP_INT", uops)
16041604
self.assertIn("_POP_TWO_LOAD_CONST_INLINE_BORROW", uops)
16051605

1606+
def test_to_bool_bool_contains_op_set(self):
1607+
"""
1608+
Test that _TO_BOOL_BOOL is removed from code like:
1609+
1610+
res = foo in some_set
1611+
if res:
1612+
....
1613+
1614+
"""
1615+
def testfunc(n):
1616+
x = 0
1617+
s = {1, 2, 3}
1618+
for _ in range(n):
1619+
a = 2
1620+
in_set = a in s
1621+
if in_set:
1622+
x += 1
1623+
return x
1624+
1625+
res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
1626+
self.assertEqual(res, TIER2_THRESHOLD)
1627+
self.assertIsNotNone(ex)
1628+
uops = get_opnames(ex)
1629+
self.assertIn("_CONTAINS_OP_SET", uops)
1630+
self.assertNotIn("_TO_BOOL_BOOL", uops)
1631+
16061632
def test_remove_guard_for_known_type_str(self):
16071633
def f(n):
16081634
for i in range(n):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Allow the JIT to remove an extra ``_TO_BOOL_BOOL`` instruction after
2+
``_CONTAINS_OP_SET`` by setting the return type to bool.

Python/optimizer_bytecodes.c

+4
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,10 @@ dummy_func(void) {
477477
res = sym_new_type(ctx, &PyBool_Type);
478478
}
479479

480+
op(_CONTAINS_OP_SET, (left, right -- res)) {
481+
res = sym_new_type(ctx, &PyBool_Type);
482+
}
483+
480484
op(_LOAD_CONST, (-- value)) {
481485
PyObject *val = PyTuple_GET_ITEM(co->co_consts, this_instr->oparg);
482486
int opcode = _Py_IsImmortal(val) ? _LOAD_CONST_INLINE_BORROW : _LOAD_CONST_INLINE;

Python/optimizer_cases.c.h

+3-3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)