r/programming • u/mcmcc • May 30 '17
Compiler Optimizations are Awesome
https://blog.regehr.org/archives/15159
u/t0rakka May 31 '17
The value of optimizing compiler is that you can write reasonable code and not by default expect it to result in completely garbage machine code. There is a symbiosis between experienced programmer and a compiler; the programmer will know how specific idioms will behave when translated into machine code. This is however on-going process because what you "know" has to be updated periodically. This causes "code rot" which means old code begins to stink - it is written with specific idioms and patterns that obfuscate the intent the programmer had in mind when he crafted the code in the first place.
The code that survives the test of time best is simplest possible code to solve a specific problem.
Meanwhile in the real world computers have finite performance and code has to be fast enough to get the job done. Number of CPU cores has been stuck to ~4 cores on mainstream desktop for a long while now. There is a change coming in the near future to this which means more multi-threading which means more complicated code. Clarity of expressing our intent will be more important than ever. I welcome the awesome compiler optimizations. :)
6
May 31 '17
Second, size matters. Most of the computers in the world are embedded and many of these are storage-constrained. Compiler optimization reduces code size and this phenomenon is completely independent of the hot/cold issue.
I wonder if he has numbers to back this up, that optimizations reduce code size compare to naive compiling. If we compile
int factorial(int x) {
return x > 1 ? x * factorial(x-1) : 1;
}With no optimizations (on my particular version of GCC, which is 7.0 from git not that long ago) we get
_Z9factoriali:
.LFB0:
.cfi_startproc
push rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
mov rbp, rsp
.cfi_def_cfa_register 6
sub rsp, 16
mov DWORD PTR [rbp-4], edi
cmp DWORD PTR [rbp-4], 1
jle .L2
mov eax, DWORD PTR [rbp-4]
sub eax, 1
mov edi, eax
call _Z9factoriali
imul eax, DWORD PTR [rbp-4]
jmp .L4
.L2:
mov eax, 1
.L4:
leave
.cfi_def_cfa 7, 8
ret
.cfi_endprocIf I compile with -O3 I get
_Z9factoriali:
.LFB0:
.cfi_startproc
cmp edi, 1
jle .L7
lea eax, [rdi-2]
lea ecx, [rdi-1]
cmp eax, 7
jbe .L8
mov DWORD PTR [rsp-12], edi
mov edx, ecx
xor eax, eax
movd xmm5, DWORD PTR [rsp-12]
shr edx, 2
movdqa xmm0, XMMWORD PTR .LC0[rip]
pshufd xmm2, xmm5, 0
movdqa xmm4, XMMWORD PTR .LC2[rip]
paddd xmm2, XMMWORD PTR .LC1[rip]
.p2align 4,,10
.p2align 3
.L4:
movdqa xmm3, xmm2
add eax, 1
movdqa xmm1, xmm2
cmp eax, edx
paddd xmm2, xmm4
pmuludq xmm3, xmm0
psrlq xmm0, 32
psrlq xmm1, 32
pmuludq xmm1, xmm0
pshufd xmm0, xmm3, 8
pshufd xmm1, xmm1, 8
punpckldq xmm0, xmm1
jb .L4
movdqa xmm2, xmm0
mov edx, ecx
movdqa xmm1, xmm0
psrlq xmm0, 32
and edx, -4
psrldq xmm2, 8
sub edi, edx
cmp ecx, edx
pmuludq xmm1, xmm2
psrlq xmm2, 32
pshufd xmm1, xmm1, 8
pmuludq xmm0, xmm2
pshufd xmm0, xmm0, 8
punpckldq xmm1, xmm0
movdqa xmm0, xmm1
psrldq xmm1, 4
pmuludq xmm0, xmm1
movd eax, xmm0
je .L1
lea ecx, [rdi-1]
.L3:
imul eax, edi
cmp ecx, 1
je .L1
lea edx, [rdi-2]
imul eax, ecx
cmp edx, 1
je .L1
lea ecx, [rdi-3]
imul eax, edx
cmp ecx, 1
je .L1
lea edx, [rdi-4]
imul eax, ecx
cmp edx, 1
je .L1
lea ecx, [rdi-5]
imul eax, edx
cmp ecx, 1
je .L1
lea edx, [rdi-6]
imul eax, ecx
cmp edx, 1
je .L1
imul eax, edx
sub edi, 7
imul eax, edi
retSorry for the wall of text.
23
u/TNorthover May 31 '17 edited May 31 '17
It depends what you tell the compiler. Especially, "-O3" tells the compiler to aim for performance no matter what the size penalty is. It may or may not succeed, but a line-by-line dump doesn't argue either way.
Both GCC and Clang produce more compact code with "-Os" (optimize for size, though they both interpret that differently too).
2
May 31 '17
To be clear I'm not saying optimizations can't create more compact code, that's obviously false (and while I've never measured I am reasonably confident
-Osdoes a reasonable good job at it). I just wonder whether or not the normal optimizations gcc/clang run actually end up creating more compact code or not.8
u/TNorthover May 31 '17
That's definitely worth worrying about. I can't speak for GCC, but Clang interprets
-Osas "go fast but don't unnecessarily bloat code". Generally it ought to be a decent balance, but that definition is so hand-wavy as to be meaningless.If you use
-O2or-O3, clang will assume you don't care about code size.In either case it's not possible to work out what actually results in smaller code in general. For example you can come up with small functions that may or may not be worth inlining. Just tiny changes in the rest of the program can make a function better standalone or better inlined (or better inlined sometimes).
7
u/masklinn May 31 '17
If you use -O2 or -O3, clang will assume you don't care about code size.
That's true for O3, but not for O2. O2 is "try to strike a good balance", Os is based on O2 but may disable some optimisations which "typically increase code sizes" and enable some optimisations specifically designed to reduce code size.
In Clang, Os is identical to O2, and has been for years (since at least 3.2).
5
May 31 '17
You seem like the sort of person who might be able to answer this.
I only have a surface knowledge of optimization, but something that is repeatedly a lot these days is that making data small/fit in cache is pretty much the most important thing you can do. Why doesn't increasing code size go against that?
14
u/evaned May 31 '17
something that is repeatedly a lot these days is that making data small/fit in cache is pretty much the most important thing you can do. Why doesn't increasing code size go against that?
Not the person you're replying to, but... it does. Just one of many things that the compiler has to weigh, and why optimization is haaard.
But everything is a tradeoff, right? For example, maybe the compiler enlarges a performance-critical section of code that's executed repeatedly, but even the enlarged version still fits into the cache (so there's no hit while it's running) and whatever optimizations made it larger helped more during its processing than the extra cache pressure cost.
There are also optimizations that will often help but sometimes hurt, but the compiler can't tell when each will happen; but because they help more than they hurt, it applies them.
Finally, I don't have concrete data to back this up, but I suspect that data cache locality matters more than instruction cache locality, in the sense that it's much easier to blow your data cache than instruction cache. This guess is based on the fact that most (longer-lived) programs have much more data than code. Even extremely large programs have "only" a couple hundred MB of code,1 but will often operate on GBs of data. I also suspect it's much more common for a relatively tight loop to walk over a huge amount of data than it is for a small amount of data to be accessed by an enormous amount of code in sequence.
1 For example, Chrome running on my system seems to have around 250 MB of executable memory (I got that via
cat /proc/2230/maps| grep r-x| cut -d" " -f1| sed 's/^\([0-9a-f]*\)-\([0-9a-f]*\)$/0x\2-0x\1/'| tr '\n' '+'and evaluating that expression), but apparently something like 6 GB (!) of virtual address space used, 933 MB of which is resident.5
u/AlotOfReading May 31 '17
Like everything else in optimization, it depends heavily on the particulars. Some optimizations like loop unrolling force you to make a choice between smaller and faster, although the degree of both depends on the code preceding the immediate assembly, as well as where the code is in memory and the system state.
5
u/ThisIs_MyName May 31 '17 edited May 31 '17
Why doesn't increasing code size go against that?
Sometimes -Os results in faster code than -O2 for exactly this reason. Compiler flags like "funroll-loops" are also a meme for this reason.
Another issue is that optimizations that increase code size do very well on naive benchmarks because most benchmark executables are small enough to always fit in the cache. Real binaries don't.
In most cases however, -O2 is faster.
1
u/doom_Oo7 May 31 '17
Sometimes -Os results in faster code than -O2 for exactly this reason.
in any remotely recent benchmark it's not the case
4
May 31 '17
The most code fattening optimisations are inlining and loop unrolling. While they are obviously damaging cache locality, they are enabling potentially many other optimisations and therefore worth trying. If your cost model is reasonable, you can balance code size vs. the effects of a better vectorisation, specialisation, constant propagation, etc.
17
u/zoells May 31 '17
What about with -Os?
5
u/holgerschurig May 31 '17 edited May 31 '17
Much, much smaller, albeit compiled with a much older gcc:
$ gcc-4.9 -Os -c -o fact.o fact.c $ objdump -d fact.o fact.o: file format elf32-i386 Disassembly of section .text: 00000000 <factorial>: 0: 55 push %ebp 1: b8 01 00 00 00 mov $0x1,%eax 6: 89 e5 mov %esp,%ebp 8: 8b 55 08 mov 0x8(%ebp),%edx b: 83 fa 01 cmp $0x1,%edx e: 7e 06 jle 16 <factorial+0x16> 10: 0f af c2 imul %edx,%eax 13: 4a dec %edx 14: eb f5 jmp b <factorial+0xb> 16: 5d pop %ebp 17: c3 ret(I like the objdump output for this purpose better, because you can immediately see the byte count on the left column).
BTW, clang-3.8 for this simple procedure only emits 0x15 (21) bytes of instructions with
-Os. And 0x14c (332) bytes with-O3.8
u/jpakkane May 31 '17
For -O2 (according to Compiler Explorer, GCC 7):
factorial(int): cmp edi, 1 mov eax, 1 jle .L4 .L3: imul eax, edi sub edi, 1 cmp edi, 1 jne .L3 rep ret .L4: rep retWhich is noticeably smaller than without optimizations.
2
2
u/maxhaton May 31 '17
That's not a good example. This is best demonstrated by how good compilers are at eliminated unused variables and common subexpessions(Both done easily with SSA IRs). This is a very cheap optimisation and can eliminate entire basic blocks of code that would otherwise do nothing. Your factorial example is only a good example for showing off the auto-vectorisation and loop unrolling of one's compiler.
You are also optimising for speed (-O3) not size.
2
u/industry7 May 31 '17
Many compilers allow you to choose between optimizing run time speed vs optimizing executable size vs optimizing run time power usage, etc.
1
u/ellen_magic May 31 '17
Bernstein's talk is filled with detail and examples. John Regehr's dismissal is just a few paragraphs of personal claims.
2
84
u/slavik262 May 31 '17
Do people seriously make arguments that compiler optimizations aren't useful? Have they ever looked at the assembly compilers emit without optimizations enabled? It's incredibly bad.
Also, anybody who quotes Knuth as saying,
without the sentence that immediately follows:
is either misinformed or disingenuous.