Wado

Wado Optimizer

The optimizer rewrites NIR (WEP: NIR), then a smaller set of passes rewrites WIR before emission. This document lists what runs, one line per pass. The order is the one in src/optimize.rs and src/wir_optimize.rs, and WADO_LIST_PASSES prints it. Each pass's module doc says how it works.

Philosophy

When WebAssembly provides a native instruction for a feature, prefer it over a complex compiler transformation. That keeps the compiler small, lets the runtime JIT do the work, and produces smaller output. Examples are select for branchless conditionals, array.copy and array.fill for bulk operations, and br_table for dense matches.

A call to a function that declares no effects, or to an #[ambient] one, may be removed when its result is unused. A call that may trap or may not return stays, since removing it changes what the program does.

Optimization Levels

Flag Iterations Inline threshold Contract checks Notes
-O0 0 N/A on DCE alone, which keeps an e2e run cheap; nothing else is optimized
-O1 2 4 on The default of wado run, wado serve, wado test and each run-*
-O2 15 16 off For a release build; the default of every other subcommand
-O3 20 26 off For fuzzing the optimizer, more than for a build
-Os 15 16 off Strips the name section; a failed assert only traps; no loop unrolling

The levels differ in what a program does, not only in its speed: below -O2, a call marked unchecked traps when it breaks its contract (see Contract Checks).

The inline threshold bounds what one inlined copy adds to its caller. That is the Wasm instructions on the callee's hot path, less the call it replaces. --optimize-iterations and --optimize-inline-threshold override a level's values. --optimize-inline-growth <pct> also bounds how far inlining may grow the whole program. No level sets it.

Specializing a callee on its constant arguments mints a clone per distinct set of constants, up to a cap per module. --optimize-specializations <n> sets the cap. Reaching it is a remark under --log-level info, naming the first callee that kept its general version.

A pass reports a change only when it made one, because the fixed-point loop stops once no pass reports a change. At -O2, -O3, and -Os the loop must converge within the level's own count. At -O1, and wherever --optimize-iterations sets the count, it is only a budget.

Architecture

NIR has two tiers: a skeleton carrying effect order, control flow, and allocation, and a hash-consed graph of the pure values it reaches. Local rewrites are rules on one worklist engine, and a per-function dirty set lets a pass skip functions unchanged since it last ran. A whole-program analysis keeps what each body answers alone across rounds, and re-derives it only for the bodies a rewrite reached. CSE, GVN, and pure copy propagation are not passes, because the hash-consing already does them. See WEP: NIR Optimizer Architecture.

The passes run on --optimize-threads threads, and the output does not depend on how many. See WEP: Parallel Optimizer.

Pipeline

-O0 runs only DCE, and the part of step 8 that WIR Passes keeps at -O0. Every other level runs the whole list.

  1. DCE.
  2. Before the loop: cold_outline, match_to_switch over global initializers, and the early arithmetic promotion.
  3. The fixed-point loop: container_sroa, peephole, value_copy_demote, sroa_param, sroa_variant_return, inline, peephole, let_block_flatten, sroa, copy_prop, dae, drve, const_folding, param_spec, licm (with condition_implication). Once it converges, inline releases the callees it held back, and the loop runs again.
  4. After the loop, once: field_scalarize, store_load_forward, const_branch_prune, const_object_globalization, const_folding, scalar_forward, clone_forward.
  5. DCE.
  6. promote_fields, condition_implication (with const_branch_prune), loop_version_bce.
  7. Backend rewrites: select_lowering, multi_value_return, multi_value_param, freeze_pure_arith.
  8. The WIR passes.

NIR Passes

peephole is one worklist per function shared by the rules that need no fixed position. It runs once before inline and once after, and each run has rules of its own:

Allocation and aggregates:

Lower's ownership analysis chooses the defensive copies before NIR exists, so no pass here elides them (WEP: Ownership Analysis).

Variants and references:

Scalars and dataflow:

Loops and fields:

Whole program and backend:

WIR Passes

A WIR pass stays only if it changes the emitted Wasm. One that NIR or another WIR pass already covers is removed. At every level, nullable references are lowered first. -O0 then only removes dead items and settles the locals (step 11).

  1. Trivial copy propagation.
  2. Box-local elimination.
  3. Constant struct-field forwarding, for constant-index bounds checks.
  4. Array rewrites: constant arrays to data segments, large literals split, and the zero fill of a fresh array removed.
  5. Peephole: repeated field loads reused, instruction selection (select, rotates), and variant result slots flattened. Then a resource whose $Resource box no reference reaches is kept as its bare handle, across the locals, parameters and results it moves through.
  6. Dead-store elimination: a store to a local that every path overwrites, or leaves the function after, before reading it.
  7. Global cleanup (constant initializers, duplicate globals, dead data), then br_if selection, the calls to a function left empty and the once-flags guarding them, loop unrolling, and branch hints. A small loop that reads GC arrays gains a copy running several iterations per test of its condition, so wasmtime shares part of each array.get's bounds check across them. The original loop runs what is left.
  8. DCE and compaction.
  9. Local coalescing: a local read once is first forwarded into its read. Then locals of one Wasm type that are never live at once share a slot, and so do the two ends of a copy. A local's nullability is settled before it shares one.
  10. Tee fusion: a local.set and the read right after it become a local.tee. A local this leaves unread is removed.
  11. Local settling: a non-null local that Wasm's block-scoped rule sees read before any write is declared nullable. The locals are then grouped by Wasm type, the most used first.

A #![wasm_module(...)] core module, such as the allocator, runs the same list on its own, with its passes named wir/<module>:<pass>.

Branch Hints

A cold marker, builtin::cold_path(), says that the code around it rarely runs. The author writes one where they expect a path to be rare. The compiler writes one where the program itself makes a path rare: ahead of a trap, past a global's once-guard, and in the default arm of a switch.

What a Marker Covers

A marker makes its basic block cold. A basic block is a straight run of code that control enters only at its start and leaves only at its end. Wado's IR nests blocks rather than listing basic blocks, so the optimizer reads the same rule through dominance: a point is cold when every path through it passes the marker. The code after the marker in its block is cold, and so is the code before it, back to the last statement that can leave the block first.

Every pass that reads a marker reads this one rule: the inliner's prices, cold_outline's regions, the callees only cold code calls, the remarks, and the branch hints. The hints read the markers that say a branch is unlikely; the other passes read the ones that say code is cold. cold_path() says both.

Hints and Flags

A branch whose one side is cold gets a hint that the other side is likely. wasmtime lays out the cold side out of line. A branch to a trap is hinted the same way, marker or not.

-f no-branch-hinting leaves the hints out of the Wasm, so a benchmark measures what they are worth to the engine. -f no-cold-paths drops every marker, the compiler's included, before any pass reads one, so a benchmark measures what the markers are worth to the whole pipeline.

Profile-Guided Optimization

The rules are in the specification, and the design in WEP: Profile-Guided Optimization.

Applying a profile marks each region by the two halves of rarity (crate::rarity). An unlikely and cold region gets cold_path(). An unlikely one alone gets unlikely_path(), which only the branch hints read. A cold one alone gets cold_code(), which every other pass reads and the hints do not. -f no-pgo ignores the profile, and -f no-cold-paths ignores every marker, so three builds of one program can be compared.

Two questions stay open while profiles spread, and each optimizer change that touches cold paths answers them again:

Differential Testing (EMI)

wado-compiler/tests/emi.rs injects code behind a guard that is always false at run time, and compiles programs under random profiles. It checks that the program's output does not change at any level. mise run emi-calibrate, emi-mutate and emi-profile run it, and CI runs it nightly. See WEP: Compiler Fuzzing.

Not Yet Implemented

Architectural work is tracked in WEP: NIR Optimizer Architecture.

Tried and Found Ineffective

References