1

If in a function I need a fixed shuffle mask, should I set it as const or static const?

const __m128i SHUFFLE_MASK = _mm_setr_epi8(0,  4,  8, 12, -1, -1, -1, -1,
                                           -1, -1, -1, -1, -1, -1, -1, -1);

static const __m128i SHUFFLE_MASK = _mm_setr_epi8(0,  4,  8, 12, -1, -1, -1, -1,
                                                  -1, -1, -1, -1, -1, -1, -1, -1);
Antonio
  • 19,451
  • 13
  • 99
  • 197
  • possible duplicate of [C++ semantics of \`static const\` vs \`const\`](http://stackoverflow.com/questions/3709207/c-semantics-of-static-const-vs-const) – Adriano Repetti Jan 17 '14 at 11:00
  • @Adriano I don't know if it is a real difference, but I am using a function to initialize the variable, not a constant. As a side note, the function is not a static function. – Antonio Jan 17 '14 at 11:01
  • If function is static or not IMO doesn't matter (as it doesn't matter if you're using a function or literal values, it's not a constexpr). Anyway I'd use static const because at first sight you do that computation once (but here a compiler can be much clever than what we expect so an inspection to generated code may be more useful than my guessing). – Adriano Repetti Jan 17 '14 at 11:07
  • I agree with Adriano - check the generated code. In my case, a static const variable was much worse because g++ generated code to check if the variable was set each time. YMMV. – Emil Styrke Apr 08 '14 at 08:09

1 Answers1

1

Usually _mm_setr_epi8 of compile-time-constant data ends up compiling to a 16B chunk of read-only data that gets loaded (or used as a memory operand). (look for labels like .LC0 in the gcc -S asm output). This is already optimal.

Emil Styrke commented that static const can end up including code to check if the static location is already initialized. Since there's no benefit, and a possible cost (at least on older gcc, haven't checked myself), avoid static const for vectors (esp. when the declaration and initializer is inside a function).

IDK if gcc ever optimizes a setr that has a pattern in the data into a movd and shuffle, or something like that. If so, then you might potentially want to avoid generating your constant with instructions, instead of having it there as a memory operand.

This seems like a very unlikely case, though. But if you need to defeat such an optimization, you can probably do it using a static (file-scope) char array to hold your constant, and casting a pointer to a vector type.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847