C 中的 ARM Neon:如何在使用内部函数时组合不同的 128 位数据类型?

ARM Neon in C: How to combine different 128bit data types while using intrinsics?

TLTR

对于 arm 内在函数,如何将 uint8x16_t 类型的 128 位变量输入到需要 uint16x8_t 的函数中?


加长版

上下文:我有一张灰度图像,每个像素 1 个字节。我想将它缩小 2 倍。对于每个 2x2 输入框,我想取最小像素。在纯 C 中,代码将如下所示:

for (int y = 0; y < rows; y += 2) {
    uint8_t* p_out = outBuffer + (y / 2) * outStride;
    uint8_t* p_in = inBuffer + y * inStride;
    for (int x = 0; x < cols; x += 2) {
         *p_out = min(min(p_in[0],p_in[1]),min(p_in[inStride],p_in[inStride + 1]) );
         p_out++;
         p_in+=2;
    }
}

其中 rows 和 cols 都是 2 的倍数。我称 "stride" 图像中从一个像素到紧邻下方像素所需的字节步长。

现在我想对其进行矢量化。思路是:

  1. 取2个连续的像素行
  2. 从第一行开始在 a 中加载 16 个字节,并在 b
  3. 中加载正下方的 16 个字节
  4. 计算 ab 之间的最小字节。存储在 a.
  5. 创建 a 的副本,将其右移 1 个字节(8 位)。存储在b.
  6. 计算 ab 之间的最小字节。存储在 a.
  7. 在输出图像中存储 a 的每个第二个字节(丢弃一半字节)

我想用 Neon 内在函数来写这个。好消息是,对于每一步都有一个与之匹配的内在。

例如,在第 3 点可以使用(来自 here):

uint8x16_t  vminq_u8(uint8x16_t a, uint8x16_t b);

并且在第 4 点,可以使用以下之一使用 8 位的移位(来自 here):

uint16x8_t vrshrq_n_u16(uint16x8_t a, __constrange(1,16) int b);
uint32x4_t vrshrq_n_u32(uint32x4_t a, __constrange(1,32) int b);
uint64x2_t vrshrq_n_u64(uint64x2_t a, __constrange(1,64) int b);

那是因为我不关心字节 1、3、5、7、9、11、13、15 会发生什么,因为无论如何它们都会从最终结果中丢弃。 (这个正确性已经验证过了,不是问题的重点。)

但是,vminq_u8 的输出是 uint8x16_t 类型,它与我想使用的移位内在函数不兼容。在 C++ 中,我用 , while I have been told that the problem (Edit: although that answer refer to C++, and in fact ), nor by 解决了这个问题,因为这会打破严格的别名规则。

在使用 ARM Neon 内部函数时如何组合不同的数据类型?

针对此类问题,arm_neon.h提供了vreinterpret{q}_dsttype_srctype转换运算符。

In some situations, you might want to treat a vector as having a different type, without changing its value. A set of intrinsics is provided to perform this type of conversion.

因此,假设 ab 声明为:

uint8x16_t a, b;

你的第4点可以写成(*):

b = vreinterpretq_u8_u16(vrshrq_n_u16(vreinterpretq_u16_u8(a), 8) );

但是,请注意,不幸的是,这并没有解决使用向量类型数组的数据类型,请参阅


(*) 应该说,这比等效的(在此特定上下文中)SSE 代码要麻烦得多,因为 SSE 只有一种 128 位整数数据类型(即 __m128i):

__m128i b = _mm_srli_si128(a,1);