[StableHLO] Add plugin registration for composite and custom-call rewrites (#25067) Compiler plugins need to recognize StableHLO composites and custom calls before input conversion removes their identity. Add a TargetRegistry and preprocessing pipeline helper through the existing compiler plugin hook. Composite handlers register by exact name and version; custom-call handlers register by target name. Passes own immutable registry snapshots, and registrations can declare the dialects their handlers create. Handlers receive the original operation, including all operands and regions. They validate applicability before modifying IR and leave IR unchanged when declining. Remaining composites retain their decomposition fallback. Custom calls with effects, aliases, tokens, or futures are excluded from registered dispatch. The preprocessing helper checks for unsupported mixed StableHLO/VHLO input, deserializes VHLO, and runs registered rewrites before ordinary input conversion. This provides the specialization point used by PyTorch → TorchAX exports to preserve operations such as attention and quantization through StableHLO lowering. Mutable model buffers remain explicit state inputs and outputs; buffer donation enables storage reuse independently of composite specialization. This PR supplies the registry and preprocessing infrastructure. Producer-specific handlers and alias-support opt-in are separate changes. Tests cover registry ownership and matching, preprocessing, original operand/region preservation, and chained declines followed by decomposition fallback. Assisted-by: codex --------- Signed-off-by: Jelle Schuhmacher <schuehmacher@roofline.ai>
diff --git a/build_tools/bazel_to_cmake/bazel_to_cmake_targets.py b/build_tools/bazel_to_cmake/bazel_to_cmake_targets.py index 9801560..81473e3 100644 --- a/build_tools/bazel_to_cmake/bazel_to_cmake_targets.py +++ b/build_tools/bazel_to_cmake/bazel_to_cmake_targets.py
@@ -65,6 +65,7 @@ "@llvm-project//mlir:CommonFolders": [""], "@llvm-project//mlir:ConversionPasses": [""], "@llvm-project//mlir:DialectUtils": [""], + "@llvm-project//mlir:FuncExtensions": ["MLIRFuncAllExtensions"], "@llvm-project//mlir:GPUDialect": ["MLIRGPUDialect"], "@llvm-project//mlir:GPUTransforms": ["MLIRGPUTransforms"], "@llvm-project//mlir:InliningUtils": [""],
diff --git a/compiler/plugins/input/StableHLO/Conversion/BUILD.bazel b/compiler/plugins/input/StableHLO/Conversion/BUILD.bazel index 7231138..1d48f10 100644 --- a/compiler/plugins/input/StableHLO/Conversion/BUILD.bazel +++ b/compiler/plugins/input/StableHLO/Conversion/BUILD.bazel
@@ -133,3 +133,59 @@ "@stablehlo//:stablehlo_passes", ], ) + +iree_compiler_cc_library( + name = "CustomCallMetadata", + srcs = ["StableHLOCustomCallMetadata.cpp"], + hdrs = ["StableHLOCustomCallMetadata.h"], + deps = [ + "@llvm-project//mlir:IR", + "@stablehlo//:stablehlo_ops", + ], +) + +iree_gentbl_cc_library( + name = "TargetRegistryPassesIncGen", + tbl_outs = [ + ( + ["--gen-pass-decls"], + "TargetRegistryPasses.h.inc", + ), + ], + tblgen = "@llvm-project//mlir:mlir-tblgen", + td_file = "TargetRegistryPasses.td", + deps = [ + "@llvm-project//mlir:PassBaseTdFiles", + ], +) + +iree_compiler_cc_library( + name = "TargetRegistry", + srcs = ["TargetRegistry.cpp"], + hdrs = [ + "TargetRegistry.h", + "TargetRegistryPasses.h.inc", + ], + deps = [ + ":TargetRegistryPassesIncGen", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:TransformUtils", + "@llvm-project//mlir:Transforms", + "@stablehlo//:stablehlo_ops", + ], +) + +iree_compiler_cc_library( + name = "CustomCallAndCompositePreprocessing", + srcs = ["CustomCallAndCompositePreprocessing.cpp"], + hdrs = ["CustomCallAndCompositePreprocessing.h"], + deps = [ + ":PassHeaders", + ":StableHLOLegalization", + ":TargetRegistry", + "@llvm-project//mlir:Pass", + "@stablehlo//:stablehlo_passes", + ], +)
diff --git a/compiler/plugins/input/StableHLO/Conversion/CMakeLists.txt b/compiler/plugins/input/StableHLO/Conversion/CMakeLists.txt index 018b437..fae31b1 100644 --- a/compiler/plugins/input/StableHLO/Conversion/CMakeLists.txt +++ b/compiler/plugins/input/StableHLO/Conversion/CMakeLists.txt
@@ -124,4 +124,61 @@ PUBLIC ) +iree_cc_library( + NAME + CustomCallMetadata + HDRS + "StableHLOCustomCallMetadata.h" + SRCS + "StableHLOCustomCallMetadata.cpp" + DEPS + MLIRIR + StablehloOps + PUBLIC +) + +iree_tablegen_library( + NAME + TargetRegistryPassesIncGen + TD_FILE + "TargetRegistryPasses.td" + OUTS + --gen-pass-decls TargetRegistryPasses.h.inc +) + +iree_cc_library( + NAME + TargetRegistry + HDRS + "TargetRegistry.h" + "TargetRegistryPasses.h.inc" + SRCS + "TargetRegistry.cpp" + DEPS + ::TargetRegistryPassesIncGen + LLVMSupport + MLIRIR + MLIRPass + MLIRTransformUtils + MLIRTransforms + StablehloOps + PUBLIC +) + +iree_cc_library( + NAME + CustomCallAndCompositePreprocessing + HDRS + "CustomCallAndCompositePreprocessing.h" + SRCS + "CustomCallAndCompositePreprocessing.cpp" + DEPS + ::PassHeaders + ::StableHLOLegalization + ::TargetRegistry + MLIRPass + StablehloPasses + PUBLIC +) + ### BAZEL_TO_CMAKE_PRESERVES_ALL_CONTENT_BELOW_THIS_LINE ###
diff --git a/compiler/plugins/input/StableHLO/Conversion/CustomCallAndCompositePreprocessing.cpp b/compiler/plugins/input/StableHLO/Conversion/CustomCallAndCompositePreprocessing.cpp new file mode 100644 index 0000000..eac1653 --- /dev/null +++ b/compiler/plugins/input/StableHLO/Conversion/CustomCallAndCompositePreprocessing.cpp
@@ -0,0 +1,24 @@ +// Copyright 2026 The IREE Authors +// +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#include "compiler/plugins/input/StableHLO/Conversion/CustomCallAndCompositePreprocessing.h" + +#include "compiler/plugins/input/StableHLO/Conversion/Passes.h" +#include "compiler/plugins/input/StableHLO/Conversion/TargetRegistry.h" +#include "mlir/Pass/PassManager.h" +#include "stablehlo/transforms/Passes.h" + +namespace mlir::iree_compiler::stablehlo { + +void buildCustomCallAndCompositePreprocessingPassPipeline( + OpPassManager &passManager, const TargetRegistry ®istry) { + passManager.addPass(createCheckVHLOStableHloMixUsage()); + mlir::stablehlo::createStablehloDeserializePipeline(passManager); + passManager.addPass( + createRewriteRegisteredCustomCallsAndCompositesPass(registry)); +} + +} // namespace mlir::iree_compiler::stablehlo
diff --git a/compiler/plugins/input/StableHLO/Conversion/CustomCallAndCompositePreprocessing.h b/compiler/plugins/input/StableHLO/Conversion/CustomCallAndCompositePreprocessing.h new file mode 100644 index 0000000..5b8a958 --- /dev/null +++ b/compiler/plugins/input/StableHLO/Conversion/CustomCallAndCompositePreprocessing.h
@@ -0,0 +1,23 @@ +// Copyright 2026 The IREE Authors +// +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifndef IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_CUSTOMCALLANDCOMPOSITEPREPROCESSING_H_ +#define IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_CUSTOMCALLANDCOMPOSITEPREPROCESSING_H_ + +#include "compiler/plugins/input/StableHLO/Conversion/TargetRegistry.h" +#include "mlir/Pass/PassManager.h" + +namespace mlir::iree_compiler::stablehlo { + +// For plugin preprocessing hooks: normalize raw VHLO before rewriting +// registered custom calls and composites. Unhandled operations remain available +// to later handlers or decomposition. +void buildCustomCallAndCompositePreprocessingPassPipeline( + OpPassManager &passManager, const TargetRegistry ®istry); + +} // namespace mlir::iree_compiler::stablehlo + +#endif // IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_CUSTOMCALLANDCOMPOSITEPREPROCESSING_H_
diff --git a/compiler/plugins/input/StableHLO/Conversion/StableHLOCustomCallMetadata.cpp b/compiler/plugins/input/StableHLO/Conversion/StableHLOCustomCallMetadata.cpp new file mode 100644 index 0000000..dbaab51 --- /dev/null +++ b/compiler/plugins/input/StableHLO/Conversion/StableHLOCustomCallMetadata.cpp
@@ -0,0 +1,21 @@ +// Copyright 2026 The IREE Authors +// +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#include "compiler/plugins/input/StableHLO/Conversion/StableHLOCustomCallMetadata.h" + +namespace mlir::iree_compiler::stablehlo { + +bool hasEmptyCustomCallMetadata(mlir::stablehlo::CustomCallOp op) { + return op.getApiVersion() == + mlir::stablehlo::CustomCallApiVersion::API_VERSION_TYPED_FFI && + op.hasEmptyBackendConfig() && op.getCalledComputations().empty() && + (!op.getOperandLayouts() || op.getOperandLayouts()->empty()) && + (!op.getResultLayouts() || op.getResultLayouts()->empty()) && + (!op.getResultTilings() || op.getResultTilings()->empty()) && + op->getDiscardableAttrs().empty(); +} + +} // namespace mlir::iree_compiler::stablehlo
diff --git a/compiler/plugins/input/StableHLO/Conversion/StableHLOCustomCallMetadata.h b/compiler/plugins/input/StableHLO/Conversion/StableHLOCustomCallMetadata.h new file mode 100644 index 0000000..13302af --- /dev/null +++ b/compiler/plugins/input/StableHLO/Conversion/StableHLOCustomCallMetadata.h
@@ -0,0 +1,21 @@ +// Copyright 2026 The IREE Authors +// +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifndef IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_STABLEHLOCUSTOMCALLMETADATA_H_ +#define IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_STABLEHLOCUSTOMCALLMETADATA_H_ + +#include "stablehlo/dialect/StablehloOps.h" + +namespace mlir::iree_compiler::stablehlo { + +// Returns true if |op| is a typed-FFI custom call with an empty or absent +// backend_config and no called computations, layouts, result tilings or +// discardable attributes. Side effects and aliases are left to the caller. +bool hasEmptyCustomCallMetadata(mlir::stablehlo::CustomCallOp op); + +} // namespace mlir::iree_compiler::stablehlo + +#endif // IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_STABLEHLOCUSTOMCALLMETADATA_H_
diff --git a/compiler/plugins/input/StableHLO/Conversion/TargetRegistry.cpp b/compiler/plugins/input/StableHLO/Conversion/TargetRegistry.cpp new file mode 100644 index 0000000..47e72c9 --- /dev/null +++ b/compiler/plugins/input/StableHLO/Conversion/TargetRegistry.cpp
@@ -0,0 +1,208 @@ +// Copyright 2026 The IREE Authors +// +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#include "compiler/plugins/input/StableHLO/Conversion/TargetRegistry.h" +#include "mlir/IR/BuiltinOps.h" +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" + +namespace mlir::iree_compiler::stablehlo { + +#define GEN_PASS_DEF_REWRITEREGISTEREDCUSTOMCALLSANDCOMPOSITESPASS +#include "compiler/plugins/input/StableHLO/Conversion/TargetRegistryPasses.h.inc" + +LogicalResult +TargetRegistry::addCustomCall(StringRef name, CustomCallHandler handler, + DialectRegistration registerDialects) { + if (name.empty() || !handler) { + return failure(); + } + auto guardedHandler = [handler = std::move(handler)]( + mlir::stablehlo::CustomCallOp op, + PatternRewriter &rewriter) -> LogicalResult { + // Tokens and futures can occur inside tuples. Check every leaf so nested + // values cannot bypass the ordering and completion restrictions below. + auto hasOrderingType = [](Type type) { + SmallVector<Type> leaves; + if (auto tuple = dyn_cast<TupleType>(type)) { + tuple.getFlattenedTypes(leaves); + } else { + leaves.push_back(type); + } + return llvm::any_of(leaves, [](Type leaf) { + return isa<mlir::stablehlo::TokenType, mlir::stablehlo::FutureType>( + leaf); + }); + }; + // Registered dispatch supports pure value rewrites. Effects and + // asynchronous completion need ordering guarantees; aliases need storage + // identity. These contracts are outside this registry, so leave such calls + // unchanged. + if (op.getHasSideEffect() || !op.getOutputOperandAliases().empty() || + llvm::any_of(op.getOperandTypes(), hasOrderingType) || + llvm::any_of(op.getResultTypes(), hasOrderingType)) { + return failure(); + } + return handler(op, rewriter); + }; + return success( + customCalls + .try_emplace(name, + Entry<CustomCallHandler>{std::move(guardedHandler), + std::move(registerDialects)}) + .second); +} + +LogicalResult +TargetRegistry::addComposite(StringRef name, int32_t version, + CompositeHandler handler, + DialectRegistration registerDialects) { + if (name.empty() || !handler) { + return failure(); + } + return success( + composites[name] + .emplace(version, + Entry<CompositeHandler>{std::move(handler), + std::move(registerDialects)}) + .second); +} + +const TargetRegistry::CustomCallHandler * +TargetRegistry::lookupCustomCall(StringRef name) const { + auto it = customCalls.find(name); + return it == customCalls.end() ? nullptr : &it->second.handler; +} + +const TargetRegistry::CompositeHandler * +TargetRegistry::lookupComposite(StringRef name, int32_t version) const { + auto versions = composites.find(name); + if (versions == composites.end()) { + return nullptr; + } + auto it = versions->second.find(version); + return it == versions->second.end() ? nullptr : &it->second.handler; +} + +void TargetRegistry::registerDependentDialects( + DialectRegistry &dialects) const { + for (const auto &customCall : customCalls) { + if (customCall.second.registerDialects) { + customCall.second.registerDialects(dialects); + } + } + for (const auto &versions : composites) { + for (const auto &[version, entry] : versions.second) { + if (entry.registerDialects) { + entry.registerDialects(dialects); + } + } + } +} + +namespace { +using RegistrySnapshot = std::shared_ptr<const TargetRegistry>; + +struct CustomCallDispatch final + : OpRewritePattern<mlir::stablehlo::CustomCallOp> { + CustomCallDispatch(MLIRContext *context, RegistrySnapshot registry) + : OpRewritePattern(context), registry(std::move(registry)) {} + LogicalResult matchAndRewrite(mlir::stablehlo::CustomCallOp op, + PatternRewriter &rewriter) const override { + auto *handler = registry->lookupCustomCall(op.getCallTargetName()); + return handler ? (*handler)(op, rewriter) : failure(); + } + RegistrySnapshot registry; +}; + +struct CompositeDispatch final + : OpRewritePattern<mlir::stablehlo::CompositeOp> { + CompositeDispatch(MLIRContext *context, RegistrySnapshot registry) + : OpRewritePattern(context), registry(std::move(registry)) {} + LogicalResult matchAndRewrite(mlir::stablehlo::CompositeOp op, + PatternRewriter &rewriter) const override { + auto *handler = registry->lookupComposite(op.getName(), op.getVersion()); + if (!handler) { + return failure(); + } + // Ops the handler creates carry the composite's name and numerical profile + // so later diagnostics can name their origin. + std::string provenance = ("composite " + op.getName()).str(); + if (auto profile = op.getCompositeAttributes().getAs<StringAttr>( + "numerical_profile")) { + provenance += (" (" + profile.getValue() + ")").str(); + } + OpBuilder::Listener *listener = rewriter.getListener(); + ProvenanceListener provenanceListener(listener, + rewriter.getStringAttr(provenance)); + rewriter.setListener(&provenanceListener); + LogicalResult result = (*handler)(op, rewriter); + rewriter.setListener(listener); + return result; + } + + // Adds the composite's name to the locations of newly inserted operations. + // Handlers must use the supplied rewriter: a separate builder would bypass + // both this listener and the greedy rewrite driver. + struct ProvenanceListener final : RewriterBase::ForwardingListener { + ProvenanceListener(OpBuilder::Listener *listener, StringAttr provenance) + : ForwardingListener(listener), provenance(provenance) {} + void notifyOperationInserted(Operation *op, + OpBuilder::InsertPoint previous) override { + // A moved op keeps its location. + if (!previous.isSet()) { + op->setLoc(NameLoc::get(provenance, op->getLoc())); + } + ForwardingListener::notifyOperationInserted(op, previous); + } + StringAttr provenance; + }; + RegistrySnapshot registry; +}; + +void populatePatterns(RewritePatternSet &patterns, RegistrySnapshot registry) { + patterns.add<CustomCallDispatch, CompositeDispatch>(patterns.getContext(), + registry); +} + +class RewriteRegisteredCustomCallsAndCompositesPass final + : public impl::RewriteRegisteredCustomCallsAndCompositesPassBase< + RewriteRegisteredCustomCallsAndCompositesPass> { +public: + explicit RewriteRegisteredCustomCallsAndCompositesPass( + const TargetRegistry ®istry) + : registry(std::make_shared<const TargetRegistry>(registry)) {} + RewriteRegisteredCustomCallsAndCompositesPass( + const RewriteRegisteredCustomCallsAndCompositesPass &) = default; + + void getDependentDialects(DialectRegistry &dialects) const override { + Base::getDependentDialects(dialects); + registry->registerDependentDialects(dialects); + } + void runOnOperation() override { + RewritePatternSet patterns(&getContext()); + populatePatterns(patterns, registry); + if (failed(applyPatternsGreedily(getOperation(), std::move(patterns)))) { + signalPassFailure(); + } + } + +private: + RegistrySnapshot registry; +}; +} // namespace + +void populateTargetRewritePatterns(RewritePatternSet &patterns, + const TargetRegistry ®istry) { + populatePatterns(patterns, std::make_shared<const TargetRegistry>(registry)); +} + +std::unique_ptr<Pass> createRewriteRegisteredCustomCallsAndCompositesPass( + const TargetRegistry ®istry) { + return std::make_unique<RewriteRegisteredCustomCallsAndCompositesPass>( + registry); +} + +} // namespace mlir::iree_compiler::stablehlo
diff --git a/compiler/plugins/input/StableHLO/Conversion/TargetRegistry.h b/compiler/plugins/input/StableHLO/Conversion/TargetRegistry.h new file mode 100644 index 0000000..91edca6 --- /dev/null +++ b/compiler/plugins/input/StableHLO/Conversion/TargetRegistry.h
@@ -0,0 +1,85 @@ +// Copyright 2026 The IREE Authors +// +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifndef IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_TARGETREGISTRY_H_ +#define IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_TARGETREGISTRY_H_ + +#include <functional> +#include <map> +#include <memory> +#include <string> +#include <vector> + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringMap.h" +#include "mlir/IR/DialectRegistry.h" +#include "mlir/IR/PatternMatch.h" +#include "mlir/Pass/Pass.h" +#include "stablehlo/dialect/StablehloOps.h" + +namespace mlir::iree_compiler::stablehlo { + +// Handlers receive the original operation with all its operands and regions. +// Check applicability before changing IR, including helper symbols and +// attributes. Success must replace the matched operation. Failure must leave +// the IR unchanged for later handlers or decomposition. +// +// Make all IR changes through the supplied rewriter so the rewrite driver and +// provenance listener can observe them. +// Captured handler state must support concurrent calls from pass clones. +class TargetRegistry { +public: + using CustomCallHandler = std::function<LogicalResult( + mlir::stablehlo::CustomCallOp, PatternRewriter &)>; + using CompositeHandler = std::function<LogicalResult( + mlir::stablehlo::CompositeOp, PatternRewriter &)>; + using DialectRegistration = std::function<void(DialectRegistry &)>; + + // Duplicate keys fail without replacing the existing handler. + // Custom calls with effects, tokens, futures or aliases are left unchanged. + LogicalResult addCustomCall(StringRef name, CustomCallHandler handler, + DialectRegistration registerDialects = {}); + // Registers a handler for this exact composite name and semantic version. + // Unregistered versions remain available for decomposition. A custom call's + // api_version identifies its calling interface; custom-call handlers must + // check which interfaces they support. + LogicalResult addComposite(StringRef name, int32_t version, + CompositeHandler handler, + DialectRegistration registerDialects = {}); + + const CustomCallHandler *lookupCustomCall(StringRef name) const; + const CompositeHandler *lookupComposite(StringRef name, + int32_t version) const; + void registerDependentDialects(DialectRegistry &dialects) const; + +private: + template <typename Handler> + struct Entry { + Handler handler; + DialectRegistration registerDialects; + }; + llvm::StringMap<Entry<CustomCallHandler>> customCalls; + // Versions of each composite name. + llvm::StringMap<std::map<int32_t, Entry<CompositeHandler>>> composites; +}; + +// Patterns and passes copy the registry, so later registrations cannot affect +// an already constructed pipeline. +// +// If a handler declines a composite, it remains available for later handlers. +// The standard input conversion pipeline decomposes any remaining composites. +// To retain one, the pipeline must exclude it from decomposition and provide a +// downstream consumer. +void populateTargetRewritePatterns(RewritePatternSet &patterns, + const TargetRegistry ®istry); +// The pass requires an explicit registry and cannot be parsed directly from +// text. Use a named pipeline that constructs the registry for textual callers. +std::unique_ptr<Pass> createRewriteRegisteredCustomCallsAndCompositesPass( + const TargetRegistry ®istry); + +} // namespace mlir::iree_compiler::stablehlo + +#endif // IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_TARGETREGISTRY_H_
diff --git a/compiler/plugins/input/StableHLO/Conversion/TargetRegistryPasses.td b/compiler/plugins/input/StableHLO/Conversion/TargetRegistryPasses.td new file mode 100644 index 0000000..f53dee2 --- /dev/null +++ b/compiler/plugins/input/StableHLO/Conversion/TargetRegistryPasses.td
@@ -0,0 +1,36 @@ +// Copyright 2026 The IREE Authors +// +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifndef IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_TARGETREGISTRYPASSES +#define IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_TARGETREGISTRYPASSES + +include "mlir/Pass/PassBase.td" + +// These passes require a caller-supplied registry. Keep their generated bases +// separate from Passes.td, whose passes are registered for textual construction. +def RewriteRegisteredCustomCallsAndCompositesPass : + Pass<"iree-stablehlo-rewrite-registered-custom-calls-and-composites", + "ModuleOp"> { + let summary = "Rewrites registered StableHLO custom calls and composites"; + let description = [{ + Invokes registered handlers for custom-call targets and exact composite + names and versions. Handlers replace operations they accept and leave IR + unchanged when declining. Remaining composites retain their decomposition. + + Each pass owns a snapshot of the registry supplied at construction. Later + registrations do not affect it. + }]; + // Suppress generated parameterless factories. Only the generated base is + // used; textual pipelines must construct a registry through a named pipeline. + let constructor = [{ + createRewriteRegisteredCustomCallsAndCompositesPass(registry) + }]; + let dependentDialects = [ + "::mlir::stablehlo::StablehloDialect", + ]; +} + +#endif // IREE_COMPILER_PLUGINS_INPUT_STABLEHLO_CONVERSION_TARGETREGISTRYPASSES
diff --git a/compiler/plugins/input/StableHLO/Conversion/test/BUILD.bazel b/compiler/plugins/input/StableHLO/Conversion/test/BUILD.bazel index 3a3b2f6..987fd79 100644 --- a/compiler/plugins/input/StableHLO/Conversion/test/BUILD.bazel +++ b/compiler/plugins/input/StableHLO/Conversion/test/BUILD.bazel
@@ -4,6 +4,7 @@ # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +load("//build_tools/bazel:build_defs.oss.bzl", "iree_compiler_cc_test") load("//build_tools/bazel:enforce_glob.bzl", "enforce_glob") load("//build_tools/bazel:iree_lit_test.bzl", "iree_lit_test_suite") @@ -44,3 +45,77 @@ "@llvm-project//llvm:FileCheck", ], ) + +iree_compiler_cc_test( + name = "TargetRegistryTest", + testonly = True, + srcs = ["TargetRegistryTest.cpp"], + deps = [ + "//compiler/plugins/input/StableHLO/Conversion:TargetRegistry", + "//compiler/src/iree/testing:gtest_main", + "@com_google_googletest//:gtest", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:ArithDialect", + "@llvm-project//mlir:AsmParser", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Parser", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:TransformUtils", + "@llvm-project//mlir:Transforms", + "@stablehlo//:stablehlo_ops", + "@stablehlo//:stablehlo_passes", + ], +) + +iree_compiler_cc_test( + name = "CustomCallAndCompositePreprocessingTest", + testonly = True, + srcs = ["CustomCallAndCompositePreprocessingTest.cpp"], + deps = [ + "//compiler/plugins/input/StableHLO/Conversion", + "//compiler/plugins/input/StableHLO/Conversion:CustomCallAndCompositePreprocessing", + "//compiler/plugins/input/StableHLO/Conversion:CustomCallMetadata", + "//compiler/plugins/input/StableHLO/Conversion:TargetRegistry", + "//compiler/src/iree/testing:gtest_main", + "@com_google_googletest//:gtest", + "@llvm-project//mlir:ArithDialect", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Parser", + "@llvm-project//mlir:Pass", + "@stablehlo//:stablehlo_ops", + "@stablehlo//:stablehlo_passes", + ], +) + +iree_compiler_cc_test( + name = "TargetPipelineTest", + testonly = True, + srcs = ["TargetPipelineTest.cpp"], + deps = [ + "//compiler/plugins/input/StableHLO/Conversion", + "//compiler/plugins/input/StableHLO/Conversion:CustomCallAndCompositePreprocessing", + "//compiler/plugins/input/StableHLO/Conversion:CustomCallMetadata", + "//compiler/plugins/input/StableHLO/Conversion:TargetRegistry", + "//compiler/src/iree/compiler/Dialect/HAL/Target", + "//compiler/src/iree/compiler/Pipelines", + "//compiler/src/iree/compiler/Pipelines:Options", + "//compiler/src/iree/compiler/PluginAPI", + "//compiler/src/iree/testing:gtest_main", + "@com_google_googletest//:gtest", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:ArithDialect", + "@llvm-project//mlir:ControlFlowDialect", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:FuncExtensions", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Parser", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:SCFDialect", + "@llvm-project//mlir:TensorDialect", + "@llvm-project//mlir:Transforms", + "@stablehlo//:stablehlo_ops", + "@stablehlo//:stablehlo_passes", + ], +)
diff --git a/compiler/plugins/input/StableHLO/Conversion/test/CMakeLists.txt b/compiler/plugins/input/StableHLO/Conversion/test/CMakeLists.txt index 5e024ae..e168720 100644 --- a/compiler/plugins/input/StableHLO/Conversion/test/CMakeLists.txt +++ b/compiler/plugins/input/StableHLO/Conversion/test/CMakeLists.txt
@@ -37,4 +37,81 @@ iree-opt ) +iree_cc_test( + NAME + TargetRegistryTest + SRCS + "TargetRegistryTest.cpp" + DEPS + LLVMSupport + MLIRArithDialect + MLIRAsmParser + MLIRFuncDialect + MLIRIR + MLIRParser + MLIRPass + MLIRTransformUtils + MLIRTransforms + StablehloOps + StablehloPasses + gmock + gtest + iree::compiler::plugins::input::StableHLO::Conversion::TargetRegistry + iree::testing::gtest_main +) + +iree_cc_test( + NAME + CustomCallAndCompositePreprocessingTest + SRCS + "CustomCallAndCompositePreprocessingTest.cpp" + DEPS + MLIRArithDialect + MLIRFuncDialect + MLIRIR + MLIRParser + MLIRPass + StablehloOps + StablehloPasses + gmock + gtest + iree::compiler::plugins::input::StableHLO::Conversion + iree::compiler::plugins::input::StableHLO::Conversion::CustomCallAndCompositePreprocessing + iree::compiler::plugins::input::StableHLO::Conversion::CustomCallMetadata + iree::compiler::plugins::input::StableHLO::Conversion::TargetRegistry + iree::testing::gtest_main +) + +iree_cc_test( + NAME + TargetPipelineTest + SRCS + "TargetPipelineTest.cpp" + DEPS + LLVMSupport + MLIRArithDialect + MLIRControlFlowDialect + MLIRFuncAllExtensions + MLIRFuncDialect + MLIRIR + MLIRParser + MLIRPass + MLIRSCFDialect + MLIRTensorDialect + MLIRTransforms + StablehloOps + StablehloPasses + gmock + gtest + iree::compiler::Dialect::HAL::Target + iree::compiler::Pipelines + iree::compiler::Pipelines::Options + iree::compiler::PluginAPI + iree::compiler::plugins::input::StableHLO::Conversion + iree::compiler::plugins::input::StableHLO::Conversion::CustomCallAndCompositePreprocessing + iree::compiler::plugins::input::StableHLO::Conversion::CustomCallMetadata + iree::compiler::plugins::input::StableHLO::Conversion::TargetRegistry + iree::testing::gtest_main +) + ### BAZEL_TO_CMAKE_PRESERVES_ALL_CONTENT_BELOW_THIS_LINE ###
diff --git a/compiler/plugins/input/StableHLO/Conversion/test/CustomCallAndCompositePreprocessingTest.cpp b/compiler/plugins/input/StableHLO/Conversion/test/CustomCallAndCompositePreprocessingTest.cpp new file mode 100644 index 0000000..2f7cd96 --- /dev/null +++ b/compiler/plugins/input/StableHLO/Conversion/test/CustomCallAndCompositePreprocessingTest.cpp
@@ -0,0 +1,144 @@ +// Copyright 2026 The IREE Authors +// +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#include "compiler/plugins/input/StableHLO/Conversion/CustomCallAndCompositePreprocessing.h" +#include "compiler/plugins/input/StableHLO/Conversion/StableHLOCustomCallMetadata.h" +#include "compiler/plugins/input/StableHLO/Conversion/TargetRegistry.h" + +#include <gtest/gtest.h> +#include <atomic> + +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" +#include "mlir/IR/BuiltinOps.h" +#include "mlir/IR/Verifier.h" +#include "mlir/Parser/Parser.h" +#include "mlir/Pass/PassManager.h" +#include "stablehlo/transforms/Passes.h" + +namespace mlir::iree_compiler::stablehlo { +namespace { + +constexpr StringLiteral kCustomCallModule = R"mlir( +module { + func.func @run() -> tensor<i32> { + %result = stablehlo.custom_call @example.constant() { + api_version = 4 : i32, backend_config = {configuration = "preserved"}, + has_side_effect = false + } : () -> tensor<i32> + return %result : tensor<i32> + } +} +)mlir"; + +class CustomCallAndCompositePreprocessingTest : public ::testing::Test { +protected: + CustomCallAndCompositePreprocessingTest() { + context.loadDialect<func::FuncDialect, mlir::stablehlo::StablehloDialect>(); + } + + void checkCustomCall(bool serializeToVhlo) { + auto module = parseSourceString<ModuleOp>(kCustomCallModule, &context); + ASSERT_TRUE(module); + if (serializeToVhlo) { + PassManager serialization(&context); + serialization.addPass( + mlir::stablehlo::createStablehloLegalizeToVhloPass()); + ASSERT_TRUE(succeeded(serialization.run(*module))); + bool foundVhlo = false; + module->walk([&](Operation *op) { + foundVhlo |= op->getName().getDialectNamespace() == "vhlo"; + }); + ASSERT_TRUE(foundVhlo); + } + + auto calls = std::make_shared<std::atomic<unsigned>>(0); + TargetRegistry registry; + ASSERT_TRUE(succeeded(registry.addCustomCall( + "example.constant", + [calls](mlir::stablehlo::CustomCallOp op, + PatternRewriter &rewriter) -> LogicalResult { + EXPECT_EQ(op->getAttrOfType<DictionaryAttr>("backend_config") + .getAs<StringAttr>("configuration") + .getValue(), + "preserved"); + EXPECT_EQ(op->getAttrOfType<IntegerAttr>("api_version").getInt(), 4); + EXPECT_FALSE(hasEmptyCustomCallMetadata(op)); + ++*calls; + auto type = cast<RankedTensorType>(op.getResult(0).getType()); + auto constant = arith::ConstantOp::create( + rewriter, op.getLoc(), type, + DenseIntElementsAttr::get(type, APInt(32, 7))); + rewriter.replaceOp(op, constant.getResult()); + return success(); + }, + [](DialectRegistry &dialects) { + dialects.insert<arith::ArithDialect>(); + }))); + + PassManager preprocessing(&context); + buildCustomCallAndCompositePreprocessingPassPipeline(preprocessing, + registry); + ASSERT_TRUE(succeeded(preprocessing.run(*module))); + EXPECT_EQ(calls->load(), 1u); + EXPECT_TRUE(succeeded(verify(*module))); + module->walk([&](Operation *op) { + EXPECT_NE(op->getName().getDialectNamespace(), "vhlo"); + EXPECT_FALSE(isa<mlir::stablehlo::CustomCallOp>(op)); + }); + auto func = module->lookupSymbol<func::FuncOp>("run"); + ASSERT_TRUE(func); + auto result = cast<func::ReturnOp>(func.getBody().front().getTerminator()) + .getOperands() + .front(); + auto constant = result.getDefiningOp<arith::ConstantOp>(); + ASSERT_TRUE(constant); + auto value = cast<DenseIntElementsAttr>(constant.getValue()); + EXPECT_EQ(value.getSplatValue<APInt>().getSExtValue(), 7); + } + + MLIRContext context; +}; + +TEST_F(CustomCallAndCompositePreprocessingTest, + HandlesStablehloBeforeInputConversion) { + checkCustomCall(false); +} + +TEST_F(CustomCallAndCompositePreprocessingTest, + NormalizesVhloBeforeTargetLookup) { + checkCustomCall(true); +} + +TEST_F(CustomCallAndCompositePreprocessingTest, + LeavesOtherInputDialectsUnchanged) { + context.loadDialect<arith::ArithDialect>(); + auto module = parseSourceString<ModuleOp>(R"mlir( + module { + func.func @run(%x: i32) -> i32 { + %c = arith.constant 1 : i32 + %result = arith.addi %x, %c : i32 + return %result : i32 + } + } + )mlir", + &context); + ASSERT_TRUE(module); + auto original = module->clone(); + TargetRegistry registry; + PassManager preprocessing(&context); + buildCustomCallAndCompositePreprocessingPassPipeline(preprocessing, registry); + ASSERT_TRUE(succeeded(preprocessing.run(*module))); + std::string before, after; + llvm::raw_string_ostream beforeStream(before), afterStream(after); + original->print(beforeStream); + module->print(afterStream); + EXPECT_EQ(before, after); + original->destroy(); +} + +} // namespace +} // namespace mlir::iree_compiler::stablehlo
diff --git a/compiler/plugins/input/StableHLO/Conversion/test/TargetPipelineTest.cpp b/compiler/plugins/input/StableHLO/Conversion/test/TargetPipelineTest.cpp new file mode 100644 index 0000000..16d80a9 --- /dev/null +++ b/compiler/plugins/input/StableHLO/Conversion/test/TargetPipelineTest.cpp
@@ -0,0 +1,178 @@ +// Copyright 2026 The IREE Authors +// +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#include "compiler/plugins/input/StableHLO/Conversion/CustomCallAndCompositePreprocessing.h" +#include "compiler/plugins/input/StableHLO/Conversion/Passes.h" +#include "compiler/plugins/input/StableHLO/Conversion/StableHLOCustomCallMetadata.h" +#include "compiler/plugins/input/StableHLO/Conversion/TargetRegistry.h" +#include "iree/compiler/Dialect/HAL/Target/TargetRegistry.h" +#include "iree/compiler/Pipelines/Pipelines.h" +#include "iree/compiler/PluginAPI/Client.h" + +#include <gtest/gtest.h> +#include <atomic> + +#include "llvm/Support/raw_ostream.h" +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" +#include "mlir/Dialect/Func/Extensions/InlinerExtension.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" +#include "mlir/Dialect/SCF/IR/SCF.h" +#include "mlir/Dialect/Tensor/IR/Tensor.h" +#include "mlir/IR/BuiltinOps.h" +#include "mlir/IR/Diagnostics.h" +#include "mlir/IR/SymbolTable.h" +#include "mlir/IR/Verifier.h" +#include "mlir/Parser/Parser.h" +#include "mlir/Transforms/Passes.h" +#include "stablehlo/transforms/Passes.h" + +namespace mlir::iree_compiler::stablehlo { +namespace { +class TargetExtension final : public PipelineExtensions { +public: + TargetExtension() : rewrites(std::make_shared<std::atomic<unsigned>>(0)) { + auto count = rewrites; + auto result = registry.addComposite( + "test.identity", 1, + [count](mlir::stablehlo::CompositeOp op, + PatternRewriter &rewriter) -> LogicalResult { + ++*count; + rewriter.replaceOp(op, op.getInputs()); + return success(); + }); + EXPECT_TRUE(succeeded(result)); + } + void extendInputConversionPreprocessingPassPipeline( + OpPassManager &manager, InputDialectOptions::Type inputType) override { + ++preprocessingCalls; + buildCustomCallAndCompositePreprocessingPassPipeline(manager, registry); + } + + bool + extendCustomInputConversionPassPipeline(OpPassManager &manager, + std::string_view mnemonic) override { + if (mnemonic != "stablehlo" && mnemonic != "vhlo") { + return false; + } + ++conversionCalls; + buildStableHLOInputConversionPassPipeline(manager, StableHloOptions{}); + return true; + } + + void populateDetectedCustomInputConversionTypes( + ModuleOp &module, llvm::StringSet<> &mnemonics) override { + ++detectionCalls; + module.walk([&](Operation *op) { + if (op->getName().getDialectNamespace() == "stablehlo") { + mnemonics.insert("stablehlo"); + } + }); + } + + TargetRegistry registry; + std::shared_ptr<std::atomic<unsigned>> rewrites; + unsigned preprocessingCalls = 0; + unsigned conversionCalls = 0; + unsigned detectionCalls = 0; +}; + +// Runs the precompile pipeline from its start to input conversion, or to +// |end|. +static LogicalResult +runInputPipeline(ModuleOp module, TargetExtension &extension, + StringRef mnemonic = "stablehlo", + const IREE::HAL::TargetOptions &halOptions = {}, + IREEVMPipelinePhase end = IREEVMPipelinePhase::Input) { + IREEVMPipelineHooks hooks; + hooks.pipelineExtensions = &extension; + InputDialectOptions inputOptions; + inputOptions.inputTypeMnemonic = mnemonic.str(); + IREE::HAL::TargetRegistry targets; + PassManager manager(module.getContext()); + buildIREEPrecompileTransformPassPipeline( + targets, {}, {}, inputOptions, {}, {}, {}, {}, {}, halOptions, hooks, + manager, IREEVMPipelinePhase::Start, end); + return manager.run(module); +} + +class TargetPipelineTest : public ::testing::Test { +protected: + void runPipeline(StringRef mnemonic, bool rawVhlo, bool includeFallback) { + DialectRegistry dialects; + func::registerInlinerExtension(dialects); + MLIRContext context(dialects); + context.loadDialect<func::FuncDialect, mlir::stablehlo::StablehloDialect>(); + std::string source = R"mlir( + module { + func.func @registered(%input: tensor<2xf32>) -> tensor<2xf32> { + %result = stablehlo.composite "test.identity" %input { + decomposition = @reference, version = 1 : i32 + } : (tensor<2xf32>) -> tensor<2xf32> + return %result : tensor<2xf32> + } + func.func private @reference(%input: tensor<2xf32>) -> tensor<2xf32> { + return %input : tensor<2xf32> + } + } + )mlir"; + auto module = parseSourceString<ModuleOp>(source, &context); + ASSERT_TRUE(module); + if (includeFallback) { + auto registered = module->lookupSymbol<func::FuncOp>("registered"); + auto fallback = registered.clone(); + fallback.setName("fallback"); + fallback.walk([](mlir::stablehlo::CompositeOp op) { op.setVersion(99); }); + module->push_back(fallback); + } + if (rawVhlo) { + PassManager serialization(&context); + serialization.addPass( + mlir::stablehlo::createStablehloLegalizeToVhloPass()); + ASSERT_TRUE(succeeded(serialization.run(*module))); + } + + TargetExtension extension; + ASSERT_TRUE(succeeded(runInputPipeline(*module, extension, mnemonic))); + EXPECT_EQ(extension.preprocessingCalls, 1u); + EXPECT_EQ(extension.rewrites->load(), 1u); + EXPECT_EQ(extension.detectionCalls, mnemonic == "auto" ? 1u : 0u); + EXPECT_EQ(extension.conversionCalls, + mnemonic == "auto" && !includeFallback ? 0u : 1u); + module->walk([&](Operation *op) { + EXPECT_NE(op->getName().getDialectNamespace(), "vhlo"); + EXPECT_FALSE(isa<mlir::stablehlo::CompositeOp>(op)); + }); + for (StringRef name : {StringRef("registered"), StringRef("fallback")}) { + auto function = module->lookupSymbol<func::FuncOp>(name); + if (!function) { + continue; + } + auto returned = + cast<func::ReturnOp>(function.getBody().front().getTerminator()); + EXPECT_EQ(returned.getOperands().front(), function.getArgument(0)); + } + } +}; + +TEST_F(TargetPipelineTest, ExplicitStablehloRunsPreprocessingBeforeFallback) { + runPipeline("stablehlo", false, true); +} +TEST_F(TargetPipelineTest, ExplicitVhloRunsPreprocessingBeforeFallback) { + runPipeline("vhlo", true, true); +} +TEST_F(TargetPipelineTest, AutoDetectsRemainingFallbackAfterPreprocessing) { + runPipeline("auto", false, true); +} +TEST_F(TargetPipelineTest, AutoAcceptsFullyRewrittenGenericInput) { + runPipeline("auto", false, false); +} +TEST_F(TargetPipelineTest, AutoNormalizesVhloBeforeDetection) { + runPipeline("auto", true, true); +} + +} // namespace +} // namespace mlir::iree_compiler::stablehlo
diff --git a/compiler/plugins/input/StableHLO/Conversion/test/TargetRegistryTest.cpp b/compiler/plugins/input/StableHLO/Conversion/test/TargetRegistryTest.cpp new file mode 100644 index 0000000..24a4b47 --- /dev/null +++ b/compiler/plugins/input/StableHLO/Conversion/test/TargetRegistryTest.cpp
@@ -0,0 +1,554 @@ +// Copyright 2026 The IREE Authors +// +// Licensed under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#include "compiler/plugins/input/StableHLO/Conversion/TargetRegistry.h" + +#include <gtest/gtest.h> + +#include "llvm/ADT/StringSet.h" +#include "mlir/AsmParser/AsmParser.h" +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" +#include "mlir/IR/Builders.h" +#include "mlir/IR/BuiltinOps.h" +#include "mlir/IR/Verifier.h" +#include "mlir/Parser/Parser.h" +#include "mlir/Pass/PassManager.h" +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" +#include "stablehlo/dialect/StablehloOps.h" +#include "stablehlo/transforms/Passes.h" + +namespace mlir::iree_compiler::stablehlo { +namespace { + +TargetRegistry::CustomCallHandler replaceWithI32(int32_t value) { + return [value](mlir::stablehlo::CustomCallOp op, + PatternRewriter &rewriter) -> LogicalResult { + auto type = cast<RankedTensorType>(op.getResult(0).getType()); + auto attr = DenseIntElementsAttr::get(type, APInt(32, value)); + auto constant = + arith::ConstantOp::create(rewriter, op.getLoc(), type, attr); + rewriter.replaceOp(op, constant.getResult()); + return success(); + }; +} + +class TargetRegistryTest : public ::testing::Test { +protected: + TargetRegistryTest() { + context.loadDialect<func::FuncDialect, arith::ArithDialect, + mlir::stablehlo::StablehloDialect>(); + } + + OwningOpRef<ModuleOp> parseModule(StringRef source) { + auto module = parseSourceString<ModuleOp>(source, &context); + if (module) { + EXPECT_TRUE(succeeded(verify(*module))); + } + return module; + } + + bool runRewritePass(ModuleOp module, const TargetRegistry ®istry) { + PassManager manager(&context); + manager.addPass( + createRewriteRegisteredCustomCallsAndCompositesPass(registry)); + return succeeded(manager.run(module)); + } + + std::string print(ModuleOp module) { + std::string result; + llvm::raw_string_ostream stream(result); + module.print(stream); + return result; + } + + MLIRContext context; +}; + +TEST_F(TargetRegistryTest, RejectsEmptyNamesAndNullHandlers) { + TargetRegistry registry; + auto compositeHandler = [](mlir::stablehlo::CompositeOp, PatternRewriter &) { + return failure(); + }; + EXPECT_FALSE(succeeded(registry.addCustomCall("", replaceWithI32(1)))); + EXPECT_FALSE(succeeded(registry.addCustomCall("empty_handler", {}))); + EXPECT_FALSE(succeeded(registry.addComposite("", 0, compositeHandler))); + EXPECT_FALSE(succeeded(registry.addComposite("empty_handler", 0, {}))); +} + +TEST_F(TargetRegistryTest, ExternalPatternsDeclineAliasesByDefault) { + TargetRegistry registry; + int calls = 0; + ASSERT_TRUE(succeeded(registry.addCustomCall( + "test.alias", + [&calls](mlir::stablehlo::CustomCallOp op, PatternRewriter &rewriter) { + ++calls; + rewriter.replaceOp(op, op.getOperand(0)); + return success(); + }))); + auto module = parseModule(R"mlir( + module { + func.func @run(%buffer: memref<4xi32>) -> memref<4xi32> { + %r = stablehlo.custom_call @test.alias(%buffer) { + api_version = 4 : i32, backend_config = {}, + has_side_effect = false, + output_operand_aliases = [#stablehlo.output_operand_alias< + output_tuple_indices = [], operand_index = 0, + operand_tuple_indices = []>] + } : (memref<4xi32>) -> memref<4xi32> + return %r : memref<4xi32> + } + } + )mlir"); + ASSERT_TRUE(module); + RewritePatternSet patterns(&context); + populateTargetRewritePatterns(patterns, registry); + ASSERT_TRUE(succeeded(applyPatternsGreedily(*module, std::move(patterns)))); + EXPECT_EQ(calls, 0); + EXPECT_NE(print(*module).find("test.alias"), std::string::npos); +} + +TEST_F(TargetRegistryTest, PureHandlersDeclineEffectsAndTokens) { + TargetRegistry registry; + int calls = 0; + ASSERT_TRUE(succeeded(registry.addCustomCall( + "test.identity", + [&calls](mlir::stablehlo::CustomCallOp op, PatternRewriter &rewriter) { + ++calls; + rewriter.replaceOp(op, op.getOperand(0)); + return success(); + }))); + auto module = parseModule(R"mlir( + module { + func.func @effect(%input: tensor<i32>) -> tensor<i32> { + %result = stablehlo.custom_call @test.identity(%input) { + has_side_effect = true + } : (tensor<i32>) -> tensor<i32> + return %result : tensor<i32> + } + func.func @token(%input: !stablehlo.token) -> !stablehlo.token { + %result = stablehlo.custom_call @test.identity(%input) { + has_side_effect = false + } : (!stablehlo.token) -> !stablehlo.token + return %result : !stablehlo.token + } + } + )mlir"); + ASSERT_TRUE(module); + std::string before = print(*module); + ASSERT_TRUE(runRewritePass(*module, registry)); + EXPECT_EQ(calls, 0); + EXPECT_EQ(print(*module), before); +} + +TEST_F(TargetRegistryTest, DuplicateCustomCallDoesNotReplaceHandler) { + TargetRegistry registry; + ASSERT_TRUE(succeeded(registry.addCustomCall("target", replaceWithI32(1)))); + const auto *first = registry.lookupCustomCall("target"); + ASSERT_NE(first, nullptr); + EXPECT_FALSE(succeeded(registry.addCustomCall("target", replaceWithI32(2)))); + EXPECT_EQ(registry.lookupCustomCall("target"), first); + + auto module = parseModule(R"mlir( + module { + func.func @run() -> tensor<i32> { + %0 = stablehlo.custom_call @target() {has_side_effect = false} + : () -> tensor<i32> + return %0 : tensor<i32> + } + } + )mlir"); + ASSERT_TRUE(module); + ASSERT_TRUE(runRewritePass(*module, registry)); + EXPECT_NE(print(*module).find("dense<1>"), std::string::npos); +} + +TEST_F(TargetRegistryTest, CompositeVersionsAndCustomCallNamesAreIndependent) { + TargetRegistry registry; + auto compositeHandler = [](mlir::stablehlo::CompositeOp, PatternRewriter &) { + return failure(); + }; + ASSERT_TRUE(succeeded(registry.addComposite("shared", 0, compositeHandler))); + EXPECT_FALSE(succeeded(registry.addComposite("shared", 0, compositeHandler))); + EXPECT_TRUE(succeeded(registry.addComposite("shared", 1, compositeHandler))); + ASSERT_TRUE(succeeded(registry.addCustomCall("shared", replaceWithI32(3)))); + EXPECT_NE(registry.lookupComposite("shared", 0), nullptr); + EXPECT_NE(registry.lookupComposite("shared", 1), nullptr); + EXPECT_NE(registry.lookupCustomCall("shared"), nullptr); +} + +TEST_F(TargetRegistryTest, OwnsTemporaryStringKeys) { + TargetRegistry registry; + { + std::string key = "temporary_target"; + ASSERT_TRUE(succeeded(registry.addCustomCall(key, replaceWithI32(4)))); + } + EXPECT_NE(registry.lookupCustomCall("temporary_target"), nullptr); +} + +TEST_F(TargetRegistryTest, PassSnapshotsRegistryBeforeLaterRegistration) { + TargetRegistry registry; + PassManager manager(&context); + manager.addPass( + createRewriteRegisteredCustomCallsAndCompositesPass(registry)); + ASSERT_TRUE( + succeeded(registry.addCustomCall("late_target", replaceWithI32(5)))); + + auto module = parseModule(R"mlir( + module { + func.func @run() -> tensor<i32> { + %0 = stablehlo.custom_call @late_target() {has_side_effect = false} + : () -> tensor<i32> + return %0 : tensor<i32> + } + } + )mlir"); + ASSERT_TRUE(module); + ASSERT_TRUE(succeeded(manager.run(*module))); + EXPECT_NE(print(*module).find("stablehlo.custom_call @late_target"), + std::string::npos); +} + +TEST_F(TargetRegistryTest, ClonedPassOutlivesRegistry) { + auto clonedPipeline = [&]() -> std::unique_ptr<OpPassManager> { + TargetRegistry registry; + if (failed(registry.addCustomCall("owned_target", replaceWithI32(7)))) { + return nullptr; + } + OpPassManager original(ModuleOp::getOperationName()); + original.addPass( + createRewriteRegisteredCustomCallsAndCompositesPass(registry)); + return std::make_unique<OpPassManager>(original); + }(); + ASSERT_NE(clonedPipeline, nullptr); + auto module = parseModule(R"mlir( + module { + func.func @run() -> tensor<i32> { + %0 = stablehlo.custom_call @owned_target() {has_side_effect = false} + : () -> tensor<i32> + return %0 : tensor<i32> + } + } + )mlir"); + ASSERT_TRUE(module); + PassManager manager(&context); + static_cast<OpPassManager &>(manager) = *clonedPipeline; + ASSERT_TRUE(succeeded(manager.run(*module))); + EXPECT_NE(print(*module).find("dense<7>"), std::string::npos); +} + +TEST_F(TargetRegistryTest, HandlerCanUseDependentDialect) { + DialectRegistry dialectRegistry; + dialectRegistry + .insert<func::FuncDialect, mlir::stablehlo::StablehloDialect>(); + MLIRContext context(dialectRegistry); + TargetRegistry registry; + auto handler = [](mlir::stablehlo::CustomCallOp op, + PatternRewriter &rewriter) -> LogicalResult { + auto type = cast<RankedTensorType>(op.getResult(0).getType()); + auto attr = DenseIntElementsAttr::get(type, APInt(32, 9)); + auto constant = + arith::ConstantOp::create(rewriter, op.getLoc(), type, attr); + rewriter.replaceOp(op, constant.getResult()); + return success(); + }; + ASSERT_TRUE(succeeded(registry.addCustomCall( + "arith_target", handler, [](DialectRegistry &dialects) { + dialects.insert<arith::ArithDialect>(); + }))); + auto module = parseSourceString<ModuleOp>(R"mlir( + module { + func.func @run() -> tensor<i32> { + %0 = stablehlo.custom_call @arith_target() {has_side_effect = false} + : () -> tensor<i32> + return %0 : tensor<i32> + } + } + )mlir", + &context); + ASSERT_TRUE(module); + PassManager manager(&context); + manager.addPass( + createRewriteRegisteredCustomCallsAndCompositesPass(registry)); + ASSERT_TRUE(succeeded(manager.run(*module))); + EXPECT_NE(context.getLoadedDialect<arith::ArithDialect>(), nullptr); + std::string printed; + llvm::raw_string_ostream stream(printed); + module->print(stream); + EXPECT_NE(printed.find("arith.constant dense<9>"), std::string::npos); +} + +// The handler rewrites only the supported version with mode "identity". +// An unknown version skips the handler; an unsupported mode is declined by it. +// Both remain as composites until they are replaced by decomposition calls. +TEST_F(TargetRegistryTest, + UnsupportedCompositeVersionsAndModesRemainForDecomposition) { + TargetRegistry registry; + int handlerCalls = 0; + auto handler = [&handlerCalls](mlir::stablehlo::CompositeOp op, + PatternRewriter &rewriter) -> LogicalResult { + EXPECT_EQ(op.getVersion(), 1); + ++handlerCalls; + auto mode = op.getCompositeAttributes().getAs<StringAttr>("mode"); + if (!mode || mode.getValue() != "identity") { + return failure(); + } + rewriter.replaceOp(op, op.getInputs()); + return success(); + }; + ASSERT_TRUE(succeeded(registry.addComposite("test.identity", 1, handler))); + auto module = parseModule(R"mlir( + module { + func.func @run(%arg0: tensor<4xf32>) + -> (tensor<4xf32>, tensor<4xf32>, tensor<4xf32>) { + %exact = stablehlo.composite "test.identity" %arg0 { + decomposition = @reference_identity, + composite_attributes = {mode = "identity"}, + version = 1 : i32 + } : (tensor<4xf32>) -> tensor<4xf32> + %unknown_version = stablehlo.composite "test.identity" %arg0 { + decomposition = @reference_identity, + composite_attributes = {mode = "identity"}, + version = 99 : i32 + } : (tensor<4xf32>) -> tensor<4xf32> + %unsupported_mode = stablehlo.composite "test.identity" %arg0 { + decomposition = @reference_identity, + composite_attributes = {mode = "unsupported"}, + version = 1 : i32 + } : (tensor<4xf32>) -> tensor<4xf32> + return %exact, %unknown_version, %unsupported_mode + : tensor<4xf32>, tensor<4xf32>, tensor<4xf32> + } + func.func private @reference_identity(%arg0: tensor<4xf32>) + -> tensor<4xf32> { + return %arg0 : tensor<4xf32> + } + } + )mlir"); + ASSERT_TRUE(module); + + ASSERT_TRUE(runRewritePass(*module, registry)); + EXPECT_GE(handlerCalls, 2); + int remainingComposites = 0; + module->walk([&](mlir::stablehlo::CompositeOp) { ++remainingComposites; }); + EXPECT_EQ(remainingComposites, 2); + + PassManager manager(&context); + manager.addNestedPass<func::FuncOp>( + mlir::stablehlo::createStablehloLegalizeCompositeToCallPass( + mlir::stablehlo::StablehloLegalizeCompositeToCallPassOptions{ + /*exceptListOption=*/{}})); + ASSERT_TRUE(succeeded(manager.run(*module))); + remainingComposites = 0; + module->walk([&](mlir::stablehlo::CompositeOp) { ++remainingComposites; }); + EXPECT_EQ(remainingComposites, 0); + int referenceCalls = 0; + module->walk([&](func::CallOp call) { + if (call.getCallee() == "reference_identity") { + ++referenceCalls; + } + }); + EXPECT_EQ(referenceCalls, 2); +} + +// Handlers receive the JAX dimension and platform operands along with the data. +// The handler returns the data operand for accepted composites. If it declines, +// all operands remain available for decomposition. +TEST_F(TargetRegistryTest, + HandlersReceiveDimensionAndPlatformOperandsAndDeclinesPreserveThem) { + TargetRegistry registry; + std::vector<size_t> inputCounts; + auto handler = [&inputCounts](mlir::stablehlo::CompositeOp op, + PatternRewriter &rewriter) -> LogicalResult { + inputCounts.push_back(op.getInputs().size()); + EXPECT_TRUE(succeeded(verify(op))); + auto mode = op.getCompositeAttributes().getAs<StringAttr>("mode"); + if (!mode || mode.getValue() != "identity") { + return failure(); + } + rewriter.replaceOp(op, op.getInputs().take_back(1)); + return success(); + }; + ASSERT_TRUE(succeeded(registry.addComposite("test.identity", 1, handler))); + auto module = parseModule(R"mlir( + module { + func.func @run(%s: tensor<i64>, %p: tensor<i32>, %x: tensor<?x7xf32>) + -> (tensor<?x7xf32>, tensor<?x7xf32>, tensor<?x7xf32>) { + %one = stablehlo.composite "test.identity" %s, %x { + decomposition = @dims_identity, + composite_attributes = {mode = "identity"}, + version = 1 : i32 + } : (tensor<i64>, tensor<?x7xf32>) -> tensor<?x7xf32> + %two = stablehlo.composite "test.identity" %p, %s, %x { + decomposition = @platform_dims_identity, + composite_attributes = {mode = "identity"}, + version = 1 : i32 + } : (tensor<i32>, tensor<i64>, tensor<?x7xf32>) -> tensor<?x7xf32> + %declined = stablehlo.composite "test.identity" %s, %x { + decomposition = @dims_identity, + composite_attributes = {mode = "unsupported"}, + version = 1 : i32 + } : (tensor<i64>, tensor<?x7xf32>) -> tensor<?x7xf32> + return %one, %two, %declined + : tensor<?x7xf32>, tensor<?x7xf32>, tensor<?x7xf32> + } + func.func private @dims_identity( + %arg0: tensor<i64> {jax.global_constant = "s"}, + %arg1: tensor<?x7xf32>) -> tensor<?x7xf32> { + return %arg1 : tensor<?x7xf32> + } + func.func private @platform_dims_identity( + %arg0: tensor<i32> {jax.global_constant = "_platform_index"}, + %arg1: tensor<i64> {jax.global_constant = "s"}, + %arg2: tensor<?x7xf32>) -> tensor<?x7xf32> { + return %arg2 : tensor<?x7xf32> + } + } + )mlir"); + ASSERT_TRUE(module); + + ASSERT_TRUE(runRewritePass(*module, registry)); + ASSERT_FALSE(inputCounts.empty()); + for (size_t count : inputCounts) { + EXPECT_TRUE(count == 2u || count == 3u); + } + auto run = module->lookupSymbol<func::FuncOp>("run"); + auto returned = cast<func::ReturnOp>(run.getBody().front().getTerminator()); + EXPECT_EQ(returned.getOperand(0), run.getArgument(2)); + EXPECT_EQ(returned.getOperand(1), run.getArgument(2)); + // The declined composite keeps every operand for its decomposition. + SmallVector<mlir::stablehlo::CompositeOp> remaining; + module->walk( + [&](mlir::stablehlo::CompositeOp op) { remaining.push_back(op); }); + ASSERT_EQ(remaining.size(), 1u); + EXPECT_EQ(remaining.front().getInputs().size(), 2u); + EXPECT_EQ(returned.getOperand(2), remaining.front().getResult(0)); +} + +TEST_F(TargetRegistryTest, ChainedDeclinesPreserveDecompositionFallback) { + auto module = parseModule(R"mlir( + module { + func.func @run(%s: tensor<i64>, %x: tensor<?x7xf32>) -> tensor<?x7xf32> { + %a = stablehlo.composite "test.identity" %s, %x { + decomposition = @reference, version = 1 : i32 + } : (tensor<i64>, tensor<?x7xf32>) -> tensor<?x7xf32> + %b = stablehlo.composite "test.identity" %s, %a { + decomposition = @reference, version = 1 : i32 + } : (tensor<i64>, tensor<?x7xf32>) -> tensor<?x7xf32> + return %b : tensor<?x7xf32> + } + func.func private @reference( + %s: tensor<i64> {jax.global_constant = "s"}, + %x: tensor<?x7xf32>) -> tensor<?x7xf32> { + return %x : tensor<?x7xf32> + } + } + )mlir"); + ASSERT_TRUE(module); + std::string before = print(*module); + TargetRegistry registry; + unsigned calls = 0; + ASSERT_TRUE(succeeded( + registry.addComposite("test.identity", 1, + [&calls](mlir::stablehlo::CompositeOp op, + PatternRewriter &) -> LogicalResult { + ++calls; + EXPECT_EQ(op.getInputs().size(), 2u); + EXPECT_TRUE(succeeded(verify(op))); + return failure(); + }))); + ASSERT_TRUE(runRewritePass(*module, registry)); + EXPECT_GE(calls, 2u); + EXPECT_EQ(print(*module), before); + + PassManager fallback(&context); + fallback.addNestedPass<func::FuncOp>( + mlir::stablehlo::createStablehloLegalizeCompositeToCallPass( + mlir::stablehlo::StablehloLegalizeCompositeToCallPassOptions{ + /*exceptListOption=*/{}})); + ASSERT_TRUE(succeeded(fallback.run(*module))); + EXPECT_TRUE(succeeded(verify(*module))); + unsigned referenceCalls = 0; + module->walk([&](func::CallOp call) { + EXPECT_EQ(call.getCallee(), "reference"); + EXPECT_EQ(call.getNumOperands(), 2u); + ++referenceCalls; + }); + EXPECT_EQ(referenceCalls, 2u); + module->walk([](mlir::stablehlo::CompositeOp) { + ADD_FAILURE() << "Composite did not decompose"; + }); +} + +TEST_F(TargetRegistryTest, DeclinedRegionsRemainAvailableToLaterHandlers) { + auto module = parseModule(R"mlir( + module { + func.func @run(%s: tensor<i64>, %x: tensor<f32>) -> tensor<f32> { + %r = "stablehlo.composite"(%s, %x) ({ + ^bb0(%value: tensor<f32>): + "stablehlo.return"(%value) : (tensor<f32>) -> () + }) {name = "test.region", decomposition = @reference, + version = 1 : i32} : (tensor<i64>, tensor<f32>) -> tensor<f32> + return %r : tensor<f32> + } + func.func private @reference( + %s: tensor<i64> {jax.global_constant = "s"}, + %x: tensor<f32>) -> tensor<f32> { + return %x : tensor<f32> + } + } + )mlir"); + ASSERT_TRUE(module); + auto run = module->lookupSymbol<func::FuncOp>("run"); + auto original = *run.getOps<mlir::stablehlo::CompositeOp>().begin(); + Block *originalBody = &original->getRegion(0).front(); + std::string before = print(*module); + TargetRegistry declining; + unsigned declines = 0; + ASSERT_TRUE(succeeded(declining.addComposite( + "test.region", 1, + [original, originalBody, &declines](mlir::stablehlo::CompositeOp op, + PatternRewriter &) -> LogicalResult { + ++declines; + EXPECT_EQ(op, original); + EXPECT_EQ(op.getInputs().size(), 2u); + EXPECT_TRUE(succeeded(verify(op))); + EXPECT_EQ(op->getNumRegions(), 1u); + if (op->getNumRegions() == 1) { + EXPECT_EQ(&op->getRegion(0).front(), originalBody); + } + return failure(); + }))); + ASSERT_TRUE(runRewritePass(*module, declining)); + EXPECT_GE(declines, 1u); + EXPECT_EQ(print(*module), before); + + TargetRegistry accepting; + unsigned calls = 0; + ASSERT_TRUE(succeeded(accepting.addComposite( + "test.region", 1, + [original, originalBody, + &calls](mlir::stablehlo::CompositeOp op, + PatternRewriter &rewriter) -> LogicalResult { + ++calls; + EXPECT_EQ(op, original); + EXPECT_TRUE(succeeded(verify(op))); + EXPECT_EQ(op->getNumRegions(), 1u); + if (op->getNumRegions() == 1) { + EXPECT_EQ(&op->getRegion(0).front(), originalBody); + } + rewriter.replaceOp(op, op.getInputs().take_back(1)); + return success(); + }))); + ASSERT_TRUE(runRewritePass(*module, accepting)); + EXPECT_EQ(calls, 1u); + EXPECT_TRUE(succeeded(verify(*module))); + auto returned = cast<func::ReturnOp>(run.getBody().front().getTerminator()); + EXPECT_EQ(returned.getOperand(0), run.getArgument(1)); +} + +} // namespace +} // namespace mlir::iree_compiler::stablehlo