https://gcc.gnu.org/bugzilla/show_bug.cgi?id=103897

            Bug ID: 103897
           Summary: x86: Missing optimizations with _mm_undefined_si128
                    and PMOVSX*
           Product: gcc
           Version: 12.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: nekotekina at gmail dot com
  Target Milestone: ---

Hello, I was trying to use VPMOVSXWD and other PMOVSX* intrinsics and also
emulate them for SSE2 targets. I noticed two (at least) distinct problems:
1) (V)PMOVSX** can use a memory operand, but emits a separate load instruction.
2) _mm_undefined_si128() always generates an additional zeroing instruction.
Using it in combination with unpack and arithmetic shift instructions looks
like an optimal way to emulate PMOVSX for SSE2 target.

Godbolt example includes clang output for comparison.

https://godbolt.org/z/KE8q9v6qG

#include <emmintrin.h>
#include <immintrin.h>

__attribute__((__target__("avx"))) void test0(__m128i* dst, __m128i* src)
{
    // Emit VPMOVSXWD: can combine load from memory, but emits 2 instructions
    // Looks like gcc 8.5 was doing better
    *dst = _mm_cvtepi16_epi32(*src);
}

void test1(__m128i* dst, __m128i* src)
{
    // Emulate VPMOVSXWD: sets zero specifically for _mm_undefined_si128
    *dst = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_undefined_si128(), *src), 16);
}

void test2(__m128i* dst, __m128i* src)
{
    // Sets zero register but absolutely can reuse PSLLW result    
    *dst = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_undefined_si128(),
_mm_slli_epi16(*src, 1)), 16);
}

void test3(__m128i* dst, __m128i* src)
{
    // Similar to test1, but emulate "high" VPMOVSXWD
    *dst = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_undefined_si128(), *src), 16);
}

__attribute__((__target__("avx"))) void test4(__m128i* dst, __m128i* src)
{
    // Bonus (not sure what is the idiomatic way to MOVSX high part)
    *dst = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_undefined_si128(), *src), 16);
}

__attribute__((__target__("avx"))) void test5(__m128i* dst, __m128i* src)
{
    // Emits two zeroing instructions
    *dst = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_undefined_si128(),
_mm_packs_epi16(_mm_undefined_si128(), *src)), 16);
}

Reply via email to