Skip to content

Commit 1ccfa7f

Browse files
committed
More optimizations
1 parent 04b236b commit 1ccfa7f

File tree

3 files changed

+39
-3
lines changed

3 files changed

+39
-3
lines changed

Lib/test/test_capi/test_opt.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1832,6 +1832,27 @@ def testfunc(n):
18321832
self.assertIn("_BINARY_OP_ADD_UNICODE", uops)
18331833
self.assertNotIn("_GUARD_NOS_UNICODE", uops)
18341834

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

18361857
def global_identity(x):
18371858
return x

Python/optimizer_bytecodes.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -855,8 +855,15 @@ dummy_func(void) {
855855
}
856856
}
857857

858-
op(_CALL_STR_1, (unused, unused, unused -- res)) {
859-
res = sym_new_type(ctx, &PyUnicode_Type);
858+
op(_CALL_STR_1, (unused, unused, arg -- res)) {
859+
if (sym_matches_type(arg, &PyUnicode_Type)) {
860+
// e.g. str('foo') or str(foo) where foo is known to be a string
861+
PyObject *value = sym_get_const(ctx, arg);
862+
res = sym_new_const(ctx, value);
863+
}
864+
else {
865+
res = sym_new_type(ctx, &PyUnicode_Type);
866+
}
860867
}
861868

862869
op(_GUARD_IS_TRUE_POP, (flag -- )) {

Python/optimizer_cases.c.h

Lines changed: 9 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)