diff --git a/Lib/test/test_peepholer.py b/Lib/test/test_peepholer.py index fa8b5ceebb9f32..579eb86faeffa9 100644 --- a/Lib/test/test_peepholer.py +++ b/Lib/test/test_peepholer.py @@ -1156,6 +1156,14 @@ def f(self): print(heapify_max) self.assertInBytecode(f, "LOAD_FAST_BORROW", "self") + def test_ternary_expression_uses_load_fast_borrow(self): + def f(a, b): + return a if a < b else b + + self.assertNotInBytecode(f, "LOAD_FAST") + self.assertInBytecode(f, "LOAD_FAST_BORROW", "a") + self.assertInBytecode(f, "LOAD_FAST_BORROW", "b") + class DirectCfgOptimizerTests(CfgOptimizationTestCase): def test_optimize_cfg_const_index_out_of_range(self): diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-03-27-04-16-08.gh-issue-145629.eLFhwn.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-03-27-04-16-08.gh-issue-145629.eLFhwn.rst new file mode 100644 index 00000000000000..9bea5c06f3c5ee --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-03-27-04-16-08.gh-issue-145629.eLFhwn.rst @@ -0,0 +1 @@ +Use ``LOAD_FAST_BORROW`` in both branches of a returned conditional expression by merging single-predecessor exit blocks in the CFG optimizer. diff --git a/Python/flowgraph.c b/Python/flowgraph.c index fc676dc6feb167..829a5f7a57b293 100644 --- a/Python/flowgraph.c +++ b/Python/flowgraph.c @@ -1278,6 +1278,28 @@ inline_small_or_no_lineno_blocks(basicblock *entryblock) { return changes; } +/* Merge an exit block into its fallthrough predecessor when it is the sole + * predecessor (requires b_predecessors to be up to date). + */ +static int +merge_single_predecessor_exit_blocks(basicblock *entryblock) +{ + for (basicblock *b = entryblock; b != NULL; b = b->b_next) { + cfg_instr *last = basicblock_last_instr(b); + basicblock *next = b->b_next; + if (last == NULL || next == NULL || is_jump(last) || + !BB_HAS_FALLTHROUGH(b) || next->b_predecessors != 1 || + !basicblock_exits_scope(next)) + { + continue; + } + RETURN_IF_ERROR(basicblock_append_instructions(b, next)); + next->b_iused = 0; + next->b_predecessors = 0; + } + return SUCCESS; +} + // Attempt to eliminate jumps to jumps by updating inst to jump to // target->i_target using the provided opcode. Return whether or not the // optimization was successful. @@ -2677,6 +2699,7 @@ optimize_cfg(cfg_builder *g, PyObject *consts, PyObject *const_cache, RETURN_IF_ERROR(check_cfg(g)); RETURN_IF_ERROR(inline_small_or_no_lineno_blocks(g->g_entryblock)); RETURN_IF_ERROR(remove_unreachable(g->g_entryblock)); + RETURN_IF_ERROR(merge_single_predecessor_exit_blocks(g->g_entryblock)); RETURN_IF_ERROR(resolve_line_numbers(g, firstlineno)); RETURN_IF_ERROR(optimize_load_const(const_cache, g, consts, consts_index)); for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {