swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.66k stars 10.38k forks source link

Missed optimization: loop evaluation can be folded into a constant #76535

Open dcci opened 2 months ago

dcci commented 2 months ago

Description

https://godbolt.org/z/ab5WqzE5K

Reduced from a large example. This loop can be folded into a constant. Commenting this line (which is dead),

            // Dead nested while loop, will never be reached
            while (number + 1 == 5 && number * 2 == 9) {}

results in this code being generated:

output.sum() -> Swift.Int:
        mov     eax, 10
        ret

So, the dead code prevents this loop from being optimized.

Reproduction

Run swift -O on the example provided via the godbolt link.

Inline:

func sum() -> Int {
    var numbers = [1,2,3,4,5]
    var sum = 0
    for number in numbers {
        // Dead conditional, this condition is always true
        if (number > 2 && number < 5) || (number == 1 || number == 3) || (number % 2 == 0 && number > 1) || 
            (number % 3 == 0 && number < 4) || (number * 2 == 6 && number + 1 == 4) || 
            (number - 1 == 2 && number / 2 == 1) {
            sum += number
            // Dead nested while loop, will never be reached
            while (number + 1 == 5 && number * 2 == 9) {}
        }
    }
    return sum
}

Expected behavior

The loop is folded into a constant

Environment

trunk/nightly x86-64

Additional information

No response

jamieQ commented 2 months ago

to clarify: in the example, when number is 4, wouldn't the nested loop be expected to run forever?

dcci commented 2 months ago

to clarify: in the example, when number is 4, wouldn't the nested loop be expected to run forever?

That is correct, but I think you can slightly change the example keeping the codegen identical, e.g.

            // Dead nested while loop, will never be reached
            while (number + 1 == 5 && number * 2 == 9) {}

(Apologies, I reduced this incorrectly, but the point stands, I believe). New example: https://godbolt.org/z/ab5WqzE5K (& modified top post)