How to access SIMD vector elements when overloading array access operators?

I'm trying to make SIMD code that works with MSVC, with compilation from Clang to Xcode 6. Unfortunately, I get an error when the array access operators are overloaded into a custom vector class, which I cannot fix. The vector template has specializations for arrays 4 and 8 in length, which use the built-in SIMD functions, but the array access operator to return a link to a vector element (to update this element) gives me an error in clang "a non-constant link cannot bind to a vector element" .

Full source code

Overloaded operators:

#ifdef _MSC_VER float operator[](int idx) const { return v.m256_f32[idx]; } // m256_f32 MSVC only float& operator[](int idx) { return v.m256_f32[idx]; } #else float operator[](int idx) const { return v[idx]; } float& operator[](int idx) { return v[idx]; } #endif 

Error from Clang:

 non-const reference cannot bind to vector element float& operator[](int idx) { return v[idx]; } ^~~~~~ 
+5
source share
2 answers

I think you will probably need to use a union for this, for example:

 union U { __m256 v; float a[8]; }; 

and the value operator will be:

 float operator[](int idx) const { U u = { v }; return ua[idx]; } 

The link operator is more complex, and the only way I can do this is to use the punning function, so with the usual caveats:

 float& operator[](int idx) { return ((float *)&v)[idx]; } 

I'm not even sure if this -fno-strict-aliasing and you might need -fno-strict-aliasing .

To avoid this nastiness, I suppose you could consider changing the member variable from __m256 v; to U u; .

I just hope that you are not doing this kind of thing inside any critical cycles.

+5
source

This works read-only, so you cannot return a link to a float. But this should work with runtime values:

  • > = SSE4.1 +: use PEXTRD functions such as _mm_extract_ps
  • before SSE4.1: _mm_cvtsi128_si32 + _mm_srli_si128 to access any 32-bit element (then with union)
+2
source

Source: https://habr.com/ru/post/1205469/


All Articles