25  Rewrite Pattern

A rewrite pattern is a local, declarative unit of transformation logic. It says how to recognize an operation shape and, when its semantic preconditions hold, replace it with an equivalent or deliberately converted form. Patterns are used for canonicalization, lowering, legalization, and target-specific optimization.

25.1 Match Is A Proof Obligation

A pattern must match more than a convenient syntax. Its matcher establishes every condition required for the rewrite: type compatibility, attributes, shape information, use counts, effects, dominance, and dialect semantics where relevant. If the proof is incomplete, the pattern must fail to match.

For example, replacing add x, 0 with x requires the correct zero constant and integer or floating semantics that preserve the operation’s flags and corner cases. A similar-looking floating rewrite may be invalid in the presence of NaN, signed zero, or constrained fast-math behavior.

25.2 Rewrite Through The Rewriter

PatternRewriter supplies APIs to create operations at a valid insertion point, replace an operation’s results, erase an operation, modify it in place, and report changes to the driver. Build the replacement first, then atomically redirect uses and erase the old operation through the rewriter.

Patterns should be small and composable. A pattern that recognizes a huge subgraph, performs global analysis, and mutates unrelated operations is hard to order and test. Put broad policy in a pass or analysis; keep the pattern focused on a local semantic transformation.

25.3 Benefits And Ordering

Patterns have benefits that guide greedy rewriting and legalization. Benefits are heuristics, not proofs of correctness. A higher-benefit pattern may run first, but every applied pattern still must preserve its semantic contract. Avoid creating cycles: two patterns that rewrite between equally valid forms can make a greedy driver churn until its iteration limit.

Test a pattern with the intended match, nearby non-matches, and the cases where it must reject incomplete information. A good pattern test demonstrates both the IR change and the invariant that justified it.