Skip to content

Missed optimization: redundant conversion to bool when the value is already in valid bool range #84605

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

Open
YanWQ-monad opened this issue Mar 9, 2024 · 1 comment

Comments

@YanWQ-monad
Copy link
Contributor

For the IR

define i1 @src(ptr %x) {
  %1 = load i8, ptr %x, align 1
  %2 = icmp ult i8 %1, 2
  br i1 %2, label %bb1, label %bb2

bb2:
  %3 = tail call i1 @dynamic()
  br label %bb3

bb1:
  %4 = icmp eq i8 %1, 1
  br label %bb3

bb3:
  %5 = phi i1 [ %4, %bb1 ], [ %3, %bb2 ]
  ret i1 %5
}

declare i1 @dynamic()

which generates the following instructions in x86 (https://godbolt.org/z/hY5EjobTv):

src:                                    # @src
        movzx   eax, byte ptr [rdi]
        cmp     al, 2
        jae     dynamic@PLT                     # TAILCALL
        cmp     al, 1
        sete    al
        ret

The conversion of eax to bool is redundant after jae, we can directly ret (eax) as eax is already in valid bool range [0, 1].


This issue is extracted from rust-lang/rust#121673.

I tried to implement this optimization in IR by folding icmp eq %x, 1 to trunc %x to i1 in #83829, but it doesn't work well, since InstCombine would canonicalize trunc to (X & 1) != 0, which results in one more and instruction in backend.

So, I am going to implement this optimization in backend. Please let me know if there is a better way to address this issue.
If possible, please assign this issue to me, thanks.

@andjo403
Copy link
Contributor

andjo403 commented Mar 9, 2024

InstCombine would canonicalize trunc to (X & 1) != 0

the canonicalizion of trunc is mentioned in the https://discourse.llvm.org/t/rfc-add-nowrap-flags-to-trunc/77453/3 maybe is interesting to you.

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

No branches or pull requests

3 participants