llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

`(x == 0 || y == 0)` can fold to `(x * y == 0)` for small integers in `-Oz` mode

Open Explorer09 opened this issue 1 year ago • 5 comments

This is an optimization feature request. (And a follow-up of #160612)

If the integers a and b are so small that (a * b) (the multiplication) cannot overflow, then (a == 0 || b == 0) can convert to (a * b == 0) for smaller code size.

Because it's significantly slower to use multiplication in place of logical checks, I expect this optimization be performed only in -Oz mode.

Note that Clang is already able to transform (a * b == 0) into (a == 0 || b == 0) if the result never overflows. This request is about the doing the opposite transformation for an aggressive code size reduction.

Architectures that I know can benefit from this optimization include: x86-64 and RISCV64.

#include <stdbool.h>
#include <stdint.h>

bool func1(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
    return a == 0 || b == 0 || c == 0 || d == 0;
}

bool func2(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
    if (a == 0)
        return true;
    if (b == 0)
        return true;
    if (c == 0)
        return true;
    return d == 0;
}

bool func3(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
    return ((uint32_t)a * b * c * d) == 0;
}

Compiler Explorer link

func2:
        testl   %edi, %edi
        sete    %al
        testl   %esi, %esi
        sete    %sil
        orb     %al, %sil
        testl   %edx, %edx
        sete    %dl
        testl   %ecx, %ecx
        sete    %al
        orb     %dl, %al
        orb     %sil, %al
        retq

func3:
        imull   %esi, %edi
        imull   %ecx, %edx
        imull   %edi, %edx
        testl   %edx, %edx
        sete    %al
        retq

EDIT: I've reported the same feature request in GCC

Explorer09 avatar Oct 21 '25 21:10 Explorer09

Hi, i'd like to tackle the optimization

vidsinghal avatar Oct 30 '25 15:10 vidsinghal

Hi @vidsinghal ,are you still working on this issue? If you don’t have bandwidth right now, I’d be glad to take it over or split the work.

TelGome avatar Nov 13 '25 13:11 TelGome

Hi, yes, i am working on another PR, I am happy to work on it together.

vidsinghal avatar Nov 13 '25 15:11 vidsinghal

Great! Thanks for the quick reply. I’m interested in improving RISC-V support for both Clang and GCC. If you haven’t pushed anything yet, I’ll start a first cut and open a draft PR; we can iterate together there. Let me know if you’d prefer another way to collaborate!

TelGome avatar Nov 14 '25 05:11 TelGome

This approach works for me.

vidsinghal avatar Nov 17 '25 13:11 vidsinghal