Act III · Speaking to the Machine
Part 13 of 61The Compiler
Can a program write machine code as good as the code a person writes by hand?
The part opens on the Job's scan loop from Part 6, where the hand-written assembly advances a pointer by twelve bytes and the source indexes a table instead. FORTRAN in 1957 had to come close to hand-coded programs or nobody would have used it, and the part builds a compiler for the Pebble language under the same test. A checker resolves names, scopes, types and layouts, and the program becomes three-address code on a control-flow graph. On that graph dominators and their frontiers place the phi-functions of static single assignment, dataflow analysis becomes the search for a least fixed point on a lattice, and constant propagation, value numbering, loop transformations and inlining are measured pass by pass. Register allocation turns into graph colouring: hard in general, but strict SSA interference graphs are chordal, and the part shows the four-cycle without a chord that leaving SSA creates. Compiled at level 2 the array scan runs 853,694 instructions against 827,576 for the hand-written loop and 4,466,758 unoptimized. The part ends by asking whether the compiler is right: a differential fuzzer, rewrite rules checked by an SMT solver, and a small superoptimizer that searches for short programs.
What you need. Programming in a C-like language, and graphs as vertices and edges. Sets ordered by inclusion are introduced where the lattices need them.
- Mathematics, ideas and history
- IRs and CFGs, dominators, SSA, dataflow as lattice fixed points, optimization, instruction selection, register allocation as coloring
- What we build or compute
- the Pebble compiler; the Job compiled
What you will be able to do
Degree
- Split three-address code into basic blocks, draw the control-flow graph and compute its dominator tree.
- Solve liveness on a small loop by iterating from empty sets, and build the interference graph from the result.
- Colour an interference graph by Chaitin's simplify and select, and say when a value must be spilled.
Graduate
- Compute dominance frontiers, place pruned phi-functions and rename along the dominator tree.
- Explain why a monotone framework on a lattice of finite height converges, and when its solution equals the meet over paths.
- Derive why strict SSA interference graphs are chordal and why copies inserted on leaving SSA can create a hole.
Research
- State what the halting argument does and does not rule out for an optimizer, and what a superoptimizer's validated candidate proves under its word model.
- Reproduce the fixed-k clique-tree dynamic program for spill-everywhere on chordal graphs and say which extensions change the problem.
Industry
- Choose optimization levels for a build, read the generated assembly, and measure instructions, cycles and time as separate quantities.
- Test a compiler change by differential fuzzing against a reference interpreter, and state the language model before proving a rewrite such as (x * c) / c = x.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 17 min · Graduate 47 min · Research 51 min · Industry 22 min.
- 0A program that writes programsDegree2 min
- 1FORTRAN, and the shape of a compilerDegree3 min
- 2Names, scopes and typesDegree2 min
- 3Three-address code and the control-flow graphDegree3 min
- 4DominatorsGraduate3 min
- 5Static single assignmentGraduate5 min
- 6Dataflow analysis and fixed pointsGraduate3 min
- 7Optimizations on SSAGraduate3 min
- 8LoopsGraduate3 min
- 9Inlining and aliasingGraduate2 min
- 10Instruction selectionGraduate2 min
- 11Register allocationDegree5 min
- 12Scheduling and the pipelineGraduate3 min
- 13The Job, compiledIndustry3 min
- 14Is the compiler right?Industry3 min
- 15Frontier: searching for the best programResearch4 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
A program that writes programsDegree2 min
In Part 6 we wrote the Job's inner loop in Pebble assembly. Each array entry occupies twelve bytes, so the hand-written loop advances a pointer by twelve. The high-level source instead indexes table entries. Our compiler recovers a pointer recurrence from that index. Compare the highlighted address updates. On this first-chapter input, the hand-written program executes instructions. The unoptimized array program executes , and the final measured configuration executes . Relative to the hand-written version, that is a change of percent on this workload. These are executed instruction counts; pipeline cycles and elapsed time come later.
Here is where we are going. A whole compiler, from the tree Part 12's parser builds down to Pebble machine code. The program as a graph, with dominators, the static single assignment form, and dataflow analysis as the search for a fixed point. A sequence of optimizations, each switched on in turn and measured on the Job. Register allocation as graph colouring, a hard problem in general, and the theorem that makes it easy on SSA programs. And the questions at the edge: how do we know a compiler is right, and can a machine search for the best possible program?
1FORTRAN, and the shape of a compilerDegree3 min
In the early nineteen fifties, programs were written in machine code, by hand. In 1952 Grace Hopper's A-0 system stitched together subroutines from a library by number, and she called it a compiler: it compiled a program out of pieces. But most programmers were sure that anything automatic would produce code far too slow to use. Machine time cost more than programmer time, and the experts wrote tight code. John Backus's team at IBM set out to prove them wrong. Their FORTRAN compiler for the IBM 704 was delivered in April 1957, after about eighteen person-years of work, and most of that work went into optimization. It even simulated the flow of the program to estimate which loops ran most often, and gave those loops the machine's three index registers. Backus explained why, twenty years later: if FORTRAN produced programs only half as fast as hand-coded ones, nobody would have used it. The language was the easy part. The hard part was the promise that the code would be nearly as good as an expert's. That promise is the subject of this part.
A common compiler architecture has three broad parts. The front end understands the source language. It lexes and parses, checks names and types, and translates the tree into an intermediate representation, or IR. The middle end analyzes and transforms that representation. Shared optimizations can serve several languages and machines, although some still depend on source semantics or target costs. The back end chooses target instructions, assigns registers, schedules work and emits assembly or machine code. Real compilers may interleave these stages or use several IRs. The organizing principle is a sequence of representations with precise meanings. Each translation must preserve the behaviors required by the source and target semantics.
Here is the linked-list Job passing through our compiler. Its source characters become tokens and syntax-tree nodes. After checking names and types, lowering produces intermediate instructions in blocks. SSA construction inserts phis. The final recorded optimizer configuration leaves intermediate instructions. Inlining, loop tests and other transformations can increase static size while trying to improve execution; smaller source or IR is not the sole objective. The backend emits machine instructions occupying bytes in this recorded count. The instructions execute repeatedly, so static code size differs from dynamic work. These demonstrations are reproducible computations. Historical events and general mathematical results require their cited sources and assumptions as well.
2Names, scopes and typesDegree2 min
The parser of Part 12 checks the grammar, but a grammar cannot check that every name was declared before it is used. That needs memory of everything declared so far, which is beyond a context-free language. So the compiler's next pass walks the tree with a symbol table. The outermost scope holds the globals and the functions, including the built-ins. Entering lookup pushes a new scope, with its parameters w and n, and then its locals as they are declared: p, q and i. When the body says head, the checker looks in the innermost scope first, finds nothing, and looks outward, to the global. A local of the same name would have shadowed it. This rule, static or lexical scope, arrived with ALGOL 60's nested blocks, and it means every use of a name is settled from the text alone, before the program runs.
The checker assigns types according to the language's rules. Above each line are premises; below it is the conclusion. Two integer operands produce an integer sum. Indexing a pointer to T by an integer produces an element of type T. Selecting a declared struct field uses that field's type. Gamma records the typing environment, including the current names and their types. Our checker applies these rules while traversing the syntax tree. These four rejected fragments initialize an integer with null, use an undeclared name, select a nonexistent field, or pass the wrong argument count. The messages are our checker's actual output. Without the required checks, an implementation might reject them elsewhere, crash or compute a wrong result; a runtime crash is not guaranteed. Part 14 studies the guarantees of particular type systems and how some types can be inferred.
3Three-address code and the control-flow graphDegree3 min
Our middle end uses simple instructions grouped into basic blocks. Other compilers may use different tree or graph representations. Take s equals s plus a of i. Its syntax tree contains an assignment, an addition and an array index. Lowering gives the intermediate results names: scale i by four for an integer element, add the array address, load, add to s, and assign the result. The arithmetic has the familiar three-address shape: a destination and up to two inputs. Calls, branches, stores and later phi functions have their own operand conventions; the name is not a universal arity rule for every IR instruction. The percent names denote values or virtual registers. We can introduce as many as the translation needs, leaving the problem of fitting live values into physical registers to the back end.
Control flow is lowered the same way. Here is a small function, total, which adds up the positive entries of an array and subtracts one for each other entry. The entry block sets s and i to zero. The while loop becomes a block that tests i against n and branches either into the body or out to the exit. The body loads a of i and tests it. The if becomes two blocks, then and else, which meet again at endif. And endif increments i and jumps back to the test. Every structured statement turns into labelled blocks and branches between them. Notice that then and else both load a of i again, as the source said. A naive translation repeats work. The optimizer will remove some of it, and we will see what it misses.
The graph's straight-line pieces are basic blocks. Under normal control flow, entry is at the first instruction and transfer is at the terminator. A trap, exception or nonreturning call can prevent later instructions from running, so entering a block does not unconditionally guarantee that every instruction finishes. Leaders include the first instruction, branch targets and instructions after transfers; richer exception models add their own boundaries. A control-flow graph has blocks as nodes and possible transfers as edges. Frances Allen's work helped establish compiler control-flow analysis. The displayed whole-Job counts come from our actual lowered representation. Cycles identify repeated control paths. Dominance later isolates natural loops; profiling and input behavior determine which cycles dominate the execution cost.
4DominatorsGraduate3 min
The first thing the middle end computes about the graph is who dominates whom. A block d dominates a block n if every path from the entry to n passes through d. Whenever n runs, d has already run. Take endif. Control can reach it through then, or through else, or around the loop any number of times first. Every one of these paths passes through entry, the loop test while one, and body two. Those three dominate endif, and so does endif itself. Then five does not: there is a path round it, by else. An equivalent test: delete d from the graph. If n can no longer be reached from the entry, d dominates n. Our test suite checks the compiler's answer against exactly this definition, for every pair of blocks in the Job.
For a block reachable from entry, its dominators form a chain under domination. Every reachable block except entry therefore has a closest strict dominator, its immediate dominator. Drawing an edge from that parent to the block gives the dominator tree, rooted at entry. Notice where endif hangs: from body two, rather than then or else, because neither branch dominates the join. Now d dominates n exactly when d is n or an ancestor of n in this tree. A table of dominator sets has become one parent pointer per non-root block. The compiler uses this structure to place phis and to track which definitions are available along every incoming path.
One more idea, and it is the one SSA needs. The dominance frontier of d contains blocks n where d dominates a predecessor of n, but does not strictly dominate n. Strictly matters: a block dominates itself, yet a loop header can belong to its own frontier. Then five's frontier is endif. Then five dominates itself, a predecessor of endif, but a path through else reaches endif without visiting then. Body two's frontier contains the loop test, while one, reached around the back edge. While one is also in its own frontier: it dominates the back-edge predecessor, without strictly dominating itself. These are join points where definitions from different incoming paths may meet. Taking the frontier again for newly inserted definitions tells SSA where further phi functions may be needed.
5Static single assignmentGraduate5 min
In our IR the variable s is assigned in three places: in the entry, in then, and in else. To know anything about a use of s, the compiler must first work out which assignments could have produced its value. In straight-line code there is a simple cure. Give every assignment a fresh name, s one, s two, s three, and rewrite each use to the name that reaches it. Now every name is defined exactly once, and every use points at exactly one definition. Facts about s three are facts about one instruction, true wherever s three appears. The difficulty is where control flow joins. After an if, which name holds s? It depends on which branch ran.
SSA represents a control-flow join with a phi function. In total, the join's s dot five selects s dot four from then or s dot three from else. The operand is selected by the incoming edge. A phi does not evaluate both alternatives as an ordinary function call would, and all phis at a block entry take their incoming values simultaneously. They are bookkeeping for values, rather than a Pebble machine instruction. The loop header has the same issue: i dot two takes i dot one from entry on the first visit and i dot three from the back edge on later visits. The running sum needs another phi. This example has three phis for two source variables. When leaving SSA, the compiler must implement edge copies safely, including critical edges and simultaneous-copy cycles.
Where must the phis go? Not at every join: that would be correct but wasteful. The answer uses the previous chapter. s is assigned in the entry, in then and in else. The frontier of then is endif, and so is the frontier of else. A definition from then meets a definition from elsewhere exactly there, so endif gets a phi for s. But that phi is itself a new assignment of s, so its own frontier needs one too: the loop header, while one. i is assigned in the entry and in endif, whose frontier is while one again. Repeat until no new phi appears: the iterated dominance frontier. And keep only the phis whose variable is still live there, which is called pruned SSA. This is the algorithm of Cytron, Ferrante, Rosen, Wegman and Zadeck at IBM, published in 1991, and almost every optimizing compiler since has used it or a descendant of it.
Renaming follows the dominator tree with a stack for each source variable. On entering a block, push a fresh SSA name for each definition. A use reads the current top, respecting instruction order inside the block. Fill this block's incoming operands in successor phis, visit dominator-tree children, then pop the names introduced here when returning. A phi use belongs to its incoming edge. Follow the highlighted path from entry through while one and body two to then five. The stack for s contains s dot one from entry, s dot two from the header phi, and s dot four from the current branch. On return, the branch's name is popped before a sibling is visited. Dominance ensures that a reused definition is available on every path to its use, with instruction and phi-edge positions handled correctly. The tree supplies the nested traversal structure; it does not turn arbitrary memory or side effects into immutable values.
Why go to this trouble? Because once every use has exactly one definition, the links from definitions to uses are just pointers, and a fact about a name, say that it is a constant, is true everywhere the name appears. The analyses of the next chapters can follow these links directly, instead of sweeping over every block again and again. Industrial compilers agree. This is LLVM's pass called mem2reg, run by clang on the same function written in C. Its phis sit in the same places: two at the loop header, for s and i, and one at the join after the if. And when optimization is done, the phis are taken out again: each becomes a copy placed on its incoming edge, which the register allocator will try to make disappear.
6Dataflow analysis and fixed pointsGraduate3 min
The compiler's main tool for reasoning about a whole function is dataflow analysis. The first example is liveness. A variable is live at a point if some path from that point uses it before assigning it again. Its current value might still be needed. Two equations say this for every block. A variable is live at the end of b if it is live at the start of some successor. And it is live at the start of b if b uses it before assigning it, or it is live at the end and b does not assign it. Information flows backward here, from each use to the definitions before it. The answer matters for register allocation: a register holding a value that is no longer live is free for something else.
The equations refer to each other around the loop, so we solve them the way we found dominators. Start with every set empty. Visit the blocks, backward, and apply the equations; whenever a block's set grows, its predecessors must be visited again. The exit block uses s. Endif uses i. Else uses s and i. Then uses a, s and i. The body adds nothing new to that, and the loop test adds n. The entry assigns s and i, so only a and n are live on entry: they are the parameters. But the sets just grown at the loop test flow back round the loop, to endif, then and else, which all grow again. One more sweep changes nothing. Fourteen visits, twelve of which changed something, and the answer is a fixed point of the equations: apply them once more and every set stays the same.
Why does this liveness iteration stop? Kildall's framework makes the reason precise. The possible sets of four live variables form a lattice with sixteen elements, ordered by inclusion. Empty is bottom; all four variables are top. Each transfer function is monotone: enlarging the incoming facts cannot shrink its result. Because we start at bottom and revisit affected equations, induction shows that our successive facts only grow. Monotone does not mean an arbitrary starting value must grow. Endif's set grows from empty, to i alone, to all four variables. There can be at most four strict additions to any set. A fair worklist therefore terminates on this finite-height lattice, and an empty worklist means every equation is satisfied.
7Optimizations on SSAGraduate3 min
Constant propagation uses another finite-height lattice. This diagram chooses the dual ordering to the earlier growing liveness sets. Top means that no executable evidence has arrived yet. A particular constant is in the middle; bottom means conflicting values or a value that varies. The analysis moves downward: an SSA name changes at most from unseen to a constant to varying. That bounds value changes, while a worklist also tracks executable edges. Reversing the order would describe the same information process as an ascent from bottom. Merge three with three and obtain three. Merge three with four and obtain varying. Merge three with an input whose edge is not yet known executable, and provisionally retain three. If more executable evidence arrives, the value must be revised. This optimism belongs to the analysis, not permission to assume a runtime value without proof.
Here is a function made for the purpose. a is four, b is a times eight, and if b is more than sixteen, c is x plus b, otherwise x minus one. In SSA form it has four blocks and a phi at the join. The analysis finds that a is four, so b is thirty-two, so the comparison is true. And it tracks which edges can execute at the same time as which values are constant. Since the comparison is always true, the edge to else is never taken: else never runs. So the phi at the join may ignore the operand arriving from else, and c dot four is simply x plus thirty-two. What remains is two instructions: x plus thirty-two, times two. Doing both jobs at once, constants and reachable code, finds more than running either one first. This is Wegman and Zadeck's algorithm, from 1991. On this Job and at this point in the pass order, the measured change is small. Other programs can expose many constants, and inlining or loop transformations can create further opportunities.
Value numbering reuses an already available computation. This example forms i times four repeatedly. A key records a supported operation and its operand values. For selected commutative operations, canonical operand order exposes another equality. When the key matches an available earlier instruction, replace the later uses with that earlier result. Our global pass scopes the table while walking the dominator tree, so the reused definition is available on every path to its new use. SSA keeps operand identities stable, but does not make memory immutable. This pass does not merge loads; calls, traps and memory effects require their own legality arguments. On this recorded array Job, eliminating repeated table-address arithmetic reduces the instruction count by the amount shown. The percentage measures this workload and pass ordering, rather than all programs or elapsed time.
8LoopsGraduate3 min
Profiling often identifies loops as important costs. Dominance helps locate one useful class of loops. A back edge n to h has a target h that dominates its source n. Its natural loop contains h and the blocks that can reach n without passing through h; include n itself. The header h is the single entry from outside that natural loop. Irreducible control flow can have multiple-entry cycles that this representation does not capture as one natural loop. In the recorded array Job's word function, the highlighted outer loop scans table entries. Its inner loop compares letters. The displayed block sets come from the actual control-flow graph. Nested loops often multiply execution counts, but early exits, input sizes and paths determine which blocks really run most.
Some computations produce the same value on every iteration. Operand invariance is the starting point: each input comes from outside the loop or from another invariant computation. Moving a total, effect-free instruction into the preheader can replace repeated work with one computation. The recorded word-function example hoists instructions; follow their destinations in the intermediate-code panel. Loads require two separate arguments: the memory must not change, and moving the access must not introduce a trap on a path that previously skipped it. Our repaired pass allows only header loads before any potentially trapping or effectful instruction, with invariant addresses and no loop stores or calls. It does not assume different widths cannot overlap. A conditional body load remains guarded, even when its address is invariant. In this array-Job pass comparison, the instruction count changes by percent. The result measures this program, not a general promise about loops.
An induction recurrence can replace repeated address arithmetic. The left panel recomputes an indexed table address inside the scan. If i increases by one, table plus twelve times i increases by twelve, under this machine's word and address semantics. Carry that derived address as another loop value and advance it by twelve. The compiler must initialize it correctly, preserve exits and updates, and retain valid memory accesses. This is induction-variable strength reduction. The right panel shows the pointer recurrence in the actual generated code. In this pass comparison, the array Job changes from to executed instructions, or percent. It recovers the hand-written loop's pointer idea; the full compiled program still has its own overhead and need not beat that baseline.
9Inlining and aliasingGraduate2 min
So far every optimization has worked inside one function. But a call is a wall: the caller cannot see what the callee does. In the list Job, lookup calls same for every entry of the right length, to compare the letters. Inlining copies same's body into lookup, in place of the call, with the arguments substituted for the parameters. That saves the call itself: moving the arguments, saving registers, the jump and the return. And more importantly, the body now sits inside the caller's loop, where the other passes can see it together with everything around it. The price is code size, and a copy for every call site. Our compiler inlines only small functions that are not recursive. Clang weighs an estimated cost against a threshold for each call site. On the list Job, inlining saves four percent. The array Job has no small function in its hot loop, so nothing changes.
A central memory question is whether two accesses can overlap. Store one through p, then two through q, then load through p. If the addresses overlap, the second store can change the answer. Even different access widths can overlap in byte-addressed memory. Compilers combine several kinds of evidence: object identities, address calculations, points-to sets, language aliasing rules and function summaries. C's character-type access is an important exception to type-based alias assumptions: a byte store can change an integer's representation. Our conservative repaired loop pass does not use width alone as proof of independence. C restrict is a contract the program must honor; Rust's reference rules and unsafe code have their own requirements. A missed optimization is preferable to silently assuming an alias cannot exist.
10Instruction selectionGraduate2 min
The back end begins by choosing machine instructions. Think of the IR for a of i as a small tree: a load, of a plus i shifted left by two. Each Pebble instruction covers a pattern in such trees, a tile. A shift by a constant. An addition. And a load, which on Pebble can also add a constant offset to its address for free. Instruction selection covers the tree with tiles, every node exactly once. Here three tiles: shift, add, load. Each tile becomes one instruction. A field access like p dot count, a load of p plus twelve, fits a single tile, because the load's offset absorbs the addition.
How should the tiles be chosen? The simplest method is called maximal munch. Start at the root of the tree, choose the largest tile that matches there, and recurse on whatever subtrees hang below the tile's leaves. Then emit the instructions in reverse, so that operands are computed before the operations that use them. For a load from p plus twelve, the largest tile is the load with an offset, one instruction, rather than an add followed by a load. It is greedy and takes linear time, and it is what our compiler does.
Here is the whole of same, the letter comparison, on the left as IR and on the right as selected Pebble instructions. Most IR instructions become one instruction each. But the loop test is two IR instructions, a comparison producing a truth value and a branch on it, and Pebble can do both at once: branch if greater or equal. The selector fuses them, and inverts the condition so that the common case falls through into the loop body. The calling convention appears too: the three arguments arrive in registers a zero to a two, and are moved into the function's own names. But the code still uses virtual registers, as many as it likes. Pebble has thirteen that the compiler may allocate. Fitting the one into the other is the next chapter, and the deepest.
11Register allocationDegree5 min
After selection, total uses seventeen virtual registers. Pebble has thirteen it may allocate, and bigger functions use hundreds. Which values may share a register? Two values interfere if both are live at the same point: both still needed. Then they need different registers. Values that never live at the same time can share one. Here is total after optimization, in SSA form. Notice the strength-reduced pointer i v two, stepping by four. Draw a node for each value and an edge for each pair that interferes, and you have the interference graph: seventeen nodes, forty-one edges. For instance, s dot two, the running sum, is still live when t ten is loaded, so they interfere.
So the problem becomes a famous one. Give each register a colour. Assign every node a colour so that no edge joins two nodes of the same colour, and you have assigned every value a register so that no two values needed at once share one. Our allocator colours this graph with five colours. And five is the minimum, because the graph contains a clique of five: five values all live at the same moment, each adjacent to all the others.
Gregory Chaitin and his colleagues at IBM built the first allocator of this kind in 1981. Simplify: suppose a node has fewer neighbours than there are registers. However its neighbours are coloured, one colour is left for it. So remove it, push it on a stack, and repeat on the smaller graph. Kempe used the same trick in 1879, in a flawed proof of the four colour theorem. If every remaining node has too many neighbours, pick one to spill: it lives in memory, stored after each definition and loaded before each use. Choose the cheapest, a value used rarely, with many neighbours, outside any loop. Select: pop the nodes back off the stack and give each a colour its neighbours do not have. Two refinements matter a great deal. Coalescing merges the two ends of a copy into one node, so the copy disappears; this is how the copies left by phis vanish. Briggs and George gave tests for when merging is safe. And rematerialization: a value that is a constant or an address need not be stored at all, only recomputed where it is needed.
Strict SSA reveals a useful special case. A graph is chordal when every cycle of at least four vertices has a chord between nonconsecutive vertices. The SSA allocation results of Hack and colleagues, and related independent work, show chordality for the interference model with each definition dominating its uses and phi operands treated on incoming edges. A value's live region can then be represented as a subtree of the suitably detailed dominator tree. Intersecting such subtrees produces a chordal graph. A perfect elimination order followed by greedy coloring in reverse uses exactly the clique number. Suitable algorithms run in the explicit graph's vertices plus edges. This assumes interchangeable registers and excludes extra physical-register constraints, spilling and coalescing costs. The recorded tables compare our SSA graphs with the graphs after phi copies are inserted. Leaving SSA can destroy chordality, even though the program still computes the same result.
The register sweep recompiles the same list Job with different register budgets. Read executed instructions and spill counts separately. Fewer registers can leave more copies, require more saves around calls, or force loads and stores. The plotted totals belong to this first-chapter input. The heuristic's choices are not monotone: a spill can disappear when a smaller budget changes ordering and coalescing decisions. That observation is about this allocator, not an optimality theorem. Linear scan, associated with Poletto and Sarkar's 1999 work, trades different analysis and allocation costs by processing live intervals. It is widely used in just-in-time settings, with many refinements. Relative compile time and generated-code quality depend on the algorithms and workload; one is not uniformly faster or worse than every graph-coloring allocator.
12Scheduling and the pipelineGraduate3 min
The last job of the back end is to choose an order for the instructions within each block. Here is the inner loop of word: compare one letter. Add, load a byte, add, load a byte, branch if equal. Draw an edge from one instruction to another when the second must wait for the first. The first add produces the address the first load uses. The branch needs both loaded bytes, and on Part 7's pipeline a load's result arrives a cycle late: a branch right after the load it depends on stalls. And one edge is different. Instruction three overwrites t three, which instruction two reads. Three must wait for two, not because of any value, but because the register allocator chose to reuse t three. A false dependence, and an example of the two phases fighting: allocate first and you constrain the schedule; schedule first and you may need more registers.
The standard method is list scheduling. Keep a list of the instructions that are ready, because everything they wait for has been placed. Each cycle, place the ready instruction with the longest path to the end of the block, so the critical path starts as early as possible and independent work fills the gaps. Finding the very best order is NP-hard in general, and this greedy rule is what nearly everyone uses. In our block it cannot help much. Even with a spare register, removing the false dependence, the second load must still come right before the branch that needs it. A block of five instructions in a single chain has nothing to hide the delay behind. To do better, a scheduler must look across blocks, and across loop iterations.
Now measure the generated code on Part 7's simulated pipeline, using the same -byte passage. Compare the hand-written program, the compiled array program, its scheduled form and the compiled list program. Scheduling removes of the compiled array program's load-use stall cycles. The remaining dependency chains limit this local scheduler's opportunities. Relative to hand-written code, the compiled array instruction count changes by percent, while its cycle count changes by percent. In this configuration, every conditional branch is predicted not taken. The inverted loops repeatedly take their conditional back branches, creating flushes. The next comparison changes the predictor while keeping this program and input fixed.
13The Job, compiledIndustry3 min
This experiment enables transformations cumulatively on both Job versions and counts instructions on the same first-chapter input. The unoptimized array configuration executes instructions. Register allocation brings it to . The next bars add inversion, SSA and constant propagation. Their changes reflect the actual combination, including copies left after SSA destruction. Value numbering changes the preceding array count by percent, and the repaired invariant-code pass changes it by percent. Strength reduction then changes it by percent. The final array count is , beside the dashed hand-written baseline of . Inlining changes the list version here while leaving the array count unchanged. This order is an experiment, not a universal ranking of passes. Legality, register pressure, code shape and earlier transformations interact. A correct compiler may miss an optimization; an unsafe shortcut does not count as a valid speed improvement.
Instruction count is not elapsed time. This table uses Part 8's simulated out-of-order core and six text passages. The table records both instruction totals and cycles for each implementation; compare their actual differences on every passage. Compare each row and the aggregate ratio rather than assuming one fixed percentage for every input. Overlap and dependency chains help explain why eliminating instructions may save few cycles. The observations are consistent with important load dependencies; these totals alone are not a full causal performance-counter study. The unoptimized comparison has a much larger aggregate cycle cost. Optimization matters on this workload, but neither the last few percent nor the same bottleneck must generalize to another program, machine or input distribution.
The sixth ledger row is a projection from the recorded model. We multiply the earlier hand-written row's corpus estimate by the ratio of total compiled to hand-written cycles across six sampled passages. This gives seconds for compiled code, versus seconds for the hand-written baseline; the unoptimized projection is seconds. These are extrapolated times under the earlier clock and cost assumptions, not a full-corpus hardware timing. The practical achievement is a readable source program that approaches this hand-written implementation on the selected machine model. Later algorithm changes can alter the amount of work much more substantially. New inputs or machines require new measurements.
14Is the compiler right?Industry3 min
A wrong-code compiler bug can be difficult to locate. A defined source program produces machine code with a different result, an extra trap or another behavior outside the source contract. Sometimes the only symptom is a plausible wrong number. Each transformation must preserve the supported semantic guarantees, including for unusual programs generated by macros, inlining and earlier compiler passes. C's undefined behavior changes the obligation: a compiler need not preserve an expected result for an execution whose source already has undefined behavior. But a transformation must not introduce such a failure into a defined execution. That distinction is central to the guarded-load regression we will examine.
Csmith turns random source programs into compiler tests. Its generator avoids undefined behavior and the unspecified choices that would undermine a stable expected output. Merely avoiding undefined behavior in an arbitrary C program would not, by itself, guarantee one output. Compile the generated program with several compilers and optimization levels, then compare the observed checksums. These diagram values illustrate the method. A disagreement is a finding to investigate: the source assumptions, harness and reference tools also need checking. In their 2011 paper, Yang, Chen, Eide and Regehr reported more than three hundred and twenty-five previously unknown bugs over three years. The study found crashes and wrong code in tested compilers, while reporting no wrong-code finding in CompCert's verified parts. That is a dated study result within a stated testing boundary.
Our compiler also has a differential test generator. It creates loops, arrays, pointers and globals. Indices are normalized into range. A square plus one stays nonzero even under thirty-two-bit wrapping, because a square is zero or one modulo four. But loop bodies can modify their counters, so small written bounds do not guarantee termination. The reference is the unoptimized IR interpreter. Its assumptions and implementation need testing too. This run generated programs, averaging lines. The interpreter excluded executions; their recorded reasons accompany the data. The remaining programs were compared at four compiler levels, with mismatches. That is finite evidence within the step limits. Separate directed semantic checks found two load-hoisting errors: a skipped null load became a trap, and overlapping byte and word accesses produced a stale value. The repaired cases retain their original results. These directed regressions complement the fuzzer; they were not discoveries made by this displayed random sample.
15Frontier: searching for the best programResearch4 min
An optimizing compiler usually improves a program according to selected costs; it does not promise the best equivalent program. Even deciding whether a particular replacement is legal can be impossible in a general language with unbounded computation. Consider a program that simulates an arbitrary machine M and prints a character if M halts. A silent infinite loop has the same observable behavior precisely when M never halts. An always-correct decision procedure for that equivalence would decide halting. This argument needs the unbounded semantic model; a fixed finite-memory Pebble machine has a finite state space, even if exhaustive analysis is impractical. It also does not assume an optimizer chooses one canonical spelling among equally short programs. Appel's full-employment theme is that compiler improvement keeps confronting such limits. For small restricted instruction fragments, however, candidate search and proof can still be useful.
Massalin's 1987 superoptimizer searched small instruction sequences. Our demonstration borrows that idea, with an important limit. It searches increasing candidate lengths over selected register operations, immediate forms and available values. Finite test inputs reject many candidates quickly. A separate z3 check asks whether each survivor equals its specification for every encoded thirty-two-bit input. That proof concerns the arithmetic fragment and specified output, not memory, calling conventions or an entire compiler. The table shows short sequences whose equivalence checks succeeded. Our pruning merges prefixes that agree only on finite tests, so the search can miss useful alternatives. The first found length is not a certificate of global shortestness, even though an accepted equivalence proof is meaningful. The absolute-value sequence uses arithmetic sign shift, addition and exclusive-or. At the most negative signed word, the mathematical positive answer is unrepresentable; the specification returns the wrapped word. Signed division by two instead needs rounding toward zero. The min sequence is checked against signed comparison, including extreme inputs.
Equality saturation keeps alternatives instead of committing to the first rewrite. In this example, a times two times two uses rules valid for our wrapping thirty-two-bit words. Other integer and floating-point semantics require their own rules. A one-way pass might turn the inner multiply into a shift before a multiplication-combining rule sees it. That illustrates a phase-ordering choice. An e-graph stores equivalence classes and shared expression structure. It can retain a times two and a shifted left by one as alternatives in one class. Rewriting expands and merges these classes. Our small example reaches the displayed alternatives, but general saturation need not terminate or stay small. Practical systems stop at time, size or iteration limits. Extraction chooses a represented expression under a specified cost model; here a single shift by two wins. Optimal tree-cost extraction is different from optimizing shared programs or proving global machine-code optimality. Tate and colleagues introduced equality saturation, and egg made it practical for many applications with domain-specific rewrite rules.
These directions require carefully stated problems. Strict SSA makes uniform-register graph coloring tractable. Spill selection and copy coalescing add different optimization problems. For spill-everywhere without holes, a fixed number of registers already has known polynomial algorithms; allowing that number as input can make the chordal-graph problem hard. The notes separate these cases. E-graph extraction depends on whether costs count expression occurrences or shared computations. Some formulations admit simple dynamic programming; sharing and extra constraints can create harder problems. Verified optimization also faces an engineering frontier: supported language features, target coverage, proof effort, compilation time and generated-code performance. CompCert's published speed comparisons name particular targets and compiler versions. They are not a universal ranking against current optimization levels. Extending synthesis and validation to loops adds state, memory, invariants and termination questions. No five-instruction cutoff defines that entire field. Our starred exercise starts by reproducing a known restricted spilling result, then asks for a precisely scoped research investigation.
Recap, problems, and where this comes backAll tracks3 min
We built a path from parsed source to Pebble machine code. A checker resolves names, scopes, types and layouts. Intermediate instructions and control-flow graphs make dependencies explicit. Dominators and frontiers support static single assignment, while dataflow equations compute conservative facts. We measured constant propagation, value numbering, dead-code elimination, loop transformations and inlining on a specified Job workload. Instruction selection chooses tiles; allocation maps live values to constrained storage; scheduling trades dependencies against machine resources. Strict SSA gives a particularly tractable graph-coloring model, not a complete solution to every allocation cost. Differential tests, semantic regression cases and encoded solver proofs supply different kinds of evidence. Candidate search then explores some transformations our hand-written rules miss.
Where this comes back. Part 14 proves what the type checker's promises are worth, and Part 15 builds the runtimes where just-in-time compilers and garbage collectors live. Parts 16 and 17 replace the Job's algorithm, and the compiler carries the gain to the machine. Graph colouring and dynamic programming return in Parts 18 and 19, and Rice's theorem and NP-hardness are proved in Parts 25 and 26. Part 41 builds the system that runs the compiler, CompCert's proof is Part 54, Ken Thompson's self-reproducing compiler is the finale, and Part 60 compiles for accelerators.
The notes contain six problems with worked guidance. Pause on any one. The fifth is a build problem: merge repeated loads only when the address and intervening memory effects justify it. Include overlapping byte and word accesses, guarded loads and negative cases, then compare outputs before measuring gains. The starred problem distinguishes a known fixed-register spill-everywhere algorithm from a research extension. First reproduce the restricted result. Then define the cost, register model and desired guarantee before investigating the literature. The exercise does not label that already-solved special case an open problem.
Next time. A whole programming language made of nothing but functions, Church's lambda calculus. Types that tame it, a proof that well-typed programs cannot go wrong, and types inferred without being written. Part 14, Lambda and Types.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Part 14 proves what the type checker's promises are worth and Part 15 builds the runtimes where JIT compilers live; Parts 16 and 17 replace the Job's algorithm and this compiler carries the gain to the machine. Graph colouring returns in Part 18, Rice's theorem and NP-hardness are proved in Parts 25 and 26, CompCert's proof is Part 54, and Thompson's compiler backdoor is built into this compiler in Part 55.
Key results
The part's results in one place, for revision.
Try it
Lab 13 · SSA interference graphs are chordal, until the copies come back
Lower the Job and nine fuzzer-generated programs with the series' compiler, put every function into SSA, optimize it, and check three claims of the part: dominators match their definition, the SSA interference graph is chordal and colours with exactly as many registers as its largest clique, and the optimized program prints what the unoptimized one prints.
python -m videos.cs.labs 13
needs numpy, scipy, matplotlib · download lab13.py ·
source on GitHubfunctions checked 59 (13,412 dominance pairs agree with 'delete d')
SSA graphs that are chordal 59 of 59 (theory: all)
colours used = largest clique 59 of 59 (theory: all)
Job, same 16 values, 6 registers
Job, lookup 28 values, 7 registers
Job, printnum 22 values, 4 registers
Job, report 31 values, 6 registers
Job, main 29 values, 4 registers
still chordal after leaving SSA 39 of 59
a hole in 'same' after leaving SSA a cycle of 4 values with no chord
optimized output = unoptimized output 6 of 6 programs that halt within the limit
In SSA every interference graph here is chordal, so greedy colouring along a perfect elimination order is optimal; the copies that replace phi-functions break that in 20 of 59 functions.
The code (133 lines; it asserts its own result)
"""Lab 13: put the Job and nine random programs into SSA, and check that their registers colour exactly."""
from videos.coursekit import labs
import copy
import numpy as np
from explainer.cs.lang import pebble_lang as P
from explainer.cs.lang.compiler import analysis as AN
from explainer.cs.lang.compiler import check as C
from explainer.cs.lang.compiler import fuzz as F
from explainer.cs.lang.compiler import interp as IT
from explainer.cs.lang.compiler import lower as L
from explainer.cs.lang.compiler import opt as O
from explainer.cs.lang.compiler import ssa as S
TITLE = "SSA interference graphs are chordal, until the copies come back"
GOAL = ("Lower the Job and nine fuzzer-generated programs with the series' compiler, put every function into SSA, "
"optimize it, and check three claims of the part: dominators match their definition, the SSA interference "
"graph is chordal and colours with exactly as many registers as its largest clique, and the optimized "
"program prints what the unoptimized one prints.")
TASKS = [
"Skip O.optimize(f) and compare the clique sizes. Which functions need fewer registers after optimization?",
"Pebble may allocate 13 registers. Count the functions whose SSA graph needs more, then lower the budget to 4 as in the film's register sweep.",
"Print AN.find_hole(after) for the Job's function 'same' and find the four values in str(f). Which of them are copies that replaced a phi?",
]
PROGRAMS = 9
STEPS = 60_000 # the reference interpreter's budget per program
REGISTERS = 13 # the registers Pebble may allocate
def module(prog):
"""Lower a parsed program to three-address code on a control-flow graph (loops inverted, as at level 2)."""
prog = copy.deepcopy(prog)
return L.lower(prog, C.check(prog), rotate=True)
def dominators_by_deletion(f):
"""d dominates n iff n is d or n cannot be reached from the entry once d is deleted (Chapter 4's definition)."""
lab, labels = f.labels(), [b.label for b in f.blocks]
out = set()
for d in labels:
seen, stack = set(), ([] if d == labels[0] else [labels[0]])
while stack:
x = stack.pop()
if x not in seen and x != d:
seen.add(x)
stack += lab[x].succs()
out |= {(d, n) for n in labels if n == d or n not in seen}
return out
def output(m):
try:
return bytes(IT.run(m, b"", max_steps=STEPS).out)
except IT.Stuck:
return None # the reference run hit the step limit: excluded, as in the film's fuzzer
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
job = P.parse(P.JOB)
sources = [("Job", job)] + [(f"fuzz {s}", P.parse(F.program(int(s)))) for s in rng.integers(0, 10 ** 6, PROGRAMS)]
rows, dom_pairs, compared, same = [], 0, 0, 0
for name, src in sources:
m = module(src)
before = output(module(src)) if name != "Job" else None
for f in m.funcs:
idom, _ = S.dominators(f)
labels = [b.label for b in f.blocks]
mine = {(d, n) for d in labels for n in labels if S.dominates(idom, d, n)}
assert mine == dominators_by_deletion(f), f"dominators of {f.name} disagree with the definition"
dom_pairs += len(labels) ** 2
S.to_ssa(f)
O.optimize(f)
g = AN.interference_ssa(f)
chordal, order, _ = AN.is_chordal(g)
colours = max(AN.color_peo(g, order).values(), default=-1) + 1
clique = AN.max_clique_chordal(g)
assert chordal, f"{name}.{f.name}: an SSA interference graph with a hole"
assert colours == clique, f"{name}.{f.name}: {colours} colours for a largest clique of {clique}"
S.from_ssa(f)
after = AN.interference_ssa(f)
rows.append(dict(prog=name, fn=f.name, values=len(g), colours=colours, after=AN.is_chordal(after)[0]))
if before is not None:
compared += 1
same += output(m) == before
jobrows = [r for r in rows if r["prog"] == "Job"]
holes = sum(not r["after"] for r in rows)
f = module(job).func("same")
S.to_ssa(f)
O.optimize(f)
S.from_ssa(f)
hole = AN.find_hole(AN.interference_ssa(f))
lab.row("functions checked", f"{len(rows)} ({dom_pairs:,} dominance pairs agree with 'delete d')")
lab.row("SSA graphs that are chordal", f"{len(rows)} of {len(rows)} (theory: all)")
lab.row("colours used = largest clique", f"{len(rows)} of {len(rows)} (theory: all)")
for r in jobrows:
lab.row(f"Job, {r['fn']}", f"{r['values']} values, {r['colours']} registers")
lab.row("still chordal after leaving SSA", f"{len(rows) - holes} of {len(rows)}")
lab.row("a hole in 'same' after leaving SSA", f"a cycle of {len(hole)} values with no chord" if hole else "none")
lab.row("optimized output = unoptimized output", f"{same} of {compared} programs that halt within the limit")
assert holes >= 1 and not next(r for r in jobrows if r["fn"] == "same")["after"], "leaving SSA should create holes"
assert hole is not None and len(hole) == 4, "the film's four-cycle without a chord"
assert compared >= 3 and same == compared, "an optimization changed what a program prints"
lab.note = ("In SSA every interference graph here is chordal, so greedy colouring along a perfect elimination "
"order is optimal; the copies that replace phi-functions break that in "
f"{holes} of {len(rows)} functions.")
fig, ax = labs.figure(2, size=(11, 4.4))
for is_job, color, label in ((False, labs.BLUE, "fuzzed functions"), (True, labs.GOLD, "the Job's functions")):
sel = [r for r in rows if (r["prog"] == "Job") == is_job]
ax[0].scatter([r["values"] for r in sel], [r["colours"] for r in sel], s=26 if is_job else 14, color=color,
alpha=0.9, label=label, zorder=3 if is_job else 2)
ax[0].axhline(REGISTERS, color=labs.RED, ls="--", lw=1, label=f"Pebble's {REGISTERS} allocatable registers")
ax[0].set(title="Registers an SSA function needs = its largest clique", xscale="log",
xlabel="values (vertices of the interference graph)", ylabel="registers (colours)")
ax[0].set_ylim(0, REGISTERS + 3.5)
ax[0].legend(loc="upper left", ncols=2)
counts = [len(rows), len(rows) - holes]
ax[1].set_axisbelow(True)
ax[1].grid(axis="x", visible=False)
ax[1].bar([0, 1], counts, color=[labs.GREEN, labs.ORANGE], width=0.55)
ax[1].bar([1], [holes], bottom=[len(rows) - holes], color=labs.RED, width=0.55)
for x, y, s in ((0, counts[0], f"{counts[0]} chordal"), (1, counts[1], f"{counts[1]} chordal"),
(1, len(rows), f"{holes} with a hole")):
ax[1].text(x, y - 0.03 * len(rows), s, ha="center", va="top", color=labs.BG, fontweight="bold")
ax[1].set(title="Chordal interference graphs, before and after the copies", ylabel="functions",
xticks=[0, 1], xticklabels=["in SSA", "after leaving SSA"], xlim=(-0.6, 1.6))
lab.fig = fig
return lab
Now change it
- Skip O.optimize(f) and compare the clique sizes. Which functions need fewer registers after optimization?
- Pebble may allocate 13 registers. Count the functions whose SSA graph needs more, then lower the budget to 4 as in the film's register sweep.
- Print AN.find_hole(after) for the Job's function 'same' and find the four values in str(f). Which of them are copies that replaced a phi?
Problems, with solutions
Try each problem before opening its solution.
-
Dominators and φs. Use edges E→H, H→B/X, B→T/F, T→R/J, F→J, J→H; R and X return. Compute the dominator tree and frontiers. Initialize
vin E, assign it in T/F and use it in X.Solution
Immediate-dominator edges are E→H, H→B/X, B→T/F/J, T→R. DF(T)=DF(F)={J}; DF(J)=DF(B)=DF(H)={H}; DF(E)=DF(R)=DF(X)=∅. Iterated-frontier placement puts φs at J and H. With the stated use at X,
vis live at H, so pruning keeps the header φ. If that incoming value is never used before redefinition, a suitably changed example can prune it. R has one predecessor and adds no merge. The two outgoing T edges are CFG edges, not sequential execution. -
Least liveness solution. B1 initializes
s=0; i=0; B2 testsi<n, goes to B3 or X; B3 executess=s+i; i=i+1then returns to B2; X usessand returns. Solve backward liveness.Solution
IN(X)={s}, OUT(X)=∅, IN(B2)=IN(B3)={s,i,n}, IN(B1)={n}. OUT(B1)=OUT(B2)=OUT(B3)={s,i,n}. Starting at bottom and applying the monotone equations reaches these sets. Every use reachable without a redefinition forces its variable into the corresponding set; induction on iterations shows that the result lies below every fixed point. To exhibit a larger fixed point, include an unused parameter
tin the universe and add it to IN and OUT of B1/B2/B3 only. The back edge sustains it, while the exit boundary stays OUT(X)=∅ and IN(X)={s}. Adding it to every set would violate that boundary. -
Word arithmetic. For which nonzero signed 32-bit constants c is
(x*c)/c = xvalid for every word x?Solution
Under Pebble's wrapping multiply and division toward zero, including wrapping
INT_MIN/-1, exactly c=1 and c=−1 work. For |c|≥2, any wrapped product has magnitude at most 2³¹; division cannot reach x=2³¹−1. For c=3 and x=2³¹−1, the product wraps to 2³¹−3, and the quotient is 715,827,881. Mathematical integer multiplication followed by exact division does cancel. C signed-overflow and division undefined behavior permit different transformations on defined executions; unsigned modular arithmetic also does not justify this cancellation. State the language model before proving a rewrite. -
Simplification and optimistic coloring. Prove the degree-<k removal rule and analyze a 4-cycle for k=2.
Solution
Restore removed vertices in reverse order. Each has fewer than k already-colored neighbors, so a color remains. A 4-cycle has degree k everywhere, so conservative simplification stalls and a basic spill decision may choose a value even though the graph is bipartite. Optimistically pushing one vertex permits the rest to simplify and succeeds on this graph. This example does not make optimistic coloring optimal on arbitrary graphs or with architectural register constraints.
-
Build: load value numbering. Design a safe first implementation, then explain what changes across blocks.
Solution
Within one block, key a load by width, address value and memory version. Reuse a dominating earlier load only if no intervening store may overlap it and no call or relevant I/O/effect invalidates the observation. A conservative implementation invalidates on every store, regardless of width, and resets at each block boundary. This version does not remove a load in a different block. To reuse the body load inside its dominated then block, track sound memory versions through edges and joins (or use a memory-SSA/alias analysis), as well as control and trap legality. A join is not handled by merely incrementing a traversal-local counter. Test byte-store/word-load overlap, word-store/byte-load overlap, calls, joins, zero-trip loops and conditional invalid pointers, then compare interpreter and physical execution. The current regression suite includes the LICM overlap and guarded-null failures; finite fuzzing supplements these tests without proving the new pass.
-
★ Research: precisely scoped spilling. Reproduce a known fixed-k algorithm before defining an extension.
Solution
Solution and starting point. For weighted spill-everywhere without holes on a chordal interference graph, a clique-tree dynamic program is polynomial for each fixed register count k. At each clique, retain a subset of at most k vertices; require agreement on the parent separator, combine compatible child states, and charge each retained vertex's weight exactly once, at its highest containing clique. Running intersection makes those local choices consistent. Maximizing retained weight gives exact minimum spill cost W−retained weight. The number of states grows like a power with exponent k, so this is not a polynomial bound when k is input. Holes, mandatory short ranges, reload placement, coalescing and machine constraints change the problem; consult the relevant theorem before transferring a bound. A retained-weight approximation does not transfer its ratio to spill cost: W=100, optimum retained=99 gives spill=1, whereas retained=50 gives spill=50 despite retaining more than half the optimum. Implement the known DP, compare it on small exhaustively solved instances, then specify one extension and review its literature before calling it open.
Notes and sources
Glossary
编译器 compiler · 前端 / 中端 / 后端 front end / middle end / back end · 中间表示 intermediate representation (IR) · 符号表 symbol table · 作用域 scope · 遮蔽 shadowing · 类型规则 typing rule · 对齐 alignment · 布局 layout · 取地址 address taken · 三地址码 three-address code · 临时变量 temporary · 基本块 basic block · 首指令 leader · 控制流图 control-flow graph · 支配 dominate · 直接支配者 immediate dominator · 支配树 dominator tree · 支配边界 dominance frontier · 逆后序 reverse postorder · 静态单赋值 static single assignment (SSA) · φ 函数 φ-function · 剪枝 SSA pruned SSA · 数据流分析 dataflow analysis · 活跃 live · 到达定义 reaching definitions · 可用表达式 available expressions · 格 lattice · 单调 monotone · 不动点 fixed point · 稀疏条件常量传播 sparse conditional constant propagation · 复写传播 copy propagation · 死代码消除 dead-code elimination · 值编号 value numbering · 强度削弱 strength reduction · 阶段顺序 phase ordering · 回边 back edge · 自然循环 natural loop · 循环头 loop header · 前置块 preheader · 循环反转 loop inversion · 循环不变代码外提 loop-invariant code motion · 归纳变量 induction variable · 循环展开 unrolling · 内联 inlining · 调用图 call graph · 别名分析 alias analysis · 指令选择 instruction selection · 铺砖 tiling · 最大吞噬 maximal munch · 寄存器分配 register allocation · 冲突图 interference graph · 着色 colouring · 溢出 spill · 合并 coalescing · 再物化 rematerialization · 弦图 chordal graph · 线性扫描 linear scan · 指令调度 instruction scheduling · 依赖图 dependence graph · 列表调度 list scheduling · 软件流水 software pipelining · 差分测试 differential testing · 模糊测试 fuzzing · 翻译确认 translation validation · 超级优化 superoptimization · 等式饱和 equality saturation · e 图 e-graph
Sources
Primary checks for the scoped claims
Sources
Canon. Books: Aho, Lam, Sethi & Ullman, Compilers: Principles, Techniques, and Tools (the Dragon Book), ch. 6–10; Cooper & Torczon, Engineering a Compiler; Appel, Modern Compiler Implementation in ML; Muchnick, Advanced Compiler Design and Implementation; Rastello & Bouchez Tichadou (eds.), SSA-based Compiler Design; Nielson, Nielson & Hankin, Principles of Program Analysis.
Papers: Backus et al., "The FORTRAN automatic coding system" (1957); Backus, "The history of FORTRAN I, II, and III" (1978); Strong et al., "The problem of programming communication with changing machines" (UNCOL, 1958); Rice, "Classes of recursively enumerable sets and their decision problems" (1953); Allen, "Control flow analysis" (1970); Allen & Cocke, "A catalogue of optimizing transformations" (1971); Kildall, "A unified approach to global program optimization" (1973); Kam & Ullman, "Monotone data flow analysis frameworks" (1977); Aho & Johnson, "Optimal code generation for expression trees" (1976); Lengauer & Tarjan, "A fast algorithm for finding dominators in a flowgraph" (1979); Rau & Glaeser, "Some scheduling techniques and an easily schedulable horizontal architecture" (1981); Chaitin et al., "Register allocation via coloring" (1981) and Chaitin, "Register allocation and spilling via graph coloring" (1982); Gavril, "The intersection graphs of subtrees in trees are exactly the chordal graphs" (1974); Massalin, "Superoptimizer: a look at the smallest program" (1987); Lam, "Software pipelining" (1988); Cytron, Ferrante, Rosen, Wegman & Zadeck, "Efficiently computing static single assignment form and the control dependence graph" (1991); Wegman & Zadeck, "Constant propagation with conditional branches" (1991); Fraser, Hanson & Proebsting, "Engineering a simple, efficient code-generator generator" (iburg, 1992); Briggs, Cooper & Torczon, "Improvements to graph coloring register allocation" (1994); George & Appel, "Iterated register coalescing" (1996); Andersen, Program analysis and specialization for the C programming language (1994); Steensgaard, "Points-to analysis in almost linear time" (1996); Landi, "Undecidability of static analysis" (1992); Ramalingam, "The undecidability of aliasing" (1994); Pnueli, Siegel & Singerman, "Translation validation" (1998); Poletto & Sarkar, "Linear scan register allocation" (1999); Necula, "Translation validation for an optimizing compiler" (2000); Cooper, Harvey & Kennedy, "A simple, fast dominance algorithm" (2001); Lattner & Adve, "LLVM: a compilation framework for lifelong program analysis and transformation" (2004).
Recent. Hack, Grund & Goos, "Register allocation for programs in SSA-form" (2006); Bouchez, Darte & Rastello, "On the complexity of spill everywhere under SSA form" (2007); Leroy, "Formal verification of a realistic compiler" (2009); Tate, Stepp, Tatlock & Lerner, "Equality saturation: a new approach to optimization" (2009); Yang, Chen, Eide & Regehr, "Finding and understanding bugs in C compilers" (2011); Schkufza, Sharma & Aiken, "Stochastic superoptimization" (2013); Lopes, Menendez, Nagarakatte & Regehr, "Provably correct peephole optimizations with Alive" (2015); Sasnauskas et al., "Souper: a synthesizing superoptimizer" (2017); Willsey et al., "egg: fast and extensible equality saturation" (2021); Trofin et al., "MLGO: a machine learning guided compiler optimizations framework" (2021); Mankowitz et al., "Faster sorting algorithms discovered using deep reinforcement learning" (2023).
About this partfrom its README
Part 13 of the sixty-one-part course, in Act III, Speaking to the Machine. Part 12 built the reader for Pebble; this part builds the compiler, follows its intermediate representations, and tests whether the generated machine code preserves the program's behavior.
The compiler is in explainer/cs/lang/compiler/: name/type checking and layout, CFG lowering, an IR interpreter,
dominators and SSA, optimization passes, instruction selection, register allocation, scheduling, differential
fuzzing and bounded enumerative search with separate SMT validation. The chapter uses actual traces and graphs
from these implementations. Tests live in tests/test_cs13_compiler.py.
The seventeen scenes cover the scan-loop hook; compiler history and pipeline; semantic checking; IR and CFGs; dominators; SSA; dataflow fixed points; optimization; loops; inlining and aliasing; instruction selection; register allocation; scheduling; the compiled Job; correctness; the research frontier; and worked problems.
What is computed and builtMeasurements and interpretation
These are the repaired local data, not universal compiler performance claims.
| Quantity | Recorded result | Scope |
|---|---|---|
| First-chapter array scan, hand written | 827,576 instructions | Pebble physical execution |
Same scan, compiled -O0 |
4,466,758 instructions | Same workload |
Same scan, compiled -O2 / -O3 |
853,694 instructions | About 3.2% above hand written |
List Job, compiled -O2 / -O3 |
768,386 / 739,791 instructions | First chapter |
| Pipeline input | 2,285 characters; 651 tokens; 371 AST nodes | List Job |
| Lowered / final IR | 207 instructions in 61 blocks / 311 instructions | Final count includes the compiler pipeline's transformations |
| Emitted code | 238 instruction words; 952 bytes | Physical 32-bit words before _brk, including runtime code; 234 indented listing lines is a different statistic |
| Liveness trace | 14 visits; 12 updates | The displayed total CFG |
| Allocation example | 17 vertices; 41 edges; clique and coloring size 5 | The displayed interference graph |
| LICM example | 2 pure IR operations hoisted | No conditional load is speculated |
| Register sweep, 13 → 4 registers | 768,386 → 1,156,277 instructions | Current list-Job run |
| Six-passage out-of-order core comparison | Compiled cycles / hand cycles = 1.0666 | Aggregate cycle counts, not mean passage ratios |
| Ledger projection | 61.18 seconds compiled; 57.4 seconds hand written | Scaled from simulated cycles; not a measured production wall time |
| Host GCC 14.2.0 C Job | 220.5 / 127.5 / 145.1 / 116.5 ms | -O0…-O3, recorded local best of three |
| LLVM 19.1.7 | 3 mem2reg φs; 90 parsed pipeline names, 61 distinct |
Printed opt -O2 pipeline text; not executed per-function pass counts |
| Differential sample | 240 generated; 190 compared at four levels; 50 excluded; 0 mismatches | Exclusions hit the reference step limit; no correctness proof |
Instruction counts, pipeline cycles, projected ledger time, host timings and code size measure different things. The compiled program can execute more instructions and still exhibit a different pipeline cost. The six measured passages are the comparison population; the ledger extrapolation assumes that their relative cycle cost transfers.
The search chapter displays eight candidates of lengths 1, 1, 2, 2, 3, 3, 3 and 4. Finite test observations prune
the search; this pruning is incomplete. Each displayed candidate is separately validated under its SMT word model.
The approximately 310-second search-plus-proof total belongs to the recorded host. These are validated candidates,
not proofs of shortest code. Absolute value at INT_MIN follows Pebble's wrap-around definition.
Notes
- Dominance refers to reachable CFG nodes. A dominance frontier requires that the node does not strictly dominate the destination, so a loop header can belong to its own frontier. Renaming walks the actual dominator tree; instruction order and φ-edge uses still matter.
- Monotone does not mean inflationary. Bottom initialization, a fair worklist and finite lattice height establish convergence here. Equality with meet-over-paths needs the stated distributivity assumptions and concerns syntactic CFG paths, including infeasible ones.
- Strict SSA interference is chordal under the uniform-register model. Coloring an explicit chordal graph and solving spilling, coalescing, instruction constraints or full allocation have different complexity bounds.
- Greedy maximal munch is a heuristic with arbitrary tile costs. Tree dynamic programming is optimal only for its specified tree/tile cost model; the general DAG problem has additional sharing choices.
- Memory transformations require both memory and control/trap safety. Different access widths can overlap. The
repaired LICM keeps conditional loads guarded and only moves a header load under conservative effect checks.
C's character alias exception,
restrictcontracts and Rust references require their own language rules. - Rice/halting arguments concern unbounded program models. They are not undecidability proofs for a fixed finite machine. CompCert's proved translation begins at its specified AST and ends at assembly, with an explicit trusted boundary. The fuzzer's bounded sample and historical Csmith/Alive results are evidence with separate scopes.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- History: Hopper's A-0 (1952); FORTRAN (Backus 1957, eighteen person-years, "half as fast"); front, middle and back ends; M + N instead of M × N (UNCOL 1958, GCC, LLVM); the list Job through every stage, counted.
- Semantic analysis: scopes as a stack of symbol tables (lexical scope, ALGOL 60); typing rules as inference rules;
four rejected programs; struct layout and alignment (
Node16 bytes,Entry12); globals, virtual registers, address-taken locals. - Three-address code, basic blocks and leaders, control-flow graphs (Allen 1970); clang's LLVM IR beside ours.
- Dominators: the definition checked against "delete d"; the iterative algorithm (Cooper–Harvey–Kennedy; 2 passes on every function of the Job); dominator trees; dominance frontiers; Lengauer–Tarjan mentioned.
- SSA (Cytron et al. 1991): φ-functions at iterated dominance frontiers, pruned; renaming down the dominator tree;
clang's
mem2regplaces the same φs; out-of-SSA copies. - Dataflow analysis: liveness iterated on screen (14 visits); reaching definitions and available expressions; monotone frameworks on lattices (Kildall 1973), the lattice of subsets and its height; Knaster–Tarski and Kleene; meet-over-paths and Kam & Ullman.
- Optimizations: the constant lattice and SCCP (Wegman & Zadeck 1991); copy propagation and DCE as mark and sweep;
value numbering (−20% on the array Job); algebra and its traps; phase ordering (clang
-O2: 88 pass runs). - Loops: back edges and natural loops; loop inversion and preheaders; invariant code motion with a type-based load rule; induction-variable strength reduction (−36%), which rediscovers Part 6's pointer; unrolling, vectorization and the polyhedral model described.
- Inlining; the call graph and summaries; alias analysis (type-based, address-taken, points-to,
restrict), undecidable in general (Rice; the reduction shown). - Instruction selection: tiles; maximal munch; Aho–Johnson dynamic programming and iburg; DAG tiling NP-hard; compare-and-branch fusion.
- Register allocation:
- interference graphs and Chaitin's coloring (1981): simplify, spill, select; Briggs/George coalescing; rematerialization; NP-hard by reduction from coloring;
- SSA interference graphs are chordal (Hack et al. 2006), checked on every function of the Job, and the 4-hole that leaving SSA creates;
- the register sweep (13 → 4 registers); linear scan.
- Instruction scheduling: the dependence DAG and false dependences; list scheduling; on Part 7's pipeline, loop inversion costs cycles without prediction and wins with it; software pipelining (callback to Part 8).
- The Job compiled from the Pebble language, pass by pass and level by level; on Part 8's core (11% fewer
instructions, the same cycles); ledger row 5; gcc
-O0…-O3on this machine. - Correctness: Csmith (Yang et al. 2011); our fuzzer (240 programs, 0 mismatches, and the two bugs it found while the compiler was built); five rewrite rules proved or refuted by z3; Alive; translation validation; CompCert previewed (Part 54).
- Frontier: the full employment theorem; a superoptimizer (Massalin 1987) rebuilt with z3 proofs; STOKE, Souper, AlphaDev; equality saturation and e-graphs (egg, Cranelift); MLGO; open problems. Outro.
Computed: our compiler with each pass switched on in turn (instructions on the emulator, cycles on Parts 7 and 8);
fixpoint iterations; coloring with spills and a register sweep; a chordality check on SSA interference graphs; a
differential fuzzer; z3 rule checks; a superoptimizer; clang's IR and gcc's levels on this machine.
Visuals: dataflow facts flowing around the CFG; φs landing at dominance frontiers; the interference graph being
colored; the code shrinking pass by pass; an e-graph.
In practice: LLVM and GCC, JIT tiers, compiler engineering, reading optimizer output (Compiler Explorer, -Rpass),
choosing optimization levels, PGO and LTO.
Reading: the Dragon Book; Cooper & Torczon, Engineering a Compiler; Appel, Modern Compiler Implementation in
ML; Muchnick, Advanced Compiler Design and Implementation; Rastello & Bouchez, SSA-based Compiler Design;
Nielson, Nielson & Hankin, Principles of Program Analysis; Cytron et al. 1991; Chaitin 1981; Kildall 1973; Hack et
al. 2006; Poletto & Sarkar 1999; Lattner & Adve 2004; Yang et al. 2011; Massalin 1987; Willsey et al. 2021.
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
支配树与 φ。 边为 E→H,H→B/X,B→T/F,T→R/J,F→J,J→H;R、X 返回。 E 初始化 v,T/F 赋值,X 使用。直接支配树为 E→H,H→B/X,B→T/F/J,T→R。 DF(T)=DF(F)={J},DF(J)=DF(B)=DF(H)={H},其余为空。迭代支配边界在 J、H 放 φ;由于 X 使用 v, v 在 H 活跃,剪枝仍保留循环头 φ。R 只有一个前驱,不增加合流。T 的两条出边表示分支,并非顺序执行。
-
最小活跃性解。 B1 初始化 s、i;B2 测试 i<n,进入 B3 或 X;B3 累加并递增后回 B2;X 使用 s。 IN(X)={s}、OUT(X)=∅、IN(B2)=IN(B3)={s,i,n}、IN(B1)={n};三个非出口块的 OUT 均为 {s,i,n}。 从空集开始的单调迭代得到最小不动点。若全集包含未使用参数 t,只把它加入三个非出口块的 IN/OUT,回边可以 维持这个更大的不动点;X 的边界不变。给所有集合都加 t 会破坏出口方程。
-
机器字运算。 在 Pebble 的 32 位回绕乘法、向零截断除法和 INT_MIN/−1 回绕规则下, 对所有 x 都有 (x*c)/c=x 的非零常量只有 ±1。|c|≥2 时,回绕乘积的绝对值最多为 2³¹,商不可能达到 x=2³¹−1。c=3 时乘积为 2³¹−3,商为 715,827,881。数学整数、C 的有符号未定义行为、无符号模运算 属于不同模型,不能混用证明。
-
化简与乐观着色。 逆序放回度数小于 k 时移走的结点,总有空闲颜色。k=2 的四圈所有度数都等于 k, 保守化简无法开始,可能选择溢出;但图本身可二着色。乐观压栈一个点后,其余点可化简,本例无需溢出。 这不证明乐观算法在任意图或带机器约束时最优。
-
动手:读取的值编号。 同一基本块内,用读取宽度、地址值和内存版本作键。只有更早读取支配当前读取, 且其间没有可能重叠的写入、调用或相关副作用,才可复用。保守版本遇到任何宽度的写入都失效,并在块边界重置; 它不会消除跨块读取。跨块需要沿边和合流传播可靠的内存版本,配合支配、别名及控制/陷阱条件;遍历时随意增加 一个计数器并不足够。测试不同宽度重叠、调用、合流、零次循环和条件保护的无效指针,再比较解释器与机器执行。 有限模糊测试只能补充证据,不能证明新优化正确。
-
★ 研究:精确定义溢出问题。 对弦图上有权、无空洞的处处溢出,固定 k 的团树动态规划已经是已知结果。 每个团保留至多 k 个点,父子分隔集上的选择必须一致,每个点的权重只在最高包含团计一次。最大保留权重给出 精确溢出代价 W−保留权重;状态数的指数依赖 k,不能据此声称 k 作为输入时也为多项式。 空洞、必须保留的短活跃段、重载位置、合并和机器约束会改变问题。保留权重的近似比不等于溢出代价近似比: W=100、最优保留99时只溢出1,保留50却溢出50。先实现已知算法并对小图穷举验证,再定义扩展、查阅文献, 判断是否仍为开放问题。
Build the film
python -m videos.cs.cs13.compute # the part's numbers, into .cache/cs13
python tools/build.py cs13 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs13 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs13. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build itBuild and cache provenance
python -m videos.cs.cs13.compute
python tools/build.py cs13 -q l
python tools/build.py cs13
python -m unittest tests.test_cs13_compiler
Fourteen compiler-dependent data caches carry a revision hash over compute.py and the compiler source. Normal
loads regenerate stale entries; cached-only QA rejects them before mutation. Host GCC, LLVM and superoptimization
records retain their recorded tools and timing context. Re-measure those deliberately with, for example,
python -m videos.cs.cs13.compute --force gcc. Computation requires the relevant local tools and Z3.
A cached numeric artifact is not by itself evidence that a changed compiler was re-executed.