Skip to content

Commit 786fa89

Browse files
Constant fold LOAD_FAST_BORROW
1 parent 9525911 commit 786fa89

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

Lib/test/test_capi/test_opt.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3457,6 +3457,24 @@ def testfunc(n):
34573457
# _POP_TOP_NOP is a sign the optimizer ran and didn't hit bottom.
34583458
self.assertGreaterEqual(count_ops(ex, "_POP_TOP_NOP"), 1)
34593459

3460+
def test_strength_reduce_constant_load_fast_borrow(self):
3461+
# If we detect a _LOAD_FAST_BORROW is actually loading a constant,
3462+
# reduce that to a _LOAD_CONST_INLINE_BORROW which saves
3463+
# the read from locals.
3464+
def testfunc(n):
3465+
class A: pass
3466+
a = A()
3467+
for _ in range(n):
3468+
x = 0
3469+
a.x = x
3470+
3471+
_, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD)
3472+
self.assertIsNotNone(ex)
3473+
uops = get_opnames(ex)
3474+
3475+
self.assertIn("_LOAD_CONST_INLINE_BORROW", uops)
3476+
self.assertNotIn("_LOAD_FAST_BORROW_4", uops)
3477+
34603478
def test_143026(self):
34613479
# https://github.com/python/cpython/issues/143026
34623480

Python/optimizer_bytecodes.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,16 @@ dummy_func(void) {
9292

9393
op(_LOAD_FAST_BORROW, (-- value)) {
9494
value = PyJitRef_Borrow(GETLOCAL(oparg));
95+
PyObject *const_val = sym_get_const(ctx, value);
96+
if (const_val != NULL) {
97+
// If we know we're loading a constant, convert
98+
// to a _LOAD_CONST_INLINE_BORROW to save a memory load.
99+
// It's safe to always borrow here, because
100+
// JIT constants only come from _LOAD_CONST
101+
// (which holds a strong reference), or from
102+
// constant-folded _JIT values, which are immortal.
103+
REPLACE_OP(this_instr, _LOAD_CONST_INLINE_BORROW, 0, (uintptr_t)const_val);
104+
}
95105
}
96106

97107
op(_LOAD_FAST_AND_CLEAR, (-- value)) {

Python/optimizer_cases.c.h

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)