SSA Form: One Assignment per Variable

Compilers such as LLVM and GCC turn code into SSA form before analysing it. A small example of why it works so well.

IR2 min read
IR

SSA (Static Single Assignment) is an intermediate representation in which every variable is assigned exactly once. When a variable would be reassigned, a new variable with a new name is created instead.

example.rsRust
let mut x = 1;x = x + 2;x = x * 3;

In SSA form the same code looks like this:

IRIR
%x1 = 1%x2 = add %x1, 2%x3 = mul %x2, 3

Why It Works

Every name is defined in exactly one place, so “where did this value come from?” always has a single answer. That makes optimizations such as constant propagation, dead code elimination and common subexpression elimination much simpler.

Branches and phi

When a value can arrive along two different paths, SSA places a phi instruction at the join point. The phi picks the right value depending on which block control came from.

example.rsRust
let y = if c { 10 } else { 20 };
IRIR
then: br joinelse: br joinjoin: %y = phi i32 [10, then], [20, else]

phi is not a real machine instruction. During code generation it becomes copy instructions placed on the incoming edges.

Sources

  1. R. Cytron, J. Ferrante, B. K. Rosen, M. N. Wegman, F. K. Zadeck. “Efficiently computing static single assignment form and the control dependence graph.” ACM TOPLAS 13(4), 1991, 451–490. doi:10.1145/115372.115320
  2. LLVM Language Reference Manual, “phi instruction”. llvm.org/docs/LangRef
  3. K. D. Cooper, L. Torczon. Engineering a Compiler, 2nd ed., Morgan Kaufmann, 2011, ch. 9.