From b37ec56952d110e82344a2337aebdbcc4d404daf Mon Sep 17 00:00:00 2001 From: Mingzhu Yan Date: Wed, 18 Mar 2026 11:14:05 +0000 Subject: [PATCH] gh-131798: JIT: optimize _LOAD_COMMON_CONSTANT --- Lib/test/test_capi/test_opt.py | 12 ++++++++++++ Python/optimizer_bytecodes.c | 7 +++++++ Python/optimizer_cases.c.h | 5 ++++- 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Lib/test/test_capi/test_opt.py b/Lib/test/test_capi/test_opt.py index 2a126a7b29cc73..3f1edb3f9a2db7 100644 --- a/Lib/test/test_capi/test_opt.py +++ b/Lib/test/test_capi/test_opt.py @@ -2832,6 +2832,18 @@ def testfunc(n): self.assertIn("_GUARD_TYPE_VERSION", uops) self.assertNotIn("_CHECK_ATTR_CLASS", uops) + def test_load_common_constant(self): + def testfunc(n): + for _ in range(n): + x = list(i for i in ()) + return x + res, ex = self._run_with_optimizer(testfunc, TIER2_THRESHOLD) + self.assertEqual(res, list(())) + self.assertIsNotNone(ex) + uops = get_opnames(ex) + self.assertIn("_BUILD_LIST", uops) + self.assertNotIn("_LOAD_COMMON_CONSTANT", uops) + def test_load_small_int(self): def testfunc(n): x = 0 diff --git a/Python/optimizer_bytecodes.c b/Python/optimizer_bytecodes.c index 7ca33e9e77fb74..06ed7db4fb076e 100644 --- a/Python/optimizer_bytecodes.c +++ b/Python/optimizer_bytecodes.c @@ -631,6 +631,13 @@ dummy_func(void) { value = PyJitRef_Borrow(sym_new_const(ctx, val)); } + op(_LOAD_COMMON_CONSTANT, (-- value)) { + assert(oparg < NUM_COMMON_CONSTANTS); + PyObject *val = _PyInterpreterState_GET()->common_consts[oparg]; + ADD_OP(_LOAD_CONST_INLINE_BORROW, 0, (uintptr_t)val); + value = PyJitRef_Borrow(sym_new_const(ctx, val)); + } + op(_LOAD_SMALL_INT, (-- value)) { PyObject *val = PyLong_FromLong(oparg); assert(val); diff --git a/Python/optimizer_cases.c.h b/Python/optimizer_cases.c.h index df6368ca8ce011..31ab4b42d922fd 100644 --- a/Python/optimizer_cases.c.h +++ b/Python/optimizer_cases.c.h @@ -1435,7 +1435,10 @@ case _LOAD_COMMON_CONSTANT: { JitOptRef value; - value = sym_new_not_null(ctx); + assert(oparg < NUM_COMMON_CONSTANTS); + PyObject *val = _PyInterpreterState_GET()->common_consts[oparg]; + ADD_OP(_LOAD_CONST_INLINE_BORROW, 0, (uintptr_t)val); + value = PyJitRef_Borrow(sym_new_const(ctx, val)); CHECK_STACK_BOUNDS(1); stack_pointer[0] = value; stack_pointer += 1;