4 ms·
One optimization I've always found impressive: #include <stdint.h> uint32_t testFunction(uint32_t x) { return ((x & 0xff) << 24) | ((x & 0
by JoshTriplett 10y ago
One optimization I've always found impressive:
#include <stdint.h>
uint32_t testFunction(uint32_t x)
{
return ((x & 0xff) << 24) | ((x & 0xff00) << 8) | ((x & 0xff0000) >> 8) | ((x & 0xff000000) >> 24);
}
compiles into:
testFunction(unsigned int):
mov eax, edi
bswap eax
ret
Another fun one, that only works with clang:
#include <stdint.h>
int testFunction(uint64_t x)
{
int count;
for (count = 0; x; count++)
x &= x - 1;
return count;
}
compiles into:
testFunction(unsigned long):
popcnt rax, rdi
ret
- eridius 10y agoImpressive? Those are probably specially-coded optimizations rather than the result of generic optimizations.
- JoshTriplett 10y agoAs I understand it, the bswap optimization doesn't pattern-match for that specific code (and it works for any equivalent shift/mask code); it analyzes the flow of the bits to figure out the final bit pattern relative to the original, realizes the whole expression had the effect of a bswap, and substitutes a bswap.
- dom0 10y agoYes, that's called pattern matching.
- IshKebab 10y agoNot the kind of pattern matching they were talking about.
- sunfish 10y agoActually, in LLVM's case it really is just explicitly checking for a few specific bswap patterns rather than doing anything fancy: https://github.com/llvm-mirror/llvm/blob/master/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp#L1594 https://github.com/llvm-mirror/llvm/blob/master/lib/Transfor...
- gratilup 10y agoAs a compiler engineer, those are some of the least impressive things done by modern compilers. Why? Because there isn't anything smart behind them, it's pure pattern matching.
- AstralStorm 10y agoThe latter is generally not faster on most modern chips. Results in similar microcode to non vectoring assembly, but you need to put data in the SSE registers which is not free. A smart compiler would not use the new SSE version. (perhaps you didn't set the flags right?) This is why: http://0x80.pl/articles/sse-popcount.html http://0x80.pl/articles/sse-popcount.html
- gpderetta 10y agoThere is no sse usage in the popcnt example posted by the OP. That's probably why you are getting downvoted.
- dangerbird2 10y agoThe second example makes sense: rdi stores the first subroutine argument in amd64 calling conventions and rax stores the return value. I imagine it's easy for the compiler to infer that the loop is just counting 1 bits, which popcnt does. I imagine if you called functions or initialized local variables in the loop, it would be much more messy