Skip to content

Commit 0545930

Browse files
committed
Optimize case when input is already a tuple
1 parent c657bb3 commit 0545930

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed

Lib/test/test_capi/test_opt.py

+23
Original file line numberDiff line numberDiff line change
@@ -1832,6 +1832,29 @@ def testfunc(n):
18321832
self.assertIn("_BINARY_OP_SUBSCR_TUPLE_INT", uops)
18331833
self.assertNotIn("_GUARD_NOS_TUPLE", uops)
18341834

1835+
def test_call_tuple_1_result_propagates_for_tuple_input(self):
1836+
# Test a special case where the argument of tuple(arg)
1837+
# is known to be a tuple. The information about the
1838+
# argument being a tuple should be propagated to the
1839+
# result of tuple(arg).
1840+
def testfunc(n):
1841+
x = 0
1842+
for _ in range(n):
1843+
y = tuple((1, 2)) # tuple argument
1844+
a, _ = y # _UNPACK_SEQUENCE_TWO_TUPLE
1845+
if a == 1: # _COMPARE_OP_INT + _GUARD_IS_TRUE_POP are removed
1846+
x += 1
1847+
return x
1848+
1849+
res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
1850+
self.assertEqual(res, TIER2_THRESHOLD)
1851+
self.assertIsNotNone(ex)
1852+
uops = get_opnames(ex)
1853+
self.assertIn("_CALL_TUPLE_1", uops)
1854+
self.assertIn("_UNPACK_SEQUENCE_TWO_TUPLE", uops)
1855+
self.assertNotIn("_COMPARE_OP_INT", uops)
1856+
self.assertNotIn("_GUARD_IS_TRUE_POP", uops)
1857+
18351858

18361859
def global_identity(x):
18371860
return x

Python/optimizer_bytecodes.c

+7-1
Original file line numberDiff line numberDiff line change
@@ -958,7 +958,13 @@ dummy_func(void) {
958958
}
959959

960960
op(_CALL_TUPLE_1, (callable, null, arg -- res)) {
961-
res = sym_new_type(ctx, &PyTuple_Type);
961+
if (sym_matches_type(arg, &PyTuple_Type)) {
962+
// e.g. tuple((1, 2)) or tuple(foo) where foo is known to be a tuple
963+
res = arg;
964+
}
965+
else {
966+
res = sym_new_type(ctx, &PyTuple_Type);
967+
}
962968
}
963969

964970
op(_GUARD_TOS_LIST, (tos -- tos)) {

Python/optimizer_cases.c.h

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

0 commit comments

Comments
 (0)