Equivalent of __builtin_shuffle in Clang?

I’ve been working on some vector operations in C/C++ and I came across the GCC built-in function __builtin_shuffle. However, when I tried to compile the same code with Clang, I encountered an error: “error: use of undeclared identifier ‘__builtin_shuffle’”.

Is there an equivalent function or method in Clang that I can use for this purpose?

I found a useful resource in the GCC documentation regarding “Using Vector Instructions through Built-in Functions,” which can be found here. This might be helpful for those who are looking for information on vector extensions in GCC.

#include <stdio.h>

typedef int   v4si __attribute__ ((vector_size (16)));
typedef float v4sf __attribute__ ((vector_size (16)));

int main() {
    v4sf v1 = v4sf{1, 2, 3, 4};
    v4sf v2 = v4sf{10, 20, 30, 40};
    v4sf v3 = __builtin_shuffle(v1, v4si{0,2});
    v4sf v4 = __builtin_shuffle(v1, v2, v4si{0,4,1,5});

    printf("{%g,%g,%g,%g}\n", v1[0], v1[1], v1[2], v1[3]);
    printf("{%g,%g,%g,%g}\n", v2[0], v2[1], v2[2], v2[3]);
    printf("{%g,%g,%g,%g}\n", v3[0], v3[1], v3[2], v3[3]);
    printf("{%g,%g,%g,%g}\n", v4[0], v4[1], v4[2], v4[3]);
    return 0;
}

Output (GCC):
{1,2,3,4}
{10,20,30,40}
{1,3,?,?}
{1,10,2,20}

If anyone can help me find an equivalent function or workaround for Clang, I’d greatly appreciate it.

I guess the big question is for what reason (since that may change the answer).

I’ve used std::mt19937 for shuffling needs but there’s also std::shuffle.

1 Like

The reason: Transpiling into C++ from a programming language is made more convenient when using __builtin_shuffle . Because for example “u = v.wzyx;” → “u = __builtin_shuffle(v, v4si{3,2,1,0});”. Moreover, this built-in function allows seamless shuffling not only within a single variable but also between two distinct variables.

However, Clang doesn’t support it.