Skip to content

Peephole optimizations for NULLs in lists and scalar lists #23523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: blead
Choose a base branch
from

Conversation

richardleach
Copy link
Contributor

my $x = (1,2,3); produces the following OP tree in blead:

2     <;> nextstate(main 1 -e:1) v:{ ->3
6     <1> padsv_store[$x:1,2] vKS/LVINTRO ->7
5        <@> list sKP ->6
3           <0> pushmark v ->4
-           <0> ex-const v ->-
-           <0> ex-const v ->4
4           <$> const(IV 3) s ->5
-        <0> ex-padsv sRM*/LVINTRO ->6

This is functionally equivalent to my $x = 3;:

2     <;> nextstate(main 1 -e:1) v:{ ->3
4     <1> padsv_store[$x:1,2] vKS/LVINTRO ->5
3        <$> const(IV 3) s ->4
-        <0> ex-padsv sRM*/LVINTRO ->4

Refactoring Perl_scalar / Perl_scalarvoid to allow the transformation of the first tree into the second is proabably not worth the churn, given that constructing the first tree will typically emit "Useless use of X in scalar context" warnings. Some cases may silently slip through though, such as when the consts 0 and 1 are excluded from these warnings.

The attached commits enable the peephole optimizer to do two things:

  1. Remove OP_NULL list nodes, when they have no kids and have a sibling.
  2. Adjust the op_next pointers to skip over the unnecessary OP_PUSHMARK and OP_LIST nodes.

That gives an OP tree like this:

2     <;> nextstate(main 1 -e:1) v:{ ->3
4     <1> padsv_store[$x:1,2] vKS/LVINTRO ->5
-        <1> ex-list sKP ->4
-           <0> ex-pushmark v ->3
3           <$> const[IV 3] s ->4
-        <0> ex-padsv sRM*/LVINTRO ->4

Closes: #23448


  • This set of changes does not require a perldelta entry.

Note: This shouldn't occur particularly frequently, as superfluous
arguments are likely to trigger warnings when scalar context is
applied to the list.

e.g. `my $x = (1,2,3);` is essentially the same as `my $x = 3;`
@richardleach richardleach marked this pull request as draft August 1, 2025 11:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Optimise away LIST/ex-LIST trees containing one item
1 participant