[mlir][SPIR-V] `canonicalize` produces invalid `spirv.SpecConstantOperation` by folding and hoisting enclosed op
[mlir][SPIR-V] canonicalize produces invalid spirv.SpecConstantOperation by folding and hoisting enclosed op
Summary
Running mlir-opt --canonicalize on a valid module containing spirv.SpecConstantOperation with a constant-foldable enclosed op breaks the operation's structural verifier invariants, triggering:
error: 'spirv.SpecConstantOperation' op expected exactly 2 nested ops
The failure is caused by a two-step interaction between constant folding and OperationFolder constant hoisting:
- Step 1 (Folding): The greedy rewriter constant-folds the enclosed operation (e.g.,
spirv.IAdd(1, 1)intospirv.Constant 2) and materializes the new constant inside thespirv.SpecConstantOperationregion.- Invariant violation 1:
spirv.Constantdoes not have theUsableInSpecConstantOptrait, violating the enclosed-op contract.
- Invariant violation 1:
- Step 2 (Hoisting): In the next iteration,
OperationFolder::insertKnownConstant(mlir/lib/Transforms/Utils/FoldUtils.cpp) encounters this constant. Becausespirv.SpecConstantOperationdoes not haveRegionKind::IsolatedFromAbove(nor does the SPIR-V dialect implementDialectFoldInterface::shouldMaterializeIntofor this region),getInsertionRegionresolves to the parentspirv.funcbody. - The constant is hoisted out of
spirv.SpecConstantOperationinto the enclosing function.- Invariant violation 2 (observed crash): The region is left containing only
spirv.mlir.yield(1 nested op instead of the required 2), failing the region cardinality verification check inspirv.SpecConstantOperationOp::verifyRegions.
- Invariant violation 2 (observed crash): The region is left containing only
Minimal Reproducer
// min.mlir
"builtin.module"() ({
"spirv.module"() <{addressing_model = #spirv.addressing_model<Logical>, memory_model = #spirv.memory_model<GLSL450>}> ({
"spirv.func"() <{function_control = #spirv.function_control<None>, function_type = () -> i32, sym_name = "f"}> ({
%0 = "spirv.Constant"() <{value = 1 : i32}> : () -> i32
%1 = "spirv.SpecConstantOperation"() ({
%2 = "spirv.IAdd"(%0, %0) : (i32, i32) -> i32
"spirv.mlir.yield"(%2) : (i32) -> ()
}) : () -> i32
"spirv.ReturnValue"(%1) : (i32) -> ()
}) : () -> ()
}) : () -> ()
}) : () -> ()
Run canonicalization:
mlir-opt min.mlir --canonicalize
Expected Behavior
canonicalize should preserve valid IR. If the enclosed operation within spirv.SpecConstantOperation folds, either:
- The entire
spirv.SpecConstantOperationshould fold as a unit (e.g., replaced by the resulting constant in the parent block), or - The rewrite should be rejected if
spirv.SpecConstantOperationsemantics prevent partial in-region folding.
In no case should it emit a partially stripped spirv.SpecConstantOperation that fails verification.
Actual Behavior
Verification fails immediately on the modified IR:
min.mlir:5:12: error: 'spirv.SpecConstantOperation' op expected exactly 2 nested ops
note: see current operation:
%1 = "spirv.SpecConstantOperation"() ({
"spirv.mlir.yield"(%0) : (i32) -> ()
}) : () -> i32
Suggested Fix Direction
- Fold the whole operation: When the enclosed operation in
spirv.SpecConstantOperationis constant-foldable, treatspirv.SpecConstantOperationas foldable as a unit, replacing the entire op with the folded result in the enclosing scope. - Prevent partial inner folding/hoisting: Ensure that constants are not individually materialized inside
SpecConstantOperationor hoisted out leaving an invalid empty shell. Merely preventing the hoist (e.g. viaDialectFoldInterface) is insufficient on its own, becausespirv.Constantis not legal insideSpecConstantOperation(UsableInSpecConstantOprequirement).
Tested Versions
- LLVM
mainat commitca566d552f7a9e507388cdba9539dd6e36c94bef - LLVM
24.0.0git(67005b724c917e1bdca50c82ecaa1b21a69244ed, macOS arm64)
@llvm/issue-subscribers-mlir
Author: lin334141-cell
Versions
- Reproduced on LLVM
24.0.0gitat67005b724c917e1bdca50c82ecaa1b21a69244ed(mlir-opt, Release + assertions) and on LLVMmainat61817b48e757f9a07f2a84e36326542052c12c22(checked out 2026-10-29). Both fail identically. We do not claim these are the newest available revisions. - Source-status note (not a reproduction claim): as of 2026-11-01 the relevant logic on
mainis functionally unchanged —OperationFolder::insertKnownConstantinmlir/lib/Transforms/Utils/FoldUtils.cppstill hoists constants to the computed insertion region; the Oct-2026 refactors (#232574, #233776) only replacedop->moveBefore(...)withrewriter.moveOpBefore(...)and added aConstantInsertionResultreturn. We have not built or run a newer revision. - The same failure signature (
'spirv.SpecConstantOperation' op expected exactly 2 nested ops, exit code 1) was independently observed on Linux x86_64 builds by an external fuzzer pipeline on four distinct generated programs, all reducing to the structure below.
Description
mlir-opt --canonicalize rewrites a verifier-accepted module containing a spirv.SpecConstantOperation whose enclosed op can be constant-folded into IR that violates the spirv.SpecConstantOperation verification invariants. Two invariants are broken by the combined rewrite:
- the enclosed-op contract: the region's first op must have the
UsableInSpecConstantOptrait (mlir/include/mlir/Dialect/SPIRV/IR/SPIRVOps.h-declared trait; check atmlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp:2181at67005b72), and - the region cardinality: the region must contain exactly 2 ops (
mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp:2176-2177at67005b72).
Mechanism (traced with -debug-only=greedy-rewriter and a debugger breakpoint on Operation::moveBefore):
- Iteration 1 of the greedy driver constant-folds the enclosed op (e.g.
spirv.ISub(x, x)orspirv.IAdd(c, c)) and materializes the resultingspirv.Constantinside theSpecConstantOperationregion (at the folded op's insertion point). The region now has 2 ops, but the enclosed op isspirv.Constant, which does not have theUsableInSpecConstantOptrait (SPIRVStructureOps.td:68-72at67005b72listsspirv.Constant's traits; the trait is carried by arithmetic ops such asspirv.IAdd), so this intermediate state already fails the enclosed-op contract if fully verified. - Iteration 2: the per-iteration
OperationFolderconstant CSE callsOperationFolder::insertKnownConstant(mlir/lib/Transforms/Utils/FoldUtils.cpp, at revision67005b72: line 113).getInsertionRegion(FoldUtils.cpp:26-45at67005b72) walks up from the constant's block:spirv.SpecConstantOperationis neitherIsIsolatedFromAbovenor does the SPIR-V dialect implementDialectFoldInterface::shouldMaterializeIntofor its region, so the insertion region resolves to the enclosingspirv.funcbody. - The hoist then moves the constant out of the region (at
67005b72:FoldUtils.cpp:161-166,op->moveBefore(&insertBlock->front())). - The region now contains only the
spirv.mlir.yield, whose operand references a value defined outside the region. Per-pass verification then fails on the cardinality invariant:'spirv.SpecConstantOperation' op expected exactly 2 nested ops(spirv.SpecConstantOperationOp::verifyRegions,mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp:2176-2177at67005b72).
In short, the constant folding and the subsequent hoisting together break the spirv.SpecConstantOperation verification invariants: the first step violates the enclosed-op trait contract, and the second step violates the region cardinality, the latter being the observed diagnostic.
Minimal reproducer (12 lines, file min.mlir)
"builtin.module"() ({
"spirv.module"() <{addressing_model = #spirv.addressing_model<Logical>, memory_model = #spirv.memory_model<GLSL450>}> ({
"spirv.func"() <{function_control = #spirv.function_control<None>, function_type = () -> i32, sym_name = "f"}> ({
%0 = "spirv.Constant"() <{value = 1 : i32}> : () -> i32
%1 = "spirv.SpecConstantOperation"() ({
%2 = "spirv.IAdd"(%0, %0) : (i32, i32) -> i32
"spirv.mlir.yield"(%2) : (i32) -> ()
}) : () -> i32
"spirv.ReturnValue"(%1) : (i32) -> ()
}) : () -> ()
}) : () -> ()
}) : () -> ()
Commands
mlir-opt min.mlir --mlir-disable-threading --verify-each --mlir-print-op-generic \
--pass-pipeline='builtin.module(canonicalize)' -o out.mlir
Expected behavior
canonicalize must preserve the spirv.SpecConstantOperation invariants: a legal enclosed op must not be individually rewritten into an op that fails the UsableInSpecConstantOp contract, and no constant hoisting may break the region's fixed structure. Alternatively, canonicalize may fold the entire spirv.SpecConstantOperation into a constant at a legal scope, or refuse the rewrite — it must not emit IR that fails the SpecConstantOperation verifier.
Actual behavior
Exit code 1:
min.mlir:5:12: error: 'spirv.SpecConstantOperation' op expected exactly 2 nested ops
note: see current operation:
%1 = "spirv.SpecConstantOperation"() ({
"spirv.mlir.yield"(%0) : (i32) -> ()
}) : () -> i32
Upstream dedup (re-checked 2026-11-01)
- GitHub issue/PR search
repo:llvm/llvm-project SpecConstantOperation: only PR #207328 (closed; null-deref fix insideverifyRegions— different defect) and PR #147067 (SPV_EXT_replicated_composites — unrelated). - Exact diagnostic string
"expected exactly 2 nested ops": no matching issue/PR (only an unrelated PR #2 whose diff contains the phrase as a typo fix). - The recent
OperationFolderrefactors #232574 and #233776 (Oct 2026) changed listener notification and return types but kept the hoisting behavior; ourmainreproduction build post-dates them and still fails. - Not covered by #236718 (tensor.cast canonicalize abort) or the
RemoveDeadValuesassertion family (#131433, #128332) — different passes and mechanisms.
We could not find an existing report covering this specific failure mechanism as of 2026-11-01.
Suggested fix directions
A complete fix needs to address both broken invariants:
- A legal enclosed operation must not be individually constant-folded into an operation that does not satisfy the
UsableInSpecConstantOpcontract (so merely preventing the hoist, e.g. viaDialectFoldInterface::shouldMaterializeInto, is not sufficient on its own — it would still leave an invalid enclosedspirv.Constantinside the region). - The subsequent constant hoisting (
OperationFolder::insertKnownConstant) must not break the fixed structure of such regions.
An alternative is to treat the spirv.SpecConstantOperation as a unit: fold or rewrite the whole op (e.g. into the folded constant at a legal scope) when its enclosed op folds. The concrete approach is up to the maintainers; we are happy to help test any proposed fix.
Context
Four independently generated programs (two from a fresh pilot, two from a 24h production run) all hit this exact signature; all reduce to the same structure above, so we file this as a single defect.
Thank you for taking the time to review this report. I would greatly appreciate it if the maintainers could take a look when possible and help confirm whether this is indeed a compiler bug.
If you encounter any difficulties reproducing the issue, or if additional information or test cases would be helpful, please let me know. I would be happy to provide further details or assist with reproduction.
Thank you very much for your time and help!
@llvm/issue-subscribers-mlir-spirv
Author: lin334141-cell
Summary
Running mlir-opt --canonicalize on a valid module containing spirv.SpecConstantOperation with a constant-foldable enclosed op breaks the operation's structural verifier invariants, triggering:
error: 'spirv.SpecConstantOperation' op expected exactly 2 nested ops
The failure is caused by a two-step interaction between constant folding and OperationFolder constant hoisting:
- Step 1 (Folding): The greedy rewriter constant-folds the enclosed operation (e.g.,
spirv.IAdd(1, 1)intospirv.Constant 2) and materializes the new constant inside thespirv.SpecConstantOperationregion.- Invariant violation 1:
spirv.Constantdoes not have theUsableInSpecConstantOptrait, violating the enclosed-op contract.
- Invariant violation 1:
- Step 2 (Hoisting): In the next iteration,
OperationFolder::insertKnownConstant(mlir/lib/Transforms/Utils/FoldUtils.cpp) encounters this constant. Becausespirv.SpecConstantOperationdoes not haveRegionKind::IsolatedFromAbove(nor does the SPIR-V dialect implementDialectFoldInterface::shouldMaterializeIntofor this region),getInsertionRegionresolves to the parentspirv.funcbody. - The constant is hoisted out of
spirv.SpecConstantOperationinto the enclosing function.- Invariant violation 2 (observed crash): The region is left containing only
spirv.mlir.yield(1 nested op instead of the required 2), failing the region cardinality verification check inspirv.SpecConstantOperationOp::verifyRegions.
- Invariant violation 2 (observed crash): The region is left containing only
Minimal Reproducer
// min.mlir
"builtin.module"() ({
"spirv.module"() <{addressing_model = #spirv.addressing_model<Logical>, memory_model = #spirv.memory_model<GLSL450>}> ({
"spirv.func"() <{function_control = #spirv.function_control<None>, function_type = () -> i32, sym_name = "f"}> ({
%0 = "spirv.Constant"() <{value = 1 : i32}> : () -> i32
%1 = "spirv.SpecConstantOperation"() ({
%2 = "spirv.IAdd"(%0, %0) : (i32, i32) -> i32
"spirv.mlir.yield"(%2) : (i32) -> ()
}) : () -> i32
"spirv.ReturnValue"(%1) : (i32) -> ()
}) : () -> ()
}) : () -> ()
}) : () -> ()
Run canonicalization:
mlir-opt min.mlir --canonicalize
Expected Behavior
canonicalize should preserve valid IR. If the enclosed operation within spirv.SpecConstantOperation folds, either:
- The entire
spirv.SpecConstantOperationshould fold as a unit (e.g., replaced by the resulting constant in the parent block), or - The rewrite should be rejected if
spirv.SpecConstantOperationsemantics prevent partial in-region folding.
In no case should it emit a partially stripped spirv.SpecConstantOperation that fails verification.
Actual Behavior
Verification fails immediately on the modified IR:
min.mlir:5:12: error: 'spirv.SpecConstantOperation' op expected exactly 2 nested ops
note: see current operation:
%1 = "spirv.SpecConstantOperation"() ({
"spirv.mlir.yield"(%0) : (i32) -> ()
}) : () -> i32
Suggested Fix Direction
- Fold the whole operation: When the enclosed operation in
spirv.SpecConstantOperationis constant-foldable, treatspirv.SpecConstantOperationas foldable as a unit, replacing the entire op with the folded result in the enclosing scope. - Prevent partial inner folding/hoisting: Ensure that constants are not individually materialized inside
SpecConstantOperationor hoisted out leaving an invalid empty shell. Merely preventing the hoist (e.g. viaDialectFoldInterface) is insufficient on its own, becausespirv.Constantis not legal insideSpecConstantOperation(UsableInSpecConstantOprequirement).
Tested Versions
- LLVM
mainat commitca566d552f7a9e507388cdba9539dd6e36c94bef - LLVM
24.0.0git(67005b724c917e1bdca50c82ecaa1b21a69244ed, macOS arm64)