-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Help the compiler vectorize adjacent_difference
#4958
Conversation
This comment was marked as resolved.
This comment was marked as resolved.
Interestingly it vectorizes if we use |
Thanks! 😻 I pushed minor nitpicks and a significant fix for C++14/17. Speedups look good on my 5950X:
|
I'm mirroring this to the MSVC-internal repo - please notify me if any further changes are pushed. |
I had to push an additional commit to fix the overlap check for heterogeneous types. |
Thanks for helping the compiler, said the author of the presentation, Don't Help The Compiler 😹 😻 🎉 |
📜 The approach
The following things prevented the original algorithm from vectorization:
🛑 Correctness concern
The standard defines exact steps for this algorithm. The optimization alters the steps.
In particular the standard wants the subtracted value to be saved from the previous iteration, rather than being read again.
The two below sections explain what precautions are made to make the change unobservable, so I hope the change is correct.
✅ Checks for eligibility
The following checks were added:
There's no need in check for integral types or so, since the compiler makes the final decision anyway, and it may be able optimize even something that wouldn't pass a strict check.
Apparently there's no rule that the source and the destination ranges may not overlap.
We should handle aliasing.
Unlike the #4431 precedent, we can't yield to the compiler here. The compiler is able to insert overlaps check that prevents vectorization and go to the scalar fallback in case of checks failure, but:
So we do our own checks.
Then we tell the compiler with
__restrict
that we already checked, and it should not bother. This is done in a separate function, because the__restrict
is not aliased within scope, so saying__restrict
within the original algorithm would apparently be a lie.The extra check by the compiler, if not prevented would slightly add run time and dead code size.
😾 Compiler warnings
We have a great feature called integral promotion. Smaller types are converted to integers, and there is a warning about converting them back. Local pragma suppresses them in benchmark, but not in the test.
@StephanTLavavej used a function object with
static_cast
to avoid warnings in the test.⏱️ Benchmark results
🥇 Results interpretation