From 9a10bbec47ba373b753f5ac25d9d7b6d07606fc2 Mon Sep 17 00:00:00 2001 From: fschlimb Date: Mon, 16 Nov 2026 06:00:40 -0800 Subject: [PATCH] [backend][cpu] hoist AMX stack buffers to the function entry block --- backends/cpu/ApproximateMath.cpp | 86 -------------- backends/cpu/ApproximateMath.h | 6 - backends/cpu/PrepareCPUVectors.cpp | 152 +++++++++++++++++++++++++ backends/cpu/PrepareCPUVectors.h | 21 ++++ backends/cpu/compiler.cmake | 9 +- backends/cpu/compiler_cpu.cpp | 1 + backends/cpu/test/test_compiler_cpu.py | 48 ++++++++ 7 files changed, 229 insertions(+), 94 deletions(-) create mode 100644 backends/cpu/PrepareCPUVectors.cpp create mode 100644 backends/cpu/PrepareCPUVectors.h diff --git a/backends/cpu/ApproximateMath.cpp b/backends/cpu/ApproximateMath.cpp index 988a172b..38b4a7c6 100644 --- a/backends/cpu/ApproximateMath.cpp +++ b/backends/cpu/ApproximateMath.cpp @@ -5,98 +5,17 @@ #include "ApproximateMath.h" -#include - -#include "mlir/Dialect/Affine/IR/AffineDialect.h" #include "mlir/Dialect/Arith/IR/Arith.h" -#include "mlir/Dialect/Func/IR/FuncOps.h" -#include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Dialect/Math/IR/Math.h" #include "mlir/Dialect/Math/Transforms/Passes.h" -#include "mlir/Dialect/MemRef/IR/MemRef.h" #include "mlir/Dialect/Vector/IR/VectorOps.h" -#include "mlir/Dialect/Vector/Transforms/VectorRewritePatterns.h" -#include "mlir/Dialect/X86/Transforms.h" -#include "mlir/Dialect/X86/X86Dialect.h" #include "mlir/IR/BuiltinOps.h" -#include "mlir/IR/Dominance.h" #include "mlir/Pass/Pass.h" -#include "mlir/Transforms/CSE.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" -#include "mlir/Transforms/RegionUtils.h" namespace cutile { namespace { -class PrepareCPUVectorsPass - : public mlir::PassWrapper> { -public: - MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(PrepareCPUVectorsPass) - - explicit PrepareCPUVectorsPass(llvm::StringRef entryPoint) - : prepareX86(entryPoint != "__transform_nano"), - prepareAMX(entryPoint == "__transform_nano_amx") {} - - void getDependentDialects(mlir::DialectRegistry ®istry) const override { - registry.insert(); - } - - void runOnOperation() override { - llvm::SmallVector functions; - getOperation().walk( - [&](mlir::func::FuncOp function) { functions.push_back(function); }); - auto apply = [&](auto populatePatterns) { - for (mlir::func::FuncOp function : functions) { - mlir::RewritePatternSet patterns(&getContext()); - populatePatterns(patterns); - mlir::GreedyRewriteConfig config; - config.setMaxIterations(mlir::GreedyRewriteConfig::kNoLimit); - config.setMaxNumRewrites(mlir::GreedyRewriteConfig::kNoLimit); - if (mlir::failed(mlir::applyPatternsGreedily( - function, std::move(patterns), config))) - return mlir::failure(); - } - return mlir::success(); - }; - if (mlir::failed(apply([](mlir::RewritePatternSet &patterns) { - mlir::vector::populateCastAwayVectorLeadingOneDimPatterns(patterns); - mlir::vector::populateDropUnitDimWithShapeCastPatterns(patterns); - }))) { - signalPassFailure(); - return; - } - if (!prepareX86) - return; - if (mlir::failed( - apply(mlir::x86::populatePrepareVectorContractLoopsPatterns))) { - signalPassFailure(); - return; - } - mlir::IRRewriter rewriter(&getContext()); - for (mlir::func::FuncOp function : functions) - for (mlir::Region ®ion : function->getRegions()) - mlir::eliminateTriviallyDeadOps(rewriter, region); - for (mlir::func::FuncOp function : functions) { - mlir::DominanceInfo dominance; - mlir::eliminateCommonSubExpressions(rewriter, dominance, function); - } - if (prepareAMX && mlir::failed(apply([](mlir::RewritePatternSet &patterns) { - mlir::x86::populateVectorContractMultiLevelUnrollForAMXPatterns( - patterns); - mlir::x86::populateVectorContractToAMXDotProductPatterns(patterns); - }))) - signalPassFailure(); - } - -private: - bool prepareX86; - bool prepareAMX; -}; - class ApproximateMathPass : public mlir::PassWrapper> { @@ -130,9 +49,4 @@ std::unique_ptr createApproximateMathPass() { return std::make_unique(); } -std::unique_ptr -createPrepareCPUVectorsPass(llvm::StringRef entryPoint) { - return std::make_unique(entryPoint); -} - } // namespace cutile diff --git a/backends/cpu/ApproximateMath.h b/backends/cpu/ApproximateMath.h index afe3087a..6051332e 100644 --- a/backends/cpu/ApproximateMath.h +++ b/backends/cpu/ApproximateMath.h @@ -7,10 +7,6 @@ #include -namespace llvm { -class StringRef; -} - namespace mlir { class Pass; } @@ -19,6 +15,4 @@ namespace cutile { // Replaces math functions with vectorizable polynomial approximations, except // sin and cos, whose approximation is inaccurate for large arguments. std::unique_ptr createApproximateMathPass(); -std::unique_ptr -createPrepareCPUVectorsPass(llvm::StringRef entryPoint); } // namespace cutile diff --git a/backends/cpu/PrepareCPUVectors.cpp b/backends/cpu/PrepareCPUVectors.cpp new file mode 100644 index 00000000..46d08a53 --- /dev/null +++ b/backends/cpu/PrepareCPUVectors.cpp @@ -0,0 +1,152 @@ +// SPDX-FileCopyrightText: Copyright (c) <2026> Intel Corporation. All rights +// reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +#include "PrepareCPUVectors.h" + +#include +#include + +#include "mlir/Dialect/Affine/IR/AffineDialect.h" +#include "mlir/Dialect/Arith/IR/Arith.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" +#include "mlir/Dialect/Math/IR/Math.h" +#include "mlir/Dialect/MemRef/IR/MemRef.h" +#include "mlir/Dialect/Vector/IR/VectorOps.h" +#include "mlir/Dialect/Vector/Transforms/VectorRewritePatterns.h" +#include "mlir/Dialect/X86/Transforms.h" +#include "mlir/Dialect/X86/X86Dialect.h" +#include "mlir/IR/BuiltinOps.h" +#include "mlir/IR/Dominance.h" +#include "mlir/Pass/Pass.h" +#include "mlir/Transforms/CSE.h" +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" +#include "mlir/Transforms/RegionUtils.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SetVector.h" + +namespace cutile { +namespace { + +class AllocaCollector : public mlir::RewriterBase::Listener { +public: + void notifyOperationInserted(mlir::Operation *operation, + mlir::OpBuilder::InsertPoint previous) override { + if (!previous.isSet() && mlir::isa(operation)) + allocas.insert(operation); + } + + void notifyOperationErased(mlir::Operation *operation) override { + if (mlir::isa(operation)) + allocas.remove(operation); + } + + llvm::SmallVector takeAllocas() { + return allocas.takeVector(); + } + +private: + llvm::SetVector allocas; +}; + +class PrepareCPUVectorsPass + : public mlir::PassWrapper> { +public: + MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(PrepareCPUVectorsPass) + + explicit PrepareCPUVectorsPass(llvm::StringRef entryPoint) + : prepareX86(entryPoint != "__transform_nano"), + prepareAMX(entryPoint == "__transform_nano_amx") {} + + void getDependentDialects(mlir::DialectRegistry ®istry) const override { + registry.insert(); + } + + void runOnOperation() override { + llvm::SmallVector functions; + getOperation().walk( + [&](mlir::func::FuncOp function) { functions.push_back(function); }); + auto apply = [&](auto populatePatterns, + mlir::RewriterBase::Listener *listener = nullptr) { + for (mlir::func::FuncOp function : functions) { + mlir::RewritePatternSet patterns(&getContext()); + populatePatterns(patterns); + mlir::GreedyRewriteConfig config; + config.setListener(listener); + config.setMaxIterations(mlir::GreedyRewriteConfig::kNoLimit); + config.setMaxNumRewrites(mlir::GreedyRewriteConfig::kNoLimit); + if (mlir::failed(mlir::applyPatternsGreedily( + function, std::move(patterns), config))) + return mlir::failure(); + } + return mlir::success(); + }; + if (mlir::failed(apply([](mlir::RewritePatternSet &patterns) { + mlir::vector::populateCastAwayVectorLeadingOneDimPatterns(patterns); + mlir::vector::populateDropUnitDimWithShapeCastPatterns(patterns); + }))) { + signalPassFailure(); + return; + } + if (!prepareX86) + return; + if (mlir::failed( + apply(mlir::x86::populatePrepareVectorContractLoopsPatterns))) { + signalPassFailure(); + return; + } + mlir::IRRewriter rewriter(&getContext()); + for (mlir::func::FuncOp function : functions) + for (mlir::Region ®ion : function->getRegions()) + mlir::eliminateTriviallyDeadOps(rewriter, region); + for (mlir::func::FuncOp function : functions) { + mlir::DominanceInfo dominance; + mlir::eliminateCommonSubExpressions(rewriter, dominance, function); + } + if (!prepareAMX) + return; + AllocaCollector collector; + if (mlir::failed(apply( + [](mlir::RewritePatternSet &patterns) { + mlir::x86::populateVectorContractMultiLevelUnrollForAMXPatterns( + patterns); + mlir::x86::populateVectorContractToAMXDotProductPatterns( + patterns); + }, + &collector))) { + signalPassFailure(); + return; + } + // Non-entry allocas are dynamic in LLVM; 64 B is a cache line/AMX tile row. + llvm::SmallVector allocas = collector.takeAllocas(); + for (mlir::Operation *operation : llvm::reverse(allocas)) { + auto alloca = mlir::cast(operation); + if (alloca->getNumOperands()) + continue; + mlir::Block &entry = + alloca->getParentOfType().getBody().front(); + alloca->moveBefore(&entry, entry.begin()); + alloca.setAlignment( + std::max(alloca.getAlignment().value_or(0), 64)); + } + } + +private: + bool prepareX86; + bool prepareAMX; +}; + +} // namespace + +std::unique_ptr +createPrepareCPUVectorsPass(llvm::StringRef entryPoint) { + return std::make_unique(entryPoint); +} + +} // namespace cutile diff --git a/backends/cpu/PrepareCPUVectors.h b/backends/cpu/PrepareCPUVectors.h new file mode 100644 index 00000000..9e754122 --- /dev/null +++ b/backends/cpu/PrepareCPUVectors.h @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: Copyright (c) <2026> Intel Corporation. All rights +// reserved. +// +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +namespace llvm { +class StringRef; +} + +namespace mlir { +class Pass; +} + +namespace cutile { +std::unique_ptr +createPrepareCPUVectorsPass(llvm::StringRef entryPoint); +} // namespace cutile diff --git a/backends/cpu/compiler.cmake b/backends/cpu/compiler.cmake index 28b255e2..84eb0069 100644 --- a/backends/cpu/compiler.cmake +++ b/backends/cpu/compiler.cmake @@ -2,7 +2,10 @@ # # SPDX-License-Identifier: Apache-2.0 -target_sources(_compiler PRIVATE cpu/compiler_cpu.cpp cpu/ApproximateMath.cpp) +target_sources(_compiler PRIVATE + cpu/compiler_cpu.cpp + cpu/ApproximateMath.cpp + cpu/PrepareCPUVectors.cpp) if(CUTILE_NATIVE_SDK_DIR) target_include_directories(_compiler SYSTEM PRIVATE ${LLD_INCLUDE_DIRS}) else() @@ -19,6 +22,8 @@ llvm_map_components_to_libnames(_llvm_libs nativecodegen passes) target_link_libraries(_compiler PRIVATE ${_llvm_libs}) if(NOT LLVM_ENABLE_RTTI) - set_source_files_properties(cpu/ApproximateMath.cpp + set_source_files_properties( + cpu/ApproximateMath.cpp + cpu/PrepareCPUVectors.cpp PROPERTIES COMPILE_OPTIONS "-fno-rtti") endif() \ No newline at end of file diff --git a/backends/cpu/compiler_cpu.cpp b/backends/cpu/compiler_cpu.cpp index 1ce18cb5..c61ed921 100644 --- a/backends/cpu/compiler_cpu.cpp +++ b/backends/cpu/compiler_cpu.cpp @@ -7,6 +7,7 @@ #include "mlir/compiler.h" #include "ApproximateMath.h" +#include "PrepareCPUVectors.h" #include "amx.h" #include "lld/Common/Driver.h" #include "mlir/Conversion/Passes.h" diff --git a/backends/cpu/test/test_compiler_cpu.py b/backends/cpu/test/test_compiler_cpu.py index 41cbad17..7108eac3 100644 --- a/backends/cpu/test/test_compiler_cpu.py +++ b/backends/cpu/test/test_compiler_cpu.py @@ -97,6 +97,54 @@ def test_builtin_cpu_pipeline_rejects_unknown_entry_point(native): native.lower_cpu_mlir(b"module {}", "unknown") +# The leading loop moves later top-level ops out of the LLVM entry block. +_AMX_MATMUL_AFTER_LOOP = b""" +#lhs = affine_map<(m, n, k) -> (m, k)> +#rhs = affine_map<(m, n, k) -> (k, n)> +#acc = affine_map<(m, n, k) -> (m, n)> +module { + func.func private @declaration() + func.func @matmul(%a: memref<32x64xbf16>, %b: memref<64x32xbf16>, + %c: memref<32x32xbf16>) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c32 = arith.constant 32 : index + %c64 = arith.constant 64 : index + %pad = arith.constant 0.0 : bf16 + %zero = arith.constant dense<0.0> : vector<32x32xf32> + scf.for %i = %c0 to %c32 step %c1 { + memref.store %pad, %c[%c0, %i] : memref<32x32xbf16> + } + %sum = scf.for %k = %c0 to %c64 step %c32 + iter_args(%acc = %zero) -> (vector<32x32xf32>) { + %x = vector.transfer_read %a[%c0, %k], %pad {in_bounds = [true, true]} + : memref<32x64xbf16>, vector<32x32xbf16> + %y = vector.transfer_read %b[%k, %c0], %pad {in_bounds = [true, true]} + : memref<64x32xbf16>, vector<32x32xbf16> + %product = vector.contract {indexing_maps = [#lhs, #rhs, #acc], + iterator_types = ["parallel", "parallel", "reduction"], + kind = #vector.kind} %x, %y, %acc + : vector<32x32xbf16>, vector<32x32xbf16> into vector<32x32xf32> + scf.yield %product : vector<32x32xf32> + } + %result = arith.truncf %sum : vector<32x32xf32> to vector<32x32xbf16> + vector.transfer_write %result, %c[%c0, %c0] {in_bounds = [true, true]} + : vector<32x32xbf16>, memref<32x32xbf16> + return + } +} +""" + + +def test_amx_pipeline_moves_stack_buffers_to_entry_block(native): + llvm_ir = native.lower_cpu_mlir(_AMX_MATMUL_AFTER_LOOP, "__transform_nano_amx").decode() + function = llvm_ir[llvm_ir.index("@matmul("):] + entry, _, rest = function[:function.index("\n}\n")].partition("\n\n") + allocas = [line for line in entry.splitlines() if "= alloca " in line] + assert allocas and all("align 64" in line for line in allocas) + assert "= alloca " not in rest + + @ct.kernel def _divide(x, y, out): a = ct.load(x, index=(0,), shape=(1,))