Reputation: 9996
I am working on SSE
and a newbie here. I am trying to use shuffle
instruction to shuffle a 16 bit vector like below:
Input:
1 2 3 4 5 6 7 8
Output:
1 5 2 6 3 7 4 8
How do I achieve the desired target? I am confused about the constant being used here and I don't see any 16 bit shuffle
instruction. shuffle
instruction is only available for 8 bit and 32 bit.
Upvotes: 3
Views: 5573
Reputation: 212969
So long as you can assume SSSE3 then you can use pshufb
aka _mm_shuffle_epi8
:
#include <stdio.h>
#include <tmmintrin.h> // SSSE3
int main()
{
__m128i v_in = _mm_setr_epi16(1, 2, 3, 4, 5, 6, 7, 8);
__m128i v_perm = _mm_setr_epi8(0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15);
__m128i v_out = _mm_shuffle_epi8(v_in, v_perm); // pshufb
printf("v_in = %vhd\n", v_in);
printf("v_out = %vhd\n", v_out);
return 0;
}
Compile and run:
$ gcc -Wall -mssse3 green_goblin.c
$ ./a.out
v_in = 1 2 3 4 5 6 7 8
v_out = 1 5 2 6 3 7 4 8
Alternate solution which relies only on SSE2:
#include <stdio.h>
#include <emmintrin.h> // SSE2
int main()
{
__m128i v_in = _mm_setr_epi16(1, 2, 3, 4, 5, 6, 7, 8);
__m128i v_out = _mm_shuffle_epi32(v_in, _MM_SHUFFLE(3, 1, 2, 0)); // pshufd
v_out = _mm_shufflelo_epi16(v_out, _MM_SHUFFLE(3, 1, 2, 0)); // pshuflw
v_out = _mm_shufflehi_epi16(v_out, _MM_SHUFFLE(3, 1, 2, 0)); // pshufhw
printf("v_in = %vhd\n", v_in);
printf("v_out = %vhd\n", v_out);
return 0;
}
Compile and run:
$ gcc -Wall -msse2 green_goblin_sse2.c
$ ./a.out
v_in = 1 2 3 4 5 6 7 8
v_out = 1 5 2 6 3 7 4 8
Upvotes: 6