php-src
php-src copied to clipboard
Range inference optimizer bug
Description
The following code:
<?php
function f($x) {
if ($x > 5 && $x < 7) {
return match ((int) $x) { 6 => "six", default => "not six" };
}
}
echo f(5.5);
Resulted in this output:
six // under opcache/optimizations
not six // without
Obviously "not six" is the right answer.
The problem can be seen in range inference:
#3.CV0($x) [any] RANGE[6..++] = Pi(#1.CV0($x) & RANGE[6 .. ++]) // $x > 5
#5.CV0($x) [any] RANGE[6..6] = Pi(#3.CV0($x) & RANGE[-- .. 6]) // $x < 7
#6.T3 [long] RANGE[6..6] = CAST (long) #5.CV0($x) [any] RANGE[6..6]
So each comparisons narrows the range, but (int)5.5 equals 5. Then SCCP performs folding and we end up with the wrong result. The problem is that the range inference is only valid on int inputs.
I'm unsure how to fix this. We could track whether the range is definitely for an int, but that's painful.
PHP Version
8.4+
Operating System
No response
Here is an related case I stumbled across I find intresting
function f($x) {
if ($x == 6) {
return match ((int)$x) {
6 => "six",
default => "not six",
};
}
}
echo f(true);
With Opcache open it returns six. Which it shouldn't.
JIT fuzzer ran into a variant: https://issues.oss-fuzz.com/issues/579025375
#5.CV1($a) [undef] RANGE[--..-3] = Pi(#3 & RANGE[-- .. -3]) ; from $a < -2
#8.CV0($ÿ) [long, double] RANGE[--..-6] = ADD #5 #5
#10 = MOD #6.T2 #8.CV0($ÿ) ; op2 range excludes 0 and -1