r/cpp • • 25d ago

Catastrophic misoptimization of byte-range equality comparison in all major C++ compilers (and Rust). Language issue or compiler issue?

Someone brought a C++ snippet that reduced to the following (std::array used instead of char* for consistency for later)

bool eq2(const std::array<char, 64>& lhs, const std::array<char, 64>& rhs) {
    for (int i = 0; i < 64; ++i)
        if (lhs[i] != rhs[i])
            return false;
    return true;
}

It basically returns true iff two 64 byte memory regions are a bitwise match. You'd think this can be optimized by modern compilers flawlessly, right? Right?! And the worst thing that can happen is it doesn't get autovectorized, right? Right?!

Well, to everybody's surprise... https://godbolt.org/z/v4d8G5ovh

GCC attempts to partially conditionally vectorize but doesn't want to use unaligned loads. Moreover its vectorization is way more cumbersome than it needs to be. Then after it finds a mismatch it... reverts to the unvectorized version?! Clang and MSVC do not even attempt to vectorize it - and in a way it makes them end up better than GCC, which is wild.


Now, to try to investigate we've checked how it looks in Rust. https://godbolt.org/z/K7xE3qc94. It does what GCC does but fully vectorized.

At this point we're confused as to what the source of the problem is. Are we missing something with respect to what transformations are allowed? Is it really that much to ask from the as-if rule?

As a sanity check we use std::array's operator==. https://godbolt.org/z/xPhPYMjvz. Oh would you look at that? Now the compilers can do well (ok not you MSVC. GCC also fumbles the flag register slightly). The situation is the same in Rust - https://godbolt.org/z/3GjWorze8. Not only does it vectorize correctly but the vectorized code is better - using vpxor.


Ultimately this isn't just academical. Situations like this undermine the trust in the compiler at the most fundamental level. Not every place can use std::array, not everyone can use ranges and span yet. We could use std::equal but why does it matter so much? What if != changes to < and there's no good solution anymore? To what degree are we supposed to be paranoid about basic optimizations being done or not?

The similarity of codegen between Rust and C++ would point to it being either a compiler issue or a fundamental code correctness issue. The fact that C++ Clang differs from Rust (LLVM) would suggest it's at least partially a language issue. Why is this extremely simple code so nasty?


edit. some more [not so] fun findings https://www.reddit.com/r/cpp/comments/1xlyti8/catastrophic_misoptimization_of_byterange/19s1i09srxdaa/

100 Upvotes

122 comments sorted by

View all comments

112

u/ts826848 25d ago edited 25d ago

When I saw "misoptimization" in the title I thought I would see an incorrect optimization, not a missed optimization.

Passing -Rpass-missed=.* -Rpass-analysis=.* to Clang results in the following:

<source>:4:5: remark: loop not vectorized: Latch block does not have a countable exit condition [-Rpass-analysis=loop-vectorize]
<source>:4:5: remark: loop not vectorized: Cannot vectorize uncountable loop [-Rpass-analysis=loop-vectorize]
<source>:4:5: remark: loop not vectorized [-Rpass-missed=loop-vectorize]
<source>:5:13: remark: Cannot SLP vectorize list: vectorization was impossible with available vectorization factors [-Rpass-missed=slp-vectorizer]
    5 |         if (lhs[i] != rhs[i])
      |             ^

So I think the early bailout is confuzzling LLVM's autovectorizer.

And indeed, if you replace the early return with a result variable you get a significantly better result, albeit one that still isn't quite as good as lhs == rhs. Looking at the LLVM IR there's something funky going on with the way it combines intermediate variables (involving freezing uninitialized bits?), and it seems this is sufficient to result in differences in code generation. If you replace the if in the loop with a &= to eliminate the early return entirely you get the same assembly as lhs == rhs

Situations like this undermine the trust in the compiler at the most fundamental level.

The extent to which your trust is undermined depends entirely on what you want and/or need out of your compiler. For some people, performance is a "nice to have": if the compiler performs a given optimization, great! If not, eh, it's probably fine. For others, performance is effectively a correctness requirement, and the ability to express such requirements is somewhat patchy for different languages (e.g., emplace-like operations, tail calls, guaranteed inlining/autovectorization, etc.).

The fact that C++ Clang differs from Rust (LLVM) would suggest it's at least partially a language issue.

Keep in mind that rustc and Clang are separate frontends with different internals and might output quite different LLVM IR for semantically identical source code. For instance (at least when I last looked) rustc leaned on LLVM's native extended-width integers while Clang performed SROA before emitting LLVM, which means LLVM saw very different IR.

9

u/Sopel97 25d ago edited 25d ago

ok now this one is funny https://godbolt.org/z/Kbd166cME, with i<57 in GCC the codegen is in a way better than for i<64 case, clang vectorizes correctly (and it's non-obvious!)

edit. https://godbolt.org/z/ezY8P87oG

5

u/Sopel97 25d ago edited 25d ago

I see now how the title is ambiguous. Didn't want to call it a missed optimization due to the behavior of GCC and rustc. Sorry about that.

Thanks for the insight. https://github.com/llvm/llvm-project/issues/238003 would suggest that with llvm it's indeed some specific reduction dead-end that is not hit with clang.

35

u/SleepyMyroslav 25d ago

I think you don't understand the meaning of the word 'catastrophic'. For non-native English speakers like me, it is even worse than you can imagine. If you want to vectorize something, you will have to do it with explicit tools (like Highway, https://github.com/google/highway for example).

4

u/13steinj 25d ago

I consider such a missed optimization a catastrophic result. I have too many engineers (read: more than 0 normally, more than 10 because of LLMs) writing manual ASM and/or intrinsics rather than trusting the compiler.

If it can't do the (seemingly) simple cases, it gives this group a pass to continue doing what they are doing.

12

u/CocktailPerson 25d ago

Those people will always find a way to justify writing assembly and intrinsics, because they think writing assembly and intrinsics is fun. They have a vested interest in distrusting the compiler.

If someone uses this as a reason to write assembly or intrinsics when == is right there and does what they want, then they are not a serious person and shouldn't be treated as such.

4

u/13steinj 24d ago

Firstly, this is a reduced case. Does == work if on a struct that contains one character but does not itself have an operator==? This code is reasonable and can exist-- private methods that understand the internal layout and semantic of related library types, but has no external semantic for equality. In such cases, == is not "right there and does what they want."

Secondly, it's usually not vested interest, but rather paranoia, that comes from cases like these.

2

u/CocktailPerson 24d ago

First, doesn't matter. Reduced cases the only ones for which writing assembly is a feasible alternative. If you dismiss enough of these silly "reduced cases" with "write idiomatic C++," you eventually get cases that are too complex to justify writing in assembly anyway. And then you just make them write non-idiomatic but performant C++ instead.

I'm not sure I get the point of your char-struct example either. Would people really suggest writing something with non-primitive types like that in assembly? If somebody uses that as an example of why you can't blindly trust the compiler, then sure, but if someone uses that as an example of why you can't blindly trust the compiler and therefore need to write it in assembly instead, then again, they're not a serious person.

Second, it is vested interest, expressed as paranoia. They want to write assembly, so they concern-troll about cases like these instead of just inspecting the compiler output and reasoning about how to change the source code to improve the output. Again, these are not serious people. You can just reject their silly little assembly routines, tell them to write idiomatic C++, and ignore them.

1

u/FrogNoPants 23d ago

I write C++ code that uses intrinsics every day, and I rarely drop down to "assembly" or even raw intrinsics, we can wrap intrinsics in libraries easily enough these days, so it isn't just for reduced cases--it applies to pretty much anything that is a bottleneck.
I'm not going to inspect the compilers output on every update or minor code change, that is a waste of time. Also I have far too much code that uses intrinsics under the hood to be bothered with that.

3

u/cd_fr91400 25d ago

AO wrote "Someone brought a C++ snippet that reduced to the following...".

The important word here is "reduced".
It does not mean their actual case is a == case. It means they could simplify their case to such a simple one, so we, as redditors, can understand it.

I am not strongly opposed to the first part. I am not advocating for writing assembly and intrinsics. I just say these persons *may* have good reasons to do so. I do not know their case, I have no opinion about their seriousness.

5

u/ts826848 25d ago

Hey, you never know, everyone could be missing the optimization in completely different ways! Optimization is an endless rabbit hole.

6

u/Ameisen vemips, avr, rendering, systems 25d ago

I've had this happen. I had an optimization issue where having a function that had a single argument that was then immediately returned, but also having a __builtin_assume or equivalent asserting what its value was (or was constrained to be), caused worse codegen on GCC, Clang, and MSVC. Apparently due to the assume screwing up the optimizer's understanding that the returned value was identical to the argument.

1

u/Kristine_1975 24d ago

Yeah, clang's __builtin_assume is... counter-intuitive: https://discourse.llvm.org/t/llvm-assume-blocks-optimization/71609

2

u/-dag- 25d ago

So I think the early bailout is confuzzling LLVM's autovectorizer.

That's crazy. Good vectorizing compilers can easily handle that.

13

u/F54280 25d ago

Why would that be? With early bailout, the behavior of the code is defined to be different if there is a pagefault while reading the lhs or rhs.

Now, is the compiler able to decide that this cannot happen with std::array is a different question…

-3

u/-dag- 25d ago

Masking should suppress faults. 

7

u/F54280 25d ago

The code OP presented does generate a fault if everything is equal up to the fault, and not fault in the other case. The simd version will not have the same fault behavior.

→ More replies (1)

13

u/ts826848 25d ago

I guess that means LLVM isn't quite a good vectorizing compiler then? Though to be fair the remark on its own doesn't indicate whether not autovectorizing cases like this is intentional (e.g., cost-benefit ratio isn't good enough or the like).

-6

u/-dag- 25d ago

Correct. See what the Intel compiler does with it. 

15

u/ts826848 25d ago

This? It looks basically identical to what Clang outputs (which kind of makes sense since icx is LLVM-based these days), though to be fair I am very much not familiar with Intel's compiler so maybe I'm just holding it wrong.

0

u/chibuku_chauya 25d ago

Try icc on Godbolt instead. That’s the old Intel compiler.

12

u/ts826848 25d ago

I actually originally tried that one because I didn't know Intel's compiler now goes by icx, but the codegen didn't seem much better.

15

u/Poddster 25d ago

No no, try this other compiler!

-2

u/chibuku_chauya 25d ago

Ah, good to know!