Hoisting Loop-Invariant Code

A computation that gives the same result on every iteration should not stay inside the loop. LICM does that for you.

Optimization2 min read
Optimization

An expression inside a loop that produces the same result on every iteration is called loop-invariant. Computing it once before the loop removes wasted work. Compilers call this transformation LICM (loop-invariant code motion).

scale.rsRust
fn scale_all(out: &mut [i32], data: &[i32], scale: i32) { for i in 0..out.len() { out[i] = data[i] * (scale * 2); }}

scale * 2 never changes during the loop. The compiler moves the multiplication in front of it:

scale.rsRust
fn scale_all(out: &mut [i32], data: &[i32], scale: i32) { let k = scale * 2; // once, before the loop for i in 0..out.len() { out[i] = data[i] * k; }}

When It Cannot Move

Not every expression can be hoisted. The compiler checks that:

  • The inputs of the expression do not change inside the loop.
  • The expression has no side effects, such as writing to a file or changing shared state.
  • If the expression can fail (like division by zero), running it early does not change behaviour even when the loop runs zero times.

Bounds Checks in Rust

Rust checks bounds on every access such as data[i]. Here i is limited by out.len(), but data may have a different length. Adding a length check before the loop gives the optimizer what it needs to drop the check inside it; whether it actually does depends on the compiler version and settings.

scale.rsRust
assert!(data.len() >= out.len());

The payoff is largest in nested loops: a value that stays constant in the outer loop is no longer recomputed on every inner iteration.

Sources

  1. A. V. Aho, M. S. Lam, R. Sethi, J. D. Ullman. Compilers: Principles, Techniques, and Tools, 2nd ed., Addison-Wesley, 2006, ch. 9.
  2. LLVM’s Analysis and Transform Passes, “licm: Loop Invariant Code Motion”. llvm.org/docs/Passes