cpython icon indicating copy to clipboard operation
cpython copied to clipboard

gh-121246: LOAD_CONST optimizer now uses a helper function to get the next non-NOP instruction possibly in a following block

Open blhsing opened this issue 1 year ago • 0 comments

As reported in gh-121246, the following Python code:

def func(x):
    return True if x else False

would be compiled into the following bytecode:

 2 LOAD_FAST                0 (x)
 4 POP_JUMP_IF_FALSE        2 (to 10)
 6 LOAD_CONST               1 (True)
 8 RETURN_VALUE
10 LOAD_CONST               2 (False)
12 RETURN_VALUE

The two pairs of LOAD_CONST + RETURN_VALUE are each supposed to be optimized into a RETURN_CONST but were not. In the former case, it was because a NOP was between LOAD_CONST and RETURN_VALUE as a result of a prior optimization so the peephole optmizer could not obtain RETURN_VALUE as the next instruction from LOAD_CONST. In the latter case, it was because RETURN_VALUE was in a block following that of LOAD_CONST. The current approach of using &bb->b_instr[i + 1] to obtain the next instruction would fail for both cases.

This PR made the LOAD_CONST-specific peephole optimizer obtain the next instruction instead by using a helper function that skips NOP instructions and turns to the next block if at the end of the current block.

The other optimizer functions may be able benefit from switching to the same helper function, but I decided not to make such changes to other optimizer functions unnecessarily unless there is an actual need.

blhsing avatar Jul 03 '24 06:07 blhsing