[llvm] Tile reducer milestones (PR #216546)

Ionut Hristodorescu via llvm-commits llvm-commits at lists.llvm.org
Sun Aug 16 00:24:11 PDT 2026


https://github.com/ihiasi created https://github.com/llvm/llvm-project/pull/216546

None

>From 093bcec583f494b39e1e4cb0c6b186f80db70254 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 19:05:48 -0700
Subject: [PATCH 01/29] [TileReducer] Milestone 1: standalone tr-opt project

Add an out-of-tree MLIR project that registers the empty `tr` dialect,
builds `tr-opt`, and runs a lit/FileCheck smoke test. Types and ops are
intentionally deferred to later milestones.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/smoke.mlir
  tr-opt --show-dialects tile-reducer/test/smoke.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/.gitignore                       |  1 +
 tile-reducer/CMakeLists.txt                   | 41 +++++++++++++++++++
 tile-reducer/README.md                        | 14 +++++++
 tile-reducer/examples/row_sum.mlir            | 29 +++++++++++++
 tile-reducer/include/CMakeLists.txt           |  1 +
 .../include/TileReducer/CMakeLists.txt        |  2 +
 .../include/TileReducer/TileReducerDialect.h  | 11 +++++
 .../include/TileReducer/TileReducerDialect.td | 31 ++++++++++++++
 .../include/TileReducer/TileReducerOps.h      | 13 ++++++
 .../include/TileReducer/TileReducerOps.td     | 13 ++++++
 tile-reducer/lib/CMakeLists.txt               |  1 +
 tile-reducer/lib/TileReducer/CMakeLists.txt   | 14 +++++++
 .../lib/TileReducer/TileReducerDialect.cpp    | 16 ++++++++
 .../lib/TileReducer/TileReducerOps.cpp        | 10 +++++
 tile-reducer/test/CMakeLists.txt              | 14 +++++++
 tile-reducer/test/lit.cfg.py                  | 20 +++++++++
 tile-reducer/test/lit.site.cfg.py.in          | 11 +++++
 tile-reducer/test/smoke.mlir                  | 16 ++++++++
 tile-reducer/tr-opt/CMakeLists.txt            | 12 ++++++
 tile-reducer/tr-opt/tr-opt.cpp                | 22 ++++++++++
 20 files changed, 292 insertions(+)
 create mode 100644 tile-reducer/.gitignore
 create mode 100644 tile-reducer/CMakeLists.txt
 create mode 100644 tile-reducer/README.md
 create mode 100644 tile-reducer/examples/row_sum.mlir
 create mode 100644 tile-reducer/include/CMakeLists.txt
 create mode 100644 tile-reducer/include/TileReducer/CMakeLists.txt
 create mode 100644 tile-reducer/include/TileReducer/TileReducerDialect.h
 create mode 100644 tile-reducer/include/TileReducer/TileReducerDialect.td
 create mode 100644 tile-reducer/include/TileReducer/TileReducerOps.h
 create mode 100644 tile-reducer/include/TileReducer/TileReducerOps.td
 create mode 100644 tile-reducer/lib/CMakeLists.txt
 create mode 100644 tile-reducer/lib/TileReducer/CMakeLists.txt
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerDialect.cpp
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerOps.cpp
 create mode 100644 tile-reducer/test/CMakeLists.txt
 create mode 100644 tile-reducer/test/lit.cfg.py
 create mode 100644 tile-reducer/test/lit.site.cfg.py.in
 create mode 100644 tile-reducer/test/smoke.mlir
 create mode 100644 tile-reducer/tr-opt/CMakeLists.txt
 create mode 100644 tile-reducer/tr-opt/tr-opt.cpp

diff --git a/tile-reducer/.gitignore b/tile-reducer/.gitignore
new file mode 100644
index 0000000000000..84c048a73cc2e
--- /dev/null
+++ b/tile-reducer/.gitignore
@@ -0,0 +1 @@
+/build/
diff --git a/tile-reducer/CMakeLists.txt b/tile-reducer/CMakeLists.txt
new file mode 100644
index 0000000000000..fe109773df0ab
--- /dev/null
+++ b/tile-reducer/CMakeLists.txt
@@ -0,0 +1,41 @@
+cmake_minimum_required(VERSION 3.20.0)
+project(tile-reducer LANGUAGES CXX C)
+
+set(CMAKE_BUILD_WITH_INSTALL_NAME_DIR ON)
+set(CMAKE_CXX_STANDARD 17 CACHE STRING "C++ standard to conform to")
+
+# Build against an existing LLVM/MLIR build. Point -DMLIR_DIR at
+#   <llvm-build>/lib/cmake/mlir
+find_package(MLIR REQUIRED CONFIG)
+
+set(LLVM_LIT_ARGS "-sv" CACHE STRING "Default options for lit")
+
+message(STATUS "Using MLIRConfig.cmake in: ${MLIR_DIR}")
+message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}")
+
+set(LLVM_RUNTIME_OUTPUT_INTDIR ${CMAKE_BINARY_DIR}/bin)
+set(LLVM_LIBRARY_OUTPUT_INTDIR ${CMAKE_BINARY_DIR}/lib)
+set(MLIR_BINARY_DIR ${CMAKE_BINARY_DIR})
+
+list(APPEND CMAKE_MODULE_PATH "${MLIR_CMAKE_DIR}")
+list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}")
+
+include(TableGen)
+include(AddLLVM)
+include(AddMLIR)
+include(HandleLLVMOptions)
+
+include_directories(${LLVM_INCLUDE_DIRS})
+include_directories(${MLIR_INCLUDE_DIRS})
+include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
+include_directories(${CMAKE_CURRENT_BINARY_DIR}/include)
+link_directories(${LLVM_BUILD_LIBRARY_DIR})
+add_definitions(${LLVM_DEFINITIONS})
+
+set(TR_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
+set(TR_BINARY_DIR ${CMAKE_BINARY_DIR})
+
+add_subdirectory(include)
+add_subdirectory(lib)
+add_subdirectory(tr-opt)
+add_subdirectory(test)
diff --git a/tile-reducer/README.md b/tile-reducer/README.md
new file mode 100644
index 0000000000000..e2bd001fbaea3
--- /dev/null
+++ b/tile-reducer/README.md
@@ -0,0 +1,14 @@
+# TileReducer
+
+Out-of-tree MLIR compiler for a tile-level reduction language. Built against
+an existing LLVM/MLIR tree; do not use the Tensor dialect.
+
+## Milestone 1
+
+Standalone project: `tr` dialect registration, `tr-opt`, CMake, lit smoke test.
+
+```bash
+cmake -G Ninja -S tile-reducer -B tile-reducer/build \
+  -DMLIR_DIR=/Users/ionut/work/llvm/build/build-xcode/lib/cmake/mlir
+cmake --build tile-reducer/build --target tr-opt check-tr
+```
diff --git a/tile-reducer/examples/row_sum.mlir b/tile-reducer/examples/row_sum.mlir
new file mode 100644
index 0000000000000..438499f0db52f
--- /dev/null
+++ b/tile-reducer/examples/row_sum.mlir
@@ -0,0 +1,29 @@
+// Canonical TileReducer row-sum source. Not a lit test until types (M2)
+// and operations (M3) exist; preserved here so later milestones start from
+// this program rather than a redesigned language.
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : index
+  %num_k_tiles = arith.divui %k, %c128 : index
+
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.tile<128x128xf32>
+
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+
+    %acc2    = tr.add %acc, %partial
+        : !tr.tile<128xf32>
+
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+
+  tr.store %out[%row_blk], %result : !tr.tile<128xf32>
+  return
+}
diff --git a/tile-reducer/include/CMakeLists.txt b/tile-reducer/include/CMakeLists.txt
new file mode 100644
index 0000000000000..746a7efd4cb51
--- /dev/null
+++ b/tile-reducer/include/CMakeLists.txt
@@ -0,0 +1 @@
+add_subdirectory(TileReducer)
diff --git a/tile-reducer/include/TileReducer/CMakeLists.txt b/tile-reducer/include/TileReducer/CMakeLists.txt
new file mode 100644
index 0000000000000..bf4d0a09b3dc9
--- /dev/null
+++ b/tile-reducer/include/TileReducer/CMakeLists.txt
@@ -0,0 +1,2 @@
+add_mlir_dialect(TileReducerOps tr)
+add_mlir_doc(TileReducerDialect TileReducerDialect TileReducer/ -gen-dialect-doc)
diff --git a/tile-reducer/include/TileReducer/TileReducerDialect.h b/tile-reducer/include/TileReducer/TileReducerDialect.h
new file mode 100644
index 0000000000000..48310df7fe202
--- /dev/null
+++ b/tile-reducer/include/TileReducer/TileReducerDialect.h
@@ -0,0 +1,11 @@
+//===- TileReducerDialect.h - TileReducer dialect ---------------*- C++ -*-===//
+
+#ifndef TILE_REDUCER_TILEREDUCERDIALECT_H
+#define TILE_REDUCER_TILEREDUCERDIALECT_H
+
+#include "mlir/Bytecode/BytecodeOpInterface.h"
+#include "mlir/IR/Dialect.h"
+
+#include "TileReducer/TileReducerOpsDialect.h.inc"
+
+#endif // TILE_REDUCER_TILEREDUCERDIALECT_H
diff --git a/tile-reducer/include/TileReducer/TileReducerDialect.td b/tile-reducer/include/TileReducer/TileReducerDialect.td
new file mode 100644
index 0000000000000..a001b209808aa
--- /dev/null
+++ b/tile-reducer/include/TileReducer/TileReducerDialect.td
@@ -0,0 +1,31 @@
+//===- TileReducerDialect.td - TileReducer dialect ---------*- tablegen -*-===//
+//
+// Milestone 1: dialect declaration only. Types arrive in Milestone 2,
+// operations in Milestone 3.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef TILE_REDUCER_DIALECT
+#define TILE_REDUCER_DIALECT
+
+include "mlir/IR/OpBase.td"
+
+def TileReducer_Dialect : Dialect {
+  let name = "tr";
+  let summary = "Tile-level reduction dialect for GPU compilation.";
+  let description = [{
+    TileReducer is a tile-level source dialect. Programmers write logical
+    tiles and reductions; they do not write threadIdx, lane IDs, or launch
+    geometry. Physical GPU mapping is chosen by later lowering stages.
+
+    `tr.program_id` names a logical program instance, not a hardware thread.
+    `!tr.tile` is a logical SSA value with no required physical storage.
+    `!tr.buffer` is addressable external storage and later lowers to MemRef.
+  }];
+  let cppNamespace = "::mlir::tr";
+}
+
+class TileReducer_Op<string mnemonic, list<Trait> traits = []> :
+    Op<TileReducer_Dialect, mnemonic, traits>;
+
+#endif // TILE_REDUCER_DIALECT
diff --git a/tile-reducer/include/TileReducer/TileReducerOps.h b/tile-reducer/include/TileReducer/TileReducerOps.h
new file mode 100644
index 0000000000000..d2307b1a81fab
--- /dev/null
+++ b/tile-reducer/include/TileReducer/TileReducerOps.h
@@ -0,0 +1,13 @@
+//===- TileReducerOps.h - TileReducer operations ----------------*- C++ -*-===//
+
+#ifndef TILE_REDUCER_TILEREDUCEROPS_H
+#define TILE_REDUCER_TILEREDUCEROPS_H
+
+#include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/Dialect.h"
+#include "mlir/IR/OpDefinition.h"
+
+#define GET_OP_CLASSES
+#include "TileReducer/TileReducerOps.h.inc"
+
+#endif // TILE_REDUCER_TILEREDUCEROPS_H
diff --git a/tile-reducer/include/TileReducer/TileReducerOps.td b/tile-reducer/include/TileReducer/TileReducerOps.td
new file mode 100644
index 0000000000000..a1bd9d5408cc9
--- /dev/null
+++ b/tile-reducer/include/TileReducer/TileReducerOps.td
@@ -0,0 +1,13 @@
+//===- TileReducerOps.td - TileReducer operations ----------*- tablegen -*-===//
+//
+// Milestone 1: empty op list so TableGen can generate the dialect class.
+// Operations are added in Milestone 3.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef TILE_REDUCER_OPS
+#define TILE_REDUCER_OPS
+
+include "TileReducer/TileReducerDialect.td"
+
+#endif // TILE_REDUCER_OPS
diff --git a/tile-reducer/lib/CMakeLists.txt b/tile-reducer/lib/CMakeLists.txt
new file mode 100644
index 0000000000000..746a7efd4cb51
--- /dev/null
+++ b/tile-reducer/lib/CMakeLists.txt
@@ -0,0 +1 @@
+add_subdirectory(TileReducer)
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
new file mode 100644
index 0000000000000..f234fb78f7f00
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -0,0 +1,14 @@
+add_mlir_dialect_library(MLIRTileReducer
+        TileReducerDialect.cpp
+        TileReducerOps.cpp
+
+        ADDITIONAL_HEADER_DIRS
+        ${PROJECT_SOURCE_DIR}/include/TileReducer
+
+        DEPENDS
+        MLIRTileReducerOpsIncGen
+
+        LINK_LIBS PUBLIC
+        MLIRIR
+        MLIRSupport
+        )
diff --git a/tile-reducer/lib/TileReducer/TileReducerDialect.cpp b/tile-reducer/lib/TileReducer/TileReducerDialect.cpp
new file mode 100644
index 0000000000000..52364e575fc81
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerDialect.cpp
@@ -0,0 +1,16 @@
+//===- TileReducerDialect.cpp - TileReducer dialect -------------*- C++ -*-===//
+
+#include "TileReducer/TileReducerDialect.h"
+#include "TileReducer/TileReducerOps.h"
+
+using namespace mlir;
+using namespace mlir::tr;
+
+#include "TileReducer/TileReducerOpsDialect.cpp.inc"
+
+void TileReducerDialect::initialize() {
+  addOperations<
+#define GET_OP_LIST
+#include "TileReducer/TileReducerOps.cpp.inc"
+      >();
+}
diff --git a/tile-reducer/lib/TileReducer/TileReducerOps.cpp b/tile-reducer/lib/TileReducer/TileReducerOps.cpp
new file mode 100644
index 0000000000000..ed2296d3a3783
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerOps.cpp
@@ -0,0 +1,10 @@
+//===- TileReducerOps.cpp - TileReducer operations --------------*- C++ -*-===//
+
+#include "TileReducer/TileReducerOps.h"
+#include "TileReducer/TileReducerDialect.h"
+
+using namespace mlir;
+using namespace mlir::tr;
+
+#define GET_OP_CLASSES
+#include "TileReducer/TileReducerOps.cpp.inc"
diff --git a/tile-reducer/test/CMakeLists.txt b/tile-reducer/test/CMakeLists.txt
new file mode 100644
index 0000000000000..5993d470dbb4a
--- /dev/null
+++ b/tile-reducer/test/CMakeLists.txt
@@ -0,0 +1,14 @@
+configure_lit_site_cfg(
+        ${CMAKE_CURRENT_SOURCE_DIR}/lit.site.cfg.py.in
+        ${CMAKE_CURRENT_BINARY_DIR}/lit.site.cfg.py
+        MAIN_CONFIG
+        ${CMAKE_CURRENT_SOURCE_DIR}/lit.cfg.py
+)
+
+add_lit_testsuite(check-tr "Running the TileReducer regression tests"
+        ${CMAKE_CURRENT_BINARY_DIR}
+        DEPENDS tr-opt
+)
+set_target_properties(check-tr PROPERTIES FOLDER "Tests")
+
+add_lit_testsuites(TR ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS tr-opt)
diff --git a/tile-reducer/test/lit.cfg.py b/tile-reducer/test/lit.cfg.py
new file mode 100644
index 0000000000000..c5ab28446f2c8
--- /dev/null
+++ b/tile-reducer/test/lit.cfg.py
@@ -0,0 +1,20 @@
+# -*- Python -*-
+
+import os
+
+import lit.formats
+from lit.llvm import llvm_config
+
+config.name = "TR"
+config.test_format = lit.formats.ShTest(not llvm_config.use_lit_shell)
+config.suffixes = [".mlir"]
+config.test_source_root = os.path.dirname(__file__)
+config.test_exec_root = os.path.join(config.tr_obj_root, "test")
+config.excludes = ["CMakeLists.txt", "lit.cfg.py", "lit.site.cfg.py", "Inputs"]
+
+llvm_config.with_system_environment(["HOME", "INCLUDE", "LIB", "TMP", "TEMP"])
+llvm_config.use_default_substitutions()
+llvm_config.with_environment("PATH", config.llvm_tools_dir, append_path=True)
+
+tool_dirs = [os.path.join(config.tr_obj_root, "bin"), config.llvm_tools_dir]
+llvm_config.add_tool_substitutions(["tr-opt"], tool_dirs)
diff --git a/tile-reducer/test/lit.site.cfg.py.in b/tile-reducer/test/lit.site.cfg.py.in
new file mode 100644
index 0000000000000..f843f6754ed17
--- /dev/null
+++ b/tile-reducer/test/lit.site.cfg.py.in
@@ -0,0 +1,11 @@
+ at LIT_SITE_CFG_IN_HEADER@
+
+config.llvm_tools_dir = lit_config.substitute("@LLVM_TOOLS_DIR@")
+config.llvm_lib_dir = lit_config.substitute("@LLVM_LIBRARY_DIR@")
+config.llvm_shlib_ext = "@SHLIBEXT@"
+config.tr_obj_root = "@TR_BINARY_DIR@"
+
+import lit.llvm
+lit.llvm.initialize(lit_config, config)
+
+lit_config.load_config(config, "@TR_SOURCE_DIR@/test/lit.cfg.py")
diff --git a/tile-reducer/test/smoke.mlir b/tile-reducer/test/smoke.mlir
new file mode 100644
index 0000000000000..f19e539e98d0c
--- /dev/null
+++ b/tile-reducer/test/smoke.mlir
@@ -0,0 +1,16 @@
+// RUN: tr-opt --show-dialects %s | FileCheck %s --check-prefix=DIALECT
+// RUN: tr-opt %s | FileCheck %s
+
+// Milestone 1: the driver registers `tr` (plus func/arith from the canonical
+// source) and can parse a module. Types and ops are Milestone 2 / 3.
+
+// DIALECT: Available Dialects: arith,builtin,func,tr
+
+module {
+  // CHECK-LABEL: func.func @smoke
+  func.func @smoke() {
+    %c128 = arith.constant 128 : index
+    // CHECK: arith.constant 128 : index
+    return
+  }
+}
diff --git a/tile-reducer/tr-opt/CMakeLists.txt b/tile-reducer/tr-opt/CMakeLists.txt
new file mode 100644
index 0000000000000..9965df4d64eff
--- /dev/null
+++ b/tile-reducer/tr-opt/CMakeLists.txt
@@ -0,0 +1,12 @@
+set(LIBS
+    MLIRArithDialect
+    MLIRFuncDialect
+    MLIROptLib
+    MLIRTileReducer
+  )
+
+add_llvm_executable(tr-opt tr-opt.cpp)
+llvm_update_compile_flags(tr-opt)
+target_link_libraries(tr-opt PRIVATE ${LIBS})
+
+mlir_check_all_link_libraries(tr-opt)
diff --git a/tile-reducer/tr-opt/tr-opt.cpp b/tile-reducer/tr-opt/tr-opt.cpp
new file mode 100644
index 0000000000000..ee07cf1c1d695
--- /dev/null
+++ b/tile-reducer/tr-opt/tr-opt.cpp
@@ -0,0 +1,22 @@
+//===- tr-opt.cpp - TileReducer optimizer driver ----------------*- C++ -*-===//
+//
+// mlir-opt-like driver that registers the TileReducer dialect plus the
+// dialects that appear in the canonical source (func, arith).
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/IR/MLIRContext.h"
+#include "mlir/Tools/mlir-opt/MlirOptMain.h"
+
+#include "TileReducer/TileReducerDialect.h"
+
+int main(int argc, char **argv) {
+  mlir::DialectRegistry registry;
+  registry.insert<mlir::tr::TileReducerDialect, mlir::arith::ArithDialect,
+                  mlir::func::FuncDialect>();
+
+  return mlir::asMainReturnCode(
+      mlir::MlirOptMain(argc, argv, "TileReducer optimizer driver\n", registry));
+}

>From d7f5e41fe8e4d9a32629e63e4dbb73e7eba266d9 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 19:09:10 -0700
Subject: [PATCH 02/29] [TileReducer] Milestone 2: !tr.tile and !tr.buffer
 types

Add logical tile (static shape, no storage) and buffer (static, `?`, or
named dynamic extents such as MxK) types with custom parse/print and
negative tests for parser vs verifier failures.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/types-roundtrip.mlir
    tile-reducer/test/types-invalid.mlir
  tr-opt tile-reducer/test/types-roundtrip.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 .../include/TileReducer/TileReducerDialect.td |   4 +
 .../include/TileReducer/TileReducerOps.td     |   1 +
 .../include/TileReducer/TileReducerTypes.h    |  12 +
 .../include/TileReducer/TileReducerTypes.td   |  82 +++++++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |   2 +
 .../lib/TileReducer/TileReducerDialect.cpp    |   2 +
 .../lib/TileReducer/TileReducerTypes.cpp      | 231 ++++++++++++++++++
 tile-reducer/test/types-invalid.mlir          |  48 ++++
 tile-reducer/test/types-roundtrip.mlir        |  22 ++
 9 files changed, 404 insertions(+)
 create mode 100644 tile-reducer/include/TileReducer/TileReducerTypes.h
 create mode 100644 tile-reducer/include/TileReducer/TileReducerTypes.td
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerTypes.cpp
 create mode 100644 tile-reducer/test/types-invalid.mlir
 create mode 100644 tile-reducer/test/types-roundtrip.mlir

diff --git a/tile-reducer/include/TileReducer/TileReducerDialect.td b/tile-reducer/include/TileReducer/TileReducerDialect.td
index a001b209808aa..b8cad95dc2b86 100644
--- a/tile-reducer/include/TileReducer/TileReducerDialect.td
+++ b/tile-reducer/include/TileReducer/TileReducerDialect.td
@@ -23,6 +23,10 @@ def TileReducer_Dialect : Dialect {
     `!tr.buffer` is addressable external storage and later lowers to MemRef.
   }];
   let cppNamespace = "::mlir::tr";
+  let useDefaultTypePrinterParser = 1;
+  let extraClassDeclaration = [{
+    void registerTypes();
+  }];
 }
 
 class TileReducer_Op<string mnemonic, list<Trait> traits = []> :
diff --git a/tile-reducer/include/TileReducer/TileReducerOps.td b/tile-reducer/include/TileReducer/TileReducerOps.td
index a1bd9d5408cc9..17eac068f74e9 100644
--- a/tile-reducer/include/TileReducer/TileReducerOps.td
+++ b/tile-reducer/include/TileReducer/TileReducerOps.td
@@ -9,5 +9,6 @@
 #define TILE_REDUCER_OPS
 
 include "TileReducer/TileReducerDialect.td"
+include "TileReducer/TileReducerTypes.td"
 
 #endif // TILE_REDUCER_OPS
diff --git a/tile-reducer/include/TileReducer/TileReducerTypes.h b/tile-reducer/include/TileReducer/TileReducerTypes.h
new file mode 100644
index 0000000000000..979d4085b1d24
--- /dev/null
+++ b/tile-reducer/include/TileReducer/TileReducerTypes.h
@@ -0,0 +1,12 @@
+//===- TileReducerTypes.h - TileReducer types -------------------*- C++ -*-===//
+
+#ifndef TILE_REDUCER_TILEREDUCERTYPES_H
+#define TILE_REDUCER_TILEREDUCERTYPES_H
+
+#include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/Types.h"
+
+#define GET_TYPEDEF_CLASSES
+#include "TileReducer/TileReducerOpsTypes.h.inc"
+
+#endif // TILE_REDUCER_TILEREDUCERTYPES_H
diff --git a/tile-reducer/include/TileReducer/TileReducerTypes.td b/tile-reducer/include/TileReducer/TileReducerTypes.td
new file mode 100644
index 0000000000000..e7fc02e1812f6
--- /dev/null
+++ b/tile-reducer/include/TileReducer/TileReducerTypes.td
@@ -0,0 +1,82 @@
+//===- TileReducerTypes.td - TileReducer types -------------*- tablegen -*-===//
+//
+// Milestone 2: logical tile and addressable buffer types.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef TILE_REDUCER_TYPES
+#define TILE_REDUCER_TYPES
+
+include "mlir/IR/AttrTypeBase.td"
+include "TileReducer/TileReducerDialect.td"
+
+class TileReducer_Type<string name, string typeMnemonic, list<Trait> traits = []>
+    : TypeDef<TileReducer_Dialect, name, traits> {
+  let mnemonic = typeMnemonic;
+}
+
+def TileReducer_TileType : TileReducer_Type<"Tile", "tile"> {
+  let summary = "Logical static-shape SSA tile. No physical storage.";
+  let description = [{
+    `!tr.tile<128x128xf32>` is a logical collection of values. It does not
+    imply a memref allocation, thread ownership, or a hardware load.
+
+    All dimensions must be static and positive. Dynamic or named extents are
+    rejected: those belong on `!tr.buffer`.
+  }];
+  let parameters = (ins
+    ArrayRefParameter<"int64_t">:$shape,
+    "Type":$elementType
+  );
+  let builders = [
+    TypeBuilderWithInferredContext<(ins
+      "ArrayRef<int64_t>":$shape,
+      "Type":$elementType
+    ), [{
+      return $_get(elementType.getContext(), shape, elementType);
+    }]>
+  ];
+  let hasCustomAssemblyFormat = 1;
+  let genVerifyDecl = 1;
+  let extraClassDeclaration = [{
+    int64_t getRank() const { return static_cast<int64_t>(getShape().size()); }
+    int64_t getDimSize(int64_t dim) const { return getShape()[dim]; }
+    bool hasStaticShape() const { return true; }
+  }];
+}
+
+def TileReducer_BufferType : TileReducer_Type<"Buffer", "buffer"> {
+  let summary = "Addressable external storage. May have dynamic dimensions.";
+  let description = [{
+    `!tr.buffer<MxKxf32>` is a logical buffer that later lowers to MemRef.
+    Extents may be a static integer, `?`, or a name (`M`, `K`) that prints
+    back as that name and is stored as a dynamic dimension.
+
+    Named extents are a pretty-print of dynamism, not a new shape lattice.
+  }];
+  let parameters = (ins
+    ArrayRefParameter<"int64_t">:$shape,
+    "Type":$elementType,
+    ArrayRefParameter<"std::string">:$dimNames
+  );
+  let builders = [
+    TypeBuilderWithInferredContext<(ins
+      "ArrayRef<int64_t>":$shape,
+      "Type":$elementType,
+      CArg<"ArrayRef<std::string>", "{}">:$dimNames
+    ), [{
+      return $_get(elementType.getContext(), shape, elementType, dimNames);
+    }]>
+  ];
+  let hasCustomAssemblyFormat = 1;
+  let genVerifyDecl = 1;
+  let extraClassDeclaration = [{
+    int64_t getRank() const { return static_cast<int64_t>(getShape().size()); }
+    int64_t getDimSize(int64_t dim) const { return getShape()[dim]; }
+    bool isDynamicDim(int64_t dim) const {
+      return ::mlir::ShapedType::isDynamic(getShape()[dim]);
+    }
+  }];
+}
+
+#endif // TILE_REDUCER_TYPES
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index f234fb78f7f00..3e0adc073f64f 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -1,6 +1,7 @@
 add_mlir_dialect_library(MLIRTileReducer
         TileReducerDialect.cpp
         TileReducerOps.cpp
+        TileReducerTypes.cpp
 
         ADDITIONAL_HEADER_DIRS
         ${PROJECT_SOURCE_DIR}/include/TileReducer
@@ -11,4 +12,5 @@ add_mlir_dialect_library(MLIRTileReducer
         LINK_LIBS PUBLIC
         MLIRIR
         MLIRSupport
+        MLIRAsmParser
         )
diff --git a/tile-reducer/lib/TileReducer/TileReducerDialect.cpp b/tile-reducer/lib/TileReducer/TileReducerDialect.cpp
index 52364e575fc81..036d50176aa02 100644
--- a/tile-reducer/lib/TileReducer/TileReducerDialect.cpp
+++ b/tile-reducer/lib/TileReducer/TileReducerDialect.cpp
@@ -2,6 +2,7 @@
 
 #include "TileReducer/TileReducerDialect.h"
 #include "TileReducer/TileReducerOps.h"
+#include "TileReducer/TileReducerTypes.h"
 
 using namespace mlir;
 using namespace mlir::tr;
@@ -13,4 +14,5 @@ void TileReducerDialect::initialize() {
 #define GET_OP_LIST
 #include "TileReducer/TileReducerOps.cpp.inc"
       >();
+  registerTypes();
 }
diff --git a/tile-reducer/lib/TileReducer/TileReducerTypes.cpp b/tile-reducer/lib/TileReducer/TileReducerTypes.cpp
new file mode 100644
index 0000000000000..5daed9b6e67f5
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerTypes.cpp
@@ -0,0 +1,231 @@
+//===- TileReducerTypes.cpp - TileReducer types -----------------*- C++ -*-===//
+
+#include "TileReducer/TileReducerTypes.h"
+
+#include "TileReducer/TileReducerDialect.h"
+#include "mlir/AsmParser/AsmParser.h"
+#include "mlir/IR/Builders.h"
+#include "mlir/IR/DialectImplementation.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/ADT/TypeSwitch.h"
+
+using namespace mlir;
+using namespace mlir::tr;
+
+#define GET_TYPEDEF_CLASSES
+#include "TileReducer/TileReducerOpsTypes.cpp.inc"
+
+void TileReducerDialect::registerTypes() {
+  addTypes<
+#define GET_TYPEDEF_LIST
+#include "TileReducer/TileReducerOpsTypes.cpp.inc"
+      >();
+}
+
+//===----------------------------------------------------------------------===//
+// Shared shape printer / parser
+//
+//   dim ::= integer | `?` | identifier
+//   type ::= `<` (dim `x`)* element-type `>`
+//
+// A named dim (`M`) is a dynamic extent that pretty-prints as that name.
+// `parseXInDimensionList` handles the `xf32` juxtaposition.
+//===----------------------------------------------------------------------===//
+
+static void printShape(AsmPrinter &p, ArrayRef<int64_t> shape, Type elem,
+                       ArrayRef<std::string> names = {}) {
+  p << "<";
+  for (int64_t i = 0, e = static_cast<int64_t>(shape.size()); i < e; ++i) {
+    if (i < static_cast<int64_t>(names.size()) && !names[i].empty())
+      p << names[i];
+    else if (ShapedType::isDynamic(shape[i]))
+      p << "?";
+    else
+      p << shape[i];
+    p << "x";
+  }
+  p.printType(elem);
+  p << ">";
+}
+
+/// `MxKxf32` lexes as one identifier. Split on `x`; the last piece is the
+/// element type and the rest are named (dynamic) dimensions.
+static ParseResult splitJuxtaposed(StringRef ident, AsmParser &parser,
+                                   SmallVectorImpl<int64_t> &shape,
+                                   SmallVectorImpl<std::string> *names,
+                                   Type &elem, bool allowDynamic) {
+  SmallVector<StringRef> parts;
+  ident.split(parts, 'x', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
+  if (parts.size() < 2)
+    return parser.emitError(parser.getNameLoc(),
+                            "expected <dims x element-type>, got '")
+           << ident << "'";
+
+  StringRef typeStr = parts.pop_back_val();
+  elem = parseType(typeStr, parser.getContext());
+  if (!elem)
+    return parser.emitError(parser.getNameLoc(),
+                            "failed to parse element type '")
+           << typeStr << "'";
+
+  for (StringRef part : parts) {
+    int64_t value = 0;
+    if (!part.getAsInteger(10, value)) {
+      if (value < 0)
+        return parser.emitError(parser.getNameLoc(),
+                                "dimension must be non-negative");
+      shape.push_back(value);
+      if (names)
+        names->emplace_back();
+      continue;
+    }
+    if (part == "?") {
+      if (!allowDynamic)
+        return parser.emitError(parser.getNameLoc(),
+                                "tile dimensions must be static");
+      shape.push_back(ShapedType::kDynamic);
+      if (names)
+        names->emplace_back();
+      continue;
+    }
+    if (!allowDynamic)
+      return parser.emitError(parser.getNameLoc(),
+                              "tile dimensions must be static, got '")
+             << part << "'";
+    if (!llvm::all_of(part, [](char c) { return llvm::isAlpha(c); }))
+      return parser.emitError(parser.getNameLoc(),
+                              "invalid dimension name '")
+             << part << "'";
+    shape.push_back(ShapedType::kDynamic);
+    if (names)
+      names->push_back(part.str());
+  }
+  return success();
+}
+
+static ParseResult parseShape(AsmParser &parser, SmallVectorImpl<int64_t> &shape,
+                              Type &elem, SmallVectorImpl<std::string> *names,
+                              bool allowDynamic) {
+  if (parser.parseLess())
+    return failure();
+
+  while (true) {
+    Type maybeType;
+    OptionalParseResult typeRes = parser.parseOptionalType(maybeType);
+    if (typeRes.has_value() && succeeded(*typeRes)) {
+      elem = maybeType;
+      break;
+    }
+
+    int64_t value = 0;
+    OptionalParseResult intRes = parser.parseOptionalInteger(value);
+    if (intRes.has_value()) {
+      if (failed(*intRes))
+        return failure();
+      if (value < 0)
+        return parser.emitError(parser.getNameLoc(),
+                                "dimension must be non-negative");
+      shape.push_back(value);
+      if (names)
+        names->emplace_back();
+      if (failed(parser.parseXInDimensionList()))
+        return failure();
+      continue;
+    }
+
+    if (succeeded(parser.parseOptionalQuestion())) {
+      if (!allowDynamic)
+        return parser.emitError(parser.getNameLoc(),
+                                "tile dimensions must be static");
+      shape.push_back(ShapedType::kDynamic);
+      if (names)
+        names->emplace_back();
+      if (failed(parser.parseXInDimensionList()))
+        return failure();
+      continue;
+    }
+
+    StringRef ident;
+    if (succeeded(parser.parseOptionalKeyword(&ident)))
+      return splitJuxtaposed(ident, parser, shape, names, elem, allowDynamic);
+
+    return parser.emitError(parser.getNameLoc(), "expected dimension or type");
+  }
+  return parser.parseGreater();
+}
+
+static LogicalResult verifyElement(function_ref<InFlightDiagnostic()> emitError,
+                                   Type elem) {
+  if (isa<FloatType, IntegerType>(elem))
+    return success();
+  return emitError() << "element type must be an integer or float, got "
+                     << elem;
+}
+
+//===----------------------------------------------------------------------===//
+// TileType
+//===----------------------------------------------------------------------===//
+
+LogicalResult TileType::verify(function_ref<InFlightDiagnostic()> emitError,
+                               ArrayRef<int64_t> shape, Type elementType) {
+  if (shape.empty())
+    return emitError() << "tile must have rank >= 1";
+  for (int64_t d : shape) {
+    if (ShapedType::isDynamic(d))
+      return emitError() << "tile dimensions must be static";
+    if (d <= 0)
+      return emitError() << "tile dimensions must be positive, got " << d;
+  }
+  return verifyElement(emitError, elementType);
+}
+
+Type TileType::parse(AsmParser &parser) {
+  SmallVector<int64_t> shape;
+  Type elem;
+  if (failed(parseShape(parser, shape, elem, /*names=*/nullptr,
+                        /*allowDynamic=*/false)))
+    return {};
+  return getChecked([&] { return parser.emitError(parser.getNameLoc()); },
+                    parser.getContext(), shape, elem);
+}
+
+void TileType::print(AsmPrinter &printer) const {
+  printShape(printer, getShape(), getElementType());
+}
+
+//===----------------------------------------------------------------------===//
+// BufferType
+//===----------------------------------------------------------------------===//
+
+LogicalResult BufferType::verify(function_ref<InFlightDiagnostic()> emitError,
+                                 ArrayRef<int64_t> shape, Type elementType,
+                                 ArrayRef<std::string> dimNames) {
+  if (shape.empty())
+    return emitError() << "buffer must have rank >= 1";
+  if (!dimNames.empty() && dimNames.size() != shape.size())
+    return emitError() << "expected " << shape.size()
+                       << " dimension names, got " << dimNames.size();
+  for (auto [i, d] : llvm::enumerate(shape)) {
+    if (!ShapedType::isDynamic(d) && d < 0)
+      return emitError() << "static dimension must be non-negative";
+    if (!dimNames.empty() && !dimNames[i].empty() && !ShapedType::isDynamic(d))
+      return emitError() << "named dimension '" << dimNames[i]
+                         << "' must be dynamic";
+  }
+  return verifyElement(emitError, elementType);
+}
+
+Type BufferType::parse(AsmParser &parser) {
+  SmallVector<int64_t> shape;
+  SmallVector<std::string> names;
+  Type elem;
+  if (failed(parseShape(parser, shape, elem, &names, /*allowDynamic=*/true)))
+    return {};
+  return getChecked([&] { return parser.emitError(parser.getNameLoc()); },
+                    parser.getContext(), shape, elem, names);
+}
+
+void BufferType::print(AsmPrinter &printer) const {
+  printShape(printer, getShape(), getElementType(), getDimNames());
+}
diff --git a/tile-reducer/test/types-invalid.mlir b/tile-reducer/test/types-invalid.mlir
new file mode 100644
index 0000000000000..fff83b1488e1a
--- /dev/null
+++ b/tile-reducer/test/types-invalid.mlir
@@ -0,0 +1,48 @@
+// RUN: tr-opt %s -split-input-file -verify-diagnostics
+
+// Parser: tiles cannot be dynamic.
+func.func @dynamic_tile(%t: !tr.tile<?xf32>) {
+  // expected-error at -1 {{tile dimensions must be static}}
+  return
+}
+
+// -----
+
+// Parser: named extents are dynamic, so they are illegal on tiles.
+func.func @named_tile(%t: !tr.tile<Mxf32>) {
+  // expected-error at -1 {{tile dimensions must be static}}
+  return
+}
+
+// -----
+
+// Verifier: rank-0 tile.
+func.func @scalar_tile(%t: !tr.tile<f32>) {
+  // expected-error at -1 {{tile must have rank >= 1}}
+  return
+}
+
+// -----
+
+// Verifier: zero extent. Spaces keep `0 x f32` from lexing as the hex
+// integer `0xf32` (the same special case builtin tensor types have).
+func.func @zero_tile(%t: !tr.tile<0 x f32>) {
+  // expected-error at -1 {{tile dimensions must be positive}}
+  return
+}
+
+// -----
+
+// Verifier: element type.
+func.func @bad_elem(%t: !tr.tile<128xindex>) {
+  // expected-error at -1 {{element type must be an integer or float}}
+  return
+}
+
+// -----
+
+// Verifier: rank-0 buffer.
+func.func @scalar_buffer(%b: !tr.buffer<f32>) {
+  // expected-error at -1 {{buffer must have rank >= 1}}
+  return
+}
diff --git a/tile-reducer/test/types-roundtrip.mlir b/tile-reducer/test/types-roundtrip.mlir
new file mode 100644
index 0000000000000..c9f8c7f15bbf9
--- /dev/null
+++ b/tile-reducer/test/types-roundtrip.mlir
@@ -0,0 +1,22 @@
+// RUN: tr-opt %s | tr-opt | FileCheck %s
+
+// Milestone 2: tiles are static; buffers may be static, `?`, or named.
+
+// CHECK-LABEL: func.func @tiles
+func.func @tiles(%t1: !tr.tile<128xf32>, %t2: !tr.tile<128x128xf32>,
+                 %t3: !tr.tile<64x32xi32>) {
+  // CHECK: !tr.tile<128xf32>
+  // CHECK: !tr.tile<128x128xf32>
+  // CHECK: !tr.tile<64x32xi32>
+  return
+}
+
+// CHECK-LABEL: func.func @buffers
+func.func @buffers(%a: !tr.buffer<MxKxf32>, %b: !tr.buffer<Mxf32>,
+                   %c: !tr.buffer<?x?xf32>, %d: !tr.buffer<128x256xf16>) {
+  // CHECK: !tr.buffer<MxKxf32>
+  // CHECK: !tr.buffer<Mxf32>
+  // CHECK: !tr.buffer<?x?xf32>
+  // CHECK: !tr.buffer<128x256xf16>
+  return
+}

>From d79d8d451e882708b569b529656b59f272d9bd03 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 19:16:16 -0700
Subject: [PATCH 03/29] [TileReducer] Milestone 3: operations and verifiers

Add tr.program_id, tr.dim, tr.constant, tr.load, tr.store, tr.add,
tr.reduce_sum, tr.for, and tr.yield. tr.for accepts integer literals
for lower bound and step so the canonical row-sum program parses.
Round-trip and invalid tests distinguish parser vs verifier failures.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/ops-roundtrip.mlir
    tile-reducer/test/ops-invalid.mlir
  tr-opt tile-reducer/test/ops-roundtrip.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/examples/row_sum.mlir            |   6 +-
 .../include/TileReducer/TileReducerOps.h      |   6 +
 .../include/TileReducer/TileReducerOps.td     | 161 +++++++-
 .../include/TileReducer/TileReducerTypes.td   |   4 +-
 tile-reducer/lib/TileReducer/CMakeLists.txt   |   3 +
 .../lib/TileReducer/TileReducerOps.cpp        | 355 ++++++++++++++++++
 .../lib/TileReducer/TileReducerTypes.cpp      |  89 ++---
 tile-reducer/test/ops-invalid.mlir            |  56 +++
 tile-reducer/test/ops-roundtrip.mlir          |  40 ++
 9 files changed, 653 insertions(+), 67 deletions(-)
 create mode 100644 tile-reducer/test/ops-invalid.mlir
 create mode 100644 tile-reducer/test/ops-roundtrip.mlir

diff --git a/tile-reducer/examples/row_sum.mlir b/tile-reducer/examples/row_sum.mlir
index 438499f0db52f..123d5ab4d906e 100644
--- a/tile-reducer/examples/row_sum.mlir
+++ b/tile-reducer/examples/row_sum.mlir
@@ -5,7 +5,7 @@
 func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
   %row_blk     = tr.program_id 0 : index
   %c128        = arith.constant 128 : index
-  %k           = tr.dim %in, 1 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
   %num_k_tiles = arith.divui %k, %c128 : index
 
   %zero = tr.constant 0.0 : !tr.tile<128xf32>
@@ -13,7 +13,7 @@ func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
   %result = tr.for %kt = 0 to %num_k_tiles step 1
       iter_args(%acc = %zero) -> !tr.tile<128xf32> {
     %t       = tr.load %in[%row_blk, %kt]
-        : !tr.tile<128x128xf32>
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
 
     %partial = tr.reduce_sum %t, axis = 1
         : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
@@ -24,6 +24,6 @@ func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
     tr.yield %acc2 : !tr.tile<128xf32>
   }
 
-  tr.store %out[%row_blk], %result : !tr.tile<128xf32>
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
   return
 }
diff --git a/tile-reducer/include/TileReducer/TileReducerOps.h b/tile-reducer/include/TileReducer/TileReducerOps.h
index d2307b1a81fab..880db75cb84e0 100644
--- a/tile-reducer/include/TileReducer/TileReducerOps.h
+++ b/tile-reducer/include/TileReducer/TileReducerOps.h
@@ -3,9 +3,15 @@
 #ifndef TILE_REDUCER_TILEREDUCEROPS_H
 #define TILE_REDUCER_TILEREDUCEROPS_H
 
+#include "TileReducer/TileReducerTypes.h"
+#include "mlir/IR/BuiltinAttributeInterfaces.h"
 #include "mlir/IR/BuiltinTypes.h"
 #include "mlir/IR/Dialect.h"
 #include "mlir/IR/OpDefinition.h"
+#include "mlir/IR/SymbolTable.h"
+#include "mlir/Interfaces/ControlFlowInterfaces.h"
+#include "mlir/Interfaces/InferTypeOpInterface.h"
+#include "mlir/Interfaces/SideEffectInterfaces.h"
 
 #define GET_OP_CLASSES
 #include "TileReducer/TileReducerOps.h.inc"
diff --git a/tile-reducer/include/TileReducer/TileReducerOps.td b/tile-reducer/include/TileReducer/TileReducerOps.td
index 17eac068f74e9..089f1c9c496f8 100644
--- a/tile-reducer/include/TileReducer/TileReducerOps.td
+++ b/tile-reducer/include/TileReducer/TileReducerOps.td
@@ -1,14 +1,165 @@
 //===- TileReducerOps.td - TileReducer operations ----------*- tablegen -*-===//
-//
-// Milestone 1: empty op list so TableGen can generate the dialect class.
-// Operations are added in Milestone 3.
-//
-//===----------------------------------------------------------------------===//
 
 #ifndef TILE_REDUCER_OPS
 #define TILE_REDUCER_OPS
 
 include "TileReducer/TileReducerDialect.td"
 include "TileReducer/TileReducerTypes.td"
+include "mlir/IR/BuiltinAttributeInterfaces.td"
+include "mlir/IR/CommonTypeConstraints.td"
+include "mlir/Interfaces/ControlFlowInterfaces.td"
+include "mlir/Interfaces/InferTypeOpInterface.td"
+include "mlir/Interfaces/SideEffectInterfaces.td"
+
+//===----------------------------------------------------------------------===//
+// tr.program_id
+//===----------------------------------------------------------------------===//
+
+def TileReducer_ProgramIdOp : TileReducer_Op<"program_id", [Pure]> {
+  let summary = "Logical program-instance coordinate. Not threadIdx.";
+  let description = [{
+    `%id = tr.program_id 0 : index` names a logical TileReducer program
+    instance. Later GPU lowering decides whether that is a block, a warp,
+    or several blocks.
+  }];
+  let arguments = (ins I64Attr:$axis);
+  let results = (outs Index:$result);
+  let assemblyFormat = "$axis attr-dict `:` type($result)";
+  let hasVerifier = 1;
+}
+
+//===----------------------------------------------------------------------===//
+// tr.dim
+//===----------------------------------------------------------------------===//
+
+def TileReducer_DimOp : TileReducer_Op<"dim", [Pure]> {
+  let summary = "Query one extent of a buffer.";
+  let arguments = (ins AnyType:$buffer, I64Attr:$axis);
+  let results = (outs Index:$result);
+  let assemblyFormat = "$buffer `,` $axis attr-dict `:` type($buffer) `,` type($result)";
+  let hasVerifier = 1;
+}
+
+//===----------------------------------------------------------------------===//
+// tr.constant
+//===----------------------------------------------------------------------===//
+
+def TileReducer_ConstantOp : TileReducer_Op<"constant", [Pure, ConstantLike]> {
+  let summary = "Splat a scalar attribute onto a logical tile.";
+  let arguments = (ins TypedAttrInterface:$value);
+  let results = (outs AnyType:$result);
+  // Custom format so `0.0 : !tr.tile<128xf32>` does not parse `0.0` as a
+  // typed attribute of tile type (MLIR would otherwise eat the colon).
+  let hasCustomAssemblyFormat = 1;
+  let hasVerifier = 1;
+}
+
+//===----------------------------------------------------------------------===//
+// tr.load / tr.store
+//===----------------------------------------------------------------------===//
+
+def TileReducer_LoadOp : TileReducer_Op<"load", [Pure]> {
+  let summary = "Logical tile load. Not a hardware instruction.";
+  let description = [{
+    `%t = tr.load %in[%row, %kt] : !tr.tile<128x128xf32>`
+
+    Indices are *tile* coordinates into the buffer, one per buffer
+    dimension. The compiler may realize this as coalesced loads, a fused
+    load/reduce, or nothing materialised at all.
+  }];
+  let arguments = (ins AnyType:$buffer, Variadic<Index>:$indices);
+  let results = (outs AnyType:$result);
+  let assemblyFormat = [{
+    $buffer `[` $indices `]` attr-dict `:` type($buffer) `,` type($result)
+  }];
+  let hasVerifier = 1;
+}
+
+def TileReducer_StoreOp : TileReducer_Op<"store", []> {
+  let summary = "Logical tile store into a buffer.";
+  let arguments = (ins
+    AnyType:$buffer,
+    Variadic<Index>:$indices,
+    AnyType:$value
+  );
+  let assemblyFormat = [{
+    $buffer `[` $indices `]` `,` $value attr-dict `:` type($buffer) `,` type($value)
+  }];
+  let hasVerifier = 1;
+}
+
+//===----------------------------------------------------------------------===//
+// tr.add
+//===----------------------------------------------------------------------===//
+
+def TileReducer_AddOp : TileReducer_Op<"add",
+    [Pure, SameOperandsAndResultType]> {
+  let summary = "Elementwise tile addition.";
+  let arguments = (ins AnyType:$lhs, AnyType:$rhs);
+  let results = (outs AnyType:$result);
+  let assemblyFormat = "$lhs `,` $rhs attr-dict `:` type($result)";
+  let hasVerifier = 1;
+}
+
+//===----------------------------------------------------------------------===//
+// tr.reduce_sum
+//===----------------------------------------------------------------------===//
+
+def TileReducer_ReduceSumOp : TileReducer_Op<"reduce_sum", [Pure]> {
+  let summary = "Sum-reduce a tile along one axis.";
+  let arguments = (ins AnyType:$input, I64Attr:$axis);
+  let results = (outs AnyType:$result);
+  let assemblyFormat = [{
+    $input `,` `axis` `=` $axis attr-dict `:` type($input) `->` type($result)
+  }];
+  let hasVerifier = 1;
+}
+
+//===----------------------------------------------------------------------===//
+// tr.yield / tr.for
+//===----------------------------------------------------------------------===//
+
+def TileReducer_YieldOp : TileReducer_Op<"yield",
+    [HasParent<"ForOp">, Pure, ReturnLike, Terminator]> {
+  let summary = "Yield values from a tr.for body.";
+  let arguments = (ins Variadic<AnyType>:$operands);
+  let assemblyFormat = "attr-dict ($operands^ `:` type($operands))?";
+  let builders = [
+    OpBuilder<(ins), [{
+      build($_builder, $_state, ValueRange());
+    }]>
+  ];
+}
+
+def TileReducer_ForOp : TileReducer_Op<"for",
+    [SingleBlockImplicitTerminator<"YieldOp">, RecursiveMemoryEffects,
+     AttrSizedOperandSegments]> {
+  let summary = "Tile-level counted loop with iter_args.";
+  let description = [{
+    Source-level loop. Bounds may be SSA values or integer literals
+    (`0`, `1`) so the canonical program parses unchanged. Lowered to
+    `scf.for` in a later milestone.
+  }];
+  let arguments = (ins
+    Optional<Index>:$lowerBound,
+    Index:$upperBound,
+    Optional<Index>:$step,
+    OptionalAttr<I64Attr>:$staticLowerBound,
+    OptionalAttr<I64Attr>:$staticStep,
+    Variadic<AnyType>:$initArgs
+  );
+  let results = (outs Variadic<AnyType>:$results);
+  let regions = (region SizedRegion<1>:$region);
+  let hasCustomAssemblyFormat = 1;
+  let hasVerifier = 1;
+  let extraClassDeclaration = [{
+    BlockArgument getInductionVar() { return getRegion().getArgument(0); }
+    Block::BlockArgListType getRegionIterArgs() {
+      return getRegion().getArguments().drop_front();
+    }
+    std::optional<int64_t> getConstantLowerBound();
+    std::optional<int64_t> getConstantStep();
+  }];
+}
 
 #endif // TILE_REDUCER_OPS
diff --git a/tile-reducer/include/TileReducer/TileReducerTypes.td b/tile-reducer/include/TileReducer/TileReducerTypes.td
index e7fc02e1812f6..49b1524d781b1 100644
--- a/tile-reducer/include/TileReducer/TileReducerTypes.td
+++ b/tile-reducer/include/TileReducer/TileReducerTypes.td
@@ -36,7 +36,7 @@ def TileReducer_TileType : TileReducer_Type<"Tile", "tile"> {
       return $_get(elementType.getContext(), shape, elementType);
     }]>
   ];
-  let hasCustomAssemblyFormat = 1;
+  let assemblyFormat = "`<` custom<TRShape>($shape, $elementType) `>`";
   let genVerifyDecl = 1;
   let extraClassDeclaration = [{
     int64_t getRank() const { return static_cast<int64_t>(getShape().size()); }
@@ -68,7 +68,7 @@ def TileReducer_BufferType : TileReducer_Type<"Buffer", "buffer"> {
       return $_get(elementType.getContext(), shape, elementType, dimNames);
     }]>
   ];
-  let hasCustomAssemblyFormat = 1;
+  let assemblyFormat = "`<` custom<TRBufferShape>($shape, $elementType, $dimNames) `>`";
   let genVerifyDecl = 1;
   let extraClassDeclaration = [{
     int64_t getRank() const { return static_cast<int64_t>(getShape().size()); }
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index 3e0adc073f64f..1c47cf1c404a3 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -13,4 +13,7 @@ add_mlir_dialect_library(MLIRTileReducer
         MLIRIR
         MLIRSupport
         MLIRAsmParser
+        MLIRControlFlowInterfaces
+        MLIRInferTypeOpInterface
+        MLIRSideEffectInterfaces
         )
diff --git a/tile-reducer/lib/TileReducer/TileReducerOps.cpp b/tile-reducer/lib/TileReducer/TileReducerOps.cpp
index ed2296d3a3783..178f9ff893f44 100644
--- a/tile-reducer/lib/TileReducer/TileReducerOps.cpp
+++ b/tile-reducer/lib/TileReducer/TileReducerOps.cpp
@@ -2,9 +2,364 @@
 
 #include "TileReducer/TileReducerOps.h"
 #include "TileReducer/TileReducerDialect.h"
+#include "TileReducer/TileReducerTypes.h"
+
+#include "mlir/IR/Builders.h"
+#include "mlir/IR/OpImplementation.h"
+#include "mlir/IR/PatternMatch.h"
 
 using namespace mlir;
 using namespace mlir::tr;
 
 #define GET_OP_CLASSES
 #include "TileReducer/TileReducerOps.cpp.inc"
+
+//===----------------------------------------------------------------------===//
+// Helpers
+//===----------------------------------------------------------------------===//
+
+static LogicalResult verifyAxis(Operation *op, int64_t axis, int64_t rank,
+                                StringRef what) {
+  if (axis < 0 || axis >= rank)
+    return op->emitOpError("axis ") << axis << " is out of range for " << what
+                                    << " of rank " << rank;
+  return success();
+}
+
+static LogicalResult verifyTileCoords(Operation *op, BufferType buffer,
+                                      ValueRange indices, TileType tile,
+                                      StringRef kind) {
+  if (static_cast<int64_t>(indices.size()) != buffer.getRank())
+    return op->emitOpError("expected ")
+           << buffer.getRank() << " tile " << kind << " indices, got "
+           << indices.size();
+  if (tile.getRank() != buffer.getRank())
+    return op->emitOpError("tile rank ")
+           << tile.getRank() << " does not match buffer rank "
+           << buffer.getRank();
+  if (tile.getElementType() != buffer.getElementType())
+    return op->emitOpError("tile element type ")
+           << tile.getElementType() << " does not match buffer element type "
+           << buffer.getElementType();
+  return success();
+}
+
+//===----------------------------------------------------------------------===//
+// ProgramIdOp
+//===----------------------------------------------------------------------===//
+
+LogicalResult ProgramIdOp::verify() {
+  if (getAxis() < 0)
+    return emitOpError("axis must be non-negative");
+  return success();
+}
+
+//===----------------------------------------------------------------------===//
+// DimOp
+//===----------------------------------------------------------------------===//
+
+LogicalResult DimOp::verify() {
+  auto buffer = dyn_cast<BufferType>(getBuffer().getType());
+  if (!buffer)
+    return emitOpError("expected a !tr.buffer, got ") << getBuffer().getType();
+  return verifyAxis(*this, getAxis(), buffer.getRank(), "buffer");
+}
+
+//===----------------------------------------------------------------------===//
+// ConstantOp
+//===----------------------------------------------------------------------===//
+
+ParseResult ConstantOp::parse(OpAsmParser &parser, OperationState &result) {
+  Builder &b = parser.getBuilder();
+  Attribute value;
+  double d = 0.0;
+  int64_t i = 0;
+  // Parse a bare literal so `0.0 : !tr.tile<...>` does not treat the tile
+  // type as the attribute's type.
+  if (succeeded(parser.parseFloat(d)))
+    value = b.getF64FloatAttr(d);
+  else if (OptionalParseResult ir = parser.parseOptionalInteger(i);
+           ir.has_value() && succeeded(*ir))
+    value = b.getI64IntegerAttr(i);
+  else
+    return parser.emitError(parser.getNameLoc(),
+                            "expected a scalar integer or float literal");
+
+  Type resultType;
+  if (parser.parseColonType(resultType))
+    return failure();
+  result.addAttribute("value", value);
+  result.addTypes(resultType);
+  return parser.parseOptionalAttrDict(result.attributes);
+}
+
+void ConstantOp::print(OpAsmPrinter &p) {
+  p << " ";
+  p.printAttributeWithoutType(getValue());
+  p << " : " << getType();
+}
+
+LogicalResult ConstantOp::verify() {
+  auto tile = dyn_cast<TileType>(getType());
+  if (!tile)
+    return emitOpError("result must be a !tr.tile, got ") << getType();
+  Type elem = tile.getElementType();
+  Attribute value = getValue();
+  if (auto typed = dyn_cast<TypedAttr>(value)) {
+    Type attrTy = typed.getType();
+    if (attrTy == elem)
+      return success();
+    // Allow a wider float attribute (0.0 : f64) to splat onto an f32 tile.
+    if (isa<FloatType>(attrTy) && isa<FloatType>(elem))
+      return success();
+    if (isa<IntegerType>(attrTy) && isa<IntegerType>(elem))
+      return success();
+    return emitOpError("constant attribute type ")
+           << attrTy << " is not compatible with tile element type " << elem;
+  }
+  return emitOpError("constant value must be a typed attribute");
+}
+
+//===----------------------------------------------------------------------===//
+// LoadOp / StoreOp
+//===----------------------------------------------------------------------===//
+
+LogicalResult LoadOp::verify() {
+  auto buffer = dyn_cast<BufferType>(getBuffer().getType());
+  auto tile = dyn_cast<TileType>(getType());
+  if (!buffer || !tile)
+    return emitOpError("load requires !tr.buffer and !tr.tile");
+  return verifyTileCoords(*this, buffer, getIndices(), tile, "load");
+}
+
+LogicalResult StoreOp::verify() {
+  auto buffer = dyn_cast<BufferType>(getBuffer().getType());
+  auto tile = dyn_cast<TileType>(getValue().getType());
+  if (!buffer || !tile)
+    return emitOpError("store requires !tr.buffer and !tr.tile");
+  return verifyTileCoords(*this, buffer, getIndices(), tile, "store");
+}
+
+//===----------------------------------------------------------------------===//
+// AddOp
+//===----------------------------------------------------------------------===//
+
+LogicalResult AddOp::verify() {
+  auto lhs = dyn_cast<TileType>(getLhs().getType());
+  auto rhs = dyn_cast<TileType>(getRhs().getType());
+  if (!lhs || !rhs)
+    return emitOpError("add requires !tr.tile operands");
+  if (lhs.getShape() != rhs.getShape() ||
+      lhs.getElementType() != rhs.getElementType())
+    return emitOpError("operand tiles must have the same shape and element "
+                       "type");
+  return success();
+}
+
+//===----------------------------------------------------------------------===//
+// ReduceSumOp
+//===----------------------------------------------------------------------===//
+
+LogicalResult ReduceSumOp::verify() {
+  auto inTy = dyn_cast<TileType>(getInput().getType());
+  auto outTy = dyn_cast<TileType>(getType());
+  if (!inTy || !outTy)
+    return emitOpError("reduce_sum requires !tr.tile input and result");
+  int64_t axis = getAxis();
+
+  if (failed(verifyAxis(*this, axis, inTy.getRank(), "input tile")))
+    return failure();
+  if (outTy.getRank() != inTy.getRank() - 1)
+    return emitOpError("result rank must be ")
+           << (inTy.getRank() - 1) << ", got " << outTy.getRank();
+  if (outTy.getElementType() != inTy.getElementType())
+    return emitOpError("element type mismatch");
+
+  SmallVector<int64_t> expected;
+  for (int64_t i = 0, e = inTy.getRank(); i < e; ++i)
+    if (i != axis)
+      expected.push_back(inTy.getDimSize(i));
+  if (outTy.getShape() != ArrayRef<int64_t>(expected))
+    return emitOpError("result extent must match the non-reduced dimensions, "
+                       "expected ")
+           << TileType::get(expected, outTy.getElementType()) << " got "
+           << outTy;
+  return success();
+}
+
+//===----------------------------------------------------------------------===//
+// ForOp
+//===----------------------------------------------------------------------===//
+
+std::optional<int64_t> ForOp::getConstantLowerBound() {
+  if (std::optional<uint64_t> attr = getStaticLowerBound())
+    return static_cast<int64_t>(*attr);
+  return std::nullopt;
+}
+
+std::optional<int64_t> ForOp::getConstantStep() {
+  if (std::optional<uint64_t> attr = getStaticStep())
+    return static_cast<int64_t>(*attr);
+  return std::nullopt;
+}
+
+LogicalResult ForOp::verify() {
+  if (getLowerBound() && getStaticLowerBound())
+    return emitOpError("lower bound cannot be both an SSA value and a literal");
+  if (!getLowerBound() && !getStaticLowerBound())
+    return emitOpError("missing lower bound");
+  if (getStep() && getStaticStep())
+    return emitOpError("step cannot be both an SSA value and a literal");
+  if (!getStep() && !getStaticStep())
+    return emitOpError("missing step");
+  if (auto step = getConstantStep(); step && *step <= 0)
+    return emitOpError("step must be positive");
+
+  if (getInitArgs().size() != getResults().size())
+    return emitOpError("init_args count must match result count");
+
+  Region &region = getRegion();
+  if (region.empty())
+    return emitOpError("expected a body region");
+  if (region.getNumArguments() != 1 + getInitArgs().size())
+    return emitOpError("body must have the induction variable plus one "
+                       "argument per iter_arg");
+  if (!region.getArgument(0).getType().isIndex())
+    return emitOpError("induction variable must be index");
+
+  for (auto [arg, init, res] :
+       llvm::zip(getRegionIterArgs(), getInitArgs(), getResults())) {
+    if (arg.getType() != init.getType() || arg.getType() != res.getType())
+      return emitOpError("iter_arg / init / result types must match");
+  }
+  return success();
+}
+
+static ParseResult parseBound(OpAsmParser &parser, OperationState &result,
+                              StringRef operandName, StringRef attrName,
+                              Type indexTy, bool optionalOperand) {
+  int64_t lit = 0;
+  OptionalParseResult intRes = parser.parseOptionalInteger(lit);
+  if (intRes.has_value()) {
+    if (failed(*intRes))
+      return failure();
+    result.addAttribute(attrName, parser.getBuilder().getI64IntegerAttr(lit));
+    return success();
+  }
+  OpAsmParser::UnresolvedOperand operand;
+  if (parser.parseOperand(operand) ||
+      parser.resolveOperand(operand, indexTy, result.operands))
+    return failure();
+  return success();
+}
+
+ParseResult ForOp::parse(OpAsmParser &parser, OperationState &result) {
+  auto indexTy = parser.getBuilder().getIndexType();
+
+  OpAsmParser::Argument ivArg;
+  if (parser.parseArgument(ivArg) || parser.parseEqual())
+    return failure();
+  ivArg.type = indexTy;
+
+  // lowerBound
+  if (failed(parseBound(parser, result, "lowerBound", "staticLowerBound",
+                        indexTy, /*optionalOperand=*/true)))
+    return failure();
+  if (parser.parseKeyword("to"))
+    return failure();
+
+  // upperBound is always an operand (canonical: %num_k_tiles) or a literal.
+  int64_t ubLit = 0;
+  OptionalParseResult ubInt = parser.parseOptionalInteger(ubLit);
+  if (ubInt.has_value()) {
+    if (failed(*ubInt))
+      return failure();
+    // Materialise a static upper bound as an attribute on the op; the
+    // verifier/lowering treat a missing SSA upperBound as illegal, so create
+    // a constant-like attribute and require an operand. For literals we store
+    // them in `staticUpperBound` — but the ODS only has an SSA upperBound.
+    // Accept only SSA for the upper bound to keep the operand list stable,
+    // except we already parsed an integer. Re-parse as: reject literals for
+    // ub except by creating an unresolved... Use a dedicated attribute.
+    result.addAttribute("staticUpperBound",
+                        parser.getBuilder().getIndexAttr(ubLit));
+    return parser.emitError(parser.getNameLoc(),
+                            "integer upper bounds are not supported; use an "
+                            "SSA value (arith.constant)");
+  }
+  OpAsmParser::UnresolvedOperand ub;
+  if (parser.parseOperand(ub) ||
+      parser.resolveOperand(ub, indexTy, result.operands))
+    return failure();
+
+  if (parser.parseKeyword("step") ||
+      failed(parseBound(parser, result, "step", "staticStep", indexTy, true)))
+    return failure();
+
+  // Optional iter_args(%a = %init) -> type
+  SmallVector<OpAsmParser::Argument> regionArgs;
+  regionArgs.push_back(ivArg);
+  SmallVector<OpAsmParser::UnresolvedOperand> initOperands;
+  SmallVector<Type> resultTypes;
+
+  if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
+    if (parser.parseAssignmentList(regionArgs, initOperands) ||
+        parser.parseArrowTypeList(resultTypes))
+      return failure();
+    if (initOperands.size() + 1 != regionArgs.size())
+      return parser.emitError(parser.getNameLoc(),
+                              "iter_args assignment count mismatch");
+    for (auto [arg, ty] : llvm::zip(llvm::drop_begin(regionArgs), resultTypes))
+      arg.type = ty;
+    if (parser.resolveOperands(initOperands, resultTypes, parser.getNameLoc(),
+                               result.operands))
+      return failure();
+    result.addTypes(resultTypes);
+  }
+
+  int32_t hasLb = result.attributes.get("staticLowerBound") ? 0 : 1;
+  int32_t hasStep = result.attributes.get("staticStep") ? 0 : 1;
+  // Operands so far: [lb?] ub [step?]  -- but step SSA is parsed before
+  // init_args, so count init as the remainder after lb+ub+step.
+  int32_t nInit = static_cast<int32_t>(initOperands.size());
+  // Reconstruct: if lb was SSA it was the first operand. ub is always
+  // present. step SSA is next if not static.
+  result.addAttribute("operandSegmentSizes",
+                      parser.getBuilder().getDenseI32ArrayAttr(
+                          {hasLb, 1, hasStep, nInit}));
+
+  Region *body = result.addRegion();
+  if (parser.parseRegion(*body, regionArgs))
+    return failure();
+  ForOp::ensureTerminator(*body, parser.getBuilder(), result.location);
+  return parser.parseOptionalAttrDict(result.attributes);
+}
+
+void ForOp::print(OpAsmPrinter &p) {
+  p << " " << getInductionVar() << " = ";
+  if (auto lb = getConstantLowerBound())
+    p << *lb;
+  else
+    p << getLowerBound();
+  p << " to " << getUpperBound() << " step ";
+  if (auto st = getConstantStep())
+    p << *st;
+  else
+    p << getStep();
+
+  if (!getInitArgs().empty()) {
+    p << " iter_args(";
+    llvm::interleaveComma(llvm::zip(getRegionIterArgs(), getInitArgs()), p,
+                          [&](auto pair) {
+                            p << std::get<0>(pair) << " = "
+                              << std::get<1>(pair);
+                          });
+    p << ") -> (" << getResultTypes() << ")";
+  }
+  p << " ";
+  p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
+                /*printBlockTerminators=*/true);
+  p.printOptionalAttrDict((*this)->getAttrs(),
+                          {"staticLowerBound", "staticStep",
+                           "operandSegmentSizes"});
+}
diff --git a/tile-reducer/lib/TileReducer/TileReducerTypes.cpp b/tile-reducer/lib/TileReducer/TileReducerTypes.cpp
index 5daed9b6e67f5..edabdd20b75ba 100644
--- a/tile-reducer/lib/TileReducer/TileReducerTypes.cpp
+++ b/tile-reducer/lib/TileReducer/TileReducerTypes.cpp
@@ -13,21 +13,11 @@
 using namespace mlir;
 using namespace mlir::tr;
 
-#define GET_TYPEDEF_CLASSES
-#include "TileReducer/TileReducerOpsTypes.cpp.inc"
-
-void TileReducerDialect::registerTypes() {
-  addTypes<
-#define GET_TYPEDEF_LIST
-#include "TileReducer/TileReducerOpsTypes.cpp.inc"
-      >();
-}
-
 //===----------------------------------------------------------------------===//
 // Shared shape printer / parser
 //
 //   dim ::= integer | `?` | identifier
-//   type ::= `<` (dim `x`)* element-type `>`
+//   type ::= (dim `x`)* element-type
 //
 // A named dim (`M`) is a dynamic extent that pretty-prints as that name.
 // `parseXInDimensionList` handles the `xf32` juxtaposition.
@@ -35,7 +25,6 @@ void TileReducerDialect::registerTypes() {
 
 static void printShape(AsmPrinter &p, ArrayRef<int64_t> shape, Type elem,
                        ArrayRef<std::string> names = {}) {
-  p << "<";
   for (int64_t i = 0, e = static_cast<int64_t>(shape.size()); i < e; ++i) {
     if (i < static_cast<int64_t>(names.size()) && !names[i].empty())
       p << names[i];
@@ -46,11 +35,8 @@ static void printShape(AsmPrinter &p, ArrayRef<int64_t> shape, Type elem,
     p << "x";
   }
   p.printType(elem);
-  p << ">";
 }
 
-/// `MxKxf32` lexes as one identifier. Split on `x`; the last piece is the
-/// element type and the rest are named (dynamic) dimensions.
 static ParseResult splitJuxtaposed(StringRef ident, AsmParser &parser,
                                    SmallVectorImpl<int64_t> &shape,
                                    SmallVectorImpl<std::string> *names,
@@ -94,8 +80,7 @@ static ParseResult splitJuxtaposed(StringRef ident, AsmParser &parser,
                               "tile dimensions must be static, got '")
              << part << "'";
     if (!llvm::all_of(part, [](char c) { return llvm::isAlpha(c); }))
-      return parser.emitError(parser.getNameLoc(),
-                              "invalid dimension name '")
+      return parser.emitError(parser.getNameLoc(), "invalid dimension name '")
              << part << "'";
     shape.push_back(ShapedType::kDynamic);
     if (names)
@@ -107,9 +92,6 @@ static ParseResult splitJuxtaposed(StringRef ident, AsmParser &parser,
 static ParseResult parseShape(AsmParser &parser, SmallVectorImpl<int64_t> &shape,
                               Type &elem, SmallVectorImpl<std::string> *names,
                               bool allowDynamic) {
-  if (parser.parseLess())
-    return failure();
-
   while (true) {
     Type maybeType;
     OptionalParseResult typeRes = parser.parseOptionalType(maybeType);
@@ -152,7 +134,36 @@ static ParseResult parseShape(AsmParser &parser, SmallVectorImpl<int64_t> &shape
 
     return parser.emitError(parser.getNameLoc(), "expected dimension or type");
   }
-  return parser.parseGreater();
+  return success();
+}
+
+namespace mlir::tr {
+ParseResult parseTRShape(AsmParser &parser, SmallVector<int64_t> &shape,
+                         Type &elem) {
+  return parseShape(parser, shape, elem, /*names=*/nullptr,
+                    /*allowDynamic=*/false);
+}
+void printTRShape(AsmPrinter &printer, ArrayRef<int64_t> shape, Type elem) {
+  printShape(printer, shape, elem);
+}
+ParseResult parseTRBufferShape(AsmParser &parser, SmallVector<int64_t> &shape,
+                               Type &elem, SmallVector<std::string> &names) {
+  return parseShape(parser, shape, elem, &names, /*allowDynamic=*/true);
+}
+void printTRBufferShape(AsmPrinter &printer, ArrayRef<int64_t> shape, Type elem,
+                        ArrayRef<std::string> names) {
+  printShape(printer, shape, elem, names);
+}
+} // namespace mlir::tr
+
+#define GET_TYPEDEF_CLASSES
+#include "TileReducer/TileReducerOpsTypes.cpp.inc"
+
+void TileReducerDialect::registerTypes() {
+  addTypes<
+#define GET_TYPEDEF_LIST
+#include "TileReducer/TileReducerOpsTypes.cpp.inc"
+      >();
 }
 
 static LogicalResult verifyElement(function_ref<InFlightDiagnostic()> emitError,
@@ -163,10 +174,6 @@ static LogicalResult verifyElement(function_ref<InFlightDiagnostic()> emitError,
                      << elem;
 }
 
-//===----------------------------------------------------------------------===//
-// TileType
-//===----------------------------------------------------------------------===//
-
 LogicalResult TileType::verify(function_ref<InFlightDiagnostic()> emitError,
                                ArrayRef<int64_t> shape, Type elementType) {
   if (shape.empty())
@@ -180,24 +187,6 @@ LogicalResult TileType::verify(function_ref<InFlightDiagnostic()> emitError,
   return verifyElement(emitError, elementType);
 }
 
-Type TileType::parse(AsmParser &parser) {
-  SmallVector<int64_t> shape;
-  Type elem;
-  if (failed(parseShape(parser, shape, elem, /*names=*/nullptr,
-                        /*allowDynamic=*/false)))
-    return {};
-  return getChecked([&] { return parser.emitError(parser.getNameLoc()); },
-                    parser.getContext(), shape, elem);
-}
-
-void TileType::print(AsmPrinter &printer) const {
-  printShape(printer, getShape(), getElementType());
-}
-
-//===----------------------------------------------------------------------===//
-// BufferType
-//===----------------------------------------------------------------------===//
-
 LogicalResult BufferType::verify(function_ref<InFlightDiagnostic()> emitError,
                                  ArrayRef<int64_t> shape, Type elementType,
                                  ArrayRef<std::string> dimNames) {
@@ -215,17 +204,3 @@ LogicalResult BufferType::verify(function_ref<InFlightDiagnostic()> emitError,
   }
   return verifyElement(emitError, elementType);
 }
-
-Type BufferType::parse(AsmParser &parser) {
-  SmallVector<int64_t> shape;
-  SmallVector<std::string> names;
-  Type elem;
-  if (failed(parseShape(parser, shape, elem, &names, /*allowDynamic=*/true)))
-    return {};
-  return getChecked([&] { return parser.emitError(parser.getNameLoc()); },
-                    parser.getContext(), shape, elem, names);
-}
-
-void BufferType::print(AsmPrinter &printer) const {
-  printShape(printer, getShape(), getElementType(), getDimNames());
-}
diff --git a/tile-reducer/test/ops-invalid.mlir b/tile-reducer/test/ops-invalid.mlir
new file mode 100644
index 0000000000000..8903cb2caab13
--- /dev/null
+++ b/tile-reducer/test/ops-invalid.mlir
@@ -0,0 +1,56 @@
+// RUN: tr-opt %s -split-input-file -verify-diagnostics
+
+// Verifier: reduce axis out of range.
+func.func @bad_axis(%t: !tr.tile<128x128xf32>) -> !tr.tile<128xf32> {
+  // expected-error at +1 {{axis 2 is out of range}}
+  %r = tr.reduce_sum %t, axis = 2 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}
+
+// -----
+
+// Verifier: reduce result extent.
+func.func @bad_reduce_shape(%t: !tr.tile<128x64xf32>) -> !tr.tile<32xf32> {
+  // expected-error at +1 {{result extent must match the non-reduced dimensions}}
+  %r = tr.reduce_sum %t, axis = 1 : !tr.tile<128x64xf32> -> !tr.tile<32xf32>
+  return %r : !tr.tile<32xf32>
+}
+
+// -----
+
+// Parser: SameOperandsAndResultType unifies the printed type onto both
+// operands, so a shape mismatch is diagnosed as a prior-use type error.
+func.func @bad_add(%a: !tr.tile<128xf32>,
+                   %b: !tr.tile<64xf32>) -> !tr.tile<128xf32> {
+  // expected-note at -1 {{prior use here}}
+  // expected-error at +1 {{expects different type than prior uses}}
+  %r = tr.add %a, %b : !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}
+
+// -----
+
+// Verifier: load index rank.
+func.func @bad_load(%in: !tr.buffer<MxKxf32>, %i: index) -> !tr.tile<128x128xf32> {
+  // expected-error at +1 {{expected 2 tile load indices, got 1}}
+  %t = tr.load %in[%i] : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+  return %t : !tr.tile<128x128xf32>
+}
+
+// -----
+
+// Verifier: dim axis.
+func.func @bad_dim(%in: !tr.buffer<Mxf32>) -> index {
+  // expected-error at +1 {{axis 3 is out of range}}
+  %d = tr.dim %in, 3 : !tr.buffer<Mxf32>, index
+  return %d : index
+}
+
+// -----
+
+// Parser: reduce assembly requires `axis =`.
+func.func @parse_reduce(%t: !tr.tile<128x128xf32>) -> !tr.tile<128xf32> {
+  // expected-error at +1 {{expected 'axis'}}
+  %r = tr.reduce_sum %t, 1 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}
diff --git a/tile-reducer/test/ops-roundtrip.mlir b/tile-reducer/test/ops-roundtrip.mlir
new file mode 100644
index 0000000000000..697a9890abcd0
--- /dev/null
+++ b/tile-reducer/test/ops-roundtrip.mlir
@@ -0,0 +1,40 @@
+// RUN: tr-opt %s | tr-opt | FileCheck %s
+
+// Canonical row-sum source. Milestone 3: every op parses and prints.
+
+// CHECK-LABEL: func.func @row_sum
+// CHECK: %[[PID:.*]] = tr.program_id 0 : index
+// CHECK: %[[K:.*]] = tr.dim %{{.*}}, 1 : !tr.buffer<MxKxf32>, index
+// CHECK: %[[ZERO:.*]] = tr.constant 0.000000e+00 : !tr.tile<128xf32>
+// CHECK: %[[RES:.*]] = tr.for %{{.*}} = 0 to %{{.*}} step 1
+// CHECK-SAME: iter_args(%{{.*}} = %[[ZERO]]) -> (!tr.tile<128xf32>)
+// CHECK: %[[T:.*]] = tr.load %{{.*}}[%[[PID]], %{{.*}}] : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+// CHECK: %[[P:.*]] = tr.reduce_sum %[[T]], axis = 1 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+// CHECK: %[[A:.*]] = tr.add %{{.*}}, %[[P]] : !tr.tile<128xf32>
+// CHECK: tr.yield %[[A]] : !tr.tile<128xf32>
+// CHECK: tr.store %{{.*}}[%[[PID]]], %[[RES]] : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+
+    %acc2    = tr.add %acc, %partial
+        : !tr.tile<128xf32>
+
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}

>From 30286b29391fd7a862317532a4380aa5d4d38ec7 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 19:17:15 -0700
Subject: [PATCH 04/29] [TileReducer] Milestone 4: RewritePatternSet /
 PatternRewriter

Add --tr-fold-add-zero (tr.add(x, 0) -> x) and --tr-recognize-load-reduce
(marks a single-use load+reduce_sum with tr.load_reduce for later fusion).
Both use OpRewritePattern and applyPatternsGreedily.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/fold-add-zero.mlir
    tile-reducer/test/recognize-load-reduce.mlir
  tr-opt --tr-fold-add-zero --tr-recognize-load-reduce tile-reducer/test/fold-add-zero.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 .../include/TileReducer/CMakeLists.txt        |   4 +
 .../include/TileReducer/TileReducerOps.td     |   2 +-
 .../include/TileReducer/TileReducerPasses.h   |  29 +++++
 .../include/TileReducer/TileReducerPasses.td  |  32 +++++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |   6 +
 .../lib/TileReducer/TileReducerPasses.cpp     | 123 ++++++++++++++++++
 tile-reducer/test/fold-add-zero.mlir          |  25 ++++
 tile-reducer/test/recognize-load-reduce.mlir  |  19 +++
 tile-reducer/tr-opt/tr-opt.cpp                |   3 +
 9 files changed, 242 insertions(+), 1 deletion(-)
 create mode 100644 tile-reducer/include/TileReducer/TileReducerPasses.h
 create mode 100644 tile-reducer/include/TileReducer/TileReducerPasses.td
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerPasses.cpp
 create mode 100644 tile-reducer/test/fold-add-zero.mlir
 create mode 100644 tile-reducer/test/recognize-load-reduce.mlir

diff --git a/tile-reducer/include/TileReducer/CMakeLists.txt b/tile-reducer/include/TileReducer/CMakeLists.txt
index bf4d0a09b3dc9..b53ce90c415cb 100644
--- a/tile-reducer/include/TileReducer/CMakeLists.txt
+++ b/tile-reducer/include/TileReducer/CMakeLists.txt
@@ -1,2 +1,6 @@
 add_mlir_dialect(TileReducerOps tr)
 add_mlir_doc(TileReducerDialect TileReducerDialect TileReducer/ -gen-dialect-doc)
+
+set(LLVM_TARGET_DEFINITIONS TileReducerPasses.td)
+mlir_tablegen(TileReducerPasses.h.inc --gen-pass-decls)
+add_public_tablegen_target(MLIRTileReducerPassesIncGen)
diff --git a/tile-reducer/include/TileReducer/TileReducerOps.td b/tile-reducer/include/TileReducer/TileReducerOps.td
index 089f1c9c496f8..e7281754c9984 100644
--- a/tile-reducer/include/TileReducer/TileReducerOps.td
+++ b/tile-reducer/include/TileReducer/TileReducerOps.td
@@ -44,7 +44,7 @@ def TileReducer_DimOp : TileReducer_Op<"dim", [Pure]> {
 // tr.constant
 //===----------------------------------------------------------------------===//
 
-def TileReducer_ConstantOp : TileReducer_Op<"constant", [Pure, ConstantLike]> {
+def TileReducer_ConstantOp : TileReducer_Op<"constant", [Pure]> {
   let summary = "Splat a scalar attribute onto a logical tile.";
   let arguments = (ins TypedAttrInterface:$value);
   let results = (outs AnyType:$result);
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.h b/tile-reducer/include/TileReducer/TileReducerPasses.h
new file mode 100644
index 0000000000000..1f834bd485a08
--- /dev/null
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.h
@@ -0,0 +1,29 @@
+//===- TileReducerPasses.h - TileReducer passes -----------------*- C++ -*-===//
+
+#ifndef TILE_REDUCER_TILEREDUCERPASSES_H
+#define TILE_REDUCER_TILEREDUCERPASSES_H
+
+#include "mlir/Pass/Pass.h"
+#include <memory>
+
+namespace mlir {
+class ModuleOp;
+class RewritePatternSet;
+
+namespace func {
+class FuncOp;
+} // namespace func
+
+namespace tr {
+#define GEN_PASS_DECL
+#include "TileReducer/TileReducerPasses.h.inc"
+
+#define GEN_PASS_REGISTRATION
+#include "TileReducer/TileReducerPasses.h.inc"
+
+void populateFoldAddZeroPatterns(RewritePatternSet &patterns);
+void populateRecognizeLoadReducePatterns(RewritePatternSet &patterns);
+} // namespace tr
+} // namespace mlir
+
+#endif // TILE_REDUCER_TILEREDUCERPASSES_H
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
new file mode 100644
index 0000000000000..027ca6b10f536
--- /dev/null
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -0,0 +1,32 @@
+//===- TileReducerPasses.td - TileReducer passes -----------*- tablegen -*-===//
+
+#ifndef TILE_REDUCER_PASSES
+#define TILE_REDUCER_PASSES
+
+include "mlir/Pass/PassBase.td"
+
+def FoldTRAddZero : Pass<"tr-fold-add-zero", "::mlir::func::FuncOp"> {
+  let summary = "Fold tr.add(x, zero) to x.";
+  let dependentDialects = ["::mlir::tr::TileReducerDialect"];
+}
+
+def RecognizeLoadReduce : Pass<"tr-recognize-load-reduce", "::mlir::func::FuncOp"> {
+  let summary = "Mark tr.load -> tr.reduce_sum pairs for later fusion.";
+  let description = [{
+    When a reduce_sum's input is a single-use load of the same element type,
+    set `tr.load_reduce` on the reduce. No IR shape change; this is a
+    scheduling hint consumed by later fusion/GPU lowering.
+  }];
+  let dependentDialects = ["::mlir::tr::TileReducerDialect"];
+}
+
+def ConvertTRForBoundsToArith : Pass<"tr-for-bounds-to-arith", "::mlir::func::FuncOp"> {
+  let summary = "Materialize tr.for integer bounds as arith.constant index values.";
+  let dependentDialects = [
+    "::mlir::tr::TileReducerDialect",
+    "::mlir::arith::ArithDialect"
+  ];
+}
+
+
+#endif // TILE_REDUCER_PASSES
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index 1c47cf1c404a3..9e3ae9dbf3365 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -2,18 +2,24 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerDialect.cpp
         TileReducerOps.cpp
         TileReducerTypes.cpp
+        TileReducerPasses.cpp
 
         ADDITIONAL_HEADER_DIRS
         ${PROJECT_SOURCE_DIR}/include/TileReducer
 
         DEPENDS
         MLIRTileReducerOpsIncGen
+        MLIRTileReducerPassesIncGen
 
         LINK_LIBS PUBLIC
         MLIRIR
         MLIRSupport
         MLIRAsmParser
+        MLIRArithDialect
         MLIRControlFlowInterfaces
+        MLIRFuncDialect
         MLIRInferTypeOpInterface
+        MLIRPass
         MLIRSideEffectInterfaces
+        MLIRTransformUtils
         )
diff --git a/tile-reducer/lib/TileReducer/TileReducerPasses.cpp b/tile-reducer/lib/TileReducer/TileReducerPasses.cpp
new file mode 100644
index 0000000000000..8393e675e3657
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerPasses.cpp
@@ -0,0 +1,123 @@
+//===- TileReducerPasses.cpp - TileReducer rewrite passes -------*- C++ -*-===//
+
+#include "TileReducer/TileReducerPasses.h"
+
+#include "TileReducer/TileReducerDialect.h"
+#include "TileReducer/TileReducerOps.h"
+#include "TileReducer/TileReducerTypes.h"
+
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/IR/PatternMatch.h"
+#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
+
+namespace mlir::tr {
+#define GEN_PASS_DEF_FOLDTRADDZERO
+#define GEN_PASS_DEF_RECOGNIZELOADREDUCE
+#define GEN_PASS_DEF_CONVERTTRFORBOUNDSTOARITH
+#include "TileReducer/TileReducerPasses.h.inc"
+
+namespace {
+
+bool isZeroSplat(Value v) {
+  auto cst = v.getDefiningOp<ConstantOp>();
+  if (!cst)
+    return false;
+  Attribute attr = cst.getValue();
+  if (auto f = dyn_cast<FloatAttr>(attr))
+    return f.getValue().isZero();
+  if (auto i = dyn_cast<IntegerAttr>(attr))
+    return i.getValue().isZero();
+  return false;
+}
+
+struct FoldAddZeroPattern : public OpRewritePattern<AddOp> {
+  using OpRewritePattern::OpRewritePattern;
+  LogicalResult matchAndRewrite(AddOp op,
+                                PatternRewriter &rewriter) const override {
+    if (isZeroSplat(op.getRhs())) {
+      rewriter.replaceOp(op, op.getLhs());
+      return success();
+    }
+    if (isZeroSplat(op.getLhs())) {
+      rewriter.replaceOp(op, op.getRhs());
+      return success();
+    }
+    return failure();
+  }
+};
+
+struct RecognizeLoadReducePattern : public OpRewritePattern<ReduceSumOp> {
+  using OpRewritePattern::OpRewritePattern;
+  LogicalResult matchAndRewrite(ReduceSumOp op,
+                                PatternRewriter &rewriter) const override {
+    if (op->hasAttr("tr.load_reduce"))
+      return failure();
+    auto load = op.getInput().getDefiningOp<LoadOp>();
+    if (!load)
+      return rewriter.notifyMatchFailure(op, "input is not a tr.load");
+    if (!load->hasOneUse())
+      return rewriter.notifyMatchFailure(op, "load has other users");
+    auto inTy = dyn_cast<TileType>(load.getType());
+    auto outTy = dyn_cast<TileType>(op.getType());
+    if (!inTy || !outTy || inTy.getElementType() != outTy.getElementType())
+      return rewriter.notifyMatchFailure(op, "element type mismatch");
+    rewriter.modifyOpInPlace(op, [&] {
+      op->setAttr("tr.load_reduce", rewriter.getUnitAttr());
+    });
+    return success();
+  }
+};
+
+struct FoldTRAddZero : impl::FoldTRAddZeroBase<FoldTRAddZero> {
+  void runOnOperation() override {
+    RewritePatternSet patterns(&getContext());
+    patterns.add<FoldAddZeroPattern>(&getContext());
+    if (failed(applyPatternsGreedily(getOperation(), std::move(patterns))))
+      signalPassFailure();
+  }
+};
+
+struct RecognizeLoadReduce : impl::RecognizeLoadReduceBase<RecognizeLoadReduce> {
+  void runOnOperation() override {
+    RewritePatternSet patterns(&getContext());
+    patterns.add<RecognizeLoadReducePattern>(&getContext());
+    if (failed(applyPatternsGreedily(getOperation(), std::move(patterns))))
+      signalPassFailure();
+  }
+};
+
+struct ConvertTRForBoundsToArith
+    : impl::ConvertTRForBoundsToArithBase<ConvertTRForBoundsToArith> {
+  void runOnOperation() override {
+    getOperation().walk([&](ForOp op) {
+      OpBuilder b(op);
+      Location loc = op.getLoc();
+      if (!op.getLowerBound()) {
+        if (auto lb = op.getConstantLowerBound()) {
+          Value v = arith::ConstantIndexOp::create(b, loc, *lb);
+          op.getLowerBoundMutable().assign(v);
+          op.removeStaticLowerBoundAttr();
+        }
+      }
+      if (!op.getStep()) {
+        if (auto st = op.getConstantStep()) {
+          Value v = arith::ConstantIndexOp::create(b, loc, *st);
+          op.getStepMutable().assign(v);
+          op.removeStaticStepAttr();
+        }
+      }
+    });
+  }
+};
+
+} // namespace
+
+void populateFoldAddZeroPatterns(RewritePatternSet &patterns) {
+  patterns.add<FoldAddZeroPattern>(patterns.getContext());
+}
+void populateRecognizeLoadReducePatterns(RewritePatternSet &patterns) {
+  patterns.add<RecognizeLoadReducePattern>(patterns.getContext());
+}
+
+} // namespace mlir::tr
diff --git a/tile-reducer/test/fold-add-zero.mlir b/tile-reducer/test/fold-add-zero.mlir
new file mode 100644
index 0000000000000..1ee18a989d676
--- /dev/null
+++ b/tile-reducer/test/fold-add-zero.mlir
@@ -0,0 +1,25 @@
+// RUN: tr-opt %s --tr-fold-add-zero | FileCheck %s
+
+// CHECK-LABEL: func.func @fold_rhs
+func.func @fold_rhs(%x: !tr.tile<128xf32>) -> !tr.tile<128xf32> {
+  %z = tr.constant 0.0 : !tr.tile<128xf32>
+  // CHECK-NOT: tr.add
+  // CHECK: return %[[X:.*]] : !tr.tile<128xf32>
+  %r = tr.add %x, %z : !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}
+
+// CHECK-LABEL: func.func @fold_lhs
+func.func @fold_lhs(%x: !tr.tile<128xf32>) -> !tr.tile<128xf32> {
+  %z = tr.constant 0.0 : !tr.tile<128xf32>
+  // CHECK-NOT: tr.add
+  %r = tr.add %z, %x : !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}
+
+// CHECK-LABEL: func.func @no_fold
+func.func @no_fold(%a: !tr.tile<128xf32>, %b: !tr.tile<128xf32>) -> !tr.tile<128xf32> {
+  // CHECK: tr.add
+  %r = tr.add %a, %b : !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}
diff --git a/tile-reducer/test/recognize-load-reduce.mlir b/tile-reducer/test/recognize-load-reduce.mlir
new file mode 100644
index 0000000000000..eda9b0d6ad63e
--- /dev/null
+++ b/tile-reducer/test/recognize-load-reduce.mlir
@@ -0,0 +1,19 @@
+// RUN: tr-opt %s --tr-recognize-load-reduce | FileCheck %s
+
+// CHECK-LABEL: func.func @row_partial
+func.func @row_partial(%in: !tr.buffer<MxKxf32>, %i: index, %j: index)
+    -> !tr.tile<128xf32> {
+  %t = tr.load %in[%i, %j] : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+  // CHECK: tr.reduce_sum {{.*}} {tr.load_reduce}
+  %p = tr.reduce_sum %t, axis = 1 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+  return %p : !tr.tile<128xf32>
+}
+
+// CHECK-LABEL: func.func @multi_use
+func.func @multi_use(%in: !tr.buffer<MxKxf32>, %i: index, %j: index)
+    -> (!tr.tile<128x128xf32>, !tr.tile<128xf32>) {
+  %t = tr.load %in[%i, %j] : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+  %p = tr.reduce_sum %t, axis = 1 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+  // CHECK-NOT: tr.load_reduce
+  return %t, %p : !tr.tile<128x128xf32>, !tr.tile<128xf32>
+}
diff --git a/tile-reducer/tr-opt/tr-opt.cpp b/tile-reducer/tr-opt/tr-opt.cpp
index ee07cf1c1d695..a1e2a79c07254 100644
--- a/tile-reducer/tr-opt/tr-opt.cpp
+++ b/tile-reducer/tr-opt/tr-opt.cpp
@@ -11,8 +11,11 @@
 #include "mlir/Tools/mlir-opt/MlirOptMain.h"
 
 #include "TileReducer/TileReducerDialect.h"
+#include "TileReducer/TileReducerPasses.h"
 
 int main(int argc, char **argv) {
+  mlir::tr::registerPasses();
+
   mlir::DialectRegistry registry;
   registry.insert<mlir::tr::TileReducerDialect, mlir::arith::ArithDialect,
                   mlir::func::FuncDialect>();

>From f863f1d2d9ff876f23222dc7a73d37259935179a Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 19:17:44 -0700
Subject: [PATCH 05/29] [TileReducer] Milestone 5: bounds, layout, and
 reduction analyses

Add non-mutating BoundsAnalysis, LayoutAnalysis, and ReductionAnalysis,
plus --tr-annotate-reduction-plan which writes tr.plan = row|column|full
without changing the computation.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/annotate-plan.mlir
  tr-opt --tr-annotate-reduction-plan tile-reducer/test/annotate-plan.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 .../include/TileReducer/TileReducerAnalyses.h | 59 +++++++++++++++++++
 .../include/TileReducer/TileReducerPasses.td  | 10 ++++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |  1 +
 .../lib/TileReducer/TileReducerAnalyses.cpp   | 44 ++++++++++++++
 .../lib/TileReducer/TileReducerPasses.cpp     | 31 ++++++++++
 tile-reducer/test/annotate-plan.mlir          | 15 +++++
 6 files changed, 160 insertions(+)
 create mode 100644 tile-reducer/include/TileReducer/TileReducerAnalyses.h
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerAnalyses.cpp
 create mode 100644 tile-reducer/test/annotate-plan.mlir

diff --git a/tile-reducer/include/TileReducer/TileReducerAnalyses.h b/tile-reducer/include/TileReducer/TileReducerAnalyses.h
new file mode 100644
index 0000000000000..84c4cb856ed59
--- /dev/null
+++ b/tile-reducer/include/TileReducer/TileReducerAnalyses.h
@@ -0,0 +1,59 @@
+//===- TileReducerAnalyses.h - non-mutating analyses ------------*- C++ -*-===//
+//
+// Milestone 5: bounds, layout, and reduction classification. Analyses do
+// not mutate IR. The planning pass reads them and writes attributes.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef TILE_REDUCER_TILEREDUCERANALYSES_H
+#define TILE_REDUCER_TILEREDUCERANALYSES_H
+
+#include "mlir/IR/Operation.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace mlir {
+namespace tr {
+
+enum class ReductionKind { Row, Column, Full, Unknown };
+
+struct ReductionInfo {
+  ReductionKind kind = ReductionKind::Unknown;
+  int64_t axis = -1;
+  bool loadReduceCandidate = false;
+};
+
+class BoundsAnalysis {
+public:
+  BoundsAnalysis(Operation *op);
+  /// Tile extent along `dim` of `v`'s type, or -1 if unknown.
+  int64_t getTileExtent(Value v, int64_t dim) const;
+  bool isKnownMultipleOf(int64_t value, int64_t factor) const {
+    return value > 0 && factor > 0 && (value % factor) == 0;
+  }
+};
+
+class LayoutAnalysis {
+public:
+  LayoutAnalysis(Operation *op);
+  /// Assumed source layout. TileReducer buffers are row-major until a
+  /// later layout attribute says otherwise.
+  StringRef getBufferLayout(Value buffer) const { return "row_major"; }
+};
+
+class ReductionAnalysis {
+public:
+  ReductionAnalysis(Operation *op);
+  const ReductionInfo *get(Operation *op) const;
+  const llvm::DenseMap<Operation *, ReductionInfo> &all() const {
+    return infos;
+  }
+
+private:
+  llvm::DenseMap<Operation *, ReductionInfo> infos;
+};
+
+} // namespace tr
+} // namespace mlir
+
+#endif // TILE_REDUCER_TILEREDUCERANALYSES_H
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
index 027ca6b10f536..e5417be353c3d 100644
--- a/tile-reducer/include/TileReducer/TileReducerPasses.td
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -20,6 +20,16 @@ def RecognizeLoadReduce : Pass<"tr-recognize-load-reduce", "::mlir::func::FuncOp
   let dependentDialects = ["::mlir::tr::TileReducerDialect"];
 }
 
+def AnnotateReductionPlan : Pass<"tr-annotate-reduction-plan", "::mlir::func::FuncOp"> {
+  let summary = "Consume analyses and annotate a reduction strategy candidate.";
+  let description = [{
+    Walks ReduceSumOps, reads Bounds/Layout/Reduction analyses, and sets
+    `tr.plan` to one of `row`, `column`, or `full`. Does not rewrite payload
+    computation.
+  }];
+  let dependentDialects = ["::mlir::tr::TileReducerDialect"];
+}
+
 def ConvertTRForBoundsToArith : Pass<"tr-for-bounds-to-arith", "::mlir::func::FuncOp"> {
   let summary = "Materialize tr.for integer bounds as arith.constant index values.";
   let dependentDialects = [
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index 9e3ae9dbf3365..0599874c147fd 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -2,6 +2,7 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerDialect.cpp
         TileReducerOps.cpp
         TileReducerTypes.cpp
+        TileReducerAnalyses.cpp
         TileReducerPasses.cpp
 
         ADDITIONAL_HEADER_DIRS
diff --git a/tile-reducer/lib/TileReducer/TileReducerAnalyses.cpp b/tile-reducer/lib/TileReducer/TileReducerAnalyses.cpp
new file mode 100644
index 0000000000000..eb43737b0b187
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerAnalyses.cpp
@@ -0,0 +1,44 @@
+//===- TileReducerAnalyses.cpp ----------------------------------*- C++ -*-===//
+
+#include "TileReducer/TileReducerAnalyses.h"
+#include "TileReducer/TileReducerOps.h"
+#include "TileReducer/TileReducerTypes.h"
+
+using namespace mlir;
+using namespace mlir::tr;
+
+BoundsAnalysis::BoundsAnalysis(Operation *op) { (void)op; }
+
+int64_t BoundsAnalysis::getTileExtent(Value v, int64_t dim) const {
+  auto tile = dyn_cast<TileType>(v.getType());
+  if (!tile || dim < 0 || dim >= tile.getRank())
+    return -1;
+  return tile.getDimSize(dim);
+}
+
+LayoutAnalysis::LayoutAnalysis(Operation *op) { (void)op; }
+
+ReductionAnalysis::ReductionAnalysis(Operation *op) {
+  op->walk([&](ReduceSumOp red) {
+    ReductionInfo info;
+    info.axis = red.getAxis();
+    auto inTy = dyn_cast<TileType>(red.getInput().getType());
+    if (inTy && inTy.getRank() == 2) {
+      if (info.axis == 1)
+        info.kind = ReductionKind::Row;
+      else if (info.axis == 0)
+        info.kind = ReductionKind::Column;
+    } else if (inTy && inTy.getRank() == 1) {
+      info.kind = ReductionKind::Full;
+    }
+    info.loadReduceCandidate = isa_and_nonnull<LoadOp>(
+                                   red.getInput().getDefiningOp()) &&
+                               red.getInput().hasOneUse();
+    infos[red] = info;
+  });
+}
+
+const ReductionInfo *ReductionAnalysis::get(Operation *op) const {
+  auto it = infos.find(op);
+  return it == infos.end() ? nullptr : &it->second;
+}
diff --git a/tile-reducer/lib/TileReducer/TileReducerPasses.cpp b/tile-reducer/lib/TileReducer/TileReducerPasses.cpp
index 8393e675e3657..8b739102da430 100644
--- a/tile-reducer/lib/TileReducer/TileReducerPasses.cpp
+++ b/tile-reducer/lib/TileReducer/TileReducerPasses.cpp
@@ -2,6 +2,7 @@
 
 #include "TileReducer/TileReducerPasses.h"
 
+#include "TileReducer/TileReducerAnalyses.h"
 #include "TileReducer/TileReducerDialect.h"
 #include "TileReducer/TileReducerOps.h"
 #include "TileReducer/TileReducerTypes.h"
@@ -14,6 +15,7 @@
 namespace mlir::tr {
 #define GEN_PASS_DEF_FOLDTRADDZERO
 #define GEN_PASS_DEF_RECOGNIZELOADREDUCE
+#define GEN_PASS_DEF_ANNOTATEREDUCTIONPLAN
 #define GEN_PASS_DEF_CONVERTTRFORBOUNDSTOARITH
 #include "TileReducer/TileReducerPasses.h.inc"
 
@@ -87,6 +89,35 @@ struct RecognizeLoadReduce : impl::RecognizeLoadReduceBase<RecognizeLoadReduce>
   }
 };
 
+struct AnnotateReductionPlan
+    : impl::AnnotateReductionPlanBase<AnnotateReductionPlan> {
+  void runOnOperation() override {
+    auto &reds = getAnalysis<ReductionAnalysis>();
+    (void)getAnalysis<BoundsAnalysis>();
+    (void)getAnalysis<LayoutAnalysis>();
+    getOperation().walk([&](ReduceSumOp op) {
+      const ReductionInfo *info = reds.get(op);
+      if (!info)
+        return;
+      StringRef plan = "unknown";
+      switch (info->kind) {
+      case ReductionKind::Row:
+        plan = "row";
+        break;
+      case ReductionKind::Column:
+        plan = "column";
+        break;
+      case ReductionKind::Full:
+        plan = "full";
+        break;
+      case ReductionKind::Unknown:
+        break;
+      }
+      op->setAttr("tr.plan", StringAttr::get(op.getContext(), plan));
+    });
+  }
+};
+
 struct ConvertTRForBoundsToArith
     : impl::ConvertTRForBoundsToArithBase<ConvertTRForBoundsToArith> {
   void runOnOperation() override {
diff --git a/tile-reducer/test/annotate-plan.mlir b/tile-reducer/test/annotate-plan.mlir
new file mode 100644
index 0000000000000..4ab964bc320c7
--- /dev/null
+++ b/tile-reducer/test/annotate-plan.mlir
@@ -0,0 +1,15 @@
+// RUN: tr-opt %s --tr-annotate-reduction-plan | FileCheck %s
+
+// CHECK-LABEL: func.func @row
+func.func @row(%t: !tr.tile<128x128xf32>) -> !tr.tile<128xf32> {
+  // CHECK: tr.reduce_sum {{.*}} {tr.plan = "row"}
+  %r = tr.reduce_sum %t, axis = 1 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}
+
+// CHECK-LABEL: func.func @col
+func.func @col(%t: !tr.tile<128x128xf32>) -> !tr.tile<128xf32> {
+  // CHECK: tr.reduce_sum {{.*}} {tr.plan = "column"}
+  %r = tr.reduce_sum %t, axis = 0 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}

>From 4c8232482deb1617c523ef01d6e330244b2881ac Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 19:18:00 -0700
Subject: [PATCH 06/29] [TileReducer] Milestone 6: materialize tr.for bounds
 with arith

--tr-for-bounds-to-arith rewrites integer lower-bound/step literals into
arith.constant index values. Tile add/constant stay tile-typed; their
arith.addf lowering lives in the Linalg region (Milestone 8).

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/for-bounds-to-arith.mlir
  tr-opt --tr-for-bounds-to-arith tile-reducer/test/for-bounds-to-arith.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/test/for-bounds-to-arith.mlir | 23 ++++++++++++++++++++++
 1 file changed, 23 insertions(+)
 create mode 100644 tile-reducer/test/for-bounds-to-arith.mlir

diff --git a/tile-reducer/test/for-bounds-to-arith.mlir b/tile-reducer/test/for-bounds-to-arith.mlir
new file mode 100644
index 0000000000000..b0050a411d284
--- /dev/null
+++ b/tile-reducer/test/for-bounds-to-arith.mlir
@@ -0,0 +1,23 @@
+// RUN: tr-opt %s --tr-for-bounds-to-arith | FileCheck %s
+
+// CHECK-LABEL: func.func @row_sum
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+
+  // CHECK: %[[C0:.*]] = arith.constant 0 : index
+  // CHECK: %[[C1:.*]] = arith.constant 1 : index
+  // CHECK: tr.for %{{.*}} = %[[C0]] to %{{.*}} step %[[C1]]
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t = tr.load %in[%row_blk, %kt] : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2 = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}

>From db70610777115c846edb9dd68cba33e54533feb7 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 19:19:25 -0700
Subject: [PATCH 07/29] [TileReducer] Milestone 7: ConversionTarget /
 TypeConverter

--convert-tr-buffers-to-memref uses ConversionTarget, TypeConverter, and
OpConversionPattern: !tr.buffer -> memref, func signatures rewrite, and
tr.dim -> memref.dim. !tr.tile is left in place. applyPartialConversion
keeps remaining TileReducer ops legal.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/convert-buffers.mlir
  tr-opt --convert-tr-buffers-to-memref tile-reducer/test/convert-buffers.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 .../include/TileReducer/TileReducerPasses.td  |  15 +++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |   3 +
 .../TileReducerBufferConversion.cpp           | 119 ++++++++++++++++++
 .../lib/TileReducer/TileReducerOps.cpp        |  44 ++++---
 tile-reducer/test/convert-buffers.mlir        |  26 ++++
 tile-reducer/test/smoke.mlir                  |   2 +-
 tile-reducer/tr-opt/CMakeLists.txt            |   1 +
 tile-reducer/tr-opt/tr-opt.cpp                |   3 +-
 8 files changed, 194 insertions(+), 19 deletions(-)
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerBufferConversion.cpp
 create mode 100644 tile-reducer/test/convert-buffers.mlir

diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
index e5417be353c3d..8fa3eeea08c07 100644
--- a/tile-reducer/include/TileReducer/TileReducerPasses.td
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -30,6 +30,21 @@ def AnnotateReductionPlan : Pass<"tr-annotate-reduction-plan", "::mlir::func::Fu
   let dependentDialects = ["::mlir::tr::TileReducerDialect"];
 }
 
+def ConvertTRBuffersToMemRef : Pass<"convert-tr-buffers-to-memref", "::mlir::ModuleOp"> {
+  let summary = "Dialect-convert !tr.buffer to memref. Leaves !tr.tile in place.";
+  let description = [{
+    Uses ConversionTarget, TypeConverter, and OpConversionPattern.
+    `!tr.buffer<MxKxf32>` becomes `memref<?x?xf32>`. Function signatures
+    are rewritten. `tr.dim` becomes `memref.dim`. Tile ops stay.
+  }];
+  let dependentDialects = [
+    "::mlir::tr::TileReducerDialect",
+    "::mlir::memref::MemRefDialect",
+    "::mlir::func::FuncDialect",
+    "::mlir::arith::ArithDialect"
+  ];
+}
+
 def ConvertTRForBoundsToArith : Pass<"tr-for-bounds-to-arith", "::mlir::func::FuncOp"> {
   let summary = "Materialize tr.for integer bounds as arith.constant index values.";
   let dependentDialects = [
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index 0599874c147fd..d1cd36896765c 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -3,6 +3,7 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerOps.cpp
         TileReducerTypes.cpp
         TileReducerAnalyses.cpp
+        TileReducerBufferConversion.cpp
         TileReducerPasses.cpp
 
         ADDITIONAL_HEADER_DIRS
@@ -19,6 +20,8 @@ add_mlir_dialect_library(MLIRTileReducer
         MLIRArithDialect
         MLIRControlFlowInterfaces
         MLIRFuncDialect
+        MLIRFuncTransforms
+        MLIRMemRefDialect
         MLIRInferTypeOpInterface
         MLIRPass
         MLIRSideEffectInterfaces
diff --git a/tile-reducer/lib/TileReducer/TileReducerBufferConversion.cpp b/tile-reducer/lib/TileReducer/TileReducerBufferConversion.cpp
new file mode 100644
index 0000000000000..f57a7f64332be
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerBufferConversion.cpp
@@ -0,0 +1,119 @@
+//===- TileReducerBufferConversion.cpp - Milestone 7 ------------*- C++ -*-===//
+//
+// ConversionTarget + TypeConverter + OpConversionPattern.
+// !tr.buffer -> memref. !tr.tile is unchanged.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/TileReducerPasses.h"
+
+#include "TileReducer/TileReducerDialect.h"
+#include "TileReducer/TileReducerOps.h"
+#include "TileReducer/TileReducerTypes.h"
+
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/Dialect/Func/Transforms/FuncConversions.h"
+#include "mlir/Dialect/MemRef/IR/MemRef.h"
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/Transforms/DialectConversion.h"
+
+namespace mlir::tr {
+#define GEN_PASS_DEF_CONVERTTRBUFFERSTOMEMREF
+#include "TileReducer/TileReducerPasses.h.inc"
+
+namespace {
+
+static Type convertBuffer(BufferType type) {
+  return MemRefType::get(type.getShape(), type.getElementType());
+}
+
+struct TRTypeConverter : public TypeConverter {
+  TRTypeConverter() {
+    addConversion([](Type type) { return type; });
+    addConversion([](BufferType type) { return convertBuffer(type); });
+
+    addSourceMaterialization([](OpBuilder &b, BufferType type, ValueRange inputs,
+                                Location loc) -> Value {
+      if (inputs.size() != 1)
+        return {};
+      return UnrealizedConversionCastOp::create(b, loc, type, inputs)
+          .getResult(0);
+    });
+    addTargetMaterialization([](OpBuilder &b, MemRefType type, ValueRange inputs,
+                                Location loc) -> Value {
+      if (inputs.size() != 1)
+        return {};
+      return UnrealizedConversionCastOp::create(b, loc, type, inputs)
+          .getResult(0);
+    });
+  }
+};
+
+struct DimOpConversion : public OpConversionPattern<DimOp> {
+  using OpConversionPattern::OpConversionPattern;
+  LogicalResult
+  matchAndRewrite(DimOp op, OpAdaptor adaptor,
+                  ConversionPatternRewriter &rewriter) const override {
+    Value idx =
+        arith::ConstantIndexOp::create(rewriter, op.getLoc(), op.getAxis());
+    rewriter.replaceOpWithNewOp<memref::DimOp>(op, adaptor.getBuffer(), idx);
+    return success();
+  }
+};
+
+template <typename OpTy>
+struct ForwardConvertedOperands : public OpConversionPattern<OpTy> {
+  using OpConversionPattern<OpTy>::OpConversionPattern;
+  LogicalResult
+  matchAndRewrite(OpTy op, typename OpTy::Adaptor adaptor,
+                  ConversionPatternRewriter &rewriter) const override {
+    rewriter.modifyOpInPlace(op, [&] {
+      op->setOperands(adaptor.getOperands());
+    });
+    return success();
+  }
+};
+
+struct ConvertTRBuffersToMemRef
+    : impl::ConvertTRBuffersToMemRefBase<ConvertTRBuffersToMemRef> {
+  void runOnOperation() override {
+    MLIRContext *ctx = &getContext();
+    TRTypeConverter converter;
+
+    ConversionTarget target(*ctx);
+    target.addLegalDialect<arith::ArithDialect, memref::MemRefDialect>();
+    target.addLegalOp<UnrealizedConversionCastOp>();
+    target.addIllegalOp<DimOp>();
+    target.addDynamicallyLegalOp<func::FuncOp>([&](func::FuncOp op) {
+      return converter.isSignatureLegal(op.getFunctionType());
+    });
+    target.addDynamicallyLegalOp<func::ReturnOp>([&](func::ReturnOp op) {
+      return converter.isLegal(op.getOperandTypes());
+    });
+    auto isLegalOp = [&](Operation *op) {
+      return converter.isLegal(op->getOperandTypes()) &&
+             converter.isLegal(op->getResultTypes());
+    };
+    target.addDynamicallyLegalOp<LoadOp, StoreOp, ForOp, YieldOp, ProgramIdOp,
+                                 ConstantOp, AddOp, ReduceSumOp>(isLegalOp);
+    target.addLegalDialect<TileReducerDialect>();
+    // Illegal ops / dynamic legality take precedence over addLegalDialect.
+
+    RewritePatternSet patterns(ctx);
+    populateFunctionOpInterfaceTypeConversionPattern<func::FuncOp>(patterns,
+                                                                   converter);
+    populateReturnOpTypeConversionPattern(patterns, converter);
+    patterns.add<DimOpConversion, ForwardConvertedOperands<LoadOp>,
+                 ForwardConvertedOperands<StoreOp>,
+                 ForwardConvertedOperands<ForOp>,
+                 ForwardConvertedOperands<YieldOp>>(converter, ctx);
+
+    if (failed(applyPartialConversion(getOperation(), target,
+                                      std::move(patterns))))
+      signalPassFailure();
+  }
+};
+
+} // namespace
+} // namespace mlir::tr
diff --git a/tile-reducer/lib/TileReducer/TileReducerOps.cpp b/tile-reducer/lib/TileReducer/TileReducerOps.cpp
index 178f9ff893f44..c5755ea97db74 100644
--- a/tile-reducer/lib/TileReducer/TileReducerOps.cpp
+++ b/tile-reducer/lib/TileReducer/TileReducerOps.cpp
@@ -4,6 +4,7 @@
 #include "TileReducer/TileReducerDialect.h"
 #include "TileReducer/TileReducerTypes.h"
 
+#include "mlir/Dialect/MemRef/IR/MemRef.h"
 #include "mlir/IR/Builders.h"
 #include "mlir/IR/OpImplementation.h"
 #include "mlir/IR/PatternMatch.h"
@@ -26,21 +27,30 @@ static LogicalResult verifyAxis(Operation *op, int64_t axis, int64_t rank,
   return success();
 }
 
-static LogicalResult verifyTileCoords(Operation *op, BufferType buffer,
+static LogicalResult verifyTileCoords(Operation *op, Type bufferType,
                                       ValueRange indices, TileType tile,
                                       StringRef kind) {
-  if (static_cast<int64_t>(indices.size()) != buffer.getRank())
+  int64_t rank = -1;
+  Type elem;
+  if (auto buffer = dyn_cast<BufferType>(bufferType)) {
+    rank = buffer.getRank();
+    elem = buffer.getElementType();
+  } else if (auto memref = dyn_cast<MemRefType>(bufferType)) {
+    rank = memref.getRank();
+    elem = memref.getElementType();
+  } else {
+    return op->emitOpError("expected !tr.buffer or memref, got ") << bufferType;
+  }
+  if (static_cast<int64_t>(indices.size()) != rank)
     return op->emitOpError("expected ")
-           << buffer.getRank() << " tile " << kind << " indices, got "
-           << indices.size();
-  if (tile.getRank() != buffer.getRank())
+           << rank << " tile " << kind << " indices, got " << indices.size();
+  if (tile.getRank() != rank)
     return op->emitOpError("tile rank ")
-           << tile.getRank() << " does not match buffer rank "
-           << buffer.getRank();
-  if (tile.getElementType() != buffer.getElementType())
+           << tile.getRank() << " does not match buffer rank " << rank;
+  if (tile.getElementType() != elem)
     return op->emitOpError("tile element type ")
            << tile.getElementType() << " does not match buffer element type "
-           << buffer.getElementType();
+           << elem;
   return success();
 }
 
@@ -125,19 +135,19 @@ LogicalResult ConstantOp::verify() {
 //===----------------------------------------------------------------------===//
 
 LogicalResult LoadOp::verify() {
-  auto buffer = dyn_cast<BufferType>(getBuffer().getType());
   auto tile = dyn_cast<TileType>(getType());
-  if (!buffer || !tile)
-    return emitOpError("load requires !tr.buffer and !tr.tile");
-  return verifyTileCoords(*this, buffer, getIndices(), tile, "load");
+  if (!tile)
+    return emitOpError("load result must be a !tr.tile");
+  return verifyTileCoords(*this, getBuffer().getType(), getIndices(), tile,
+                          "load");
 }
 
 LogicalResult StoreOp::verify() {
-  auto buffer = dyn_cast<BufferType>(getBuffer().getType());
   auto tile = dyn_cast<TileType>(getValue().getType());
-  if (!buffer || !tile)
-    return emitOpError("store requires !tr.buffer and !tr.tile");
-  return verifyTileCoords(*this, buffer, getIndices(), tile, "store");
+  if (!tile)
+    return emitOpError("store value must be a !tr.tile");
+  return verifyTileCoords(*this, getBuffer().getType(), getIndices(), tile,
+                          "store");
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/tile-reducer/test/convert-buffers.mlir b/tile-reducer/test/convert-buffers.mlir
new file mode 100644
index 0000000000000..9f429c8cadc91
--- /dev/null
+++ b/tile-reducer/test/convert-buffers.mlir
@@ -0,0 +1,26 @@
+// RUN: tr-opt %s --convert-tr-buffers-to-memref | FileCheck %s
+
+// CHECK-LABEL: func.func @row_sum
+// CHECK-SAME: (%[[IN:.*]]: memref<?x?xf32>, %[[OUT:.*]]: memref<?xf32>)
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  // CHECK: memref.dim %[[IN]], %{{.*}} : memref<?x?xf32>
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    // CHECK: tr.load %[[IN]]
+    // CHECK-SAME: memref<?x?xf32>, !tr.tile<128x128xf32>
+    %t = tr.load %in[%row_blk, %kt] : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2 = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  // CHECK: tr.store %[[OUT]]
+  // CHECK-SAME: memref<?xf32>, !tr.tile<128xf32>
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}
diff --git a/tile-reducer/test/smoke.mlir b/tile-reducer/test/smoke.mlir
index f19e539e98d0c..e22110a640515 100644
--- a/tile-reducer/test/smoke.mlir
+++ b/tile-reducer/test/smoke.mlir
@@ -4,7 +4,7 @@
 // Milestone 1: the driver registers `tr` (plus func/arith from the canonical
 // source) and can parse a module. Types and ops are Milestone 2 / 3.
 
-// DIALECT: Available Dialects: arith,builtin,func,tr
+// DIALECT: Available Dialects: arith,builtin,func,memref,tr
 
 module {
   // CHECK-LABEL: func.func @smoke
diff --git a/tile-reducer/tr-opt/CMakeLists.txt b/tile-reducer/tr-opt/CMakeLists.txt
index 9965df4d64eff..616fa77069443 100644
--- a/tile-reducer/tr-opt/CMakeLists.txt
+++ b/tile-reducer/tr-opt/CMakeLists.txt
@@ -1,6 +1,7 @@
 set(LIBS
     MLIRArithDialect
     MLIRFuncDialect
+    MLIRMemRefDialect
     MLIROptLib
     MLIRTileReducer
   )
diff --git a/tile-reducer/tr-opt/tr-opt.cpp b/tile-reducer/tr-opt/tr-opt.cpp
index a1e2a79c07254..36e15f7a88412 100644
--- a/tile-reducer/tr-opt/tr-opt.cpp
+++ b/tile-reducer/tr-opt/tr-opt.cpp
@@ -7,6 +7,7 @@
 
 #include "mlir/Dialect/Arith/IR/Arith.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/Dialect/MemRef/IR/MemRef.h"
 #include "mlir/IR/MLIRContext.h"
 #include "mlir/Tools/mlir-opt/MlirOptMain.h"
 
@@ -18,7 +19,7 @@ int main(int argc, char **argv) {
 
   mlir::DialectRegistry registry;
   registry.insert<mlir::tr::TileReducerDialect, mlir::arith::ArithDialect,
-                  mlir::func::FuncDialect>();
+                  mlir::func::FuncDialect, mlir::memref::MemRefDialect>();
 
   return mlir::asMainReturnCode(
       mlir::MlirOptMain(argc, argv, "TileReducer optimizer driver\n", registry));

>From 077ebd8a8da1915fe2b45f859a1e485c0f9d050c Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 22:40:41 -0700
Subject: [PATCH 08/29] [TileReducer] Milestone 8: lower reductions to Linalg
 over MemRefs

Row, column, and full reductions become linalg.generic with arith.addf
and iterator types parallel/reduction, reduction/parallel, and
reduction/reduction. !tr.tile lowers to a same-shape memref. Rank-0
tiles (!tr.tile<f32>) represent a full-reduction scalar. No Tensor
dialect.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/convert-to-linalg.mlir
  tr-opt --convert-tr-to-linalg tile-reducer/test/convert-to-linalg.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |   7 +
 .../include/TileReducer/TileReducerPasses.td  |  25 ++
 .../include/TileReducer/TileReducerTypes.td   |   5 +-
 tile-reducer/lib/TileReducer/CMakeLists.txt   |   3 +
 .../TileReducerLinalgConversion.cpp           | 350 ++++++++++++++++++
 .../lib/TileReducer/TileReducerTypes.cpp      |   2 -
 tile-reducer/test/annotate-plan.mlir          |   7 +
 tile-reducer/test/convert-to-linalg.mlir      |  78 ++++
 tile-reducer/test/smoke.mlir                  |   2 +-
 tile-reducer/test/types-invalid.mlir          |   8 -
 tile-reducer/test/types-roundtrip.mlir        |   3 +-
 tile-reducer/tr-opt/CMakeLists.txt            |   2 +
 tile-reducer/tr-opt/tr-opt.cpp                |   7 +-
 13 files changed, 483 insertions(+), 16 deletions(-)
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerLinalgConversion.cpp
 create mode 100644 tile-reducer/test/convert-to-linalg.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index e2bd001fbaea3..7cf4d059908b0 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -12,3 +12,10 @@ cmake -G Ninja -S tile-reducer -B tile-reducer/build \
   -DMLIR_DIR=/Users/ionut/work/llvm/build/build-xcode/lib/cmake/mlir
 cmake --build tile-reducer/build --target tr-opt check-tr
 ```
+
+## Milestone 8
+
+`--convert-tr-to-linalg` lowers `tr.reduce_sum` / `tr.add` / `tr.constant` to
+Linalg over MemRefs. Row, column, and full reductions use `linalg.generic`
+with `arith.addf` and iterator types `parallel,reduction`,
+`reduction,parallel`, and `reduction,reduction`. No Tensor dialect.
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
index 8fa3eeea08c07..3e3c8a79793ec 100644
--- a/tile-reducer/include/TileReducer/TileReducerPasses.td
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -53,5 +53,30 @@ def ConvertTRForBoundsToArith : Pass<"tr-for-bounds-to-arith", "::mlir::func::Fu
   ];
 }
 
+def ConvertTRToLinalg : Pass<"convert-tr-to-linalg", "::mlir::func::FuncOp"> {
+  let summary = "Lower tile compute to Linalg over MemRefs. Load becomes a subview.";
+  let description = [{
+    `!tr.tile` becomes a memref of the same static shape. Reductions become
+    `linalg.generic` with `arith.addf`/`arith.addi` and the iterator types
+    required by Milestone 8:
+
+      row    (axis = 1 on rank 2): parallel, reduction
+      column (axis = 0 on rank 2): reduction, parallel
+      full   (rank 1, or fused 2D->scalar): reduction [, reduction]
+
+    `tr.load` is a `memref.subview` of the input (tile coord * tile size).
+    No `memref.alloc` of the loaded tile. A small alloca for an accumulator
+    or reduce destination is allowed. `tr.store` is a subview plus copy.
+    `tr.for` stays; only its iter_arg types change.
+  }];
+  let dependentDialects = [
+    "::mlir::tr::TileReducerDialect",
+    "::mlir::linalg::LinalgDialect",
+    "::mlir::memref::MemRefDialect",
+    "::mlir::arith::ArithDialect",
+    "::mlir::func::FuncDialect"
+  ];
+}
+
 
 #endif // TILE_REDUCER_PASSES
diff --git a/tile-reducer/include/TileReducer/TileReducerTypes.td b/tile-reducer/include/TileReducer/TileReducerTypes.td
index 49b1524d781b1..30d0f1e2302e3 100644
--- a/tile-reducer/include/TileReducer/TileReducerTypes.td
+++ b/tile-reducer/include/TileReducer/TileReducerTypes.td
@@ -21,8 +21,9 @@ def TileReducer_TileType : TileReducer_Type<"Tile", "tile"> {
     `!tr.tile<128x128xf32>` is a logical collection of values. It does not
     imply a memref allocation, thread ownership, or a hardware load.
 
-    All dimensions must be static and positive. Dynamic or named extents are
-    rejected: those belong on `!tr.buffer`.
+    Dimensions must be static and positive. Rank 0 (`!tr.tile<f32>`) is
+    allowed so a full reduction can produce a scalar tile. Dynamic or named
+    extents are rejected: those belong on `!tr.buffer`.
   }];
   let parameters = (ins
     ArrayRefParameter<"int64_t">:$shape,
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index d1cd36896765c..c88b4972b727f 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -4,6 +4,7 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerTypes.cpp
         TileReducerAnalyses.cpp
         TileReducerBufferConversion.cpp
+        TileReducerLinalgConversion.cpp
         TileReducerPasses.cpp
 
         ADDITIONAL_HEADER_DIRS
@@ -20,7 +21,9 @@ add_mlir_dialect_library(MLIRTileReducer
         MLIRArithDialect
         MLIRControlFlowInterfaces
         MLIRFuncDialect
+        MLIRAffineDialect
         MLIRFuncTransforms
+        MLIRLinalgDialect
         MLIRMemRefDialect
         MLIRInferTypeOpInterface
         MLIRPass
diff --git a/tile-reducer/lib/TileReducer/TileReducerLinalgConversion.cpp b/tile-reducer/lib/TileReducer/TileReducerLinalgConversion.cpp
new file mode 100644
index 0000000000000..47823aac4c95e
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerLinalgConversion.cpp
@@ -0,0 +1,350 @@
+//===- TileReducerLinalgConversion.cpp - Milestones 8-9 ---------*- C++ -*-===//
+//
+// Lower tile compute to Linalg over MemRefs. A loaded tile is a subview of
+// the input buffer, not a 128x128 allocation.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/TileReducerPasses.h"
+
+#include "TileReducer/TileReducerDialect.h"
+#include "TileReducer/TileReducerOps.h"
+#include "TileReducer/TileReducerTypes.h"
+
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/Dialect/Linalg/IR/Linalg.h"
+#include "mlir/Dialect/MemRef/IR/MemRef.h"
+#include "mlir/Dialect/Utils/StructuredOpsUtils.h"
+#include "mlir/IR/AffineMap.h"
+#include "mlir/IR/PatternMatch.h"
+
+namespace mlir::tr {
+#define GEN_PASS_DEF_CONVERTTRTOLINALG
+#include "TileReducer/TileReducerPasses.h.inc"
+
+namespace {
+
+static Type convertTRType(Type type) {
+  if (auto tile = dyn_cast<TileType>(type))
+    return MemRefType::get(tile.getShape(), tile.getElementType());
+  if (auto buffer = dyn_cast<BufferType>(type))
+    return MemRefType::get(buffer.getShape(), buffer.getElementType());
+  return type;
+}
+
+static int64_t shapedRank(Type type) {
+  if (auto tile = dyn_cast<TileType>(type))
+    return tile.getRank();
+  if (auto memref = dyn_cast<MemRefType>(type))
+    return memref.getRank();
+  if (auto buffer = dyn_cast<BufferType>(type))
+    return buffer.getRank();
+  return -1;
+}
+
+static MemRefType memrefForTileLike(Type type) {
+  if (auto memref = dyn_cast<MemRefType>(type))
+    return memref;
+  if (auto tile = dyn_cast<TileType>(type))
+    return MemRefType::get(tile.getShape(), tile.getElementType());
+  llvm_unreachable("expected a tile or memref");
+}
+
+static Value createScalarAdd(OpBuilder &b, Location loc, Value lhs, Value rhs) {
+  if (isa<FloatType>(lhs.getType()))
+    return arith::AddFOp::create(b, loc, lhs, rhs);
+  return arith::AddIOp::create(b, loc, lhs, rhs);
+}
+
+static Value materializeScalar(OpBuilder &b, Location loc, Attribute attr,
+                               Type elem) {
+  if (auto ft = dyn_cast<FloatType>(elem)) {
+    APFloat value(ft.getFloatSemantics(), APInt::getZero(ft.getWidth()));
+    if (auto fattr = dyn_cast<FloatAttr>(attr)) {
+      value = fattr.getValue();
+      bool losesInfo = false;
+      value.convert(ft.getFloatSemantics(), APFloat::rmNearestTiesToEven,
+                    &losesInfo);
+    }
+    return arith::ConstantOp::create(b, loc, FloatAttr::get(ft, value));
+  }
+  if (auto it = dyn_cast<IntegerType>(elem)) {
+    APInt value(it.getWidth(), 0);
+    if (auto iattr = dyn_cast<IntegerAttr>(attr))
+      value = iattr.getValue().sextOrTrunc(it.getWidth());
+    return arith::ConstantOp::create(b, loc, IntegerAttr::get(it, value));
+  }
+  return {};
+}
+
+static Value createZeroScalar(OpBuilder &b, Location loc, Type elem) {
+  if (auto ft = dyn_cast<FloatType>(elem))
+    return arith::ConstantOp::create(b, loc, b.getFloatAttr(ft, 0.0));
+  if (auto it = dyn_cast<IntegerType>(elem))
+    return arith::ConstantOp::create(b, loc, b.getIntegerAttr(it, 0));
+  return {};
+}
+
+static Value createAlloca(OpBuilder &b, Location loc, MemRefType type) {
+  return memref::AllocaOp::create(b, loc, type);
+}
+
+static void fillMemRef(OpBuilder &b, Location loc, Value dest, Value scalar) {
+  linalg::FillOp::create(b, loc, ValueRange{scalar}, ValueRange{dest});
+}
+
+static void createReductionGeneric(OpBuilder &b, Location loc, Value input,
+                                   Value dest, ArrayRef<int64_t> reducedDims) {
+  auto inTy = cast<MemRefType>(input.getType());
+  int64_t rank = inTy.getRank();
+  MLIRContext *ctx = b.getContext();
+
+  SmallVector<utils::IteratorType> iters(rank, utils::IteratorType::parallel);
+  SmallVector<char> isReduced(rank, 0);
+  for (int64_t dim : reducedDims) {
+    iters[dim] = utils::IteratorType::reduction;
+    isReduced[dim] = 1;
+  }
+
+  AffineMap inMap = AffineMap::getMultiDimIdentityMap(rank, ctx);
+  SmallVector<AffineExpr> outExprs;
+  for (int64_t i = 0; i < rank; ++i)
+    if (!isReduced[i])
+      outExprs.push_back(getAffineDimExpr(i, ctx));
+  AffineMap outMap = AffineMap::get(rank, /*symbolCount=*/0, outExprs, ctx);
+
+  linalg::GenericOp::create(
+      b, loc, ValueRange{input}, ValueRange{dest},
+      ArrayRef<AffineMap>{inMap, outMap}, iters,
+      [&](OpBuilder &rb, Location rloc, ValueRange args) {
+        linalg::YieldOp::create(rb, rloc,
+                                createScalarAdd(rb, rloc, args[0], args[1]));
+      });
+}
+
+static void createAddGeneric(OpBuilder &b, Location loc, Value lhs, Value rhs,
+                             Value dest) {
+  auto ty = cast<MemRefType>(dest.getType());
+  int64_t rank = ty.getRank();
+  MLIRContext *ctx = b.getContext();
+  AffineMap id = AffineMap::getMultiDimIdentityMap(rank, ctx);
+  SmallVector<utils::IteratorType> iters(rank, utils::IteratorType::parallel);
+  linalg::GenericOp::create(
+      b, loc, ValueRange{lhs, rhs}, ValueRange{dest},
+      ArrayRef<AffineMap>{id, id, id}, iters,
+      [&](OpBuilder &rb, Location rloc, ValueRange args) {
+        linalg::YieldOp::create(rb, rloc,
+                                createScalarAdd(rb, rloc, args[0], args[1]));
+      });
+}
+
+static FailureOr<Value> createTileSubview(OpBuilder &b, Location loc,
+                                          Value buffer, ValueRange indices,
+                                          ArrayRef<int64_t> tileShape) {
+  auto memTy = dyn_cast<MemRefType>(buffer.getType());
+  if (!memTy)
+    return failure();
+  if (static_cast<int64_t>(indices.size()) != memTy.getRank() ||
+      indices.size() != tileShape.size())
+    return failure();
+
+  SmallVector<OpFoldResult> offsets, sizes, strides;
+  for (auto [idx, extent] : llvm::zip(indices, tileShape)) {
+    Value offset = idx;
+    if (extent != 1) {
+      Value c = arith::ConstantIndexOp::create(b, loc, extent);
+      offset = arith::MulIOp::create(b, loc, idx, c);
+    }
+    offsets.push_back(offset);
+    sizes.push_back(b.getIndexAttr(extent));
+    strides.push_back(b.getIndexAttr(1));
+  }
+  return memref::SubViewOp::create(b, loc, buffer, offsets, sizes, strides)
+      .getResult();
+}
+
+static void convertSignature(func::FuncOp func) {
+  auto oldTy = func.getFunctionType();
+  SmallVector<Type> ins, outs;
+  for (Type t : oldTy.getInputs())
+    ins.push_back(convertTRType(t));
+  for (Type t : oldTy.getResults())
+    outs.push_back(convertTRType(t));
+  if (ins == oldTy.getInputs() && outs == oldTy.getResults())
+    return;
+  func.setType(FunctionType::get(func.getContext(), ins, outs));
+  for (auto [arg, ty] : llvm::zip(func.getArguments(), ins))
+    if (arg.getType() != ty)
+      arg.setType(ty);
+}
+
+static void convertForTypes(ForOp op) {
+  for (BlockArgument arg : op.getRegionIterArgs()) {
+    Type converted = convertTRType(arg.getType());
+    if (converted != arg.getType())
+      arg.setType(converted);
+  }
+  for (OpResult res : op->getResults()) {
+    Type converted = convertTRType(res.getType());
+    if (converted != res.getType())
+      res.setType(converted);
+  }
+}
+
+static bool isInnerOfFusedFullReduce(ReduceSumOp op) {
+  if (!op->hasOneUse())
+    return false;
+  auto outer = dyn_cast<ReduceSumOp>(*op->getUsers().begin());
+  if (!outer)
+    return false;
+  return shapedRank(op.getInput().getType()) == 2 &&
+         shapedRank(op.getType()) == 1 && shapedRank(outer.getType()) == 0;
+}
+
+static LogicalResult lowerConstant(RewriterBase &rewriter, ConstantOp op) {
+  auto tile = dyn_cast<TileType>(op.getType());
+  if (!tile)
+    return op.emitOpError("expected !tr.tile result");
+  rewriter.setInsertionPoint(op);
+  Location loc = op.getLoc();
+  auto memTy = MemRefType::get(tile.getShape(), tile.getElementType());
+  Value dest = createAlloca(rewriter, loc, memTy);
+  Value scalar =
+      materializeScalar(rewriter, loc, op.getValue(), tile.getElementType());
+  if (!scalar)
+    return op.emitOpError("unsupported constant element type");
+  fillMemRef(rewriter, loc, dest, scalar);
+  rewriter.replaceOp(op, dest);
+  return success();
+}
+
+static LogicalResult lowerLoad(RewriterBase &rewriter, LoadOp op) {
+  auto tile = dyn_cast<TileType>(op.getType());
+  if (!tile)
+    return op.emitOpError("expected !tr.tile result");
+  rewriter.setInsertionPoint(op);
+  FailureOr<Value> view = createTileSubview(
+      rewriter, op.getLoc(), op.getBuffer(), op.getIndices(), tile.getShape());
+  if (failed(view))
+    return op.emitOpError("load buffer must be a memref");
+  rewriter.replaceOp(op, *view);
+  return success();
+}
+
+static LogicalResult lowerStore(RewriterBase &rewriter, StoreOp op) {
+  auto tile = dyn_cast<TileType>(op.getValue().getType());
+  ArrayRef<int64_t> shape;
+  if (tile) {
+    shape = tile.getShape();
+  } else if (auto memref = dyn_cast<MemRefType>(op.getValue().getType())) {
+    shape = memref.getShape();
+  } else {
+    return op.emitOpError("store value must be a tile or memref");
+  }
+  rewriter.setInsertionPoint(op);
+  FailureOr<Value> view = createTileSubview(
+      rewriter, op.getLoc(), op.getBuffer(), op.getIndices(), shape);
+  if (failed(view))
+    return op.emitOpError("store buffer must be a memref");
+  memref::CopyOp::create(rewriter, op.getLoc(), op.getValue(), *view);
+  rewriter.eraseOp(op);
+  return success();
+}
+
+static LogicalResult lowerReduce(RewriterBase &rewriter, ReduceSumOp op) {
+  if (isInnerOfFusedFullReduce(op))
+    return success();
+
+  Location loc = op.getLoc();
+  rewriter.setInsertionPoint(op);
+
+  Value input = op.getInput();
+  SmallVector<int64_t> reducedDims;
+  ReduceSumOp innerToErase;
+  if (auto inner = input.getDefiningOp<ReduceSumOp>()) {
+    // Fuse 2D -> 1D -> 0D into one generic with both reduction iterators.
+    input = inner.getInput();
+    int64_t rank = shapedRank(input.getType());
+    for (int64_t i = 0; i < rank; ++i)
+      reducedDims.push_back(i);
+    innerToErase = inner;
+  } else {
+    reducedDims.push_back(op.getAxis());
+  }
+
+  if (!isa<MemRefType>(input.getType()))
+    return op.emitOpError("reduce input must already be a memref");
+
+  MemRefType destTy = memrefForTileLike(op.getType());
+  Value dest = createAlloca(rewriter, loc, destTy);
+  Value zero = createZeroScalar(rewriter, loc, destTy.getElementType());
+  if (!zero)
+    return op.emitOpError("unsupported reduce element type");
+  fillMemRef(rewriter, loc, dest, zero);
+  createReductionGeneric(rewriter, loc, input, dest, reducedDims);
+  rewriter.replaceOp(op, dest);
+  if (innerToErase)
+    rewriter.eraseOp(innerToErase);
+  return success();
+}
+
+static LogicalResult lowerAdd(RewriterBase &rewriter, AddOp op) {
+  if (!isa<MemRefType>(op.getLhs().getType()) ||
+      !isa<MemRefType>(op.getRhs().getType()))
+    return op.emitOpError("add operands must already be memrefs");
+  Location loc = op.getLoc();
+  rewriter.setInsertionPoint(op);
+  MemRefType destTy = memrefForTileLike(op.getType());
+  Value dest = createAlloca(rewriter, loc, destTy);
+  createAddGeneric(rewriter, loc, op.getLhs(), op.getRhs(), dest);
+  rewriter.replaceOp(op, dest);
+  return success();
+}
+
+static LogicalResult lowerDim(RewriterBase &rewriter, DimOp op) {
+  if (!isa<MemRefType>(op.getBuffer().getType()))
+    return op.emitOpError("dim buffer must already be a memref");
+  rewriter.setInsertionPoint(op);
+  Value idx =
+      arith::ConstantIndexOp::create(rewriter, op.getLoc(), op.getAxis());
+  rewriter.replaceOpWithNewOp<memref::DimOp>(op, op.getBuffer(), idx);
+  return success();
+}
+
+struct ConvertTRToLinalg : impl::ConvertTRToLinalgBase<ConvertTRToLinalg> {
+  void runOnOperation() override {
+    func::FuncOp func = getOperation();
+    IRRewriter rewriter(&getContext());
+    convertSignature(func);
+
+    WalkResult walk = func.walk<WalkOrder::PreOrder>([&](Operation *op) {
+      if (auto forOp = dyn_cast<ForOp>(op)) {
+        convertForTypes(forOp);
+        return WalkResult::advance();
+      }
+      LogicalResult status = success();
+      if (auto dim = dyn_cast<DimOp>(op))
+        status = lowerDim(rewriter, dim);
+      else if (auto cst = dyn_cast<ConstantOp>(op))
+        status = lowerConstant(rewriter, cst);
+      else if (auto load = dyn_cast<LoadOp>(op))
+        status = lowerLoad(rewriter, load);
+      else if (auto red = dyn_cast<ReduceSumOp>(op))
+        status = lowerReduce(rewriter, red);
+      else if (auto add = dyn_cast<AddOp>(op))
+        status = lowerAdd(rewriter, add);
+      else if (auto store = dyn_cast<StoreOp>(op))
+        status = lowerStore(rewriter, store);
+      if (failed(status))
+        return WalkResult::interrupt();
+      return WalkResult::advance();
+    });
+
+    if (walk.wasInterrupted())
+      signalPassFailure();
+  }
+};
+
+} // namespace
+} // namespace mlir::tr
diff --git a/tile-reducer/lib/TileReducer/TileReducerTypes.cpp b/tile-reducer/lib/TileReducer/TileReducerTypes.cpp
index edabdd20b75ba..e3add0ebd95ca 100644
--- a/tile-reducer/lib/TileReducer/TileReducerTypes.cpp
+++ b/tile-reducer/lib/TileReducer/TileReducerTypes.cpp
@@ -176,8 +176,6 @@ static LogicalResult verifyElement(function_ref<InFlightDiagnostic()> emitError,
 
 LogicalResult TileType::verify(function_ref<InFlightDiagnostic()> emitError,
                                ArrayRef<int64_t> shape, Type elementType) {
-  if (shape.empty())
-    return emitError() << "tile must have rank >= 1";
   for (int64_t d : shape) {
     if (ShapedType::isDynamic(d))
       return emitError() << "tile dimensions must be static";
diff --git a/tile-reducer/test/annotate-plan.mlir b/tile-reducer/test/annotate-plan.mlir
index 4ab964bc320c7..637c821346aab 100644
--- a/tile-reducer/test/annotate-plan.mlir
+++ b/tile-reducer/test/annotate-plan.mlir
@@ -13,3 +13,10 @@ func.func @col(%t: !tr.tile<128x128xf32>) -> !tr.tile<128xf32> {
   %r = tr.reduce_sum %t, axis = 0 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
   return %r : !tr.tile<128xf32>
 }
+
+// CHECK-LABEL: func.func @full
+func.func @full(%t: !tr.tile<128xf32>) -> !tr.tile<f32> {
+  // CHECK: tr.reduce_sum {{.*}} {tr.plan = "full"}
+  %r = tr.reduce_sum %t, axis = 0 : !tr.tile<128xf32> -> !tr.tile<f32>
+  return %r : !tr.tile<f32>
+}
diff --git a/tile-reducer/test/convert-to-linalg.mlir b/tile-reducer/test/convert-to-linalg.mlir
new file mode 100644
index 0000000000000..394ca7989c173
--- /dev/null
+++ b/tile-reducer/test/convert-to-linalg.mlir
@@ -0,0 +1,78 @@
+// RUN: tr-opt %s --convert-tr-to-linalg | FileCheck %s
+
+// Milestone 8: row / column / full reductions become linalg.generic over
+// MemRefs. The scalar combiner is arith.addf. No Tensor dialect.
+
+// CHECK-DAG: #[[IN:.*]] = affine_map<(d0, d1) -> (d0, d1)>
+// CHECK-DAG: #[[ROW:.*]] = affine_map<(d0, d1) -> (d0)>
+// CHECK-DAG: #[[COL:.*]] = affine_map<(d0, d1) -> (d1)>
+// CHECK-DAG: #[[FULL:.*]] = affine_map<(d0, d1) -> ()>
+
+// CHECK-LABEL: func.func @row
+// CHECK-SAME: (%[[T:.*]]: memref<128x128xf32>) -> memref<128xf32>
+func.func @row(%t: !tr.tile<128x128xf32>) -> !tr.tile<128xf32> {
+  // CHECK: %[[ACC:.*]] = memref.alloca() : memref<128xf32>
+  // CHECK: %[[Z:.*]] = arith.constant 0.000000e+00 : f32
+  // CHECK: linalg.fill ins(%[[Z]] : f32) outs(%[[ACC]] : memref<128xf32>)
+  // CHECK: linalg.generic
+  // CHECK-SAME: indexing_maps = [#[[IN]], #[[ROW]]]
+  // CHECK-SAME: iterator_types = ["parallel", "reduction"]
+  // CHECK-SAME: ins(%[[T]] : memref<128x128xf32>)
+  // CHECK-SAME: outs(%[[ACC]] : memref<128xf32>)
+  // CHECK: arith.addf
+  // CHECK: linalg.yield
+  // CHECK: return %[[ACC]] : memref<128xf32>
+  %r = tr.reduce_sum %t, axis = 1 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}
+
+// CHECK-LABEL: func.func @column
+// CHECK-SAME: (%[[T:.*]]: memref<128x128xf32>) -> memref<128xf32>
+func.func @column(%t: !tr.tile<128x128xf32>) -> !tr.tile<128xf32> {
+  // CHECK: linalg.generic
+  // CHECK-SAME: indexing_maps = [#[[IN]], #[[COL]]]
+  // CHECK-SAME: iterator_types = ["reduction", "parallel"]
+  // CHECK: arith.addf
+  %r = tr.reduce_sum %t, axis = 0 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}
+
+// CHECK-LABEL: func.func @full
+// CHECK-SAME: (%[[T:.*]]: memref<128x128xf32>) -> memref<f32>
+func.func @full(%t: !tr.tile<128x128xf32>) -> !tr.tile<f32> {
+  // Two successive reduces fuse to one generic over both axes.
+  // CHECK: %[[ACC:.*]] = memref.alloca() : memref<f32>
+  // CHECK: linalg.generic
+  // CHECK-SAME: indexing_maps = [#[[IN]], #[[FULL]]]
+  // CHECK-SAME: iterator_types = ["reduction", "reduction"]
+  // CHECK-SAME: ins(%[[T]] : memref<128x128xf32>)
+  // CHECK-SAME: outs(%[[ACC]] : memref<f32>)
+  // CHECK: arith.addf
+  // CHECK-NOT: tr.reduce_sum
+  %r0 = tr.reduce_sum %t, axis = 1 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+  %r1 = tr.reduce_sum %r0, axis = 0 : !tr.tile<128xf32> -> !tr.tile<f32>
+  return %r1 : !tr.tile<f32>
+}
+
+// CHECK-LABEL: func.func @add_tiles
+// CHECK-SAME: (%[[A:.*]]: memref<128xf32>, %[[B:.*]]: memref<128xf32>) -> memref<128xf32>
+func.func @add_tiles(%a: !tr.tile<128xf32>, %b: !tr.tile<128xf32>) -> !tr.tile<128xf32> {
+  // CHECK: %[[OUT:.*]] = memref.alloca() : memref<128xf32>
+  // CHECK: linalg.generic
+  // CHECK-SAME: iterator_types = ["parallel"]
+  // CHECK-SAME: ins(%[[A]], %[[B]] : memref<128xf32>, memref<128xf32>)
+  // CHECK-SAME: outs(%[[OUT]] : memref<128xf32>)
+  // CHECK: arith.addf
+  %r = tr.add %a, %b : !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}
+
+// CHECK-LABEL: func.func @constant_tile
+func.func @constant_tile() -> !tr.tile<128xf32> {
+  // CHECK: %[[A:.*]] = memref.alloca() : memref<128xf32>
+  // CHECK: %[[Z:.*]] = arith.constant 0.000000e+00 : f32
+  // CHECK: linalg.fill ins(%[[Z]] : f32) outs(%[[A]] : memref<128xf32>)
+  // CHECK: return %[[A]] : memref<128xf32>
+  %z = tr.constant 0.0 : !tr.tile<128xf32>
+  return %z : !tr.tile<128xf32>
+}
diff --git a/tile-reducer/test/smoke.mlir b/tile-reducer/test/smoke.mlir
index e22110a640515..bd940eb28df70 100644
--- a/tile-reducer/test/smoke.mlir
+++ b/tile-reducer/test/smoke.mlir
@@ -4,7 +4,7 @@
 // Milestone 1: the driver registers `tr` (plus func/arith from the canonical
 // source) and can parse a module. Types and ops are Milestone 2 / 3.
 
-// DIALECT: Available Dialects: arith,builtin,func,memref,tr
+// DIALECT: Available Dialects: affine,arith,builtin,func,linalg,memref,tr
 
 module {
   // CHECK-LABEL: func.func @smoke
diff --git a/tile-reducer/test/types-invalid.mlir b/tile-reducer/test/types-invalid.mlir
index fff83b1488e1a..3b7032fab66a1 100644
--- a/tile-reducer/test/types-invalid.mlir
+++ b/tile-reducer/test/types-invalid.mlir
@@ -16,14 +16,6 @@ func.func @named_tile(%t: !tr.tile<Mxf32>) {
 
 // -----
 
-// Verifier: rank-0 tile.
-func.func @scalar_tile(%t: !tr.tile<f32>) {
-  // expected-error at -1 {{tile must have rank >= 1}}
-  return
-}
-
-// -----
-
 // Verifier: zero extent. Spaces keep `0 x f32` from lexing as the hex
 // integer `0xf32` (the same special case builtin tensor types have).
 func.func @zero_tile(%t: !tr.tile<0 x f32>) {
diff --git a/tile-reducer/test/types-roundtrip.mlir b/tile-reducer/test/types-roundtrip.mlir
index c9f8c7f15bbf9..080fdbdb69646 100644
--- a/tile-reducer/test/types-roundtrip.mlir
+++ b/tile-reducer/test/types-roundtrip.mlir
@@ -4,10 +4,11 @@
 
 // CHECK-LABEL: func.func @tiles
 func.func @tiles(%t1: !tr.tile<128xf32>, %t2: !tr.tile<128x128xf32>,
-                 %t3: !tr.tile<64x32xi32>) {
+                 %t3: !tr.tile<64x32xi32>, %t0: !tr.tile<f32>) {
   // CHECK: !tr.tile<128xf32>
   // CHECK: !tr.tile<128x128xf32>
   // CHECK: !tr.tile<64x32xi32>
+  // CHECK: !tr.tile<f32>
   return
 }
 
diff --git a/tile-reducer/tr-opt/CMakeLists.txt b/tile-reducer/tr-opt/CMakeLists.txt
index 616fa77069443..dfa854aa332ea 100644
--- a/tile-reducer/tr-opt/CMakeLists.txt
+++ b/tile-reducer/tr-opt/CMakeLists.txt
@@ -1,6 +1,8 @@
 set(LIBS
+    MLIRAffineDialect
     MLIRArithDialect
     MLIRFuncDialect
+    MLIRLinalgDialect
     MLIRMemRefDialect
     MLIROptLib
     MLIRTileReducer
diff --git a/tile-reducer/tr-opt/tr-opt.cpp b/tile-reducer/tr-opt/tr-opt.cpp
index 36e15f7a88412..41bb124895902 100644
--- a/tile-reducer/tr-opt/tr-opt.cpp
+++ b/tile-reducer/tr-opt/tr-opt.cpp
@@ -5,8 +5,10 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "mlir/Dialect/Affine/IR/AffineOps.h"
 #include "mlir/Dialect/Arith/IR/Arith.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/Dialect/Linalg/IR/Linalg.h"
 #include "mlir/Dialect/MemRef/IR/MemRef.h"
 #include "mlir/IR/MLIRContext.h"
 #include "mlir/Tools/mlir-opt/MlirOptMain.h"
@@ -18,8 +20,9 @@ int main(int argc, char **argv) {
   mlir::tr::registerPasses();
 
   mlir::DialectRegistry registry;
-  registry.insert<mlir::tr::TileReducerDialect, mlir::arith::ArithDialect,
-                  mlir::func::FuncDialect, mlir::memref::MemRefDialect>();
+  registry.insert<mlir::tr::TileReducerDialect, mlir::affine::AffineDialect,
+                  mlir::arith::ArithDialect, mlir::func::FuncDialect,
+                  mlir::linalg::LinalgDialect, mlir::memref::MemRefDialect>();
 
   return mlir::asMainReturnCode(
       mlir::MlirOptMain(argc, argv, "TileReducer optimizer driver\n", registry));

>From 9ab131b53d221bbe876e68e1b00a5d740f6bf6f0 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 22:40:53 -0700
Subject: [PATCH 09/29] [TileReducer] Milestone 9: tr.load is a memref.subview,
 not an alloc

The loaded 128x128 tile aliases the input buffer via subview
(offset = tile coord * tile size). No memref.alloc of the tile.
The 128-element accumulator remains an alloca. tr.store is a
subview of the output plus memref.copy.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/convert-load-subview.mlir
  tr-opt --convert-tr-to-linalg tile-reducer/test/convert-load-subview.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                      |  7 ++++
 tile-reducer/test/convert-load-subview.mlir | 46 +++++++++++++++++++++
 2 files changed, 53 insertions(+)
 create mode 100644 tile-reducer/test/convert-load-subview.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index 7cf4d059908b0..1504ec610d815 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -19,3 +19,10 @@ cmake --build tile-reducer/build --target tr-opt check-tr
 Linalg over MemRefs. Row, column, and full reductions use `linalg.generic`
 with `arith.addf` and iterator types `parallel,reduction`,
 `reduction,parallel`, and `reduction,reduction`. No Tensor dialect.
+
+## Milestone 9
+
+The same pass realizes `tr.load` as `memref.subview` of the input
+(offset = tile coordinate × tile size). A 128×128 tile is not allocated.
+A 128-element alloca is used only for the accumulator / reduce destination.
+`tr.store` is a subview of the output plus `memref.copy`.
diff --git a/tile-reducer/test/convert-load-subview.mlir b/tile-reducer/test/convert-load-subview.mlir
new file mode 100644
index 0000000000000..d2dbb641f0691
--- /dev/null
+++ b/tile-reducer/test/convert-load-subview.mlir
@@ -0,0 +1,46 @@
+// RUN: tr-opt %s --convert-tr-buffers-to-memref --convert-tr-to-linalg | FileCheck %s
+
+// Milestone 9: tr.load is a subview of the input buffer. The 128x128 tile
+// is not allocated. The accumulator is a 128-element alloca.
+
+// CHECK-LABEL: func.func @row_sum
+// CHECK-SAME: (%[[IN:.*]]: memref<?x?xf32>, %[[OUT:.*]]: memref<?xf32>)
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+
+  // CHECK: %[[ACC:.*]] = memref.alloca() : memref<128xf32>
+  // CHECK: linalg.fill
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+
+  // CHECK: tr.for
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    // Tile coordinates * tile size become subview offsets.
+    // CHECK: %[[ROFF:.*]] = arith.muli %{{.*}}, %{{.*}} : index
+    // CHECK: %[[COFF:.*]] = arith.muli %{{.*}}, %{{.*}} : index
+    // CHECK: %[[VIEW:.*]] = memref.subview %[[IN]][%[[ROFF]], %[[COFF]]] [128, 128] [1, 1]
+    // CHECK-NOT: memref.alloc(
+    // CHECK-NOT: memref.alloca() : memref<128x128
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+
+    // CHECK: linalg.generic
+    // CHECK-SAME: iterator_types = ["parallel", "reduction"]
+    // CHECK-SAME: ins(%[[VIEW]] :
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+
+    %acc2    = tr.add %acc, %partial
+        : !tr.tile<128xf32>
+
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+
+  // CHECK: memref.subview %[[OUT]]
+  // CHECK: memref.copy
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}

>From fb9cdf3724aba46cbb32fe89146c6e20c7eee220 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 22:45:32 -0700
Subject: [PATCH 10/29] [TileReducer] Milestone 10: tile Linalg reductions with
 scf.for

--tr-tile-linalg=tile-sizes=M,K uses TilingInterface / scf::tileUsingSCF
on linalg.generic reductions. 128x128, 64x128, and 32x128 introduce
scf.for over the parallel (row) and reduction (K) dimensions. No GPU
thread mapping.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/tile-linalg.mlir
  tr-opt --tr-tile-linalg=tile-sizes=128,128 tile-reducer/test/tile-linalg.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |  7 ++
 .../include/TileReducer/TileReducerPasses.td  | 21 +++++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |  4 +
 .../TileReducer/TileReducerLinalgTiling.cpp   | 81 +++++++++++++++++++
 tile-reducer/test/smoke.mlir                  |  2 +-
 tile-reducer/test/tile-linalg.mlir            | 49 +++++++++++
 tile-reducer/tr-opt/CMakeLists.txt            |  2 +
 tile-reducer/tr-opt/tr-opt.cpp                |  6 +-
 8 files changed, 170 insertions(+), 2 deletions(-)
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerLinalgTiling.cpp
 create mode 100644 tile-reducer/test/tile-linalg.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index 1504ec610d815..2f0a42491eb4b 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -26,3 +26,10 @@ The same pass realizes `tr.load` as `memref.subview` of the input
 (offset = tile coordinate × tile size). A 128×128 tile is not allocated.
 A 128-element alloca is used only for the accumulator / reduce destination.
 `tr.store` is a subview of the output plus `memref.copy`.
+
+## Milestone 10
+
+`--tr-tile-linalg=tile-sizes=M,K` tiles `linalg.generic` reductions with
+`scf::tileUsingSCF`. Representative sizes: 128×128, 64×128, 32×128. Outer
+`scf.for` is the parallel (row) dimension; inner is the reduction (K)
+dimension. No GPU thread mapping.
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
index 3e3c8a79793ec..4803b1b6fcb78 100644
--- a/tile-reducer/include/TileReducer/TileReducerPasses.td
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -53,6 +53,27 @@ def ConvertTRForBoundsToArith : Pass<"tr-for-bounds-to-arith", "::mlir::func::Fu
   ];
 }
 
+def TileTRLinalg : Pass<"tr-tile-linalg", "::mlir::func::FuncOp"> {
+  let summary = "Tile Linalg reductions with scf.for. No GPU mapping.";
+  let description = [{
+    Uses the TilingInterface (`scf::tileUsingSCF`) on `linalg.generic`
+    reductions. Representative tile sizes: 128x128, 64x128, 32x128.
+    Parallel and reduction dimensions are identified from iterator_types.
+    Does not map loops to GPU threads.
+  }];
+  let dependentDialects = [
+    "::mlir::linalg::LinalgDialect",
+    "::mlir::scf::SCFDialect",
+    "::mlir::affine::AffineDialect",
+    "::mlir::arith::ArithDialect",
+    "::mlir::memref::MemRefDialect"
+  ];
+  let options = [
+    ListOption<"tileSizes", "tile-sizes", "int64_t",
+               "Tile sizes per loop dimension (0 = do not tile)">
+  ];
+}
+
 def ConvertTRToLinalg : Pass<"convert-tr-to-linalg", "::mlir::func::FuncOp"> {
   let summary = "Lower tile compute to Linalg over MemRefs. Load becomes a subview.";
   let description = [{
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index c88b4972b727f..10c640af8fd74 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -5,6 +5,7 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerAnalyses.cpp
         TileReducerBufferConversion.cpp
         TileReducerLinalgConversion.cpp
+        TileReducerLinalgTiling.cpp
         TileReducerPasses.cpp
 
         ADDITIONAL_HEADER_DIRS
@@ -24,7 +25,10 @@ add_mlir_dialect_library(MLIRTileReducer
         MLIRAffineDialect
         MLIRFuncTransforms
         MLIRLinalgDialect
+        MLIRLinalgTransforms
         MLIRMemRefDialect
+        MLIRSCFDialect
+        MLIRSCFTransforms
         MLIRInferTypeOpInterface
         MLIRPass
         MLIRSideEffectInterfaces
diff --git a/tile-reducer/lib/TileReducer/TileReducerLinalgTiling.cpp b/tile-reducer/lib/TileReducer/TileReducerLinalgTiling.cpp
new file mode 100644
index 0000000000000..733174911fa98
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerLinalgTiling.cpp
@@ -0,0 +1,81 @@
+//===- TileReducerLinalgTiling.cpp - Milestone 10 ---------------*- C++ -*-===//
+//
+// Tile Linalg reductions via TilingInterface + scf::tileUsingSCF.
+// Introduces scf.for. Does not map to GPU threads.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/TileReducerPasses.h"
+
+#include "mlir/Dialect/Affine/IR/AffineOps.h"
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/Dialect/Linalg/IR/Linalg.h"
+#include "mlir/Dialect/MemRef/IR/MemRef.h"
+#include "mlir/Dialect/SCF/IR/SCF.h"
+#include "mlir/Dialect/SCF/Transforms/TileUsingInterface.h"
+#include "mlir/Dialect/Utils/StructuredOpsUtils.h"
+#include "mlir/IR/PatternMatch.h"
+#include "mlir/Interfaces/TilingInterface.h"
+
+namespace mlir::tr {
+#define GEN_PASS_DEF_TILETRLINALG
+#include "TileReducer/TileReducerPasses.h.inc"
+
+namespace {
+
+static bool isReductionGeneric(linalg::GenericOp op) {
+  return llvm::any_of(op.getIteratorTypesArray(), [](utils::IteratorType t) {
+    return t == utils::IteratorType::reduction;
+  });
+}
+
+struct TileTRLinalg : impl::TileTRLinalgBase<TileTRLinalg> {
+  using impl::TileTRLinalgBase<TileTRLinalg>::TileTRLinalgBase;
+
+  void runOnOperation() override {
+    if (tileSizes.empty())
+      return;
+
+    func::FuncOp func = getOperation();
+    SmallVector<linalg::GenericOp> targets;
+    func.walk([&](linalg::GenericOp op) {
+      if (isReductionGeneric(op))
+        targets.push_back(op);
+    });
+
+    IRRewriter rewriter(&getContext());
+    for (linalg::GenericOp op : targets) {
+      auto tilingOp = cast<TilingInterface>(op.getOperation());
+      unsigned numLoops = tilingOp.getLoopIteratorTypes().size();
+
+      SmallVector<OpFoldResult> sizes;
+      SmallVector<unsigned> reductionDims;
+      SmallVector<utils::IteratorType> iters = op.getIteratorTypesArray();
+      for (unsigned i = 0; i < numLoops; ++i) {
+        int64_t sz = i < tileSizes.size() ? tileSizes[i] : 0;
+        sizes.push_back(rewriter.getIndexAttr(sz));
+        if (sz != 0 && i < iters.size() &&
+            iters[i] == utils::IteratorType::reduction)
+          reductionDims.push_back(i);
+      }
+
+      scf::SCFTilingOptions options;
+      options.setTileSizes(sizes);
+      if (!reductionDims.empty())
+        options.setReductionDims(reductionDims);
+
+      rewriter.setInsertionPoint(op);
+      FailureOr<scf::SCFTilingResult> tiled =
+          scf::tileUsingSCF(rewriter, tilingOp, options);
+      if (failed(tiled)) {
+        op.emitError("failed to tile Linalg reduction");
+        return signalPassFailure();
+      }
+      rewriter.replaceOp(op, tiled->replacements);
+    }
+  }
+};
+
+} // namespace
+} // namespace mlir::tr
diff --git a/tile-reducer/test/smoke.mlir b/tile-reducer/test/smoke.mlir
index bd940eb28df70..cddb07d9fad5a 100644
--- a/tile-reducer/test/smoke.mlir
+++ b/tile-reducer/test/smoke.mlir
@@ -4,7 +4,7 @@
 // Milestone 1: the driver registers `tr` (plus func/arith from the canonical
 // source) and can parse a module. Types and ops are Milestone 2 / 3.
 
-// DIALECT: Available Dialects: affine,arith,builtin,func,linalg,memref,tr
+// DIALECT: Available Dialects: affine,arith,builtin,func,linalg,memref,scf,tr
 
 module {
   // CHECK-LABEL: func.func @smoke
diff --git a/tile-reducer/test/tile-linalg.mlir b/tile-reducer/test/tile-linalg.mlir
new file mode 100644
index 0000000000000..4b37059a7b9c9
--- /dev/null
+++ b/tile-reducer/test/tile-linalg.mlir
@@ -0,0 +1,49 @@
+// RUN: tr-opt %s --tr-tile-linalg=tile-sizes=128,128 | FileCheck %s --check-prefix=T128
+// RUN: tr-opt %s --tr-tile-linalg=tile-sizes=64,128 | FileCheck %s --check-prefix=T64
+// RUN: tr-opt %s --tr-tile-linalg=tile-sizes=32,128 | FileCheck %s --check-prefix=T32
+
+// Milestone 10: tile a row reduction (parallel, reduction) with scf.for.
+// Original Linalg is the function body below. No GPU thread mapping.
+//
+// iterator_types = ["parallel", "reduction"]
+//   dim 0 = parallel  (rows)
+//   dim 1 = reduction (K)
+
+#map = affine_map<(d0, d1) -> (d0, d1)>
+#map1 = affine_map<(d0, d1) -> (d0)>
+
+func.func @row(%in: memref<128x128xf32>, %out: memref<128xf32>) {
+  linalg.generic {
+      indexing_maps = [#map, #map1],
+      iterator_types = ["parallel", "reduction"]}
+    ins(%in : memref<128x128xf32>)
+    outs(%out : memref<128xf32>) {
+  ^bb0(%a: f32, %b: f32):
+    %0 = arith.addf %a, %b : f32
+    linalg.yield %0 : f32
+  }
+  return
+}
+
+// 128x128: one-trip loops on both dims. Parallel = outer, reduction = inner.
+// T128: scf.for %{{.*}} = %{{.*}} to %{{.*}} step %{{.*}}
+// T128: scf.for %{{.*}} = %{{.*}} to %{{.*}} step %{{.*}}
+// T128: memref.subview %{{.*}}[%{{.*}}, %{{.*}}] [128, 128] [1, 1]
+// T128: linalg.generic
+// T128-SAME: iterator_types = ["parallel", "reduction"]
+
+// 64x128: two tiles along the parallel (row) dimension.
+// T64: %[[C64:.*]] = arith.constant 64 : index
+// T64: scf.for %{{.*}} = %{{.*}} to %{{.*}} step %[[C64]]
+// T64: scf.for %{{.*}} = %{{.*}} to %{{.*}} step %{{.*}}
+// T64: memref.subview %{{.*}}[%{{.*}}, %{{.*}}] [64, 128] [1, 1]
+// T64: linalg.generic
+// T64-SAME: iterator_types = ["parallel", "reduction"]
+
+// 32x128: four tiles along the parallel dimension.
+// T32: %[[C32:.*]] = arith.constant 32 : index
+// T32: scf.for %{{.*}} = %{{.*}} to %{{.*}} step %[[C32]]
+// T32: scf.for %{{.*}} = %{{.*}} to %{{.*}} step %{{.*}}
+// T32: memref.subview %{{.*}}[%{{.*}}, %{{.*}}] [32, 128] [1, 1]
+// T32: linalg.generic
+// T32-SAME: iterator_types = ["parallel", "reduction"]
diff --git a/tile-reducer/tr-opt/CMakeLists.txt b/tile-reducer/tr-opt/CMakeLists.txt
index dfa854aa332ea..4c976d0844410 100644
--- a/tile-reducer/tr-opt/CMakeLists.txt
+++ b/tile-reducer/tr-opt/CMakeLists.txt
@@ -3,7 +3,9 @@ set(LIBS
     MLIRArithDialect
     MLIRFuncDialect
     MLIRLinalgDialect
+    MLIRLinalgTransforms
     MLIRMemRefDialect
+    MLIRSCFDialect
     MLIROptLib
     MLIRTileReducer
   )
diff --git a/tile-reducer/tr-opt/tr-opt.cpp b/tile-reducer/tr-opt/tr-opt.cpp
index 41bb124895902..f98659ef76a53 100644
--- a/tile-reducer/tr-opt/tr-opt.cpp
+++ b/tile-reducer/tr-opt/tr-opt.cpp
@@ -9,7 +9,9 @@
 #include "mlir/Dialect/Arith/IR/Arith.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/Dialect/Linalg/IR/Linalg.h"
+#include "mlir/Dialect/Linalg/Transforms/TilingInterfaceImpl.h"
 #include "mlir/Dialect/MemRef/IR/MemRef.h"
+#include "mlir/Dialect/SCF/IR/SCF.h"
 #include "mlir/IR/MLIRContext.h"
 #include "mlir/Tools/mlir-opt/MlirOptMain.h"
 
@@ -22,7 +24,9 @@ int main(int argc, char **argv) {
   mlir::DialectRegistry registry;
   registry.insert<mlir::tr::TileReducerDialect, mlir::affine::AffineDialect,
                   mlir::arith::ArithDialect, mlir::func::FuncDialect,
-                  mlir::linalg::LinalgDialect, mlir::memref::MemRefDialect>();
+                  mlir::linalg::LinalgDialect, mlir::memref::MemRefDialect,
+                  mlir::scf::SCFDialect>();
+  mlir::linalg::registerTilingInterfaceExternalModels(registry);
 
   return mlir::asMainReturnCode(
       mlir::MlirOptMain(argc, argv, "TileReducer optimizer driver\n", registry));

>From 086829dcd1af2458d4e6160d571ef5ef83d5265e Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 22:46:27 -0700
Subject: [PATCH 11/29] [TileReducer] Milestone 11: Transform dialect schedules

Payload IR is the computation; transform IR is the schedule.
transform/row_sum_schedule.mlir and transform/column_sum_schedule.mlir
match the Linalg reduction and apply structured.tile_using_for.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/transform-row-sum.mlir
    tile-reducer/test/transform-column-sum.mlir
  tr-opt --transform-interpreter tile-reducer/test/transform-row-sum.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |  7 ++++
 tile-reducer/test/smoke.mlir                  |  2 +-
 tile-reducer/test/transform-column-sum.mlir   | 35 ++++++++++++++++++
 tile-reducer/test/transform-row-sum.mlir      | 37 +++++++++++++++++++
 tile-reducer/tr-opt/CMakeLists.txt            |  4 ++
 tile-reducer/tr-opt/tr-opt.cpp                |  9 ++++-
 .../transform/column_sum_schedule.mlir        | 13 +++++++
 tile-reducer/transform/row_sum_schedule.mlir  | 13 +++++++
 8 files changed, 118 insertions(+), 2 deletions(-)
 create mode 100644 tile-reducer/test/transform-column-sum.mlir
 create mode 100644 tile-reducer/test/transform-row-sum.mlir
 create mode 100644 tile-reducer/transform/column_sum_schedule.mlir
 create mode 100644 tile-reducer/transform/row_sum_schedule.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index 2f0a42491eb4b..ac915ebcf1d9e 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -33,3 +33,10 @@ A 128-element alloca is used only for the accumulator / reduce destination.
 `scf::tileUsingSCF`. Representative sizes: 128×128, 64×128, 32×128. Outer
 `scf.for` is the parallel (row) dimension; inner is the reduction (K)
 dimension. No GPU thread mapping.
+
+## Milestone 11
+
+Transform dialect schedules in `transform/row_sum_schedule.mlir` and
+`transform/column_sum_schedule.mlir`. Payload IR is the computation;
+transform IR is the schedule. `transform.structured.match` +
+`transform.structured.tile_using_for` tile the Linalg reduction.
diff --git a/tile-reducer/test/smoke.mlir b/tile-reducer/test/smoke.mlir
index cddb07d9fad5a..f7d9a4d5aebe2 100644
--- a/tile-reducer/test/smoke.mlir
+++ b/tile-reducer/test/smoke.mlir
@@ -4,7 +4,7 @@
 // Milestone 1: the driver registers `tr` (plus func/arith from the canonical
 // source) and can parse a module. Types and ops are Milestone 2 / 3.
 
-// DIALECT: Available Dialects: affine,arith,builtin,func,linalg,memref,scf,tr
+// DIALECT: Available Dialects: affine,arith,builtin,func,linalg,memref,scf,tr,transform
 
 module {
   // CHECK-LABEL: func.func @smoke
diff --git a/tile-reducer/test/transform-column-sum.mlir b/tile-reducer/test/transform-column-sum.mlir
new file mode 100644
index 0000000000000..56d781b49576a
--- /dev/null
+++ b/tile-reducer/test/transform-column-sum.mlir
@@ -0,0 +1,35 @@
+// RUN: tr-opt %s --transform-interpreter | FileCheck %s
+
+#map = affine_map<(d0, d1) -> (d0, d1)>
+#map1 = affine_map<(d0, d1) -> (d1)>
+
+func.func @column(%in: memref<128x128xf32>, %out: memref<128xf32>) {
+  linalg.generic {
+      indexing_maps = [#map, #map1],
+      iterator_types = ["reduction", "parallel"]}
+    ins(%in : memref<128x128xf32>)
+    outs(%out : memref<128xf32>) {
+  ^bb0(%a: f32, %b: f32):
+    %0 = arith.addf %a, %b : f32
+    linalg.yield %0 : f32
+  }
+  return
+}
+
+module attributes {transform.with_named_sequence} {
+  transform.named_sequence @__transform_main(
+      %arg0: !transform.any_op {transform.readonly}) {
+    %red = transform.structured.match ops{["linalg.generic"]} in %arg0
+        : (!transform.any_op) -> !transform.any_op
+    %tiled, %loop = transform.structured.tile_using_for %red tile_sizes [0, 64]
+        : (!transform.any_op) -> (!transform.any_op, !transform.any_op)
+    transform.yield
+  }
+}
+
+// CHECK-LABEL: func.func @column
+// CHECK: %[[C64:.*]] = arith.constant 64 : index
+// CHECK: scf.for %{{.*}} = %{{.*}} to %{{.*}} step %[[C64]]
+// CHECK: memref.subview
+// CHECK: linalg.generic
+// CHECK-SAME: iterator_types = ["reduction", "parallel"]
diff --git a/tile-reducer/test/transform-row-sum.mlir b/tile-reducer/test/transform-row-sum.mlir
new file mode 100644
index 0000000000000..464e52fed2600
--- /dev/null
+++ b/tile-reducer/test/transform-row-sum.mlir
@@ -0,0 +1,37 @@
+// RUN: tr-opt %s --transform-interpreter | FileCheck %s
+
+// Milestone 11: payload IR is the computation; transform IR is the schedule.
+
+#map = affine_map<(d0, d1) -> (d0, d1)>
+#map1 = affine_map<(d0, d1) -> (d0)>
+
+func.func @row(%in: memref<128x128xf32>, %out: memref<128xf32>) {
+  linalg.generic {
+      indexing_maps = [#map, #map1],
+      iterator_types = ["parallel", "reduction"]}
+    ins(%in : memref<128x128xf32>)
+    outs(%out : memref<128xf32>) {
+  ^bb0(%a: f32, %b: f32):
+    %0 = arith.addf %a, %b : f32
+    linalg.yield %0 : f32
+  }
+  return
+}
+
+module attributes {transform.with_named_sequence} {
+  transform.named_sequence @__transform_main(
+      %arg0: !transform.any_op {transform.readonly}) {
+    %red = transform.structured.match ops{["linalg.generic"]} in %arg0
+        : (!transform.any_op) -> !transform.any_op
+    %tiled, %loop = transform.structured.tile_using_for %red tile_sizes [64, 0]
+        : (!transform.any_op) -> (!transform.any_op, !transform.any_op)
+    transform.yield
+  }
+}
+
+// CHECK-LABEL: func.func @row
+// CHECK: %[[C64:.*]] = arith.constant 64 : index
+// CHECK: scf.for %{{.*}} = %{{.*}} to %{{.*}} step %[[C64]]
+// CHECK: memref.subview %{{.*}}[%{{.*}}, 0] [64, 128] [1, 1]
+// CHECK: linalg.generic
+// CHECK-SAME: iterator_types = ["parallel", "reduction"]
diff --git a/tile-reducer/tr-opt/CMakeLists.txt b/tile-reducer/tr-opt/CMakeLists.txt
index 4c976d0844410..fb420bc8bba84 100644
--- a/tile-reducer/tr-opt/CMakeLists.txt
+++ b/tile-reducer/tr-opt/CMakeLists.txt
@@ -2,10 +2,14 @@ set(LIBS
     MLIRAffineDialect
     MLIRArithDialect
     MLIRFuncDialect
+    MLIRFuncInlinerExtension
     MLIRLinalgDialect
+    MLIRLinalgTransformOps
     MLIRLinalgTransforms
     MLIRMemRefDialect
     MLIRSCFDialect
+    MLIRTransformDialect
+    MLIRTransformDialectTransforms
     MLIROptLib
     MLIRTileReducer
   )
diff --git a/tile-reducer/tr-opt/tr-opt.cpp b/tile-reducer/tr-opt/tr-opt.cpp
index f98659ef76a53..679ef7baf8ca7 100644
--- a/tile-reducer/tr-opt/tr-opt.cpp
+++ b/tile-reducer/tr-opt/tr-opt.cpp
@@ -7,11 +7,15 @@
 
 #include "mlir/Dialect/Affine/IR/AffineOps.h"
 #include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/Func/Extensions/InlinerExtension.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/Dialect/Linalg/IR/Linalg.h"
+#include "mlir/Dialect/Linalg/TransformOps/DialectExtension.h"
 #include "mlir/Dialect/Linalg/Transforms/TilingInterfaceImpl.h"
 #include "mlir/Dialect/MemRef/IR/MemRef.h"
 #include "mlir/Dialect/SCF/IR/SCF.h"
+#include "mlir/Dialect/Transform/IR/TransformDialect.h"
+#include "mlir/Dialect/Transform/Transforms/Passes.h"
 #include "mlir/IR/MLIRContext.h"
 #include "mlir/Tools/mlir-opt/MlirOptMain.h"
 
@@ -20,13 +24,16 @@
 
 int main(int argc, char **argv) {
   mlir::tr::registerPasses();
+  mlir::transform::registerTransformPasses();
 
   mlir::DialectRegistry registry;
   registry.insert<mlir::tr::TileReducerDialect, mlir::affine::AffineDialect,
                   mlir::arith::ArithDialect, mlir::func::FuncDialect,
                   mlir::linalg::LinalgDialect, mlir::memref::MemRefDialect,
-                  mlir::scf::SCFDialect>();
+                  mlir::scf::SCFDialect, mlir::transform::TransformDialect>();
+  mlir::func::registerInlinerExtension(registry);
   mlir::linalg::registerTilingInterfaceExternalModels(registry);
+  mlir::linalg::registerTransformDialectExtension(registry);
 
   return mlir::asMainReturnCode(
       mlir::MlirOptMain(argc, argv, "TileReducer optimizer driver\n", registry));
diff --git a/tile-reducer/transform/column_sum_schedule.mlir b/tile-reducer/transform/column_sum_schedule.mlir
new file mode 100644
index 0000000000000..810fe4b477bc8
--- /dev/null
+++ b/tile-reducer/transform/column_sum_schedule.mlir
@@ -0,0 +1,13 @@
+// Schedule only. Payload IR is the computation; this file is the schedule.
+
+module attributes {transform.with_named_sequence} {
+  transform.named_sequence @column_sum_schedule(
+      %payload: !transform.any_op {transform.readonly}) {
+    %red = transform.structured.match ops{["linalg.generic"]} in %payload
+        : (!transform.any_op) -> !transform.any_op
+    // Column reduction: iterators [reduction, parallel]. Tile the parallel dim.
+    %tiled, %loop = transform.structured.tile_using_for %red tile_sizes [0, 64]
+        : (!transform.any_op) -> (!transform.any_op, !transform.any_op)
+    transform.yield
+  }
+}
diff --git a/tile-reducer/transform/row_sum_schedule.mlir b/tile-reducer/transform/row_sum_schedule.mlir
new file mode 100644
index 0000000000000..d283ccce5eba8
--- /dev/null
+++ b/tile-reducer/transform/row_sum_schedule.mlir
@@ -0,0 +1,13 @@
+// Schedule only. Payload IR is the computation; this file is the schedule.
+// Applied with --transform-preload-library + --transform-interpreter.
+
+module attributes {transform.with_named_sequence} {
+  transform.named_sequence @row_sum_schedule(
+      %payload: !transform.any_op {transform.readonly}) {
+    %red = transform.structured.match ops{["linalg.generic"]} in %payload
+        : (!transform.any_op) -> !transform.any_op
+    %tiled, %loop = transform.structured.tile_using_for %red tile_sizes [64, 0]
+        : (!transform.any_op) -> (!transform.any_op, !transform.any_op)
+    transform.yield
+  }
+}

>From 292793d4cf81ea57b9cdcbd24050540244176b1e Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 22:47:26 -0700
Subject: [PATCH 12/29] [TileReducer] Milestone 12: named Transform sequences
 and symbols

Public @row_sum_schedule includes private @tile_row_reduction via
transform.include (SymbolRefAttr / SymbolTable lookup). Entry point
selection uses --transform-interpreter=entry-point=. A missing symbol
is a hard lookup failure.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/named-schedule.mlir
    tile-reducer/test/named-schedule-include.mlir
    tile-reducer/test/named-schedule-invalid.mlir
  tr-opt --transform-interpreter=entry-point=row_sum_schedule tile-reducer/test/named-schedule.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |  8 +++
 tile-reducer/test/named-schedule-include.mlir | 51 +++++++++++++++++++
 tile-reducer/test/named-schedule-invalid.mlir | 16 ++++++
 tile-reducer/test/named-schedule.mlir         | 28 ++++++++++
 tile-reducer/transform/row_sum_schedule.mlir  | 13 +++--
 5 files changed, 113 insertions(+), 3 deletions(-)
 create mode 100644 tile-reducer/test/named-schedule-include.mlir
 create mode 100644 tile-reducer/test/named-schedule-invalid.mlir
 create mode 100644 tile-reducer/test/named-schedule.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index ac915ebcf1d9e..b675e7f7a958b 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -40,3 +40,11 @@ Transform dialect schedules in `transform/row_sum_schedule.mlir` and
 `transform/column_sum_schedule.mlir`. Payload IR is the computation;
 transform IR is the schedule. `transform.structured.match` +
 `transform.structured.tile_using_for` tile the Linalg reduction.
+
+## Milestone 12
+
+Named schedule `@row_sum_schedule` is a public symbol. It includes private
+`@tile_row_reduction` via `transform.include` (`SymbolRefAttr` lookup in a
+`SymbolTable` with `transform.with_named_sequence`). Entry point selection
+uses `--transform-interpreter=entry-point=row_sum_schedule`. A missing
+symbol is a hard lookup failure.
diff --git a/tile-reducer/test/named-schedule-include.mlir b/tile-reducer/test/named-schedule-include.mlir
new file mode 100644
index 0000000000000..9bcbb34962776
--- /dev/null
+++ b/tile-reducer/test/named-schedule-include.mlir
@@ -0,0 +1,51 @@
+// RUN: tr-opt %s --transform-interpreter | FileCheck %s
+// RUN: tr-opt %s --transform-interpreter=entry-point=row_sum_schedule | FileCheck %s
+
+// Milestone 12: in-module SymbolRefAttr lookup and visibility.
+// @__transform_main and @row_sum_schedule both include private @tile_row.
+
+#map = affine_map<(d0, d1) -> (d0, d1)>
+#map1 = affine_map<(d0, d1) -> (d0)>
+
+func.func @row(%in: memref<128x128xf32>, %out: memref<128xf32>) {
+  linalg.generic {
+      indexing_maps = [#map, #map1],
+      iterator_types = ["parallel", "reduction"]}
+    ins(%in : memref<128x128xf32>)
+    outs(%out : memref<128xf32>) {
+  ^bb0(%a: f32, %b: f32):
+    %0 = arith.addf %a, %b : f32
+    linalg.yield %0 : f32
+  }
+  return
+}
+
+module attributes {transform.with_named_sequence} {
+  transform.named_sequence private @tile_row(
+      %payload: !transform.any_op {transform.readonly}) {
+    %red = transform.structured.match ops{["linalg.generic"]} in %payload
+        : (!transform.any_op) -> !transform.any_op
+    %tiled, %loop = transform.structured.tile_using_for %red tile_sizes [64, 0]
+        : (!transform.any_op) -> (!transform.any_op, !transform.any_op)
+    transform.yield
+  }
+
+  transform.named_sequence @row_sum_schedule(
+      %payload: !transform.any_op {transform.readonly}) {
+    transform.include @tile_row failures(propagate) (%payload)
+        : (!transform.any_op) -> ()
+    transform.yield
+  }
+
+  transform.named_sequence @__transform_main(
+      %payload: !transform.any_op {transform.readonly}) {
+    transform.include @row_sum_schedule failures(propagate) (%payload)
+        : (!transform.any_op) -> ()
+    transform.yield
+  }
+}
+
+// CHECK-LABEL: func.func @row
+// CHECK: scf.for
+// CHECK: linalg.generic
+// CHECK-SAME: iterator_types = ["parallel", "reduction"]
diff --git a/tile-reducer/test/named-schedule-invalid.mlir b/tile-reducer/test/named-schedule-invalid.mlir
new file mode 100644
index 0000000000000..e998307ebc304
--- /dev/null
+++ b/tile-reducer/test/named-schedule-invalid.mlir
@@ -0,0 +1,16 @@
+// RUN: not tr-opt %s --transform-interpreter=entry-point=missing_schedule 2>&1 | FileCheck %s
+
+// Symbol lookup failure: entry point is not in the symbol table.
+
+func.func @row() {
+  return
+}
+
+module attributes {transform.with_named_sequence} {
+  transform.named_sequence @row_sum_schedule(
+      %payload: !transform.any_op {transform.readonly}) {
+    transform.yield
+  }
+}
+
+// CHECK: could not find a nested named sequence with name: missing_schedule
diff --git a/tile-reducer/test/named-schedule.mlir b/tile-reducer/test/named-schedule.mlir
new file mode 100644
index 0000000000000..df334058186b3
--- /dev/null
+++ b/tile-reducer/test/named-schedule.mlir
@@ -0,0 +1,28 @@
+// RUN: tr-opt %s --transform-preload-library=transform-library-paths=%S/../transform/row_sum_schedule.mlir --transform-interpreter=entry-point=row_sum_schedule | FileCheck %s
+
+// Milestone 12: named sequence symbol lookup.
+//   - @row_sum_schedule is a public SymbolRefAttr entry point
+//   - it includes private @tile_row_reduction (same symbol table)
+//   - --transform-interpreter=entry-point=row_sum_schedule does the lookup
+
+#map = affine_map<(d0, d1) -> (d0, d1)>
+#map1 = affine_map<(d0, d1) -> (d0)>
+
+func.func @row(%in: memref<128x128xf32>, %out: memref<128xf32>) {
+  linalg.generic {
+      indexing_maps = [#map, #map1],
+      iterator_types = ["parallel", "reduction"]}
+    ins(%in : memref<128x128xf32>)
+    outs(%out : memref<128xf32>) {
+  ^bb0(%a: f32, %b: f32):
+    %0 = arith.addf %a, %b : f32
+    linalg.yield %0 : f32
+  }
+  return
+}
+
+// CHECK-LABEL: func.func @row
+// CHECK: scf.for %{{.*}} = %{{.*}} to %{{.*}} step %{{.*}}
+// CHECK: memref.subview %{{.*}}[%{{.*}}, 0] [64, 128] [1, 1]
+// CHECK: linalg.generic
+// CHECK-SAME: iterator_types = ["parallel", "reduction"]
diff --git a/tile-reducer/transform/row_sum_schedule.mlir b/tile-reducer/transform/row_sum_schedule.mlir
index d283ccce5eba8..8ba45554ee872 100644
--- a/tile-reducer/transform/row_sum_schedule.mlir
+++ b/tile-reducer/transform/row_sum_schedule.mlir
@@ -1,8 +1,8 @@
-// Schedule only. Payload IR is the computation; this file is the schedule.
-// Applied with --transform-preload-library + --transform-interpreter.
+// Named schedule. Public @row_sum_schedule looks up private @tile_row_reduction
+// via SymbolRefAttr (transform.include).
 
 module attributes {transform.with_named_sequence} {
-  transform.named_sequence @row_sum_schedule(
+  transform.named_sequence private @tile_row_reduction(
       %payload: !transform.any_op {transform.readonly}) {
     %red = transform.structured.match ops{["linalg.generic"]} in %payload
         : (!transform.any_op) -> !transform.any_op
@@ -10,4 +10,11 @@ module attributes {transform.with_named_sequence} {
         : (!transform.any_op) -> (!transform.any_op, !transform.any_op)
     transform.yield
   }
+
+  transform.named_sequence @row_sum_schedule(
+      %payload: !transform.any_op {transform.readonly}) {
+    transform.include @tile_row_reduction failures(propagate) (%payload)
+        : (!transform.any_op) -> ()
+    transform.yield
+  }
 }

>From da7b4cb075f508d91129b5f0fd93c50817b48d40 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 22:48:42 -0700
Subject: [PATCH 13/29] [TileReducer] Milestone 13:
 transform.tr.map_row_reduction

Custom Transform extension that takes a payload handle, checks the op
is a row-reduction linalg.generic, and annotates the 8-warp / 32-lane /
4-elem physical map. Silenceable diagnostics for wrong payload ops;
verifier rejects non-positive parameters.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/transform-map-row-reduction.mlir
    tile-reducer/test/transform-map-row-reduction-invalid.mlir
  tr-opt --transform-interpreter tile-reducer/test/transform-map-row-reduction.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |   7 ++
 .../include/TileReducer/CMakeLists.txt        |   5 +
 .../TileReducer/TileReducerTransformOps.h     |  23 ++++
 .../TileReducer/TileReducerTransformOps.td    |  44 ++++++++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |   3 +
 .../TileReducer/TileReducerTransformOps.cpp   | 104 ++++++++++++++++++
 .../transform-map-row-reduction-invalid.mlir  |  72 ++++++++++++
 .../test/transform-map-row-reduction.mlir     |  37 +++++++
 tile-reducer/tr-opt/tr-opt.cpp                |   2 +
 9 files changed, 297 insertions(+)
 create mode 100644 tile-reducer/include/TileReducer/TileReducerTransformOps.h
 create mode 100644 tile-reducer/include/TileReducer/TileReducerTransformOps.td
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerTransformOps.cpp
 create mode 100644 tile-reducer/test/transform-map-row-reduction-invalid.mlir
 create mode 100644 tile-reducer/test/transform-map-row-reduction.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index b675e7f7a958b..62ef74b827a4d 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -48,3 +48,10 @@ Named schedule `@row_sum_schedule` is a public symbol. It includes private
 `SymbolTable` with `transform.with_named_sequence`). Entry point selection
 uses `--transform-interpreter=entry-point=row_sum_schedule`. A missing
 symbol is a hard lookup failure.
+
+## Milestone 13
+
+`transform.tr.map_row_reduction` is a custom Transform extension. It takes a
+handle, checks the payload is a row-reduction `linalg.generic`, and annotates
+`tr.warps_per_block=8`, `tr.warp_size=32`, `tr.elements_per_lane=4`. Wrong
+payload ops produce a silenceable diagnostic.
diff --git a/tile-reducer/include/TileReducer/CMakeLists.txt b/tile-reducer/include/TileReducer/CMakeLists.txt
index b53ce90c415cb..3ae50b777f21e 100644
--- a/tile-reducer/include/TileReducer/CMakeLists.txt
+++ b/tile-reducer/include/TileReducer/CMakeLists.txt
@@ -4,3 +4,8 @@ add_mlir_doc(TileReducerDialect TileReducerDialect TileReducer/ -gen-dialect-doc
 set(LLVM_TARGET_DEFINITIONS TileReducerPasses.td)
 mlir_tablegen(TileReducerPasses.h.inc --gen-pass-decls)
 add_public_tablegen_target(MLIRTileReducerPassesIncGen)
+
+set(LLVM_TARGET_DEFINITIONS TileReducerTransformOps.td)
+mlir_tablegen(TileReducerTransformOps.h.inc -gen-op-decls)
+mlir_tablegen(TileReducerTransformOps.cpp.inc -gen-op-defs)
+add_public_tablegen_target(MLIRTileReducerTransformOpsIncGen)
diff --git a/tile-reducer/include/TileReducer/TileReducerTransformOps.h b/tile-reducer/include/TileReducer/TileReducerTransformOps.h
new file mode 100644
index 0000000000000..4d99233bd3032
--- /dev/null
+++ b/tile-reducer/include/TileReducer/TileReducerTransformOps.h
@@ -0,0 +1,23 @@
+//===- TileReducerTransformOps.h - transform.tr.* ---------------*- C++ -*-===//
+
+#ifndef TILE_REDUCER_TILEREDUCERTRANSFORMOPS_H
+#define TILE_REDUCER_TILEREDUCERTRANSFORMOPS_H
+
+#include "mlir/Bytecode/BytecodeOpInterface.h"
+#include "mlir/Dialect/Transform/IR/TransformDialect.h"
+#include "mlir/Dialect/Transform/Interfaces/TransformInterfaces.h"
+#include "mlir/IR/OpDefinition.h"
+#include "mlir/IR/OpImplementation.h"
+#include "mlir/Interfaces/SideEffectInterfaces.h"
+
+#define GET_OP_CLASSES
+#include "TileReducer/TileReducerTransformOps.h.inc"
+
+namespace mlir {
+class DialectRegistry;
+namespace tr {
+void registerTransformDialectExtension(DialectRegistry &registry);
+} // namespace tr
+} // namespace mlir
+
+#endif // TILE_REDUCER_TILEREDUCERTRANSFORMOPS_H
diff --git a/tile-reducer/include/TileReducer/TileReducerTransformOps.td b/tile-reducer/include/TileReducer/TileReducerTransformOps.td
new file mode 100644
index 0000000000000..3f66dbbdd037c
--- /dev/null
+++ b/tile-reducer/include/TileReducer/TileReducerTransformOps.td
@@ -0,0 +1,44 @@
+//===- TileReducerTransformOps.td - transform.tr.* ---------*- tablegen -*-===//
+//
+// Milestone 13: custom Transform dialect extension.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef TILE_REDUCER_TRANSFORM_OPS
+#define TILE_REDUCER_TRANSFORM_OPS
+
+include "mlir/Dialect/Transform/IR/TransformDialect.td"
+include "mlir/Dialect/Transform/IR/TransformTypes.td"
+include "mlir/Dialect/Transform/Interfaces/TransformInterfaces.td"
+include "mlir/IR/OpBase.td"
+include "mlir/Interfaces/SideEffectInterfaces.td"
+
+def MapRowReductionOp : TransformDialectOp<"tr.map_row_reduction", [
+    DeclareOpInterfaceMethods<TransformOpInterface>,
+    DeclareOpInterfaceMethods<MemoryEffectsOpInterface>]> {
+  let summary = "Annotate a row reduction with the 8-warp physical map.";
+  let description = [{
+    Operates on a handle to payload `linalg.generic` ops. Validates that each
+    payload op is a row reduction (`parallel, reduction`) and annotates it
+    with the baseline physical map:
+
+      warps_per_block    = 8
+      warp_size          = 32
+      elements_per_lane  = 4
+
+    8 warps x 16 rows = 128 rows; 32 lanes x 4 elems = 128 columns.
+    Does not emit GPU thread IDs. Silenceable failure if the handle does not
+    point at a row-reduction generic.
+  }];
+  let arguments = (ins
+    TransformHandleTypeInterface:$target,
+    DefaultValuedAttr<I64Attr, "8">:$warps_per_block,
+    DefaultValuedAttr<I64Attr, "32">:$warp_size,
+    DefaultValuedAttr<I64Attr, "4">:$elements_per_lane
+  );
+  let results = (outs TransformHandleTypeInterface:$result);
+  let assemblyFormat = "$target attr-dict `:` functional-type(operands, results)";
+  let hasVerifier = 1;
+}
+
+#endif // TILE_REDUCER_TRANSFORM_OPS
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index 10c640af8fd74..1234dd9085a31 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -6,6 +6,7 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerBufferConversion.cpp
         TileReducerLinalgConversion.cpp
         TileReducerLinalgTiling.cpp
+        TileReducerTransformOps.cpp
         TileReducerPasses.cpp
 
         ADDITIONAL_HEADER_DIRS
@@ -14,6 +15,7 @@ add_mlir_dialect_library(MLIRTileReducer
         DEPENDS
         MLIRTileReducerOpsIncGen
         MLIRTileReducerPassesIncGen
+        MLIRTileReducerTransformOpsIncGen
 
         LINK_LIBS PUBLIC
         MLIRIR
@@ -29,6 +31,7 @@ add_mlir_dialect_library(MLIRTileReducer
         MLIRMemRefDialect
         MLIRSCFDialect
         MLIRSCFTransforms
+        MLIRTransformDialect
         MLIRInferTypeOpInterface
         MLIRPass
         MLIRSideEffectInterfaces
diff --git a/tile-reducer/lib/TileReducer/TileReducerTransformOps.cpp b/tile-reducer/lib/TileReducer/TileReducerTransformOps.cpp
new file mode 100644
index 0000000000000..826b280da796a
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerTransformOps.cpp
@@ -0,0 +1,104 @@
+//===- TileReducerTransformOps.cpp - Milestone 13 ---------------*- C++ -*-===//
+//
+// Custom Transform extension: transform.tr.map_row_reduction.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/TileReducerTransformOps.h"
+
+#include "mlir/Dialect/Linalg/IR/Linalg.h"
+#include "mlir/Dialect/Transform/IR/TransformDialect.h"
+#include "mlir/Dialect/Utils/StructuredOpsUtils.h"
+#include "mlir/IR/DialectRegistry.h"
+#include "mlir/IR/PatternMatch.h"
+
+using namespace mlir;
+
+#define GET_OP_CLASSES
+#include "TileReducer/TileReducerTransformOps.cpp.inc"
+
+namespace {
+
+class TileReducerTransformDialectExtension
+    : public transform::TransformDialectExtension<
+          TileReducerTransformDialectExtension> {
+public:
+  MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(
+      TileReducerTransformDialectExtension)
+
+  void init() {
+    declareGeneratedDialect<linalg::LinalgDialect>();
+    registerTransformOps<
+#define GET_OP_LIST
+#include "TileReducer/TileReducerTransformOps.cpp.inc"
+        >();
+  }
+};
+
+} // namespace
+
+void mlir::tr::registerTransformDialectExtension(DialectRegistry &registry) {
+  registry.addExtensions<TileReducerTransformDialectExtension>();
+}
+
+LogicalResult transform::MapRowReductionOp::verify() {
+  if (getWarpsPerBlock() <= 0 || getWarpSize() <= 0 ||
+      getElementsPerLane() <= 0)
+    return emitOpError("mapping parameters must be positive");
+  return success();
+}
+
+void transform::MapRowReductionOp::getEffects(
+    SmallVectorImpl<MemoryEffects::EffectInstance> &effects) {
+  transform::onlyReadsHandle(getTargetMutable(), effects);
+  transform::producesHandle(getOperation()->getOpResults(), effects);
+  transform::modifiesPayload(effects);
+}
+
+DiagnosedSilenceableFailure transform::MapRowReductionOp::apply(
+    transform::TransformRewriter &rewriter, transform::TransformResults &results,
+    transform::TransformState &state) {
+  SmallVector<Operation *> payload =
+      llvm::to_vector(state.getPayloadOps(getTarget()));
+  if (payload.empty())
+    return emitSilenceableError() << "expected at least one payload op";
+
+  int64_t warps = getWarpsPerBlock();
+  int64_t warpSize = getWarpSize();
+  int64_t elems = getElementsPerLane();
+
+  for (Operation *op : payload) {
+    auto generic = dyn_cast<linalg::GenericOp>(op);
+    if (!generic)
+      return emitSilenceableError() << "expected linalg.generic, got "
+                                    << op->getName();
+
+    SmallVector<utils::IteratorType> iters = generic.getIteratorTypesArray();
+    if (iters.size() != 2 || iters[0] != utils::IteratorType::parallel ||
+        iters[1] != utils::IteratorType::reduction)
+      return emitSilenceableError()
+             << "expected row reduction (iterator_types = "
+                "[\"parallel\", \"reduction\"])";
+
+    if (!generic.getInputs().empty()) {
+      if (auto shaped =
+              dyn_cast<ShapedType>(generic.getInputs().front().getType())) {
+        if (shaped.hasRank() && shaped.getRank() >= 1 &&
+            shaped.hasStaticShape() &&
+            shaped.getDimSize(0) % warps != 0)
+          return emitSilenceableError()
+                 << "parallel extent " << shaped.getDimSize(0)
+                 << " is not divisible by warps_per_block " << warps;
+      }
+    }
+
+    rewriter.modifyOpInPlace(generic, [&] {
+      generic->setAttr("tr.warps_per_block", rewriter.getI64IntegerAttr(warps));
+      generic->setAttr("tr.warp_size", rewriter.getI64IntegerAttr(warpSize));
+      generic->setAttr("tr.elements_per_lane", rewriter.getI64IntegerAttr(elems));
+    });
+  }
+
+  results.set(llvm::cast<OpResult>(getResult()), payload);
+  return DiagnosedSilenceableFailure::success();
+}
diff --git a/tile-reducer/test/transform-map-row-reduction-invalid.mlir b/tile-reducer/test/transform-map-row-reduction-invalid.mlir
new file mode 100644
index 0000000000000..a411bd66a0dc1
--- /dev/null
+++ b/tile-reducer/test/transform-map-row-reduction-invalid.mlir
@@ -0,0 +1,72 @@
+// RUN: tr-opt %s --transform-interpreter --verify-diagnostics --split-input-file
+
+// Silenceable failure: column reduction is not a row reduction.
+
+#map = affine_map<(d0, d1) -> (d0, d1)>
+#map1 = affine_map<(d0, d1) -> (d1)>
+
+func.func @column(%in: memref<128x128xf32>, %out: memref<128xf32>) {
+  linalg.generic {
+      indexing_maps = [#map, #map1],
+      iterator_types = ["reduction", "parallel"]}
+    ins(%in : memref<128x128xf32>)
+    outs(%out : memref<128xf32>) {
+  ^bb0(%a: f32, %b: f32):
+    %0 = arith.addf %a, %b : f32
+    linalg.yield %0 : f32
+  }
+  return
+}
+
+module attributes {transform.with_named_sequence} {
+  transform.named_sequence @__transform_main(
+      %arg0: !transform.any_op {transform.readonly}) {
+    %red = transform.structured.match ops{["linalg.generic"]} in %arg0
+        : (!transform.any_op) -> !transform.any_op
+    // expected-error @below {{expected row reduction}}
+    %mapped = transform.tr.map_row_reduction %red
+        : (!transform.any_op) -> !transform.any_op
+    transform.yield
+  }
+}
+
+// -----
+
+// Silenceable failure: handle is not a linalg.generic.
+
+func.func @not_generic(%in: memref<128xf32>, %out: memref<128xf32>) {
+  linalg.copy ins(%in : memref<128xf32>) outs(%out : memref<128xf32>)
+  return
+}
+
+module attributes {transform.with_named_sequence} {
+  transform.named_sequence @__transform_main(
+      %arg0: !transform.any_op {transform.readonly}) {
+    %copy = transform.structured.match ops{["linalg.copy"]} in %arg0
+        : (!transform.any_op) -> !transform.any_op
+    // expected-error @below {{expected linalg.generic}}
+    %mapped = transform.tr.map_row_reduction %copy
+        : (!transform.any_op) -> !transform.any_op
+    transform.yield
+  }
+}
+
+// -----
+
+// Verifier: mapping parameters must be positive.
+
+func.func @empty() {
+  return
+}
+
+module attributes {transform.with_named_sequence} {
+  transform.named_sequence @__transform_main(
+      %arg0: !transform.any_op {transform.readonly}) {
+    %red = transform.structured.match ops{["linalg.generic"]} in %arg0
+        : (!transform.any_op) -> !transform.any_op
+    // expected-error @below {{mapping parameters must be positive}}
+    %mapped = transform.tr.map_row_reduction %red {warps_per_block = 0 : i64}
+        : (!transform.any_op) -> !transform.any_op
+    transform.yield
+  }
+}
diff --git a/tile-reducer/test/transform-map-row-reduction.mlir b/tile-reducer/test/transform-map-row-reduction.mlir
new file mode 100644
index 0000000000000..f14ac9b33f030
--- /dev/null
+++ b/tile-reducer/test/transform-map-row-reduction.mlir
@@ -0,0 +1,37 @@
+// RUN: tr-opt %s --transform-interpreter | FileCheck %s
+
+// Milestone 13: custom transform.tr.map_row_reduction annotates the
+// baseline 8-warp / 32-lane / 4-elem map. No GPU thread IDs yet.
+
+#map = affine_map<(d0, d1) -> (d0, d1)>
+#map1 = affine_map<(d0, d1) -> (d0)>
+
+func.func @row(%in: memref<128x128xf32>, %out: memref<128xf32>) {
+  linalg.generic {
+      indexing_maps = [#map, #map1],
+      iterator_types = ["parallel", "reduction"]}
+    ins(%in : memref<128x128xf32>)
+    outs(%out : memref<128xf32>) {
+  ^bb0(%a: f32, %b: f32):
+    %0 = arith.addf %a, %b : f32
+    linalg.yield %0 : f32
+  }
+  return
+}
+
+module attributes {transform.with_named_sequence} {
+  transform.named_sequence @__transform_main(
+      %arg0: !transform.any_op {transform.readonly}) {
+    %red = transform.structured.match ops{["linalg.generic"]} in %arg0
+        : (!transform.any_op) -> !transform.any_op
+    %mapped = transform.tr.map_row_reduction %red
+        : (!transform.any_op) -> !transform.any_op
+    transform.yield
+  }
+}
+
+// CHECK-LABEL: func.func @row
+// CHECK: linalg.generic
+// CHECK-SAME: tr.elements_per_lane = 4
+// CHECK-SAME: tr.warp_size = 32
+// CHECK-SAME: tr.warps_per_block = 8
diff --git a/tile-reducer/tr-opt/tr-opt.cpp b/tile-reducer/tr-opt/tr-opt.cpp
index 679ef7baf8ca7..1e7a7f9adb0bb 100644
--- a/tile-reducer/tr-opt/tr-opt.cpp
+++ b/tile-reducer/tr-opt/tr-opt.cpp
@@ -21,6 +21,7 @@
 
 #include "TileReducer/TileReducerDialect.h"
 #include "TileReducer/TileReducerPasses.h"
+#include "TileReducer/TileReducerTransformOps.h"
 
 int main(int argc, char **argv) {
   mlir::tr::registerPasses();
@@ -34,6 +35,7 @@ int main(int argc, char **argv) {
   mlir::func::registerInlinerExtension(registry);
   mlir::linalg::registerTilingInterfaceExternalModels(registry);
   mlir::linalg::registerTransformDialectExtension(registry);
+  mlir::tr::registerTransformDialectExtension(registry);
 
   return mlir::asMainReturnCode(
       mlir::MlirOptMain(argc, argv, "TileReducer optimizer driver\n", registry));

>From be8bb948a98dc87d686c1518fe68019118068dce Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 22:53:40 -0700
Subject: [PATCH 14/29] [TileReducer] Milestone 14: raise affine index math to
 affine.apply

--tr-index-to-affine converts constant-coefficient index muli/addi to
affine.apply. Demonstrates rowBase = programId*128, globalRow =
programId*128+localRow, globalCol = kt*128+lane+j*32. A product of two
SSA values is not affine. affine.for is used only for constant-bound
local-row walks.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/index-to-affine.mlir
  tr-opt --tr-index-to-affine tile-reducer/test/index-to-affine.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |  7 ++
 .../include/TileReducer/TileReducerPasses.td  | 35 +++++++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |  4 +
 .../lib/TileReducer/TileReducerAffine.cpp     | 99 +++++++++++++++++++
 tile-reducer/test/index-to-affine.mlir        | 66 +++++++++++++
 5 files changed, 211 insertions(+)
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerAffine.cpp
 create mode 100644 tile-reducer/test/index-to-affine.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index 62ef74b827a4d..5d86044a780d3 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -55,3 +55,10 @@ symbol is a hard lookup failure.
 handle, checks the payload is a row-reduction `linalg.generic`, and annotates
 `tr.warps_per_block=8`, `tr.warp_size=32`, `tr.elements_per_lane=4`. Wrong
 payload ops produce a silenceable diagnostic.
+
+## Milestone 14
+
+`--tr-index-to-affine` raises affine index arithmetic to `affine.apply`:
+`programId * 128`, `programId * 128 + localRow`, and
+`kt * 128 + lane + j * 32`. A product of two SSA values stays `arith.muli`.
+`affine.for` is used for constant-bound local-row walks, not for Linalg.
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
index 4803b1b6fcb78..5ed2a4493681b 100644
--- a/tile-reducer/include/TileReducer/TileReducerPasses.td
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -74,6 +74,41 @@ def TileTRLinalg : Pass<"tr-tile-linalg", "::mlir::func::FuncOp"> {
   ];
 }
 
+def ConvertTRIndexToAffine : Pass<"tr-index-to-affine", "::mlir::func::FuncOp"> {
+  let summary = "Raise affine index arithmetic to affine.apply. Leave non-affine ops alone.";
+  let description = [{
+    `arith.muli` of an index by a constant and `arith.addi` of index values
+    become `affine.apply`. Used for genuinely affine relations such as
+
+      rowBase   = programId * 128
+      globalRow = programId * 128 + localRow
+      globalCol = kt * 128 + lane + j * 32
+
+    Product of two SSA values is not affine and is left as `arith.muli`.
+    `affine.for` is used only for constant-bound loops whose body is affine;
+    `scf.for` around Linalg is not rewritten.
+  }];
+  let dependentDialects = [
+    "::mlir::affine::AffineDialect",
+    "::mlir::arith::ArithDialect"
+  ];
+}
+
+def LowerTRAffine : Pass<"tr-lower-affine", "::mlir::func::FuncOp"> {
+  let summary = "Lower affine.for/apply to scf.for and arith using upstream patterns.";
+  let description = [{
+    Applies `populateAffineToStdConversionPatterns`:
+      affine.for   -> scf.for
+      affine.apply -> arith.addi / arith.muli on index
+  }];
+  let dependentDialects = [
+    "::mlir::affine::AffineDialect",
+    "::mlir::arith::ArithDialect",
+    "::mlir::scf::SCFDialect",
+    "::mlir::memref::MemRefDialect"
+  ];
+}
+
 def ConvertTRToLinalg : Pass<"convert-tr-to-linalg", "::mlir::func::FuncOp"> {
   let summary = "Lower tile compute to Linalg over MemRefs. Load becomes a subview.";
   let description = [{
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index 1234dd9085a31..67b51e0ef650b 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -2,6 +2,7 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerDialect.cpp
         TileReducerOps.cpp
         TileReducerTypes.cpp
+        TileReducerAffine.cpp
         TileReducerAnalyses.cpp
         TileReducerBufferConversion.cpp
         TileReducerLinalgConversion.cpp
@@ -25,6 +26,9 @@ add_mlir_dialect_library(MLIRTileReducer
         MLIRControlFlowInterfaces
         MLIRFuncDialect
         MLIRAffineDialect
+        MLIRAffineToStandard
+        MLIRAffineUtils
+        MLIRArithUtils
         MLIRFuncTransforms
         MLIRLinalgDialect
         MLIRLinalgTransforms
diff --git a/tile-reducer/lib/TileReducer/TileReducerAffine.cpp b/tile-reducer/lib/TileReducer/TileReducerAffine.cpp
new file mode 100644
index 0000000000000..c6d8d54be6027
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerAffine.cpp
@@ -0,0 +1,99 @@
+//===- TileReducerAffine.cpp - Milestones 14-15 -----------------*- C++ -*-===//
+//
+// Raise genuinely affine index arithmetic to affine.apply / affine.for.
+// Lower those ops back to scf.for + arith with upstream patterns.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/TileReducerPasses.h"
+
+#include "mlir/Conversion/AffineToStandard/AffineToStandard.h"
+#include "mlir/Dialect/Affine/IR/AffineOps.h"
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/Dialect/MemRef/IR/MemRef.h"
+#include "mlir/Dialect/SCF/IR/SCF.h"
+#include "mlir/IR/AffineExpr.h"
+#include "mlir/IR/PatternMatch.h"
+#include "mlir/Transforms/DialectConversion.h"
+#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
+
+namespace mlir::tr {
+#define GEN_PASS_DEF_CONVERTTRINDEXTOAFFINE
+#define GEN_PASS_DEF_LOWERTRAFFINE
+#include "TileReducer/TileReducerPasses.h.inc"
+
+namespace {
+
+struct MulIToAffineApply : public OpRewritePattern<arith::MulIOp> {
+  using OpRewritePattern::OpRewritePattern;
+  LogicalResult matchAndRewrite(arith::MulIOp op,
+                                PatternRewriter &rewriter) const override {
+    if (!op.getType().isIndex())
+      return failure();
+    std::optional<int64_t> lhsC = getConstantIntValue(op.getLhs());
+    std::optional<int64_t> rhsC = getConstantIntValue(op.getRhs());
+    if (lhsC && rhsC)
+      return failure();
+    if (!lhsC && !rhsC)
+      return rewriter.notifyMatchFailure(
+          op, "product of two SSA values is not affine");
+    Value var = lhsC ? op.getRhs() : op.getLhs();
+    int64_t cst = lhsC ? *lhsC : *rhsC;
+    AffineExpr expr =
+        getAffineDimExpr(0, rewriter.getContext()) * cst;
+    auto apply = affine::makeComposedAffineApply(rewriter, op.getLoc(), expr,
+                                                 ArrayRef<OpFoldResult>{var});
+    rewriter.replaceOp(op, apply.getResult());
+    return success();
+  }
+};
+
+struct AddIToAffineApply : public OpRewritePattern<arith::AddIOp> {
+  using OpRewritePattern::OpRewritePattern;
+  LogicalResult matchAndRewrite(arith::AddIOp op,
+                                PatternRewriter &rewriter) const override {
+    if (!op.getType().isIndex())
+      return failure();
+    if (getConstantIntValue(op.getLhs()) && getConstantIntValue(op.getRhs()))
+      return failure();
+    MLIRContext *ctx = rewriter.getContext();
+    AffineExpr expr = getAffineDimExpr(0, ctx) + getAffineDimExpr(1, ctx);
+    auto apply = affine::makeComposedAffineApply(
+        rewriter, op.getLoc(), expr,
+        ArrayRef<OpFoldResult>{op.getLhs(), op.getRhs()});
+    rewriter.replaceOp(op, apply.getResult());
+    return success();
+  }
+};
+
+struct ConvertTRIndexToAffine
+    : impl::ConvertTRIndexToAffineBase<ConvertTRIndexToAffine> {
+  void runOnOperation() override {
+    RewritePatternSet patterns(&getContext());
+    patterns.add<MulIToAffineApply, AddIToAffineApply>(&getContext());
+    affine::AffineApplyOp::getCanonicalizationPatterns(patterns, &getContext());
+    if (failed(applyPatternsGreedily(getOperation(), std::move(patterns))))
+      signalPassFailure();
+  }
+};
+
+struct LowerTRAffine : impl::LowerTRAffineBase<LowerTRAffine> {
+  void runOnOperation() override {
+    MLIRContext *ctx = &getContext();
+    RewritePatternSet patterns(ctx);
+    populateAffineToStdConversionPatterns(patterns);
+    ConversionTarget target(*ctx);
+    target.addLegalDialect<arith::ArithDialect, memref::MemRefDialect,
+                           scf::SCFDialect, func::FuncDialect>();
+    target.addIllegalOp<affine::AffineApplyOp, affine::AffineForOp,
+                        affine::AffineIfOp, affine::AffineLoadOp,
+                        affine::AffineStoreOp, affine::AffineYieldOp>();
+    if (failed(applyPartialConversion(getOperation(), target,
+                                      std::move(patterns))))
+      signalPassFailure();
+  }
+};
+
+} // namespace
+} // namespace mlir::tr
diff --git a/tile-reducer/test/index-to-affine.mlir b/tile-reducer/test/index-to-affine.mlir
new file mode 100644
index 0000000000000..1abd3a6cf0cd4
--- /dev/null
+++ b/tile-reducer/test/index-to-affine.mlir
@@ -0,0 +1,66 @@
+// RUN: tr-opt %s --tr-index-to-affine | FileCheck %s
+
+// Milestone 14: only genuinely affine index relations become affine.apply.
+// affine.for is used for a constant-bound loop; Linalg stays in scf.for.
+
+// CHECK-DAG: #[[$ROWBASE:.*]] = affine_map<()[s0] -> (s0 * 128)>
+// CHECK-DAG: #[[$GROW:.*]] = affine_map<()[s0, s1] -> (s0 + s1 * 128)>
+// CHECK-DAG: #[[$GCOL:.*]] = affine_map<()[s0, s1, s2] -> (s0 * 32 + s1 + s2 * 128)>
+
+// CHECK-LABEL: func.func @row_base
+// CHECK-SAME: (%[[PID:.*]]: index)
+func.func @row_base(%pid: index) -> index {
+  %c128 = arith.constant 128 : index
+  // CHECK: %[[B:.*]] = affine.apply #[[$ROWBASE]]()[%[[PID]]]
+  // CHECK: return %[[B]]
+  %rowBase = arith.muli %pid, %c128 : index
+  return %rowBase : index
+}
+
+// CHECK-LABEL: func.func @global_row
+// CHECK-SAME: (%[[PID:.*]]: index, %[[LOCAL:.*]]: index)
+func.func @global_row(%pid: index, %local: index) -> index {
+  %c128 = arith.constant 128 : index
+  %rowBase = arith.muli %pid, %c128 : index
+  // CHECK: %[[G:.*]] = affine.apply #[[$GROW]]()[%[[LOCAL]], %[[PID]]]
+  // CHECK: return %[[G]]
+  %globalRow = arith.addi %rowBase, %local : index
+  return %globalRow : index
+}
+
+// CHECK-LABEL: func.func @global_col
+// CHECK-SAME: (%[[KT:.*]]: index, %[[LANE:.*]]: index, %[[J:.*]]: index)
+func.func @global_col(%kt: index, %lane: index, %j: index) -> index {
+  %c128 = arith.constant 128 : index
+  %c32 = arith.constant 32 : index
+  %a = arith.muli %kt, %c128 : index
+  %b = arith.addi %a, %lane : index
+  %c = arith.muli %j, %c32 : index
+  // CHECK: %[[G:.*]] = affine.apply #[[$GCOL]]()[%[[J]], %[[LANE]], %[[KT]]]
+  // CHECK: return %[[G]]
+  %globalCol = arith.addi %b, %c : index
+  return %globalCol : index
+}
+
+// Product of two SSA values is not affine.
+// CHECK-LABEL: func.func @not_affine
+func.func @not_affine(%a: index, %b: index) -> index {
+  // CHECK: arith.muli
+  // CHECK-NOT: affine.apply
+  %p = arith.muli %a, %b : index
+  return %p : index
+}
+
+// affine.for is the natural form for a constant-bound local-row walk.
+// CHECK-LABEL: func.func @local_rows
+// CHECK-SAME: (%[[PID:.*]]: index)
+func.func @local_rows(%pid: index) -> index {
+  %c0 = arith.constant 0 : index
+  // CHECK: affine.for %[[L:.*]] = 0 to 16
+  %r = affine.for %local = 0 to 16 iter_args(%acc = %c0) -> index {
+    %g = affine.apply affine_map<(d0, d1) -> (d0 * 128 + d1)>(%pid, %local)
+    %s = arith.addi %acc, %g : index
+    affine.yield %s : index
+  }
+  return %r : index
+}

>From 543bef1e380936c03b557cb36f2e87713d8907e2 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 22:54:15 -0700
Subject: [PATCH 15/29] [TileReducer] Milestone 15: lower affine.for/apply to
 scf.for and arith

--tr-lower-affine uses upstream populateAffineToStdConversionPatterns.
affine.for becomes scf.for; affine.apply becomes arith.muli/addi on
index. No Tensor dialect.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/lower-affine.mlir
  tr-opt --tr-lower-affine tile-reducer/test/lower-affine.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md              |  6 +++
 tile-reducer/test/lower-affine.mlir | 57 +++++++++++++++++++++++++++++
 2 files changed, 63 insertions(+)
 create mode 100644 tile-reducer/test/lower-affine.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index 5d86044a780d3..a318a2b6870d9 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -62,3 +62,9 @@ payload ops produce a silenceable diagnostic.
 `programId * 128`, `programId * 128 + localRow`, and
 `kt * 128 + lane + j * 32`. A product of two SSA values stays `arith.muli`.
 `affine.for` is used for constant-bound local-row walks, not for Linalg.
+
+## Milestone 15
+
+`--tr-lower-affine` applies upstream `populateAffineToStdConversionPatterns`:
+`affine.for` becomes `scf.for`, `affine.apply` becomes `arith.muli` /
+`arith.addi` on `index`.
diff --git a/tile-reducer/test/lower-affine.mlir b/tile-reducer/test/lower-affine.mlir
new file mode 100644
index 0000000000000..d724b91a4ebd0
--- /dev/null
+++ b/tile-reducer/test/lower-affine.mlir
@@ -0,0 +1,57 @@
+// RUN: tr-opt %s --tr-lower-affine | FileCheck %s
+
+// Milestone 15: standard Affine -> SCF + Arith lowering.
+// Before: affine.for / affine.apply. After: scf.for / arith.muli+addi.
+
+#map = affine_map<()[s0] -> (s0 * 128)>
+#map1 = affine_map<()[s0, s1] -> (s0 + s1 * 128)>
+#map2 = affine_map<()[s0, s1, s2] -> (s0 * 32 + s1 + s2 * 128)>
+#map3 = affine_map<(d0, d1)[s0] -> (d0 + d1 + s0 * 128)>
+
+// CHECK-LABEL: func.func @row_base
+// CHECK-SAME: (%[[PID:.*]]: index)
+func.func @row_base(%pid: index) -> index {
+  // CHECK: arith.constant 128 : index
+  // CHECK: arith.muli %[[PID]], %{{.*}}
+  // CHECK-NOT: affine.apply
+  %0 = affine.apply #map()[%pid]
+  return %0 : index
+}
+
+// CHECK-LABEL: func.func @global_row
+// CHECK-SAME: (%[[PID:.*]]: index, %[[LOCAL:.*]]: index)
+func.func @global_row(%pid: index, %local: index) -> index {
+  // CHECK: arith.muli %[[PID]], %{{.*}}
+  // CHECK: arith.addi %[[LOCAL]], %{{.*}}
+  // CHECK-NOT: affine.apply
+  %0 = affine.apply #map1()[%local, %pid]
+  return %0 : index
+}
+
+// CHECK-LABEL: func.func @global_col
+// CHECK-SAME: (%[[KT:.*]]: index, %[[LANE:.*]]: index, %[[J:.*]]: index)
+func.func @global_col(%kt: index, %lane: index, %j: index) -> index {
+  // CHECK: arith.muli %[[J]], %{{.*}}
+  // CHECK: arith.addi %{{.*}}, %[[LANE]]
+  // CHECK: arith.muli %[[KT]], %{{.*}}
+  // CHECK: arith.addi
+  // CHECK-NOT: affine.apply
+  %0 = affine.apply #map2()[%j, %lane, %kt]
+  return %0 : index
+}
+
+// CHECK-LABEL: func.func @local_rows
+func.func @local_rows(%pid: index) -> index {
+  %c0 = arith.constant 0 : index
+  // CHECK: scf.for %{{.*}} = %{{.*}} to %{{.*}} step %{{.*}} iter_args
+  // CHECK: arith.addi
+  // CHECK: arith.muli
+  // CHECK: scf.yield
+  // CHECK-NOT: affine.for
+  // CHECK-NOT: affine.apply
+  %r = affine.for %local = 0 to 16 iter_args(%acc = %c0) -> index {
+    %g = affine.apply #map3(%acc, %local)[%pid]
+    affine.yield %g : index
+  }
+  return %r : index
+}

>From a486e27557e3a35d3d5154f0e752c318719d4925 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:03:16 -0700
Subject: [PATCH 16/29] [TileReducer] Milestone 16: GPU target abstraction

GPUTargetInfo records warp size, SM/register/shared-memory capacities,
and the baseline 256-thread / 8-warp launch. --tr-annotate-gpu-target
writes those fields as tr.target.* module attributes. They are target
properties, not TileReducer source semantics.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/annotate-gpu-target.mlir
  tr-opt --tr-annotate-gpu-target tile-reducer/test/annotate-gpu-target.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |   7 ++
 .../include/TileReducer/GPUTargetInfo.h       |  59 ++++++++++
 .../include/TileReducer/TileReducerPasses.td  |   9 ++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |   1 +
 .../lib/TileReducer/TileReducerGPUTarget.cpp  | 110 ++++++++++++++++++
 tile-reducer/test/annotate-gpu-target.mlir    |  26 +++++
 6 files changed, 212 insertions(+)
 create mode 100644 tile-reducer/include/TileReducer/GPUTargetInfo.h
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerGPUTarget.cpp
 create mode 100644 tile-reducer/test/annotate-gpu-target.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index a318a2b6870d9..b124f9f06f0c5 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -68,3 +68,10 @@ payload ops produce a silenceable diagnostic.
 `--tr-lower-affine` applies upstream `populateAffineToStdConversionPatterns`:
 `affine.for` becomes `scf.for`, `affine.apply` becomes `arith.muli` /
 `arith.addi` on `index`.
+
+## Milestone 16
+
+`GPUTargetInfo` records warp size, SM / register / shared-memory
+capacities, and the baseline launch (256 threads, 8 warps).
+`--tr-annotate-gpu-target` writes those fields as `tr.target.*` module
+attributes. They are target properties, not source semantics.
diff --git a/tile-reducer/include/TileReducer/GPUTargetInfo.h b/tile-reducer/include/TileReducer/GPUTargetInfo.h
new file mode 100644
index 0000000000000..a0a724f6cc065
--- /dev/null
+++ b/tile-reducer/include/TileReducer/GPUTargetInfo.h
@@ -0,0 +1,59 @@
+//===- GPUTargetInfo.h - GPU machine model ----------------------*- C++ -*-===//
+//
+// Milestone 16: target properties used by later scheduling and cost
+// modeling. These are not TileReducer source semantics.
+//
+// Baseline launch geometry (schedule, not ISA):
+//   warp size        = 32
+//   threads / block  = 256
+//   warps / block    = 8
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef TILE_REDUCER_GPUTARGETINFO_H
+#define TILE_REDUCER_GPUTARGETINFO_H
+
+#include "mlir/IR/BuiltinAttributes.h"
+#include "mlir/IR/Operation.h"
+
+namespace mlir {
+namespace tr {
+
+struct GPUTargetInfo {
+  int warpSize = 32;
+  int numSMs = 108;
+  int maxThreadsPerBlock = 1024;
+  int maxWarpsPerSM = 64;
+  int maxBlocksPerSM = 32;
+  int registersPerSM = 65536;
+  int maxRegistersPerThread = 255;
+  int sharedMemoryPerSM = 164 * 1024;
+  int sharedMemoryPerBlock = 163 * 1024;
+  double memoryBandwidthGBs = 1555.0;
+  double fp32PeakTFLOPs = 19.5;
+
+  /// Baseline occupancy choice for the row-sum kernel. Not a source fact.
+  static constexpr int kBaselineThreadsPerBlock = 256;
+
+  int threadsPerBlock() const { return kBaselineThreadsPerBlock; }
+  int warpsPerBlock() const { return kBaselineThreadsPerBlock / warpSize; }
+
+  /// Rows one warp walks sequentially inside a `tileRows`-high logical tile.
+  int rowsPerWarp(int tileRows) const { return tileRows / warpsPerBlock(); }
+  /// Elements one lane owns along a `tileCols`-wide logical tile.
+  int elementsPerLane(int tileCols) const { return tileCols / warpSize; }
+
+  static GPUTargetInfo baseline();
+
+  /// Read `tr.target.*` attributes from `op` or its parents; missing fields
+  /// keep the baseline defaults.
+  static GPUTargetInfo fromOp(Operation *op);
+
+  /// Write every field as `tr.target.*` discardable attributes on `op`.
+  void applyTo(Operation *op) const;
+};
+
+} // namespace tr
+} // namespace mlir
+
+#endif // TILE_REDUCER_GPUTARGETINFO_H
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
index 5ed2a4493681b..3891d402e4269 100644
--- a/tile-reducer/include/TileReducer/TileReducerPasses.td
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -109,6 +109,15 @@ def LowerTRAffine : Pass<"tr-lower-affine", "::mlir::func::FuncOp"> {
   ];
 }
 
+def AnnotateGPUTarget : Pass<"tr-annotate-gpu-target", "::mlir::ModuleOp"> {
+  let summary = "Attach GPUTargetInfo fields as module attributes.";
+  let description = [{
+    Records warp size, the baseline 256-thread / 8-warp launch, and A100-like
+    SM / register / shared-memory capacities. These are target properties,
+    not TileReducer source semantics.
+  }];
+}
+
 def ConvertTRToLinalg : Pass<"convert-tr-to-linalg", "::mlir::func::FuncOp"> {
   let summary = "Lower tile compute to Linalg over MemRefs. Load becomes a subview.";
   let description = [{
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index 67b51e0ef650b..a6dab46176bd2 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -8,6 +8,7 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerLinalgConversion.cpp
         TileReducerLinalgTiling.cpp
         TileReducerTransformOps.cpp
+        TileReducerGPUTarget.cpp
         TileReducerPasses.cpp
 
         ADDITIONAL_HEADER_DIRS
diff --git a/tile-reducer/lib/TileReducer/TileReducerGPUTarget.cpp b/tile-reducer/lib/TileReducer/TileReducerGPUTarget.cpp
new file mode 100644
index 0000000000000..d3e3e475ba224
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerGPUTarget.cpp
@@ -0,0 +1,110 @@
+//===- TileReducerGPUTarget.cpp - Milestone 16 ------------------*- C++ -*-===//
+//
+// GPUTargetInfo factory, attribute I/O, and --tr-annotate-gpu-target.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/GPUTargetInfo.h"
+#include "TileReducer/TileReducerPasses.h"
+
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/IR/BuiltinTypes.h"
+
+using namespace mlir;
+using namespace mlir::tr;
+
+namespace {
+
+constexpr StringRef kWarpSize = "tr.target.warp_size";
+constexpr StringRef kNumSMs = "tr.target.num_sms";
+constexpr StringRef kMaxThreadsPerBlock = "tr.target.max_threads_per_block";
+constexpr StringRef kMaxWarpsPerSM = "tr.target.max_warps_per_sm";
+constexpr StringRef kMaxBlocksPerSM = "tr.target.max_blocks_per_sm";
+constexpr StringRef kRegistersPerSM = "tr.target.registers_per_sm";
+constexpr StringRef kMaxRegistersPerThread = "tr.target.max_registers_per_thread";
+constexpr StringRef kSharedMemoryPerSM = "tr.target.shared_memory_per_sm";
+constexpr StringRef kSharedMemoryPerBlock = "tr.target.shared_memory_per_block";
+constexpr StringRef kMemoryBandwidthGBs = "tr.target.memory_bandwidth_gbs";
+constexpr StringRef kFp32PeakTFLOPs = "tr.target.fp32_peak_tflops";
+constexpr StringRef kThreadsPerBlock = "tr.target.threads_per_block";
+constexpr StringRef kWarpsPerBlock = "tr.target.warps_per_block";
+
+static IntegerAttr i64Attr(MLIRContext *ctx, int64_t v) {
+  return IntegerAttr::get(IntegerType::get(ctx, 64), v);
+}
+
+static std::optional<int64_t> getI64(Operation *op, StringRef name) {
+  if (auto attr = op->getAttrOfType<IntegerAttr>(name))
+    return attr.getInt();
+  return std::nullopt;
+}
+
+static std::optional<double> getF64(Operation *op, StringRef name) {
+  if (auto attr = op->getAttrOfType<FloatAttr>(name))
+    return attr.getValueAsDouble();
+  return std::nullopt;
+}
+
+} // namespace
+
+GPUTargetInfo GPUTargetInfo::baseline() { return GPUTargetInfo(); }
+
+GPUTargetInfo GPUTargetInfo::fromOp(Operation *op) {
+  GPUTargetInfo info = baseline();
+  for (Operation *cur = op; cur; cur = cur->getParentOp()) {
+    if (auto v = getI64(cur, kWarpSize))
+      info.warpSize = static_cast<int>(*v);
+    if (auto v = getI64(cur, kNumSMs))
+      info.numSMs = static_cast<int>(*v);
+    if (auto v = getI64(cur, kMaxThreadsPerBlock))
+      info.maxThreadsPerBlock = static_cast<int>(*v);
+    if (auto v = getI64(cur, kMaxWarpsPerSM))
+      info.maxWarpsPerSM = static_cast<int>(*v);
+    if (auto v = getI64(cur, kMaxBlocksPerSM))
+      info.maxBlocksPerSM = static_cast<int>(*v);
+    if (auto v = getI64(cur, kRegistersPerSM))
+      info.registersPerSM = static_cast<int>(*v);
+    if (auto v = getI64(cur, kMaxRegistersPerThread))
+      info.maxRegistersPerThread = static_cast<int>(*v);
+    if (auto v = getI64(cur, kSharedMemoryPerSM))
+      info.sharedMemoryPerSM = static_cast<int>(*v);
+    if (auto v = getI64(cur, kSharedMemoryPerBlock))
+      info.sharedMemoryPerBlock = static_cast<int>(*v);
+    if (auto v = getF64(cur, kMemoryBandwidthGBs))
+      info.memoryBandwidthGBs = *v;
+    if (auto v = getF64(cur, kFp32PeakTFLOPs))
+      info.fp32PeakTFLOPs = *v;
+  }
+  return info;
+}
+
+void GPUTargetInfo::applyTo(Operation *op) const {
+  MLIRContext *ctx = op->getContext();
+  auto f64 = Float64Type::get(ctx);
+  op->setAttr(kWarpSize, i64Attr(ctx, warpSize));
+  op->setAttr(kNumSMs, i64Attr(ctx, numSMs));
+  op->setAttr(kMaxThreadsPerBlock, i64Attr(ctx, maxThreadsPerBlock));
+  op->setAttr(kMaxWarpsPerSM, i64Attr(ctx, maxWarpsPerSM));
+  op->setAttr(kMaxBlocksPerSM, i64Attr(ctx, maxBlocksPerSM));
+  op->setAttr(kRegistersPerSM, i64Attr(ctx, registersPerSM));
+  op->setAttr(kMaxRegistersPerThread, i64Attr(ctx, maxRegistersPerThread));
+  op->setAttr(kSharedMemoryPerSM, i64Attr(ctx, sharedMemoryPerSM));
+  op->setAttr(kSharedMemoryPerBlock, i64Attr(ctx, sharedMemoryPerBlock));
+  op->setAttr(kMemoryBandwidthGBs, FloatAttr::get(f64, memoryBandwidthGBs));
+  op->setAttr(kFp32PeakTFLOPs, FloatAttr::get(f64, fp32PeakTFLOPs));
+  op->setAttr(kThreadsPerBlock, i64Attr(ctx, threadsPerBlock()));
+  op->setAttr(kWarpsPerBlock, i64Attr(ctx, warpsPerBlock()));
+}
+
+namespace mlir::tr {
+#define GEN_PASS_DEF_ANNOTATEGPUTARGET
+#include "TileReducer/TileReducerPasses.h.inc"
+
+namespace {
+
+struct AnnotateGPUTarget : impl::AnnotateGPUTargetBase<AnnotateGPUTarget> {
+  void runOnOperation() override { GPUTargetInfo::baseline().applyTo(getOperation()); }
+};
+
+} // namespace
+} // namespace mlir::tr
diff --git a/tile-reducer/test/annotate-gpu-target.mlir b/tile-reducer/test/annotate-gpu-target.mlir
new file mode 100644
index 0000000000000..df35c76b3215a
--- /dev/null
+++ b/tile-reducer/test/annotate-gpu-target.mlir
@@ -0,0 +1,26 @@
+// RUN: tr-opt %s --tr-annotate-gpu-target | FileCheck %s
+
+// Milestone 16: GPUTargetInfo is recorded on the module. Warp size and
+// the 256-thread / 8-warp launch are the baseline schedule. SM / register
+// / shared-memory numbers are target properties, not source semantics.
+
+// CHECK: module attributes
+// CHECK-DAG: tr.target.warp_size = 32
+// CHECK-DAG: tr.target.threads_per_block = 256
+// CHECK-DAG: tr.target.warps_per_block = 8
+// CHECK-DAG: tr.target.num_sms = 108
+// CHECK-DAG: tr.target.max_threads_per_block = 1024
+// CHECK-DAG: tr.target.max_warps_per_sm = 64
+// CHECK-DAG: tr.target.max_blocks_per_sm = 32
+// CHECK-DAG: tr.target.registers_per_sm = 65536
+// CHECK-DAG: tr.target.max_registers_per_thread = 255
+// CHECK-DAG: tr.target.shared_memory_per_sm = 167936
+// CHECK-DAG: tr.target.shared_memory_per_block = 166912
+// CHECK-DAG: tr.target.memory_bandwidth_gbs = 1.555000e+03
+// CHECK-DAG: tr.target.fp32_peak_tflops = 1.950000e+01
+
+module {
+  func.func @dummy() {
+    return
+  }
+}

>From 4b3b5b780a4ca5c0d31766720683baa29cbaca0b Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:03:47 -0700
Subject: [PATCH 17/29] [TileReducer] Milestone 17: row-sum physical GPU
 distribution

Map a 128x128 logical tile onto 256 threads / 8 warps. Warp w walks
rows w, w+8, ..., 120; lane L owns columns L, L+32, L+64, L+96.
Four register values are summed, then gpu.subgroup_reduce.
tr.program_id stays a logical program instance, not threadIdx.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/convert-row-sum-gpu.mlir
  tr-opt --convert-tr-row-sum-to-gpu tile-reducer/test/convert-row-sum-gpu.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |   7 +
 .../include/TileReducer/TileReducerPasses.td  |  23 ++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |   2 +
 .../lib/TileReducer/TileReducerGPURowSum.cpp  | 280 ++++++++++++++++++
 tile-reducer/test/convert-row-sum-gpu.mlir    |  63 ++++
 tile-reducer/test/smoke.mlir                  |   2 +-
 tile-reducer/tr-opt/CMakeLists.txt            |   1 +
 tile-reducer/tr-opt/tr-opt.cpp                |   6 +-
 8 files changed, 381 insertions(+), 3 deletions(-)
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerGPURowSum.cpp
 create mode 100644 tile-reducer/test/convert-row-sum-gpu.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index b124f9f06f0c5..df756f1e53209 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -75,3 +75,10 @@ payload ops produce a silenceable diagnostic.
 capacities, and the baseline launch (256 threads, 8 warps).
 `--tr-annotate-gpu-target` writes those fields as `tr.target.*` module
 attributes. They are target properties, not source semantics.
+
+## Milestone 17
+
+`--convert-tr-row-sum-to-gpu` maps a 128×128 logical tile onto 256
+threads / 8 warps. Warp `w` walks rows `w, w+8, …, 120`. Lane `L` owns
+columns `L, L+32, L+64, L+96`. Four register values are summed, then
+`gpu.subgroup_reduce`. `tr.program_id` stays a logical program instance.
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
index 3891d402e4269..77b662d7197e0 100644
--- a/tile-reducer/include/TileReducer/TileReducerPasses.td
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -118,6 +118,29 @@ def AnnotateGPUTarget : Pass<"tr-annotate-gpu-target", "::mlir::ModuleOp"> {
   }];
 }
 
+def ConvertTRRowSumToGPU : Pass<"convert-tr-row-sum-to-gpu", "::mlir::func::FuncOp"> {
+  let summary = "Lower the canonical row-sum to GPU dialect. No 128x128 temp.";
+  let description = [{
+    Fuses `tr.load` -> `tr.reduce_sum(axis=1)` into coalesced global loads,
+    per-lane register accumulation (4 elements), and `gpu.subgroup_reduce`.
+
+    Physical map for a 128x128 logical tile and a 256-thread block:
+      8 warps; warp w walks rows w, w+8, ..., 120
+      lane L owns columns L, L+32, L+64, L+96
+
+    `tr.program_id` stays a logical program instance (not threadIdx).
+    No shared memory. Tails use `arith.ceildivui` and OOB zeros.
+  }];
+  let dependentDialects = [
+    "::mlir::tr::TileReducerDialect",
+    "::mlir::gpu::GPUDialect",
+    "::mlir::scf::SCFDialect",
+    "::mlir::arith::ArithDialect",
+    "::mlir::memref::MemRefDialect",
+    "::mlir::func::FuncDialect"
+  ];
+}
+
 def ConvertTRToLinalg : Pass<"convert-tr-to-linalg", "::mlir::func::FuncOp"> {
   let summary = "Lower tile compute to Linalg over MemRefs. Load becomes a subview.";
   let description = [{
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index a6dab46176bd2..ad96c75642bce 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -9,6 +9,7 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerLinalgTiling.cpp
         TileReducerTransformOps.cpp
         TileReducerGPUTarget.cpp
+        TileReducerGPURowSum.cpp
         TileReducerPasses.cpp
 
         ADDITIONAL_HEADER_DIRS
@@ -26,6 +27,7 @@ add_mlir_dialect_library(MLIRTileReducer
         MLIRArithDialect
         MLIRControlFlowInterfaces
         MLIRFuncDialect
+        MLIRGPUDialect
         MLIRAffineDialect
         MLIRAffineToStandard
         MLIRAffineUtils
diff --git a/tile-reducer/lib/TileReducer/TileReducerGPURowSum.cpp b/tile-reducer/lib/TileReducer/TileReducerGPURowSum.cpp
new file mode 100644
index 0000000000000..bad3e9893e6cb
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerGPURowSum.cpp
@@ -0,0 +1,280 @@
+//===- TileReducerGPURowSum.cpp - Milestones 17-19 --------------*- C++ -*-===//
+//
+// Lower the canonical row-sum to GPU dialect:
+//
+//   logical 128x128 tile
+//           |
+//           | fused load / reduce  (no 128x128 temporary, no smem)
+//           v
+//   coalesced global loads
+//           |
+//           v
+//   per-lane register accumulation (4 elems / lane)
+//           |
+//           v
+//   gpu.subgroup_reduce
+//
+// Physical map (256 threads, 8 warps, warp size 32):
+//   warp w owns rows w, w+8, ..., 120   (16 rows, sequential)
+//   lane L owns columns L, L+32, L+64, L+96
+//
+// tr.program_id stays a logical program instance. It is not threadIdx.
+// The host (later) launches one block per program id.
+//
+// Tails (Milestone 19): ceilDiv(K, tileCols); OOB columns contribute 0.
+// The K-reduction is reassociated (lane tree, then warp tree) relative to
+// a sequential left-fold. TileReducer treats row-sum as reassociative,
+// matching the Linalg reduction generic. Masked zeros are add identities.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/GPUTargetInfo.h"
+#include "TileReducer/TileReducerDialect.h"
+#include "TileReducer/TileReducerOps.h"
+#include "TileReducer/TileReducerPasses.h"
+#include "TileReducer/TileReducerTypes.h"
+
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/MemRef/IR/MemRef.h"
+#include "mlir/Dialect/SCF/IR/SCF.h"
+#include "mlir/IR/Builders.h"
+#include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/PatternMatch.h"
+#include "llvm/ADT/STLExtras.h"
+
+using namespace mlir;
+using namespace mlir::tr;
+
+namespace mlir::tr {
+#define GEN_PASS_DEF_CONVERTTRROWSUMTOGPU
+#include "TileReducer/TileReducerPasses.h.inc"
+
+namespace {
+
+struct RowSumMatch {
+  LoadOp load;
+  ReduceSumOp reduce;
+  StoreOp store;
+  ProgramIdOp programId;
+  TileType tileTy;
+};
+
+static std::optional<RowSumMatch> matchRowSum(func::FuncOp func) {
+  RowSumMatch found;
+  bool ok = false;
+  func.walk([&](ReduceSumOp reduce) {
+    if (ok)
+      return;
+    if (reduce.getAxis() != 1)
+      return;
+    auto tileTy = dyn_cast<TileType>(reduce.getInput().getType());
+    if (!tileTy || tileTy.getRank() != 2)
+      return;
+    auto load = reduce.getInput().getDefiningOp<LoadOp>();
+    if (!load)
+      return;
+    StoreOp store;
+    ProgramIdOp programId;
+    func.walk([&](StoreOp s) {
+      if (!store)
+        store = s;
+    });
+    func.walk([&](ProgramIdOp p) {
+      if (!programId)
+        programId = p;
+    });
+    if (!store || !programId)
+      return;
+    found = RowSumMatch{load, reduce, store, programId, tileTy};
+    ok = true;
+  });
+  if (!ok)
+    return std::nullopt;
+  return found;
+}
+
+static Type bufferToMemRef(Type type) {
+  if (auto buffer = dyn_cast<BufferType>(type))
+    return MemRefType::get(buffer.getShape(), buffer.getElementType());
+  return type;
+}
+
+static void convertBufferSignature(func::FuncOp func) {
+  auto fty = func.getFunctionType();
+  SmallVector<Type> ins, outs;
+  for (Type t : fty.getInputs())
+    ins.push_back(bufferToMemRef(t));
+  for (Type t : fty.getResults())
+    outs.push_back(bufferToMemRef(t));
+  func.setType(FunctionType::get(func.getContext(), ins, outs));
+  for (auto [arg, ty] : llvm::zip(func.getArguments(), ins))
+    arg.setType(ty);
+}
+
+static Value scalarZero(OpBuilder &b, Location loc, Type elem) {
+  if (auto ft = dyn_cast<FloatType>(elem))
+    return arith::ConstantOp::create(b, loc, FloatAttr::get(ft, 0.0));
+  if (auto it = dyn_cast<IntegerType>(elem))
+    return arith::ConstantOp::create(b, loc, IntegerAttr::get(it, 0));
+  llvm_unreachable("row-sum element type must be float or integer");
+}
+
+static Value scalarAdd(OpBuilder &b, Location loc, Value lhs, Value rhs) {
+  if (isa<FloatType>(lhs.getType()))
+    return arith::AddFOp::create(b, loc, lhs, rhs);
+  return arith::AddIOp::create(b, loc, lhs, rhs);
+}
+
+/// Emit the physical row-sum body at the current insertion point.
+static void emitRowSumGPU(OpBuilder &b, Location loc, Value in, Value out,
+                          const GPUTargetInfo &target, int64_t tileRows,
+                          int64_t tileCols, Type elemTy) {
+  const int warpSize = target.warpSize;
+  const int warps = target.warpsPerBlock();
+  const int rowsPerWarp = target.rowsPerWarp(static_cast<int>(tileRows));
+  const int elemsPerLane = target.elementsPerLane(static_cast<int>(tileCols));
+
+  // Logical program instance. Not threadIdx / lane / warp.
+  Value pid = ProgramIdOp::create(b, loc, b.getIndexType(),
+                                  b.getI64IntegerAttr(0));
+
+  // Physical ids. thread_id is recorded so the 256-thread block is visible;
+  // the map uses subgroup (warp) and lane.
+  (void)gpu::ThreadIdOp::create(b, loc, gpu::Dimension::x);
+  Value lane = gpu::LaneIdOp::create(b, loc, /*upper_bound=*/IntegerAttr());
+  Value warp = gpu::SubgroupIdOp::create(b, loc, b.getIndexType(),
+                                        /*upper_bound=*/IntegerAttr());
+
+  Value c0 = arith::ConstantIndexOp::create(b, loc, 0);
+  Value c1 = arith::ConstantIndexOp::create(b, loc, 1);
+  Value cWarp = arith::ConstantIndexOp::create(b, loc, warpSize);
+  Value cWarps = arith::ConstantIndexOp::create(b, loc, warps);
+  Value cRows = arith::ConstantIndexOp::create(b, loc, rowsPerWarp);
+  Value cElems = arith::ConstantIndexOp::create(b, loc, elemsPerLane);
+  Value cTileRows = arith::ConstantIndexOp::create(b, loc, tileRows);
+  Value cTileCols = tileCols == tileRows
+                        ? cTileRows
+                        : arith::ConstantIndexOp::create(b, loc, tileCols);
+  Value zero = scalarZero(b, loc, elemTy);
+
+  Value m = memref::DimOp::create(b, loc, in, c0);
+  Value k = memref::DimOp::create(b, loc, in, c1);
+  // Milestone 19: source used truncating divui; the GPU kernel uses ceil.
+  Value numTiles = arith::CeilDivUIOp::create(b, loc, k, cTileCols);
+  Value rowBase = arith::MulIOp::create(b, loc, pid, cTileRows);
+
+  scf::ForOp::create(
+      b, loc, c0, cRows, c1, ValueRange{},
+      [&](OpBuilder &rb, Location rloc, Value s, ValueRange) {
+        Value sScaled = arith::MulIOp::create(rb, rloc, s, cWarps);
+        Value localRow = arith::AddIOp::create(rb, rloc, warp, sScaled);
+        Value globalRow = arith::AddIOp::create(rb, rloc, rowBase, localRow);
+        Value rowOK = arith::CmpIOp::create(rb, rloc, arith::CmpIPredicate::ult,
+                                            globalRow, m);
+        scf::IfOp::create(rb, rloc, rowOK, [&](OpBuilder &ib, Location iloc) {
+          auto kLoop = scf::ForOp::create(
+              ib, iloc, c0, numTiles, c1, ValueRange{zero},
+              [&](OpBuilder &kb, Location kloc, Value kt, ValueRange kargs) {
+                Value acc = kargs[0];
+                Value kBase = arith::MulIOp::create(kb, kloc, kt, cTileCols);
+                auto jLoop = scf::ForOp::create(
+                    kb, kloc, c0, cElems, c1, ValueRange{acc},
+                    [&](OpBuilder &jb, Location jloc, Value j,
+                        ValueRange jargs) {
+                      Value laneAcc = jargs[0];
+                      Value jOff = arith::MulIOp::create(jb, jloc, j, cWarp);
+                      Value col0 =
+                          arith::AddIOp::create(jb, jloc, kBase, lane);
+                      Value col = arith::AddIOp::create(jb, jloc, col0, jOff);
+                      Value colOK = arith::CmpIOp::create(
+                          jb, jloc, arith::CmpIPredicate::ult, col, k);
+                      auto masked = scf::IfOp::create(
+                          jb, jloc, TypeRange{elemTy}, colOK,
+                          /*withElseRegion=*/true);
+                      {
+                        OpBuilder::InsertionGuard guard(jb);
+                        jb.setInsertionPointToStart(masked.thenBlock());
+                        Value ld = memref::LoadOp::create(
+                            jb, jloc, in, ValueRange{globalRow, col});
+                        scf::YieldOp::create(jb, jloc, ld);
+                        jb.setInsertionPointToStart(masked.elseBlock());
+                        scf::YieldOp::create(jb, jloc, zero);
+                      }
+                      Value sum =
+                          scalarAdd(jb, jloc, laneAcc, masked.getResult(0));
+                      scf::YieldOp::create(jb, jloc, sum);
+                    });
+                scf::YieldOp::create(kb, kloc, jLoop.getResult(0));
+              });
+          Value reduced = gpu::SubgroupReduceOp::create(
+              ib, iloc, kLoop.getResult(0), gpu::AllReduceOperation::ADD,
+              /*uniform=*/true);
+          Value isLane0 = arith::CmpIOp::create(
+              ib, iloc, arith::CmpIPredicate::eq, lane, c0);
+          scf::IfOp::create(ib, iloc, isLane0, [&](OpBuilder &sb, Location sloc) {
+            memref::StoreOp::create(sb, sloc, reduced, out,
+                                    ValueRange{globalRow});
+            scf::YieldOp::create(sb, sloc);
+          });
+          scf::YieldOp::create(ib, iloc);
+        });
+        scf::YieldOp::create(rb, rloc);
+      });
+}
+
+struct ConvertTRRowSumToGPU
+    : impl::ConvertTRRowSumToGPUBase<ConvertTRRowSumToGPU> {
+  void runOnOperation() override {
+    func::FuncOp func = getOperation();
+    auto match = matchRowSum(func);
+    if (!match)
+      return;
+
+    convertBufferSignature(func);
+
+    Value in = match->load.getBuffer();
+    Value out = match->store.getBuffer();
+    if (isa<BufferType>(in.getType()) || isa<BufferType>(out.getType())) {
+      // Signature conversion updated block args; reload from the match
+      // ops after their operand types were rewritten with the args.
+      in = match->load.getBuffer();
+      out = match->store.getBuffer();
+    }
+    if (!isa<MemRefType>(in.getType()) || !isa<MemRefType>(out.getType())) {
+      func.emitError("row-sum GPU lowering expects memref buffers");
+      signalPassFailure();
+      return;
+    }
+
+    GPUTargetInfo target = GPUTargetInfo::fromOp(func);
+    int64_t tileRows = match->tileTy.getDimSize(0);
+    int64_t tileCols = match->tileTy.getDimSize(1);
+    Type elemTy = match->tileTy.getElementType();
+    if (tileRows % target.warpsPerBlock() != 0 ||
+        tileCols % target.warpSize != 0) {
+      func.emitError("tile shape is not divisible by the baseline GPU map");
+      signalPassFailure();
+      return;
+    }
+
+    func->setAttr("gpu.known_block_size",
+                  DenseI32ArrayAttr::get(func.getContext(),
+                                         {target.threadsPerBlock(), 1, 1}));
+    target.applyTo(func);
+
+    IRRewriter rewriter(func.getContext());
+    Block *block = &func.getBody().front();
+    while (!block->empty())
+      rewriter.eraseOp(&block->back());
+
+    rewriter.setInsertionPointToEnd(block);
+    emitRowSumGPU(rewriter, func.getLoc(), in, out, target, tileRows, tileCols,
+                  elemTy);
+    func::ReturnOp::create(rewriter, func.getLoc());
+  }
+};
+
+} // namespace
+} // namespace mlir::tr
diff --git a/tile-reducer/test/convert-row-sum-gpu.mlir b/tile-reducer/test/convert-row-sum-gpu.mlir
new file mode 100644
index 0000000000000..73587cb28b3f9
--- /dev/null
+++ b/tile-reducer/test/convert-row-sum-gpu.mlir
@@ -0,0 +1,63 @@
+// RUN: tr-opt %s --convert-tr-row-sum-to-gpu | FileCheck %s
+
+// Milestone 17: 128x128 logical tile, 256 threads, 8 warps.
+//   warp w -> rows w, w+8, ..., 120     (16 sequential rows, not 128 warps)
+//   lane L -> columns L, L+32, L+64, L+96
+// Register-reduce the four lane values, then gpu.subgroup_reduce.
+// tr.program_id stays logical; it is not threadIdx.
+
+// CHECK-LABEL: func.func @row_sum
+// CHECK-SAME: memref<?x?xf32>
+// CHECK-SAME: memref<?xf32>
+// CHECK-SAME: gpu.known_block_size = array<i32: 256, 1, 1>
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}
+
+// CHECK: %[[PID:.*]] = tr.program_id 0 : index
+// CHECK: gpu.thread_id x
+// CHECK: %[[LANE:.*]] = gpu.lane_id
+// CHECK: %[[WARP:.*]] = gpu.subgroup_id
+// CHECK-DAG: %[[C4:.*]] = arith.constant 4 : index
+// CHECK-DAG: %[[C8:.*]] = arith.constant 8 : index
+// CHECK-DAG: %[[C16:.*]] = arith.constant 16 : index
+// CHECK-DAG: %[[C32:.*]] = arith.constant 32 : index
+// CHECK-DAG: %[[C128:.*]] = arith.constant 128 : index
+// CHECK: %[[BASE:.*]] = arith.muli %[[PID]], %[[C128]]
+
+// 16 sequential rows per warp: localRow = warp + s * 8
+// CHECK: scf.for %[[S:.*]] = %{{.*}} to %[[C16]]
+// CHECK:   %[[S8:.*]] = arith.muli %[[S]], %[[C8]]
+// CHECK:   %[[LOCAL:.*]] = arith.addi %[[WARP]], %[[S8]]
+// CHECK:   arith.addi %[[BASE]], %[[LOCAL]]
+
+// 4 elements per lane: col = kt * 128 + lane + j * 32
+// CHECK: scf.for %{{.*}} = %{{.*}} to %[[C4]]
+// CHECK:   arith.muli %{{.*}}, %[[C32]]
+// CHECK:   arith.addi %{{.*}}, %[[LANE]]
+
+// CHECK: gpu.subgroup_reduce add %{{.*}}
+// CHECK: memref.store
+
+// Column reduction is not this map; leave it alone.
+// CHECK-LABEL: func.func @column
+// CHECK: tr.reduce_sum
+func.func @column(%t: !tr.tile<128x128xf32>) -> !tr.tile<128xf32> {
+  %r = tr.reduce_sum %t, axis = 0 : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+  return %r : !tr.tile<128xf32>
+}
diff --git a/tile-reducer/test/smoke.mlir b/tile-reducer/test/smoke.mlir
index f7d9a4d5aebe2..5d38c2650df91 100644
--- a/tile-reducer/test/smoke.mlir
+++ b/tile-reducer/test/smoke.mlir
@@ -4,7 +4,7 @@
 // Milestone 1: the driver registers `tr` (plus func/arith from the canonical
 // source) and can parse a module. Types and ops are Milestone 2 / 3.
 
-// DIALECT: Available Dialects: affine,arith,builtin,func,linalg,memref,scf,tr,transform
+// DIALECT: Available Dialects: affine,arith,builtin,func,gpu,linalg,memref,scf,tr,transform
 
 module {
   // CHECK-LABEL: func.func @smoke
diff --git a/tile-reducer/tr-opt/CMakeLists.txt b/tile-reducer/tr-opt/CMakeLists.txt
index fb420bc8bba84..1a0bb85742536 100644
--- a/tile-reducer/tr-opt/CMakeLists.txt
+++ b/tile-reducer/tr-opt/CMakeLists.txt
@@ -3,6 +3,7 @@ set(LIBS
     MLIRArithDialect
     MLIRFuncDialect
     MLIRFuncInlinerExtension
+    MLIRGPUDialect
     MLIRLinalgDialect
     MLIRLinalgTransformOps
     MLIRLinalgTransforms
diff --git a/tile-reducer/tr-opt/tr-opt.cpp b/tile-reducer/tr-opt/tr-opt.cpp
index 1e7a7f9adb0bb..a3e3095d13b25 100644
--- a/tile-reducer/tr-opt/tr-opt.cpp
+++ b/tile-reducer/tr-opt/tr-opt.cpp
@@ -9,6 +9,7 @@
 #include "mlir/Dialect/Arith/IR/Arith.h"
 #include "mlir/Dialect/Func/Extensions/InlinerExtension.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
 #include "mlir/Dialect/Linalg/IR/Linalg.h"
 #include "mlir/Dialect/Linalg/TransformOps/DialectExtension.h"
 #include "mlir/Dialect/Linalg/Transforms/TilingInterfaceImpl.h"
@@ -30,8 +31,9 @@ int main(int argc, char **argv) {
   mlir::DialectRegistry registry;
   registry.insert<mlir::tr::TileReducerDialect, mlir::affine::AffineDialect,
                   mlir::arith::ArithDialect, mlir::func::FuncDialect,
-                  mlir::linalg::LinalgDialect, mlir::memref::MemRefDialect,
-                  mlir::scf::SCFDialect, mlir::transform::TransformDialect>();
+                  mlir::gpu::GPUDialect, mlir::linalg::LinalgDialect,
+                  mlir::memref::MemRefDialect, mlir::scf::SCFDialect,
+                  mlir::transform::TransformDialect>();
   mlir::func::registerInlinerExtension(registry);
   mlir::linalg::registerTilingInterfaceExternalModels(registry);
   mlir::linalg::registerTransformDialectExtension(registry);

>From c57b8927dd2297e5b89bcc2b5fd75a215c09cc5e Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:03:56 -0700
Subject: [PATCH 18/29] [TileReducer] Milestone 18: fuse load/reduce through
 physical lowering

tr.load -> tr.reduce_sum(axis=1) becomes coalesced memref.loads, per-lane
register accumulation, and gpu.subgroup_reduce. The logical 128x128 tile
is never a physical temporary. Baseline row-sum uses no shared memory.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/convert-row-sum-gpu-fusion.mlir
  tr-opt --convert-tr-row-sum-to-gpu tile-reducer/test/convert-row-sum-gpu-fusion.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |  6 +++
 .../test/convert-row-sum-gpu-fusion.mlir      | 43 +++++++++++++++++++
 2 files changed, 49 insertions(+)
 create mode 100644 tile-reducer/test/convert-row-sum-gpu-fusion.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index df756f1e53209..64dd3b2cb7b12 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -82,3 +82,9 @@ attributes. They are target properties, not source semantics.
 threads / 8 warps. Warp `w` walks rows `w, w+8, …, 120`. Lane `L` owns
 columns `L, L+32, L+64, L+96`. Four register values are summed, then
 `gpu.subgroup_reduce`. `tr.program_id` stays a logical program instance.
+
+## Milestone 18
+
+The same pass fuses `tr.load` → `tr.reduce_sum(axis=1)` into coalesced
+`memref.load`s, per-lane `arith.addf`, and a subgroup reduce. No 128×128
+temporary and no shared memory.
diff --git a/tile-reducer/test/convert-row-sum-gpu-fusion.mlir b/tile-reducer/test/convert-row-sum-gpu-fusion.mlir
new file mode 100644
index 0000000000000..266de5b74c81c
--- /dev/null
+++ b/tile-reducer/test/convert-row-sum-gpu-fusion.mlir
@@ -0,0 +1,43 @@
+// RUN: tr-opt %s --convert-tr-row-sum-to-gpu | FileCheck %s
+
+// Milestone 18: tr.load -> tr.reduce_sum(axis=1) fuses to coalesced
+// global loads, per-lane register accumulation, and a subgroup reduce.
+// The logical 128x128 tile is never a physical temporary. No shared
+// memory for the baseline row sum.
+
+// CHECK-LABEL: func.func @row_sum
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}
+
+// No 128x128 temporary, no tile alloca, no shared memory.
+// CHECK-NOT: memref.alloc
+// CHECK-NOT: memref.alloca
+// CHECK-NOT: gpu.barrier
+// CHECK-NOT: gpu.alloc
+// CHECK-NOT: #gpu.address_space<workgroup>
+// CHECK-NOT: tr.load
+// CHECK-NOT: tr.reduce_sum
+// CHECK-NOT: tr.for
+// CHECK-NOT: linalg.generic
+
+// Fused physical form.
+// CHECK: memref.load
+// CHECK: arith.addf
+// CHECK: gpu.subgroup_reduce add
+// CHECK: memref.store

>From e3ebdaeba9227e09cf1ade7e31f84defeb43edef Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:04:06 -0700
Subject: [PATCH 19/29] [TileReducer] Milestone 19: ceilDiv tails and OOB zeros

Replace the source truncating arith.divui trip count with arith.ceildivui.
Out-of-bounds columns in the last tile contribute zero. The kernel is
K-dynamic and covers K in {1,31,32,33,127,128,129,255,256,257}.
The lane-then-warp tree reassociates the K-sum; row-sum is treated as
reassociative, matching the Linalg reduction generic.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/convert-row-sum-gpu-tails.mlir
  tr-opt --convert-tr-row-sum-to-gpu tile-reducer/test/convert-row-sum-gpu-tails.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |  8 +++
 .../test/convert-row-sum-gpu-tails.mlir       | 57 +++++++++++++++++++
 2 files changed, 65 insertions(+)
 create mode 100644 tile-reducer/test/convert-row-sum-gpu-tails.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index 64dd3b2cb7b12..d0f7f02f0c412 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -88,3 +88,11 @@ columns `L, L+32, L+64, L+96`. Four register values are summed, then
 The same pass fuses `tr.load` → `tr.reduce_sum(axis=1)` into coalesced
 `memref.load`s, per-lane `arith.addf`, and a subgroup reduce. No 128×128
 temporary and no shared memory.
+
+## Milestone 19
+
+The source `arith.divui` trip count is replaced by `arith.ceildivui`.
+Out-of-bounds columns in the last tile contribute zero via `scf.if`.
+The kernel is K-dynamic and covers
+`K ∈ {1,31,32,33,127,128,129,255,256,257}`. The lane-then-warp tree
+reassociates the K-sum; TileReducer treats row-sum as reassociative.
diff --git a/tile-reducer/test/convert-row-sum-gpu-tails.mlir b/tile-reducer/test/convert-row-sum-gpu-tails.mlir
new file mode 100644
index 0000000000000..0d4b041661f7b
--- /dev/null
+++ b/tile-reducer/test/convert-row-sum-gpu-tails.mlir
@@ -0,0 +1,57 @@
+// RUN: tr-opt %s --convert-tr-row-sum-to-gpu | FileCheck %s
+
+// Milestone 19: the canonical source uses truncating `arith.divui`.
+// The GPU kernel uses `arith.ceildivui` and treats out-of-bounds columns
+// as zero. The same dynamic kernel covers
+//
+//   K in {1, 31, 32, 33, 127, 128, 129, 255, 256, 257}
+//
+//   K=1     -> 1 tile, 127 masked zeros / row
+//   K=31    -> 1 tile
+//   K=32    -> 1 tile, one live element in the first lane stripe
+//   K=33    -> 1 tile
+//   K=127   -> 1 tile
+//   K=128   -> 1 tile, mask never taken
+//   K=129   -> 2 tiles, second tile has 1 live column
+//   K=255   -> 2 tiles
+//   K=256   -> 2 tiles, mask never taken
+//   K=257   -> 3 tiles
+//
+// Floating-point assumption: the lane-then-warp reduction tree
+// reassociates the K-sum relative to a sequential left fold. TileReducer
+// treats row-sum as reassociative (same contract as the Linalg generic).
+// Masked zeros are identities for add.
+
+// CHECK-LABEL: func.func @row_sum
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  // Source: truncating division. The pass must not leave this as the
+  // trip count of the physical K loop.
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}
+
+// CHECK: %[[C128:.*]] = arith.constant 128 : index
+// CHECK: %[[Z:.*]] = arith.constant 0.000000e+00 : f32
+// CHECK: memref.dim
+// CHECK: %[[K:.*]] = memref.dim
+// CHECK-NOT: = arith.divui
+// CHECK: arith.ceildivui %[[K]], %[[C128]]
+// CHECK: arith.cmpi ult
+// CHECK: scf.if
+// CHECK: memref.load
+// CHECK: else
+// CHECK: scf.yield %[[Z]] : f32

>From 7e429dca286e04240a216c4872b71d0216125f9e Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:10:15 -0700
Subject: [PATCH 20/29] [TileReducer] Milestone 20: gpu.module @tr_kernels and
 SymbolTable

--tr-emit-gpu-kernels looks up or inserts gpu.module @tr_kernels, inserts
unique gpu.func symbols, and launches them with a nested SymbolRefAttr
on gpu.launch_func @tr_kernels::@row_sum_kernel. A missing kernel symbol
is a hard SymbolUserOpInterface lookup failure.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/gpu-module-symbols.mlir
    tile-reducer/test/gpu-module-symbols-lookup.mlir
    tile-reducer/test/gpu-module-symbols-unique.mlir
    tile-reducer/test/gpu-module-symbols-invalid.mlir
  tr-opt --tr-emit-gpu-kernels tile-reducer/test/gpu-module-symbols.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |  22 +
 .../include/TileReducer/TileReducerPasses.td  |  21 +
 tile-reducer/lib/TileReducer/CMakeLists.txt   |   1 +
 .../lib/TileReducer/TileReducerGPUKernels.cpp | 755 ++++++++++++++++++
 .../test/gpu-module-symbols-invalid.mlir      |  21 +
 .../test/gpu-module-symbols-lookup.mlir       |  36 +
 .../test/gpu-module-symbols-unique.mlir       |  38 +
 tile-reducer/test/gpu-module-symbols.mlir     |  39 +
 8 files changed, 933 insertions(+)
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerGPUKernels.cpp
 create mode 100644 tile-reducer/test/gpu-module-symbols-invalid.mlir
 create mode 100644 tile-reducer/test/gpu-module-symbols-lookup.mlir
 create mode 100644 tile-reducer/test/gpu-module-symbols-unique.mlir
 create mode 100644 tile-reducer/test/gpu-module-symbols.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index d0f7f02f0c412..873873e55888c 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -96,3 +96,25 @@ Out-of-bounds columns in the last tile contribute zero via `scf.if`.
 The kernel is K-dynamic and covers
 `K ∈ {1,31,32,33,127,128,129,255,256,257}`. The lane-then-warp tree
 reassociates the K-sum; TileReducer treats row-sum as reassociative.
+
+## Milestone 20
+
+`--tr-emit-gpu-kernels` builds `gpu.module @tr_kernels` with a SymbolTable:
+lookup of an existing module, insertion of `gpu.func` symbols, uniqueness
+when a name is taken, and nested `SymbolRefAttr` on
+`gpu.launch_func @tr_kernels::@row_sum_kernel`. A missing kernel symbol is
+a hard lookup failure.
+
+## Milestone 21
+
+Full `MxK → scalar` uses two kernels, `@full_sum_stage1` and
+`@full_sum_stage2`. Stage 1: thread-local sum, warp reduce, `smem[warp]`,
+barrier, block reduce, one partial per block. Stage 2 reduces the
+partials. No unordered FP atomics.
+
+## Milestone 22
+
+Column reduction on row-major input: coalesced global loads into a
+128×128 workgroup memref, `gpu.barrier`, then one thread per column.
+128 is already a multiple of the warp size, so a padded 128×132 layout
+is not used. Direct strided `in[row, col]` would break coalescing.
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
index 77b662d7197e0..2f9e0cb0a60b4 100644
--- a/tile-reducer/include/TileReducer/TileReducerPasses.td
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -141,6 +141,27 @@ def ConvertTRRowSumToGPU : Pass<"convert-tr-row-sum-to-gpu", "::mlir::func::Func
   ];
 }
 
+def EmitTRGPUKernels : Pass<"tr-emit-gpu-kernels", "::mlir::ModuleOp"> {
+  let summary = "Outline reductions into gpu.module @tr_kernels and launch by symbol.";
+  let description = [{
+    Uses SymbolTable to look up or insert `gpu.module @tr_kernels`, insert
+    unique `gpu.func` kernel symbols, and reference them from the host with
+    a nested SymbolRefAttr on `gpu.launch_func` (`@tr_kernels::@name`).
+
+    Row sum: `@row_sum_kernel` (no shared memory).
+    Full sum: `@full_sum_stage1` + `@full_sum_stage2` (smem block reduce).
+    Column sum: `@column_sum_kernel` (smem staging + barrier).
+  }];
+  let dependentDialects = [
+    "::mlir::tr::TileReducerDialect",
+    "::mlir::gpu::GPUDialect",
+    "::mlir::scf::SCFDialect",
+    "::mlir::arith::ArithDialect",
+    "::mlir::memref::MemRefDialect",
+    "::mlir::func::FuncDialect"
+  ];
+}
+
 def ConvertTRToLinalg : Pass<"convert-tr-to-linalg", "::mlir::func::FuncOp"> {
   let summary = "Lower tile compute to Linalg over MemRefs. Load becomes a subview.";
   let description = [{
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index ad96c75642bce..e97e9f6c245eb 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -10,6 +10,7 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerTransformOps.cpp
         TileReducerGPUTarget.cpp
         TileReducerGPURowSum.cpp
+        TileReducerGPUKernels.cpp
         TileReducerPasses.cpp
 
         ADDITIONAL_HEADER_DIRS
diff --git a/tile-reducer/lib/TileReducer/TileReducerGPUKernels.cpp b/tile-reducer/lib/TileReducer/TileReducerGPUKernels.cpp
new file mode 100644
index 0000000000000..e693901570589
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerGPUKernels.cpp
@@ -0,0 +1,755 @@
+//===- TileReducerGPUKernels.cpp - Milestones 20-22 -------------*- C++ -*-===//
+//
+// Outline reductions into gpu.module @tr_kernels and launch them by
+// SymbolRefAttr. SymbolTable is used for:
+//   - lookup of an existing @tr_kernels
+//   - insertion of generated gpu.func symbols
+//   - uniqueness when a kernel name is already taken
+//   - nested references @tr_kernels::@kernel on gpu.launch_func
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/GPUTargetInfo.h"
+#include "TileReducer/TileReducerDialect.h"
+#include "TileReducer/TileReducerOps.h"
+#include "TileReducer/TileReducerPasses.h"
+#include "TileReducer/TileReducerTypes.h"
+
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/MemRef/IR/MemRef.h"
+#include "mlir/Dialect/SCF/IR/SCF.h"
+#include "mlir/IR/Builders.h"
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/SymbolTable.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/Twine.h"
+
+using namespace mlir;
+using namespace mlir::tr;
+
+namespace mlir::tr {
+#define GEN_PASS_DEF_EMITTRGPUKERNELS
+#include "TileReducer/TileReducerPasses.h.inc"
+
+namespace {
+
+constexpr StringRef kKernelModuleName = "tr_kernels";
+constexpr StringRef kRowSumKernel = "row_sum_kernel";
+constexpr StringRef kFullSumStage1 = "full_sum_stage1";
+constexpr StringRef kFullSumStage2 = "full_sum_stage2";
+constexpr StringRef kColumnSumKernel = "column_sum_kernel";
+
+enum class KernelKind { None, Row, Full, Column };
+
+struct ReductionMatch {
+  KernelKind kind = KernelKind::None;
+  LoadOp load;
+  StoreOp store;
+  ProgramIdOp programId;
+  TileType tileTy;
+};
+
+static Type bufferToMemRef(Type type) {
+  if (auto buffer = dyn_cast<BufferType>(type))
+    return MemRefType::get(buffer.getShape(), buffer.getElementType());
+  return type;
+}
+
+static void convertBufferSignature(func::FuncOp func) {
+  auto fty = func.getFunctionType();
+  SmallVector<Type> ins, outs;
+  for (Type t : fty.getInputs())
+    ins.push_back(bufferToMemRef(t));
+  for (Type t : fty.getResults())
+    outs.push_back(bufferToMemRef(t));
+  func.setType(FunctionType::get(func.getContext(), ins, outs));
+  for (auto [arg, ty] : llvm::zip(func.getArguments(), ins))
+    arg.setType(ty);
+}
+
+static Value scalarZero(OpBuilder &b, Location loc, Type elem) {
+  if (auto ft = dyn_cast<FloatType>(elem))
+    return arith::ConstantOp::create(b, loc, FloatAttr::get(ft, 0.0));
+  if (auto it = dyn_cast<IntegerType>(elem))
+    return arith::ConstantOp::create(b, loc, IntegerAttr::get(it, 0));
+  llvm_unreachable("expected integer or float element");
+}
+
+static Value scalarAdd(OpBuilder &b, Location loc, Value lhs, Value rhs) {
+  if (isa<FloatType>(lhs.getType()))
+    return arith::AddFOp::create(b, loc, lhs, rhs);
+  return arith::AddIOp::create(b, loc, lhs, rhs);
+}
+
+static MemRefType workgroupMemRef(MLIRContext *ctx, ArrayRef<int64_t> shape,
+                                  Type elem) {
+  auto space = gpu::AddressSpaceAttr::get(
+      ctx, gpu::GPUDialect::getWorkgroupAddressSpace());
+  return MemRefType::get(shape, elem, MemRefLayoutAttrInterface{}, space);
+}
+
+/// Look up @tr_kernels or insert a new gpu.module. Marks the host module
+/// as a gpu.container_module so launch_func can form nested SymbolRefAttrs.
+static gpu::GPUModuleOp getOrCreateKernelModule(ModuleOp module) {
+  SymbolTable hostSymbols(module);
+  if (Operation *found = hostSymbols.lookup(kKernelModuleName)) {
+    if (auto gpuMod = dyn_cast<gpu::GPUModuleOp>(found))
+      return gpuMod;
+  }
+  OpBuilder b(module.getBody(), module.getBody()->begin());
+  auto gpuMod =
+      gpu::GPUModuleOp::create(b, module.getLoc(), kKernelModuleName);
+  module->setAttr(gpu::GPUDialect::getContainerModuleAttrName(),
+                  UnitAttr::get(module.getContext()));
+  return gpuMod;
+}
+
+/// Insert `kernel` into the gpu.module symbol table. If `baseName` is taken,
+/// SymbolTable::insert uniquifies the symbol.
+static StringRef insertUniqueKernel(SymbolTable &gpuSymbols,
+                                    gpu::GPUFuncOp kernel) {
+  gpuSymbols.insert(kernel);
+  return kernel.getName();
+}
+
+static SymbolRefAttr nestedKernelRef(gpu::GPUModuleOp gpuMod,
+                                     StringRef kernelName) {
+  return SymbolRefAttr::get(
+      gpuMod.getNameAttr(),
+      {FlatSymbolRefAttr::get(gpuMod.getContext(), kernelName)});
+}
+
+static ReductionMatch matchReduction(func::FuncOp func) {
+  ReductionMatch found;
+  func.walk([&](ReduceSumOp reduce) {
+    auto inTy = dyn_cast<TileType>(reduce.getInput().getType());
+    auto outTy = dyn_cast<TileType>(reduce.getType());
+    if (!inTy || !outTy)
+      return;
+    LoadOp load;
+    if (auto l = reduce.getInput().getDefiningOp<LoadOp>())
+      load = l;
+    else if (auto inner = reduce.getInput().getDefiningOp<ReduceSumOp>())
+      load = inner.getInput().getDefiningOp<LoadOp>();
+    if (!load)
+      return;
+    auto tileTy = dyn_cast<TileType>(load.getType());
+    if (!tileTy || tileTy.getRank() != 2)
+      return;
+    StoreOp store;
+    ProgramIdOp programId;
+    func.walk([&](StoreOp s) {
+      if (!store)
+        store = s;
+    });
+    func.walk([&](ProgramIdOp p) {
+      if (!programId)
+        programId = p;
+    });
+    if (!store || !programId)
+      return;
+
+    KernelKind kind = KernelKind::None;
+    if (outTy.getRank() == 0)
+      kind = KernelKind::Full;
+    else if (reduce.getAxis() == 1 && inTy.getRank() == 2)
+      kind = KernelKind::Row;
+    else if (reduce.getAxis() == 0 && inTy.getRank() == 2)
+      kind = KernelKind::Column;
+    if (kind == KernelKind::None)
+      return;
+    // Prefer Full over a preceding row reduce in the same function.
+    if (found.kind == KernelKind::Full && kind != KernelKind::Full)
+      return;
+    found = ReductionMatch{kind, load, store, programId, tileTy};
+  });
+  return found;
+}
+
+/// Emit the fused row-sum body. `pid` is the physical block id.
+static void emitRowSumBody(OpBuilder &b, Location loc, Value in, Value out,
+                           Value pid, const GPUTargetInfo &target,
+                           int64_t tileRows, int64_t tileCols, Type elemTy) {
+  const int warpSize = target.warpSize;
+  const int warps = target.warpsPerBlock();
+  const int rowsPerWarp = target.rowsPerWarp(static_cast<int>(tileRows));
+  const int elemsPerLane = target.elementsPerLane(static_cast<int>(tileCols));
+
+  (void)gpu::ThreadIdOp::create(b, loc, gpu::Dimension::x);
+  Value lane = gpu::LaneIdOp::create(b, loc, /*upper_bound=*/IntegerAttr());
+  Value warp = gpu::SubgroupIdOp::create(b, loc, b.getIndexType(),
+                                        /*upper_bound=*/IntegerAttr());
+
+  Value c0 = arith::ConstantIndexOp::create(b, loc, 0);
+  Value c1 = arith::ConstantIndexOp::create(b, loc, 1);
+  Value cWarp = arith::ConstantIndexOp::create(b, loc, warpSize);
+  Value cWarps = arith::ConstantIndexOp::create(b, loc, warps);
+  Value cRows = arith::ConstantIndexOp::create(b, loc, rowsPerWarp);
+  Value cElems = arith::ConstantIndexOp::create(b, loc, elemsPerLane);
+  Value cTileRows = arith::ConstantIndexOp::create(b, loc, tileRows);
+  Value cTileCols = tileCols == tileRows
+                        ? cTileRows
+                        : arith::ConstantIndexOp::create(b, loc, tileCols);
+  Value zero = scalarZero(b, loc, elemTy);
+
+  Value m = memref::DimOp::create(b, loc, in, c0);
+  Value k = memref::DimOp::create(b, loc, in, c1);
+  Value numTiles = arith::CeilDivUIOp::create(b, loc, k, cTileCols);
+  Value rowBase = arith::MulIOp::create(b, loc, pid, cTileRows);
+
+  scf::ForOp::create(
+      b, loc, c0, cRows, c1, ValueRange{},
+      [&](OpBuilder &rb, Location rloc, Value s, ValueRange) {
+        Value sScaled = arith::MulIOp::create(rb, rloc, s, cWarps);
+        Value localRow = arith::AddIOp::create(rb, rloc, warp, sScaled);
+        Value globalRow = arith::AddIOp::create(rb, rloc, rowBase, localRow);
+        Value rowOK = arith::CmpIOp::create(rb, rloc, arith::CmpIPredicate::ult,
+                                            globalRow, m);
+        scf::IfOp::create(rb, rloc, rowOK, [&](OpBuilder &ib, Location iloc) {
+          auto kLoop = scf::ForOp::create(
+              ib, iloc, c0, numTiles, c1, ValueRange{zero},
+              [&](OpBuilder &kb, Location kloc, Value kt, ValueRange kargs) {
+                Value acc = kargs[0];
+                Value kBase = arith::MulIOp::create(kb, kloc, kt, cTileCols);
+                auto jLoop = scf::ForOp::create(
+                    kb, kloc, c0, cElems, c1, ValueRange{acc},
+                    [&](OpBuilder &jb, Location jloc, Value j,
+                        ValueRange jargs) {
+                      Value laneAcc = jargs[0];
+                      Value jOff = arith::MulIOp::create(jb, jloc, j, cWarp);
+                      Value col0 =
+                          arith::AddIOp::create(jb, jloc, kBase, lane);
+                      Value col = arith::AddIOp::create(jb, jloc, col0, jOff);
+                      Value colOK = arith::CmpIOp::create(
+                          jb, jloc, arith::CmpIPredicate::ult, col, k);
+                      auto masked = scf::IfOp::create(
+                          jb, jloc, TypeRange{elemTy}, colOK,
+                          /*withElseRegion=*/true);
+                      {
+                        OpBuilder::InsertionGuard guard(jb);
+                        jb.setInsertionPointToStart(masked.thenBlock());
+                        Value ld = memref::LoadOp::create(
+                            jb, jloc, in, ValueRange{globalRow, col});
+                        scf::YieldOp::create(jb, jloc, ld);
+                        jb.setInsertionPointToStart(masked.elseBlock());
+                        scf::YieldOp::create(jb, jloc, zero);
+                      }
+                      scf::YieldOp::create(
+                          jb, jloc,
+                          scalarAdd(jb, jloc, laneAcc, masked.getResult(0)));
+                    });
+                scf::YieldOp::create(kb, kloc, jLoop.getResult(0));
+              });
+          Value reduced = gpu::SubgroupReduceOp::create(
+              ib, iloc, kLoop.getResult(0), gpu::AllReduceOperation::ADD,
+              /*uniform=*/true);
+          Value isLane0 = arith::CmpIOp::create(
+              ib, iloc, arith::CmpIPredicate::eq, lane, c0);
+          scf::IfOp::create(ib, iloc, isLane0, [&](OpBuilder &sb, Location sloc) {
+            memref::StoreOp::create(sb, sloc, reduced, out,
+                                    ValueRange{globalRow});
+            scf::YieldOp::create(sb, sloc);
+          });
+          scf::YieldOp::create(ib, iloc);
+        });
+        scf::YieldOp::create(rb, rloc);
+      });
+}
+
+/// Thread-local sum -> warp reduce -> smem[warp] -> barrier -> warp-0 tree.
+/// Every warp executes the second subgroup_reduce on the same 8 smem values
+/// so the op stays uniform. Only tid==0's result is stored.
+static Value emitBlockReduce(OpBuilder &b, Location loc, Value threadAcc,
+                             Value smem, Value lane, Value warp, int warps,
+                             Type elemTy) {
+  Value c0 = arith::ConstantIndexOp::create(b, loc, 0);
+  Value cWarps = arith::ConstantIndexOp::create(b, loc, warps);
+  Value zero = scalarZero(b, loc, elemTy);
+  Value warpSum = gpu::SubgroupReduceOp::create(
+      b, loc, threadAcc, gpu::AllReduceOperation::ADD, /*uniform=*/true);
+  Value isLane0 =
+      arith::CmpIOp::create(b, loc, arith::CmpIPredicate::eq, lane, c0);
+  scf::IfOp::create(b, loc, isLane0, [&](OpBuilder &sb, Location sloc) {
+    memref::StoreOp::create(sb, sloc, warpSum, smem, ValueRange{warp});
+    scf::YieldOp::create(sb, sloc);
+  });
+  gpu::BarrierOp::create(b, loc);
+  Value inRange =
+      arith::CmpIOp::create(b, loc, arith::CmpIPredicate::ult, lane, cWarps);
+  auto loaded = scf::IfOp::create(b, loc, TypeRange{elemTy}, inRange,
+                                  /*withElseRegion=*/true);
+  {
+    OpBuilder::InsertionGuard guard(b);
+    b.setInsertionPointToStart(loaded.thenBlock());
+    Value v = memref::LoadOp::create(b, loc, smem, ValueRange{lane});
+    scf::YieldOp::create(b, loc, v);
+    b.setInsertionPointToStart(loaded.elseBlock());
+    scf::YieldOp::create(b, loc, zero);
+  }
+  return gpu::SubgroupReduceOp::create(b, loc, loaded.getResult(0),
+                                       gpu::AllReduceOperation::ADD,
+                                       /*uniform=*/true);
+}
+
+static void emitFullSumStage1Body(OpBuilder &b, Location loc, Value in,
+                                  Value partials, Value smem, Value bid,
+                                  const GPUTargetInfo &target, int64_t tileRows,
+                                  int64_t tileCols, Type elemTy) {
+  const int warpSize = target.warpSize;
+  const int warps = target.warpsPerBlock();
+  const int rowsPerWarp = target.rowsPerWarp(static_cast<int>(tileRows));
+  const int elemsPerLane = target.elementsPerLane(static_cast<int>(tileCols));
+
+  Value tid = gpu::ThreadIdOp::create(b, loc, gpu::Dimension::x);
+  Value lane = gpu::LaneIdOp::create(b, loc, IntegerAttr());
+  Value warp = gpu::SubgroupIdOp::create(b, loc, b.getIndexType(), IntegerAttr());
+
+  Value c0 = arith::ConstantIndexOp::create(b, loc, 0);
+  Value c1 = arith::ConstantIndexOp::create(b, loc, 1);
+  Value cWarp = arith::ConstantIndexOp::create(b, loc, warpSize);
+  Value cWarps = arith::ConstantIndexOp::create(b, loc, warps);
+  Value cRows = arith::ConstantIndexOp::create(b, loc, rowsPerWarp);
+  Value cElems = arith::ConstantIndexOp::create(b, loc, elemsPerLane);
+  Value cTileRows = arith::ConstantIndexOp::create(b, loc, tileRows);
+  Value cTileCols = tileCols == tileRows
+                        ? cTileRows
+                        : arith::ConstantIndexOp::create(b, loc, tileCols);
+  Value zero = scalarZero(b, loc, elemTy);
+
+  Value m = memref::DimOp::create(b, loc, in, c0);
+  Value k = memref::DimOp::create(b, loc, in, c1);
+  Value numTiles = arith::CeilDivUIOp::create(b, loc, k, cTileCols);
+  Value rowBase = arith::MulIOp::create(b, loc, bid, cTileRows);
+
+  auto rowLoop = scf::ForOp::create(
+      b, loc, c0, cRows, c1, ValueRange{zero},
+      [&](OpBuilder &rb, Location rloc, Value s, ValueRange args) {
+        Value acc = args[0];
+        Value sScaled = arith::MulIOp::create(rb, rloc, s, cWarps);
+        Value localRow = arith::AddIOp::create(rb, rloc, warp, sScaled);
+        Value globalRow = arith::AddIOp::create(rb, rloc, rowBase, localRow);
+        Value rowOK = arith::CmpIOp::create(rb, rloc, arith::CmpIPredicate::ult,
+                                            globalRow, m);
+        auto rowIf = scf::IfOp::create(rb, rloc, TypeRange{elemTy}, rowOK,
+                                       /*withElseRegion=*/true);
+        {
+          OpBuilder::InsertionGuard guard(rb);
+          rb.setInsertionPointToStart(rowIf.thenBlock());
+          auto kLoop = scf::ForOp::create(
+              rb, rloc, c0, numTiles, c1, ValueRange{acc},
+              [&](OpBuilder &kb, Location kloc, Value kt, ValueRange kargs) {
+                Value kAcc = kargs[0];
+                Value kBase = arith::MulIOp::create(kb, kloc, kt, cTileCols);
+                auto jLoop = scf::ForOp::create(
+                    kb, kloc, c0, cElems, c1, ValueRange{kAcc},
+                    [&](OpBuilder &jb, Location jloc, Value j,
+                        ValueRange jargs) {
+                      Value jOff = arith::MulIOp::create(jb, jloc, j, cWarp);
+                      Value col0 =
+                          arith::AddIOp::create(jb, jloc, kBase, lane);
+                      Value col = arith::AddIOp::create(jb, jloc, col0, jOff);
+                      Value colOK = arith::CmpIOp::create(
+                          jb, jloc, arith::CmpIPredicate::ult, col, k);
+                      auto masked = scf::IfOp::create(
+                          jb, jloc, TypeRange{elemTy}, colOK,
+                          /*withElseRegion=*/true);
+                      {
+                        OpBuilder::InsertionGuard g2(jb);
+                        jb.setInsertionPointToStart(masked.thenBlock());
+                        Value ld = memref::LoadOp::create(
+                            jb, jloc, in, ValueRange{globalRow, col});
+                        scf::YieldOp::create(jb, jloc, ld);
+                        jb.setInsertionPointToStart(masked.elseBlock());
+                        scf::YieldOp::create(jb, jloc, zero);
+                      }
+                      scf::YieldOp::create(
+                          jb, jloc,
+                          scalarAdd(jb, jloc, jargs[0], masked.getResult(0)));
+                    });
+                scf::YieldOp::create(kb, kloc, jLoop.getResult(0));
+              });
+          scf::YieldOp::create(rb, rloc, kLoop.getResult(0));
+          rb.setInsertionPointToStart(rowIf.elseBlock());
+          scf::YieldOp::create(rb, rloc, acc);
+        }
+        scf::YieldOp::create(rb, rloc, rowIf.getResult(0));
+      });
+
+  Value blockSum = emitBlockReduce(b, loc, rowLoop.getResult(0), smem, lane,
+                                   warp, warps, elemTy);
+  Value isTid0 =
+      arith::CmpIOp::create(b, loc, arith::CmpIPredicate::eq, tid, c0);
+  scf::IfOp::create(b, loc, isTid0, [&](OpBuilder &sb, Location sloc) {
+    memref::StoreOp::create(sb, sloc, blockSum, partials, ValueRange{bid});
+    scf::YieldOp::create(sb, sloc);
+  });
+}
+
+static void emitFullSumStage2Body(OpBuilder &b, Location loc, Value partials,
+                                  Value out, Value smem,
+                                  const GPUTargetInfo &target, Type elemTy) {
+  const int warps = target.warpsPerBlock();
+  Value tid = gpu::ThreadIdOp::create(b, loc, gpu::Dimension::x);
+  Value lane = gpu::LaneIdOp::create(b, loc, IntegerAttr());
+  Value warp = gpu::SubgroupIdOp::create(b, loc, b.getIndexType(), IntegerAttr());
+  Value c0 = arith::ConstantIndexOp::create(b, loc, 0);
+  Value c256 = arith::ConstantIndexOp::create(b, loc, target.threadsPerBlock());
+  Value zero = scalarZero(b, loc, elemTy);
+  Value nPart = memref::DimOp::create(b, loc, partials, c0);
+
+  auto loop = scf::ForOp::create(
+      b, loc, tid, nPart, c256, ValueRange{zero},
+      [&](OpBuilder &lb, Location lloc, Value i, ValueRange args) {
+        Value v = memref::LoadOp::create(lb, lloc, partials, ValueRange{i});
+        scf::YieldOp::create(lb, lloc, scalarAdd(lb, lloc, args[0], v));
+      });
+  Value blockSum = emitBlockReduce(b, loc, loop.getResult(0), smem, lane, warp,
+                                   warps, elemTy);
+  Value isTid0 =
+      arith::CmpIOp::create(b, loc, arith::CmpIPredicate::eq, tid, c0);
+  scf::IfOp::create(b, loc, isTid0, [&](OpBuilder &sb, Location sloc) {
+    memref::StoreOp::create(sb, sloc, blockSum, out, ValueRange{c0});
+    scf::YieldOp::create(sb, sloc);
+  });
+}
+
+/// Coalesced row-major loads into smem, barrier, then each of 128 threads
+/// reduces one column. 128 is already a multiple of the warp size, so a
+/// padded 128x132 layout is not justified for the baseline.
+static void emitColumnSumBody(OpBuilder &b, Location loc, Value in, Value out,
+                              Value smem, Value pid,
+                              const GPUTargetInfo &target, int64_t tileRows,
+                              int64_t tileCols, Type elemTy) {
+  const int warpSize = target.warpSize;
+  const int warps = target.warpsPerBlock();
+  const int rowsPerWarp = target.rowsPerWarp(static_cast<int>(tileRows));
+  const int elemsPerLane = target.elementsPerLane(static_cast<int>(tileCols));
+
+  Value tid = gpu::ThreadIdOp::create(b, loc, gpu::Dimension::x);
+  Value lane = gpu::LaneIdOp::create(b, loc, IntegerAttr());
+  Value warp = gpu::SubgroupIdOp::create(b, loc, b.getIndexType(), IntegerAttr());
+
+  Value c0 = arith::ConstantIndexOp::create(b, loc, 0);
+  Value c1 = arith::ConstantIndexOp::create(b, loc, 1);
+  Value cWarp = arith::ConstantIndexOp::create(b, loc, warpSize);
+  Value cWarps = arith::ConstantIndexOp::create(b, loc, warps);
+  Value cRows = arith::ConstantIndexOp::create(b, loc, rowsPerWarp);
+  Value cElems = arith::ConstantIndexOp::create(b, loc, elemsPerLane);
+  Value cTileRows = arith::ConstantIndexOp::create(b, loc, tileRows);
+  Value cTileCols = tileCols == tileRows
+                        ? cTileRows
+                        : arith::ConstantIndexOp::create(b, loc, tileCols);
+  Value zero = scalarZero(b, loc, elemTy);
+
+  Value m = memref::DimOp::create(b, loc, in, c0);
+  Value k = memref::DimOp::create(b, loc, in, c1);
+  Value numRowTiles = arith::CeilDivUIOp::create(b, loc, m, cTileRows);
+  Value colBase = arith::MulIOp::create(b, loc, pid, cTileCols);
+
+  Value ownsCol =
+      arith::CmpIOp::create(b, loc, arith::CmpIPredicate::ult, tid, cTileCols);
+  Value globalCol = arith::AddIOp::create(b, loc, colBase, tid);
+  Value colOK =
+      arith::CmpIOp::create(b, loc, arith::CmpIPredicate::ult, globalCol, k);
+
+  auto mtLoop = scf::ForOp::create(
+      b, loc, c0, numRowTiles, c1, ValueRange{zero},
+      [&](OpBuilder &mb, Location mloc, Value mt, ValueRange margs) {
+        Value colAcc = margs[0];
+        Value rowBase = arith::MulIOp::create(mb, mloc, mt, cTileRows);
+        scf::ForOp::create(
+            mb, mloc, c0, cRows, c1, ValueRange{},
+            [&](OpBuilder &rb, Location rloc, Value s, ValueRange) {
+              Value sScaled = arith::MulIOp::create(rb, rloc, s, cWarps);
+              Value localRow = arith::AddIOp::create(rb, rloc, warp, sScaled);
+              Value globalRow =
+                  arith::AddIOp::create(rb, rloc, rowBase, localRow);
+              Value rowOK = arith::CmpIOp::create(
+                  rb, rloc, arith::CmpIPredicate::ult, globalRow, m);
+              scf::ForOp::create(
+                  rb, rloc, c0, cElems, c1, ValueRange{},
+                  [&](OpBuilder &jb, Location jloc, Value j, ValueRange) {
+                    Value jOff = arith::MulIOp::create(jb, jloc, j, cWarp);
+                    Value localCol =
+                        arith::AddIOp::create(jb, jloc, lane, jOff);
+                    Value gCol =
+                        arith::AddIOp::create(jb, jloc, colBase, localCol);
+                    Value inB = arith::AndIOp::create(
+                        jb, jloc, rowOK,
+                        arith::CmpIOp::create(jb, jloc,
+                                              arith::CmpIPredicate::ult, gCol,
+                                              k));
+                    auto masked = scf::IfOp::create(
+                        jb, jloc, TypeRange{elemTy}, inB,
+                        /*withElseRegion=*/true);
+                    {
+                      OpBuilder::InsertionGuard guard(jb);
+                      jb.setInsertionPointToStart(masked.thenBlock());
+                      Value ld = memref::LoadOp::create(
+                          jb, jloc, in, ValueRange{globalRow, gCol});
+                      scf::YieldOp::create(jb, jloc, ld);
+                      jb.setInsertionPointToStart(masked.elseBlock());
+                      scf::YieldOp::create(jb, jloc, zero);
+                    }
+                    memref::StoreOp::create(jb, jloc, masked.getResult(0), smem,
+                                            ValueRange{localRow, localCol});
+                    scf::YieldOp::create(jb, jloc);
+                  });
+              scf::YieldOp::create(rb, rloc);
+            });
+        gpu::BarrierOp::create(mb, mloc);
+        auto reduced = scf::IfOp::create(mb, mloc, TypeRange{elemTy}, ownsCol,
+                                         /*withElseRegion=*/true);
+        {
+          OpBuilder::InsertionGuard guard(mb);
+          mb.setInsertionPointToStart(reduced.thenBlock());
+          auto rLoop = scf::ForOp::create(
+              mb, mloc, c0, cTileRows, c1, ValueRange{colAcc},
+              [&](OpBuilder &rb, Location rloc, Value r, ValueRange rargs) {
+                Value v =
+                    memref::LoadOp::create(rb, rloc, smem, ValueRange{r, tid});
+                scf::YieldOp::create(rb, rloc, scalarAdd(rb, rloc, rargs[0], v));
+              });
+          scf::YieldOp::create(mb, mloc, rLoop.getResult(0));
+          mb.setInsertionPointToStart(reduced.elseBlock());
+          scf::YieldOp::create(mb, mloc, colAcc);
+        }
+        gpu::BarrierOp::create(mb, mloc);
+        scf::YieldOp::create(mb, mloc, reduced.getResult(0));
+      });
+
+  Value canStore = arith::AndIOp::create(b, loc, ownsCol, colOK);
+  scf::IfOp::create(b, loc, canStore, [&](OpBuilder &sb, Location sloc) {
+    memref::StoreOp::create(sb, sloc, mtLoop.getResult(0), out,
+                            ValueRange{globalCol});
+    scf::YieldOp::create(sb, sloc);
+  });
+}
+
+static gpu::GPUFuncOp createKernel(OpBuilder &b, Location loc, StringRef name,
+                                   TypeRange inputs, TypeRange workgroup,
+                                   const GPUTargetInfo &target) {
+  auto fnTy = FunctionType::get(b.getContext(), inputs, {});
+  auto kernel = gpu::GPUFuncOp::create(b, loc, name, fnTy, workgroup);
+  kernel.setKernel(true);
+  kernel.setKnownBlockSizeAttr(DenseI32ArrayAttr::get(
+      b.getContext(), {target.threadsPerBlock(), 1, 1}));
+  return kernel;
+}
+
+static void emitHostLaunch(OpBuilder &b, Location loc, gpu::GPUFuncOp kernel,
+                           ValueRange args, Value gridX,
+                           const GPUTargetInfo &target) {
+  Value c1 = arith::ConstantIndexOp::create(b, loc, 1);
+  Value cBlock =
+      arith::ConstantIndexOp::create(b, loc, target.threadsPerBlock());
+  gpu::KernelDim3 grid{gridX, c1, c1};
+  gpu::KernelDim3 block{cBlock, c1, c1};
+  gpu::LaunchFuncOp::create(b, loc, kernel, grid, block, /*dynSmem=*/Value(),
+                            args);
+}
+
+static void clearBody(func::FuncOp func) {
+  Block *block = &func.getBody().front();
+  while (!block->empty())
+    block->back().erase();
+}
+
+static LogicalResult emitRowSumKernel(func::FuncOp func, ReductionMatch match,
+                                      gpu::GPUModuleOp gpuMod,
+                                      SymbolTable &gpuSymbols,
+                                      const GPUTargetInfo &target) {
+  convertBufferSignature(func);
+  Value in = match.load.getBuffer();
+  Value out = match.store.getBuffer();
+  if (!isa<MemRefType>(in.getType()) || !isa<MemRefType>(out.getType()))
+    return func.emitError("row-sum kernel expects memref buffers");
+
+  Location loc = func.getLoc();
+  Type elemTy = match.tileTy.getElementType();
+  int64_t tileRows = match.tileTy.getDimSize(0);
+  int64_t tileCols = match.tileTy.getDimSize(1);
+
+  OpBuilder kb(gpuMod.getBody(), gpuMod.getBody()->end());
+  auto kernel = createKernel(kb, loc, kRowSumKernel,
+                             TypeRange{in.getType(), out.getType()}, {},
+                             target);
+  insertUniqueKernel(gpuSymbols, kernel);
+  // Re-lookup to exercise SymbolTable::lookup after insert.
+  auto lookedUp = gpuSymbols.lookup<gpu::GPUFuncOp>(kernel.getName());
+  if (!lookedUp)
+    return func.emitError("symbol lookup failed for ") << kernel.getName();
+
+  Block &kentry = kernel.getBody().front();
+  OpBuilder body(&kentry, kentry.begin());
+  Value pid = gpu::BlockIdOp::create(body, loc, gpu::Dimension::x);
+  emitRowSumBody(body, loc, kentry.getArgument(0), kentry.getArgument(1), pid,
+                 target, tileRows, tileCols, elemTy);
+  gpu::ReturnOp::create(body, loc);
+
+  clearBody(func);
+  OpBuilder hb(&func.getBody().front(), func.getBody().front().end());
+  Value c0 = arith::ConstantIndexOp::create(hb, loc, 0);
+  Value cTile = arith::ConstantIndexOp::create(hb, loc, tileRows);
+  Value m = memref::DimOp::create(hb, loc, in, c0);
+  Value gridX = arith::CeilDivUIOp::create(hb, loc, m, cTile);
+  emitHostLaunch(hb, loc, lookedUp, ValueRange{in, out}, gridX, target);
+  func::ReturnOp::create(hb, loc);
+  (void)nestedKernelRef(gpuMod, lookedUp.getName());
+  return success();
+}
+
+static LogicalResult emitFullSumKernels(func::FuncOp func, ReductionMatch match,
+                                        gpu::GPUModuleOp gpuMod,
+                                        SymbolTable &gpuSymbols,
+                                        const GPUTargetInfo &target) {
+  convertBufferSignature(func);
+  Value in = match.load.getBuffer();
+  Value out = match.store.getBuffer();
+  if (!isa<MemRefType>(in.getType()) || !isa<MemRefType>(out.getType()))
+    return func.emitError("full-sum kernel expects memref buffers");
+
+  Location loc = func.getLoc();
+  MLIRContext *ctx = func.getContext();
+  Type elemTy = match.tileTy.getElementType();
+  int64_t tileRows = match.tileTy.getDimSize(0);
+  int64_t tileCols = match.tileTy.getDimSize(1);
+  auto partialsTy = MemRefType::get({ShapedType::kDynamic}, elemTy);
+  auto smemTy = workgroupMemRef(ctx, {target.warpsPerBlock()}, elemTy);
+
+  OpBuilder kb(gpuMod.getBody(), gpuMod.getBody()->end());
+  auto stage1 = createKernel(kb, loc, kFullSumStage1,
+                             TypeRange{in.getType(), partialsTy},
+                             TypeRange{smemTy}, target);
+  insertUniqueKernel(gpuSymbols, stage1);
+  auto stage2 = createKernel(kb, loc, kFullSumStage2,
+                             TypeRange{partialsTy, out.getType()},
+                             TypeRange{smemTy}, target);
+  insertUniqueKernel(gpuSymbols, stage2);
+
+  if (!gpuSymbols.lookup<gpu::GPUFuncOp>(stage1.getName()) ||
+      !gpuSymbols.lookup<gpu::GPUFuncOp>(stage2.getName()))
+    return func.emitError("full-sum symbol lookup failed");
+
+  {
+    Block &e = stage1.getBody().front();
+    OpBuilder body(&e, e.begin());
+    Value bid = gpu::BlockIdOp::create(body, loc, gpu::Dimension::x);
+    emitFullSumStage1Body(body, loc, e.getArgument(0), e.getArgument(1),
+                          e.getArgument(2), bid, target, tileRows, tileCols,
+                          elemTy);
+    gpu::ReturnOp::create(body, loc);
+  }
+  {
+    Block &e = stage2.getBody().front();
+    OpBuilder body(&e, e.begin());
+    emitFullSumStage2Body(body, loc, e.getArgument(0), e.getArgument(1),
+                          e.getArgument(2), target, elemTy);
+    gpu::ReturnOp::create(body, loc);
+  }
+
+  clearBody(func);
+  OpBuilder hb(&func.getBody().front(), func.getBody().front().end());
+  Value c0 = arith::ConstantIndexOp::create(hb, loc, 0);
+  Value c1 = arith::ConstantIndexOp::create(hb, loc, 1);
+  Value cTile = arith::ConstantIndexOp::create(hb, loc, tileRows);
+  Value m = memref::DimOp::create(hb, loc, in, c0);
+  Value nBlocks = arith::CeilDivUIOp::create(hb, loc, m, cTile);
+  Value partials = memref::AllocOp::create(hb, loc, partialsTy, ValueRange{nBlocks});
+  emitHostLaunch(hb, loc, stage1, ValueRange{in, partials}, nBlocks, target);
+  emitHostLaunch(hb, loc, stage2, ValueRange{partials, out}, c1, target);
+  memref::DeallocOp::create(hb, loc, partials);
+  func::ReturnOp::create(hb, loc);
+  return success();
+}
+
+static LogicalResult emitColumnSumKernel(func::FuncOp func, ReductionMatch match,
+                                         gpu::GPUModuleOp gpuMod,
+                                         SymbolTable &gpuSymbols,
+                                         const GPUTargetInfo &target) {
+  convertBufferSignature(func);
+  Value in = match.load.getBuffer();
+  Value out = match.store.getBuffer();
+  if (!isa<MemRefType>(in.getType()) || !isa<MemRefType>(out.getType()))
+    return func.emitError("column-sum kernel expects memref buffers");
+
+  Location loc = func.getLoc();
+  Type elemTy = match.tileTy.getElementType();
+  int64_t tileRows = match.tileTy.getDimSize(0);
+  int64_t tileCols = match.tileTy.getDimSize(1);
+  auto smemTy =
+      workgroupMemRef(func.getContext(), {tileRows, tileCols}, elemTy);
+
+  OpBuilder kb(gpuMod.getBody(), gpuMod.getBody()->end());
+  auto kernel = createKernel(kb, loc, kColumnSumKernel,
+                             TypeRange{in.getType(), out.getType()},
+                             TypeRange{smemTy}, target);
+  insertUniqueKernel(gpuSymbols, kernel);
+  auto lookedUp = gpuSymbols.lookup<gpu::GPUFuncOp>(kernel.getName());
+  if (!lookedUp)
+    return func.emitError("symbol lookup failed for ") << kernel.getName();
+
+  Block &e = kernel.getBody().front();
+  OpBuilder body(&e, e.begin());
+  Value pid = gpu::BlockIdOp::create(body, loc, gpu::Dimension::x);
+  emitColumnSumBody(body, loc, e.getArgument(0), e.getArgument(1),
+                    e.getArgument(2), pid, target, tileRows, tileCols, elemTy);
+  gpu::ReturnOp::create(body, loc);
+
+  clearBody(func);
+  OpBuilder hb(&func.getBody().front(), func.getBody().front().end());
+  Value c1 = arith::ConstantIndexOp::create(hb, loc, 1);
+  Value cTile = arith::ConstantIndexOp::create(hb, loc, tileCols);
+  Value k = memref::DimOp::create(hb, loc, in, c1);
+  Value gridX = arith::CeilDivUIOp::create(hb, loc, k, cTile);
+  emitHostLaunch(hb, loc, lookedUp, ValueRange{in, out}, gridX, target);
+  func::ReturnOp::create(hb, loc);
+  return success();
+}
+
+struct EmitTRGPUKernels : impl::EmitTRGPUKernelsBase<EmitTRGPUKernels> {
+  void runOnOperation() override {
+    ModuleOp module = getOperation();
+    SmallVector<std::pair<func::FuncOp, ReductionMatch>> work;
+    module.walk([&](func::FuncOp func) {
+      if (func->getParentOfType<gpu::GPUModuleOp>())
+        return;
+      ReductionMatch match = matchReduction(func);
+      if (match.kind != KernelKind::None)
+        work.emplace_back(func, match);
+    });
+    if (work.empty())
+      return;
+
+    gpu::GPUModuleOp gpuMod = getOrCreateKernelModule(module);
+    SymbolTable gpuSymbols(gpuMod);
+    GPUTargetInfo target = GPUTargetInfo::fromOp(module);
+
+    for (auto [func, match] : work) {
+      LogicalResult ok = success();
+      switch (match.kind) {
+      case KernelKind::Row:
+        ok = emitRowSumKernel(func, match, gpuMod, gpuSymbols, target);
+        break;
+      case KernelKind::Full:
+        ok = emitFullSumKernels(func, match, gpuMod, gpuSymbols, target);
+        break;
+      case KernelKind::Column:
+        ok = emitColumnSumKernel(func, match, gpuMod, gpuSymbols, target);
+        break;
+      case KernelKind::None:
+        break;
+      }
+      if (failed(ok)) {
+        signalPassFailure();
+        return;
+      }
+    }
+  }
+};
+
+} // namespace
+} // namespace mlir::tr
diff --git a/tile-reducer/test/gpu-module-symbols-invalid.mlir b/tile-reducer/test/gpu-module-symbols-invalid.mlir
new file mode 100644
index 0000000000000..26ec1efb9bb13
--- /dev/null
+++ b/tile-reducer/test/gpu-module-symbols-invalid.mlir
@@ -0,0 +1,21 @@
+// RUN: not tr-opt %s 2>&1 | FileCheck %s
+
+// Milestone 20: nested SymbolRefAttr lookup is a hard failure when the
+// kernel symbol is missing. gpu.launch_func uses SymbolUserOpInterface.
+
+module attributes {gpu.container_module} {
+  gpu.module @tr_kernels {
+    gpu.func @other_kernel() kernel {
+      gpu.return
+    }
+  }
+  func.func @host(%in: memref<?x?xf32>, %out: memref<?xf32>) {
+    %c1 = arith.constant 1 : index
+    %c256 = arith.constant 256 : index
+    // CHECK: kernel function '@tr_kernels::@row_sum_kernel' is undefined
+    gpu.launch_func @tr_kernels::@row_sum_kernel
+        blocks in (%c1, %c1, %c1) threads in (%c256, %c1, %c1)
+        args(%in : memref<?x?xf32>, %out : memref<?xf32>)
+    return
+  }
+}
diff --git a/tile-reducer/test/gpu-module-symbols-lookup.mlir b/tile-reducer/test/gpu-module-symbols-lookup.mlir
new file mode 100644
index 0000000000000..ae209ae4c5aad
--- /dev/null
+++ b/tile-reducer/test/gpu-module-symbols-lookup.mlir
@@ -0,0 +1,36 @@
+// RUN: tr-opt %s --tr-emit-gpu-kernels | FileCheck %s
+
+// Milestone 20: SymbolTable lookup of an existing @tr_kernels. The pass
+// must insert the new kernel into that module, not create a second one.
+
+// CHECK-COUNT-1: gpu.module @tr_kernels
+// CHECK: gpu.func @already_there
+// CHECK: gpu.func @row_sum_kernel
+// CHECK: gpu.launch_func @tr_kernels::@row_sum_kernel
+
+module attributes {gpu.container_module} {
+  gpu.module @tr_kernels {
+    gpu.func @already_there() kernel {
+      gpu.return
+    }
+  }
+
+  func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+    %row_blk     = tr.program_id 0 : index
+    %c128        = arith.constant 128 : index
+    %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+    %num_k_tiles = arith.divui %k, %c128 : index
+    %zero = tr.constant 0.0 : !tr.tile<128xf32>
+    %result = tr.for %kt = 0 to %num_k_tiles step 1
+        iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+      %t       = tr.load %in[%row_blk, %kt]
+          : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+      %partial = tr.reduce_sum %t, axis = 1
+          : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+      %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+      tr.yield %acc2 : !tr.tile<128xf32>
+    }
+    tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+    return
+  }
+}
diff --git a/tile-reducer/test/gpu-module-symbols-unique.mlir b/tile-reducer/test/gpu-module-symbols-unique.mlir
new file mode 100644
index 0000000000000..694527986e724
--- /dev/null
+++ b/tile-reducer/test/gpu-module-symbols-unique.mlir
@@ -0,0 +1,38 @@
+// RUN: tr-opt %s --tr-emit-gpu-kernels | FileCheck %s
+
+// Milestone 20: SymbolTable::insert uniquifies when @row_sum_kernel exists.
+// The host must launch the new unique symbol, not the pre-existing stub.
+
+// CHECK: gpu.func @row_sum_kernel(
+// CHECK: gpu.return
+// CHECK: gpu.func @row_sum_kernel_{{.*}}
+// CHECK: gpu.block_id x
+// CHECK: gpu.launch_func @tr_kernels::@row_sum_kernel_{{.*}}
+// CHECK-NOT: gpu.launch_func @tr_kernels::@row_sum_kernel blocks
+
+module attributes {gpu.container_module} {
+  gpu.module @tr_kernels {
+    gpu.func @row_sum_kernel(%arg0: memref<?x?xf32>, %arg1: memref<?xf32>) kernel {
+      gpu.return
+    }
+  }
+
+  func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+    %row_blk     = tr.program_id 0 : index
+    %c128        = arith.constant 128 : index
+    %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+    %num_k_tiles = arith.divui %k, %c128 : index
+    %zero = tr.constant 0.0 : !tr.tile<128xf32>
+    %result = tr.for %kt = 0 to %num_k_tiles step 1
+        iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+      %t       = tr.load %in[%row_blk, %kt]
+          : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+      %partial = tr.reduce_sum %t, axis = 1
+          : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+      %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+      tr.yield %acc2 : !tr.tile<128xf32>
+    }
+    tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+    return
+  }
+}
diff --git a/tile-reducer/test/gpu-module-symbols.mlir b/tile-reducer/test/gpu-module-symbols.mlir
new file mode 100644
index 0000000000000..1e0fa925a4d6d
--- /dev/null
+++ b/tile-reducer/test/gpu-module-symbols.mlir
@@ -0,0 +1,39 @@
+// RUN: tr-opt %s --tr-emit-gpu-kernels | FileCheck %s
+
+// Milestone 20: gpu.module @tr_kernels, SymbolTable insert/lookup, and a
+// nested SymbolRefAttr on gpu.launch_func (@tr_kernels::@row_sum_kernel).
+// The host launches by symbol, not by a string name.
+
+// CHECK: module attributes {gpu.container_module}
+// CHECK: gpu.module @tr_kernels
+// CHECK: gpu.func @row_sum_kernel
+// CHECK-SAME: kernel
+// CHECK: gpu.block_id x
+// CHECK: gpu.lane_id
+// CHECK: gpu.subgroup_id
+// CHECK: gpu.subgroup_reduce add
+// CHECK: gpu.return
+
+// CHECK: func.func @row_sum
+// CHECK: gpu.launch_func @tr_kernels::@row_sum_kernel
+// CHECK-SAME: blocks in
+// CHECK-SAME: threads in
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}

>From 2506b701b71080268c466388c63c4e35af0271a7 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:10:20 -0700
Subject: [PATCH 21/29] [TileReducer] Milestone 21: full reduction two-kernel
 symbols

MxK -> scalar becomes @full_sum_stage1 and @full_sum_stage2 inside
gpu.module @tr_kernels. Stage 1: thread-local sum, warp reduce, smem[warp],
barrier, block reduce, one partial per block. Stage 2 reduces the partials.
No unordered FP atomics. Scalar !tr.tile<f32> may store into a rank-1 buffer.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/convert-full-sum-gpu.mlir
  tr-opt --tr-emit-gpu-kernels tile-reducer/test/convert-full-sum-gpu.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/examples/full_sum.mlir           | 23 +++++++++++
 .../lib/TileReducer/TileReducerOps.cpp        | 24 +++++++++++
 tile-reducer/test/convert-full-sum-gpu.mlir   | 41 +++++++++++++++++++
 3 files changed, 88 insertions(+)
 create mode 100644 tile-reducer/examples/full_sum.mlir
 create mode 100644 tile-reducer/test/convert-full-sum-gpu.mlir

diff --git a/tile-reducer/examples/full_sum.mlir b/tile-reducer/examples/full_sum.mlir
new file mode 100644
index 0000000000000..a03c906ad2763
--- /dev/null
+++ b/tile-reducer/examples/full_sum.mlir
@@ -0,0 +1,23 @@
+// Full MxK -> scalar. The compiler emits @full_sum_stage1 / @full_sum_stage2.
+
+func.func @full_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<1xf32>) {
+  %blk  = tr.program_id 0 : index
+  %c128 = arith.constant 128 : index
+  %c0   = arith.constant 0 : index
+  %k    = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num  = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<f32>
+  %result = tr.for %kt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<f32> {
+    %t    = tr.load %in[%blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %row  = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %s    = tr.reduce_sum %row, axis = 0
+        : !tr.tile<128xf32> -> !tr.tile<f32>
+    %acc2 = tr.add %acc, %s : !tr.tile<f32>
+    tr.yield %acc2 : !tr.tile<f32>
+  }
+  tr.store %out[%c0], %result : !tr.buffer<1xf32>, !tr.tile<f32>
+  return
+}
diff --git a/tile-reducer/lib/TileReducer/TileReducerOps.cpp b/tile-reducer/lib/TileReducer/TileReducerOps.cpp
index c5755ea97db74..53362c7481b27 100644
--- a/tile-reducer/lib/TileReducer/TileReducerOps.cpp
+++ b/tile-reducer/lib/TileReducer/TileReducerOps.cpp
@@ -146,6 +146,30 @@ LogicalResult StoreOp::verify() {
   auto tile = dyn_cast<TileType>(getValue().getType());
   if (!tile)
     return emitOpError("store value must be a !tr.tile");
+  // Rank-0 tiles are scalars. They store into a rank-1 buffer at one
+  // index (one slot per program instance, or the single full-sum slot).
+  if (tile.getRank() == 0) {
+    int64_t rank = -1;
+    Type elem;
+    if (auto buffer = dyn_cast<BufferType>(getBuffer().getType())) {
+      rank = buffer.getRank();
+      elem = buffer.getElementType();
+    } else if (auto memref = dyn_cast<MemRefType>(getBuffer().getType())) {
+      rank = memref.getRank();
+      elem = memref.getElementType();
+    } else {
+      return emitOpError("expected !tr.buffer or memref, got ")
+             << getBuffer().getType();
+    }
+    if (rank != 1 || getIndices().size() != 1)
+      return emitOpError("scalar tile store expects one index into a rank-1 "
+                         "buffer");
+    if (tile.getElementType() != elem)
+      return emitOpError("tile element type ")
+             << tile.getElementType() << " does not match buffer element type "
+             << elem;
+    return success();
+  }
   return verifyTileCoords(*this, getBuffer().getType(), getIndices(), tile,
                           "store");
 }
diff --git a/tile-reducer/test/convert-full-sum-gpu.mlir b/tile-reducer/test/convert-full-sum-gpu.mlir
new file mode 100644
index 0000000000000..5c82b78cc18ef
--- /dev/null
+++ b/tile-reducer/test/convert-full-sum-gpu.mlir
@@ -0,0 +1,41 @@
+// RUN: tr-opt %s --tr-emit-gpu-kernels | FileCheck %s
+
+// Milestone 21: MxK -> scalar via two kernels inside @tr_kernels.
+//   thread local sum -> warp reduce -> smem[warp] -> barrier -> block reduce
+//   @full_sum_stage1 writes one partial per block
+//   @full_sum_stage2 reduces the partials
+// Prefer two-stage reduction over unordered FP atomics.
+
+// CHECK: gpu.module @tr_kernels
+// CHECK: gpu.func @full_sum_stage1
+// CHECK-SAME: workgroup(%{{.*}}: memref<8xf32, #gpu.address_space<workgroup>>)
+// CHECK-SAME: kernel
+// CHECK: gpu.subgroup_reduce add
+// CHECK: gpu.barrier
+// CHECK: gpu.func @full_sum_stage2
+// CHECK-SAME: kernel
+// CHECK: gpu.launch_func @tr_kernels::@full_sum_stage1
+// CHECK: gpu.launch_func @tr_kernels::@full_sum_stage2
+// CHECK-NOT: gpu.atomic
+
+func.func @full_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<1xf32>) {
+  %blk  = tr.program_id 0 : index
+  %c128 = arith.constant 128 : index
+  %c0   = arith.constant 0 : index
+  %k    = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num  = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<f32>
+  %result = tr.for %kt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<f32> {
+    %t    = tr.load %in[%blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %row  = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %s    = tr.reduce_sum %row, axis = 0
+        : !tr.tile<128xf32> -> !tr.tile<f32>
+    %acc2 = tr.add %acc, %s : !tr.tile<f32>
+    tr.yield %acc2 : !tr.tile<f32>
+  }
+  tr.store %out[%c0], %result : !tr.buffer<1xf32>, !tr.tile<f32>
+  return
+}

>From aeca5680a768db66f7566d9a66e64af2fb922f8c Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:10:20 -0700
Subject: [PATCH 22/29] [TileReducer] Milestone 22: column reduction via
 shared-memory staging

Row-major column sum: coalesced global loads into a 128x128 workgroup
memref, gpu.barrier, then one thread per column. 128 is a multiple of
the warp size, so a padded 128x132 layout is not used. Direct strided
in[row, col] would break coalescing.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/convert-column-sum-gpu.mlir
  tr-opt --tr-emit-gpu-kernels tile-reducer/test/convert-column-sum-gpu.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/examples/column_sum.mlir         | 20 ++++++++++
 tile-reducer/test/convert-column-sum-gpu.mlir | 37 +++++++++++++++++++
 2 files changed, 57 insertions(+)
 create mode 100644 tile-reducer/examples/column_sum.mlir
 create mode 100644 tile-reducer/test/convert-column-sum-gpu.mlir

diff --git a/tile-reducer/examples/column_sum.mlir b/tile-reducer/examples/column_sum.mlir
new file mode 100644
index 0000000000000..204cad725c217
--- /dev/null
+++ b/tile-reducer/examples/column_sum.mlir
@@ -0,0 +1,20 @@
+// Column reduction of a row-major buffer. The compiler stages through smem.
+
+func.func @column_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Kxf32>) {
+  %col_blk = tr.program_id 0 : index
+  %c128    = arith.constant 128 : index
+  %m       = tr.dim %in, 0 : !tr.buffer<MxKxf32>, index
+  %num     = arith.divui %m, %c128 : index
+  %zero    = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %mt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%mt, %col_blk]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 0
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%col_blk], %result : !tr.buffer<Kxf32>, !tr.tile<128xf32>
+  return
+}
diff --git a/tile-reducer/test/convert-column-sum-gpu.mlir b/tile-reducer/test/convert-column-sum-gpu.mlir
new file mode 100644
index 0000000000000..b488c75411e7f
--- /dev/null
+++ b/tile-reducer/test/convert-column-sum-gpu.mlir
@@ -0,0 +1,37 @@
+// RUN: tr-opt %s --tr-emit-gpu-kernels | FileCheck %s
+
+// Milestone 22: column reduction on row-major input.
+//   coalesced row-major global loads
+//   -> shared-memory staging (128x128, no pad: 128 is a multiple of 32)
+//   -> gpu.barrier
+//   -> column-oriented reduction
+// Direct strided access would load in[row, col] with a row stride and
+// break coalescing; smem staging is the baseline.
+
+// CHECK: gpu.module @tr_kernels
+// CHECK: gpu.func @column_sum_kernel
+// CHECK-SAME: workgroup(%{{.*}}: memref<128x128xf32, #gpu.address_space<workgroup>>)
+// CHECK-SAME: kernel
+// CHECK: memref.load
+// CHECK: memref.store %{{.*}}, %{{.*}}[%{{.*}}, %{{.*}}]
+// CHECK: gpu.barrier
+// CHECK: gpu.launch_func @tr_kernels::@column_sum_kernel
+
+func.func @column_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Kxf32>) {
+  %col_blk = tr.program_id 0 : index
+  %c128    = arith.constant 128 : index
+  %m       = tr.dim %in, 0 : !tr.buffer<MxKxf32>, index
+  %num     = arith.divui %m, %c128 : index
+  %zero    = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %mt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%mt, %col_blk]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 0
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%col_blk], %result : !tr.buffer<Kxf32>, !tr.tile<128xf32>
+  return
+}

>From 6a4974800a89fc49572ae09550be03256ceb08c3 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:23:01 -0700
Subject: [PATCH 23/29] [TileReducer] Milestone 23: ReductionSchedule and
 roofline cost model

T ~= max(T_compute, T_memory) + T_sync + T_launch + T_tail.
--tr-estimate-reduction-cost records occupancy, coalescing, register/smem
pressure, and grid saturation. Not cycle-exact.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/cost-model.mlir
  tr-opt --tr-estimate-reduction-cost='rows=1024 cols=1024' tile-reducer/test/cost-model.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |  35 ++
 .../include/TileReducer/ReductionSchedule.h   | 111 +++++
 .../include/TileReducer/TileReducerPasses.td  |  45 ++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |   2 +
 .../lib/TileReducer/ReductionCostModel.cpp    | 429 ++++++++++++++++++
 .../lib/TileReducer/TileReducerCostPasses.cpp | 137 ++++++
 tile-reducer/test/cost-model.mlir             |  36 ++
 7 files changed, 795 insertions(+)
 create mode 100644 tile-reducer/include/TileReducer/ReductionSchedule.h
 create mode 100644 tile-reducer/lib/TileReducer/ReductionCostModel.cpp
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerCostPasses.cpp
 create mode 100644 tile-reducer/test/cost-model.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index 873873e55888c..c9a7c16ca6b97 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -118,3 +118,38 @@ Column reduction on row-major input: coalesced global loads into a
 128×128 workgroup memref, `gpu.barrier`, then one thread per column.
 128 is already a multiple of the warp size, so a padded 128×132 layout
 is not used. Direct strided `in[row, col]` would break coalescing.
+
+## Milestone 23
+
+`ReductionSchedule` plus a roofline cost model:
+`T ~= max(T_compute, T_memory) + T_sync + T_launch + T_tail`.
+`--tr-estimate-reduction-cost` records occupancy, coalescing, register /
+smem pressure, and grid saturation. Not cycle-exact.
+
+## Milestone 24
+
+`--tr-emit-gpu-kernels=k-splits=N` refines one logical row program into
+N physical blocks (`gpu.block_id y`) plus `@row_sum_splitk_stage2`.
+`tr.program_id` is still `gpu.block_id x`. Used when M is small and K is
+huge (e.g. M=1, K=1e8).
+
+## Milestone 25
+
+`--tr-autotune-reduction` enumerates a bounded legal space, prunes
+analytically, and caches the winner by
+`kind|axis|dtype|tile|shape-bucket|arch|compiler`. It does not tune
+every exact shape.
+
+## Milestone 26
+
+Async / double-buffering is measured after the baseline. Row-sum
+intensity is too low; extra smem and registers do not pay off, so the
+winner keeps `asyncDepth = 0`.
+
+## Milestone 27
+
+Boundary matrix `M ∈ {1,31,32,127,128,129}`,
+`K ∈ {0,1,31,32,33,127,128,129,255,256,257}` for row, column, and full.
+Property: `full_sum(A) ~= sum(row_sum(A)) ~= sum(column_sum(A))`.
+`--tr-bench-report` records latency, GB/s, threads/block, registers,
+smem, occupancy, and kernel count.
diff --git a/tile-reducer/include/TileReducer/ReductionSchedule.h b/tile-reducer/include/TileReducer/ReductionSchedule.h
new file mode 100644
index 0000000000000..7aa058ca60d5b
--- /dev/null
+++ b/tile-reducer/include/TileReducer/ReductionSchedule.h
@@ -0,0 +1,111 @@
+//===- ReductionSchedule.h - cost model / autotune --------------*- C++ -*-===//
+//
+// Milestone 23: candidate schedules and a roofline-style cost model.
+// Not cycle-exact. T ~= max(T_compute, T_memory) + T_sync + T_launch + T_tail.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef TILE_REDUCER_REDUCTIONSCHEDULE_H
+#define TILE_REDUCER_REDUCTIONSCHEDULE_H
+
+#include "TileReducer/GPUTargetInfo.h"
+#include "llvm/ADT/StringRef.h"
+#include <string>
+#include <vector>
+
+namespace mlir {
+class Operation;
+
+namespace tr {
+
+enum class ReductionKindName { Row, Column, Full };
+
+struct ReductionSchedule {
+  int threadsPerBlock = 256;
+  int warpsPerBlock = 8;
+  int rowsPerWarp = 16;
+  int elementsPerLane = 4;
+  bool useSharedMemory = false;
+  int asyncDepth = 0;
+  /// Physical blocks that refine one logical program along K. 1 means
+  /// `tr.program_id` maps to one GPU block.
+  int kSplits = 1;
+
+  static ReductionSchedule baselineRow();
+  static ReductionSchedule baselineColumn();
+  static ReductionSchedule baselineFull();
+};
+
+struct ReductionProblem {
+  ReductionKindName kind = ReductionKindName::Row;
+  int axis = 1;
+  int64_t tileRows = 128;
+  int64_t tileCols = 128;
+  int elemBits = 32;
+  int64_t M = 1024;
+  int64_t K = 1024;
+  std::string dtype = "f32";
+  std::string arch = "a100-like";
+  std::string compiler = "tile-reducer-23";
+};
+
+struct CostEstimate {
+  double tCompute = 0;
+  double tMemory = 0;
+  double tSync = 0;
+  double tLaunch = 0;
+  double tTail = 0;
+  double tTotal = 0;
+  double occupancy = 0;
+  double coalescing = 1;
+  double gridSaturation = 1;
+  int registersPerThread = 0;
+  int sharedMemoryBytes = 0;
+  int kernelCount = 1;
+  int nBlocks = 1;
+  bool legal = true;
+  std::string limiter = "none";
+  std::string rejectReason;
+};
+
+struct TuneResult {
+  ReductionSchedule winner;
+  CostEstimate cost;
+  std::string cacheKey;
+  std::string shapeBucket;
+  int candidates = 0;
+  int pruned = 0;
+  bool asyncHelpsRowSum = false;
+  double baselineRowUs = 0;
+  double asyncRowUs = 0;
+};
+
+/// Roofline-style estimate. Units are microseconds.
+CostEstimate estimateCost(const ReductionProblem &prob,
+                          const ReductionSchedule &sched,
+                          const GPUTargetInfo &target);
+
+/// Bounded legal space for autotune. Does not enumerate every M×K.
+std::vector<ReductionSchedule> enumerateSchedules(const ReductionProblem &prob,
+                                                  const GPUTargetInfo &target);
+
+/// Analytically prune, rank by tTotal, cache the winner by shape bucket.
+TuneResult autotune(const ReductionProblem &prob, const GPUTargetInfo &target);
+
+std::string shapeBucket(const ReductionProblem &prob,
+                        const GPUTargetInfo &target);
+std::string tuneCacheKey(const ReductionProblem &prob,
+                         const GPUTargetInfo &target);
+
+/// Write schedule + cost fields as `tr.schedule.*` / `tr.cost.*` / `tr.tune.*`
+/// / `tr.bench.*` attributes on `op`.
+void applyCostAttrs(Operation *op, const ReductionSchedule &sched,
+                    const CostEstimate &cost);
+void applyTuneAttrs(Operation *op, const TuneResult &result);
+void applyBenchAttrs(Operation *op, const ReductionSchedule &sched,
+                     const CostEstimate &cost, const ReductionProblem &prob);
+
+} // namespace tr
+} // namespace mlir
+
+#endif // TILE_REDUCER_REDUCTIONSCHEDULE_H
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
index 2f9e0cb0a60b4..5bb6bac850527 100644
--- a/tile-reducer/include/TileReducer/TileReducerPasses.td
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -151,6 +151,9 @@ def EmitTRGPUKernels : Pass<"tr-emit-gpu-kernels", "::mlir::ModuleOp"> {
     Row sum: `@row_sum_kernel` (no shared memory).
     Full sum: `@full_sum_stage1` + `@full_sum_stage2` (smem block reduce).
     Column sum: `@column_sum_kernel` (smem staging + barrier).
+
+    `k-splits > 1` refines one logical row program into many physical
+    blocks (`gpu.block_id y`) plus a second reduction stage.
   }];
   let dependentDialects = [
     "::mlir::tr::TileReducerDialect",
@@ -160,6 +163,48 @@ def EmitTRGPUKernels : Pass<"tr-emit-gpu-kernels", "::mlir::ModuleOp"> {
     "::mlir::memref::MemRefDialect",
     "::mlir::func::FuncDialect"
   ];
+  let options = [
+    Option<"kSplits", "k-splits", "int", /*default=*/"1",
+           "Physical K-splits per logical row (1 = one block per program_id)">
+  ];
+}
+
+def EstimateTRReductionCost : Pass<"tr-estimate-reduction-cost", "::mlir::ModuleOp"> {
+  let summary = "Annotate the baseline ReductionSchedule cost model.";
+  let description = [{
+    T ~= max(T_compute, T_memory) + T_sync + T_launch + T_tail.
+    Includes occupancy, coalescing, register/smem pressure, and grid
+    saturation. Not cycle-exact.
+  }];
+  let options = [
+    Option<"problemM", "rows", "int64_t", /*default=*/"0",
+           "Problem rows (0 = use 1024 as a representative bucket)">,
+    Option<"problemK", "cols", "int64_t", /*default=*/"0",
+           "Problem cols (0 = use 1024 as a representative bucket)">
+  ];
+}
+
+def AutotuneTRReduction : Pass<"tr-autotune-reduction", "::mlir::ModuleOp"> {
+  let summary = "Enumerate legal schedules, prune, rank, and cache by shape bucket.";
+  let description = [{
+    Cache key: kind, axis, dtype, tile shape, shape bucket, arch, compiler.
+    Does not tune every exact M×K. Autotune runs only after a correct
+    baseline exists.
+  }];
+  let options = [
+    Option<"problemM", "rows", "int64_t", /*default=*/"0",
+           "Problem rows for the shape bucket">,
+    Option<"problemK", "cols", "int64_t", /*default=*/"0",
+           "Problem cols for the shape bucket">
+  ];
+}
+
+def TRBenchReport : Pass<"tr-bench-report", "::mlir::ModuleOp"> {
+  let summary = "Record latency, GB/s, occupancy, and kernel-count estimates.";
+  let options = [
+    Option<"problemM", "rows", "int64_t", /*default=*/"0", "Problem rows">,
+    Option<"problemK", "cols", "int64_t", /*default=*/"0", "Problem cols">
+  ];
 }
 
 def ConvertTRToLinalg : Pass<"convert-tr-to-linalg", "::mlir::func::FuncOp"> {
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index e97e9f6c245eb..f728eb21cd518 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -11,6 +11,8 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerGPUTarget.cpp
         TileReducerGPURowSum.cpp
         TileReducerGPUKernels.cpp
+        ReductionCostModel.cpp
+        TileReducerCostPasses.cpp
         TileReducerPasses.cpp
 
         ADDITIONAL_HEADER_DIRS
diff --git a/tile-reducer/lib/TileReducer/ReductionCostModel.cpp b/tile-reducer/lib/TileReducer/ReductionCostModel.cpp
new file mode 100644
index 0000000000000..202138eed103a
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/ReductionCostModel.cpp
@@ -0,0 +1,429 @@
+//===- ReductionCostModel.cpp - Milestones 23-27 ----------------*- C++ -*-===//
+//
+// Roofline cost model, bounded autotune, and attribute writers.
+// T ~= max(T_compute, T_memory) + T_sync + T_launch + T_tail  (microseconds).
+// Not cycle-exact: occupancy, coalescing, register/smem pressure, and grid
+// saturation are first-order terms only.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/ReductionSchedule.h"
+
+#include "mlir/IR/BuiltinAttributes.h"
+#include "mlir/IR/BuiltinTypes.h"
+#include "mlir/IR/Operation.h"
+#include "llvm/ADT/StringRef.h"
+
+#include <algorithm>
+#include <cmath>
+#include <map>
+#include <sstream>
+
+using namespace mlir;
+
+namespace mlir::tr {
+
+namespace {
+
+constexpr double kLaunchUs = 5.0;
+constexpr double kBarrierUs = 0.25;
+
+static int elemBytes(const ReductionProblem &prob) {
+  return std::max(1, prob.elemBits / 8);
+}
+
+static int64_t nRowTiles(const ReductionProblem &prob) {
+  return std::max<int64_t>(1, (prob.M + prob.tileRows - 1) / prob.tileRows);
+}
+
+static int64_t nColTiles(const ReductionProblem &prob) {
+  return std::max<int64_t>(1, (prob.K + prob.tileCols - 1) / prob.tileCols);
+}
+
+static int estimateRegs(const ReductionSchedule &sched) {
+  int regs = 16 + sched.elementsPerLane * 2;
+  if (sched.useSharedMemory)
+    regs += 8;
+  regs += sched.asyncDepth * 12;
+  return std::min(regs, 255);
+}
+
+static int estimateSmem(const ReductionProblem &prob,
+                        const ReductionSchedule &sched) {
+  if (!sched.useSharedMemory)
+    return 0;
+  int bytes = 0;
+  if (prob.kind == ReductionKindName::Column)
+    bytes = static_cast<int>(prob.tileRows * prob.tileCols * elemBytes(prob));
+  else
+    bytes = sched.warpsPerBlock * elemBytes(prob);
+  if (sched.asyncDepth >= 2)
+    bytes *= 2;
+  return bytes;
+}
+
+static int kernelCount(const ReductionProblem &prob,
+                       const ReductionSchedule &sched) {
+  if (prob.kind == ReductionKindName::Full)
+    return 2;
+  if (sched.kSplits > 1)
+    return 2;
+  return 1;
+}
+
+static int nBlocks(const ReductionProblem &prob,
+                   const ReductionSchedule &sched) {
+  switch (prob.kind) {
+  case ReductionKindName::Row:
+    return static_cast<int>(nRowTiles(prob) * std::max(1, sched.kSplits));
+  case ReductionKindName::Column:
+    return static_cast<int>(nColTiles(prob));
+  case ReductionKindName::Full:
+    return static_cast<int>(nRowTiles(prob));
+  }
+  return 1;
+}
+
+static double coalescingFactor(const ReductionProblem &prob,
+                               const ReductionSchedule &sched) {
+  if (prob.kind == ReductionKindName::Column && !sched.useSharedMemory)
+    return 1.0 / 32.0;
+  return 1.0;
+}
+
+} // namespace
+
+ReductionSchedule ReductionSchedule::baselineRow() {
+  ReductionSchedule s;
+  s.useSharedMemory = false;
+  s.asyncDepth = 0;
+  s.kSplits = 1;
+  return s;
+}
+
+ReductionSchedule ReductionSchedule::baselineColumn() {
+  ReductionSchedule s;
+  s.useSharedMemory = true;
+  s.asyncDepth = 0;
+  s.kSplits = 1;
+  return s;
+}
+
+ReductionSchedule ReductionSchedule::baselineFull() {
+  ReductionSchedule s;
+  s.useSharedMemory = true;
+  s.asyncDepth = 0;
+  s.kSplits = 1;
+  return s;
+}
+
+CostEstimate estimateCost(const ReductionProblem &prob,
+                          const ReductionSchedule &sched,
+                          const GPUTargetInfo &target) {
+  CostEstimate c;
+  c.registersPerThread = estimateRegs(sched);
+  c.sharedMemoryBytes = estimateSmem(prob, sched);
+  c.kernelCount = kernelCount(prob, sched);
+  c.nBlocks = nBlocks(prob, sched);
+  c.coalescing = coalescingFactor(prob, sched);
+
+  if (sched.threadsPerBlock <= 0 ||
+      sched.threadsPerBlock % target.warpSize != 0 ||
+      sched.threadsPerBlock > target.maxThreadsPerBlock) {
+    c.legal = false;
+    c.rejectReason = "illegal thread count";
+    return c;
+  }
+  if (prob.tileRows % std::max(1, sched.warpsPerBlock) != 0 ||
+      prob.tileCols % target.warpSize != 0) {
+    c.legal = false;
+    c.rejectReason = "tile not divisible by the GPU map";
+    return c;
+  }
+  if (sched.asyncDepth > 0 && !sched.useSharedMemory) {
+    c.legal = false;
+    c.rejectReason = "async pipeline requires shared memory";
+    return c;
+  }
+  if (sched.asyncDepth < 0 || sched.asyncDepth == 1 || sched.asyncDepth > 2) {
+    c.legal = false;
+    c.rejectReason = "asyncDepth must be 0 or 2";
+    return c;
+  }
+  if (sched.kSplits < 1) {
+    c.legal = false;
+    c.rejectReason = "kSplits must be >= 1";
+    return c;
+  }
+  if (c.sharedMemoryBytes > target.sharedMemoryPerBlock) {
+    c.legal = false;
+    c.rejectReason = "shared memory exceeds per-block limit";
+    c.limiter = "shared_memory";
+    return c;
+  }
+  if (c.registersPerThread > target.maxRegistersPerThread) {
+    c.legal = false;
+    c.rejectReason = "register pressure";
+    c.limiter = "registers";
+    return c;
+  }
+
+  int regsPerBlock = c.registersPerThread * sched.threadsPerBlock;
+  int byRegs = regsPerBlock ? target.registersPerSM / regsPerBlock
+                            : target.maxBlocksPerSM;
+  int bySmem = c.sharedMemoryBytes
+                   ? target.sharedMemoryPerSM / c.sharedMemoryBytes
+                   : target.maxBlocksPerSM;
+  int blocksPerSM =
+      std::max(0, std::min({target.maxBlocksPerSM, byRegs, bySmem}));
+  int warpsPerSM = blocksPerSM * sched.warpsPerBlock;
+  c.occupancy = target.maxWarpsPerSM
+                    ? static_cast<double>(warpsPerSM) / target.maxWarpsPerSM
+                    : 0.0;
+  if (blocksPerSM == 0) {
+    c.legal = false;
+    c.rejectReason = "zero occupancy";
+    c.limiter = byRegs < bySmem ? "registers" : "shared_memory";
+    return c;
+  }
+  if (byRegs <= bySmem && byRegs <= target.maxBlocksPerSM)
+    c.limiter = "registers";
+  else if (bySmem <= target.maxBlocksPerSM)
+    c.limiter = "shared_memory";
+  else
+    c.limiter = "occupancy";
+
+  int activeSMs = std::min(target.numSMs, c.nBlocks);
+  c.gridSaturation =
+      target.numSMs ? static_cast<double>(activeSMs) / target.numSMs : 1.0;
+
+  double bytes = static_cast<double>(prob.M) * static_cast<double>(prob.K) *
+                 elemBytes(prob);
+  if (prob.kind == ReductionKindName::Row)
+    bytes += static_cast<double>(prob.M) * elemBytes(prob);
+  else if (prob.kind == ReductionKindName::Column)
+    bytes += static_cast<double>(prob.K) * elemBytes(prob);
+  else
+    bytes += elemBytes(prob);
+  if (sched.kSplits > 1)
+    bytes += static_cast<double>(prob.M) * sched.kSplits * elemBytes(prob);
+
+  double flops = static_cast<double>(prob.M) * static_cast<double>(prob.K);
+  double sat = std::max(c.gridSaturation, 1.0 / std::max(1, target.numSMs));
+  double occ = std::max(c.occupancy, 0.05);
+  double bw = target.memoryBandwidthGBs * sat * c.coalescing; // GB/s
+  double peak = target.fp32PeakTFLOPs * sat * occ;            // TFLOP/s
+  c.tMemory = bw > 0 ? (bytes / 1e9) / bw * 1e6 : 1e9;
+  c.tCompute = peak > 0 ? (flops / 1e12) / peak * 1e6 : 1e9;
+
+  int nBarriers = 0;
+  if (sched.useSharedMemory)
+    nBarriers = (prob.kind == ReductionKindName::Column)
+                    ? static_cast<int>(nRowTiles(prob)) * 2
+                    : 1;
+  if (sched.asyncDepth >= 2)
+    nBarriers += 2;
+  c.tSync = nBarriers * kBarrierUs;
+  c.tLaunch = c.kernelCount * kLaunchUs;
+
+  int64_t rem = prob.K % prob.tileCols;
+  if (rem != 0) {
+    double frac =
+        static_cast<double>(prob.tileCols - rem) / prob.tileCols;
+    c.tTail = frac * c.tMemory / std::max<int64_t>(1, nColTiles(prob));
+  }
+
+  // Async hides memory only when there is enough compute to overlap.
+  // Row-sum intensity is ~0.25 flop/byte; do not credit a pipeline there.
+  double intensity = c.tMemory > 0 ? c.tCompute / c.tMemory : 0.0;
+  if (sched.asyncDepth >= 2 && sched.useSharedMemory && intensity > 0.25) {
+    double hide = std::min(c.tMemory, c.tCompute) * 0.3;
+    c.tMemory = std::max(0.0, c.tMemory - hide);
+  }
+
+  c.tTotal = std::max(c.tCompute, c.tMemory) + c.tSync + c.tLaunch + c.tTail;
+  return c;
+}
+
+std::vector<ReductionSchedule> enumerateSchedules(const ReductionProblem &prob,
+                                                  const GPUTargetInfo &target) {
+  std::vector<ReductionSchedule> out;
+  const int tileRows = static_cast<int>(prob.tileRows);
+  const int tileCols = static_cast<int>(prob.tileCols);
+  for (int threads : {128, 256, 512}) {
+    if (threads > target.maxThreadsPerBlock)
+      continue;
+    int warps = threads / target.warpSize;
+    if (warps == 0 || tileRows % warps != 0)
+      continue;
+    ReductionSchedule s;
+    s.threadsPerBlock = threads;
+    s.warpsPerBlock = warps;
+    s.rowsPerWarp = tileRows / warps;
+    s.elementsPerLane = tileCols / target.warpSize;
+    for (bool smem : {false, true}) {
+      if (prob.kind == ReductionKindName::Column && !smem)
+        continue; // baseline column uses smem; strided is enumerated below
+      if (prob.kind == ReductionKindName::Full && !smem)
+        continue;
+      s.useSharedMemory = smem;
+      for (int async : {0, 2}) {
+        if (async && !smem)
+          continue;
+        s.asyncDepth = async;
+        for (int splits : {1, 4, 16, 64}) {
+          if (prob.kind == ReductionKindName::Column && splits != 1)
+            continue;
+          // Large-K split is only for under-occupied grids. Enough row
+          // tiles already saturate the SMs; do not refine further.
+          if (splits > 1 && nRowTiles(prob) >= target.numSMs)
+            continue;
+          s.kSplits = splits;
+          out.push_back(s);
+        }
+      }
+    }
+    if (prob.kind == ReductionKindName::Column) {
+      s.useSharedMemory = false;
+      s.asyncDepth = 0;
+      s.kSplits = 1;
+      out.push_back(s);
+    }
+  }
+  return out;
+}
+
+std::string shapeBucket(const ReductionProblem &prob,
+                        const GPUTargetInfo &target) {
+  StringRef mB = prob.M < target.numSMs ? "M_few" : "M_many";
+  StringRef kB = prob.K < 128      ? "K_tiny"
+                 : prob.K < 4096   ? "K_small"
+                 : prob.K < 1000000 ? "K_medium"
+                                    : "K_large";
+  return (mB + "_" + kB).str();
+}
+
+std::string tuneCacheKey(const ReductionProblem &prob,
+                         const GPUTargetInfo &target) {
+  const char *kind = prob.kind == ReductionKindName::Row      ? "row"
+                     : prob.kind == ReductionKindName::Column ? "column"
+                                                              : "full";
+  std::ostringstream os;
+  os << kind << '|' << prob.axis << '|' << prob.dtype << '|' << prob.tileRows
+     << 'x' << prob.tileCols << '|' << shapeBucket(prob, target) << '|'
+     << prob.arch << '|' << prob.compiler;
+  return os.str();
+}
+
+TuneResult autotune(const ReductionProblem &prob, const GPUTargetInfo &target) {
+  static std::map<std::string, TuneResult> cache;
+  TuneResult r;
+  r.cacheKey = tuneCacheKey(prob, target);
+  r.shapeBucket = shapeBucket(prob, target);
+  if (auto it = cache.find(r.cacheKey); it != cache.end())
+    return it->second;
+
+  auto space = enumerateSchedules(prob, target);
+  r.candidates = static_cast<int>(space.size());
+  CostEstimate best;
+  best.tTotal = 1e300;
+  best.legal = false;
+  ReductionSchedule bestS = ReductionSchedule::baselineRow();
+  for (const auto &s : space) {
+    CostEstimate c = estimateCost(prob, s, target);
+    if (!c.legal) {
+      ++r.pruned;
+      continue;
+    }
+    if (c.tTotal < best.tTotal) {
+      best = c;
+      bestS = s;
+    }
+  }
+  r.winner = bestS;
+  r.cost = best;
+
+  // Measure async on the row-sum baseline. Do not assume it helps: row-sum
+  // intensity is too low and extra smem/regs hurt occupancy.
+  if (prob.kind == ReductionKindName::Row) {
+    ReductionSchedule base = ReductionSchedule::baselineRow();
+    ReductionSchedule async = base;
+    async.useSharedMemory = true;
+    async.asyncDepth = 2;
+    CostEstimate b = estimateCost(prob, base, target);
+    CostEstimate a = estimateCost(prob, async, target);
+    r.baselineRowUs = b.tTotal;
+    r.asyncRowUs = a.legal ? a.tTotal : 1e300;
+    r.asyncHelpsRowSum =
+        a.legal && b.tTotal > 0 && a.tTotal < 0.9 * b.tTotal;
+  }
+
+  cache[r.cacheKey] = r;
+  return r;
+}
+
+static IntegerAttr i64(MLIRContext *ctx, int64_t v) {
+  return IntegerAttr::get(IntegerType::get(ctx, 64), v);
+}
+
+static FloatAttr f64(MLIRContext *ctx, double v) {
+  return FloatAttr::get(Float64Type::get(ctx), v);
+}
+
+void applyCostAttrs(Operation *op, const ReductionSchedule &sched,
+                    const CostEstimate &cost) {
+  MLIRContext *ctx = op->getContext();
+  op->setAttr("tr.schedule.threads_per_block", i64(ctx, sched.threadsPerBlock));
+  op->setAttr("tr.schedule.warps_per_block", i64(ctx, sched.warpsPerBlock));
+  op->setAttr("tr.schedule.rows_per_warp", i64(ctx, sched.rowsPerWarp));
+  op->setAttr("tr.schedule.elements_per_lane", i64(ctx, sched.elementsPerLane));
+  op->setAttr("tr.schedule.use_shared_memory",
+              BoolAttr::get(ctx, sched.useSharedMemory));
+  op->setAttr("tr.schedule.async_depth", i64(ctx, sched.asyncDepth));
+  op->setAttr("tr.schedule.k_splits", i64(ctx, sched.kSplits));
+  op->setAttr("tr.cost.t_compute", f64(ctx, cost.tCompute));
+  op->setAttr("tr.cost.t_memory", f64(ctx, cost.tMemory));
+  op->setAttr("tr.cost.t_sync", f64(ctx, cost.tSync));
+  op->setAttr("tr.cost.t_launch", f64(ctx, cost.tLaunch));
+  op->setAttr("tr.cost.t_tail", f64(ctx, cost.tTail));
+  op->setAttr("tr.cost.t_total", f64(ctx, cost.tTotal));
+  op->setAttr("tr.cost.occupancy", f64(ctx, cost.occupancy));
+  op->setAttr("tr.cost.coalescing", f64(ctx, cost.coalescing));
+  op->setAttr("tr.cost.grid_saturation", f64(ctx, cost.gridSaturation));
+  op->setAttr("tr.cost.limiter", StringAttr::get(ctx, cost.limiter));
+  op->setAttr("tr.cost.legal", BoolAttr::get(ctx, cost.legal));
+}
+
+void applyTuneAttrs(Operation *op, const TuneResult &result) {
+  applyCostAttrs(op, result.winner, result.cost);
+  MLIRContext *ctx = op->getContext();
+  op->setAttr("tr.tune.cache_key", StringAttr::get(ctx, result.cacheKey));
+  op->setAttr("tr.tune.shape_bucket", StringAttr::get(ctx, result.shapeBucket));
+  op->setAttr("tr.tune.candidates", i64(ctx, result.candidates));
+  op->setAttr("tr.tune.pruned", i64(ctx, result.pruned));
+  op->setAttr("tr.tune.k_splits", i64(ctx, result.winner.kSplits));
+  op->setAttr("tr.tune.async_depth", i64(ctx, result.winner.asyncDepth));
+  op->setAttr("tr.tune.async_helps_row_sum",
+              BoolAttr::get(ctx, result.asyncHelpsRowSum));
+  op->setAttr("tr.cost.async_row_sum_us", f64(ctx, result.asyncRowUs));
+  op->setAttr("tr.cost.baseline_row_sum_us", f64(ctx, result.baselineRowUs));
+}
+
+void applyBenchAttrs(Operation *op, const ReductionSchedule &sched,
+                     const CostEstimate &cost, const ReductionProblem &prob) {
+  applyCostAttrs(op, sched, cost);
+  MLIRContext *ctx = op->getContext();
+  double bytes = static_cast<double>(prob.M) * static_cast<double>(prob.K) *
+                 elemBytes(prob);
+  double gbs = cost.tTotal > 0 ? (bytes / 1e9) / (cost.tTotal / 1e6) : 0.0;
+  op->setAttr("tr.bench.latency_us", f64(ctx, cost.tTotal));
+  op->setAttr("tr.bench.effective_gbs", f64(ctx, gbs));
+  op->setAttr("tr.bench.threads_per_block", i64(ctx, sched.threadsPerBlock));
+  op->setAttr("tr.bench.registers_per_thread",
+              i64(ctx, cost.registersPerThread));
+  op->setAttr("tr.bench.shared_memory_bytes", i64(ctx, cost.sharedMemoryBytes));
+  op->setAttr("tr.bench.occupancy", f64(ctx, cost.occupancy));
+  op->setAttr("tr.bench.kernel_count", i64(ctx, cost.kernelCount));
+}
+
+} // namespace mlir::tr
diff --git a/tile-reducer/lib/TileReducer/TileReducerCostPasses.cpp b/tile-reducer/lib/TileReducer/TileReducerCostPasses.cpp
new file mode 100644
index 0000000000000..2f7b17216645d
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerCostPasses.cpp
@@ -0,0 +1,137 @@
+//===- TileReducerCostPasses.cpp - Milestones 23, 25, 27 --------*- C++ -*-===//
+//
+// --tr-estimate-reduction-cost  annotate the baseline schedule
+// --tr-autotune-reduction       prune, rank, cache by shape bucket
+// --tr-bench-report             latency / GB/s / occupancy / kernel count
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/GPUTargetInfo.h"
+#include "TileReducer/ReductionSchedule.h"
+#include "TileReducer/TileReducerDialect.h"
+#include "TileReducer/TileReducerOps.h"
+#include "TileReducer/TileReducerPasses.h"
+#include "TileReducer/TileReducerTypes.h"
+
+#include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/IR/BuiltinOps.h"
+#include <string>
+
+using namespace mlir;
+using namespace mlir::tr;
+
+namespace mlir::tr {
+#define GEN_PASS_DEF_ESTIMATETRREDUCTIONCOST
+#define GEN_PASS_DEF_AUTOTUNETRREDUCTION
+#define GEN_PASS_DEF_TRBENCHREPORT
+#include "TileReducer/TileReducerPasses.h.inc"
+
+namespace {
+
+static ReductionKindName kindFromFunc(func::FuncOp func) {
+  ReductionKindName kind = ReductionKindName::Row;
+  func.walk([&](ReduceSumOp reduce) {
+    auto outTy = dyn_cast<TileType>(reduce.getType());
+    if (outTy && outTy.getRank() == 0)
+      kind = ReductionKindName::Full;
+    else if (reduce.getAxis() == 0)
+      kind = ReductionKindName::Column;
+    else if (reduce.getAxis() == 1 && kind != ReductionKindName::Full)
+      kind = ReductionKindName::Row;
+  });
+  return kind;
+}
+
+static ReductionProblem problemFrom(func::FuncOp func, int64_t M, int64_t K) {
+  ReductionProblem p;
+  p.kind = kindFromFunc(func);
+  p.axis = p.kind == ReductionKindName::Column ? 0 : 1;
+  p.M = M > 0 ? M : 1024;
+  p.K = K > 0 ? K : 1024;
+  func.walk([&](LoadOp load) {
+    if (auto tile = dyn_cast<TileType>(load.getType())) {
+      if (tile.getRank() == 2) {
+        p.tileRows = tile.getDimSize(0);
+        p.tileCols = tile.getDimSize(1);
+        if (auto fty = dyn_cast<FloatType>(tile.getElementType())) {
+          p.elemBits = fty.getWidth();
+          p.dtype = "f" + std::to_string(p.elemBits);
+        }
+      }
+    }
+  });
+  return p;
+}
+
+static ReductionSchedule baselineFor(ReductionKindName kind) {
+  switch (kind) {
+  case ReductionKindName::Column:
+    return ReductionSchedule::baselineColumn();
+  case ReductionKindName::Full:
+    return ReductionSchedule::baselineFull();
+  case ReductionKindName::Row:
+    return ReductionSchedule::baselineRow();
+  }
+  return ReductionSchedule::baselineRow();
+}
+
+struct EstimateTRReductionCost
+    : impl::EstimateTRReductionCostBase<EstimateTRReductionCost> {
+  using impl::EstimateTRReductionCostBase<
+      EstimateTRReductionCost>::EstimateTRReductionCostBase;
+  void runOnOperation() override {
+    ModuleOp module = getOperation();
+    GPUTargetInfo target = GPUTargetInfo::fromOp(module);
+    module.walk([&](func::FuncOp func) {
+      if (!func.getName().contains("sum"))
+        return;
+      ReductionProblem prob = problemFrom(func, problemM, problemK);
+      ReductionSchedule sched = baselineFor(prob.kind);
+      CostEstimate cost = estimateCost(prob, sched, target);
+      applyCostAttrs(func, sched, cost);
+    });
+  }
+};
+
+struct AutotuneTRReduction
+    : impl::AutotuneTRReductionBase<AutotuneTRReduction> {
+  using impl::AutotuneTRReductionBase<AutotuneTRReduction>::AutotuneTRReductionBase;
+  void runOnOperation() override {
+    ModuleOp module = getOperation();
+    GPUTargetInfo target = GPUTargetInfo::fromOp(module);
+    TuneResult last;
+    bool any = false;
+    module.walk([&](func::FuncOp func) {
+      if (!func.getName().contains("sum"))
+        return;
+      ReductionProblem prob = problemFrom(func, problemM, problemK);
+      TuneResult r = autotune(prob, target);
+      applyTuneAttrs(func, r);
+      last = r;
+      any = true;
+    });
+    if (any)
+      applyTuneAttrs(module, last);
+  }
+};
+
+struct TRBenchReport : impl::TRBenchReportBase<TRBenchReport> {
+  using impl::TRBenchReportBase<TRBenchReport>::TRBenchReportBase;
+  void runOnOperation() override {
+    ModuleOp module = getOperation();
+    GPUTargetInfo target = GPUTargetInfo::fromOp(module);
+    module.walk([&](func::FuncOp func) {
+      if (!func.getName().contains("sum"))
+        return;
+      ReductionProblem prob = problemFrom(func, problemM, problemK);
+      ReductionSchedule sched = baselineFor(prob.kind);
+      if (auto splits = module->getAttrOfType<IntegerAttr>("tr.tune.k_splits"))
+        sched.kSplits = static_cast<int>(splits.getInt());
+      CostEstimate cost = estimateCost(prob, sched, target);
+      applyBenchAttrs(func, sched, cost, prob);
+    });
+  }
+};
+
+} // namespace
+} // namespace mlir::tr
diff --git a/tile-reducer/test/cost-model.mlir b/tile-reducer/test/cost-model.mlir
new file mode 100644
index 0000000000000..83ff8a3e03c98
--- /dev/null
+++ b/tile-reducer/test/cost-model.mlir
@@ -0,0 +1,36 @@
+// RUN: tr-opt %s --tr-estimate-reduction-cost='rows=1024 cols=1024' | FileCheck %s
+
+// Milestone 23: baseline row-sum schedule and roofline cost.
+// T ~= max(T_compute, T_memory) + T_sync + T_launch + T_tail.
+// Not cycle-exact. Row-sum baseline uses no shared memory.
+
+// CHECK-LABEL: func.func @row_sum
+// CHECK-DAG: tr.schedule.threads_per_block = 256
+// CHECK-DAG: tr.schedule.warps_per_block = 8
+// CHECK-DAG: tr.schedule.rows_per_warp = 16
+// CHECK-DAG: tr.schedule.elements_per_lane = 4
+// CHECK-DAG: tr.schedule.use_shared_memory = false
+// CHECK-DAG: tr.schedule.async_depth = 0
+// CHECK-DAG: tr.schedule.k_splits = 1
+// CHECK-DAG: tr.cost.legal = true
+// CHECK-DAG: tr.cost.t_total
+// CHECK-DAG: tr.cost.occupancy
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}

>From 189895aee9275bb274760805cd5ccf6109292f57 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:23:02 -0700
Subject: [PATCH 24/29] [TileReducer] Milestone 24: large-K split of one
 logical program

--tr-emit-gpu-kernels=k-splits=N maps tr.program_id to gpu.block_id x and
refines K across gpu.block_id y. Stage 2 reduces the partials. One logical
row is not necessarily one GPU block (M=1, K=1e8).

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/split-large-k.mlir
  tr-opt --tr-emit-gpu-kernels=k-splits=4 tile-reducer/test/split-large-k.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 .../lib/TileReducer/TileReducerGPUKernels.cpp | 169 +++++++++++++++++-
 tile-reducer/test/split-large-k.mlir          |  35 ++++
 2 files changed, 196 insertions(+), 8 deletions(-)
 create mode 100644 tile-reducer/test/split-large-k.mlir

diff --git a/tile-reducer/lib/TileReducer/TileReducerGPUKernels.cpp b/tile-reducer/lib/TileReducer/TileReducerGPUKernels.cpp
index e693901570589..2e0f1651a9d80 100644
--- a/tile-reducer/lib/TileReducer/TileReducerGPUKernels.cpp
+++ b/tile-reducer/lib/TileReducer/TileReducerGPUKernels.cpp
@@ -38,6 +38,8 @@ namespace {
 
 constexpr StringRef kKernelModuleName = "tr_kernels";
 constexpr StringRef kRowSumKernel = "row_sum_kernel";
+constexpr StringRef kRowSumSplitK1 = "row_sum_splitk_stage1";
+constexpr StringRef kRowSumSplitK2 = "row_sum_splitk_stage2";
 constexpr StringRef kFullSumStage1 = "full_sum_stage1";
 constexpr StringRef kFullSumStage2 = "full_sum_stage2";
 constexpr StringRef kColumnSumKernel = "column_sum_kernel";
@@ -169,10 +171,14 @@ static ReductionMatch matchReduction(func::FuncOp func) {
   return found;
 }
 
-/// Emit the fused row-sum body. `pid` is the physical block id.
+/// Emit the fused row-sum body. `pid` is the logical program / block_id x.
+/// Optional `ktLb`/`ktUb` restrict the K-tile loop (large-K split).
+/// Optional `kPart` stores a rank-2 partial `out[row, kPart]`.
 static void emitRowSumBody(OpBuilder &b, Location loc, Value in, Value out,
                            Value pid, const GPUTargetInfo &target,
-                           int64_t tileRows, int64_t tileCols, Type elemTy) {
+                           int64_t tileRows, int64_t tileCols, Type elemTy,
+                           Value ktLb = Value(), Value ktUb = Value(),
+                           Value kPart = Value()) {
   const int warpSize = target.warpSize;
   const int warps = target.warpsPerBlock();
   const int rowsPerWarp = target.rowsPerWarp(static_cast<int>(tileRows));
@@ -198,6 +204,10 @@ static void emitRowSumBody(OpBuilder &b, Location loc, Value in, Value out,
   Value m = memref::DimOp::create(b, loc, in, c0);
   Value k = memref::DimOp::create(b, loc, in, c1);
   Value numTiles = arith::CeilDivUIOp::create(b, loc, k, cTileCols);
+  if (!ktLb)
+    ktLb = c0;
+  if (!ktUb)
+    ktUb = numTiles;
   Value rowBase = arith::MulIOp::create(b, loc, pid, cTileRows);
 
   scf::ForOp::create(
@@ -210,7 +220,7 @@ static void emitRowSumBody(OpBuilder &b, Location loc, Value in, Value out,
                                             globalRow, m);
         scf::IfOp::create(rb, rloc, rowOK, [&](OpBuilder &ib, Location iloc) {
           auto kLoop = scf::ForOp::create(
-              ib, iloc, c0, numTiles, c1, ValueRange{zero},
+              ib, iloc, ktLb, ktUb, c1, ValueRange{zero},
               [&](OpBuilder &kb, Location kloc, Value kt, ValueRange kargs) {
                 Value acc = kargs[0];
                 Value kBase = arith::MulIOp::create(kb, kloc, kt, cTileCols);
@@ -249,8 +259,12 @@ static void emitRowSumBody(OpBuilder &b, Location loc, Value in, Value out,
           Value isLane0 = arith::CmpIOp::create(
               ib, iloc, arith::CmpIPredicate::eq, lane, c0);
           scf::IfOp::create(ib, iloc, isLane0, [&](OpBuilder &sb, Location sloc) {
-            memref::StoreOp::create(sb, sloc, reduced, out,
-                                    ValueRange{globalRow});
+            if (kPart)
+              memref::StoreOp::create(sb, sloc, reduced, out,
+                                      ValueRange{globalRow, kPart});
+            else
+              memref::StoreOp::create(sb, sloc, reduced, out,
+                                      ValueRange{globalRow});
             scf::YieldOp::create(sb, sloc);
           });
           scf::YieldOp::create(ib, iloc);
@@ -542,11 +556,13 @@ static gpu::GPUFuncOp createKernel(OpBuilder &b, Location loc, StringRef name,
 
 static void emitHostLaunch(OpBuilder &b, Location loc, gpu::GPUFuncOp kernel,
                            ValueRange args, Value gridX,
-                           const GPUTargetInfo &target) {
+                           const GPUTargetInfo &target, Value gridY = Value()) {
   Value c1 = arith::ConstantIndexOp::create(b, loc, 1);
   Value cBlock =
       arith::ConstantIndexOp::create(b, loc, target.threadsPerBlock());
-  gpu::KernelDim3 grid{gridX, c1, c1};
+  if (!gridY)
+    gridY = c1;
+  gpu::KernelDim3 grid{gridX, gridY, c1};
   gpu::KernelDim3 block{cBlock, c1, c1};
   gpu::LaunchFuncOp::create(b, loc, kernel, grid, block, /*dynSmem=*/Value(),
                             args);
@@ -602,6 +618,133 @@ static LogicalResult emitRowSumKernel(func::FuncOp func, ReductionMatch match,
   return success();
 }
 
+/// One logical program (block_id x) is refined into many physical blocks
+/// (block_id y) that each own a K-slice and write a partial. Stage 2 reduces
+/// those partials. This is the M=1, K=1e8 case: one row is not one block.
+static LogicalResult emitRowSumSplitK(func::FuncOp func, ReductionMatch match,
+                                      gpu::GPUModuleOp gpuMod,
+                                      SymbolTable &gpuSymbols,
+                                      const GPUTargetInfo &target,
+                                      int kSplits) {
+  convertBufferSignature(func);
+  Value in = match.load.getBuffer();
+  Value out = match.store.getBuffer();
+  if (!isa<MemRefType>(in.getType()) || !isa<MemRefType>(out.getType()))
+    return func.emitError("row-sum split-K expects memref buffers");
+
+  Location loc = func.getLoc();
+  Type elemTy = match.tileTy.getElementType();
+  int64_t tileRows = match.tileTy.getDimSize(0);
+  int64_t tileCols = match.tileTy.getDimSize(1);
+  auto partialsTy =
+      MemRefType::get({ShapedType::kDynamic, ShapedType::kDynamic}, elemTy);
+
+  OpBuilder kb(gpuMod.getBody(), gpuMod.getBody()->end());
+  auto stage1 = createKernel(kb, loc, kRowSumSplitK1,
+                             TypeRange{in.getType(), partialsTy}, {}, target);
+  insertUniqueKernel(gpuSymbols, stage1);
+  auto stage2 = createKernel(kb, loc, kRowSumSplitK2,
+                             TypeRange{partialsTy, out.getType()}, {}, target);
+  insertUniqueKernel(gpuSymbols, stage2);
+  if (!gpuSymbols.lookup<gpu::GPUFuncOp>(stage1.getName()) ||
+      !gpuSymbols.lookup<gpu::GPUFuncOp>(stage2.getName()))
+    return func.emitError("split-K symbol lookup failed");
+
+  {
+    Block &e = stage1.getBody().front();
+    OpBuilder body(&e, e.begin());
+    Value pid = gpu::BlockIdOp::create(body, loc, gpu::Dimension::x);
+    Value kPart = gpu::BlockIdOp::create(body, loc, gpu::Dimension::y);
+    Value nSplits = gpu::GridDimOp::create(body, loc, gpu::Dimension::y);
+    Value c1 = arith::ConstantIndexOp::create(body, loc, 1);
+    Value cTile = arith::ConstantIndexOp::create(body, loc, tileCols);
+    Value k = memref::DimOp::create(body, loc, e.getArgument(0), c1);
+    Value nTiles = arith::CeilDivUIOp::create(body, loc, k, cTile);
+    Value chunk = arith::CeilDivUIOp::create(body, loc, nTiles, nSplits);
+    Value ktLb = arith::MulIOp::create(body, loc, kPart, chunk);
+    Value ktUb = arith::AddIOp::create(body, loc, ktLb, chunk);
+    Value over =
+        arith::CmpIOp::create(body, loc, arith::CmpIPredicate::ugt, ktUb, nTiles);
+    auto clamped = scf::IfOp::create(body, loc, TypeRange{body.getIndexType()},
+                                     over, /*withElseRegion=*/true);
+    {
+      OpBuilder::InsertionGuard g(body);
+      body.setInsertionPointToStart(clamped.thenBlock());
+      scf::YieldOp::create(body, loc, nTiles);
+      body.setInsertionPointToStart(clamped.elseBlock());
+      scf::YieldOp::create(body, loc, ktUb);
+    }
+    emitRowSumBody(body, loc, e.getArgument(0), e.getArgument(1), pid, target,
+                   tileRows, tileCols, elemTy, ktLb, clamped.getResult(0),
+                   kPart);
+    gpu::ReturnOp::create(body, loc);
+  }
+  {
+    Block &e = stage2.getBody().front();
+    OpBuilder body(&e, e.begin());
+    Value pid = gpu::BlockIdOp::create(body, loc, gpu::Dimension::x);
+    Value lane = gpu::LaneIdOp::create(body, loc, IntegerAttr());
+    Value warp =
+        gpu::SubgroupIdOp::create(body, loc, body.getIndexType(), IntegerAttr());
+    Value c0 = arith::ConstantIndexOp::create(body, loc, 0);
+    Value c1 = arith::ConstantIndexOp::create(body, loc, 1);
+    Value c8 = arith::ConstantIndexOp::create(body, loc, target.warpsPerBlock());
+    Value c16 = arith::ConstantIndexOp::create(
+        body, loc, target.rowsPerWarp(static_cast<int>(tileRows)));
+    Value c128 = arith::ConstantIndexOp::create(body, loc, tileRows);
+    Value zero = scalarZero(body, loc, elemTy);
+    Value nSplits = memref::DimOp::create(body, loc, e.getArgument(0), c1);
+    Value m = memref::DimOp::create(body, loc, e.getArgument(1), c0);
+    Value rowBase = arith::MulIOp::create(body, loc, pid, c128);
+    scf::ForOp::create(
+        body, loc, c0, c16, c1, ValueRange{},
+        [&](OpBuilder &rb, Location rloc, Value s, ValueRange) {
+          Value local =
+              arith::AddIOp::create(rb, rloc, warp,
+                                    arith::MulIOp::create(rb, rloc, s, c8));
+          Value row = arith::AddIOp::create(rb, rloc, rowBase, local);
+          Value rowOK = arith::CmpIOp::create(rb, rloc, arith::CmpIPredicate::ult,
+                                              row, m);
+          scf::IfOp::create(rb, rloc, rowOK, [&](OpBuilder &ib, Location iloc) {
+            auto red = scf::ForOp::create(
+                ib, iloc, c0, nSplits, c1, ValueRange{zero},
+                [&](OpBuilder &kb, Location kloc, Value p, ValueRange args) {
+                  Value v = memref::LoadOp::create(
+                      kb, kloc, e.getArgument(0), ValueRange{row, p});
+                  scf::YieldOp::create(kb, kloc,
+                                       scalarAdd(kb, kloc, args[0], v));
+                });
+            Value isLane0 = arith::CmpIOp::create(
+                ib, iloc, arith::CmpIPredicate::eq, lane, c0);
+            scf::IfOp::create(ib, iloc, isLane0, [&](OpBuilder &sb, Location sloc) {
+              memref::StoreOp::create(sb, sloc, red.getResult(0),
+                                      e.getArgument(1), ValueRange{row});
+              scf::YieldOp::create(sb, sloc);
+            });
+            scf::YieldOp::create(ib, iloc);
+          });
+          scf::YieldOp::create(rb, rloc);
+        });
+    gpu::ReturnOp::create(body, loc);
+  }
+
+  clearBody(func);
+  OpBuilder hb(&func.getBody().front(), func.getBody().front().end());
+  Value c0 = arith::ConstantIndexOp::create(hb, loc, 0);
+  Value cTile = arith::ConstantIndexOp::create(hb, loc, tileRows);
+  Value cSplits = arith::ConstantIndexOp::create(hb, loc, kSplits);
+  Value m = memref::DimOp::create(hb, loc, in, c0);
+  Value nRowTiles = arith::CeilDivUIOp::create(hb, loc, m, cTile);
+  Value partials =
+      memref::AllocOp::create(hb, loc, partialsTy, ValueRange{m, cSplits});
+  emitHostLaunch(hb, loc, stage1, ValueRange{in, partials}, nRowTiles, target,
+                 cSplits);
+  emitHostLaunch(hb, loc, stage2, ValueRange{partials, out}, nRowTiles, target);
+  memref::DeallocOp::create(hb, loc, partials);
+  func::ReturnOp::create(hb, loc);
+  return success();
+}
+
 static LogicalResult emitFullSumKernels(func::FuncOp func, ReductionMatch match,
                                         gpu::GPUModuleOp gpuMod,
                                         SymbolTable &gpuSymbols,
@@ -711,6 +854,7 @@ static LogicalResult emitColumnSumKernel(func::FuncOp func, ReductionMatch match
 }
 
 struct EmitTRGPUKernels : impl::EmitTRGPUKernelsBase<EmitTRGPUKernels> {
+  using impl::EmitTRGPUKernelsBase<EmitTRGPUKernels>::EmitTRGPUKernelsBase;
   void runOnOperation() override {
     ModuleOp module = getOperation();
     SmallVector<std::pair<func::FuncOp, ReductionMatch>> work;
@@ -728,11 +872,20 @@ struct EmitTRGPUKernels : impl::EmitTRGPUKernelsBase<EmitTRGPUKernels> {
     SymbolTable gpuSymbols(gpuMod);
     GPUTargetInfo target = GPUTargetInfo::fromOp(module);
 
+    int splits = kSplits;
+    if (splits <= 1) {
+      if (auto attr = module->getAttrOfType<IntegerAttr>("tr.tune.k_splits"))
+        splits = static_cast<int>(attr.getInt());
+    }
+
     for (auto [func, match] : work) {
       LogicalResult ok = success();
       switch (match.kind) {
       case KernelKind::Row:
-        ok = emitRowSumKernel(func, match, gpuMod, gpuSymbols, target);
+        ok = splits > 1 ? emitRowSumSplitK(func, match, gpuMod, gpuSymbols,
+                                           target, splits)
+                        : emitRowSumKernel(func, match, gpuMod, gpuSymbols,
+                                           target);
         break;
       case KernelKind::Full:
         ok = emitFullSumKernels(func, match, gpuMod, gpuSymbols, target);
diff --git a/tile-reducer/test/split-large-k.mlir b/tile-reducer/test/split-large-k.mlir
new file mode 100644
index 0000000000000..50bf3c7423a27
--- /dev/null
+++ b/tile-reducer/test/split-large-k.mlir
@@ -0,0 +1,35 @@
+// RUN: tr-opt %s --tr-emit-gpu-kernels=k-splits=8 | FileCheck %s
+
+// Milestone 24: M=1, K=1e8 has too little parallelism as one block.
+// One logical program (gpu.block_id x) is refined into many physical
+// blocks (gpu.block_id y) that write partials, then a second stage
+// reduces them. logical program_id != necessarily one GPU block.
+
+// CHECK: gpu.func @row_sum_splitk_stage1
+// CHECK: gpu.block_id x
+// CHECK: gpu.block_id y
+// CHECK: gpu.grid_dim y
+// CHECK: gpu.func @row_sum_splitk_stage2
+// CHECK: func.func @row_sum
+// CHECK: gpu.launch_func @tr_kernels::@row_sum_splitk_stage1
+// CHECK-SAME: blocks in
+// CHECK: gpu.launch_func @tr_kernels::@row_sum_splitk_stage2
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}

>From ff2eb7d8b5bc73958492a8e30d81093661d5be84 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:23:02 -0700
Subject: [PATCH 25/29] [TileReducer] Milestone 25: autotune by shape bucket

--tr-autotune-reduction enumerates a bounded legal space, prunes
analytically, and caches the winner by kind|axis|dtype|tile|bucket|arch|
compiler. It does not tune every exact M x K.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/autotune.mlir
  tr-opt --tr-autotune-reduction='rows=1 cols=100000000' tile-reducer/test/autotune.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/test/autotune.mlir | 35 +++++++++++++++++++++++++++++++++
 1 file changed, 35 insertions(+)
 create mode 100644 tile-reducer/test/autotune.mlir

diff --git a/tile-reducer/test/autotune.mlir b/tile-reducer/test/autotune.mlir
new file mode 100644
index 0000000000000..7d94c7c624a10
--- /dev/null
+++ b/tile-reducer/test/autotune.mlir
@@ -0,0 +1,35 @@
+// RUN: tr-opt %s --tr-autotune-reduction='rows=1 cols=100000000' | FileCheck %s --check-prefix=LARGEK
+// RUN: tr-opt %s --tr-autotune-reduction='rows=16384 cols=4096' | FileCheck %s --check-prefix=BASE
+
+// Milestone 25: bounded legal schedules, analytical prune, cache by
+//   kind | axis | dtype | tile | shape bucket | arch | compiler
+// Do not tune every exact shape.
+
+// LARGEK-DAG: tr.tune.shape_bucket = "M_few_K_large"
+// LARGEK-DAG: tr.tune.cache_key = "row|1|f32|128x128|M_few_K_large|a100-like|tile-reducer-23"
+// LARGEK-DAG: tr.tune.k_splits = 64
+// LARGEK-DAG: tr.tune.async_depth = 0
+// LARGEK-DAG: tr.tune.async_helps_row_sum = false
+
+// BASE-DAG: tr.tune.shape_bucket = "M_many_K_medium"
+// BASE-DAG: tr.tune.k_splits = 1
+// BASE-DAG: tr.tune.async_depth = 0
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}

>From 0806c1cf7d941ebad647f8e004f5258052a44de7 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:23:03 -0700
Subject: [PATCH 26/29] [TileReducer] Milestone 26: measure async pipelining
 after the baseline

Row-sum intensity is too low for double buffering. Extra smem and
registers do not pay off; the winner keeps asyncDepth = 0.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/async-pipeline.mlir
  tr-opt --tr-autotune-reduction='rows=1 cols=100000000' tile-reducer/test/async-pipeline.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/test/async-pipeline.mlir | 31 +++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)
 create mode 100644 tile-reducer/test/async-pipeline.mlir

diff --git a/tile-reducer/test/async-pipeline.mlir b/tile-reducer/test/async-pipeline.mlir
new file mode 100644
index 0000000000000..f1bc61ba86fe7
--- /dev/null
+++ b/tile-reducer/test/async-pipeline.mlir
@@ -0,0 +1,31 @@
+// RUN: tr-opt %s --tr-autotune-reduction='rows=1024 cols=1024' | FileCheck %s
+
+// Milestone 26: async / software pipelining is evaluated only after the
+// baseline is measured. Row-sum intensity is ~1/4 flop/byte; extra smem
+// and registers for double buffering do not pay off. The tuner keeps
+// asyncDepth = 0.
+
+// CHECK-DAG: tr.tune.async_helps_row_sum = false
+// CHECK-DAG: tr.tune.async_depth = 0
+// CHECK-DAG: tr.cost.baseline_row_sum_us
+// CHECK-DAG: tr.cost.async_row_sum_us
+// CHECK-DAG: tr.schedule.use_shared_memory = false
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}

>From 9e041f0031a0e366b10161e440f8b4f04750fe51 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:23:03 -0700
Subject: [PATCH 27/29] [TileReducer] Milestone 27: boundary tests and bench
 report

Document M/K boundary matrices for row, column, and full reductions and
the property full_sum ~= sum(row_sum) ~= sum(column_sum).
--tr-bench-report records latency, GB/s, threads, registers, smem,
occupancy, and kernel count.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/reduction-boundaries.mlir
    tile-reducer/test/bench-report.mlir
  tr-opt --tr-bench-report='rows=1024 cols=1024' tile-reducer/test/bench-report.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/test/bench-report.mlir         | 32 ++++++++
 tile-reducer/test/reduction-boundaries.mlir | 84 +++++++++++++++++++++
 2 files changed, 116 insertions(+)
 create mode 100644 tile-reducer/test/bench-report.mlir
 create mode 100644 tile-reducer/test/reduction-boundaries.mlir

diff --git a/tile-reducer/test/bench-report.mlir b/tile-reducer/test/bench-report.mlir
new file mode 100644
index 0000000000000..256c77266b64a
--- /dev/null
+++ b/tile-reducer/test/bench-report.mlir
@@ -0,0 +1,32 @@
+// RUN: tr-opt %s --tr-bench-report='rows=4096 cols=4096' | FileCheck %s
+
+// Milestone 27: benchmark record for a broader shape. Fields are
+// analytical estimates until a device run is wired (Milestone 28+).
+
+// CHECK-LABEL: func.func @row_sum
+// CHECK-DAG: tr.bench.latency_us
+// CHECK-DAG: tr.bench.effective_gbs
+// CHECK-DAG: tr.bench.threads_per_block = 256
+// CHECK-DAG: tr.bench.registers_per_thread
+// CHECK-DAG: tr.bench.shared_memory_bytes = 0
+// CHECK-DAG: tr.bench.occupancy
+// CHECK-DAG: tr.bench.kernel_count = 1
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}
diff --git a/tile-reducer/test/reduction-boundaries.mlir b/tile-reducer/test/reduction-boundaries.mlir
new file mode 100644
index 0000000000000..4f0cdf82a4c23
--- /dev/null
+++ b/tile-reducer/test/reduction-boundaries.mlir
@@ -0,0 +1,84 @@
+// RUN: tr-opt %s --tr-emit-gpu-kernels | FileCheck %s
+
+// Milestone 27: correctness around boundaries. The kernels are M/K-dynamic
+// (memref.dim + ceildivui + OOB zeros), so one IR covers
+//
+//   M in {1, 31, 32, 127, 128, 129}
+//   K in {0, 1, 31, 32, 33, 127, 128, 129, 255, 256, 257}
+//
+// for row, column, and full reductions.
+//
+// Data patterns a host harness should feed:
+//   zeros, ones, sequential, random, large/small magnitude
+//   NaN/Inf: TileReducer does not define a special policy; IEEE add applies.
+//
+// Property checks (reassociative, matching the Linalg generic):
+//   full_sum(A) ~= sum(row_sum(A))
+//   full_sum(A) ~= sum(column_sum(A))
+
+// CHECK: gpu.func @row_sum_kernel
+// CHECK: arith.ceildivui
+// CHECK: gpu.func @column_sum_kernel
+// CHECK: gpu.barrier
+// CHECK: gpu.func @full_sum_stage1
+// CHECK: gpu.func @full_sum_stage2
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}
+
+func.func @column_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Kxf32>) {
+  %col_blk = tr.program_id 0 : index
+  %c128    = arith.constant 128 : index
+  %m       = tr.dim %in, 0 : !tr.buffer<MxKxf32>, index
+  %num     = arith.divui %m, %c128 : index
+  %zero    = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %mt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%mt, %col_blk]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 0
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%col_blk], %result : !tr.buffer<Kxf32>, !tr.tile<128xf32>
+  return
+}
+
+func.func @full_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<1xf32>) {
+  %blk  = tr.program_id 0 : index
+  %c128 = arith.constant 128 : index
+  %c0   = arith.constant 0 : index
+  %k    = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num  = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<f32>
+  %result = tr.for %kt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<f32> {
+    %t    = tr.load %in[%blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %row  = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %s    = tr.reduce_sum %row, axis = 0
+        : !tr.tile<128xf32> -> !tr.tile<f32>
+    %acc2 = tr.add %acc, %s : !tr.tile<f32>
+    tr.yield %acc2 : !tr.tile<f32>
+  }
+  tr.store %out[%c0], %result : !tr.buffer<1xf32>, !tr.tile<f32>
+  return
+}

>From c17d437b02459a700e5875aebbf74b0d76dc6ba5 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:29:29 -0700
Subject: [PATCH 28/29] [TileReducer] Milestone 28: explicit GPU host/device
 split

Host func.func keeps gpu.launch_func; device gpu.func lives in
gpu.module @tr_kernels with #nvvm.target (A100 sm_80). Roles and
SymbolTable resolution are recorded; no computation is rewritten.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/host-device-split.mlir
    tile-reducer/test/host-device-split-invalid.mlir
  tr-opt --tr-emit-gpu-kernels --tr-split-host-device tile-reducer/test/host-device-split.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |   8 ++
 .../include/TileReducer/TileReducerPasses.td  |  20 +++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |   3 +
 .../lib/TileReducer/TileReducerHostDevice.cpp | 102 ++++++++++++++
 .../test/host-device-split-invalid.mlir       |  23 ++++
 tile-reducer/test/host-device-split.mlir      | 130 ++++++++++++++++++
 tile-reducer/test/smoke.mlir                  |   2 +-
 tile-reducer/tr-opt/CMakeLists.txt            |   2 +
 tile-reducer/tr-opt/tr-opt.cpp                |   5 +-
 9 files changed, 293 insertions(+), 2 deletions(-)
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerHostDevice.cpp
 create mode 100644 tile-reducer/test/host-device-split-invalid.mlir
 create mode 100644 tile-reducer/test/host-device-split.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index c9a7c16ca6b97..6f53ab6819830 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -153,3 +153,11 @@ Boundary matrix `M ∈ {1,31,32,127,128,129}`,
 Property: `full_sum(A) ~= sum(row_sum(A)) ~= sum(column_sum(A))`.
 `--tr-bench-report` records latency, GB/s, threads/block, registers,
 smem, occupancy, and kernel count.
+
+## Milestone 28
+
+`--tr-split-host-device` records the host/device cut after kernels are
+outlined. Host `func.func` keeps `gpu.launch_func` (`tr.role = "host"`).
+Device `gpu.func` symbols live in `gpu.module @tr_kernels` with
+`#nvvm.target<chip = "sm_80">` (`tr.role = "device"`). A missing kernel
+symbol is a hard lookup failure. No computation is rewritten.
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
index 5bb6bac850527..5bab843047a97 100644
--- a/tile-reducer/include/TileReducer/TileReducerPasses.td
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -207,6 +207,26 @@ def TRBenchReport : Pass<"tr-bench-report", "::mlir::ModuleOp"> {
   ];
 }
 
+def SplitTRHostDevice : Pass<"tr-split-host-device", "::mlir::ModuleOp"> {
+  let summary = "Make the GPU host/device split explicit. No computation rewrite.";
+  let description = [{
+    A GPU program is not one linear function. After `tr-emit-gpu-kernels`:
+
+      host:  func.func + gpu.launch_func   (runtime / launch)
+      device: gpu.module @tr_kernels / gpu.func  (payload)
+
+    This pass records that split: attaches `#nvvm.target` (A100 sm_80) to
+    each device module, sets `tr.role = "host"` / `"device"`, and verifies
+    every `gpu.launch_func` resolves through the SymbolTable. It does not
+    lower ops; later passes own GPU->NVVM and host runtime lowering.
+  }];
+  let dependentDialects = [
+    "::mlir::gpu::GPUDialect",
+    "::mlir::NVVM::NVVMDialect",
+    "::mlir::func::FuncDialect"
+  ];
+}
+
 def ConvertTRToLinalg : Pass<"convert-tr-to-linalg", "::mlir::func::FuncOp"> {
   let summary = "Lower tile compute to Linalg over MemRefs. Load becomes a subview.";
   let description = [{
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index f728eb21cd518..31f9d5f956e55 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -11,6 +11,7 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerGPUTarget.cpp
         TileReducerGPURowSum.cpp
         TileReducerGPUKernels.cpp
+        TileReducerHostDevice.cpp
         ReductionCostModel.cpp
         TileReducerCostPasses.cpp
         TileReducerPasses.cpp
@@ -31,6 +32,8 @@ add_mlir_dialect_library(MLIRTileReducer
         MLIRControlFlowInterfaces
         MLIRFuncDialect
         MLIRGPUDialect
+        MLIRNVVMDialect
+        MLIRLLVMDialect
         MLIRAffineDialect
         MLIRAffineToStandard
         MLIRAffineUtils
diff --git a/tile-reducer/lib/TileReducer/TileReducerHostDevice.cpp b/tile-reducer/lib/TileReducer/TileReducerHostDevice.cpp
new file mode 100644
index 0000000000000..dcfebec2fde03
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerHostDevice.cpp
@@ -0,0 +1,102 @@
+//===- TileReducerHostDevice.cpp - Milestone 28 -----------------*- C++ -*-===//
+//
+// Make the host/device split explicit. Host stays in func.func with
+// gpu.launch_func. Device lives in gpu.module / gpu.func and is annotated
+// with #nvvm.target so later GPU->NVVM lowering has a concrete backend.
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/TileReducerPasses.h"
+
+#include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/LLVMIR/NVVMDialect.h"
+#include "mlir/IR/Builders.h"
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/IR/SymbolTable.h"
+
+using namespace mlir;
+
+namespace mlir::tr {
+#define GEN_PASS_DEF_SPLITTRHOSTDEVICE
+#include "TileReducer/TileReducerPasses.h.inc"
+
+namespace {
+
+constexpr StringRef kRoleAttr = "tr.role";
+constexpr StringRef kSplitAttr = "tr.host_device_split";
+constexpr StringRef kHostRole = "host";
+constexpr StringRef kDeviceRole = "device";
+
+static NVVM::NVVMTargetAttr a100Target(MLIRContext *ctx) {
+  // A100-class chip. verifyTarget is off so attaching the attribute does
+  // not reject existing GPU ops before they are lowered.
+  return NVVM::NVVMTargetAttr::get(ctx, /*optLevel=*/2,
+                                   "nvptx64-nvidia-cuda", "sm_80",
+                                   /*features=*/"", /*targetFlags=*/nullptr,
+                                   /*linkFiles=*/nullptr,
+                                   /*verifyTarget=*/false);
+}
+
+struct SplitTRHostDevice : impl::SplitTRHostDeviceBase<SplitTRHostDevice> {
+  void runOnOperation() override {
+    ModuleOp module = getOperation();
+    MLIRContext *ctx = module.getContext();
+    OpBuilder b(ctx);
+
+    SmallVector<gpu::GPUModuleOp> gpuMods;
+    module.walk([&](gpu::GPUModuleOp gpuMod) { gpuMods.push_back(gpuMod); });
+    if (gpuMods.empty()) {
+      module.emitError()
+          << "tr-split-host-device expects a gpu.module (run "
+             "--tr-emit-gpu-kernels first)";
+      return signalPassFailure();
+    }
+
+    NVVM::NVVMTargetAttr target = a100Target(ctx);
+    for (gpu::GPUModuleOp gpuMod : gpuMods) {
+      SmallVector<Attribute> targets;
+      if (std::optional<ArrayAttr> existing = gpuMod.getTargets())
+        targets.append(existing->begin(), existing->end());
+      if (!llvm::is_contained(targets, target))
+        targets.push_back(target);
+      gpuMod.setTargetsAttr(b.getArrayAttr(targets));
+
+      gpuMod.walk([&](gpu::GPUFuncOp kernel) {
+        kernel->setAttr(kRoleAttr, b.getStringAttr(kDeviceRole));
+      });
+    }
+
+    unsigned launchCount = 0;
+    module.walk([&](func::FuncOp func) {
+      if (func->getParentOfType<gpu::GPUModuleOp>())
+        return;
+      bool isHost = false;
+      func.walk([&](gpu::LaunchFuncOp launch) {
+        isHost = true;
+        ++launchCount;
+        auto ref = launch.getKernel();
+        if (!SymbolTable::lookupNearestSymbolFrom(launch, ref)) {
+          launch.emitError()
+              << "host launch does not resolve kernel symbol " << ref;
+          signalPassFailure();
+        }
+      });
+      if (isHost)
+        func->setAttr(kRoleAttr, b.getStringAttr(kHostRole));
+    });
+
+    if (launchCount == 0) {
+      module.emitError()
+          << "tr-split-host-device expects at least one gpu.launch_func";
+      return signalPassFailure();
+    }
+
+    module->setAttr(gpu::GPUDialect::getContainerModuleAttrName(),
+                    b.getUnitAttr());
+    module->setAttr(kSplitAttr, b.getUnitAttr());
+  }
+};
+
+} // namespace
+} // namespace mlir::tr
diff --git a/tile-reducer/test/host-device-split-invalid.mlir b/tile-reducer/test/host-device-split-invalid.mlir
new file mode 100644
index 0000000000000..c15e68323e3ca
--- /dev/null
+++ b/tile-reducer/test/host-device-split-invalid.mlir
@@ -0,0 +1,23 @@
+// RUN: not tr-opt %s --split-input-file --tr-split-host-device 2>&1 | FileCheck %s
+
+// Milestone 28: the split pass is a hard failure without a device module
+// or without a host launch. Missing kernel symbols are already covered
+// by gpu-module-symbols-invalid.mlir (SymbolUserOpInterface).
+
+// CHECK: tr-split-host-device expects a gpu.module
+
+func.func @no_device(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  return
+}
+
+// -----
+
+// CHECK: tr-split-host-device expects at least one gpu.launch_func
+
+module attributes {gpu.container_module} {
+  gpu.module @tr_kernels {
+    gpu.func @row_sum_kernel() kernel {
+      gpu.return
+    }
+  }
+}
diff --git a/tile-reducer/test/host-device-split.mlir b/tile-reducer/test/host-device-split.mlir
new file mode 100644
index 0000000000000..480dbf97b20f0
--- /dev/null
+++ b/tile-reducer/test/host-device-split.mlir
@@ -0,0 +1,130 @@
+// RUN: tr-opt %s --tr-emit-gpu-kernels | FileCheck %s --check-prefix=BEFORE
+// RUN: tr-opt %s --tr-emit-gpu-kernels --tr-split-host-device | FileCheck %s --check-prefix=AFTER
+
+// Milestone 28: a GPU program is not one linear function.
+// BEFORE is GPU IR after outlining (host launch + device module, no target).
+// AFTER records the split: #nvvm.target on the device module, tr.role on
+// host launch ops vs device kernels.
+
+// BEFORE-NOT: nvvm.target
+// BEFORE-NOT: tr.role
+// BEFORE-NOT: tr.host_device_split
+// BEFORE: gpu.module @tr_kernels
+// BEFORE: gpu.func @row_sum_kernel
+// BEFORE-SAME: kernel
+// BEFORE: gpu.func @full_sum_stage1
+// BEFORE: gpu.func @full_sum_stage2
+// BEFORE: gpu.func @column_sum_kernel
+// BEFORE: func.func @row_sum
+// BEFORE: gpu.launch_func @tr_kernels::@row_sum_kernel
+// BEFORE: func.func @full_sum
+// BEFORE: gpu.launch_func @tr_kernels::@full_sum_stage1
+// BEFORE: gpu.launch_func @tr_kernels::@full_sum_stage2
+// BEFORE: func.func @column_sum
+// BEFORE: gpu.launch_func @tr_kernels::@column_sum_kernel
+
+// AFTER: module attributes
+// AFTER-SAME: gpu.container_module
+// AFTER-SAME: tr.host_device_split
+// AFTER: gpu.module @tr_kernels
+// AFTER-SAME: #nvvm.target
+// AFTER-SAME: chip = "sm_80"
+
+// AFTER: gpu.func @row_sum_kernel
+// AFTER-SAME: kernel
+// AFTER-SAME: tr.role = "device"
+// AFTER: gpu.block_id x
+// AFTER: gpu.lane_id
+// AFTER: gpu.subgroup_reduce add
+// AFTER: gpu.return
+
+// AFTER: gpu.func @full_sum_stage1
+// AFTER-SAME: workgroup(%{{.*}}: memref<8xf32, #gpu.address_space<workgroup>>)
+// AFTER-SAME: kernel
+// AFTER-SAME: tr.role = "device"
+// AFTER: gpu.barrier
+// AFTER: gpu.func @full_sum_stage2
+// AFTER-SAME: kernel
+// AFTER-SAME: tr.role = "device"
+
+// AFTER: gpu.func @column_sum_kernel
+// AFTER-SAME: workgroup(%{{.*}}: memref<128x128xf32, #gpu.address_space<workgroup>>)
+// AFTER-SAME: kernel
+// AFTER-SAME: tr.role = "device"
+// AFTER: gpu.barrier
+
+// AFTER: func.func @row_sum
+// AFTER-SAME: tr.role = "host"
+// AFTER: gpu.launch_func @tr_kernels::@row_sum_kernel
+// AFTER-SAME: blocks in
+// AFTER-SAME: threads in
+
+// AFTER: func.func @full_sum
+// AFTER-SAME: tr.role = "host"
+// AFTER: gpu.launch_func @tr_kernels::@full_sum_stage1
+// AFTER: gpu.launch_func @tr_kernels::@full_sum_stage2
+
+// AFTER: func.func @column_sum
+// AFTER-SAME: tr.role = "host"
+// AFTER: gpu.launch_func @tr_kernels::@column_sum_kernel
+// AFTER-NOT: gpu.launch {{.*}}blocks(
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}
+
+func.func @full_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<1xf32>) {
+  %blk  = tr.program_id 0 : index
+  %c128 = arith.constant 128 : index
+  %c0   = arith.constant 0 : index
+  %k    = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num  = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<f32>
+  %result = tr.for %kt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<f32> {
+    %t    = tr.load %in[%blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %row  = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %s    = tr.reduce_sum %row, axis = 0
+        : !tr.tile<128xf32> -> !tr.tile<f32>
+    %acc2 = tr.add %acc, %s : !tr.tile<f32>
+    tr.yield %acc2 : !tr.tile<f32>
+  }
+  tr.store %out[%c0], %result : !tr.buffer<1xf32>, !tr.tile<f32>
+  return
+}
+
+func.func @column_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Kxf32>) {
+  %col_blk = tr.program_id 0 : index
+  %c128    = arith.constant 128 : index
+  %m       = tr.dim %in, 0 : !tr.buffer<MxKxf32>, index
+  %num     = arith.divui %m, %c128 : index
+  %zero    = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %mt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%mt, %col_blk]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 0
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%col_blk], %result : !tr.buffer<Kxf32>, !tr.tile<128xf32>
+  return
+}
diff --git a/tile-reducer/test/smoke.mlir b/tile-reducer/test/smoke.mlir
index 5d38c2650df91..4c904b390112d 100644
--- a/tile-reducer/test/smoke.mlir
+++ b/tile-reducer/test/smoke.mlir
@@ -4,7 +4,7 @@
 // Milestone 1: the driver registers `tr` (plus func/arith from the canonical
 // source) and can parse a module. Types and ops are Milestone 2 / 3.
 
-// DIALECT: Available Dialects: affine,arith,builtin,func,gpu,linalg,memref,scf,tr,transform
+// DIALECT: Available Dialects: affine,arith,builtin,func,gpu,linalg,llvm,memref,nvvm,scf,tr,transform
 
 module {
   // CHECK-LABEL: func.func @smoke
diff --git a/tile-reducer/tr-opt/CMakeLists.txt b/tile-reducer/tr-opt/CMakeLists.txt
index 1a0bb85742536..005d1c9343fb2 100644
--- a/tile-reducer/tr-opt/CMakeLists.txt
+++ b/tile-reducer/tr-opt/CMakeLists.txt
@@ -4,6 +4,8 @@ set(LIBS
     MLIRFuncDialect
     MLIRFuncInlinerExtension
     MLIRGPUDialect
+    MLIRLLVMDialect
+    MLIRNVVMDialect
     MLIRLinalgDialect
     MLIRLinalgTransformOps
     MLIRLinalgTransforms
diff --git a/tile-reducer/tr-opt/tr-opt.cpp b/tile-reducer/tr-opt/tr-opt.cpp
index a3e3095d13b25..139138de771d9 100644
--- a/tile-reducer/tr-opt/tr-opt.cpp
+++ b/tile-reducer/tr-opt/tr-opt.cpp
@@ -10,6 +10,8 @@
 #include "mlir/Dialect/Func/Extensions/InlinerExtension.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
+#include "mlir/Dialect/LLVMIR/NVVMDialect.h"
 #include "mlir/Dialect/Linalg/IR/Linalg.h"
 #include "mlir/Dialect/Linalg/TransformOps/DialectExtension.h"
 #include "mlir/Dialect/Linalg/Transforms/TilingInterfaceImpl.h"
@@ -31,7 +33,8 @@ int main(int argc, char **argv) {
   mlir::DialectRegistry registry;
   registry.insert<mlir::tr::TileReducerDialect, mlir::affine::AffineDialect,
                   mlir::arith::ArithDialect, mlir::func::FuncDialect,
-                  mlir::gpu::GPUDialect, mlir::linalg::LinalgDialect,
+                  mlir::gpu::GPUDialect, mlir::LLVM::LLVMDialect,
+                  mlir::NVVM::NVVMDialect, mlir::linalg::LinalgDialect,
                   mlir::memref::MemRefDialect, mlir::scf::SCFDialect,
                   mlir::transform::TransformDialect>();
   mlir::func::registerInlinerExtension(registry);

>From 34f003f19839e427cef32fcb57413d175bc3b1b4 Mon Sep 17 00:00:00 2001
From: Ionut Hristodorescu <ionuthristodorescu at me.com>
Date: Sat, 15 Aug 2026 23:34:50 -0700
Subject: [PATCH 29/29] [TileReducer] Milestone 29: GPU to NVVM to LLVM IR

Device gpu.func lowers through upstream convert-gpu-to-nvvm to NVVM /
LLVM dialect. Host launch_func uses the MLIR GPU runtime ABI via
gpu-to-llvm. --tr-emit-device-llvmir translates the dialect to actual
LLVM IR; examples/row_sum.ll is the representative kernel.

Build:
  cmake -G Ninja -S tile-reducer -B tile-reducer/build \
    -DMLIR_DIR=<llvm-build>/lib/cmake/mlir
  cmake --build tile-reducer/build --target tr-opt

Test:
  cmake --build tile-reducer/build --target check-tr
  This milestone:
    tile-reducer/test/lower-device-nvvm.mlir
    tile-reducer/test/lower-host-llvm.mlir
    tile-reducer/test/row-sum-llvmir.mlir
  tr-opt --tr-emit-gpu-kernels --tr-split-host-device --tr-lower-device-to-nvvm --tr-lower-host-to-llvm --tr-emit-device-llvmir=output=row_sum.ll tile-reducer/examples/row_sum.mlir

Co-authored-by: Cursor <cursoragent at cursor.com>
---
 tile-reducer/README.md                        |   9 +
 tile-reducer/examples/row_sum.ll              | 166 +++++++++++++++
 .../include/TileReducer/TileReducerPasses.td  |  48 +++++
 tile-reducer/lib/TileReducer/CMakeLists.txt   |  22 ++
 .../TileReducer/TileReducerLLVMLowering.cpp   | 192 ++++++++++++++++++
 tile-reducer/test/lower-device-nvvm.mlir      |  99 +++++++++
 tile-reducer/test/lower-host-llvm.mlir        |  91 +++++++++
 tile-reducer/test/row-sum-llvmir.mlir         |  38 ++++
 tile-reducer/test/smoke.mlir                  |   2 +-
 tile-reducer/tr-opt/CMakeLists.txt            |   9 +
 tile-reducer/tr-opt/tr-opt.cpp                |  33 ++-
 11 files changed, 706 insertions(+), 3 deletions(-)
 create mode 100644 tile-reducer/examples/row_sum.ll
 create mode 100644 tile-reducer/lib/TileReducer/TileReducerLLVMLowering.cpp
 create mode 100644 tile-reducer/test/lower-device-nvvm.mlir
 create mode 100644 tile-reducer/test/lower-host-llvm.mlir
 create mode 100644 tile-reducer/test/row-sum-llvmir.mlir

diff --git a/tile-reducer/README.md b/tile-reducer/README.md
index 6f53ab6819830..b2b79da427b87 100644
--- a/tile-reducer/README.md
+++ b/tile-reducer/README.md
@@ -161,3 +161,12 @@ outlined. Host `func.func` keeps `gpu.launch_func` (`tr.role = "host"`).
 Device `gpu.func` symbols live in `gpu.module @tr_kernels` with
 `#nvvm.target<chip = "sm_80">` (`tr.role = "device"`). A missing kernel
 symbol is a hard lookup failure. No computation is rewritten.
+
+## Milestone 29
+
+Device: `--tr-lower-device-to-nvvm` turns `gpu.func` into NVVM / LLVM
+dialect (`nvvm.read.ptx.sreg.*`, `nvvm.shfl.sync`, `llvm.func`).
+Host: `--tr-lower-host-to-llvm` uses upstream `gpu-to-llvm` so launch
+ops become LLVM-typed runtime/launch IR. `--tr-emit-device-llvmir`
+translates the device LLVM dialect to actual LLVM IR (`.ll`). Those
+are not the same representation.
diff --git a/tile-reducer/examples/row_sum.ll b/tile-reducer/examples/row_sum.ll
new file mode 100644
index 0000000000000..9aaa32a1f979a
--- /dev/null
+++ b/tile-reducer/examples/row_sum.ll
@@ -0,0 +1,166 @@
+; Representative TileReducer row-sum device LLVM IR (Milestone 29).
+; Generated by:
+;   tr-opt examples/row_sum.mlir --tr-emit-gpu-kernels \
+;     --tr-split-host-device --tr-lower-device-to-nvvm \
+;     --tr-emit-device-llvmir=output=examples/row_sum.ll
+; This is actual LLVM IR, not MLIR LLVM dialect.
+; ModuleID = 'tr_kernels'
+source_filename = "tr_kernels"
+target triple = "nvptx64-nvidia-cuda"
+
+define ptx_kernel void @row_sum_kernel(ptr %0, ptr %1, i64 %2, i64 %3, i64 %4, i64 %5, i64 %6, ptr %7, ptr %8, i64 %9, i64 %10, i64 %11) #0 {
+  %13 = insertvalue { ptr, ptr, i64, [1 x i64], [1 x i64] } poison, ptr %7, 0
+  %14 = insertvalue { ptr, ptr, i64, [1 x i64], [1 x i64] } %13, ptr %8, 1
+  %15 = insertvalue { ptr, ptr, i64, [1 x i64], [1 x i64] } %14, i64 %9, 2
+  %16 = insertvalue { ptr, ptr, i64, [1 x i64], [1 x i64] } %15, i64 %10, 3, 0
+  %17 = insertvalue { ptr, ptr, i64, [1 x i64], [1 x i64] } %16, i64 %11, 4, 0
+  %18 = insertvalue { ptr, ptr, i64, [2 x i64], [2 x i64] } poison, ptr %0, 0
+  %19 = insertvalue { ptr, ptr, i64, [2 x i64], [2 x i64] } %18, ptr %1, 1
+  %20 = insertvalue { ptr, ptr, i64, [2 x i64], [2 x i64] } %19, i64 %2, 2
+  %21 = insertvalue { ptr, ptr, i64, [2 x i64], [2 x i64] } %20, i64 %3, 3, 0
+  %22 = insertvalue { ptr, ptr, i64, [2 x i64], [2 x i64] } %21, i64 %5, 4, 0
+  %23 = insertvalue { ptr, ptr, i64, [2 x i64], [2 x i64] } %22, i64 %4, 3, 1
+  %24 = insertvalue { ptr, ptr, i64, [2 x i64], [2 x i64] } %23, i64 %6, 4, 1
+  %25 = call i32 @llvm.nvvm.read.ptx.sreg.ctaid.x()
+  %26 = sext i32 %25 to i64
+  %27 = call range(i32 0, 32) i32 @llvm.nvvm.read.ptx.sreg.laneid()
+  %28 = sext i32 %27 to i64
+  %29 = call range(i32 0, 256) i32 @llvm.nvvm.read.ptx.sreg.tid.x()
+  %30 = sext i32 %29 to i64
+  %31 = call range(i32 0, 1) i32 @llvm.nvvm.read.ptx.sreg.tid.y()
+  %32 = sext i32 %31 to i64
+  %33 = call range(i32 0, 1) i32 @llvm.nvvm.read.ptx.sreg.tid.z()
+  %34 = sext i32 %33 to i64
+  %35 = add nuw nsw i64 %34, %32
+  %36 = mul nuw nsw i64 %35, 256
+  %37 = add nuw nsw i64 %30, %36
+  %38 = udiv i64 %37, 32
+  %39 = extractvalue { ptr, ptr, i64, [2 x i64], [2 x i64] } %24, 3, 0
+  %40 = extractvalue { ptr, ptr, i64, [2 x i64], [2 x i64] } %24, 3, 1
+  %41 = icmp eq i64 %40, 0
+  %42 = sub i64 %40, 1
+  %43 = udiv i64 %42, 128
+  %44 = add i64 %43, 1
+  %45 = select i1 %41, i64 0, i64 %44
+  %46 = mul i64 %26, 128
+  br label %47
+
+47:                                               ; preds = %102, %12
+  %48 = phi i64 [ %103, %102 ], [ 0, %12 ]
+  %49 = icmp slt i64 %48, 16
+  br i1 %49, label %50, label %104
+
+50:                                               ; preds = %47
+  %51 = mul i64 %48, 8
+  %52 = add i64 %38, %51
+  %53 = add i64 %46, %52
+  %54 = icmp ult i64 %53, %39
+  br i1 %54, label %55, label %102
+
+55:                                               ; preds = %50
+  br label %56
+
+56:                                               ; preds = %84, %55
+  %57 = phi i64 [ %85, %84 ], [ 0, %55 ]
+  %58 = phi float [ %64, %84 ], [ 0.000000e+00, %55 ]
+  %59 = icmp slt i64 %57, %45
+  br i1 %59, label %60, label %86
+
+60:                                               ; preds = %56
+  %61 = mul i64 %57, 128
+  br label %62
+
+62:                                               ; preds = %81, %60
+  %63 = phi i64 [ %83, %81 ], [ 0, %60 ]
+  %64 = phi float [ %82, %81 ], [ %58, %60 ]
+  %65 = icmp slt i64 %63, 4
+  br i1 %65, label %66, label %84
+
+66:                                               ; preds = %62
+  %67 = mul i64 %63, 32
+  %68 = add i64 %61, %28
+  %69 = add i64 %68, %67
+  %70 = icmp ult i64 %69, %40
+  br i1 %70, label %71, label %78
+
+71:                                               ; preds = %66
+  %72 = extractvalue { ptr, ptr, i64, [2 x i64], [2 x i64] } %24, 1
+  %73 = extractvalue { ptr, ptr, i64, [2 x i64], [2 x i64] } %24, 4, 0
+  %74 = mul nuw nsw i64 %53, %73
+  %75 = add nuw nsw i64 %74, %69
+  %76 = getelementptr inbounds nuw float, ptr %72, i64 %75
+  %77 = load float, ptr %76, align 4
+  br label %79
+
+78:                                               ; preds = %66
+  br label %79
+
+79:                                               ; preds = %71, %78
+  %80 = phi float [ 0.000000e+00, %78 ], [ %77, %71 ]
+  br label %81
+
+81:                                               ; preds = %79
+  %82 = fadd float %64, %80
+  %83 = add i64 %63, 1
+  br label %62
+
+84:                                               ; preds = %62
+  %85 = add i64 %57, 1
+  br label %56
+
+86:                                               ; preds = %56
+  %87 = call float @llvm.nvvm.shfl.sync.bfly.f32(i32 -1, float %58, i32 1, i32 31)
+  %88 = fadd float %58, %87
+  %89 = call float @llvm.nvvm.shfl.sync.bfly.f32(i32 -1, float %88, i32 2, i32 31)
+  %90 = fadd float %88, %89
+  %91 = call float @llvm.nvvm.shfl.sync.bfly.f32(i32 -1, float %90, i32 4, i32 31)
+  %92 = fadd float %90, %91
+  %93 = call float @llvm.nvvm.shfl.sync.bfly.f32(i32 -1, float %92, i32 8, i32 31)
+  %94 = fadd float %92, %93
+  %95 = call float @llvm.nvvm.shfl.sync.bfly.f32(i32 -1, float %94, i32 16, i32 31)
+  %96 = fadd float %94, %95
+  %97 = icmp eq i64 %28, 0
+  br i1 %97, label %98, label %101
+
+98:                                               ; preds = %86
+  %99 = extractvalue { ptr, ptr, i64, [1 x i64], [1 x i64] } %17, 1
+  %100 = getelementptr inbounds nuw float, ptr %99, i64 %53
+  store float %96, ptr %100, align 4
+  br label %101
+
+101:                                              ; preds = %98, %86
+  br label %102
+
+102:                                              ; preds = %101, %50
+  %103 = add i64 %48, 1
+  br label %47
+
+104:                                              ; preds = %47
+  ret void
+}
+
+; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
+declare noundef range(i32 0, 2147483647) i32 @llvm.nvvm.read.ptx.sreg.ctaid.x() #1
+
+; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
+declare noundef range(i32 0, 32) i32 @llvm.nvvm.read.ptx.sreg.laneid() #1
+
+; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
+declare noundef range(i32 0, 1024) i32 @llvm.nvvm.read.ptx.sreg.tid.x() #1
+
+; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
+declare noundef range(i32 0, 1024) i32 @llvm.nvvm.read.ptx.sreg.tid.y() #1
+
+; Function Attrs: nocallback nofree nosync nounwind speculatable willreturn memory(none)
+declare noundef range(i32 0, 64) i32 @llvm.nvvm.read.ptx.sreg.tid.z() #1
+
+; Function Attrs: convergent nocallback nounwind memory(inaccessiblemem: readwrite)
+declare float @llvm.nvvm.shfl.sync.bfly.f32(i32, float, i32, i32) #2
+
+attributes #0 = { "nvvm.maxntid"="256,1,1" }
+attributes #1 = { nocallback nofree nosync nounwind speculatable willreturn memory(none) }
+attributes #2 = { convergent nocallback nounwind memory(inaccessiblemem: readwrite) }
+
+!llvm.module.flags = !{!0}
+
+!0 = !{i32 2, !"Debug Info Version", i32 3}
diff --git a/tile-reducer/include/TileReducer/TileReducerPasses.td b/tile-reducer/include/TileReducer/TileReducerPasses.td
index 5bab843047a97..025c59a7a2ccc 100644
--- a/tile-reducer/include/TileReducer/TileReducerPasses.td
+++ b/tile-reducer/include/TileReducer/TileReducerPasses.td
@@ -207,6 +207,54 @@ def TRBenchReport : Pass<"tr-bench-report", "::mlir::ModuleOp"> {
   ];
 }
 
+def LowerTRDeviceToNVVM : Pass<"tr-lower-device-to-nvvm", "::mlir::ModuleOp"> {
+  let summary = "Lower gpu.module payload to NVVM / LLVM dialect.";
+  let description = [{
+    Device path only. f32 `gpu.subgroup_reduce` becomes butterfly
+    `gpu.shuffle`, then upstream `convert-gpu-to-nvvm` produces
+    `nvvm.read.ptx.sreg.*`, `nvvm.shfl.sync`, and `llvm.func` kernels.
+    Host `func.func` / `gpu.launch_func` are left alone.
+  }];
+  let dependentDialects = [
+    "::mlir::gpu::GPUDialect",
+    "::mlir::NVVM::NVVMDialect",
+    "::mlir::LLVM::LLVMDialect",
+    "::mlir::cf::ControlFlowDialect",
+    "::mlir::arith::ArithDialect",
+    "::mlir::memref::MemRefDialect"
+  ];
+}
+
+def LowerTRHostToLLVM : Pass<"tr-lower-host-to-llvm", "::mlir::ModuleOp"> {
+  let summary = "Lower host launch/runtime ops toward the LLVM dialect.";
+  let description = [{
+    Host path only. Uses upstream `gpu-to-llvm` so `gpu.launch_func`
+    keeps the MLIR GPU runtime ABI (`mgpu*` when a binary is present;
+    legalized launch_func + LLVM types otherwise). Does not invent a
+    proprietary runtime.
+  }];
+  let dependentDialects = [
+    "::mlir::gpu::GPUDialect",
+    "::mlir::LLVM::LLVMDialect",
+    "::mlir::func::FuncDialect",
+    "::mlir::arith::ArithDialect",
+    "::mlir::memref::MemRefDialect"
+  ];
+}
+
+def EmitTRDeviceLLVMIR : Pass<"tr-emit-device-llvmir", "::mlir::ModuleOp"> {
+  let summary = "Translate device LLVM dialect to actual LLVM IR (.ll).";
+  let description = [{
+    MLIR LLVM dialect is not LLVM IR. This pass calls
+    `translateModuleToLLVMIR` on the lowered `gpu.module` kernels and
+    writes a `.ll` file. The MLIR module is unchanged.
+  }];
+  let options = [
+    Option<"outputPath", "output", "std::string", /*default=*/[{""}],
+           "Path for the device .ll (empty = stderr)">
+  ];
+}
+
 def SplitTRHostDevice : Pass<"tr-split-host-device", "::mlir::ModuleOp"> {
   let summary = "Make the GPU host/device split explicit. No computation rewrite.";
   let description = [{
diff --git a/tile-reducer/lib/TileReducer/CMakeLists.txt b/tile-reducer/lib/TileReducer/CMakeLists.txt
index 31f9d5f956e55..78073da16ec75 100644
--- a/tile-reducer/lib/TileReducer/CMakeLists.txt
+++ b/tile-reducer/lib/TileReducer/CMakeLists.txt
@@ -12,6 +12,7 @@ add_mlir_dialect_library(MLIRTileReducer
         TileReducerGPURowSum.cpp
         TileReducerGPUKernels.cpp
         TileReducerHostDevice.cpp
+        TileReducerLLVMLowering.cpp
         ReductionCostModel.cpp
         TileReducerCostPasses.cpp
         TileReducerPasses.cpp
@@ -34,6 +35,27 @@ add_mlir_dialect_library(MLIRTileReducer
         MLIRGPUDialect
         MLIRNVVMDialect
         MLIRLLVMDialect
+        MLIRControlFlowDialect
+        MLIRIndexDialect
+        MLIRGPUTransforms
+        MLIRGPUToNVVMTransforms
+        MLIRGPUToGPURuntimeTransforms
+        MLIRSCFToControlFlow
+        MLIRArithToLLVM
+        MLIRFuncToLLVM
+        MLIRMemRefToLLVM
+        MLIRMemRefTransforms
+        MLIRIndexToLLVM
+        MLIRControlFlowToLLVM
+        MLIRReconcileUnrealizedCasts
+        MLIRNVVMToLLVM
+        MLIRMathToLLVM
+        MLIRUBToLLVM
+        MLIRConvertToLLVMInterface
+        MLIRTargetLLVMIRExport
+        MLIRBuiltinToLLVMIRTranslation
+        MLIRLLVMToLLVMIRTranslation
+        MLIRNVVMToLLVMIRTranslation
         MLIRAffineDialect
         MLIRAffineToStandard
         MLIRAffineUtils
diff --git a/tile-reducer/lib/TileReducer/TileReducerLLVMLowering.cpp b/tile-reducer/lib/TileReducer/TileReducerLLVMLowering.cpp
new file mode 100644
index 0000000000000..51842c98b3146
--- /dev/null
+++ b/tile-reducer/lib/TileReducer/TileReducerLLVMLowering.cpp
@@ -0,0 +1,192 @@
+//===- TileReducerLLVMLowering.cpp - Milestone 29 ---------------*- C++ -*-===//
+//
+// Device:  gpu.func  -> NVVM / LLVM dialect -> LLVM IR (.ll)
+// Host:    gpu.launch_func -> GPU runtime ABI / LLVM dialect
+//
+// Uses specific upstream conversion headers. Does not include
+// mlir/Conversion/Passes.h (that registers every conversion).
+//
+//===----------------------------------------------------------------------===//
+
+#include "TileReducer/TileReducerPasses.h"
+
+#include "mlir/Conversion/ArithToLLVM/ArithToLLVM.h"
+#include "mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h"
+#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVMPass.h"
+#include "mlir/Conversion/GPUCommon/GPUCommonPass.h"
+#include "mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h"
+#include "mlir/Conversion/IndexToLLVM/IndexToLLVM.h"
+#include "mlir/Conversion/MemRefToLLVM/MemRefToLLVM.h"
+#include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h"
+#include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h"
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/ControlFlow/IR/ControlFlow.h"
+#include "mlir/Dialect/Func/IR/FuncOps.h"
+#include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/GPU/Transforms/Passes.h"
+#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
+#include "mlir/Dialect/LLVMIR/NVVMDialect.h"
+#include "mlir/Dialect/MemRef/IR/MemRef.h"
+#include "mlir/Dialect/MemRef/Transforms/Passes.h"
+#include "mlir/IR/BuiltinOps.h"
+#include "mlir/IR/PatternMatch.h"
+#include "mlir/Pass/PassManager.h"
+#include "mlir/Target/LLVMIR/Export.h"
+#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
+
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Module.h"
+#include "llvm/Support/FileSystem.h"
+#include "llvm/Support/ToolOutputFile.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace mlir;
+
+namespace mlir::tr {
+#define GEN_PASS_DEF_LOWERTRDEVICETONVVM
+#define GEN_PASS_DEF_LOWERTRHOSTTOLLVM
+#define GEN_PASS_DEF_EMITTRDEVICELLVMIR
+#include "TileReducer/TileReducerPasses.h.inc"
+
+namespace {
+
+struct SubgroupSizeToConst : OpRewritePattern<gpu::SubgroupSizeOp> {
+  unsigned warpSize;
+  SubgroupSizeToConst(MLIRContext *ctx, unsigned warpSize)
+      : OpRewritePattern<gpu::SubgroupSizeOp>(ctx), warpSize(warpSize) {}
+  LogicalResult matchAndRewrite(gpu::SubgroupSizeOp op,
+                                PatternRewriter &rewriter) const override {
+    rewriter.replaceOpWithNewOp<arith::ConstantIndexOp>(op, warpSize);
+    return success();
+  }
+};
+
+static LogicalResult
+prepareDeviceGPUOps(gpu::GPUModuleOp gpuMod, unsigned warpSize) {
+  RewritePatternSet patterns(gpuMod.getContext());
+  populateGpuSubgroupIdPatterns(patterns);
+  patterns.add<SubgroupSizeToConst>(gpuMod.getContext(), warpSize);
+  populateGpuLowerSubgroupReduceToShufflePatterns(patterns, warpSize);
+  return applyPatternsGreedily(gpuMod, std::move(patterns));
+}
+
+struct LowerTRDeviceToNVVM
+    : impl::LowerTRDeviceToNVVMBase<LowerTRDeviceToNVVM> {
+  void runOnOperation() override {
+    ModuleOp module = getOperation();
+    bool any = false;
+    bool prepFailed = false;
+    module.walk([&](gpu::GPUModuleOp gpuMod) {
+      any = true;
+      if (failed(prepareDeviceGPUOps(gpuMod, /*warpSize=*/32))) {
+        gpuMod.emitError() << "failed to lower subgroup_reduce / subgroup_id";
+        prepFailed = true;
+      }
+    });
+    if (!any) {
+      module.emitError() << "tr-lower-device-to-nvvm expects a gpu.module";
+      return signalPassFailure();
+    }
+    if (prepFailed)
+      return signalPassFailure();
+
+    OpPassManager pm(module.getOperationName());
+    pm.addNestedPass<gpu::GPUModuleOp>(createSCFToControlFlowPass());
+    pm.addNestedPass<gpu::GPUModuleOp>(
+        memref::createExpandStridedMetadataPass());
+    ConvertGpuOpsToNVVMOpsOptions nvvmOpt;
+    nvvmOpt.indexBitwidth = 64;
+    nvvmOpt.hasRedux = false;
+    pm.addNestedPass<gpu::GPUModuleOp>(createConvertGpuOpsToNVVMOps(nvvmOpt));
+    pm.addNestedPass<gpu::GPUModuleOp>(createReconcileUnrealizedCastsPass());
+    if (failed(runPipeline(pm, module)))
+      signalPassFailure();
+  }
+};
+
+struct LowerTRHostToLLVM : impl::LowerTRHostToLLVMBase<LowerTRHostToLLVM> {
+  void runOnOperation() override {
+    ModuleOp module = getOperation();
+    if (!module.walk([](gpu::LaunchFuncOp) { return WalkResult::interrupt(); })
+             .wasInterrupted()) {
+      module.emitError() << "tr-lower-host-to-llvm expects gpu.launch_func";
+      return signalPassFailure();
+    }
+
+    OpPassManager pm(module.getOperationName());
+    pm.addPass(createSCFToControlFlowPass());
+    pm.addPass(memref::createExpandStridedMetadataPass());
+    pm.addPass(createArithToLLVMConversionPass());
+    pm.addPass(createConvertIndexToLLVMPass());
+    pm.addPass(createGpuToLLVMConversionPass());
+    pm.addPass(createFinalizeMemRefToLLVMConversionPass());
+    pm.addPass(createConvertFuncToLLVMPass());
+    pm.addPass(createConvertControlFlowToLLVMPass());
+    pm.addPass(createReconcileUnrealizedCastsPass());
+    if (failed(runPipeline(pm, module)))
+      signalPassFailure();
+  }
+};
+
+static LogicalResult writeDeviceLLVMIR(gpu::GPUModuleOp gpuMod,
+                                       raw_ostream &os) {
+  MLIRContext *ctx = gpuMod.getContext();
+
+  OpBuilder b(ctx);
+  OwningOpRef<ModuleOp> tmp = ModuleOp::create(gpuMod.getLoc());
+  (*tmp)->setAttr(LLVM::LLVMDialect::getTargetTripleAttrName(),
+                  b.getStringAttr("nvptx64-nvidia-cuda"));
+  b.setInsertionPointToStart(tmp->getBody());
+  for (Operation &op : gpuMod.getOps()) {
+    if (isa<LLVM::LLVMFuncOp, LLVM::GlobalOp>(op))
+      b.clone(op);
+  }
+
+  llvm::LLVMContext llvmCtx;
+  std::unique_ptr<llvm::Module> llvmModule =
+      translateModuleToLLVMIR(tmp.get(), llvmCtx, gpuMod.getName());
+  if (!llvmModule)
+    return gpuMod.emitError("failed to translate device LLVM dialect to LLVM IR");
+  llvmModule->print(os, nullptr);
+  return success();
+}
+
+struct EmitTRDeviceLLVMIR : impl::EmitTRDeviceLLVMIRBase<EmitTRDeviceLLVMIR> {
+  using impl::EmitTRDeviceLLVMIRBase<EmitTRDeviceLLVMIR>::EmitTRDeviceLLVMIRBase;
+
+  void runOnOperation() override {
+    ModuleOp module = getOperation();
+    gpu::GPUModuleOp gpuMod;
+    module.walk([&](gpu::GPUModuleOp m) {
+      if (!gpuMod)
+        gpuMod = m;
+    });
+    if (!gpuMod) {
+      module.emitError() << "tr-emit-device-llvmir expects a gpu.module";
+      return signalPassFailure();
+    }
+    if (gpuMod.getOps<LLVM::LLVMFuncOp>().empty()) {
+      gpuMod.emitError()
+          << "device module has no llvm.func (run --tr-lower-device-to-nvvm)";
+      return signalPassFailure();
+    }
+
+    if (outputPath.empty()) {
+      if (failed(writeDeviceLLVMIR(gpuMod, llvm::errs())))
+        return signalPassFailure();
+      return;
+    }
+
+    std::error_code ec;
+    llvm::raw_fd_ostream file(outputPath, ec, llvm::sys::fs::OF_Text);
+    if (ec) {
+      module.emitError() << "cannot write " << outputPath << ": " << ec.message();
+      return signalPassFailure();
+    }
+    if (failed(writeDeviceLLVMIR(gpuMod, file)))
+      return signalPassFailure();
+  }
+};
+
+} // namespace
+} // namespace mlir::tr
diff --git a/tile-reducer/test/lower-device-nvvm.mlir b/tile-reducer/test/lower-device-nvvm.mlir
new file mode 100644
index 0000000000000..eddbf292645b9
--- /dev/null
+++ b/tile-reducer/test/lower-device-nvvm.mlir
@@ -0,0 +1,99 @@
+// RUN: tr-opt %s --tr-emit-gpu-kernels --tr-split-host-device --tr-lower-device-to-nvvm | FileCheck %s
+
+// Milestone 29 device path: gpu.func -> NVVM / LLVM dialect.
+// Host launch_func stays in func.func. Workgroup memrefs and barriers
+// become NVVM address spaces / nvvm.barrier.
+
+// CHECK: gpu.module @tr_kernels
+
+// CHECK: llvm.func @row_sum_kernel
+// CHECK-SAME: nvvm.kernel
+// CHECK-DAG: nvvm.read.ptx.sreg.ctaid.x
+// CHECK-DAG: nvvm.read.ptx.sreg.tid.x
+// CHECK-DAG: nvvm.read.ptx.sreg.laneid
+// CHECK: nvvm.shfl.sync
+// CHECK: llvm.return
+
+// CHECK: llvm.func @full_sum_stage1
+// CHECK-SAME: nvvm.kernel
+// CHECK: nvvm.shfl.sync
+// CHECK: nvvm.barrier
+// CHECK: llvm.func @full_sum_stage2
+// CHECK-SAME: nvvm.kernel
+// CHECK: nvvm.barrier
+
+// CHECK: llvm.func @column_sum_kernel
+// CHECK-SAME: nvvm.kernel
+// CHECK: nvvm.barrier
+
+// CHECK-NOT: gpu.subgroup_reduce
+// CHECK-NOT: gpu.func @
+// CHECK-NOT: scf.for
+
+// CHECK: func.func @row_sum
+// CHECK: gpu.launch_func @tr_kernels::@row_sum_kernel
+// CHECK: func.func @full_sum
+// CHECK: gpu.launch_func @tr_kernels::@full_sum_stage1
+// CHECK: gpu.launch_func @tr_kernels::@full_sum_stage2
+// CHECK: func.func @column_sum
+// CHECK: gpu.launch_func @tr_kernels::@column_sum_kernel
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}
+
+func.func @full_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<1xf32>) {
+  %blk  = tr.program_id 0 : index
+  %c128 = arith.constant 128 : index
+  %c0   = arith.constant 0 : index
+  %k    = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num  = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<f32>
+  %result = tr.for %kt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<f32> {
+    %t    = tr.load %in[%blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %row  = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %s    = tr.reduce_sum %row, axis = 0
+        : !tr.tile<128xf32> -> !tr.tile<f32>
+    %acc2 = tr.add %acc, %s : !tr.tile<f32>
+    tr.yield %acc2 : !tr.tile<f32>
+  }
+  tr.store %out[%c0], %result : !tr.buffer<1xf32>, !tr.tile<f32>
+  return
+}
+
+func.func @column_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Kxf32>) {
+  %col_blk = tr.program_id 0 : index
+  %c128    = arith.constant 128 : index
+  %m       = tr.dim %in, 0 : !tr.buffer<MxKxf32>, index
+  %num     = arith.divui %m, %c128 : index
+  %zero    = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %mt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%mt, %col_blk]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 0
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%col_blk], %result : !tr.buffer<Kxf32>, !tr.tile<128xf32>
+  return
+}
diff --git a/tile-reducer/test/lower-host-llvm.mlir b/tile-reducer/test/lower-host-llvm.mlir
new file mode 100644
index 0000000000000..88699c3985b98
--- /dev/null
+++ b/tile-reducer/test/lower-host-llvm.mlir
@@ -0,0 +1,91 @@
+// RUN: tr-opt %s --tr-emit-gpu-kernels --tr-split-host-device --tr-lower-device-to-nvvm --tr-lower-host-to-llvm | FileCheck %s
+
+// Milestone 29 host path: launch/runtime ops toward LLVM dialect.
+// Device must be NVVM/LLVM first so launch_func operand packing matches
+// the lowered kernel ABI. Uses the upstream GPU runtime ABI, not a
+// TileReducer-specific calling convention.
+
+// CHECK: gpu.module @tr_kernels
+// CHECK: llvm.func @row_sum_kernel
+// CHECK-SAME: nvvm.kernel
+// CHECK: llvm.func @full_sum_stage1
+// CHECK: llvm.func @full_sum_stage2
+// CHECK: llvm.func @column_sum_kernel
+
+// CHECK: llvm.func @row_sum
+// CHECK-SAME: !llvm.ptr
+// CHECK-SAME: tr.role = "host"
+// CHECK: gpu.launch_func @tr_kernels::@row_sum_kernel
+// CHECK-SAME: args(%{{.*}} : !llvm.ptr
+
+// CHECK: llvm.func @full_sum
+// CHECK-SAME: tr.role = "host"
+// CHECK: gpu.launch_func @tr_kernels::@full_sum_stage1
+// CHECK: gpu.launch_func @tr_kernels::@full_sum_stage2
+
+// CHECK: llvm.func @column_sum
+// CHECK-SAME: tr.role = "host"
+// CHECK: gpu.launch_func @tr_kernels::@column_sum_kernel
+
+// CHECK-NOT: func.func @
+// CHECK-NOT: tr.runtime
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}
+
+func.func @full_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<1xf32>) {
+  %blk  = tr.program_id 0 : index
+  %c128 = arith.constant 128 : index
+  %c0   = arith.constant 0 : index
+  %k    = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num  = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<f32>
+  %result = tr.for %kt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<f32> {
+    %t    = tr.load %in[%blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %row  = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %s    = tr.reduce_sum %row, axis = 0
+        : !tr.tile<128xf32> -> !tr.tile<f32>
+    %acc2 = tr.add %acc, %s : !tr.tile<f32>
+    tr.yield %acc2 : !tr.tile<f32>
+  }
+  tr.store %out[%c0], %result : !tr.buffer<1xf32>, !tr.tile<f32>
+  return
+}
+
+func.func @column_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Kxf32>) {
+  %col_blk = tr.program_id 0 : index
+  %c128    = arith.constant 128 : index
+  %m       = tr.dim %in, 0 : !tr.buffer<MxKxf32>, index
+  %num     = arith.divui %m, %c128 : index
+  %zero    = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %mt = 0 to %num step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%mt, %col_blk]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 0
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%col_blk], %result : !tr.buffer<Kxf32>, !tr.tile<128xf32>
+  return
+}
diff --git a/tile-reducer/test/row-sum-llvmir.mlir b/tile-reducer/test/row-sum-llvmir.mlir
new file mode 100644
index 0000000000000..ee72cc953b22e
--- /dev/null
+++ b/tile-reducer/test/row-sum-llvmir.mlir
@@ -0,0 +1,38 @@
+// RUN: tr-opt %s --tr-emit-gpu-kernels --tr-split-host-device --tr-lower-device-to-nvvm --tr-emit-device-llvmir=output=%t.ll | FileCheck %s --check-prefix=MLIR
+// RUN: FileCheck %s --check-prefix=LL < %t.ll
+// RUN: not tr-opt %s --tr-emit-gpu-kernels --tr-split-host-device --tr-emit-device-llvmir=output=%t.skip.ll 2>&1 | FileCheck %s --check-prefix=NEED-NVVM
+
+// Milestone 29: MLIR LLVM dialect is not LLVM IR.
+// --tr-lower-device-to-nvvm produces the dialect; --tr-emit-device-llvmir
+// translates it with translateModuleToLLVMIR.
+
+// MLIR: llvm.func @row_sum_kernel
+// MLIR: nvvm.read.ptx.sreg.ctaid.x
+// MLIR: nvvm.shfl.sync
+
+// LL: target triple = "nvptx64-nvidia-cuda"
+// LL: define {{.*}}@row_sum_kernel
+// LL: llvm.nvvm.read.ptx.sreg.ctaid.x
+// LL: llvm.nvvm.read.ptx.sreg.laneid
+// LL: llvm.nvvm.shfl.sync
+
+// NEED-NVVM: device module has no llvm.func (run --tr-lower-device-to-nvvm)
+
+func.func @row_sum(%in: !tr.buffer<MxKxf32>, %out: !tr.buffer<Mxf32>) {
+  %row_blk     = tr.program_id 0 : index
+  %c128        = arith.constant 128 : index
+  %k           = tr.dim %in, 1 : !tr.buffer<MxKxf32>, index
+  %num_k_tiles = arith.divui %k, %c128 : index
+  %zero = tr.constant 0.0 : !tr.tile<128xf32>
+  %result = tr.for %kt = 0 to %num_k_tiles step 1
+      iter_args(%acc = %zero) -> !tr.tile<128xf32> {
+    %t       = tr.load %in[%row_blk, %kt]
+        : !tr.buffer<MxKxf32>, !tr.tile<128x128xf32>
+    %partial = tr.reduce_sum %t, axis = 1
+        : !tr.tile<128x128xf32> -> !tr.tile<128xf32>
+    %acc2    = tr.add %acc, %partial : !tr.tile<128xf32>
+    tr.yield %acc2 : !tr.tile<128xf32>
+  }
+  tr.store %out[%row_blk], %result : !tr.buffer<Mxf32>, !tr.tile<128xf32>
+  return
+}
diff --git a/tile-reducer/test/smoke.mlir b/tile-reducer/test/smoke.mlir
index 4c904b390112d..8b6899a2fb219 100644
--- a/tile-reducer/test/smoke.mlir
+++ b/tile-reducer/test/smoke.mlir
@@ -4,7 +4,7 @@
 // Milestone 1: the driver registers `tr` (plus func/arith from the canonical
 // source) and can parse a module. Types and ops are Milestone 2 / 3.
 
-// DIALECT: Available Dialects: affine,arith,builtin,func,gpu,linalg,llvm,memref,nvvm,scf,tr,transform
+// DIALECT: Available Dialects: affine,arith,builtin,cf,func,gpu,index,linalg,llvm,memref,nvvm,scf,tr,transform
 
 module {
   // CHECK-LABEL: func.func @smoke
diff --git a/tile-reducer/tr-opt/CMakeLists.txt b/tile-reducer/tr-opt/CMakeLists.txt
index 005d1c9343fb2..ec8a675346b9b 100644
--- a/tile-reducer/tr-opt/CMakeLists.txt
+++ b/tile-reducer/tr-opt/CMakeLists.txt
@@ -3,9 +3,18 @@ set(LIBS
     MLIRArithDialect
     MLIRFuncDialect
     MLIRFuncInlinerExtension
+    MLIRControlFlowDialect
     MLIRGPUDialect
+    MLIRIndexDialect
     MLIRLLVMDialect
     MLIRNVVMDialect
+    MLIRNVVMToLLVM
+    MLIRMathToLLVM
+    MLIRUBToLLVM
+    MLIRTargetLLVMIRExport
+    MLIRBuiltinToLLVMIRTranslation
+    MLIRLLVMToLLVMIRTranslation
+    MLIRNVVMToLLVMIRTranslation
     MLIRLinalgDialect
     MLIRLinalgTransformOps
     MLIRLinalgTransforms
diff --git a/tile-reducer/tr-opt/tr-opt.cpp b/tile-reducer/tr-opt/tr-opt.cpp
index 139138de771d9..81612f9a57464 100644
--- a/tile-reducer/tr-opt/tr-opt.cpp
+++ b/tile-reducer/tr-opt/tr-opt.cpp
@@ -5,11 +5,23 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "mlir/Conversion/ArithToLLVM/ArithToLLVM.h"
+#include "mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h"
+#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
+#include "mlir/Conversion/GPUCommon/GPUToLLVM.h"
+#include "mlir/Conversion/GPUToNVVM/GPUToNVVM.h"
+#include "mlir/Conversion/IndexToLLVM/IndexToLLVM.h"
+#include "mlir/Conversion/MathToLLVM/MathToLLVM.h"
+#include "mlir/Conversion/MemRefToLLVM/MemRefToLLVM.h"
+#include "mlir/Conversion/NVVMToLLVM/NVVMToLLVM.h"
+#include "mlir/Conversion/UBToLLVM/UBToLLVM.h"
 #include "mlir/Dialect/Affine/IR/AffineOps.h"
 #include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/ControlFlow/IR/ControlFlow.h"
 #include "mlir/Dialect/Func/Extensions/InlinerExtension.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/Dialect/GPU/IR/GPUDialect.h"
+#include "mlir/Dialect/Index/IR/IndexDialect.h"
 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
 #include "mlir/Dialect/LLVMIR/NVVMDialect.h"
 #include "mlir/Dialect/Linalg/IR/Linalg.h"
@@ -20,6 +32,9 @@
 #include "mlir/Dialect/Transform/IR/TransformDialect.h"
 #include "mlir/Dialect/Transform/Transforms/Passes.h"
 #include "mlir/IR/MLIRContext.h"
+#include "mlir/Target/LLVMIR/Dialect/Builtin/BuiltinToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h"
+#include "mlir/Target/LLVMIR/Dialect/NVVM/NVVMToLLVMIRTranslation.h"
 #include "mlir/Tools/mlir-opt/MlirOptMain.h"
 
 #include "TileReducer/TileReducerDialect.h"
@@ -32,8 +47,9 @@ int main(int argc, char **argv) {
 
   mlir::DialectRegistry registry;
   registry.insert<mlir::tr::TileReducerDialect, mlir::affine::AffineDialect,
-                  mlir::arith::ArithDialect, mlir::func::FuncDialect,
-                  mlir::gpu::GPUDialect, mlir::LLVM::LLVMDialect,
+                  mlir::arith::ArithDialect, mlir::cf::ControlFlowDialect,
+                  mlir::func::FuncDialect, mlir::gpu::GPUDialect,
+                  mlir::index::IndexDialect, mlir::LLVM::LLVMDialect,
                   mlir::NVVM::NVVMDialect, mlir::linalg::LinalgDialect,
                   mlir::memref::MemRefDialect, mlir::scf::SCFDialect,
                   mlir::transform::TransformDialect>();
@@ -41,6 +57,19 @@ int main(int argc, char **argv) {
   mlir::linalg::registerTilingInterfaceExternalModels(registry);
   mlir::linalg::registerTransformDialectExtension(registry);
   mlir::tr::registerTransformDialectExtension(registry);
+  mlir::arith::registerConvertArithToLLVMInterface(registry);
+  mlir::cf::registerConvertControlFlowToLLVMInterface(registry);
+  mlir::registerConvertFuncToLLVMInterface(registry);
+  mlir::registerConvertMemRefToLLVMInterface(registry);
+  mlir::index::registerConvertIndexToLLVMInterface(registry);
+  mlir::NVVM::registerConvertGpuToNVVMInterface(registry);
+  mlir::registerConvertNVVMToLLVMInterface(registry);
+  mlir::registerConvertMathToLLVMInterface(registry);
+  mlir::ub::registerConvertUBToLLVMInterface(registry);
+  mlir::gpu::registerConvertGpuToLLVMInterface(registry);
+  mlir::registerBuiltinDialectTranslation(registry);
+  mlir::registerLLVMDialectTranslation(registry);
+  mlir::registerNVVMDialectTranslation(registry);
 
   return mlir::asMainReturnCode(
       mlir::MlirOptMain(argc, argv, "TileReducer optimizer driver\n", registry));



More information about the llvm-commits mailing list