Lecture 15 · Code optimization

Introduction to Computer Systems · Lecture 15。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 15 (Oct 22), slide deck 15-optimization. Reading: CS:APP3e chapter 5. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and measured on an Apple M4 Pro (macOS, clang 21); 01 cross-compiles to x86-64 to match the slides’ listings. Timing numbers are from one run. Code: code/lecture15/. Reading time: ~90 minutes; ~20 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. List what a compiler can optimize (constant folding, dead code, CSE, code motion, inlining) and the hard limits on it.
  2. Recognize the two optimization blockers — memory aliasing and procedure calls — and remove them (local variables, restrict, hoisting).
  3. Explain cycles per element (CPE) and the difference between the latency bound and the throughput bound.
  4. Apply loop unrolling with multiple accumulators to expose instruction-level parallelism, and know when it stops helping.

0.2 Prerequisites and scope

  • Lecture 8: “trust the compiler” and write clear code — this lecture is when and why that is not enough.
  • Lecture 4: pipelining and branch prediction; Lectures 9–10: the memory system, the other ceiling.
  • In scope: CS:APP chapter 5 — compiler capabilities and limits, optimization blockers, the CPE benchmark, loop unrolling, multiple accumulators, and the latency/throughput bounds.

0.3 Section → code map

SectionIdeaDemo in code/lecture15/
§1what the compiler does; its limits01_compiler_opts.py
§2optimization blockers: aliasing, calls01_… (aliasing), 02_blockers.c (calls)
§3CPE; the latency bound03_cpe.c
§4unrolling and multiple accumulators03_cpe.c

1. What the compiler does, and cannot do

1.1 The optimizations

At -O1/-O2 the compiler applies a battery of transformations. 01_compiler_opts.py shows five in the generated x86-64:

  • Constant folding: evaluate constant expressions at compile time. 0xFF<<8 + 7*6 becomes a single movl $65322 — no shift, multiply or add.
  • Dead-code elimination: drop computations whose results are unused (the demo’s unused x*x multiply disappears, imul count 1 → 0).
  • Common-subexpression elimination (CSE): compute a repeated expression once. (x*y)+(x*y)+(x*y) goes from 3 multiplies to 1.
  • Code motion: hoist loop-invariant work out of the loop (n*i computed once, not per iteration).
  • Inlining: paste a small function into its caller and delete the call (inline_caller has no call at -O2).
  #1 const_fold -O2 loads the literal: movl $65322, %eax
  #2 dead_code multiplies: -O0 1 -> -O2 0
  #3 cse multiplies: -O0 3 -> -O2 1
  #5 inline_caller -O2 contains a call? no

None change what the function computes — only how fast. Usually the code shrinks; sometimes it grows (the code_motion loop gets vectorized at -O2, more instructions but faster). Fewer instructions is common, not the goal; speed is.

1.2 The limits

A compiler is bounded (slides “Limits to Compiler Optimization”):

  • It cannot change algorithmic complexity — only constant factors (which can still be 10× or more).
  • It must not change observable behavior, for any input — including edge cases you do not care about but it cannot know you do not.
  • It usually analyzes one function at a time (whole-program/link-time optimization is costly; inlining is the main exception).
  • It cannot see run-time inputs, so it must be correct and reasonable for all of them; “worst case” matters, especially for code exposed to malicious input.

The practical consequence: the compiler will not perform a transformation it cannot prove is safe. Two situations where it cannot are so common they have a name: optimization blockers.


2. Optimization blockers

2.1 Memory aliasing

If a function writes through a pointer, the compiler must assume that write might change any memory the function also reads — unless it can prove otherwise. The slides’ sum_rows1 accumulates into b[i] in memory every iteration; because b might alias a, the compiler cannot keep the running sum in a register. A local accumulator (sum_rows2) removes the doubt: the compiler keeps it in a register and stores to b[i] once.

01_compiler_opts.py shows the effect in the code for a vector accumulate *dest = *dest + src[i]:

  combine_mem (plain long*):     carries a runtime alias check + scalar fallback
  combine_restrict (restrict):   no check, a clean vectorized loop

Unable to assume dest and src do not overlap, modern clang emits a runtime alias check (compare the pointer ranges) and a scalar fallback for the overlapping case, alongside a vectorized fast path. The restrict keyword — “this is the only pointer to that memory” — lets the compiler drop the check and the fallback entirely. (On this CPU the run-time cost of the blocker is largely hidden by store-to-load forwarding, so the blocker is clearest in the generated code, not a stopwatch — which is why this one lives in the assembly demo.)

2.2 Procedure calls

The compiler usually cannot prove a function call is free of side effects or that its result is invariant, so it will not hoist, reorder or remove it. The classic trap is a call in a loop condition. 02_blockers.c lowercases a string with strlen(s) in the loop test vs the length hoisted into a local:

  length n   strlen-in-loop   hoisted      growth
  25000      10.14 ms         0.008 ms
  50000      40.29 ms         0.016 ms     4.0x
  100000     160.34 ms        0.031 ms     4.0x
  200000     639.08 ms        0.060 ms     4.0x

strlen is O(n) and runs every iteration, so the loop is O(n²) — the time quadruples when n doubles. The hoisted version is O(n) (doubles), and thousands of times faster at the largest size. The compiler cannot hoist strlen itself: the loop writes s[i], so it cannot prove the length is invariant. You must hoist it.

These are the two blockers the slides stress — memory references and procedure calls. Removing them is the programmer’s job; the compiler stays correct for all inputs.


3. Cycles per element, and the latency bound

3.1 CPE

To talk about the speed of a loop over n elements, the slides use cycles per element (CPE): time = CPE·n + overhead, so CPE is the slope. Lower is better. (These notes report time per element in ns, since user space cannot read the cycle counter on arm64 macOS; at ~4 GHz, 0.25 ns/element ≈ 1 cycle/element.)

The slides’ combine benchmark sums (or multiplies) a vector. 03_cpe.c runs the progression:

  version                ns/element   what
  combine1 (call/elem)   0.783        a function call per element
  combine4 (local acc)   0.538        basic: 1 accumulator, latency-bound

combine1 (the abstract version, a get call per element) is dominated by the call. combine4 (a local accumulator, direct array access — §1’s basic optimizations applied) removes it. But now it hits a wall.

3.2 The latency bound

combine4 is stuck at the latency of one floating-point add. Each iteration’s acc = acc + data[i] needs the previous iteration’s acc, so the adds form a single dependency chain: the CPU cannot start the next add until the last one’s result is ready, several cycles later. The FP-add unit is pipelined — it can start an add every cycle — but a single chain uses only one slot, so throughput is capped at 1/latency. This is the latency bound.

Unrolling the loop does not help if it keeps one accumulator:

  unroll x4, 1 acc       0.556        unrolled but still 1 chain -> no gain

Same single dependency chain, same bound. Unrolling alone reduces loop overhead but not the critical path of a reduction.


4. Breaking the bound: multiple accumulators

The fix is loop unrolling with multiple accumulators: split the sum into K independent running totals, combined at the end. Now there are K independent dependency chains, so K adds can be in flight at once, filling the pipeline. 03_cpe.c:

  unroll x2, 2 accs      0.283        2 independent chains
  unroll x4, 4 accs      0.182        4 independent chains
  unroll x8, 8 accs      0.091        8 independent chains  (~5.9x over combine4)

Nearly linear speedup with the number of accumulators — until the throughput bound: the point where the FP units (times the pipeline depth), or the memory system, saturate and more accumulators stop helping. On this machine eight accumulators reach ~0.09 ns/element, about 5.9× the basic version (and, with the compiler also vectorizing each chain, into the slides’ “several elements per cycle” territory).

Two cautions:

  • For floating point, reassociating the sum into K partial sums changes the result in the last bits (FP addition is not associative — Lecture 1). The compiler will not do it for you unless you pass -ffast-math; writing multiple accumulators is you choosing to accept that. For integers it is exact.
  • Past the throughput ceiling, the bottleneck moves to the memory system (Lectures 9–10) or the functional units; profile to find the knee rather than piling on accumulators.

The slides’ summary of high performance: pick a good algorithm and compiler flags; write compiler-friendly code (no needless blockers); then tune the hot inner loop to the machine — expose parallelism (multiple accumulators, vector instructions), avoid unpredictable branches (Lecture 4), and keep it cache-friendly (Lectures 9–10).


Summary

  • The compiler applies constant folding, dead-code elimination, CSE, code motion and inlining, but only constant-factor gains, never algorithmic ones, and only transformations it can prove preserve behavior for all inputs.
  • Two optimization blockers stop it: memory aliasing (a write might alias a read, so it cannot register-promote — fix with a local or restrict; modern clang instead emits a runtime alias check) and procedure calls (it cannot prove a call is pure, so it will not hoist it — a call in a loop condition is an accidental O(n²), measured).
  • CPE (cycles per element) measures a loop’s speed. A single accumulator is latency-bound — dependent adds chained at 1/latency — and unrolling alone does not help.
  • Multiple accumulators create independent dependency chains that fill the pipelined units: near-linear speedup (measured ~5.9×) up to the throughput bound, after which the memory system or functional units saturate. For FP this changes the low-order bits (non-associativity), a choice the programmer makes.

Common pitfalls

  • Assuming the compiler hoists everything. It will not move a call it cannot prove is pure; hoist invariant calls (especially out of loop conditions) yourself.
  • A function call in a loop test. for (i=0; i<strlen(s); i++) is O(n²). Compute the bound once.
  • Expecting unrolling to speed up a reduction. Unrolling with one accumulator keeps the single dependency chain; use multiple accumulators.
  • Piling on accumulators forever. Gains stop at the throughput bound; beyond it you are memory- or unit-bound.
  • Forgetting FP non-associativity. Multiple FP accumulators change the result’s last bits; fine if you accept it, wrong if you need bit-exactness.
  • Optimizing cold code. Tune the inner loop where the time actually goes; measure first.

Exercises

  1. Name the optimization. -O2 turns int x = 3600 * 24; into a stored constant 86400. Which one, and why is it always safe?

    AnswerConstant folding: both operands are compile-time constants, so the product is known and cannot depend on input — always safe.
  2. Blocker? for (i=0;i<n;i++) total += a[i]*b[i]; with total a global double. What stops the compiler keeping total in a register, and how do you fix it?

    Answer`total` is in memory and might alias `a`/`b` (or be observed concurrently), so the compiler reloads/stores it each iteration. Use a local accumulator and assign `total` once (or `restrict` the arrays).
  3. Accidental quadratic. Why is for (i=0; i<strlen(s); i++) O(n²) while n=strlen(s); for (i=0;i<n;i++) is O(n)?

    AnswerThe first recomputes `strlen` (O(n)) every iteration → O(n²). The compiler cannot hoist it because the loop may change the string. The second computes the length once.
  4. Latency vs throughput. An FP add has latency 4 cycles and the unit is fully pipelined (1 add can start per cycle). What CPE does a single-accumulator sum achieve, and what could 4 independent accumulators achieve?

    AnswerSingle accumulator: each add waits 4 cycles for the previous → CPE ≈ 4. Four independent accumulators keep the pipeline full → CPE ≈ 1 (one add completing per cycle), the throughput bound. More than 4 would not help this single unit.
  5. Does unrolling help? You unroll a sum 8× but keep one accumulator. Expected speedup?

    AnswerLittle to none for the reduction itself — it is still one dependency chain, still latency-bound. You save some loop overhead (fewer branch/increment instructions), but the critical path is unchanged. Add multiple accumulators to actually speed it up.
  6. FP caveat. Why might -ffast-math (or hand-written multiple FP accumulators) give a slightly different sum than the simple loop?

    AnswerFloating-point addition is not associative (Lecture 1), so grouping the sum into partial sums and combining them rounds differently than strict left-to-right addition. The compiler will not reassociate FP by default; `-ffast-math` lets it, and writing multiple accumulators does it explicitly — a deliberate accuracy/speed trade.

No lab is tied to this lecture, but its techniques matter in cachelab Part B (a tight transpose) and in making any lab’s hot loop fast. The method — remove blockers, then expose ILP in the inner loop, then stop when memory-bound — is general.

Further reading

  • CS:APP3e chapter 5 in full; practice problems 5.1–5.15. §5.7–5.9 (modern processors, the combine benchmark, the latency/throughput bounds) match demo 03.
  • Agner Fog’s instruction tables (latencies and throughputs of x86 instructions) and the Apple Silicon optimization notes, for the real numbers behind the bounds.
  • The compiler’s own optimization reports (-Rpass=.* for clang, -fopt-info for gcc), which say what it did and did not vectorize.

Preview of Lecture 16: Processes and multitasking

Unit IV ends here. Unit V opens with exceptional control flow: the ways control jumps that are not ordinary calls and branches. Lecture 16 introduces the process abstraction — the illusion that your program has the CPU and memory to itself (built on Lectures 11–12’s virtual memory) — and the system calls that create and manage processes: fork, exec, wait. The copy-on-write of Lecture 12 is what makes fork cheap.


术语表 (Glossary, English → 中文)

English中文
code optimization代码优化
optimization level (-O1/-O2)优化级别
constant folding常量折叠
dead-code elimination死代码消除
common-subexpression elimination (CSE)公共子表达式消除
code motion / loop-invariant hoisting代码移动 / 循环不变量外提
inlining内联
optimization blocker优化阻碍
memory aliasing内存别名
restrict keywordrestrict 关键字
side effect (of a call)副作用
cycles per element (CPE)每元素周期数
pipelined functional unit流水线化功能单元
latency / throughput延迟 / 吞吐量
latency bound / throughput bound延迟瓶颈 / 吞吐瓶颈
dependency chain / critical path依赖链 / 关键路径
instruction-level parallelism (ILP)指令级并行
loop unrolling循环展开
multiple accumulators多累加器
superscalar / out-of-order超标量 / 乱序执行
reassociation (floating point)重结合(浮点)
vectorization (SIMD)向量化
← 返回课程目录