Skip to content

Commit c3cd21c

Browse files
committed
Make _BINARY_OP_SUBSCR_TUPLE_INT smarter
1 parent 7f02ded commit c3cd21c

File tree

3 files changed

+46
-1
lines changed

3 files changed

+46
-1
lines changed

Lib/test/test_capi/test_opt.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1923,6 +1923,23 @@ def testfunc(n):
19231923
self.assertNotIn("_GUARD_TOS_INT", uops)
19241924
self.assertIn("_CALL_LEN", uops)
19251925

1926+
def test_binary_op_subscr_tuple_int(self):
1927+
def testfunc(n):
1928+
x = 0
1929+
for _ in range(n):
1930+
y = (1, 2)
1931+
if y[0] == 1: # _COMPARE_OP_INT + _GUARD_IS_TRUE_POP are removed
1932+
x += 1
1933+
return x
1934+
1935+
res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
1936+
self.assertEqual(res, TIER2_THRESHOLD)
1937+
self.assertIsNotNone(ex)
1938+
uops = get_opnames(ex)
1939+
self.assertIn("_BINARY_OP_SUBSCR_TUPLE_INT", uops)
1940+
self.assertNotIn("_COMPARE_OP_INT", uops)
1941+
self.assertNotIn("_GUARD_IS_TRUE_POP", uops)
1942+
19261943

19271944
def global_identity(x):
19281945
return x

Python/optimizer_bytecodes.c

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,20 @@ dummy_func(void) {
370370
res = sym_new_type(ctx, &PyUnicode_Type);
371371
}
372372

373+
op(_BINARY_OP_SUBSCR_TUPLE_INT, (left, right -- res)) {
374+
assert(sym_matches_type(left, &PyTuple_Type));
375+
if (sym_is_const(ctx, right)) {
376+
assert(PyLong_CheckExact(sym_get_const(ctx, right)));
377+
long index = PyLong_AsLong(sym_get_const(ctx, right));
378+
assert(index >= 0);
379+
assert(index < sym_tuple_length(left));
380+
res = sym_tuple_getitem(ctx, left, index);
381+
}
382+
else {
383+
res = sym_new_not_null(ctx);
384+
}
385+
}
386+
373387
op(_TO_BOOL, (value -- res)) {
374388
int already_bool = optimize_to_bool(this_instr, ctx, value, &res);
375389
if (!already_bool) {

Python/optimizer_cases.c.h

Lines changed: 15 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)