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

[X86] Vector conditional increment needlessly lengthens the dependency chain when the condition needs inversion

Open WalterKruger opened this issue 1 year ago • 2 comments

Due to gaps in support on x86, some vector comparisons have to be implemented by inverting the opposite condition. clang avoids that when implementing a conditional increment by instead conditionally decrementing when the condition isn't met then always incrementing.

This is unoptimal as the inversion is logically independent with the value being incremented, well the current implementation will always have a longer dependency chain due to the serial decrement then increment:

shiftLeft2_incIfNotZero:
        psllw   xmm0, 2
        pand    xmm0, xmmword ptr [rip + .LCPI0_0]
        pxor    xmm2, xmm2
        pcmpeqb xmm2, xmm1
-       paddb   xmm0, xmm2
        pcmpeqd xmm1, xmm1
+       pxor    xmm1, xmm2
        psubb   xmm0, xmm1
        ret

https://godbolt.org/z/rr7jjaxdn

Note that doesn't happen when implementing a conditional decrement.

WalterKruger avatar Nov 11 '25 01:11 WalterKruger

@llvm/issue-subscribers-backend-x86

Author: Walter (WalterKruger)

Due to gaps in support on x86, some vector comparisons have to be implemented by inverting the opposite condition. clang avoids that when implementing a conditional increment by instead conditionally decrementing when the condition isn't met then always incrementing.

This is unoptimal as the inversion is logically independent with the value being incremented, well the current implementation will always have a longer dependency chain due to the serial decrement then increment:

shiftLeft2_incIfNotZero:
        psllw   xmm0, 2
        pand    xmm0, xmmword ptr [rip + .LCPI0_0]
        pxor    xmm2, xmm2
        pcmpeqb xmm2, xmm1
-       paddb   xmm0, xmm2
        pcmpeqd xmm1, xmm1
+       pxor    xmm1, xmm2
        psubb   xmm0, xmm1
        ret

https://godbolt.org/z/rr7jjaxdn

Note that doesn't happen when implementing a conditional decrement.

llvmbot avatar Nov 11 '25 01:11 llvmbot

define <16 x i8> @shiftLeft2_incIfNotZero(<16 x i8> %x, <16 x i8> %condition) {
  %shl = shl <16 x i8> %x, splat (i8 2)
  %cmp = icmp ne <16 x i8> %condition, zeroinitializer
  %sext.neg = zext <16 x i1> %cmp to <16 x i8>
  %sub = or disjoint <16 x i8> %shl, %sext.neg
  ret <16 x i8> %sub
}

define <16 x i8> @shiftLeft2_decIfNotZero(<16 x i8> %x, <16 x i8> %condition) {
  %shl = shl <16 x i8> %x, splat (i8 2)
  %cmp = icmp ne <16 x i8> %condition, zeroinitializer
  %sext = sext <16 x i1> %cmp to <16 x i8>
  %add = add <16 x i8> %shl, %sext
  ret <16 x i8> %add
}

This might be as easy as handling addlike patterns

RKSimon avatar Nov 11 '25 09:11 RKSimon