I was reading a C++ paper on if consteval (§3.2), and saw a code showing a constexpr
strlen
implementation:
constexpr size_t strlen(char const* s) {
if constexpr (std::is_constant_evaluated()) {
for (const char *p = s; ; ++p) {
if (*p == '\0') {
return static_cast<std::size_t>(p - s);
}
}
} else {
__asm__("SSE 4.2 insanity");
}
}
I'm here to ask about the __asm__
statement in the else branch.
I know that's humour and not meant to be taken seriously, but I still decided to do some researches in case someone already explained it. When I googled the quoted message I had less than 10 results, all about this piece of code. I then researched what is SSE 4.2 and found that it's a CPU instruction set, so I really have no clue about what it appears in a C++ paper, does someone have an explanation? Thanks to those who'll read my post.
cigien is correct:
It's a placeholder to mean "some crazy SSE 4.2 stuff" :) It's not a real instruction
Although to be fair, I can't take credit for this particular joke, it comes from David Stone's constexpr function parameters paper.
The point here isn't what is actually the optimal way to implement strlen
with SSE instructions, but rather that there is a way to do so if you hand-write your assembly, which is likely going to be better than the manual loop, and whatever that way is it is definitely not constexpr friendly -- as such the specific instruction list isn't really relevant to the question. Whatever it is, it can't work at compile time, so needs to be switched out.