C8 · Lesson 32 · What the compiler does
How an optimizing compiler turns the same C into fewer instructions
The loop for (i = 0; i < n; i++) s += a[i] * 3; is one line of C. Compiled without optimization, eight passes of it take 147 instructions. Compiled with the optimizer on, the same eight passes take 53, and the answer is the same. The optimizer hasn't done anything clever with the algorithm. It has made a dozen small, safe substitutions, the same ones you'd make writing the assembly by hand, and knowing what they are tells you what to leave to the compiler and what it can't do for you.
- This is the loop compiled the way
-O0does it: every variable (i, n and s) lives in the stack frame, so each use is a load and each change a store. - Each pass reloads i and n, recomputes the address of
a, multiplies by 3 withmul, and loads and stores s. - At the end a0 holds the sum, 93, and a1 reads the board's TIMER, which counts the instructions run: 147.
Predict
The optimized version keeps s in a register, walks a pointer instead of computing i × 4, and multiplies by 3 with a shift and an add. About how many instructions does one pass of its loop take?
6: load the element, shift, add (that's the × 3), add to s, move the pointer, branch. The rest of the 17 were loads and stores of variables, address arithmetic redone every pass, and a jump that rotating the loop removes. The whole run drops from 147 instructions to 53.
Name it
The common optimizations
- Register allocation. Keep variables in registers instead of the stack. At
-O0every variable has a stack slot, and every use is alwand every change asw. This alone is usually the biggest difference between-O0and-O1. - Constant folding and propagation. Work out
3 * 4orn = 8; ... nat compile time. - Common subexpression elimination. Compute
a[i]'s address once if two expressions use it. - Loop-invariant code motion. Move work that gives the same result every pass, like
la t2, a, out of the loop. - Strength reduction. Replace an expensive operation with a cheaper one:
i * 4with a pointer that moves by 4,x * 3with(x << 1) + x, division by a constant with a multiply and a shift. - Loop rotation. Put the test at the bottom so each pass needs one branch instead of a branch and a jump.
- Inlining. Copy a small function's body into its caller, removing the call, the return and the argument moves, and often opening the way to the other optimizations.
- Dead-code elimination and unrolling (several copies of the body per pass, fewer branches).
What the compiler can't do
It must keep the program's meaning for every possible input, so it's cautious where it can't prove something:
- Aliasing. If two pointers might point at the same memory, a store through one may change what the other reads, so the compiler reloads values it would otherwise keep in registers. C's
restrictpromises they don't overlap. - Calls to unknown code may change any global, so globals are reloaded after them.
volatilevariables are loaded and stored exactly as written (lesson 18).- Floating-point sums can't be reordered, because rounding makes differ from .
Reading the result
Optimization levels trade compile time, speed and size: -O1 and -O2 for speed, -Os for size, which matters on small flash chips. To see what was done, read the assembly (-S) or step through it in a debugger, and to know whether it helped, measure (lesson 31).
The same loop as the optimizer writes it. Step through and compare the passes.
Worked example
A loop over 1000 elements computes each address with slli and add from an index. Strength reduction replaces that with a pointer that moves by 4. How many instructions does that save?
Show the solution
- Before. 2 instructions a pass for the address, plus an
addifor i. - After. One
addifor the pointer, and the index often disappears entirely, since the loop can stop when the pointer reaches the end. - The saving. That's 2 instructions saved per pass, 2000 in all.
- In the program above. The change from 17 to 6 instructions a pass is this plus register allocation, hoisting and rotation together.
Answer 2 instructions a pass, 2000 over the loop.
Worked example
A 3-instruction function is called a million times; each call costs a jal, a ret and two argument moves. What does inlining save?
Show the solution
- Before.
- After. so the calls were 57% of the work.
- More savings. Inlining also lets the compiler optimize the body together with the caller's code, for instance folding a constant argument, which often saves more than the call itself.
- The cost. It costs size: a big function inlined in many places makes the program larger.
Answer inlining saves 4 million instructions, the 57% of the work that went to the calls.
Worked example
void f(int *a, int *b) { *a += *b; *a += *b; }. Why can't the compiler load *b once? Work it out for a call where a and b both point at an int holding 1.
Show the solution
- What overlap does. If a and b point at the same int, the first statement changes
*btoo. - The right result. 1 + 1 = 2, then 2 + 2 = 4.
- Loading
*bonce. A compiler that loaded*bonce into a register would compute 1 + 1 + 1 = 3. - So it reloads. Since it can't rule out that call, it must reload
*bafter the store. restrict. Declaringint *restrict a, int *restrict bpromises the pointers never overlap, and then it may keep*bin a register.
Answer a and b may point at the same int, which should end at 4, and loading *b once would give 3.
Check
An unoptimized loop takes 14 instructions a pass; optimized, it takes 6. It runs 1000 passes.
(a)
How many instructions does optimization save?
(b)
By what factor does the loop speed up, at one instruction a cycle?
Check
A function with a 2-instruction body is called 1000 times, and each call costs 6 more instructions.
(a)
How many instructions do the calls run in all?
(b)
What share of that does inlining remove?
Check
Strength reduction turns a multiply by into a shift and an add.
Step 1
What is x shifted left by m?
Type it the way you would write it, like 3sin(2πft) or 3*sin(2*pi*f*t). Angles can be in radians or carry a degree sign, like 45°.
Step 2
What does adding x to that give?
Check
Multiply a0 by 10 without mul, and put the result in a1.
RISC-V RV32IM (base integer plus multiply and divide). End your program with ebreak. Tab indents; press Esc and then Tab to move on.
Check
*a += *b; *a += *b; runs with a and b pointing at the same int, which holds 5.
(a)
What does the int hold afterward?
(b)
What would a compiler that loaded *b only once produce?
Check
A loop runs 1000 passes of a 3-instruction body, with 2 instructions of loop overhead per pass.
(a)
How many instructions does it run?
(b)
Unrolled by 8?
Check
A loop sums the elements of a float array. Why won't the compiler split the sum into four partial sums to use four adders at once, as it would for an int array?
Explain why
Why does compiling with -O0 produce so many loads and stores, and why is that useful when debugging?
At -O0 the compiler gives every variable a home in the stack frame and translates each statement on its own: it loads the variables the statement reads, computes, and stores the result back before moving on. That's slow, because most instructions just shuffle values between memory and registers, but it means that at every line the variables in memory hold exactly the values the source says they should. A debugger can stop anywhere and show them, and stepping line by line follows the source. With optimization, values live in registers, statements are merged or moved, and some variables vanish, so the machine state no longer lines up neatly with the source.
Practice
Keep practicing
8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.