24  Folding

Folding is an operation-local simplification hook. It lets an operation replace itself with existing values or constant attributes when its result is determined by immediately available information. Folding is deliberately narrower than general rewrite patterns.

24.1 The Typical Constant Case

A constant arithmetic expression can be evaluated at compile time:

%a = arith.constant 2 : i32
%b = arith.constant 3 : i32
%sum = arith.addi %a, %b : i32

A fold for the add can return the attribute representing 5, allowing the folder to materialize an appropriate constant. A fold may also return an existing operand for a proven identity case. It must preserve exact type and arithmetic semantics; a host-language calculation that overflows differently from MLIR is not a valid fold.

24.2 Folding Is Local And Pure

The fold hook sees one operation and available constant operand attributes. It does not perform a global search, consult arbitrary use sites, or reorder memory effects. This makes folding cheap and predictable during parsing, construction, and canonicalization.

An operation with observable effects should not claim a fold that removes those effects. Likewise, a fold must not return an attribute for a dynamic value it cannot prove constant. When an operation needs multi-operation reasoning, dominance checks, or structural changes, use a rewrite pattern instead.

24.3 Materialization Matters

Returning an attribute is not the same as inserting a particular constant operation. The dialect or context materializes that attribute into an operation of the required type. This separation lets dialects control how their constants are represented and avoids hard-coding one constant operation into generic infrastructure.