r/simd • • Mar 01 '24
retrieving a byte from a runtime index in m128
Given an m128 register packed with uint8_t, how do i get the ith element?
I am aware of _mm_extract_epi16(s, 10), but it only takes in a constant known at compile time. Will it be possible to extract it using a runtime value without having to explicitly parse the value like as follow:
if (i == 1) _mm_extract_epi16(s, 1);
else if (i == 2) _mm_extract_epi16(s, 2)
...I have tried `(uint8_t)(&s + 10 * 8)` but it somehow gives the wrong answer and i'm not sure why?
Thank you.
3
Upvotes
2
u/SantaCruzDad Mar 02 '24
Comprehensive answer: https://stackoverflow.com/a/39885629/253056
1
u/NegotiationRegular61 Mar 02 '24 edited Mar 02 '24
int index = 1;
__asm{
mov rcx,index
lea rax,[Shuffle_Xmm]
add rax,rcx
vpshufb xmm0,xmm0,xmmword ptr [rax]
ret
Shuffle_Xmm:
BYTE 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,DUP 16(0)
}
1
u/UnalignedAxis111 Mar 01 '24
You have to cast the pointer first,
((uint8_t*)&s)[i].The non "UB" way is to stackalloc aligned scratch memory and use store_si128 instead.
Another way is using a variable shift or shuffle + _mm_cvtsi128_si32, but I don't think that's going to be much faster than spilling to memory - at least both Clang and GCC do spill + reload: https://godbolt.org/z/avGfoxqcq
0
u/brubakerp Mar 02 '24
_mm_extract_epi16shouldn't require a compile time constant. There's aconstprototype but nothing that would require it to be resolved at compile time. You shouldn't need to do thisif/elsebusiness. Are you sure the use of_mm_extract_epi16wasn't inside a template or some otherconstexprcontext?