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

[InstSimplify] (a ^ b) ? (~a) ^ b : a ^ (~b)

Open k-arrows opened this issue 3 years ago • 7 comments

Test code:

int foo(int a, int b)
{
    return (a ^ b) ? (~a) ^ b : a ^ (~b) ;
}

Clang 15.0.0 (and Gcc trunk)

foo(int, int):                               # @foo(int, int)
        mov     eax, edi
        xor     eax, esi
        not     eax
        ret

Clang 16.0.0 (and Clang trunk)

foo(int, int):                               # @foo(int, int)
        mov     ecx, edi
        xor     ecx, esi
        cmp     edi, esi
        not     ecx
        mov     eax, -1
        cmovne  eax, ecx
        ret

https://godbolt.org/z/qdhKnj3af

k-arrows avatar Jun 04 '23 06:06 k-arrows

I'd like to fix this, but I'm not able to find the exact transform in InstCombine causing this. It appears that the newer clang is converting a ^ (~b) into 0 ^ (-1) (which then gets folded into -1), possibly because it is able to prove that a ^ b being false means that a and b are equal. The older clang appears to be converting a ^ (~b) as well as (~a) ^ b into ~(a ^ b), then coalescing them leading to the codegen you see.

dc03 avatar Jun 09 '23 11:06 dc03

This fold doesn't introduce new instructions so what you really should take a look is InstructionSimplify, maybe https://github.com/llvm/llvm-project/blob/0662167c5b1ff45354e7c80e1495293bb8c6cf2b/llvm/lib/Analysis/InstructionSimplify.cpp#L4482

Alive proof: https://alive2.llvm.org/ce/z/KEt9R5

junaire avatar Jun 09 '23 12:06 junaire

This probably needs a generalization of simplifyWithOpReplaced to look at more than one instruction.

nikic avatar Jun 09 '23 13:06 nikic

This probably needs a generalization of simplifyWithOpReplaced to look at more than one instruction.

@nikic: Not entirely sure where this plays in. Stepping through the code, the transformation comes from here: a ^ ~b gets turned into a ^ (b ^ -1) which then gets reassociated by SimplifyAssociativeOrCommutative here to be (a ^ b) ^ -1, where a ^ b then gets transformed by simplifyByDomEq into 0. I don't see simplifyWithOpReplaced in the call stack at any point.

dc03 avatar Jun 21 '23 06:06 dc03

@dc03 The optimization regression comes from making use of dominating conditions in icmp simplification. However, we don't want to avoid that and instead make sure that the new IR can still be simplified. simplifyWithOpReplaced() is the transform that handles this kind of pattern.

nikic avatar Jun 21 '23 08:06 nikic

The regression between llvm 15 and llvm 16 , https://gcc.godbolt.org/z/Goq9ETh67

vfdff avatar Jun 21 '23 12:06 vfdff

maybe this is the simplify case https://alive2.llvm.org/ce/z/TGgJTq , show that the simplifyWithOpReplaced need look at more than one instruction.

vfdff avatar Jun 24 '23 09:06 vfdff