Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
More optimizations
  • Loading branch information
tomasr8 committed Apr 24, 2025
commit 1ccfa7f32866b8ab561c45e84dac9d3216e9d079
21 changes: 21 additions & 0 deletions Lib/test/test_capi/test_opt.py
Original file line number Diff line number Diff line change
Expand Up @@ -1832,6 +1832,27 @@ def testfunc(n):
self.assertIn("_BINARY_OP_ADD_UNICODE", uops)
self.assertNotIn("_GUARD_NOS_UNICODE", uops)
Comment thread
tomasr8 marked this conversation as resolved.

def test_call_str_1_result_is_const_for_str_input(self):
# Test a special case where the argument of str(arg)
# is known to be a string. The information about the
# argument being a string should be propagated to the
# result of str(arg).
def testfunc(n):
x = 0
for _ in range(n):
y = str('foo') # string argument
if y: # _TO_BOOL_STR + _GUARD_IS_TRUE_POP are removed
x += 1
return x

res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
self.assertEqual(res, TIER2_THRESHOLD)
self.assertIsNotNone(ex)
uops = get_opnames(ex)
self.assertIn("_CALL_STR_1", uops)
self.assertNotIn("_TO_BOOL_STR", uops)
self.assertNotIn("_GUARD_IS_TRUE_POP", uops)


def global_identity(x):
return x
Expand Down
11 changes: 9 additions & 2 deletions Python/optimizer_bytecodes.c
Original file line number Diff line number Diff line change
Expand Up @@ -855,8 +855,15 @@ dummy_func(void) {
}
}

op(_CALL_STR_1, (unused, unused, unused -- res)) {
res = sym_new_type(ctx, &PyUnicode_Type);
op(_CALL_STR_1, (unused, unused, arg -- res)) {
if (sym_matches_type(arg, &PyUnicode_Type)) {
// e.g. str('foo') or str(foo) where foo is known to be a string
PyObject *value = sym_get_const(ctx, arg);
res = sym_new_const(ctx, value);
Comment thread
tomasr8 marked this conversation as resolved.
Outdated
}
Comment on lines +859 to +862
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an optimization that Brandt suggested. When in str(foo), foo is known to be a string, we can propagate it to the output. I also added a test for this case.

else {
res = sym_new_type(ctx, &PyUnicode_Type);
}
}

op(_GUARD_IS_TRUE_POP, (flag -- )) {
Expand Down
10 changes: 9 additions & 1 deletion Python/optimizer_cases.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading