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

Missed DCE for __builtin_{clzg,ctzg} when bitshift

Open BreadTom opened this issue 1 year ago • 1 comments

Godbolt and GCC bug

unsigned long f0(unsigned long arg0, int arg1){
    int tmp1;
    if(arg1){
        tmp1 = __builtin_ctzg(arg0, 0);
        return (arg0 >> tmp1);
    }
    tmp1 = __builtin_clzg(arg0, 0);
    return (arg0 << tmp1);
}

unsigned long f1(unsigned long arg0, int arg1){
    int tmp1;
    if(arg1){
        tmp1 = __builtin_clzg(arg0, 0);
        arg0 <<= tmp1;
        tmp1 = __builtin_ctzg(arg0, 0);
        arg0 >>= tmp1;
        return arg0;
    }
    tmp1 = __builtin_ctzg(arg0, 0);
    arg0 >>= tmp1;
    tmp1 = __builtin_clzg(arg0, 0);
    arg0 <<= tmp1;
    return arg0;
}

f1() uses __builtin_ctzg() then __builtin_clzg() for returning ARG0 when it could instead use __builtin_clzg() in f0() (Vice versa) with flags -O3 -march=icelake-client.

BreadTom avatar May 14 '25 18:05 BreadTom

        tmp1 = __builtin_ctzg(arg0, 0);
        return (arg0 >> tmp1);

Maybe it's equivalent to this expression:

        return (arg0 / (arg0 & (-arg0)));

Explorer09 avatar Jun 01 '25 04:06 Explorer09