Skip to content

Commit 71009cb

Browse files
authored
GH-131798: Narrow the result type of _BINARY_OP_SUBSCR_STR_INT to str in the JIT (GH-132153)
1 parent 933c665 commit 71009cb

File tree

4 files changed

+27
-1
lines changed

4 files changed

+27
-1
lines changed

Diff for: Lib/test/test_capi/test_opt.py

+20
Original file line numberDiff line numberDiff line change
@@ -1646,6 +1646,26 @@ def f(n):
16461646
self.assertIn("_TO_BOOL_STR", uops)
16471647
self.assertNotIn("_GUARD_TOS_UNICODE", uops)
16481648

1649+
def test_binary_subcsr_str_int_narrows_to_str(self):
1650+
def testfunc(n):
1651+
x = []
1652+
s = "foo"
1653+
for _ in range(n):
1654+
y = s[0] # _BINARY_OP_SUBSCR_STR_INT
1655+
z = "bar" + y # (_GUARD_TOS_UNICODE) + _BINARY_OP_ADD_UNICODE
1656+
x.append(z)
1657+
return x
1658+
1659+
res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
1660+
self.assertEqual(res, ["barf"] * TIER2_THRESHOLD)
1661+
self.assertIsNotNone(ex)
1662+
uops = get_opnames(ex)
1663+
self.assertIn("_BINARY_OP_SUBSCR_STR_INT", uops)
1664+
# _BINARY_OP_SUBSCR_STR_INT narrows the result to 'str' so
1665+
# the unicode guard before _BINARY_OP_ADD_UNICODE is removed.
1666+
self.assertNotIn("_GUARD_TOS_UNICODE", uops)
1667+
self.assertIn("_BINARY_OP_ADD_UNICODE", uops)
1668+
16491669

16501670
def global_identity(x):
16511671
return x
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Allow the JIT to remove unicode guards after ``_BINARY_OP_SUBSCR_STR_INT``
2+
by setting the return type to string.

Diff for: Python/optimizer_bytecodes.c

+4
Original file line numberDiff line numberDiff line change
@@ -366,6 +366,10 @@ dummy_func(void) {
366366
ctx->done = true;
367367
}
368368

369+
op(_BINARY_OP_SUBSCR_STR_INT, (left, right -- res)) {
370+
res = sym_new_type(ctx, &PyUnicode_Type);
371+
}
372+
369373
op(_TO_BOOL, (value -- res)) {
370374
int already_bool = optimize_to_bool(this_instr, ctx, value, &res);
371375
if (!already_bool) {

Diff for: Python/optimizer_cases.c.h

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

0 commit comments

Comments
 (0)