C832 of 55
0 XP
  1. Hook
  2. Play
  3. Predict
  4. Name it
  5. Check
  6. Explain

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 -O0 does 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 with mul, 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?

Name it

The common optimizations

  • Register allocation. Keep variables in registers instead of the stack. At -O0 every variable has a stack slot, and every use is a lw and every change a sw. This alone is usually the biggest difference between -O0 and -O1.
  • Constant folding and propagation. Work out 3 * 4 or n = 8; ... n at 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 * 4 with a pointer that moves by 4, x * 3 with (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 restrict promises they don't overlap.
  • Calls to unknown code may change any global, so globals are reloaded after them.
  • volatile variables are loaded and stored exactly as written (lesson 18).
  • Floating-point sums can't be reordered, because rounding makes (a+b)+c differ from a+(b+c).

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
  1. Before. 2 instructions a pass for the address, plus an addi for i.
  2. After. One addi for the pointer, and the index often disappears entirely, since the loop can stop when the pointer reaches the end.
  3. The saving. That's 2 instructions saved per pass, 2000 in all.
  4. 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
  1. Before. N=106×(3+4)=7×106
  2. After. N=3×106 so the calls were 57% of the work.
  3. 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.
  4. 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
  1. What overlap does. If a and b point at the same int, the first statement changes *b too.
  2. The right result. 1 + 1 = 2, then 2 + 2 = 4.
  3. Loading *b once. A compiler that loaded *b once into a register would compute 1 + 1 + 1 = 3.
  4. So it reloads. Since it can't rule out that call, it must reload *b after the store.
  5. restrict. Declaring int *restrict a, int *restrict b promises the pointers never overlap, and then it may keep *b in 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 2m+1 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°.

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?

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.