Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing equality between two __m128i variables

Tags:

c

x86

simd

sse

If I want to do a bitwise equality test between two __m128i variables, am I required to use an SSE instruction or can I use ==? If not, which SSE instruction should I use?

like image 719
jaynp Avatar asked Nov 12 '14 06:11

jaynp


2 Answers

Although using _mm_movemask_epi8 is one solution, if you have a processor with SSE4.1 I think a better solution is to use an instruction which sets the zero or carry flag in the FLAGS register. This saves a test or cmp instruction.

To do this you could do this:

if(_mm_test_all_ones(_mm_cmpeq_epi8(v1,v2))) {
    //v0 == v1
}

Edit: as Paul R pointed out _mm_test_all_ones generates two instructions: pcmpeqd and ptest. With _mm_cmpeq_epi8 that's three instructions total. Here's a better solution which only uses two instructions in total:

__m128i neq = _mm_xor_si128(v1,v2);
if(_mm_test_all_zeros(neq,neq)) {
    //v0 == v1
}

This generates

pxor    %xmm1, %xmm0
ptest   %xmm0, %xmm0
like image 118
Z boson Avatar answered Oct 31 '22 19:10

Z boson


You can use a compare and then extract a mask from the comparison result:

__m128i vcmp = _mm_cmpeq_epi8(v0, v1);       // PCMPEQB
uint16_t vmask = _mm_movemask_epi8(vcmp);    // PMOVMSKB
if (vmask == 0xffff)
{
    // v0 == v1
}

This works with SSE2 and later.

As noted by @Zboson, if you have SSE 4.1 then you can do it like this, which may be slightly more efficient, as it's two SSE instructions and then a test on a flag (ZF):

__m128i vcmp = _mm_xor_si128(v0, v1);        // PXOR
if (_mm_testz_si128(vcmp, vcmp))             // PTEST (requires SSE 4.1)
{
    // v0 == v1
}

FWIW I just benchmarked both of these implementations on a Haswell Core i7 using clang to compile the test harness and the timing results were very similar - the SSE4 implementation appears to be very slightly faster but it's hard to measure the difference.

like image 24
Paul R Avatar answered Oct 31 '22 17:10

Paul R