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

Comparison of add of extended booleans not folded to xor

Open arsenm opened this issue 3 years ago • 11 comments

I was looking at some code that tried to compute a sort of enum scheme by adding booleans, and comparing to constant values which failed to form nice boolean code. This is really just an xor.

https://alive2.llvm.org/ce/z/RSnV-d

define i1 @src(i1 %arg, i1 %arg1) {
bb:
  %i = zext i1 %arg to i32
  %i2 = zext i1 %arg1 to i32
  %i3 = add nuw nsw i32 %i2, %i
  %i4 = icmp eq i32 %i3, 1
  ret i1 %i4
}

define i1 @tgt(i1 %arg, i1 %arg1) {
bb:
  %xor = xor i1 %arg, %arg1
  ret i1 %xor
}

arsenm avatar Aug 21 '23 12:08 arsenm

Can I fix this? But I will need some help, as I am not familiar with LLVM system yet

elhewaty avatar Sep 04 '23 14:09 elhewaty

%i4 = icmp eq i32 %i3, 1 what if the 1 were 0?

elhewaty avatar Sep 04 '23 16:09 elhewaty

%i4 = icmp eq i32 %i3, 1 what if the 1 were 0?

That would be equivalent to not(or(x, y)): https://alive2.llvm.org/ce/z/8z7Q4G

dc03 avatar Sep 04 '23 16:09 dc03

so the xor case holds for eq, 1, and zext only

elhewaty avatar Sep 04 '23 16:09 elhewaty

so the xor case holds for eq and 1 only

Yes, if you sketch out the truth table for this function you will see it is equivalent to the table for an xor, and with 0 it is equivalent to the table for a nor.

dc03 avatar Sep 04 '23 16:09 dc03

So we need to create a new function foldICmpAddExtI1 and handle all our cases? or do we have something like this already?

elhewaty avatar Sep 04 '23 16:09 elhewaty

I think foldICmpAddConstant may be what you're looking for: https://github.com/llvm/llvm-project/blob/main/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp#L2898

dc03 avatar Sep 04 '23 16:09 dc03

@arsenm Here is a candidate patch : https://reviews.llvm.org/D159464

elhewaty avatar Sep 06 '23 13:09 elhewaty

Can you please review the patch again.

elhewaty avatar Sep 14 '23 17:09 elhewaty

@arsenm ping

elhewaty avatar Sep 20 '23 15:09 elhewaty

@arsenm @nikic @goldsteinn Here's a candidate pull: https://github.com/llvm/llvm-project/pull/67895

elhewaty avatar Sep 30 '23 22:09 elhewaty