这是在unusual C preprocessor uses的博客文章(我的)发现的一个侧面问题。 对于127个不同的偏移量,有四个不同的SSE2指令的最佳序列用于移位。预处理器使得构造一个相当于129路转换语句的移位函数变得合理。原谅这里的原始代码;我不熟悉直接在这里发布代码。 查看博客文章,了解正在发生的事情。
#include <emmintrin.h>
typedef __m128i XMM;
#define xmbshl(x,n) _mm_slli_si128(x,n) // xm <<= 8*n -- BYTE shift left
#define xmbshr(x,n) _mm_srli_si128(x,n) // xm >>= 8*n -- BYTE shift right
#define xmshl64(x,n) _mm_slli_epi64(x,n) // xm.hi <<= n, xm.lo <<= n
#define xmshr64(x,n) _mm_srli_epi64(x,n) // xm.hi >>= n, xm.lo >>= n
#define xmand(a,b) _mm_and_si128(a,b)
#define xmor(a,b) _mm_or_si128(a,b)
#define xmxor(a,b) _mm_xor_si128(a,b)
#define xmzero _mm_setzero_si128()
XMM xm_shl(XMM x, unsigned nbits)
{
// These macros generate (1,2,5,6) SSE2 instructions, respectively:
#define F1(n) case 8*(n): x = xmbshl(x, n); break;
#define F2(n) case n: x = xmshl64(xmbshl(x, (n)>>3), (n)&15); break;
#define F5(n) case n: x = xmor(xmshl64(x, n), xmshr64(xmbshl(x, 8), 64-(n))); break;
#define F6(n) case n: x = xmor(xmshl64(xmbshl(x, (n)>>3), (n)&15),\
xmshr64(xmbshl(x, 8+((n)>>3)), 64-((n)&155))); break;
// These macros expand to 7 or 49 cases each:
#define DO_7(f,x) f((x)+1) f((x)+2) f((x)+3) f((x)+4) f((x)+5) f((x)+6) f((x)+7)
#define DO_7x7(f,y) DO_7(f,(y)+1*8) DO_7(f,(y)+2*8) DO_7(f,(y)+3*8) DO_7(f,(y)+4*8) \
DO_7(f,(y)+5*8) DO_7(f,(y)+6*8) DO_7(f,(y)+7*8)
switch (nbits) {
case 0: break;
DO_7(F5, 0) // 1..7
DO_7(F1, 0) // 8,16,..56
DO_7(F1, 7) // 64,72,..120
DO_7x7(F6, 0) // 9..15 17..23 ... 57..63 i.e. [9..63]\[16,24,..,56]
DO_7x7(F2,56) // 65..71 73..79 ... 121..127 i.e. [65..127]\[64,72,..,120]
default: x = xmzero;
}
return x;
}
xm_shr量以上但交换 “SHL” 和无处不在的F [1256]宏 “SHR”。 HTH。
我不认为有更好的办法。我写了一个最近重复这个问题的答案:http://stackoverflow.com/q/34478328/224132。对于编译时常量计数,它会变成4个insns,或者2个insns的count> = 64。通过变量计数,它会分支并将count和64-count从整数转移到向量寄存器。如果数据已经在整数寄存器中,'__uint128_t'在这种情况下会更好。 – 2015-12-27 17:04:12