Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Missed optimization opportunity in (z >= 0) && (x >= y + z) && (x >= y); #70374

Closed
krtab opened this issue Oct 26, 2023 · 3 comments · Fixed by #75524
Closed

Missed optimization opportunity in (z >= 0) && (x >= y + z) && (x >= y); #70374

krtab opened this issue Oct 26, 2023 · 3 comments · Fixed by #75524

Comments

@krtab
Copy link

krtab commented Oct 26, 2023

Hi!

I'm not too familiar LLVM. I was investigating this rustc issue rust-lang/rust#82801 and I realized that in the following Rust code, the last (x >= y) check is not optimized away:

#![feature(unchecked_math)]

#[no_mangle]
pub unsafe fn foo(x: u32, y : u32, z: u32) -> bool {
    (x >= y.unchecked_add(z)) && (x >= y)
}

I wrote what I believe is an equivalent C code, using the fact that overflow is UB on signed integers

bool foo(int x, int y, int z) {
    return (z >= 0) && (x >= y + z) && (x >= y);
}

but using clang trunk I get

foo:                                    # @foo
        test    edx, edx
        setns   cl
        add     edx, esi
        cmp     edx, edi
        setle   dl
        cmp     edi, esi
        setge   al
        and     al, cl
        and     al, dl
        ret

whereas GCC properly removes the last comparison

foo:
        xor     eax, eax
        test    edx, edx
        js      .L1
        add     edx, esi
        cmp     edx, edi
        setle   al
.L1:
        ret

edit:

Weirdly enough, the code below is well optimized by clang 17 but not by goldbot's clang trunk version, so there is a possible regression.

bool foo(int x, int y, int z) {
    if (z >= 0) if (x >= y + z) return (x >= y);
    return (z >= 0) && (x >= y + z) && (x >= y);
}
@dtcxzyw
Copy link
Member

dtcxzyw commented Oct 27, 2023

@dtcxzyw dtcxzyw self-assigned this Oct 27, 2023
@pinskia
Copy link

pinskia commented Nov 5, 2023

I noticed GCC does not optimize the case where s/&&/& is done, filed https://gcc.gnu.org/bugzilla/show_bug.cgi?id=112386 for that.

@krtab
Copy link
Author

krtab commented Dec 15, 2023

Thanks @dtcxzyw !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants