[llvm-branch-commits] [mlir] [mlir][ODS] Add so-called "Natural Sharding" to ops (PR #239254)

Markus Böck via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Thu Nov 5 06:49:44 PST 2026


https://github.com/zero9178 created https://github.com/llvm/llvm-project/pull/239254

Prior to this PR, ODS had one mechanism for sharding which equally split a `<Dialect>Ops.cpp.inc` file into `n` many TUs, as requested on the command line (using preprocessor defines for selective enablement). The motivation for doing so is that this can speed up compile time by splitting class definition compilation to multiple translation units.

However, this approach has one large disadvantage: Since only the `<Dialect>Ops.cpp.inc` is split, the correpsonding `<Dialect>Ops.h.inc` is still included in each translation unit. For a large dialect like NVVM or LLVM this leads to **much higher** concurrent memory usage while compiling as every compilation process contains an in-memory copy of the header plus can lead to slower compilation time overall if too many shards are being used as overall work goes up (`n` header parses instead of 1).

This PR tries to address these issues by introducing a new kind of sharding called "natural sharding". The idea is that we split `<Dialect>Ops.cpp.inc` and `<Dialect>Ops.h.inc` along so called partitions. A new header can be created for every partition and every translation unit only contains the code from its partition. This means a TU no longer needs to include the entire dialect header but only the header from its partition. One can think of these as effectively being sub-dialects from the perspective of the required boilerplate.

We call it "Natural Sharding", as the partitions are defined by the dialect authors and are meant to be categories that naturally categorizes a dialects operations (e.g., Memory ops, control flow ops, arithmetic ops, intrinsic ops, etc. in the LLVM Dialect). The new `-op-partition` then filters output generation to just a given partition.

This PR introduces the mechanism and for testing, already exercises it on the test dialect. Users of `TestOps.h` were further changed to just include a given partition if deemed useful. Overall this yielded the following build gains vs the existing sharding, measured on a 16 thread machine (Release + assertions, 16 parallel jobs, median of 3 runs). "Users of `MLIRTestDialect`" are other TUs (unittests mainly) that include `MLIRTestDialect` headers. Total memory is the sum of the max RSS of every TU:

| TUs                        | Compiler | Wall time (s)       | CPU time (s)       | Total memory used during compilation (GiB) |
|----------------------------|----------|---------------------|--------------------|--------------------------------------------|
| `MLIRTestDialect`          | clang    | 49.9 -> 35.2 (-29%) | 710 -> 365 (-49%)  | 23.3 -> 11.1 (-52%)                        |
| `MLIRTestDialect`          | clang -g | 57.8 -> 43.1 (-25%) | 791 -> 427 (-46%)  | 25.0 -> 12.5 (-50%)                        |
| `MLIRTestDialect`          | gcc      | 58.6 -> 43.8 (-25%) | 740 -> 395 (-47%)  | 41.9 -> 19.4 (-54%)                        |
| `MLIRTestDialect`          | gcc -g   | 82.5 -> 61.5 (-25%) | 1059 -> 570 (-46%) | 52.9 -> 26.7 (-50%)                        |
| Users of `MLIRTestDialect` | clang    | 45.4 -> 35.1 (-23%) | 626 -> 472 (-25%)  | 27.6 -> 21.5 (-22%)                        |
| Users of `MLIRTestDialect` | clang -g | 46.6 -> 36.1 (-23%) | 644 -> 493 (-23%)  | 28.4 -> 22.3 (-21%)                        |
| Users of `MLIRTestDialect` | gcc      | 43.6 -> 33.9 (-22%) | 604 -> 449 (-26%)  | 44.5 -> 32.8 (-26%)                        |
| Users of `MLIRTestDialect` | gcc -g   | 60.9 -> 46.1 (-24%) | 859 -> 616 (-28%)  | 57.1 -> 42.4 (-26%)                        |

Future plan is to introduce this for types and attributes as well

>From be17f42296fb32d5b3fb1751a99d18453df824b8 Mon Sep 17 00:00:00 2001
From: Markus Boeck <mboeck at nvidia.com>
Date: Thu, 5 Nov 2026 12:33:43 +0000
Subject: [PATCH] [mlir][ODS] Add so-called "Natural Sharding" to ops

Prior to this PR, ODS had one mechanism for sharding which equally split a `<Dialect>Ops.cpp.inc` file into `n` many, as requested on the command line (using preprocessor defines for selective enablement).
The motivation for doing so is that this can speed up compile time by splitting class definition compilation to multiple translation units.

However, this approach has one large disadvantage: Since only the `<Dialect>Ops.cpp.inc` is split, the correpsonding `<Dialect>Ops.h.inc` is still included in each translation unit. For a large dialect like NVVM or LLVM this leads to **much higher** concurrent memory usage while compiling as every compilation process contains an in-memory copy of the header plus can lead to slower compilation time overall if too many shards are being used as overall work goes up (`n` header parses instead of 1).

This PR tries to address these issues by introducing a new kind of sharding called "natural sharding". The idea is that we split `<Dialect>Ops.cpp.inc` and `<Dialect>Ops.h.inc` along so called partitions. A new header can be created for every partition and every translation unit only contains the code from its partition. This means a TU no longer needs to include the entire dialect header but only the header from its partition.
One can think of these as effectively being sub-dialects from the perspective of the required boilerplate.

We call it "Natural Sharding", as the partitions are defined by the dialect authors and are meant to be categories that naturally categorizes a dialects operations (e.g., Memory ops, control flow ops, arithmetic ops, intrinsic ops, etc. in the LLVM Dialect). The new `-op-partition` then filters output generation to just a given partition.

This PR introduces the mechanism and for testing, already exercises it on the test dialect. Users of `TestOps.h` were further changed to just include a given partition if deemed useful.
Overall this yielded the following build gains vs the existing sharding, measured on a 16 thread machine (Release + assertions, 16 parallel jobs, median of 3 runs). "Users of `MLIRTestDialect`" are other TUs (unittests mainly) that include `MLIRTestDialect` headers. Total memory is the sum of the max RSS of every TU:

| TUs                        | Compiler | Wall time (s)       | CPU time (s)       | Total memory used during compilation (GiB) |
|----------------------------|----------|---------------------|--------------------|--------------------------------------------|
| `MLIRTestDialect`          | clang    | 49.9 -> 35.2 (-29%) | 710 -> 365 (-49%)  | 23.3 -> 11.1 (-52%)                        |
| `MLIRTestDialect`          | clang -g | 57.8 -> 43.1 (-25%) | 791 -> 427 (-46%)  | 25.0 -> 12.5 (-50%)                        |
| `MLIRTestDialect`          | gcc      | 58.6 -> 43.8 (-25%) | 740 -> 395 (-47%)  | 41.9 -> 19.4 (-54%)                        |
| `MLIRTestDialect`          | gcc -g   | 82.5 -> 61.5 (-25%) | 1059 -> 570 (-46%) | 52.9 -> 26.7 (-50%)                        |
| Users of `MLIRTestDialect` | clang    | 45.4 -> 35.1 (-23%) | 626 -> 472 (-25%)  | 27.6 -> 21.5 (-22%)                        |
| Users of `MLIRTestDialect` | clang -g | 46.6 -> 36.1 (-23%) | 644 -> 493 (-23%)  | 28.4 -> 22.3 (-21%)                        |
| Users of `MLIRTestDialect` | gcc      | 43.6 -> 33.9 (-22%) | 604 -> 449 (-26%)  | 44.5 -> 32.8 (-26%)                        |
| Users of `MLIRTestDialect` | gcc -g   | 60.9 -> 46.1 (-24%) | 859 -> 616 (-28%)  | 57.1 -> 42.4 (-26%)                        |

Future plan is to introduce this for types and attributes as well
---
 mlir/docs/DefiningDialects/Operations.md      | 104 +++++
 mlir/include/mlir/IR/DialectBase.td           |  33 ++
 mlir/include/mlir/IR/OpBase.td                |  24 ++
 mlir/include/mlir/TableGen/Dialect.h          |   5 +
 mlir/include/mlir/TableGen/Operator.h         |   3 +
 mlir/lib/TableGen/Dialect.cpp                 |   5 +
 mlir/lib/TableGen/Operator.cpp                |   5 +
 .../TestDenseBackwardDataFlowAnalysis.cpp     |   2 +-
 .../TestDenseForwardDataFlowAnalysis.cpp      |   3 +-
 .../FuncToLLVM/TestConvertCallOp.cpp          |   3 +-
 .../Dialect/Affine/TestReifyValueBounds.cpp   |   3 +-
 .../TestOneShotModuleBufferize.cpp            |   3 +-
 .../lib/Dialect/DLTI/TestDataLayoutQuery.cpp  |   2 +-
 .../Func/TestDecomposeCallGraphTypes.cpp      |   3 +-
 mlir/test/lib/Dialect/Test/CMakeLists.txt     |  21 +-
 mlir/test/lib/Dialect/Test/TestDialect.cpp    |   3 +-
 mlir/test/lib/Dialect/Test/TestDialect.td     |  20 +-
 .../Test/TestFromLLVMIRTranslation.cpp        |   3 +-
 mlir/test/lib/Dialect/Test/TestOps.h          | 250 +----------
 mlir/test/lib/Dialect/Test/TestOps.td         | 398 ++++++++++--------
 .../{TestOps.cpp => TestOpsAttributes.cpp}    |   9 +-
 .../test/lib/Dialect/Test/TestOpsAttributes.h |  17 +
 .../lib/Dialect/Test/TestOpsConversion.cpp    |  15 +
 .../test/lib/Dialect/Test/TestOpsConversion.h |  17 +
 mlir/test/lib/Dialect/Test/TestOpsCore.cpp    |  19 +
 mlir/test/lib/Dialect/Test/TestOpsCore.h      |  18 +
 .../lib/Dialect/Test/TestOpsInterfaces.cpp    |  16 +
 .../test/lib/Dialect/Test/TestOpsInterfaces.h |  90 ++++
 .../test/lib/Dialect/Test/TestOpsPatterns.cpp |  15 +
 mlir/test/lib/Dialect/Test/TestOpsPatterns.h  |  17 +
 .../lib/Dialect/Test/TestOpsProperties.cpp    |  16 +
 .../test/lib/Dialect/Test/TestOpsProperties.h | 154 +++++++
 mlir/test/lib/Dialect/Test/TestOpsSyntax.cpp  |  10 +-
 mlir/test/lib/Dialect/Test/TestOpsSyntax.td   |   6 +-
 mlir/test/lib/Dialect/Test/TestOpsTraits.cpp  |  15 +
 mlir/test/lib/Dialect/Test/TestOpsTraits.h    |  17 +
 .../Dialect/Test/TestToLLVMIRTranslation.cpp  |   3 +-
 mlir/test/lib/Dialect/Test/TestTraits.cpp     |   2 +-
 mlir/test/lib/IR/TestBytecodeRoundtrip.cpp    |   3 +-
 mlir/test/lib/IR/TestClone.cpp                |   2 +-
 mlir/test/lib/IR/TestLazyLoading.cpp          |   1 -
 mlir/test/lib/IR/TestRegions.cpp              |   1 -
 mlir/test/lib/IR/TestSideEffects.cpp          |   2 +-
 mlir/test/lib/IR/TestSymbolUses.cpp           |   2 +-
 mlir/test/lib/IR/TestTypes.cpp                |   1 -
 mlir/test/lib/IR/TestVisitorsGeneric.cpp      |   2 +-
 mlir/test/lib/Pass/TestPassManager.cpp        |   3 +-
 mlir/test/lib/Tools/PDLL/TestPDLL.cpp         |   3 +-
 mlir/test/lib/Transforms/TestInlining.cpp     |   3 +-
 .../lib/Transforms/TestInliningCallback.cpp   |   4 +-
 .../Transforms/TestMakeIsolatedFromAbove.cpp  |   3 +-
 mlir/test/mlir-tblgen/op-partitions-error.td  |  74 ++++
 mlir/test/mlir-tblgen/op-partitions.td        | 110 +++++
 mlir/tools/mlir-tblgen/DialectGen.cpp         |  25 ++
 mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp   |  70 ++-
 mlir/tools/mlir-tblgen/OpGenHelpers.cpp       |  79 ++++
 mlir/tools/mlir-tblgen/OpGenHelpers.h         |  26 +-
 mlir/unittests/IR/AdaptorTest.cpp             |   3 +-
 mlir/unittests/IR/IRMapping.cpp               |   3 +-
 mlir/unittests/IR/InterfaceAttachmentTest.cpp |   3 +-
 mlir/unittests/IR/InterfaceTest.cpp           |   3 +-
 mlir/unittests/IR/OperationSupportTest.cpp    |   3 +-
 mlir/unittests/IR/PatternMatchTest.cpp        |   3 +-
 mlir/unittests/IR/ValueTest.cpp               |   2 -
 .../Interfaces/MemorySlotUtilsTest.cpp        |   1 -
 mlir/unittests/TableGen/OpBuildGen.cpp        |   3 +-
 66 files changed, 1293 insertions(+), 494 deletions(-)
 rename mlir/test/lib/Dialect/Test/{TestOps.cpp => TestOpsAttributes.cpp} (65%)
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsAttributes.h
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsConversion.cpp
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsConversion.h
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsCore.cpp
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsCore.h
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsInterfaces.cpp
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsInterfaces.h
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsPatterns.cpp
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsPatterns.h
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsProperties.cpp
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsProperties.h
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsTraits.cpp
 create mode 100644 mlir/test/lib/Dialect/Test/TestOpsTraits.h
 create mode 100644 mlir/test/mlir-tblgen/op-partitions-error.td
 create mode 100644 mlir/test/mlir-tblgen/op-partitions.td

diff --git a/mlir/docs/DefiningDialects/Operations.md b/mlir/docs/DefiningDialects/Operations.md
index f991f5308c5ae4..7c0228772d2488 100644
--- a/mlir/docs/DefiningDialects/Operations.md
+++ b/mlir/docs/DefiningDialects/Operations.md
@@ -1370,6 +1370,110 @@ cc_library(
 )
 ```
 
+#### Natural Sharding with Op Partitions
+
+Sharding by index splits the ops arbitrarily: which shard an op ends up in
+depends on the number of shards and on the names of all other ops. As an
+alternative, a dialect can shard its ops "naturally" by grouping them into
+named *op partitions*, such as arithmetic, memory or control flow ops. Each
+partition is generated into its own declaration and definition files, almost as
+if it were a dialect of its own, but all ops are still registered in one
+dialect.
+
+Partitions are `Partition` records with a name, which must be a C++
+identifier. The dialect lists its partitions, and every op sets its `partition`
+to one of these records (a different record with the same name is rejected),
+typically with a `let` around a group of ops:
+
+```tablegen
+def MyDialect_ArithPartition : Partition<"Arith">;
+def MyDialect_MemoryPartition : Partition<"Memory">;
+
+def MyDialect : Dialect {
+  let name = "my_dialect";
+  let opPartitions = [MyDialect_ArithPartition, MyDialect_MemoryPartition];
+}
+
+let partition = MyDialect_ArithPartition in {
+def AddOp : MyDialect_Op<"add"> { ... }
+def MulOp : MyDialect_Op<"mul"> { ... }
+}
+
+def LoadOp : MyDialect_Op<"load"> {
+  let partition = MyDialect_MemoryPartition;
+  ...
+}
+```
+
+A dialect can also name one of its partitions as `defaultOpPartition`. Ops that
+do not set `partition` are then in this partition. This allows partitioning a
+dialect incrementally: initially all ops are in the default partition, and
+groups of ops can move to their own partitions one at a time:
+
+```tablegen
+def MyDialect : Dialect {
+  let name = "my_dialect";
+  let opPartitions = [MyDialect_CorePartition, MyDialect_MemoryPartition];
+  let defaultOpPartition = MyDialect_CorePartition;
+}
+
+// In partition `Core`.
+def AddOp : MyDialect_Op<"add"> { ... }
+```
+
+Passing `-op-partition=<partition>` with a partition name to `-gen-op-decls` and
+`-gen-op-defs` generates only the ops of that partition.
+
+Without `-op-partition`, `-gen-op-defs` generates all ops as before and
+additionally defines the registration hooks of all partitions in
+`GET_OP_CLASSES`. The hooks are private members of the dialect class, and the
+dialect registers the ops of all partitions by calling `registerOperations()`
+in its `initialize()`. A dialect can therefore declare its partitions and
+register its ops with `registerOperations()` first, and split its generated
+files by partition later.
+
+`mlir-tblgen` reports an error if a requested partition does not exist. A
+partition for which no definitions are compiled results in a link error for its
+hook.
+
+In CMake, generate and include the files of each partition:
+
+```cmake
+set(LLVM_TARGET_DEFINITIONS MyDialectOps.td)
+foreach(partition Arith Memory)
+  mlir_tablegen(MyDialect${partition}Ops.h.inc -gen-op-decls -op-partition=${partition})
+  mlir_tablegen(MyDialect${partition}Ops.cpp.inc -gen-op-defs -op-partition=${partition})
+endforeach()
+```
+
+Since the generated declarations of a partition forward declare the ops of all
+other partitions, each partition can get its own header, so that users only
+include the declarations of the ops they use:
+
+```c++
+// MyDialectArithOps.h
+#include "MyDialectBase.h" // The dialect, its attributes and types.
+
+#define GET_OP_CLASSES
+#include "MyDialectArithOps.h.inc"
+
+// MyDialect.h, for users that want all ops.
+#include "MyDialectArithOps.h"
+#include "MyDialectMemoryOps.h"
+
+// MyDialectArithOps.cpp, a natural home for the C++ implementations of the
+// arithmetic ops as well.
+#include "MyDialectArithOps.h"
+#include "OpUtils.h"
+
+#define GET_OP_CLASSES
+#include "MyDialectArithOps.cpp.inc"
+```
+
+As with index sharding, utilities shared by the generated op definitions must
+be declared in a header shared by the compilation units. A dialect with op
+partitions cannot use `-op-shard-count`.
+
 ## Constraints
 
 Constraint is a core concept in table-driven operation definition: operation
diff --git a/mlir/include/mlir/IR/DialectBase.td b/mlir/include/mlir/IR/DialectBase.td
index da669c6ada639f..92b6601b7e2877 100644
--- a/mlir/include/mlir/IR/DialectBase.td
+++ b/mlir/include/mlir/IR/DialectBase.td
@@ -19,6 +19,17 @@ include "mlir/IR/Utils.td"
 // Dialect definitions
 //===----------------------------------------------------------------------===//
 
+// A partition of the ops of a dialect, for "natural sharding" of the generated
+// op declarations and definitions. See `Dialect::opPartitions`.
+class Partition<string name> {
+  // The name of the partition, a C++ identifier. `-gen-op-decls` and
+  // `-gen-op-defs` select a partition by this name with `-op-partition=...`.
+  string partitionName = name;
+
+  assert !match(partitionName, "^[A-Za-z_][A-Za-z0-9_]*$"),
+         "op partition name '" # partitionName # "' is not a C++ identifier";
+}
+
 class Dialect {
   // The name of the dialect.
   string name = ?;
@@ -99,6 +110,28 @@ class Dialect {
 
   // If this dialect can be extended at runtime with new operations or types.
   bit isExtensible = 0;
+
+  // The op partitions of this dialect, enabling "natural sharding" of its op
+  // declarations and definitions (see `Op::partition`). When non-empty, every
+  // op of the dialect must be in one of these partitions.
+  list<Partition> opPartitions = [];
+
+  // Optional. The partition of the ops of this dialect that do not set their
+  // `partition`. Must be one of `opPartitions`. This allows partitioning the
+  // ops of a dialect incrementally: all ops start in the default partition and
+  // groups of ops can move to other partitions one at a time.
+  Partition defaultOpPartition = ?;
+
+  assert !if(!initialized(defaultOpPartition),
+             !not(!empty(!filter(p, opPartitions,
+                                 !eq(p, defaultOpPartition)))),
+             1),
+         "default op partition '" #
+         !if(!initialized(defaultOpPartition),
+             defaultOpPartition.partitionName # "' (record '" #
+             !cast<string>(defaultOpPartition), "") #
+         "') of dialect '" # name #
+         "' is not one of its `opPartitions`";
 }
 
 #endif // DIALECTBASE_TD
diff --git a/mlir/include/mlir/IR/OpBase.td b/mlir/include/mlir/IR/OpBase.td
index a130d5847a1c72..3357f83e922bba 100644
--- a/mlir/include/mlir/IR/OpBase.td
+++ b/mlir/include/mlir/IR/OpBase.td
@@ -351,6 +351,30 @@ class Op<Dialect dialect, string mnemonic, list<Trait> props = []> {
   // Optional. The group of ops this op is part of.
   OpDocGroup opDocGroup = ?;
 
+  // Optional. The partition of this op. A dialect that lists its partitions in
+  // `opPartitions` is "naturally sharded": every op of the dialect must be in
+  // one of the listed partitions, `-gen-op-decls`/`-gen-op-defs` can generate
+  // the ops of one partition at a time with `-op-partition=...` into separate
+  // files.
+  // Defaults to the dialect's `defaultOpPartition`. The partition must be one
+  // of the `opPartitions` records of the dialect.
+  Partition partition = dialect.defaultOpPartition;
+
+  assert !if(!initialized(partition),
+             !not(!empty(!filter(p, opDialect.opPartitions,
+                                 !eq(p, partition)))),
+             1),
+         "op '" # NAME # "' is in partition '" #
+         !if(!initialized(partition),
+             partition.partitionName # "' (record '" #
+             !cast<string>(partition), "") #
+         "'), which is not one of the `opPartitions` of dialect '" #
+         opDialect.name # "'";
+
+  assert !or(!initialized(partition), !empty(opDialect.opPartitions)),
+         "op '" # NAME # "' is in no partition, but dialect '" #
+         opDialect.name # "' has `opPartitions` and no `defaultOpPartition`";
+
   // Dag containing the arguments of the op. Default to 0 arguments.
   dag arguments = (ins);
 
diff --git a/mlir/include/mlir/TableGen/Dialect.h b/mlir/include/mlir/TableGen/Dialect.h
index 68230196b17cc0..7913360c294e48 100644
--- a/mlir/include/mlir/TableGen/Dialect.h
+++ b/mlir/include/mlir/TableGen/Dialect.h
@@ -94,6 +94,10 @@ class Dialect {
 
   const llvm::DagInit *getDiscardableAttributes() const;
 
+  /// Returns the names of the op partitions of this dialect, see
+  /// `Op::partition`. A dialect with op partitions is "naturally sharded".
+  ArrayRef<StringRef> getOpPartitions() const;
+
   const llvm::Record *getDef() const { return def; }
 
   // Returns whether two dialects are equal by checking the equality of the
@@ -112,6 +116,7 @@ class Dialect {
 private:
   const llvm::Record *def;
   std::vector<StringRef> dependentDialects;
+  std::vector<StringRef> opPartitions;
 };
 } // namespace tblgen
 } // namespace mlir
diff --git a/mlir/include/mlir/TableGen/Operator.h b/mlir/include/mlir/TableGen/Operator.h
index bb36c077708e92..cd321dcd6ca6f3 100644
--- a/mlir/include/mlir/TableGen/Operator.h
+++ b/mlir/include/mlir/TableGen/Operator.h
@@ -330,6 +330,9 @@ class Operator {
   /// Returns the dialect of the op.
   const Dialect &getDialect() const { return dialect; }
 
+  /// Returns the name of the op's partition, or an empty string if it has none.
+  StringRef getPartitionName() const;
+
   /// Prints the contents in this operator to the given `os`. This is used for
   /// debugging purposes.
   void print(llvm::raw_ostream &os) const;
diff --git a/mlir/lib/TableGen/Dialect.cpp b/mlir/lib/TableGen/Dialect.cpp
index 84530bfa4f6fd2..a9f9b49b663ead 100644
--- a/mlir/lib/TableGen/Dialect.cpp
+++ b/mlir/lib/TableGen/Dialect.cpp
@@ -21,6 +21,9 @@ Dialect::Dialect(const llvm::Record *def) : def(def) {
     return;
   for (StringRef dialect : def->getValueAsListOfStrings("dependentDialects"))
     dependentDialects.push_back(dialect);
+  for (const llvm::Record *partition :
+       def->getValueAsListOfDefs("opPartitions"))
+    opPartitions.push_back(partition->getValueAsString("partitionName"));
 }
 
 StringRef Dialect::getName() const { return def->getValueAsString("name"); }
@@ -110,6 +113,8 @@ const llvm::DagInit *Dialect::getDiscardableAttributes() const {
   return def->getValueAsDag("discardableAttrs");
 }
 
+ArrayRef<StringRef> Dialect::getOpPartitions() const { return opPartitions; }
+
 bool Dialect::operator==(const Dialect &other) const {
   return def == other.def;
 }
diff --git a/mlir/lib/TableGen/Operator.cpp b/mlir/lib/TableGen/Operator.cpp
index f01820bcf411c3..eb9bdb1b2b5e70 100644
--- a/mlir/lib/TableGen/Operator.cpp
+++ b/mlir/lib/TableGen/Operator.cpp
@@ -151,6 +151,11 @@ void Operator::assertInvariants() const {
 
 StringRef Operator::getDialectName() const { return dialect.getName(); }
 
+StringRef Operator::getPartitionName() const {
+  const llvm::Record *partition = def.getValueAsOptionalDef("partition");
+  return partition ? partition->getValueAsString("partitionName") : "";
+}
+
 StringRef Operator::getCppClassName() const { return cppClassName; }
 
 std::string Operator::getQualCppClassName() const {
diff --git a/mlir/test/lib/Analysis/DataFlow/TestDenseBackwardDataFlowAnalysis.cpp b/mlir/test/lib/Analysis/DataFlow/TestDenseBackwardDataFlowAnalysis.cpp
index f969869b924824..5bb7fbaaac6815 100644
--- a/mlir/test/lib/Analysis/DataFlow/TestDenseBackwardDataFlowAnalysis.cpp
+++ b/mlir/test/lib/Analysis/DataFlow/TestDenseBackwardDataFlowAnalysis.cpp
@@ -11,7 +11,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "TestDenseDataFlowAnalysis.h"
-#include "TestOps.h"
+#include "TestOpsInterfaces.h"
 #include "mlir/Analysis/DataFlow/DenseAnalysis.h"
 #include "mlir/Analysis/DataFlow/Utils.h"
 #include "mlir/Analysis/DataFlowFramework.h"
diff --git a/mlir/test/lib/Analysis/DataFlow/TestDenseForwardDataFlowAnalysis.cpp b/mlir/test/lib/Analysis/DataFlow/TestDenseForwardDataFlowAnalysis.cpp
index c8b67b4ba61c00..725daef9d08e3e 100644
--- a/mlir/test/lib/Analysis/DataFlow/TestDenseForwardDataFlowAnalysis.cpp
+++ b/mlir/test/lib/Analysis/DataFlow/TestDenseForwardDataFlowAnalysis.cpp
@@ -11,8 +11,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "TestDenseDataFlowAnalysis.h"
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsInterfaces.h"
 #include "mlir/Analysis/DataFlow/DenseAnalysis.h"
 #include "mlir/Analysis/DataFlow/Utils.h"
 #include "mlir/Interfaces/SideEffectInterfaces.h"
diff --git a/mlir/test/lib/Conversion/FuncToLLVM/TestConvertCallOp.cpp b/mlir/test/lib/Conversion/FuncToLLVM/TestConvertCallOp.cpp
index 3b29867cc32631..89e02814950fd8 100644
--- a/mlir/test/lib/Conversion/FuncToLLVM/TestConvertCallOp.cpp
+++ b/mlir/test/lib/Conversion/FuncToLLVM/TestConvertCallOp.cpp
@@ -6,8 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsConversion.h"
 #include "TestTypes.h"
 #include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h"
 #include "mlir/Conversion/LLVMCommon/Pattern.h"
diff --git a/mlir/test/lib/Dialect/Affine/TestReifyValueBounds.cpp b/mlir/test/lib/Dialect/Affine/TestReifyValueBounds.cpp
index f11c14bc09fb66..efd8ee7a8ebf3f 100644
--- a/mlir/test/lib/Dialect/Affine/TestReifyValueBounds.cpp
+++ b/mlir/test/lib/Dialect/Affine/TestReifyValueBounds.cpp
@@ -6,8 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsInterfaces.h"
 #include "mlir/Dialect/Affine/IR/AffineOps.h"
 #include "mlir/Dialect/Affine/IR/ValueBoundsOpInterfaceImpl.h"
 #include "mlir/Dialect/Affine/Transforms/Transforms.h"
diff --git a/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp b/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
index d9f50ba0ee1ff4..634469278fa847 100644
--- a/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
+++ b/mlir/test/lib/Dialect/Bufferization/TestOneShotModuleBufferize.cpp
@@ -15,8 +15,7 @@
 #include "mlir/Pass/Pass.h"
 
 #include "TestAttributes.h" // TestTensorEncodingAttr, TestMemRefLayoutAttr
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsInterfaces.h"
 
 #include "llvm/ADT/TypeSwitch.h"
 
diff --git a/mlir/test/lib/Dialect/DLTI/TestDataLayoutQuery.cpp b/mlir/test/lib/Dialect/DLTI/TestDataLayoutQuery.cpp
index 9fb89d3b4528b0..d0ca7fa5c2506f 100644
--- a/mlir/test/lib/Dialect/DLTI/TestDataLayoutQuery.cpp
+++ b/mlir/test/lib/Dialect/DLTI/TestDataLayoutQuery.cpp
@@ -6,7 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestOps.h"
+#include "TestOpsInterfaces.h"
 #include "mlir/Analysis/DataLayoutAnalysis.h"
 #include "mlir/Dialect/DLTI/DLTI.h"
 #include "mlir/IR/BuiltinAttributes.h"
diff --git a/mlir/test/lib/Dialect/Func/TestDecomposeCallGraphTypes.cpp b/mlir/test/lib/Dialect/Func/TestDecomposeCallGraphTypes.cpp
index c67bcd94ea0bd6..0f789a8c822e21 100644
--- a/mlir/test/lib/Dialect/Func/TestDecomposeCallGraphTypes.cpp
+++ b/mlir/test/lib/Dialect/Func/TestDecomposeCallGraphTypes.cpp
@@ -6,8 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsInterfaces.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/Dialect/Func/Transforms/FuncConversions.h"
 #include "mlir/IR/Builders.h"
diff --git a/mlir/test/lib/Dialect/Test/CMakeLists.txt b/mlir/test/lib/Dialect/Test/CMakeLists.txt
index ca0024b8434e16..d2dab9e88304fd 100644
--- a/mlir/test/lib/Dialect/Test/CMakeLists.txt
+++ b/mlir/test/lib/Dialect/Test/CMakeLists.txt
@@ -34,15 +34,18 @@ set(LLVM_TARGET_DEFINITIONS TestOps.td)
 mlir_tablegen(TestOpsDialect.h.inc -gen-dialect-decls -dialect=test)
 mlir_tablegen(TestOpsDialect.cpp.inc -gen-dialect-defs -dialect=test)
 mlir_tablegen(TestPatterns.inc -gen-rewriters)
+# The op partitions of TestOps.td, each with its own header and source file.
+foreach(partition Core Attributes Traits Patterns Conversion Interfaces Properties)
+  mlir_tablegen(TestOps${partition}.h.inc -gen-op-decls -op-partition=${partition})
+  mlir_tablegen(TestOps${partition}.cpp.inc -gen-op-defs -op-partition=${partition})
+endforeach()
 add_public_tablegen_target(MLIRTestOpsIncGen)
 
 set(LLVM_TARGET_DEFINITIONS TestOpsSyntax.td)
-mlir_tablegen(TestOpsSyntax.h.inc -gen-op-decls)
-mlir_tablegen(TestOpsSyntax.cpp.inc -gen-op-defs)
+mlir_tablegen(TestOpsSyntax.h.inc -gen-op-decls -op-partition=Syntax)
+mlir_tablegen(TestOpsSyntax.cpp.inc -gen-op-defs -op-partition=Syntax)
 add_public_tablegen_target(MLIRTestOpsSyntaxIncGen)
 
-add_sharded_ops(TestOps 20)
-
 # Exclude tests from libMLIR.so
 add_mlir_library(MLIRTestDialect
   TestAttributes.cpp
@@ -50,13 +53,18 @@ add_mlir_library(MLIRTestDialect
   TestFormatUtils.cpp
   TestInterfaces.cpp
   TestOpDefs.cpp
-  TestOps.cpp
+  TestOpsAttributes.cpp
+  TestOpsConversion.cpp
+  TestOpsCore.cpp
+  TestOpsInterfaces.cpp
+  TestOpsPatterns.cpp
+  TestOpsProperties.cpp
+  TestOpsTraits.cpp
   TestPatterns.cpp
   TestTraits.cpp
   TestTypes.cpp
   TestOpsSyntax.cpp
   TestDialectInterfaces.cpp
-  ${SHARDED_SRCS}
 
   EXCLUDE_FROM_LIBMLIR
 
@@ -67,7 +75,6 @@ add_mlir_library(MLIRTestDialect
   MLIRTestTypeDefIncGen
   MLIRTestOpsIncGen
   MLIRTestOpsSyntaxIncGen
-  MLIRTestOpsShardGen
   MLIRConvertToEmitCPatternInterfaceIncGen
   )
 mlir_target_link_libraries(MLIRTestDialect PUBLIC
diff --git a/mlir/test/lib/Dialect/Test/TestDialect.cpp b/mlir/test/lib/Dialect/Test/TestDialect.cpp
index 57bba2e5749a86..657f25771a45ee 100644
--- a/mlir/test/lib/Dialect/Test/TestDialect.cpp
+++ b/mlir/test/lib/Dialect/Test/TestDialect.cpp
@@ -346,9 +346,8 @@ struct TestOpEffectInterfaceFallback
 void TestDialect::initialize() {
   registerAttributes();
   registerTypes();
-  registerOpsSyntax();
   addOperations<ManualCppOpWithFold>();
-  registerTestDialectOperations(this);
+  registerOperations();
   registerDynamicOp(getDynamicGenericOp(this));
   registerDynamicOp(getDynamicTerminatorOp(this));
   registerDynamicOp(getDynamicNoTerminatorOp(this));
diff --git a/mlir/test/lib/Dialect/Test/TestDialect.td b/mlir/test/lib/Dialect/Test/TestDialect.td
index 37a263f1d10b8b..debb239addc056 100644
--- a/mlir/test/lib/Dialect/Test/TestDialect.td
+++ b/mlir/test/lib/Dialect/Test/TestDialect.td
@@ -11,6 +11,19 @@
 
 include "mlir/IR/OpBase.td"
 
+// Op partitions, each generated and compiled separately. Ops from TestOps.td
+// are in `Core` unless a `let` block or their base class picks another
+// partition. All ops from TestOpsSyntax.td are in `Syntax`, which is generated
+// from that file.
+def Test_CorePartition : Partition<"Core">;
+def Test_AttributesPartition : Partition<"Attributes">;
+def Test_TraitsPartition : Partition<"Traits">;
+def Test_PatternsPartition : Partition<"Patterns">;
+def Test_ConversionPartition : Partition<"Conversion">;
+def Test_InterfacesPartition : Partition<"Interfaces">;
+def Test_PropertiesPartition : Partition<"Properties">;
+def Test_SyntaxPartition : Partition<"Syntax">;
+
 def Test_Dialect : Dialect {
   let name = "test";
   let cppNamespace = "::test";
@@ -24,6 +37,12 @@ def Test_Dialect : Dialect {
   let useDefaultTypePrinterParser = 0;
   let useDefaultAttributePrinterParser = 1;
   let isExtensible = 1;
+  let opPartitions = [
+    Test_CorePartition, Test_AttributesPartition, Test_TraitsPartition,
+    Test_PatternsPartition, Test_ConversionPartition, Test_InterfacesPartition,
+    Test_PropertiesPartition, Test_SyntaxPartition
+  ];
+  let defaultOpPartition = Test_CorePartition;
   let dependentDialects = [
     "::mlir::DLTIDialect",
     "::mlir::bufferization::BufferizationDialect"
@@ -37,7 +56,6 @@ def Test_Dialect : Dialect {
     void registerAttributes();
     void registerInterfaces();
     void registerTypes();
-    void registerOpsSyntax();
 
     // Provides a custom printing/parsing for some operations.
     ::std::optional<ParseOpHook>
diff --git a/mlir/test/lib/Dialect/Test/TestFromLLVMIRTranslation.cpp b/mlir/test/lib/Dialect/Test/TestFromLLVMIRTranslation.cpp
index b98f6ce32cdceb..c1f8629c65df42 100644
--- a/mlir/test/lib/Dialect/Test/TestFromLLVMIRTranslation.cpp
+++ b/mlir/test/lib/Dialect/Test/TestFromLLVMIRTranslation.cpp
@@ -10,8 +10,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsTraits.h"
 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
 #include "mlir/IR/Builders.h"
 #include "mlir/IR/BuiltinAttributes.h"
diff --git a/mlir/test/lib/Dialect/Test/TestOps.h b/mlir/test/lib/Dialect/Test/TestOps.h
index 5fcee322e9e2e6..8862e81a03c79d 100644
--- a/mlir/test/lib/Dialect/Test/TestOps.h
+++ b/mlir/test/lib/Dialect/Test/TestOps.h
@@ -5,247 +5,21 @@
 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 //
 //===----------------------------------------------------------------------===//
+//
+// Declares all ops of TestOps.td. Each op partition has its own header, which
+// declares the ops of that partition and forward declares the others.
+//
+//===----------------------------------------------------------------------===//
 
 #ifndef MLIR_TESTOPS_H
 #define MLIR_TESTOPS_H
 
-#include "TestAttributes.h"
-#include "TestTypes.h"
-#include "mlir/Bytecode/BytecodeImplementation.h"
-#include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
-#include "mlir/Dialect/DLTI/DLTI.h"
-#include "mlir/Dialect/DLTI/Traits.h"
-#include "mlir/Dialect/Func/IR/FuncOps.h"
-#include "mlir/Dialect/LLVMIR/NVVMRequiresSMTraits.h"
-#include "mlir/Dialect/Linalg/IR/Linalg.h"
-#include "mlir/Dialect/Linalg/IR/LinalgInterfaces.h"
-#include "mlir/Dialect/Traits.h"
-#include "mlir/IR/AsmState.h"
-#include "mlir/IR/BuiltinOps.h"
-#include "mlir/IR/BuiltinTypes.h"
-#include "mlir/IR/Dialect.h"
-#include "mlir/IR/DialectResourceBlobManager.h"
-#include "mlir/IR/ExtensibleDialect.h"
-#include "mlir/IR/OpImplementation.h"
-#include "mlir/IR/RegionKindInterface.h"
-#include "mlir/IR/SymbolTable.h"
-#include "mlir/Interfaces/CallInterfaces.h"
-#include "mlir/Interfaces/ControlFlowInterfaces.h"
-#include "mlir/Interfaces/InferIntRangeInterface.h"
-#include "mlir/Interfaces/InferTypeOpInterface.h"
-#include "mlir/Interfaces/LoopLikeInterface.h"
-#include "mlir/Interfaces/MemorySlotInterfaces.h"
-#include "mlir/Interfaces/SideEffectInterfaces.h"
-#include "mlir/Interfaces/ValueBoundsOpInterface.h"
-#include "mlir/Interfaces/ViewLikeInterface.h"
-#include "llvm/ADT/SetVector.h"
-#include "llvm/ADT/SmallVector.h"
-#include <optional>
-
-namespace test {
-// Keep this type distinct from SmallVector<int32_t>, which another test parser
-// uses with the generic FieldParser specialization in a separate translation
-// unit.
-struct KeyValueSpecializedList : llvm::SmallVector<int32_t> {
-  using llvm::SmallVector<int32_t>::SmallVector;
-};
-} // namespace test
-
-namespace mlir {
-// Self-delimiting full specializations remain usable in a keyed prop-dict even
-// when their storage type is optional or container-like.
-template <>
-struct FieldParser<test::KeyValueSpecializedList> {
-  static FailureOr<test::KeyValueSpecializedList> parse(AsmParser &parser) {
-    test::KeyValueSpecializedList values;
-    if (parser.parseCommaSeparatedList(AsmParser::Delimiter::Square, [&]() {
-          int32_t value;
-          if (parser.parseInteger(value))
-            return failure();
-          values.push_back(value);
-          return success();
-        }))
-      return failure();
-    return values;
-  }
-};
-
-template <>
-struct FieldParser<std::optional<int16_t>> {
-  static FailureOr<std::optional<int16_t>> parse(AsmParser &parser) {
-    if (succeeded(parser.parseOptionalKeyword("none")))
-      return std::optional<int16_t>{};
-    int16_t value;
-    if (parser.parseKeyword("some") || parser.parseLess() ||
-        parser.parseInteger(value) || parser.parseGreater())
-      return failure();
-    return std::optional<int16_t>{value};
-  }
-};
-} // namespace mlir
-
-namespace test {
-class TestDialect;
-
-//===----------------------------------------------------------------------===//
-// TestResource
-//===----------------------------------------------------------------------===//
-
-/// A test resource for side effects (under DefaultResource).
-struct TestResource : public mlir::SideEffects::Resource::Base<
-                          TestResource, mlir::SideEffects::DefaultResource> {
-  llvm::StringRef getName() const final { return "<Test>"; }
-  mlir::SideEffects::Resource *getParent() const override {
-    return mlir::SideEffects::DefaultResource::get();
-  }
-};
-
-/// A test resource that is a root (disjoint from DefaultResource).
-struct TestNonAddressableResource
-    : public mlir::SideEffects::Resource::Base<TestNonAddressableResource> {
-  llvm::StringRef getName() const final { return "<TestNonAddressable>"; }
-  bool isAddressable() const override { return false; }
-};
-
-/// Two disjoint sub-resources (roots) for testing sibling disjointness.
-struct TestNonAddressableSubResourceA
-    : public mlir::SideEffects::Resource::Base<TestNonAddressableSubResourceA> {
-  TestNonAddressableSubResourceA() = default;
-  llvm::StringRef getName() const override {
-    return "TestNonAddressableSubResourceA";
-  }
-  bool isAddressable() const override { return false; }
-
-protected:
-  TestNonAddressableSubResourceA(mlir::TypeID id) : Base(id) {}
-};
-
-struct TestNonAddressableSubResourceB
-    : public mlir::SideEffects::Resource::Base<TestNonAddressableSubResourceB> {
-  TestNonAddressableSubResourceB() = default;
-  llvm::StringRef getName() const override {
-    return "TestNonAddressableSubResourceB";
-  }
-  bool isAddressable() const override { return false; }
-
-protected:
-  TestNonAddressableSubResourceB(mlir::TypeID id) : Base(id) {}
-};
-
-struct TestNonAddressableResourceA
-    : public mlir::SideEffects::Resource::Base<TestNonAddressableResourceA,
-                                               TestNonAddressableSubResourceA> {
-  llvm::StringRef getName() const final { return "<TestNonAddressableA>"; }
-  bool isAddressable() const override { return false; }
-  mlir::SideEffects::Resource *getParent() const override {
-    return TestNonAddressableSubResourceA::get();
-  }
-};
-
-struct TestNonAddressableResourceB
-    : public mlir::SideEffects::Resource::Base<TestNonAddressableResourceB,
-                                               TestNonAddressableSubResourceB> {
-  llvm::StringRef getName() const final { return "<TestNonAddressableB>"; }
-  bool isAddressable() const override { return false; }
-  mlir::SideEffects::Resource *getParent() const override {
-    return TestNonAddressableSubResourceB::get();
-  }
-};
-
-//===----------------------------------------------------------------------===//
-// PropertiesWithCustomPrint
-//===----------------------------------------------------------------------===//
-
-struct PropertiesWithCustomPrint {
-  /// A shared_ptr to a const object is safe: it is equivalent to a value-based
-  /// member. Here the label will be deallocated when the last operation
-  /// refering to it is destroyed. However there is no pool-allocation: this is
-  /// offloaded to the client.
-  std::shared_ptr<const std::string> label;
-  int value;
-  bool operator==(const PropertiesWithCustomPrint &rhs) const {
-    return value == rhs.value && *label == *rhs.label;
-  }
-};
-
-llvm::LogicalResult setPropertiesFromAttribute(
-    PropertiesWithCustomPrint &prop, mlir::Attribute attr,
-    llvm::function_ref<mlir::InFlightDiagnostic()> emitError);
-mlir::DictionaryAttr
-getPropertiesAsAttribute(mlir::MLIRContext *ctx,
-                         const PropertiesWithCustomPrint &prop);
-llvm::hash_code computeHash(const PropertiesWithCustomPrint &prop);
-void customPrintProperties(mlir::OpAsmPrinter &p,
-                           const PropertiesWithCustomPrint &prop);
-mlir::ParseResult customParseProperties(mlir::OpAsmParser &parser,
-                                        PropertiesWithCustomPrint &prop);
-
-//===----------------------------------------------------------------------===//
-// MyPropStruct
-//===----------------------------------------------------------------------===//
-namespace test_properties {
-class MyPropStruct {
-public:
-  std::string content;
-  // These three methods are invoked through the  `MyStructProperty` wrapper
-  // defined in TestOps.td
-  mlir::Attribute asAttribute(mlir::MLIRContext *ctx) const;
-  static llvm::LogicalResult
-  setFromAttr(MyPropStruct &prop, mlir::Attribute attr,
-              llvm::function_ref<mlir::InFlightDiagnostic()> emitError);
-  llvm::hash_code hash() const;
-  bool operator==(const MyPropStruct &rhs) const {
-    return content == rhs.content;
-  }
-};
-inline llvm::hash_code hash_value(const MyPropStruct &S) { return S.hash(); }
-} // namespace test_properties
-using test_properties::MyPropStruct;
-
-llvm::LogicalResult readFromMlirBytecode(mlir::DialectBytecodeReader &reader,
-                                         MyPropStruct &prop);
-void writeToMlirBytecode(mlir::DialectBytecodeWriter &writer,
-                         MyPropStruct &prop);
-
-//===----------------------------------------------------------------------===//
-// VersionedProperties
-//===----------------------------------------------------------------------===//
-
-struct VersionedProperties {
-  // For the sake of testing, assume that this object was associated to version
-  // 1.2 of the test dialect when having only one int value. In the current
-  // version 2.0, the property has two values. We also assume that the class is
-  // upgrade-able if value2 = 0.
-  int value1;
-  int value2;
-  bool operator==(const VersionedProperties &rhs) const {
-    return value1 == rhs.value1 && value2 == rhs.value2;
-  }
-};
-
-llvm::LogicalResult setPropertiesFromAttribute(
-    VersionedProperties &prop, mlir::Attribute attr,
-    llvm::function_ref<mlir::InFlightDiagnostic()> emitError);
-mlir::DictionaryAttr getPropertiesAsAttribute(mlir::MLIRContext *ctx,
-                                              const VersionedProperties &prop);
-llvm::hash_code computeHash(const VersionedProperties &prop);
-void customPrintProperties(mlir::OpAsmPrinter &p,
-                           const VersionedProperties &prop);
-mlir::ParseResult customParseProperties(mlir::OpAsmParser &parser,
-                                        VersionedProperties &prop);
-
-//===----------------------------------------------------------------------===//
-// Bytecode Support
-//===----------------------------------------------------------------------===//
-
-llvm::LogicalResult readFromMlirBytecode(mlir::DialectBytecodeReader &reader,
-                                         llvm::MutableArrayRef<int64_t> prop);
-void writeToMlirBytecode(mlir::DialectBytecodeWriter &writer,
-                         llvm::ArrayRef<int64_t> prop);
-
-} // namespace test
-
-#define GET_OP_CLASSES
-#include "TestOps.h.inc"
+#include "TestOpsAttributes.h"
+#include "TestOpsConversion.h"
+#include "TestOpsCore.h"
+#include "TestOpsInterfaces.h"
+#include "TestOpsPatterns.h"
+#include "TestOpsProperties.h"
+#include "TestOpsTraits.h"
 
 #endif // MLIR_TESTOPS_H
diff --git a/mlir/test/lib/Dialect/Test/TestOps.td b/mlir/test/lib/Dialect/Test/TestOps.td
index 1790963e4f2edd..66b500ca0bed0d 100644
--- a/mlir/test/lib/Dialect/Test/TestOps.td
+++ b/mlir/test/lib/Dialect/Test/TestOps.td
@@ -45,6 +45,24 @@ include "TestTypeDefs.td"
 class TEST_Op<string mnemonic, list<Trait> traits = []> :
     Op<Test_Dialect, mnemonic, traits>;
 
+// Ops are in the dialect's default partition (`Core`), unless they are in a
+// `let partition = ... in { ... }` block. Since TableGen rejects `let` of a
+// field that a record does not have, such blocks cannot contain non-op records
+// like patterns. The sections that interleave ops and other records use these
+// base classes instead.
+class TEST_AttrOp<string mnemonic, list<Trait> traits = []> :
+    TEST_Op<mnemonic, traits> {
+  let partition = Test_AttributesPartition;
+}
+class TEST_PatternOp<string mnemonic, list<Trait> traits = []> :
+    TEST_Op<mnemonic, traits> {
+  let partition = Test_PatternsPartition;
+}
+class TEST_PropOp<string mnemonic, list<Trait> traits = []> :
+    TEST_Op<mnemonic, traits> {
+  let partition = Test_PropertiesPartition;
+}
+
 //===----------------------------------------------------------------------===//
 // Test Types
 //===----------------------------------------------------------------------===//
@@ -256,45 +274,46 @@ def MixedNormalVariadicResults : TEST_Op<
 // Test Attributes
 //===----------------------------------------------------------------------===//
 
-def AnyAttrOfOp : TEST_Op<"any_attr_of_i32_str"> {
+def AnyAttrOfOp : TEST_AttrOp<"any_attr_of_i32_str"> {
   let arguments = (ins AnyAttrOf<[I32Attr, StrAttr]>:$attr);
 }
 
-def NonNegIntAttrOp : TEST_Op<"non_negative_int_attr"> {
+def NonNegIntAttrOp : TEST_AttrOp<"non_negative_int_attr"> {
   let arguments = (ins
       ConfinedAttr<I32Attr, [IntNonNegative]>:$i32attr,
       ConfinedAttr<I64Attr, [IntNonNegative]>:$i64attr
   );
 }
 
-def PositiveIntAttrOp : TEST_Op<"positive_int_attr"> {
+def PositiveIntAttrOp : TEST_AttrOp<"positive_int_attr"> {
   let arguments = (ins
       ConfinedAttr<I32Attr, [IntPositive]>:$i32attr,
       ConfinedAttr<I64Attr, [IntPositive]>:$i64attr
   );
 }
 
-def TypeArrayAttrOp : TEST_Op<"type_array_attr"> {
+def TypeArrayAttrOp : TEST_AttrOp<"type_array_attr"> {
   let arguments = (ins TypeArrayAttr:$attr);
 }
 
-def TypeArrayAttrWithDefaultOp : TEST_Op<"type_array_attr_with_default"> {
+def TypeArrayAttrWithDefaultOp : TEST_AttrOp<"type_array_attr_with_default"> {
   let arguments = (ins DefaultValuedAttr<TypeArrayAttr, "{}">:$attr);
 }
 
-def TypedStringAttrWithTypeOp : TEST_Op<"string_attr_with_type"> {
+def TypedStringAttrWithTypeOp : TEST_AttrOp<"string_attr_with_type"> {
   let arguments = (ins TypedStrAttr<AnyInteger>:$attr);
   let assemblyFormat = "$attr attr-dict";
 }
 
-def TypedStringAttrWithMixedTypeOp : TEST_Op<"string_attr_with_mixed_type"> {
+def TypedStringAttrWithMixedTypeOp :
+    TEST_AttrOp<"string_attr_with_mixed_type"> {
   let arguments = (ins
     AnyAttrOf<[TypedStrAttr<AnyInteger>, I64Attr]>:$attr
   );
   let assemblyFormat = "$attr attr-dict";
 }
 
-def FloatAttrOp : TEST_Op<"float_attrs"> {
+def FloatAttrOp : TEST_AttrOp<"float_attrs"> {
   // TODO: Clean up the OpBase float type and attribute selectors so they
   // can express all of the types.
   let arguments = (ins
@@ -302,17 +321,17 @@ def FloatAttrOp : TEST_Op<"float_attrs"> {
   );
 }
 
-def I32EnumAttrOp : TEST_Op<"i32_enum_attr"> {
+def I32EnumAttrOp : TEST_AttrOp<"i32_enum_attr"> {
   let arguments = (ins SomeI32Enum:$attr);
   let results = (outs I32:$val);
 }
 
-def I64EnumAttrOp : TEST_Op<"i64_enum_attr"> {
+def I64EnumAttrOp : TEST_AttrOp<"i64_enum_attr"> {
   let arguments = (ins SomeI64Enum:$attr);
   let results = (outs I32:$val);
 }
 
-def IntAttrOp : TEST_Op<"int_attrs"> {
+def IntAttrOp : TEST_AttrOp<"int_attrs"> {
   let arguments = (ins
     AnyI32Attr:$any_i32_attr,
     IndexAttr:$index_attr,
@@ -321,7 +340,7 @@ def IntAttrOp : TEST_Op<"int_attrs"> {
   );
 }
 
-def FloatElementsAttrOp : TEST_Op<"float_elements_attr"> {
+def FloatElementsAttrOp : TEST_AttrOp<"float_elements_attr"> {
   let arguments = (ins
       RankedF32ElementsAttr<[2]>:$scalar_f32_attr,
       RankedF64ElementsAttr<[4, 8]>:$tensor_f64_attr
@@ -338,21 +357,21 @@ def UpdateFloatElementsAttr : Pat<
     ConstantAttr<RankedF32ElementsAttr<[2]>, "{5.0f, 6.0f}">:$f32attr,
     $f64attr)>;
 
-def IntElementsAttrOp : TEST_Op<"int_elements_attr"> {
+def IntElementsAttrOp : TEST_AttrOp<"int_elements_attr"> {
   let arguments = (ins
       AnyI32ElementsAttr:$any_i32_attr,
       I32ElementsAttr:$i32_attr
   );
 }
 
-def RankedIntElementsAttrOp : TEST_Op<"ranked_int_elements_attr"> {
+def RankedIntElementsAttrOp : TEST_AttrOp<"ranked_int_elements_attr"> {
   let arguments = (ins
       RankedI32ElementsAttr<[2]>:$vector_i32_attr,
       RankedI64ElementsAttr<[4, 8]>:$matrix_i64_attr
   );
 }
 
-def DerivedTypeAttrOp : TEST_Op<"derived_type_attr", []> {
+def DerivedTypeAttrOp : TEST_AttrOp<"derived_type_attr", []> {
   let results = (outs AnyTensor:$output);
   DerivedTypeAttr element_dtype =
     DerivedTypeAttr<"return getElementTypeOrSelf(getOutput().getType());">;
@@ -361,7 +380,7 @@ def DerivedTypeAttrOp : TEST_Op<"derived_type_attr", []> {
     "$_builder.getI32IntegerAttr($_self)">;
 }
 
-def TestPropOp : TEST_Op<"prop">,
+def TestPropOp : TEST_AttrOp<"prop">,
   Arguments<(ins Variadic<Index>:$upperInits,
       I32ElementsAttr:$transforms)>,
   Results<(outs Variadic<AnyType>:$results)> {
@@ -371,27 +390,27 @@ def TestPropOp : TEST_Op<"prop">,
 }
 
 
-def StringElementsAttrOp : TEST_Op<"string_elements_attr"> {
+def StringElementsAttrOp : TEST_AttrOp<"string_elements_attr"> {
   let arguments = (ins
       StringElementsAttr:$scalar_string_attr
   );
 }
 
-def TypedAttrOp : TEST_Op<"typed_attr"> {
+def TypedAttrOp : TEST_AttrOp<"typed_attr"> {
   let arguments = (ins TypeAttr:$type, AnyAttr:$attr);
   let assemblyFormat = [{
     attr-dict $type `=` custom<AttrElideType>(ref($type), $attr)
   }];
 }
 
-def TypeAttrOfOp : TEST_Op<"type_attr_of"> {
+def TypeAttrOfOp : TEST_AttrOp<"type_attr_of"> {
   let arguments = (ins TypeAttrOf<I64>:$type);
   let assemblyFormat = [{
     attr-dict $type
   }];
 }
 
-def DenseArrayAttrOp : TEST_Op<"dense_array_attr"> {
+def DenseArrayAttrOp : TEST_AttrOp<"dense_array_attr"> {
   let arguments = (ins
     DenseBoolArrayAttr:$i1attr,
     DenseI8ArrayAttr:$i8attr,
@@ -409,7 +428,7 @@ def DenseArrayAttrOp : TEST_Op<"dense_array_attr"> {
   }];
 }
 
-def SlashAttrOp : TEST_Op<"slash_attr"> {
+def SlashAttrOp : TEST_AttrOp<"slash_attr"> {
   let arguments = (ins SlashAttr:$attr);
 }
 
@@ -417,7 +436,7 @@ def SlashAttrOp : TEST_Op<"slash_attr"> {
 // Test Attributes Constraints
 //===----------------------------------------------------------------------===//
 
-def ConfinedDenseArrayAttrOp : TEST_Op<"confined_dense_array_attr"> {
+def ConfinedDenseArrayAttrOp : TEST_AttrOp<"confined_dense_array_attr"> {
   let arguments = (ins
       ConfinedAttr<DenseI16ArrayAttr,
                    [DenseArrayStrictlySorted<DenseI16ArrayAttr>]>:$emptyattr,
@@ -429,7 +448,7 @@ def ConfinedDenseArrayAttrOp : TEST_Op<"confined_dense_array_attr"> {
 }
 
 // It does not make sense to have this constraint on a DenseBoolArrayAttr.
-def DenseArrayStrictlyPositiveAttrOp : TEST_Op<"confined_strictly_positive_attr"> {
+def DenseArrayStrictlyPositiveAttrOp : TEST_AttrOp<"confined_strictly_positive_attr"> {
   let arguments = (ins
       ConfinedAttr<DenseI8ArrayAttr,
                    [DenseArrayStrictlyPositive<DenseI8ArrayAttr>]>:$i8attr,
@@ -450,7 +469,7 @@ def DenseArrayStrictlyPositiveAttrOp : TEST_Op<"confined_strictly_positive_attr"
 
 // It does not make sense to have this constraint on a DenseBoolArrayAttr.
 // It is always true.
-def DenseArrayNonNegativeOp : TEST_Op<"confined_non_negative_attr"> {
+def DenseArrayNonNegativeOp : TEST_AttrOp<"confined_non_negative_attr"> {
   let arguments = (ins
       ConfinedAttr<DenseI8ArrayAttr,
                    [DenseArrayNonNegative<DenseI8ArrayAttr>]>:$i8attr,
@@ -473,7 +492,7 @@ def DenseArrayNonNegativeOp : TEST_Op<"confined_non_negative_attr"> {
 // Test Promised Interfaces Constraints
 //===----------------------------------------------------------------------===//
 
-def PromisedInterfacesOp : TEST_Op<"promised_interfaces"> {
+def PromisedInterfacesOp : TEST_AttrOp<"promised_interfaces"> {
   let arguments = (ins
       ConfinedAttr<AnyAttr,
           [PromisedAttrInterface<TestExternalAttrInterface>]>:$promisedAttr,
@@ -494,14 +513,14 @@ def TestPrettyEnumAttr
     : EnumAttr<Test_Dialect, TestPrettyEnum, "pretty_enum">;
 
 // Define an op that contains the enum attribute.
-def OpWithEnum : TEST_Op<"op_with_enum"> {
+def OpWithEnum : TEST_AttrOp<"op_with_enum"> {
   let arguments = (ins TestEnumAttr:$value, OptionalAttr<AnyAttr>:$tag);
   let assemblyFormat = "enum($value) (`tag` $tag^)? attr-dict";
 }
 
 // Define an op that prints just the symbolic value of an enum attribute whose
 // own assembly format includes angle brackets.
-def OpWithEnumDirective : TEST_Op<"op_with_enum_directive"> {
+def OpWithEnumDirective : TEST_AttrOp<"op_with_enum_directive"> {
   let arguments = (ins TestPrettyEnumAttr:$value);
   let assemblyFormat = "enum($value) attr-dict";
 }
@@ -519,13 +538,13 @@ def : Pat<(OpWithEnum ConstantEnumCase<TestEnumAttr, "first">:$value,
 // Define the enum property.
 def TestEnumProp : EnumProp<TestEnum>;
 // Define an op that contains the enum property.
-def OpWithEnumProp : TEST_Op<"op_with_enum_prop"> {
+def OpWithEnumProp : TEST_AttrOp<"op_with_enum_prop"> {
   let arguments = (ins TestEnumProp:$value);
   let assemblyFormat = "$value attr-dict";
 }
 
 def TestEnumPropAttrForm : EnumPropWithAttrForm<TestEnum, TestEnumAttr>;
-def OpWithEnumPropAttrForm : TEST_Op<"op_with_enum_prop_attr_form"> {
+def OpWithEnumPropAttrForm : TEST_AttrOp<"op_with_enum_prop_attr_form"> {
   let arguments = (ins TestEnumPropAttrForm:$value);
   let assemblyFormat = "prop-dict attr-dict";
 }
@@ -533,7 +552,7 @@ def OpWithEnumPropAttrForm : TEST_Op<"op_with_enum_prop_attr_form"> {
 def TestEnumPropAttrFormAlways : EnumPropWithAttrForm<TestEnum, TestEnumAttr> {
   let storeInCustomAttribute = 1;
 }
-def OpWithEnumPropAttrFormAlways : TEST_Op<"op_with_enum_prop_attr_form_always"> {
+def OpWithEnumPropAttrFormAlways : TEST_AttrOp<"op_with_enum_prop_attr_form_always"> {
   let arguments = (ins TestEnumPropAttrFormAlways:$value);
   let assemblyFormat = "prop-dict attr-dict";
 }
@@ -541,7 +560,7 @@ def OpWithEnumPropAttrFormAlways : TEST_Op<"op_with_enum_prop_attr_form_always">
 def TestBitEnumProp : EnumProp<TestBitEnum> {
   let defaultValue = TestBitEnum.cppType # "::Read";
 }
-def OpWithTestBitEnum : TEST_Op<"op_with_bit_enum_prop"> {
+def OpWithTestBitEnum : TEST_AttrOp<"op_with_bit_enum_prop"> {
   let arguments = (ins
     TestBitEnumProp:$value1,
     TestBitEnumProp:$value2);
@@ -549,7 +568,7 @@ def OpWithTestBitEnum : TEST_Op<"op_with_bit_enum_prop"> {
 }
 
 def OpWithTestBitEnumPropDict
-    : TEST_Op<"op_with_bit_enum_prop_dict"> {
+    : TEST_AttrOp<"op_with_bit_enum_prop_dict"> {
   let arguments = (ins TestBitEnumProp:$flags, I64Prop:$next);
   let assemblyFormat = "prop-dict attr-dict";
 }
@@ -557,7 +576,7 @@ def OpWithTestBitEnumPropDict
 def TestBitEnumPropNamed : NamedEnumProp<TestBitEnum, "bit_enum"> {
   let defaultValue = TestBitEnum.cppType # "::Read";
 }
-def OpWithBitEnumPropNamed : TEST_Op<"op_with_bit_enum_prop_named"> {
+def OpWithBitEnumPropNamed : TEST_AttrOp<"op_with_bit_enum_prop_named"> {
   let arguments = (ins
     TestBitEnumPropNamed:$value1,
     TestBitEnumPropNamed:$value2);
@@ -566,14 +585,14 @@ def OpWithBitEnumPropNamed : TEST_Op<"op_with_bit_enum_prop_named"> {
 
 def TestSimpleEnum8Prop : EnumProp<TestSimpleEnum8>;
 
-def OpWithSimpleEnum8Prop : TEST_Op<"op_with_simple_enum_8_prop"> {
+def OpWithSimpleEnum8Prop : TEST_AttrOp<"op_with_simple_enum_8_prop"> {
   let arguments = (ins TestSimpleEnum8Prop:$value);
   let assemblyFormat = "$value attr-dict";
 }
 
 def TestSimpleEnum16Prop : EnumProp<TestSimpleEnum16>;
 
-def OpWithSimpleEnum16Prop : TEST_Op<"op_with_simple_enum_16_prop"> {
+def OpWithSimpleEnum16Prop : TEST_AttrOp<"op_with_simple_enum_16_prop"> {
   let arguments = (ins TestSimpleEnum16Prop:$value);
   let assemblyFormat = "$value attr-dict";
 }
@@ -586,7 +605,7 @@ def OpWithSimpleEnum16Prop : TEST_Op<"op_with_simple_enum_16_prop"> {
 def TestBitEnumAttr : EnumAttr<Test_Dialect, TestBitEnum, "bit_enum">;
 
 // Define an op that contains the enum attribute.
-def OpWithBitEnum : TEST_Op<"op_with_bit_enum"> {
+def OpWithBitEnum : TEST_AttrOp<"op_with_bit_enum"> {
   let arguments = (ins TestBitEnumAttr:$value, OptionalAttr<AnyAttr>:$tag);
   let assemblyFormat = "$value (`tag` $tag^)? attr-dict";
 }
@@ -595,19 +614,19 @@ def TestBitEnumVerticalBarAttr
     : EnumAttr<Test_Dialect, TestBitEnumVerticalBar, "bit_enum_vbar">;
 
 // Define an op that contains the enum attribute.
-def OpWithBitEnumVerticalBar : TEST_Op<"op_with_bit_enum_vbar"> {
+def OpWithBitEnumVerticalBar : TEST_AttrOp<"op_with_bit_enum_vbar"> {
   let arguments = (ins TestBitEnumVerticalBarAttr:$value,
                    OptionalAttr<AnyAttr>:$tag);
   let assemblyFormat = "$value (`tag` $tag^)? attr-dict";
 }
 
-def OpWithBitEnumDirective : TEST_Op<"op_with_bit_enum_directive"> {
+def OpWithBitEnumDirective : TEST_AttrOp<"op_with_bit_enum_directive"> {
   let arguments = (ins TestBitEnumAttr:$value);
   let assemblyFormat = "enum($value) attr-dict";
 }
 
 def OpWithBitEnumVerticalBarDirective
-    : TEST_Op<"op_with_bit_enum_vbar_directive"> {
+    : TEST_AttrOp<"op_with_bit_enum_vbar_directive"> {
   let arguments = (ins TestBitEnumVerticalBarAttr:$value);
   let assemblyFormat = "enum($value) attr-dict";
 }
@@ -819,6 +838,7 @@ def FoldToCallOp : TEST_Op<"fold_to_call_op"> {
 // Test Traits
 //===----------------------------------------------------------------------===//
 
+let partition = Test_TraitsPartition in {
 def SameOperandElementTypeOp : TEST_Op<"same_operand_element_type",
     [SameOperandsElementType]> {
   let arguments = (ins AnyType, AnyType);
@@ -1126,6 +1146,7 @@ def UnreifiableDimOfResultShapeOp : TEST_Op<"unreifiable_dim_of_result_shape",
   let arguments = (ins 2DTensorOf<[AnyType]>:$operand);
   let results = (outs 2DTensorOf<[AnyType]>:$result);
 }
+} // let partition = Test_TraitsPartition
 
 def IsNotScalar : Constraint<CPred<"$0.getType().getRank() != 0">>;
 
@@ -1133,6 +1154,7 @@ def UpdateAttr : Pat<(I32ElementsAttrOp $attr),
                      (I32ElementsAttrOp ConstantAttr<I32ElementsAttr, "0">),
                      [(IsNotScalar $attr)]>;
 
+let partition = Test_TraitsPartition in {
 def TestGreedyCfgRewriteOp : TEST_Op<"greedy_cfg_rewrite"> {
   let description = [{
     Exercises reachability changes while the greedy driver is processing its
@@ -1203,6 +1225,7 @@ def TestInternalBranchOp : TEST_Op<"internal_br",
 
   let successors = (successor AnySuccessor:$successPath, AnySuccessor:$errorPath);
 }
+} // let partition = Test_TraitsPartition
 
 // A successor that must be the block immediately following the op's block.
 def FallthroughSuccessor : Successor<
@@ -1222,6 +1245,7 @@ def ForwardSuccessor : Successor<
     }]>,
     "a forward block (a block listed after the op's block)">;
 
+let partition = Test_TraitsPartition in {
 def TestFallthroughBranchOp : TEST_Op<"fallthrough_br", [Terminator]> {
   let summary = "branch whose successors are constrained by predicates";
   let successors = (successor FallthroughSuccessor:$target,
@@ -1360,6 +1384,7 @@ def AttrWithTraitOp : TEST_Op<"attr_with_trait", []> {
   let arguments = (ins AnyAttr:$attr);
   let hasVerifier = 1;
 }
+} // let partition = Test_TraitsPartition
 
 //===----------------------------------------------------------------------===//
 // Test Locations
@@ -1395,12 +1420,12 @@ def TestLocationAttrOp : TEST_Op<"op_with_loc_attr"> {
 // Test Patterns
 //===----------------------------------------------------------------------===//
 
-def OpA : TEST_Op<"op_a"> {
+def OpA : TEST_PatternOp<"op_a"> {
   let arguments = (ins I32, I32Attr:$attr);
   let results = (outs I32);
 }
 
-def OpB : TEST_Op<"op_b"> {
+def OpB : TEST_PatternOp<"op_b"> {
   let arguments = (ins I32, I32Attr:$attr);
   let results = (outs I32);
 }
@@ -1412,10 +1437,10 @@ def TestNamedPatternRule : Pat<(OpA $input, $attr), (OpB $input, $attr)>;
 def : Pat<(OpA (OpA $input, $attr), $bttr), (OpB $input, $bttr)>;
 
 // Test added benefit.
-def OpD : TEST_Op<"op_d">, Arguments<(ins I32)>, Results<(outs I32)>;
-def OpE : TEST_Op<"op_e">, Arguments<(ins I32)>, Results<(outs I32)>;
-def OpF : TEST_Op<"op_f">, Arguments<(ins I32)>, Results<(outs I32)>;
-def OpG : TEST_Op<"op_g">, Arguments<(ins I32)>, Results<(outs I32)>;
+def OpD : TEST_PatternOp<"op_d">, Arguments<(ins I32)>, Results<(outs I32)>;
+def OpE : TEST_PatternOp<"op_e">, Arguments<(ins I32)>, Results<(outs I32)>;
+def OpF : TEST_PatternOp<"op_f">, Arguments<(ins I32)>, Results<(outs I32)>;
+def OpG : TEST_PatternOp<"op_g">, Arguments<(ins I32)>, Results<(outs I32)>;
 // Verify that bumping benefit results in selecting different op.
 def : Pat<(OpD $input), (OpE $input)>;
 def : Pat<(OpD $input), (OpF $input), [], [], (addBenefit 10)>;
@@ -1424,43 +1449,43 @@ def : Pat<(OpG $input), (OpB $input, ConstantAttr<I32Attr, "20">:$attr)>;
 def : Pat<(OpG (OpG $input)), (OpB $input, ConstantAttr<I32Attr, "34">:$attr)>;
 
 // Test patterns for zero-result op.
-def OpH : TEST_Op<"op_h">, Arguments<(ins I32)>, Results<(outs)>;
-def OpI : TEST_Op<"op_i">, Arguments<(ins I32)>, Results<(outs)>;
+def OpH : TEST_PatternOp<"op_h">, Arguments<(ins I32)>, Results<(outs)>;
+def OpI : TEST_PatternOp<"op_i">, Arguments<(ins I32)>, Results<(outs)>;
 def : Pat<(OpH $input), (OpI $input)>;
 
 // Test patterns for zero-input op.
-def OpJ : TEST_Op<"op_j">, Arguments<(ins)>, Results<(outs I32)>;
-def OpK : TEST_Op<"op_k">, Arguments<(ins)>, Results<(outs I32)>;
+def OpJ : TEST_PatternOp<"op_j">, Arguments<(ins)>, Results<(outs I32)>;
+def OpK : TEST_PatternOp<"op_k">, Arguments<(ins)>, Results<(outs I32)>;
 def : Pat<(OpJ), (OpK)>;
 
 // Test that natives calls are only called once during rewrites.
-def OpM : TEST_Op<"op_m"> {
+def OpM : TEST_PatternOp<"op_m"> {
   let arguments = (ins I32, OptionalAttr<I32Attr>:$optional_attr);
   let results = (outs I32);
 }
 
-def OpN : TEST_Op<"op_n"> {
+def OpN : TEST_PatternOp<"op_n"> {
   let arguments = (ins I32, I32);
   let results = (outs I32);
 }
 
-def OpO : TEST_Op<"op_o"> {
+def OpO : TEST_PatternOp<"op_o"> {
   let arguments = (ins I32);
   let results = (outs I32);
 }
 
-def OpP : TEST_Op<"op_p"> {
+def OpP : TEST_PatternOp<"op_p"> {
   let arguments = (ins I32, I32, I32, I32, I32, I32);
   let results = (outs I32);
 }
 
-def OpQ : TEST_Op<"op_q"> {
+def OpQ : TEST_PatternOp<"op_q"> {
   let arguments = (ins AnyType, AnyType);
   let results = (outs AnyType);
 }
 
 // Test constant-folding a pattern that maps `(F32) -> I32`.
-def SignOp : TEST_Op<"sign", [SameOperandsAndResultShape]> {
+def SignOp : TEST_PatternOp<"sign", [SameOperandsAndResultShape]> {
   let arguments = (ins RankedTensorOf<[F32]>:$operand);
   let results = (outs RankedTensorOf<[I32]>:$result);
 
@@ -1470,7 +1495,7 @@ def SignOp : TEST_Op<"sign", [SameOperandsAndResultShape]> {
 }
 
 // Test constant-folding a pattern that maps `(F32, F32) -> I1`.
-def LessThanOp : TEST_Op<"less_than", [SameOperandsAndResultShape]> {
+def LessThanOp : TEST_PatternOp<"less_than", [SameOperandsAndResultShape]> {
   let arguments = (ins RankedTensorOf<[F32]>:$lhs, RankedTensorOf<[F32]>:$rhs);
   let results = (outs RankedTensorOf<[I1]>:$result);
 
@@ -1506,22 +1531,22 @@ def TestEqualArgsCheckBeforeUserConstraintsPattern :
       [(AssertBinOpEqualArgsAndReturnTrue $op)]>;
 
 // Test for memrefs normalization of an op with normalizable memrefs.
-def OpNorm : TEST_Op<"op_norm", [MemRefsNormalizable]> {
+def OpNorm : TEST_PatternOp<"op_norm", [MemRefsNormalizable]> {
   let arguments = (ins AnyMemRef:$X, AnyMemRef:$Y);
 }
 // Test for memrefs normalization of an op without normalizable memrefs.
-def OpNonNorm : TEST_Op<"op_nonnorm"> {
+def OpNonNorm : TEST_PatternOp<"op_nonnorm"> {
   let arguments = (ins AnyMemRef:$X, AnyMemRef:$Y);
 }
 // Test for memrefs normalization of an op that has normalizable memref results.
-def OpNormRet : TEST_Op<"op_norm_ret", [MemRefsNormalizable]> {
+def OpNormRet : TEST_PatternOp<"op_norm_ret", [MemRefsNormalizable]> {
   let arguments = (ins AnyMemRef:$X);
   let results = (outs AnyMemRef:$Y, AnyMemRef:$Z);
 }
 
 // Test for memrefs normalization of an op with a reference to a function
 // symbol.
-def OpFuncRef : TEST_Op<"op_funcref"> {
+def OpFuncRef : TEST_PatternOp<"op_funcref"> {
   let summary = "Test op with a reference to a function symbol";
   let description = [{
     The "test.op_funcref" is a test op with a reference to a function symbol.
@@ -1538,18 +1563,19 @@ def : Pat<(OpM $attr, $optAttr), (OpM $attr, (OpMVal $attr) ),
     [(OpMAttributeIsNull:$optAttr)]>;
 
 // Test `$_` for ignoring op argument match.
-def TestIgnoreArgMatchSrcOp : TEST_Op<"ignore_arg_match_src"> {
+def TestIgnoreArgMatchSrcOp : TEST_PatternOp<"ignore_arg_match_src"> {
   let arguments = (ins
     AnyType:$a, AnyType:$b, AnyType:$c,
     AnyAttr:$d, AnyAttr:$e, AnyAttr:$f);
 }
-def TestIgnoreArgMatchDstOp : TEST_Op<"ignore_arg_match_dst"> {
+def TestIgnoreArgMatchDstOp : TEST_PatternOp<"ignore_arg_match_dst"> {
   let arguments = (ins AnyType:$b, AnyAttr:$f);
 }
 def : Pat<(TestIgnoreArgMatchSrcOp $_, $b, I32, I64Attr:$_, $_, $f),
           (TestIgnoreArgMatchDstOp $b, $f)>;
 
-def OpInterleavedOperandAttribute1 : TEST_Op<"interleaved_operand_attr1"> {
+def OpInterleavedOperandAttribute1 :
+    TEST_PatternOp<"interleaved_operand_attr1"> {
   let arguments = (ins
     I32:$input1,
     I64Attr:$attr1,
@@ -1558,7 +1584,8 @@ def OpInterleavedOperandAttribute1 : TEST_Op<"interleaved_operand_attr1"> {
   );
 }
 
-def OpInterleavedOperandAttribute2 : TEST_Op<"interleaved_operand_attr2"> {
+def OpInterleavedOperandAttribute2 :
+    TEST_PatternOp<"interleaved_operand_attr2"> {
   let arguments = (ins
     I32:$input1,
     I64Attr:$attr1,
@@ -1567,7 +1594,7 @@ def OpInterleavedOperandAttribute2 : TEST_Op<"interleaved_operand_attr2"> {
   );
 }
 
-def ManyArgsOp : TEST_Op<"many_arguments"> {
+def ManyArgsOp : TEST_PatternOp<"many_arguments"> {
   let arguments = (ins
     I32:$input1, I32:$input2, I32:$input3, I32:$input4, I32:$input5,
     I32:$input6, I32:$input7, I32:$input8, I32:$input9,
@@ -1596,7 +1623,7 @@ def : Pat<(OpInterleavedOperandAttribute1 $input1, $attr1, $input2, $attr2),
           (OpInterleavedOperandAttribute2 $input1, $attr1, $input2, $attr2)>;
 
 // Test NativeCodeCall.
-def OpNativeCodeCall1 : TEST_Op<"native_code_call1"> {
+def OpNativeCodeCall1 : TEST_PatternOp<"native_code_call1"> {
   let arguments = (ins
     I32:$input1, I32:$input2,
     BoolAttr:$choice,
@@ -1604,7 +1631,7 @@ def OpNativeCodeCall1 : TEST_Op<"native_code_call1"> {
   );
   let results = (outs I32);
 }
-def OpNativeCodeCall2 : TEST_Op<"native_code_call2"> {
+def OpNativeCodeCall2 : TEST_PatternOp<"native_code_call2"> {
   let arguments = (ins I32:$input, I64ArrayAttr:$attr);
   let results = (outs I32);
 }
@@ -1627,7 +1654,7 @@ def : Pat<(OpNativeCodeCall1 $input1, $input2,
                              ConstBoolAttrFalse, $attr1, $attr2),
           (UseOpResult $input2)>;
 
-def OpNativeCodeCall3 : TEST_Op<"native_code_call3"> {
+def OpNativeCodeCall3 : TEST_PatternOp<"native_code_call3"> {
   let arguments = (ins I32:$input);
   let results = (outs I32);
 }
@@ -1637,11 +1664,11 @@ def : Pattern<(OpNativeCodeCall3 $input),
               [(NativeCodeCallVoid<"createOpI($_builder, $_loc, $0)"> $input),
                (OpK)]>;
 
-def OpNativeCodeCall4 : TEST_Op<"native_code_call4"> {
+def OpNativeCodeCall4 : TEST_PatternOp<"native_code_call4"> {
   let arguments = (ins AnyType:$input1);
   let results = (outs I32:$output1, I32:$output2);
 }
-def OpNativeCodeCall5 : TEST_Op<"native_code_call5"> {
+def OpNativeCodeCall5 : TEST_PatternOp<"native_code_call5"> {
   let arguments = (ins I32:$input1, I32:$input2);
   let results = (outs I32:$output1, I32:$output2);
 }
@@ -1651,11 +1678,11 @@ def BindNativeCodeCallResult : NativeCodeCall<"bindNativeCodeCallResult($0)">;
 def : Pat<(OpNativeCodeCall4 (GetFirstI32Result $ret)),
           (OpNativeCodeCall5 (BindNativeCodeCallResult:$native $ret), $native)>;
 
-def OpNativeCodeCall6 : TEST_Op<"native_code_call6"> {
+def OpNativeCodeCall6 : TEST_PatternOp<"native_code_call6"> {
   let arguments = (ins I32:$input1, I32:$input2);
   let results = (outs I32:$output1, I32:$output2);
 }
-def OpNativeCodeCall7 : TEST_Op<"native_code_call7"> {
+def OpNativeCodeCall7 : TEST_PatternOp<"native_code_call7"> {
   let arguments = (ins I32:$input);
   let results = (outs I32);
 }
@@ -1665,11 +1692,11 @@ def : Pattern<(OpNativeCodeCall6 $arg1, $arg2),
                (OpNativeCodeCall7 $native__1)]>;
 
 // Test AllAttrOf.
-def OpAllAttrConstraint1 : TEST_Op<"all_attr_constraint_of1"> {
+def OpAllAttrConstraint1 : TEST_PatternOp<"all_attr_constraint_of1"> {
   let arguments = (ins I64ArrayAttr:$attr);
   let results = (outs I32);
 }
-def OpAllAttrConstraint2 : TEST_Op<"all_attr_constraint_of2"> {
+def OpAllAttrConstraint2 : TEST_PatternOp<"all_attr_constraint_of2"> {
   let arguments = (ins I64ArrayAttr:$attr);
   let results = (outs I32);
 }
@@ -1684,114 +1711,116 @@ def : Pat<(OpAllAttrConstraint1
           (OpAllAttrConstraint2 $attr)>;
 
 // Op for testing RewritePattern removing op with inner ops.
-def TestOpWithRegionPattern : TEST_Op<"op_with_region_pattern"> {
+def TestOpWithRegionPattern : TEST_PatternOp<"op_with_region_pattern"> {
   let regions = (region SizedRegion<1>:$region);
   let hasCanonicalizer = 1;
 }
 
-def TestOpConstant : TEST_Op<"constant", [ConstantLike, NoMemoryEffect]> {
+def TestOpConstant :
+    TEST_PatternOp<"constant", [ConstantLike, NoMemoryEffect]> {
   let arguments = (ins AnyAttr:$value);
   let results = (outs AnyType);
 
   let hasFolder = 1;
 }
 
-def OpR : TEST_Op<"op_r">, Arguments<(ins AnyInteger, AnyInteger)>, Results<(outs AnyInteger)>;
-def OpS : TEST_Op<"op_s">, Arguments<(ins AnyInteger, AnyAttr:$value)>, Results<(outs AnyInteger)>;
+def OpR : TEST_PatternOp<"op_r">, Arguments<(ins AnyInteger, AnyInteger)>, Results<(outs AnyInteger)>;
+def OpS : TEST_PatternOp<"op_s">, Arguments<(ins AnyInteger, AnyAttr:$value)>, Results<(outs AnyInteger)>;
 
 def : Pat<(OpR $input1, (ConstantLikeMatcher I32Attr:$input2)),
           (OpS:$unused $input1, $input2)>;
 
 // Op for testing trivial removal via folding of op with inner ops and no uses.
-def TestOpWithRegionFoldNoMemoryEffect : TEST_Op<
+def TestOpWithRegionFoldNoMemoryEffect : TEST_PatternOp<
     "op_with_region_fold_no_side_effect", [NoMemoryEffect]> {
   let regions = (region SizedRegion<1>:$region);
 }
 
 // Op for testing folding of outer op with inner ops.
-def TestOpWithRegionFold : TEST_Op<"op_with_region_fold"> {
+def TestOpWithRegionFold : TEST_PatternOp<"op_with_region_fold"> {
   let arguments = (ins AnyType:$operand);
   let results = (outs AnyType);
   let regions = (region SizedRegion<1>:$region);
   let hasFolder = 1;
 }
 
-def TestOpWithVariadicResultsAndFolder: TEST_Op<"op_with_variadic_results_and_folder"> {
+def TestOpWithVariadicResultsAndFolder: TEST_PatternOp<"op_with_variadic_results_and_folder"> {
   let arguments = (ins Variadic<I32>);
   let results = (outs Variadic<I32>);
   let hasFolder = 1;
 }
 
-def TestAddIOp : TEST_Op<"addi"> {
+def TestAddIOp : TEST_PatternOp<"addi"> {
   let arguments = (ins AnyTypeOf<[I32, TestI32]>:$op1,
                        AnyTypeOf<[I32, TestI32]>:$op2);
   let results = (outs AnyTypeOf<[I32, TestI32]>);
 }
 
-def TestCommutativeOp : TEST_Op<"op_commutative", [Commutative]> {
+def TestCommutativeOp : TEST_PatternOp<"op_commutative", [Commutative]> {
   let arguments = (ins I32:$op1, I32:$op2, I32:$op3, I32:$op4);
   let results = (outs I32);
 }
 
-def TestLargeCommutativeOp : TEST_Op<"op_large_commutative", [Commutative]> {
+def TestLargeCommutativeOp :
+    TEST_PatternOp<"op_large_commutative", [Commutative]> {
   let arguments = (ins I32:$op1, I32:$op2, I32:$op3, I32:$op4, I32:$op5, I32:$op6, I32:$op7);
   let results = (outs I32);
 }
 
-def TestCommutative2Op : TEST_Op<"op_commutative2", [Commutative]> {
+def TestCommutative2Op : TEST_PatternOp<"op_commutative2", [Commutative]> {
   let arguments = (ins I32:$op1, I32:$op2);
   let results = (outs I32);
 }
 
 def TestIdempotentTraitOp
- : TEST_Op<"op_idempotent_trait",
-           [SameOperandsAndResultType, NoMemoryEffect, Idempotent]> {
+ : TEST_PatternOp<"op_idempotent_trait",
+                  [SameOperandsAndResultType, NoMemoryEffect, Idempotent]> {
   let arguments = (ins I32:$op1);
   let results = (outs I32);
 }
 
 def TestIdempotentTraitBinaryOp
-    : TEST_Op<"op_idempotent_trait_binary",
-              [SameOperandsAndResultType, NoMemoryEffect, Idempotent]> {
+    : TEST_PatternOp<"op_idempotent_trait_binary",
+                     [SameOperandsAndResultType, NoMemoryEffect, Idempotent]> {
   let arguments = (ins I32:$op1, I32:$op2);
   let results = (outs I32);
 }
 
 def TestInvolutionTraitNoOperationFolderOp
- : TEST_Op<"op_involution_trait_no_operation_fold",
-           [SameOperandsAndResultType, NoMemoryEffect, Involution]> {
+ : TEST_PatternOp<"op_involution_trait_no_operation_fold",
+                  [SameOperandsAndResultType, NoMemoryEffect, Involution]> {
   let arguments = (ins I32:$op1);
   let results = (outs I32);
 }
 
 def TestInvolutionTraitFailingOperationFolderOp
- : TEST_Op<"op_involution_trait_failing_operation_fold",
-           [SameOperandsAndResultType, NoMemoryEffect, Involution]> {
+ : TEST_PatternOp<"op_involution_trait_failing_operation_fold",
+                  [SameOperandsAndResultType, NoMemoryEffect, Involution]> {
   let arguments = (ins I32:$op1);
   let results = (outs I32);
   let hasFolder = 1;
 }
 
 def TestInvolutionTraitSuccesfulOperationFolderOp
- : TEST_Op<"op_involution_trait_succesful_operation_fold",
-           [SameOperandsAndResultType, NoMemoryEffect, Involution]> {
+ : TEST_PatternOp<"op_involution_trait_succesful_operation_fold",
+                  [SameOperandsAndResultType, NoMemoryEffect, Involution]> {
   let arguments = (ins I32:$op1);
   let results = (outs I32);
   let hasFolder = 1;
 }
 
-def TestOpInPlaceFoldAnchor : TEST_Op<"op_in_place_fold_anchor"> {
+def TestOpInPlaceFoldAnchor : TEST_PatternOp<"op_in_place_fold_anchor"> {
   let arguments = (ins I32);
   let results = (outs I32);
 }
 
-def TestOpInPlaceFold : TEST_Op<"op_in_place_fold"> {
+def TestOpInPlaceFold : TEST_PatternOp<"op_in_place_fold"> {
   let arguments = (ins I32:$op, OptionalAttr<I32Attr>:$attr);
   let results = (outs I32);
   let hasFolder = 1;
 }
 
-def TestOpInPlaceSelfFold : TEST_Op<"op_in_place_self_fold"> {
+def TestOpInPlaceSelfFold : TEST_PatternOp<"op_in_place_self_fold"> {
   let arguments = (ins UnitAttr:$folded);
   let results = (outs I32);
   let hasFolder = 1;
@@ -1800,7 +1829,7 @@ def : Pat<(TestOpInPlaceSelfFold:$op $_),
           (TestOpConstant ConstantAttr<I32Attr, "97">)>;
 
 // Test op that simply returns success.
-def TestOpInPlaceFoldSuccess : TEST_Op<"op_in_place_fold_success"> {
+def TestOpInPlaceFoldSuccess : TEST_PatternOp<"op_in_place_fold_success"> {
   let results = (outs Variadic<I1>);
   let hasFolder = 1;
   let extraClassDefinition = [{
@@ -1812,7 +1841,7 @@ def TestOpInPlaceFoldSuccess : TEST_Op<"op_in_place_fold_success"> {
 }
 
 def TestOpFoldWithFoldAdaptor
-  : TEST_Op<"fold_with_fold_adaptor",
+  : TEST_PatternOp<"fold_with_fold_adaptor",
       [AttrSizedOperandSegments, NoTerminator]> {
   let arguments = (ins
     I32:$op,
@@ -1832,7 +1861,7 @@ def TestOpFoldWithFoldAdaptor
   let hasFolder = 1;
 }
 
-def TestDialectCanonicalizerOp : TEST_Op<"dialect_canonicalizable"> {
+def TestDialectCanonicalizerOp : TEST_PatternOp<"dialect_canonicalizable"> {
   let arguments = (ins);
   let results = (outs I32);
 }
@@ -1842,20 +1871,20 @@ def TestDialectCanonicalizerOp : TEST_Op<"dialect_canonicalizable"> {
 //===----------------------------------------------------------------------===//
 
 // Test symbol binding.
-def OpSymbolBindingA : TEST_Op<"symbol_binding_a", []> {
+def OpSymbolBindingA : TEST_PatternOp<"symbol_binding_a", []> {
   let arguments = (ins I32:$operand, I64Attr:$attr);
   let results = (outs I32);
 }
-def OpSymbolBindingB : TEST_Op<"symbol_binding_b", []> {
+def OpSymbolBindingB : TEST_PatternOp<"symbol_binding_b", []> {
   let arguments = (ins I32:$operand);
   let results = (outs I32);
 }
-def OpSymbolBindingC : TEST_Op<"symbol_binding_c", []> {
+def OpSymbolBindingC : TEST_PatternOp<"symbol_binding_c", []> {
   let arguments = (ins I32:$operand);
   let results = (outs I32);
   let builders = OpSymbolBindingB.builders;
 }
-def OpSymbolBindingD : TEST_Op<"symbol_binding_d", []> {
+def OpSymbolBindingD : TEST_PatternOp<"symbol_binding_d", []> {
   let arguments = (ins I32:$input1, I32:$input2, I64Attr:$attr);
   let results = (outs I32);
 }
@@ -1871,7 +1900,7 @@ def : Pattern<
     // Use bound symbols in additional constraints
     [(HasOneUse $res_a)]>;
 
-def OpSymbolBindingNoResult : TEST_Op<"symbol_binding_no_result", []> {
+def OpSymbolBindingNoResult : TEST_PatternOp<"symbol_binding_no_result", []> {
   let arguments = (ins I32:$operand);
 }
 
@@ -1884,7 +1913,7 @@ def : Pat<(OpSymbolBindingNoResult:$op $operand),
 //===----------------------------------------------------------------------===//
 
 // Test matching against op attributes.
-def OpAttrMatch1 : TEST_Op<"match_op_attribute1"> {
+def OpAttrMatch1 : TEST_PatternOp<"match_op_attribute1"> {
   let arguments = (ins
     I32Attr:$required_attr,
     OptionalAttr<I32Attr>:$optional_attr,
@@ -1893,7 +1922,7 @@ def OpAttrMatch1 : TEST_Op<"match_op_attribute1"> {
   );
   let results = (outs I32);
 }
-def OpAttrMatch2 : TEST_Op<"match_op_attribute2"> {
+def OpAttrMatch2 : TEST_PatternOp<"match_op_attribute2"> {
   let arguments = OpAttrMatch1.arguments;
   let results = (outs I32);
 }
@@ -1904,57 +1933,57 @@ def : Pat<(OpAttrMatch1 $required, $optional, $default_valued,
           (OpAttrMatch2 $required, $optional, $default_valued, $more)>;
 
 // Test unit attrs.
-def OpAttrMatch3 : TEST_Op<"match_op_attribute3"> {
+def OpAttrMatch3 : TEST_PatternOp<"match_op_attribute3"> {
   let arguments = (ins UnitAttr:$attr);
   let results = (outs I32);
 }
-def OpAttrMatch4 : TEST_Op<"match_op_attribute4"> {
+def OpAttrMatch4 : TEST_PatternOp<"match_op_attribute4"> {
   let arguments = (ins UnitAttr:$attr1, UnitAttr:$attr2);
   let results = (outs I32);
 }
 def : Pat<(OpAttrMatch3 $attr), (OpAttrMatch4 ConstUnitAttr, $attr)>;
 
 // Test with constant attr.
-def OpC : TEST_Op<"op_c">, Arguments<(ins I32)>, Results<(outs I32)>;
+def OpC : TEST_PatternOp<"op_c">, Arguments<(ins I32)>, Results<(outs I32)>;
 def : Pat<(OpC $input), (OpB $input, ConstantAttr<I32Attr, "17">:$attr)>;
 
 // Test integer enum attribute in rewrites.
 def : Pat<(I32EnumAttrOp I32Case5), (I32EnumAttrOp I32Case10)>;
 def : Pat<(I64EnumAttrOp I64Case5), (I64EnumAttrOp I64Case10)>;
 
-def ThreeResultOp : TEST_Op<"three_result"> {
+def ThreeResultOp : TEST_PatternOp<"three_result"> {
   let arguments = (ins MultiResultOpEnum:$kind);
   let results = (outs I32:$result1, F32:$result2, F32:$result3);
 }
 
 def AnotherThreeResultOp
-    : TEST_Op<"another_three_result",
-              [DeclareOpInterfaceMethods<InferTypeOpInterface>]> {
+    : TEST_PatternOp<"another_three_result",
+                     [DeclareOpInterfaceMethods<InferTypeOpInterface>]> {
   let arguments = (ins MultiResultOpEnum:$kind);
   let results = (outs I32:$result1, F32:$result2, F32:$result3);
 }
 
-def TwoResultOp : TEST_Op<"two_result"> {
+def TwoResultOp : TEST_PatternOp<"two_result"> {
   let arguments = (ins MultiResultOpEnum:$kind);
   let results = (outs I32:$result1, F32:$result2);
 }
 
-def AnotherTwoResultOp : TEST_Op<"another_two_result"> {
+def AnotherTwoResultOp : TEST_PatternOp<"another_two_result"> {
   let arguments = (ins MultiResultOpEnum:$kind);
   let results = (outs F32:$result1, F32:$result2);
 }
 
-def OneResultOp1 : TEST_Op<"one_result1"> {
+def OneResultOp1 : TEST_PatternOp<"one_result1"> {
   let arguments = (ins MultiResultOpEnum:$kind);
   let results = (outs F32:$result1);
 }
 
-def OneResultOp2 : TEST_Op<"one_result2"> {
+def OneResultOp2 : TEST_PatternOp<"one_result2"> {
   let arguments = (ins MultiResultOpEnum:$kind);
   let results = (outs I32:$result1);
 }
 
-def OneResultOp3 : TEST_Op<"one_result3"> {
+def OneResultOp3 : TEST_PatternOp<"one_result3"> {
   let arguments = (ins F32);
   let results = (outs I32:$result1);
 }
@@ -1999,11 +2028,13 @@ def : Pattern<
 // Test Patterns (Variadic Ops)
 //===----------------------------------------------------------------------===//
 
-def OneVResOneVOperandOp1 : TEST_Op<"one_variadic_out_one_variadic_in1"> {
+def OneVResOneVOperandOp1 :
+    TEST_PatternOp<"one_variadic_out_one_variadic_in1"> {
   let arguments = (ins Variadic<I32>);
   let results = (outs Variadic<I32>);
 }
-def OneVResOneVOperandOp2 : TEST_Op<"one_variadic_out_one_variadic_in2"> {
+def OneVResOneVOperandOp2 :
+    TEST_PatternOp<"one_variadic_out_one_variadic_in2"> {
   let arguments = (ins Variadic<I32>);
   let results = (outs Variadic<I32>);
 }
@@ -2012,8 +2043,8 @@ def OneVResOneVOperandOp2 : TEST_Op<"one_variadic_out_one_variadic_in2"> {
 // another similar op.
 def : Pat<(OneVResOneVOperandOp1 $inputs), (OneVResOneVOperandOp2 $inputs)>;
 
-def MixedVOperandOp1 : TEST_Op<"mixed_variadic_in1",
-                               [SameVariadicOperandSize]> {
+def MixedVOperandOp1 : TEST_PatternOp<"mixed_variadic_in1",
+                                      [SameVariadicOperandSize]> {
   let arguments = (ins
     Variadic<I32>:$input1,
     F32:$input2,
@@ -2021,8 +2052,8 @@ def MixedVOperandOp1 : TEST_Op<"mixed_variadic_in1",
   );
 }
 
-def MixedVOperandOp2 : TEST_Op<"mixed_variadic_in2",
-                               [SameVariadicOperandSize]> {
+def MixedVOperandOp2 : TEST_PatternOp<"mixed_variadic_in2",
+                                      [SameVariadicOperandSize]> {
   let arguments = (ins
     Variadic<I32>:$input1,
     F32:$input2,
@@ -2034,7 +2065,8 @@ def MixedVOperandOp2 : TEST_Op<"mixed_variadic_in2",
 def : Pat<(MixedVOperandOp1 $input1, $input2, $input3),
           (MixedVOperandOp2 $input1, $input2, $input3)>;
 
-def MixedVResultOp1 : TEST_Op<"mixed_variadic_out1", [SameVariadicResultSize]> {
+def MixedVResultOp1 :
+    TEST_PatternOp<"mixed_variadic_out1", [SameVariadicResultSize]> {
   let results = (outs
     Variadic<I32>:$output1,
     F32:$output2,
@@ -2042,7 +2074,8 @@ def MixedVResultOp1 : TEST_Op<"mixed_variadic_out1", [SameVariadicResultSize]> {
   );
 }
 
-def MixedVResultOp2 : TEST_Op<"mixed_variadic_out2", [SameVariadicResultSize]> {
+def MixedVResultOp2 :
+    TEST_PatternOp<"mixed_variadic_out2", [SameVariadicResultSize]> {
   let results = (outs
     Variadic<I32>:$output1,
     F32:$output2,
@@ -2056,12 +2089,12 @@ def MixedVResultOp2 : TEST_Op<"mixed_variadic_out2", [SameVariadicResultSize]> {
 // the information from the matched root op.
 def : Pat<(MixedVResultOp1), (MixedVResultOp2)>;
 
-def OneI32ResultOp : TEST_Op<"one_i32_out"> {
+def OneI32ResultOp : TEST_PatternOp<"one_i32_out"> {
   let results = (outs I32);
 }
 
-def MixedVOperandOp3 : TEST_Op<"mixed_variadic_in3",
-                               [SameVariadicOperandSize]> {
+def MixedVOperandOp3 : TEST_PatternOp<"mixed_variadic_in3",
+                                      [SameVariadicOperandSize]> {
   let arguments = (ins
     I32:$input1,
     Variadic<I32>:$input2,
@@ -2072,8 +2105,8 @@ def MixedVOperandOp3 : TEST_Op<"mixed_variadic_in3",
   let results = (outs I32);
 }
 
-def MixedVResultOp3 : TEST_Op<"mixed_variadic_out3",
-                               [SameVariadicResultSize]> {
+def MixedVResultOp3 : TEST_PatternOp<"mixed_variadic_out3",
+                                      [SameVariadicResultSize]> {
   let arguments = (ins I32Attr:$count);
 
   let results = (outs
@@ -2106,7 +2139,7 @@ def : Pat<(OneI32ResultOp),
               ConstantAttr<I32Attr, "2">)>;
 
 // Variadic structured matching
-def MixedVOperandOp4 : TEST_Op<"mixed_variadic_in4"> {
+def MixedVOperandOp4 : TEST_PatternOp<"mixed_variadic_in4"> {
   let arguments = (ins
     Variadic<I32>:$input1,
     I32:$input2,
@@ -2114,7 +2147,7 @@ def MixedVOperandOp4 : TEST_Op<"mixed_variadic_in4"> {
   );
 }
 
-def MixedVOperandOp5 : TEST_Op<"mixed_variadic_in5"> {
+def MixedVOperandOp5 : TEST_PatternOp<"mixed_variadic_in5"> {
   let arguments = (ins
     I32:$input1,
     I32:$input2,
@@ -2125,7 +2158,7 @@ def MixedVOperandOp5 : TEST_Op<"mixed_variadic_in5"> {
 }
 
 // Helper op to test variadic recursive pattern matching
-def MixedVOperandInOutI32Op : TEST_Op<"mixed_variadic_in_out_i32"> {
+def MixedVOperandInOutI32Op : TEST_PatternOp<"mixed_variadic_in_out_i32"> {
   let arguments = (ins
     I32:$input
   );
@@ -2159,8 +2192,8 @@ def : Pat<
   (MixedVOperandOp5 $input1, $input1, $input2, $attr1,
                     ConstantStrAttr<StrAttr, "MatchVariadicSameSymbol">)>;
 
-def MixedVOperandOp6 : TEST_Op<"mixed_variadic_in6",
-                               [SameVariadicOperandSize]> {
+def MixedVOperandOp6 : TEST_PatternOp<"mixed_variadic_in6",
+                                      [SameVariadicOperandSize]> {
   let arguments = (ins
     Variadic<I32>:$input1,
     Variadic<I32>:$input2,
@@ -2181,8 +2214,8 @@ def : Pat<
   (MixedVOperandOp5 $input2a, $input2b, $input1b, $attr1,
                     ConstantStrAttr<StrAttr, "MatchMultiVariadicSubSymbol">)>;
 
-def MixedVOperandOp7 : TEST_Op<"mixed_variadic_optional_in7",
-                               [AttrSizedOperandSegments]> {
+def MixedVOperandOp7 : TEST_PatternOp<"mixed_variadic_optional_in7",
+                                      [AttrSizedOperandSegments]> {
   let arguments = (ins
     Variadic<I32>:$input1,
     Optional<I32>:$input2,
@@ -2199,17 +2232,17 @@ def : Pat<
 // Test Patterns (either)
 //===----------------------------------------------------------------------===//
 
-def TestEitherOpA : TEST_Op<"either_op_a"> {
+def TestEitherOpA : TEST_PatternOp<"either_op_a"> {
   let arguments = (ins AnyInteger:$arg0, AnyInteger:$arg1, AnyInteger:$arg2);
   let results = (outs I32:$output);
 }
 
-def TestEitherOpB : TEST_Op<"either_op_b"> {
+def TestEitherOpB : TEST_PatternOp<"either_op_b"> {
   let arguments = (ins AnyInteger:$arg0, AnyInteger:$arg1);
   let results = (outs I32:$output);
 }
 
-def TestEitherOpC : TEST_Op<"either_op_c"> {
+def TestEitherOpC : TEST_PatternOp<"either_op_c"> {
   let arguments = (ins AnyI32Attr:$attr, AnyInteger:$arg0, AnyInteger:$arg1);
   let results = (outs I32:$output);
 }
@@ -2228,12 +2261,12 @@ def : Pat<(TestEitherOpA (either (TestEitherOpB I32:$arg1, $_),
 def : Pat<(TestEitherOpC ConstantAttr<I32Attr, "0">, (either $arg1, I32:$arg2)),
           (TestEitherOpB $arg1, $arg2)>;
 
-def TestEitherHelperOpA : TEST_Op<"either_helper_op_a"> {
+def TestEitherHelperOpA : TEST_PatternOp<"either_helper_op_a"> {
   let arguments = (ins I32:$arg0);
   let results = (outs I32:$output);
 }
 
-def TestEitherHelperOpB : TEST_Op<"either_helper_op_b"> {
+def TestEitherHelperOpB : TEST_PatternOp<"either_helper_op_b"> {
   let arguments = (ins I32:$arg0);
   let results = (outs I32:$output);
 }
@@ -2269,13 +2302,13 @@ def : Pat<(TestLocationSrcNoResOp:$loc
 // Test Patterns (Type Builders)
 //===----------------------------------------------------------------------===//
 
-def SourceOp : TEST_Op<"source_op"> {
+def SourceOp : TEST_PatternOp<"source_op"> {
   let arguments = (ins AnyInteger:$arg, AnyI32Attr:$tag);
   let results = (outs AnyInteger);
 }
 
 // An op without return type deduction.
-def OpX : TEST_Op<"op_x"> {
+def OpX : TEST_PatternOp<"op_x"> {
   let arguments = (ins AnyInteger:$input);
   let results = (outs AnyInteger);
 }
@@ -2294,12 +2327,12 @@ def : Pat<(SourceOp $val, ConstantAttr<I32Attr, "22">:$attr),
 def MakeI64Type : NativeCodeCall<"$_builder.getI64Type()">;
 def MakeI32Type : NativeCodeCall<"$_builder.getI32Type()">;
 
-def OneToTwo : TEST_Op<"one_to_two"> {
+def OneToTwo : TEST_PatternOp<"one_to_two"> {
   let arguments = (ins AnyInteger);
   let results = (outs AnyInteger, AnyInteger);
 }
 
-def TwoToOne : TEST_Op<"two_to_one"> {
+def TwoToOne : TEST_PatternOp<"two_to_one"> {
   let arguments = (ins AnyInteger, AnyInteger);
   let results = (outs AnyInteger);
 }
@@ -2332,6 +2365,7 @@ def : Pat<(SourceOp $val, ConstantAttr<I32Attr, "66">:$attr),
 def Test_LegalizerEnum_Success : ConstantStrAttr<StrAttr, "Success">;
 def Test_LegalizerEnum_Failure : ConstantStrAttr<StrAttr, "Failure">;
 
+let partition = Test_ConversionPartition in {
 def ILLegalOpA : TEST_Op<"illegal_op_a">, Results<(outs I32)>;
 def ILLegalOpB : TEST_Op<"illegal_op_b">, Results<(outs I32)>;
 def ILLegalOpC : TEST_Op<"illegal_op_c">, Results<(outs I32)>;
@@ -2375,6 +2409,7 @@ def IllegalOpWithRegion : TEST_Op<"illegal_op_with_region"> {
     }]>];
 }
 def IllegalOpWithRegionAnchor : TEST_Op<"illegal_op_with_region_anchor">;
+} // let partition = Test_ConversionPartition
 
 // Check that smaller pattern depths are chosen, i.e. prioritize more direct
 // mappings.
@@ -2396,6 +2431,7 @@ def TestRewriteOp : TEST_Op<"rewrite">,
   Arguments<(ins AnyType)>, Results<(outs AnyType)>;
 def : Pat<(TestRewriteOp $input), (replaceWithValue $input)>;
 
+let partition = Test_ConversionPartition in {
 // Check that patterns can specify bounded recursion when rewriting.
 def TestRecursiveRewriteOp : TEST_Op<"recursive_rewrite"> {
   let arguments = (ins I64Attr:$depth);
@@ -2497,6 +2533,7 @@ def TestReturnWithIgnoredValueOp : TEST_Op<"return_with_ignored_value", [
 ]> {
   let arguments = (ins Variadic<AnyType>:$values, AnyType:$unwanted_value);
 }
+} // let partition = Test_ConversionPartition
 
 //===----------------------------------------------------------------------===//
 // Test parser.
@@ -2650,6 +2687,7 @@ def ArrayOfAttrOp : TEST_Op<"array_of_attr_op"> {
 // Test SideEffects
 //===----------------------------------------------------------------------===//
 
+let partition = Test_InterfacesPartition in {
 def SideEffectOp : TEST_Op<"side_effect_op",
     [DeclareOpInterfaceMethods<MemoryEffectsOpInterface>,
      DeclareOpInterfaceMethods<TestEffectOpInterface>]> {
@@ -3067,6 +3105,7 @@ def TestRegionTypeChangerOp : TEST_Op<"region_type_changer",
   let regions = (region SizedRegion<1>:$body);
   let assemblyFormat = "`(` $entries `)` $body `:` functional-type($entries, $results) attr-dict";
 }
+} // let partition = Test_InterfacesPartition
 
 //===----------------------------------------------------------------------===//
 // Test TableGen generated build() methods
@@ -3202,6 +3241,7 @@ def TableGenBuildOp10 : TEST_Op<"tblgen_build_10",
 // Test BufferPlacement
 //===----------------------------------------------------------------------===//
 
+let partition = Test_InterfacesPartition in {
 def GetTupleElementOp: TEST_Op<"get_tuple_element"> {
   let description = [{
     Test op that returns a specified element of the tuple.
@@ -3262,6 +3302,7 @@ def OpCrashLong : TEST_Op<"op_crash_long"> {
 def OpCrashShort : TEST_Op<"op_crash_short"> {
   let results = (outs I32);
 }
+} // let partition = Test_InterfacesPartition
 
 def : Pat<(OpCrashLong $_, $_, $_), (OpCrashShort)>;
 
@@ -3269,6 +3310,7 @@ def : Pat<(OpCrashLong $_, $_, $_), (OpCrashShort)>;
 // Test DestinationStyleOpInterface.
 //===----------------------------------------------------------------------===//
 
+let partition = Test_InterfacesPartition in {
 def TestDestinationStyleOp :
     TEST_Op<"destination_style_op", [
       DestinationStyleOpInterface,
@@ -3481,6 +3523,7 @@ def TestNVVMRequiresSMArchOrFamilyCondOp :
   let arguments = (ins );
   let assemblyFormat = "attr-dict";
 }
+} // let partition = Test_InterfacesPartition
 
 //===----------------------------------------------------------------------===//
 // Test Ops with Default-Valued String Attributes
@@ -3540,6 +3583,7 @@ def TestResource : Resource<"TestResource">;
 def ParameterizedTestResource : Resource<"TestResource",
     [{::mlir::StringAttr::get(getContext(), "test parameter")}]>;
 
+let partition = Test_InterfacesPartition in {
 def TestEffectsOpA : TEST_Op<"op_with_effects_a"> {
   let arguments = (ins
     Arg<Variadic<AnyMemRef>, "", [MemRead]>,
@@ -3570,6 +3614,7 @@ def TestEffectsWrite : TEST_Op<"op_with_memwrite",
 def TestEffectsResult : TEST_Op<"test_effects_result"> {
   let results = (outs Res<I32, "", [MemAlloc, MemWrite]>);
 }
+} // let partition = Test_InterfacesPartition
 
 //===----------------------------------------------------------------------===//
 // Test Ops with verifiers
@@ -3610,6 +3655,7 @@ def TestGraphLoopOp : TEST_Op<"graph_loop",
 //===----------------------------------------------------------------------===//
 def InferIntRangeType : AnyTypeOf<[AnyInteger, Index, VectorOfNonZeroRankOf<[AnyInteger, Index]>]>;
 
+let partition = Test_InterfacesPartition in {
 def TestWithBoundsOp : TEST_Op<"with_bounds",
                           [DeclareOpInterfaceMethods<InferIntRangeInterface, ["inferResultRanges"]>,
                            NoMemoryEffect]> {
@@ -3755,6 +3801,7 @@ def RecursivelySpeculatableOp : TEST_Op<"recursively_speculatable_op", [
   let results = (outs I32:$result);
   let regions = (region SizedRegion<1>:$body);
 }
+} // let partition = Test_InterfacesPartition
 
 //===---------------------------------------------------------------------===//
 // Test CSE
@@ -3826,7 +3873,7 @@ def TestVersionedOpC : TEST_Op<"versionedC"> {
 
 
 // Op with a properties struct defined inline.
-def TestOpWithProperties : TEST_Op<"with_properties"> {
+def TestOpWithProperties : TEST_PropOp<"with_properties"> {
   let assemblyFormat = [{
     `a` `=` $a `,`
     `b` `=` $b `,`
@@ -3845,13 +3892,13 @@ def TestOpWithProperties : TEST_Op<"with_properties"> {
 }
 
 def TestOpWithPropertiesAndAttr
-  : TEST_Op<"with_properties_and_attr"> {
+  : TEST_PropOp<"with_properties_and_attr"> {
   let assemblyFormat = "$lhs prop-dict attr-dict";
 
   let arguments = (ins I32Attr:$lhs, IntProp<"int64_t">:$rhs);
 }
 
-def TestOpWithCustomPropDict : TEST_Op<"with_custom_prop_dict"> {
+def TestOpWithCustomPropDict : TEST_PropOp<"with_custom_prop_dict"> {
   let assemblyFormat = "prop-dict attr-dict";
 
   let arguments = (ins
@@ -3865,7 +3912,7 @@ def TestOpWithCustomPropDict : TEST_Op<"with_custom_prop_dict"> {
 }
 
 def TestOpWithCustomAttrPropDict
-    : TEST_Op<"with_custom_attr_prop_dict"> {
+    : TEST_PropOp<"with_custom_attr_prop_dict"> {
   let assemblyFormat = "prop-dict attr-dict";
   let arguments = (ins
     TestEnumAttr:$attr,
@@ -3875,13 +3922,13 @@ def TestOpWithCustomAttrPropDict
 }
 
 def TestOpWithCustomBitEnumAttrPropDict
-    : TEST_Op<"with_custom_bit_enum_attr_prop_dict"> {
+    : TEST_PropOp<"with_custom_bit_enum_attr_prop_dict"> {
   let assemblyFormat = "prop-dict attr-dict";
   let arguments = (ins TestBitEnumAttr:$flags, I64Attr:$next);
 }
 
 def TestOpWithPropertiesAndInferredType
-  : TEST_Op<"with_properties_and_inferred_type", [
+  : TEST_PropOp<"with_properties_and_inferred_type", [
     DeclareOpInterfaceMethods<InferTypeOpInterface>
   ]> {
   let assemblyFormat = "$lhs prop-dict attr-dict";
@@ -3900,7 +3947,7 @@ def MyStructProperty : Property<"MyPropStruct"> {
   let optionalParser = "return std::nullopt;";
 }
 
-def TestOpWithWrappedProperties : TEST_Op<"with_wrapped_properties"> {
+def TestOpWithWrappedProperties : TEST_PropOp<"with_wrapped_properties"> {
   let assemblyFormat = "prop-dict attr-dict";
   let arguments = (ins
     MyStructProperty:$prop
@@ -3908,7 +3955,7 @@ def TestOpWithWrappedProperties : TEST_Op<"with_wrapped_properties"> {
 }
 
 def TestOpWithDefaultWrappedProperties
-    : TEST_Op<"with_default_wrapped_properties"> {
+    : TEST_PropOp<"with_default_wrapped_properties"> {
   let assemblyFormat = "prop-dict attr-dict";
   let arguments = (ins
     DefaultValuedProp<MyStructProperty, "MyPropStruct{}">:$prop
@@ -3958,7 +4005,7 @@ def MyStructArrayProperty
 }
 
 def TestOpWithWrappedArrayProperties
-    : TEST_Op<"with_wrapped_array_properties"> {
+    : TEST_PropOp<"with_wrapped_array_properties"> {
   let assemblyFormat = "prop-dict attr-dict";
   let arguments = (ins MyStructArrayProperty:$prop);
 }
@@ -4154,7 +4201,7 @@ def KeyValueSpecializedOptionalProperty
 }
 
 def TestOpWithKeyValueParserBoundaries
-    : TEST_Op<"with_key_value_parser_boundaries"> {
+    : TEST_PropOp<"with_key_value_parser_boundaries"> {
   let assemblyFormat = "prop-dict attr-dict";
   let arguments = (ins
     KeyValueListProperty:$values,
@@ -4173,25 +4220,25 @@ def MyStructProperty2 : Property<"MyPropStruct"> {
   let convertFromAttribute = "return MyPropStruct::setFromAttr($_storage, $_attr, $_diag);";
 }
 
-def TestOpWithWrappedProperties2 : TEST_Op<"with_wrapped_properties2"> {
+def TestOpWithWrappedProperties2 : TEST_PropOp<"with_wrapped_properties2"> {
   let assemblyFormat = "prop-dict attr-dict";
   let arguments = (ins
     MyStructProperty2:$prop
   );
 }
 
-def TestOpWithEmptyProperties : TEST_Op<"empty_properties"> {
+def TestOpWithEmptyProperties : TEST_PropOp<"empty_properties"> {
   let assemblyFormat = "prop-dict attr-dict";
   let arguments = (ins);
 }
 
-def TestOpUsingPropertyInCustom : TEST_Op<"using_property_in_custom"> {
+def TestOpUsingPropertyInCustom : TEST_PropOp<"using_property_in_custom"> {
   let assemblyFormat = "custom<UsingPropertyInCustom>($prop) attr-dict";
   let arguments = (ins IntArrayProp<I64Prop>:$prop);
 }
 
 def TestOpUsingPropertyInCustomAndOther
-  : TEST_Op<"using_property_in_custom_and_other"> {
+  : TEST_PropOp<"using_property_in_custom_and_other"> {
   let assemblyFormat = "custom<UsingPropertyInCustom>($prop) prop-dict attr-dict";
   let arguments = (ins
     IntArrayProp<I64Prop>:$prop,
@@ -4199,7 +4246,7 @@ def TestOpUsingPropertyInCustomAndOther
   );
 }
 
-def TestOpWithVariadicSegmentProperties : TEST_Op<"variadic_segment_prop",
+def TestOpWithVariadicSegmentProperties : TEST_PropOp<"variadic_segment_prop",
     [AttrSizedOperandSegments, AttrSizedResultSegments]> {
   let arguments = (ins Variadic<I64>:$a1, Variadic<I64>:$a2);
   let results = (outs Variadic<I64>:$b1, Variadic<I64>:$b2);
@@ -4215,7 +4262,7 @@ def TestOpWithVariadicSegmentProperties : TEST_Op<"variadic_segment_prop",
 // `<{...}>` properties dictionary (since there is no other way to recover the
 // segment sizes on re-parse), so this op exercises the parser's ability to
 // read those trait-injected properties back out of `prop-dict`.
-def TestOpWithBulkTypesAndSegmentProperties : TEST_Op<"variadic_segment_prop_bulk_type",
+def TestOpWithBulkTypesAndSegmentProperties : TEST_PropOp<"variadic_segment_prop_bulk_type",
     [AttrSizedOperandSegments, AttrSizedResultSegments]> {
   let arguments = (ins Variadic<I64>:$a1, Variadic<I64>:$a2);
   let results = (outs Variadic<I64>:$b1, Variadic<I64>:$b2);
@@ -4224,7 +4271,8 @@ def TestOpWithBulkTypesAndSegmentProperties : TEST_Op<"variadic_segment_prop_bul
   }];
 }
 
-def TestOpUsingPropertyRefInCustom : TEST_Op<"using_property_ref_in_custom"> {
+def TestOpUsingPropertyRefInCustom :
+    TEST_PropOp<"using_property_ref_in_custom"> {
   let assemblyFormat = "custom<IntProperty>($first) `+` custom<SumProperty>($second, ref($first)) attr-dict";
   let arguments = (ins IntProp<"int64_t">:$first, IntProp<"int64_t">:$second);
 }
@@ -4236,7 +4284,7 @@ def IntPropertyWithWorseBytecode : Property<"int64_t"> {
 }
 
 def TestOpUsingIntPropertyWithWorseBytecode
-    : TEST_Op<"using_int_property_with_worse_bytecode"> {
+    : TEST_PropOp<"using_int_property_with_worse_bytecode"> {
   let arguments = (ins IntPropertyWithWorseBytecode:$value);
 }
 
@@ -4255,7 +4303,7 @@ def PropertiesWithCustomPrint : Property<"PropertiesWithCustomPrint"> {
   }];
 }
 
-def TestOpWithNiceProperties : TEST_Op<"with_nice_properties"> {
+def TestOpWithNiceProperties : TEST_PropOp<"with_nice_properties"> {
   let hasCustomPropertiesPrinter = 1;
   let assemblyFormat = "prop-dict attr-dict";
   let arguments = (ins
@@ -4320,7 +4368,7 @@ def VersionedProperties : Property<"VersionedProperties"> {
   }];
 }
 
-def TestOpWithVersionedProperties : TEST_Op<"with_versioned_properties"> {
+def TestOpWithVersionedProperties : TEST_PropOp<"with_versioned_properties"> {
   let hasCustomPropertiesPrinter = 1;
   let assemblyFormat = "prop-dict attr-dict";
   let arguments = (ins
@@ -4356,7 +4404,7 @@ def TestOpWithVersionedProperties : TEST_Op<"with_versioned_properties"> {
   }];
 }
 
-def TestOpWithDefaultValuedProperties : TEST_Op<"with_default_valued_properties"> {
+def TestOpWithDefaultValuedProperties : TEST_PropOp<"with_default_valued_properties"> {
   let assemblyFormat = [{
     ($a^) : (`na`)?
     ($b^)?
@@ -4370,7 +4418,7 @@ def TestOpWithDefaultValuedProperties : TEST_Op<"with_default_valued_properties"
     UnitProp:$unit);
 }
 
-def TestOpWithOptionalProperties : TEST_Op<"with_optional_properties"> {
+def TestOpWithOptionalProperties : TEST_PropOp<"with_optional_properties"> {
   let assemblyFormat = [{
     (`anAttr` `=` $anAttr^)?
     (`simple` `=` $simple^)?
@@ -4399,7 +4447,7 @@ def TestOpWithOptionalProperties : TEST_Op<"with_optional_properties"> {
     OptionalProp<UnitProp>:$maybeUnit);
 }
 
-def TestOpWithArrayProperties : TEST_Op<"with_array_properties"> {
+def TestOpWithArrayProperties : TEST_PropOp<"with_array_properties"> {
   let assemblyFormat = [{
     `ints` `=` $ints
     `strings` `=` $strings
@@ -4429,7 +4477,7 @@ class NonEmptyArray<Property p> : ConfinedProp
     <ArrayProp<p>, Neg<CPred<"$_self.empty()">>,
     "non-empty array of " # p.summary>;
 
-def OpWithPropertyPredicates : TEST_Op<"op_with_property_predicates"> {
+def OpWithPropertyPredicates : TEST_PropOp<"op_with_property_predicates"> {
   let arguments = (ins
     NonNegativeI64Prop:$scalar,
     OptionalProp<NonNegativeI64Prop>:$optional,
@@ -4446,7 +4494,7 @@ def OpWithPropertyPredicates : TEST_Op<"op_with_property_predicates"> {
   let assemblyFormat = "attr-dict prop-dict";
 }
 
-def TestPropPatternOp1 : TEST_Op<"prop_pattern_op_1"> {
+def TestPropPatternOp1 : TEST_PropOp<"prop_pattern_op_1"> {
   let arguments = (ins
     StringProp:$tag,
     I64Prop:$val,
@@ -4456,7 +4504,7 @@ def TestPropPatternOp1 : TEST_Op<"prop_pattern_op_1"> {
   let assemblyFormat = "$tag $val $cond attr-dict";
 }
 
-def TestPropPatternOp2 : TEST_Op<"prop_pattern_op_2"> {
+def TestPropPatternOp2 : TEST_PropOp<"prop_pattern_op_2"> {
   let arguments = (ins
     I32:$input,
     StringProp:$tag
@@ -4482,6 +4530,7 @@ def : Pat<
 // Test Dataflow
 //===----------------------------------------------------------------------===//
 
+let partition = Test_InterfacesPartition in {
 def TestCallAndStoreOp : TEST_Op<"call_and_store",
     [DeclareOpInterfaceMethods<CallOpInterface>]> {
   let arguments = (ins
@@ -4892,6 +4941,7 @@ def TestDummyCastOp : TEST_Op<"dummy_cast_op", []> {
   );
   let assemblyFormat = "$source attr-dict `:` type($source) `to` type($dest)";
 }
+} // let partition = Test_InterfacesPartition
 
 //===----------------------------------------------------------------------===//
 // Test assembly format references
diff --git a/mlir/test/lib/Dialect/Test/TestOps.cpp b/mlir/test/lib/Dialect/Test/TestOpsAttributes.cpp
similarity index 65%
rename from mlir/test/lib/Dialect/Test/TestOps.cpp
rename to mlir/test/lib/Dialect/Test/TestOpsAttributes.cpp
index 47d5b1b19121ef..b0bbf1b053ac0a 100644
--- a/mlir/test/lib/Dialect/Test/TestOps.cpp
+++ b/mlir/test/lib/Dialect/Test/TestOpsAttributes.cpp
@@ -1,4 +1,4 @@
-//===- TestOps.cpp - MLIR Test Dialect Operations ------------------------===//
+//===- TestOpsAttributes.cpp - Test dialect ops in partition `Attributes` -===//
 //
 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 // See https://llvm.org/LICENSE.txt for license information.
@@ -6,12 +6,11 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestOps.h"
-#include "TestDialect.h"
+#include "TestOpsAttributes.h"
 #include "TestFormatUtils.h"
-#include "mlir/Dialect/Arith/IR/Arith.h"
 
 using namespace mlir;
 using namespace test;
 
-#include "TestOps.cpp.inc"
+#define GET_OP_CLASSES
+#include "TestOpsAttributes.cpp.inc"
diff --git a/mlir/test/lib/Dialect/Test/TestOpsAttributes.h b/mlir/test/lib/Dialect/Test/TestOpsAttributes.h
new file mode 100644
index 00000000000000..039313b24931ab
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsAttributes.h
@@ -0,0 +1,17 @@
+//===- TestOpsAttributes.h - Test dialect ops in `Attributes` ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_TEST_DIALECT_TEST_TESTOPSATTRIBUTES_H
+#define MLIR_TEST_DIALECT_TEST_TESTOPSATTRIBUTES_H
+
+#include "TestDialect.h"
+
+#define GET_OP_CLASSES
+#include "TestOpsAttributes.h.inc"
+
+#endif // MLIR_TEST_DIALECT_TEST_TESTOPSATTRIBUTES_H
diff --git a/mlir/test/lib/Dialect/Test/TestOpsConversion.cpp b/mlir/test/lib/Dialect/Test/TestOpsConversion.cpp
new file mode 100644
index 00000000000000..0547b852821fec
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsConversion.cpp
@@ -0,0 +1,15 @@
+//===- TestOpsConversion.cpp - Test dialect ops in partition `Conversion` -===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "TestOpsConversion.h"
+
+using namespace mlir;
+using namespace test;
+
+#define GET_OP_CLASSES
+#include "TestOpsConversion.cpp.inc"
diff --git a/mlir/test/lib/Dialect/Test/TestOpsConversion.h b/mlir/test/lib/Dialect/Test/TestOpsConversion.h
new file mode 100644
index 00000000000000..a46e4dee6a94bf
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsConversion.h
@@ -0,0 +1,17 @@
+//===- TestOpsConversion.h - Test dialect ops in `Conversion` ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_TEST_DIALECT_TEST_TESTOPSCONVERSION_H
+#define MLIR_TEST_DIALECT_TEST_TESTOPSCONVERSION_H
+
+#include "TestDialect.h"
+
+#define GET_OP_CLASSES
+#include "TestOpsConversion.h.inc"
+
+#endif // MLIR_TEST_DIALECT_TEST_TESTOPSCONVERSION_H
diff --git a/mlir/test/lib/Dialect/Test/TestOpsCore.cpp b/mlir/test/lib/Dialect/Test/TestOpsCore.cpp
new file mode 100644
index 00000000000000..2f6da308774291
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsCore.cpp
@@ -0,0 +1,19 @@
+//===- TestOpsCore.cpp - Test dialect ops in partition `Core` -------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "TestOpsCore.h"
+#include "TestFormatUtils.h"
+// Some implicit terminators of `Core` ops are in other partitions.
+#include "TestOpsInterfaces.h"
+#include "TestOpsTraits.h"
+
+using namespace mlir;
+using namespace test;
+
+#define GET_OP_CLASSES
+#include "TestOpsCore.cpp.inc"
diff --git a/mlir/test/lib/Dialect/Test/TestOpsCore.h b/mlir/test/lib/Dialect/Test/TestOpsCore.h
new file mode 100644
index 00000000000000..fbcf4fced9d35c
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsCore.h
@@ -0,0 +1,18 @@
+//===- TestOpsCore.h - Test dialect ops in partition `Core` -----*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_TEST_DIALECT_TEST_TESTOPSCORE_H
+#define MLIR_TEST_DIALECT_TEST_TESTOPSCORE_H
+
+#include "TestDialect.h"
+#include "mlir/Interfaces/FunctionInterfaces.h"
+
+#define GET_OP_CLASSES
+#include "TestOpsCore.h.inc"
+
+#endif // MLIR_TEST_DIALECT_TEST_TESTOPSCORE_H
diff --git a/mlir/test/lib/Dialect/Test/TestOpsInterfaces.cpp b/mlir/test/lib/Dialect/Test/TestOpsInterfaces.cpp
new file mode 100644
index 00000000000000..31a53af4bf383f
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsInterfaces.cpp
@@ -0,0 +1,16 @@
+//===- TestOpsInterfaces.cpp - Test dialect ops in partition `Interfaces` -===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "TestOpsInterfaces.h"
+#include "TestFormatUtils.h"
+
+using namespace mlir;
+using namespace test;
+
+#define GET_OP_CLASSES
+#include "TestOpsInterfaces.cpp.inc"
diff --git a/mlir/test/lib/Dialect/Test/TestOpsInterfaces.h b/mlir/test/lib/Dialect/Test/TestOpsInterfaces.h
new file mode 100644
index 00000000000000..b9e614232f9a03
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsInterfaces.h
@@ -0,0 +1,90 @@
+//===- TestOpsInterfaces.h - Test dialect ops in `Interfaces` ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_TEST_DIALECT_TEST_TESTOPSINTERFACES_H
+#define MLIR_TEST_DIALECT_TEST_TESTOPSINTERFACES_H
+
+#include "TestDialect.h"
+#include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
+#include "mlir/Dialect/LLVMIR/NVVMRequiresSMTraits.h"
+#include "mlir/Interfaces/DataLayoutInterfaces.h"
+#include "mlir/Interfaces/DestinationStyleOpInterface.h"
+#include "mlir/Interfaces/MemorySlotInterfaces.h"
+#include "mlir/Interfaces/TilingInterface.h"
+
+namespace test {
+//===----------------------------------------------------------------------===//
+// TestResource
+//===----------------------------------------------------------------------===//
+
+/// A test resource for side effects (under DefaultResource).
+struct TestResource : public mlir::SideEffects::Resource::Base<
+                          TestResource, mlir::SideEffects::DefaultResource> {
+  llvm::StringRef getName() const final { return "<Test>"; }
+  mlir::SideEffects::Resource *getParent() const override {
+    return mlir::SideEffects::DefaultResource::get();
+  }
+};
+
+/// A test resource that is a root (disjoint from DefaultResource).
+struct TestNonAddressableResource
+    : public mlir::SideEffects::Resource::Base<TestNonAddressableResource> {
+  llvm::StringRef getName() const final { return "<TestNonAddressable>"; }
+  bool isAddressable() const override { return false; }
+};
+
+/// Two disjoint sub-resources (roots) for testing sibling disjointness.
+struct TestNonAddressableSubResourceA
+    : public mlir::SideEffects::Resource::Base<TestNonAddressableSubResourceA> {
+  TestNonAddressableSubResourceA() = default;
+  llvm::StringRef getName() const override {
+    return "TestNonAddressableSubResourceA";
+  }
+  bool isAddressable() const override { return false; }
+
+protected:
+  TestNonAddressableSubResourceA(mlir::TypeID id) : Base(id) {}
+};
+
+struct TestNonAddressableSubResourceB
+    : public mlir::SideEffects::Resource::Base<TestNonAddressableSubResourceB> {
+  TestNonAddressableSubResourceB() = default;
+  llvm::StringRef getName() const override {
+    return "TestNonAddressableSubResourceB";
+  }
+  bool isAddressable() const override { return false; }
+
+protected:
+  TestNonAddressableSubResourceB(mlir::TypeID id) : Base(id) {}
+};
+
+struct TestNonAddressableResourceA
+    : public mlir::SideEffects::Resource::Base<TestNonAddressableResourceA,
+                                               TestNonAddressableSubResourceA> {
+  llvm::StringRef getName() const final { return "<TestNonAddressableA>"; }
+  bool isAddressable() const override { return false; }
+  mlir::SideEffects::Resource *getParent() const override {
+    return TestNonAddressableSubResourceA::get();
+  }
+};
+
+struct TestNonAddressableResourceB
+    : public mlir::SideEffects::Resource::Base<TestNonAddressableResourceB,
+                                               TestNonAddressableSubResourceB> {
+  llvm::StringRef getName() const final { return "<TestNonAddressableB>"; }
+  bool isAddressable() const override { return false; }
+  mlir::SideEffects::Resource *getParent() const override {
+    return TestNonAddressableSubResourceB::get();
+  }
+};
+} // namespace test
+
+#define GET_OP_CLASSES
+#include "TestOpsInterfaces.h.inc"
+
+#endif // MLIR_TEST_DIALECT_TEST_TESTOPSINTERFACES_H
diff --git a/mlir/test/lib/Dialect/Test/TestOpsPatterns.cpp b/mlir/test/lib/Dialect/Test/TestOpsPatterns.cpp
new file mode 100644
index 00000000000000..a3423bda38a02d
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsPatterns.cpp
@@ -0,0 +1,15 @@
+//===- TestOpsPatterns.cpp - Test dialect ops in partition `Patterns` -----===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "TestOpsPatterns.h"
+
+using namespace mlir;
+using namespace test;
+
+#define GET_OP_CLASSES
+#include "TestOpsPatterns.cpp.inc"
diff --git a/mlir/test/lib/Dialect/Test/TestOpsPatterns.h b/mlir/test/lib/Dialect/Test/TestOpsPatterns.h
new file mode 100644
index 00000000000000..3df3f7fb6af166
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsPatterns.h
@@ -0,0 +1,17 @@
+//===- TestOpsPatterns.h - Test dialect ops in `Patterns` -------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_TEST_DIALECT_TEST_TESTOPSPATTERNS_H
+#define MLIR_TEST_DIALECT_TEST_TESTOPSPATTERNS_H
+
+#include "TestDialect.h"
+
+#define GET_OP_CLASSES
+#include "TestOpsPatterns.h.inc"
+
+#endif // MLIR_TEST_DIALECT_TEST_TESTOPSPATTERNS_H
diff --git a/mlir/test/lib/Dialect/Test/TestOpsProperties.cpp b/mlir/test/lib/Dialect/Test/TestOpsProperties.cpp
new file mode 100644
index 00000000000000..81becab1e83857
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsProperties.cpp
@@ -0,0 +1,16 @@
+//===- TestOpsProperties.cpp - Test dialect ops in partition `Properties` -===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "TestOpsProperties.h"
+#include "TestFormatUtils.h"
+
+using namespace mlir;
+using namespace test;
+
+#define GET_OP_CLASSES
+#include "TestOpsProperties.cpp.inc"
diff --git a/mlir/test/lib/Dialect/Test/TestOpsProperties.h b/mlir/test/lib/Dialect/Test/TestOpsProperties.h
new file mode 100644
index 00000000000000..d597a3f725f875
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsProperties.h
@@ -0,0 +1,154 @@
+//===- TestOpsProperties.h - Test dialect ops in `Properties` ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_TEST_DIALECT_TEST_TESTOPSPROPERTIES_H
+#define MLIR_TEST_DIALECT_TEST_TESTOPSPROPERTIES_H
+
+#include "TestDialect.h"
+#include "llvm/ADT/SmallVector.h"
+#include <optional>
+
+namespace test {
+// Keep this type distinct from SmallVector<int32_t>, which another test parser
+// uses with the generic FieldParser specialization in a separate translation
+// unit.
+struct KeyValueSpecializedList : llvm::SmallVector<int32_t> {
+  using llvm::SmallVector<int32_t>::SmallVector;
+};
+} // namespace test
+
+namespace mlir {
+// Self-delimiting full specializations remain usable in a keyed prop-dict even
+// when their storage type is optional or container-like.
+template <>
+struct FieldParser<test::KeyValueSpecializedList> {
+  static FailureOr<test::KeyValueSpecializedList> parse(AsmParser &parser) {
+    test::KeyValueSpecializedList values;
+    if (parser.parseCommaSeparatedList(AsmParser::Delimiter::Square, [&]() {
+          int32_t value;
+          if (parser.parseInteger(value))
+            return failure();
+          values.push_back(value);
+          return success();
+        }))
+      return failure();
+    return values;
+  }
+};
+
+template <>
+struct FieldParser<std::optional<int16_t>> {
+  static FailureOr<std::optional<int16_t>> parse(AsmParser &parser) {
+    if (succeeded(parser.parseOptionalKeyword("none")))
+      return std::optional<int16_t>{};
+    int16_t value;
+    if (parser.parseKeyword("some") || parser.parseLess() ||
+        parser.parseInteger(value) || parser.parseGreater())
+      return failure();
+    return std::optional<int16_t>{value};
+  }
+};
+} // namespace mlir
+
+namespace test {
+//===----------------------------------------------------------------------===//
+// PropertiesWithCustomPrint
+//===----------------------------------------------------------------------===//
+
+struct PropertiesWithCustomPrint {
+  /// A shared_ptr to a const object is safe: it is equivalent to a value-based
+  /// member. Here the label will be deallocated when the last operation
+  /// refering to it is destroyed. However there is no pool-allocation: this is
+  /// offloaded to the client.
+  std::shared_ptr<const std::string> label;
+  int value;
+  bool operator==(const PropertiesWithCustomPrint &rhs) const {
+    return value == rhs.value && *label == *rhs.label;
+  }
+};
+
+llvm::LogicalResult setPropertiesFromAttribute(
+    PropertiesWithCustomPrint &prop, mlir::Attribute attr,
+    llvm::function_ref<mlir::InFlightDiagnostic()> emitError);
+mlir::DictionaryAttr
+getPropertiesAsAttribute(mlir::MLIRContext *ctx,
+                         const PropertiesWithCustomPrint &prop);
+llvm::hash_code computeHash(const PropertiesWithCustomPrint &prop);
+void customPrintProperties(mlir::OpAsmPrinter &p,
+                           const PropertiesWithCustomPrint &prop);
+mlir::ParseResult customParseProperties(mlir::OpAsmParser &parser,
+                                        PropertiesWithCustomPrint &prop);
+
+//===----------------------------------------------------------------------===//
+// MyPropStruct
+//===----------------------------------------------------------------------===//
+namespace test_properties {
+class MyPropStruct {
+public:
+  std::string content;
+  // These three methods are invoked through the  `MyStructProperty` wrapper
+  // defined in TestOps.td
+  mlir::Attribute asAttribute(mlir::MLIRContext *ctx) const;
+  static llvm::LogicalResult
+  setFromAttr(MyPropStruct &prop, mlir::Attribute attr,
+              llvm::function_ref<mlir::InFlightDiagnostic()> emitError);
+  llvm::hash_code hash() const;
+  bool operator==(const MyPropStruct &rhs) const {
+    return content == rhs.content;
+  }
+};
+inline llvm::hash_code hash_value(const MyPropStruct &S) { return S.hash(); }
+} // namespace test_properties
+using test_properties::MyPropStruct;
+
+llvm::LogicalResult readFromMlirBytecode(mlir::DialectBytecodeReader &reader,
+                                         MyPropStruct &prop);
+void writeToMlirBytecode(mlir::DialectBytecodeWriter &writer,
+                         MyPropStruct &prop);
+
+//===----------------------------------------------------------------------===//
+// VersionedProperties
+//===----------------------------------------------------------------------===//
+
+struct VersionedProperties {
+  // For the sake of testing, assume that this object was associated to version
+  // 1.2 of the test dialect when having only one int value. In the current
+  // version 2.0, the property has two values. We also assume that the class is
+  // upgrade-able if value2 = 0.
+  int value1;
+  int value2;
+  bool operator==(const VersionedProperties &rhs) const {
+    return value1 == rhs.value1 && value2 == rhs.value2;
+  }
+};
+
+llvm::LogicalResult setPropertiesFromAttribute(
+    VersionedProperties &prop, mlir::Attribute attr,
+    llvm::function_ref<mlir::InFlightDiagnostic()> emitError);
+mlir::DictionaryAttr getPropertiesAsAttribute(mlir::MLIRContext *ctx,
+                                              const VersionedProperties &prop);
+llvm::hash_code computeHash(const VersionedProperties &prop);
+void customPrintProperties(mlir::OpAsmPrinter &p,
+                           const VersionedProperties &prop);
+mlir::ParseResult customParseProperties(mlir::OpAsmParser &parser,
+                                        VersionedProperties &prop);
+
+//===----------------------------------------------------------------------===//
+// Bytecode Support
+//===----------------------------------------------------------------------===//
+
+llvm::LogicalResult readFromMlirBytecode(mlir::DialectBytecodeReader &reader,
+                                         llvm::MutableArrayRef<int64_t> prop);
+void writeToMlirBytecode(mlir::DialectBytecodeWriter &writer,
+                         llvm::ArrayRef<int64_t> prop);
+} // namespace test
+
+#define GET_OP_CLASSES
+#include "TestOpsProperties.h.inc"
+
+#endif // MLIR_TEST_DIALECT_TEST_TESTOPSPROPERTIES_H
diff --git a/mlir/test/lib/Dialect/Test/TestOpsSyntax.cpp b/mlir/test/lib/Dialect/Test/TestOpsSyntax.cpp
index 3a971e462e2b8a..4c122c7dc34dc7 100644
--- a/mlir/test/lib/Dialect/Test/TestOpsSyntax.cpp
+++ b/mlir/test/lib/Dialect/Test/TestOpsSyntax.cpp
@@ -8,7 +8,8 @@
 
 #include "TestOpsSyntax.h"
 #include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsConversion.h"
+#include "TestOpsCore.h"
 #include "mlir/IR/OpImplementation.h"
 #include "llvm/Support/Base64.h"
 
@@ -509,10 +510,3 @@ static void printCustomOperationNameEntry(OpAsmPrinter &p, Operation *op,
 
 #define GET_OP_CLASSES
 #include "TestOpsSyntax.cpp.inc"
-
-void TestDialect::registerOpsSyntax() {
-  addOperations<
-#define GET_OP_LIST
-#include "TestOpsSyntax.cpp.inc"
-      >();
-}
diff --git a/mlir/test/lib/Dialect/Test/TestOpsSyntax.td b/mlir/test/lib/Dialect/Test/TestOpsSyntax.td
index f2d6ba3c5855e5..a81766aaa2b9c1 100644
--- a/mlir/test/lib/Dialect/Test/TestOpsSyntax.td
+++ b/mlir/test/lib/Dialect/Test/TestOpsSyntax.td
@@ -16,8 +16,12 @@ include "TestTypeDefs.td"
 include "mlir/Interfaces/InferTypeOpInterface.td"
 include "mlir/IR/OpBase.td"
 
+// The ops of this file are generated separately from TestOps.td, so they are
+// all in `Syntax`, which TestOps.td does not use.
 class TEST_Op<string mnemonic, list<Trait> traits = []> :
-    Op<Test_Dialect, mnemonic, traits>;
+    Op<Test_Dialect, mnemonic, traits> {
+  let partition = Test_SyntaxPartition;
+}
 
 def WrappingRegionOp : TEST_Op<"wrapping_region",
     [SingleBlockImplicitTerminator<"TestReturnOp">]> {
diff --git a/mlir/test/lib/Dialect/Test/TestOpsTraits.cpp b/mlir/test/lib/Dialect/Test/TestOpsTraits.cpp
new file mode 100644
index 00000000000000..41ce5043d261f3
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsTraits.cpp
@@ -0,0 +1,15 @@
+//===- TestOpsTraits.cpp - Test dialect ops in partition `Traits` ---------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "TestOpsTraits.h"
+
+using namespace mlir;
+using namespace test;
+
+#define GET_OP_CLASSES
+#include "TestOpsTraits.cpp.inc"
diff --git a/mlir/test/lib/Dialect/Test/TestOpsTraits.h b/mlir/test/lib/Dialect/Test/TestOpsTraits.h
new file mode 100644
index 00000000000000..3b7606fb1ecb55
--- /dev/null
+++ b/mlir/test/lib/Dialect/Test/TestOpsTraits.h
@@ -0,0 +1,17 @@
+//===- TestOpsTraits.h - Test dialect ops in partition `Traits` -*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef MLIR_TEST_DIALECT_TEST_TESTOPSTRAITS_H
+#define MLIR_TEST_DIALECT_TEST_TESTOPSTRAITS_H
+
+#include "TestDialect.h"
+
+#define GET_OP_CLASSES
+#include "TestOpsTraits.h.inc"
+
+#endif // MLIR_TEST_DIALECT_TEST_TESTOPSTRAITS_H
diff --git a/mlir/test/lib/Dialect/Test/TestToLLVMIRTranslation.cpp b/mlir/test/lib/Dialect/Test/TestToLLVMIRTranslation.cpp
index 19624c71f841e1..6f3a610a4c2bb1 100644
--- a/mlir/test/lib/Dialect/Test/TestToLLVMIRTranslation.cpp
+++ b/mlir/test/lib/Dialect/Test/TestToLLVMIRTranslation.cpp
@@ -10,8 +10,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsCore.h"
 #include "mlir/IR/Builders.h"
 #include "mlir/IR/BuiltinAttributes.h"
 #include "mlir/IR/BuiltinOps.h"
diff --git a/mlir/test/lib/Dialect/Test/TestTraits.cpp b/mlir/test/lib/Dialect/Test/TestTraits.cpp
index d8763f562cbefc..ca111c7648fb2a 100644
--- a/mlir/test/lib/Dialect/Test/TestTraits.cpp
+++ b/mlir/test/lib/Dialect/Test/TestTraits.cpp
@@ -6,7 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestOps.h"
+#include "TestOpsPatterns.h"
 #include "mlir/Pass/Pass.h"
 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
 
diff --git a/mlir/test/lib/IR/TestBytecodeRoundtrip.cpp b/mlir/test/lib/IR/TestBytecodeRoundtrip.cpp
index d7e224f8b04ea9..e5db4c94452e2e 100644
--- a/mlir/test/lib/IR/TestBytecodeRoundtrip.cpp
+++ b/mlir/test/lib/IR/TestBytecodeRoundtrip.cpp
@@ -6,8 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsCore.h"
 #include "mlir/Bytecode/BytecodeReader.h"
 #include "mlir/Bytecode/BytecodeWriter.h"
 #include "mlir/IR/BuiltinOps.h"
diff --git a/mlir/test/lib/IR/TestClone.cpp b/mlir/test/lib/IR/TestClone.cpp
index b742b316c77126..7b18f219b915f4 100644
--- a/mlir/test/lib/IR/TestClone.cpp
+++ b/mlir/test/lib/IR/TestClone.cpp
@@ -6,7 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestOps.h"
+#include "TestDialect.h"
 #include "mlir/IR/BuiltinOps.h"
 #include "mlir/Pass/Pass.h"
 
diff --git a/mlir/test/lib/IR/TestLazyLoading.cpp b/mlir/test/lib/IR/TestLazyLoading.cpp
index 187b977c7daaac..d6e284f4b8fcf5 100644
--- a/mlir/test/lib/IR/TestLazyLoading.cpp
+++ b/mlir/test/lib/IR/TestLazyLoading.cpp
@@ -6,7 +6,6 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
 #include "mlir/Bytecode/BytecodeReader.h"
 #include "mlir/Bytecode/BytecodeWriter.h"
 #include "mlir/IR/BuiltinOps.h"
diff --git a/mlir/test/lib/IR/TestRegions.cpp b/mlir/test/lib/IR/TestRegions.cpp
index e850691631be2f..7a4a842847d9d9 100644
--- a/mlir/test/lib/IR/TestRegions.cpp
+++ b/mlir/test/lib/IR/TestRegions.cpp
@@ -6,7 +6,6 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/IR/BuiltinOps.h"
 #include "mlir/Pass/Pass.h"
diff --git a/mlir/test/lib/IR/TestSideEffects.cpp b/mlir/test/lib/IR/TestSideEffects.cpp
index db27b323c3fd25..c51f406bd0c000 100644
--- a/mlir/test/lib/IR/TestSideEffects.cpp
+++ b/mlir/test/lib/IR/TestSideEffects.cpp
@@ -6,7 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestOps.h"
+#include "TestDialect.h"
 #include "mlir/Pass/Pass.h"
 
 using namespace mlir;
diff --git a/mlir/test/lib/IR/TestSymbolUses.cpp b/mlir/test/lib/IR/TestSymbolUses.cpp
index e8170b8531d1d8..4d4c8e769c25bd 100644
--- a/mlir/test/lib/IR/TestSymbolUses.cpp
+++ b/mlir/test/lib/IR/TestSymbolUses.cpp
@@ -6,7 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestOps.h"
+#include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/IR/BuiltinOps.h"
 #include "mlir/Pass/Pass.h"
 
diff --git a/mlir/test/lib/IR/TestTypes.cpp b/mlir/test/lib/IR/TestTypes.cpp
index c6bce111d3ea7f..ce0f799d517a68 100644
--- a/mlir/test/lib/IR/TestTypes.cpp
+++ b/mlir/test/lib/IR/TestTypes.cpp
@@ -7,7 +7,6 @@
 //===----------------------------------------------------------------------===//
 
 #include "TestTypes.h"
-#include "TestDialect.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/Pass/Pass.h"
 
diff --git a/mlir/test/lib/IR/TestVisitorsGeneric.cpp b/mlir/test/lib/IR/TestVisitorsGeneric.cpp
index 20193bd71a6f5d..04f7363a079275 100644
--- a/mlir/test/lib/IR/TestVisitorsGeneric.cpp
+++ b/mlir/test/lib/IR/TestVisitorsGeneric.cpp
@@ -6,7 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestOps.h"
+#include "TestOpsCore.h"
 #include "mlir/Pass/Pass.h"
 
 using namespace mlir;
diff --git a/mlir/test/lib/Pass/TestPassManager.cpp b/mlir/test/lib/Pass/TestPassManager.cpp
index df2736bd666ca2..56d8c9ae6d1594 100644
--- a/mlir/test/lib/Pass/TestPassManager.cpp
+++ b/mlir/test/lib/Pass/TestPassManager.cpp
@@ -6,8 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsCore.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/IR/BuiltinOps.h"
 #include "mlir/Pass/Pass.h"
diff --git a/mlir/test/lib/Tools/PDLL/TestPDLL.cpp b/mlir/test/lib/Tools/PDLL/TestPDLL.cpp
index d2c17fc63f1788..3e60f23deac7ea 100644
--- a/mlir/test/lib/Tools/PDLL/TestPDLL.cpp
+++ b/mlir/test/lib/Tools/PDLL/TestPDLL.cpp
@@ -6,8 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsPatterns.h"
 #include "mlir/Dialect/PDL/IR/PDL.h"
 #include "mlir/Dialect/PDLInterp/IR/PDLInterp.h"
 #include "mlir/Interfaces/CastInterfaces.h"
diff --git a/mlir/test/lib/Transforms/TestInlining.cpp b/mlir/test/lib/Transforms/TestInlining.cpp
index ae904a92a5d68d..9c941afc916522 100644
--- a/mlir/test/lib/Transforms/TestInlining.cpp
+++ b/mlir/test/lib/Transforms/TestInlining.cpp
@@ -12,8 +12,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsCore.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/IR/BuiltinOps.h"
 #include "mlir/IR/IRMapping.h"
diff --git a/mlir/test/lib/Transforms/TestInliningCallback.cpp b/mlir/test/lib/Transforms/TestInliningCallback.cpp
index 2888c3cf3dda84..d55b53f0652ffe 100644
--- a/mlir/test/lib/Transforms/TestInliningCallback.cpp
+++ b/mlir/test/lib/Transforms/TestInliningCallback.cpp
@@ -10,8 +10,8 @@
 // canHandleMultipleBlocks and doClone.
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsConversion.h"
+#include "TestOpsCore.h"
 #include "mlir/Analysis/CallGraph.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/Dialect/SCF/IR/SCF.h"
diff --git a/mlir/test/lib/Transforms/TestMakeIsolatedFromAbove.cpp b/mlir/test/lib/Transforms/TestMakeIsolatedFromAbove.cpp
index 85d4e7498c918c..fc1b31f773ba05 100644
--- a/mlir/test/lib/Transforms/TestMakeIsolatedFromAbove.cpp
+++ b/mlir/test/lib/Transforms/TestMakeIsolatedFromAbove.cpp
@@ -6,8 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsCore.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/IR/PatternMatch.h"
 #include "mlir/Pass/Pass.h"
diff --git a/mlir/test/mlir-tblgen/op-partitions-error.td b/mlir/test/mlir-tblgen/op-partitions-error.td
new file mode 100644
index 00000000000000..2aaf4b7ed03d72
--- /dev/null
+++ b/mlir/test/mlir-tblgen/op-partitions-error.td
@@ -0,0 +1,74 @@
+// RUN: not mlir-tblgen -gen-op-decls -I %S/../../include -DERROR1 %s 2>&1 | FileCheck --check-prefix=ERROR1 %s
+// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DERROR2 %s 2>&1 | FileCheck --check-prefix=ERROR2 %s
+// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DERROR3 %s 2>&1 | FileCheck --check-prefix=ERROR3 %s
+// RUN: not mlir-tblgen -gen-op-defs -op-partition=Memroy -I %S/../../include %s 2>&1 | FileCheck --check-prefix=ERROR4 %s
+// RUN: not mlir-tblgen -gen-op-defs -op-partition=Memory -op-shard-count=2 -I %S/../../include %s 2>&1 | FileCheck --check-prefix=ERROR5 %s
+// RUN: not mlir-tblgen -gen-op-defs -op-shard-count=2 -I %S/../../include %s 2>&1 | FileCheck --check-prefix=ERROR5 %s
+// RUN: not mlir-tblgen -gen-dialect-decls -I %S/../../include -DERROR6 %s 2>&1 | FileCheck --check-prefix=ERROR6 %s
+// RUN: not mlir-tblgen -gen-dialect-decls -I %S/../../include -DERROR7 %s 2>&1 | FileCheck --check-prefix=ERROR7 %s
+// RUN: not mlir-tblgen -gen-op-doc -op-partition=Memroy -I %S/../../include %s 2>&1 | FileCheck --check-prefix=ERROR4 %s
+// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DERROR8 %s 2>&1 | FileCheck --check-prefix=ERROR8 %s
+// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DERROR9 %s 2>&1 | FileCheck --check-prefix=ERROR9 %s
+
+include "mlir/IR/OpBase.td"
+
+def MemoryPartition : Partition<"Memory">;
+def CorePartition : Partition<"Core">;
+#ifdef ERROR6
+// ERROR6: error: assertion failed: op partition name 'my-partition' is not a C++ identifier
+def InvalidPartition : Partition<"my-partition">;
+#endif
+def SnakeCasePartition : Partition<"control_flow">;
+def CamelCasePartition : Partition<"ControlFlow">;
+
+def Test_Dialect : Dialect {
+  let name = "test";
+  let opPartitions = [MemoryPartition];
+#ifdef ERROR7
+  // ERROR7: error: op partitions 'control_flow' and 'ControlFlow' of dialect 'test' have the same registration hook 'registerOperationsControlFlow'
+  let opPartitions = [MemoryPartition, SnakeCasePartition, CamelCasePartition];
+#endif
+#ifdef ERROR9
+  // ERROR9: error: assertion failed: default op partition 'Core' (record 'CorePartition') of dialect 'test' is not one of its `opPartitions`
+  let defaultOpPartition = CorePartition;
+#endif
+}
+
+def LoadOp : Op<Test_Dialect, "load"> {
+  let partition = MemoryPartition;
+}
+
+#ifdef ERROR1
+// ERROR1: error: assertion failed: op 'NoPartitionOp' is in no partition, but dialect 'test' has `opPartitions` and no `defaultOpPartition`
+def NoPartitionOp : Op<Test_Dialect, "no_partition">;
+#endif
+
+#ifdef ERROR2
+// ERROR2: error: assertion failed: op 'UnknownPartitionOp' is in partition 'Core' (record 'CorePartition'), which is not one of the `opPartitions` of dialect 'test'
+def UnknownPartitionOp : Op<Test_Dialect, "unknown_partition"> {
+  let partition = CorePartition;
+}
+#endif
+
+#ifdef ERROR3
+def Other_Dialect : Dialect {
+  let name = "other";
+}
+// ERROR3: error: assertion failed: op 'UnpartitionedDialectOp' is in partition 'Memory' (record 'MemoryPartition'), which is not one of the `opPartitions` of dialect 'other'
+def UnpartitionedDialectOp : Op<Other_Dialect, "op"> {
+  let partition = MemoryPartition;
+}
+#endif
+
+#ifdef ERROR8
+// Partitions are matched by record, not by name.
+def OtherMemoryPartition : Partition<"Memory">;
+// ERROR8: error: assertion failed: op 'OtherMemoryOp' is in partition 'Memory' (record 'OtherMemoryPartition'), which is not one of the `opPartitions` of dialect 'test'
+def OtherMemoryOp : Op<Test_Dialect, "other_memory"> {
+  let partition = OtherMemoryPartition;
+}
+#endif
+
+// ERROR4: error: requested op partition 'Memroy' is not declared in the `opPartitions` of any dialect with ops
+
+// ERROR5: error: dialect 'test' has `opPartitions`, which cannot be combined with -op-shard-count
diff --git a/mlir/test/mlir-tblgen/op-partitions.td b/mlir/test/mlir-tblgen/op-partitions.td
new file mode 100644
index 00000000000000..5b660687ea5dc2
--- /dev/null
+++ b/mlir/test/mlir-tblgen/op-partitions.td
@@ -0,0 +1,110 @@
+// RUN: mlir-tblgen -gen-op-decls -op-partition=memory -I %S/../../include %s | FileCheck %s --check-prefix=DECLS
+// RUN: mlir-tblgen -gen-op-defs -op-partition=memory -I %S/../../include %s | FileCheck %s --check-prefix=DEFS
+// RUN: mlir-tblgen -gen-op-defs -op-partition=empty -I %S/../../include %s | FileCheck %s --check-prefix=EMPTY
+// RUN: mlir-tblgen -gen-op-defs -I %S/../../include %s | FileCheck %s --check-prefix=ALL
+// RUN: mlir-tblgen -gen-dialect-decls -I %S/../../include %s | FileCheck %s --check-prefix=DIALECT-DECLS
+
+include "mlir/IR/OpBase.td"
+
+def Test_ArithPartition : Partition<"Arith">;
+def Test_MemoryPartition : Partition<"memory">;
+def Test_EmptyPartition : Partition<"empty">;
+
+def Test_Dialect : Dialect {
+  let name = "test";
+  let cppNamespace = "test";
+  let opPartitions = [Test_ArithPartition, Test_MemoryPartition,
+                      Test_EmptyPartition];
+  let defaultOpPartition = Test_ArithPartition;
+}
+
+class Test_Op<string mnemonic, list<Trait> traits = []>
+    : Op<Test_Dialect, mnemonic, traits>;
+
+// These ops are in the default partition, Arith.
+def AddOp : Test_Op<"add">, Arguments<(ins I32:$lhs, I32:$rhs)>;
+def MulOp : Test_Op<"mul">, Arguments<(ins I32:$lhs, I32:$rhs)>;
+
+let partition = Test_MemoryPartition in {
+def LoadOp : Test_Op<"load">, Arguments<(ins I64:$addr)>;
+def StoreOp : Test_Op<"store">, Arguments<(ins I32:$value, I64:$addr)>;
+def FenceOp : Test_Op<"fence">;
+}
+
+// Only the ops of the requested partition are declared. The ops of the other
+// partitions are forward declared, so that declarations can refer to them.
+// DECLS: namespace test {
+// DECLS-EMPTY:
+// DECLS-NEXT: class AddOp;
+// DECLS: class MulOp;
+// DECLS: class FenceOp;
+// DECLS: class LoadOp;
+// DECLS: class StoreOp;
+// DECLS-LABEL: #ifdef GET_OP_CLASSES
+// DECLS-NOT: AddOp
+// DECLS-NOT: MulOp
+// DECLS: class LoadOp : public
+// DECLS-NOT: AddOp
+// DECLS-NOT: MulOp
+// DECLS-NOT: register
+
+// The registration hooks replace the op list.
+// DEFS-NOT: GET_OP_LIST
+// DEFS-LABEL: #ifdef GET_OP_CLASSES
+// DEFS: static ::llvm::LogicalResult __mlir_ods_local_type_constraint_6memory_op2Dpartitions{{[0-9]+}}(
+// DEFS-NOT: AddOp
+// DEFS: LoadOpAdaptor
+// DEFS: StoreOpAdaptor
+// DEFS-NOT: AddOp
+// DEFS: void test::TestDialect::registerOperationsMemory() {
+// DEFS-NEXT:   ::mlir::RegisteredOperationName::insert<test::FenceOp>(*this);
+// DEFS-NEXT:   ::mlir::RegisteredOperationName::insert<test::LoadOp>(*this);
+// DEFS-NEXT:   ::mlir::RegisteredOperationName::insert<test::StoreOp>(*this);
+// DEFS-NEXT: }
+// DEFS-EMPTY:
+// DEFS-NEXT: #endif // GET_OP_CLASSES
+
+// A partition without ops still gets its hook, which the dialect calls.
+// EMPTY-LABEL: #ifdef GET_OP_CLASSES
+// EMPTY: void test::TestDialect::registerOperationsEmpty() {
+// EMPTY-NEXT: }
+// EMPTY-EMPTY:
+// EMPTY-NEXT: #endif // GET_OP_CLASSES
+
+// Without a requested partition, all ops are generated with both the op list
+// and the hooks of all partitions, so that a dialect can adopt partitions
+// before it generates its ops by partition. Ops without a partition are in the
+// default partition.
+// ALL-LABEL: #ifdef GET_OP_LIST
+// ALL: test::AddOp,
+// ALL: test::FenceOp,
+// ALL: test::LoadOp,
+// ALL: test::MulOp,
+// ALL: test::StoreOp
+// ALL-LABEL: #ifdef GET_OP_CLASSES
+// ALL: static ::llvm::LogicalResult __mlir_ods_local_type_constraint_op2Dpartitions{{[0-9]+}}(
+// ALL: void test::TestDialect::registerOperationsArith() {
+// ALL-NEXT:   ::mlir::RegisteredOperationName::insert<test::AddOp>(*this);
+// ALL-NEXT:   ::mlir::RegisteredOperationName::insert<test::MulOp>(*this);
+// ALL-NEXT: }
+// ALL: void test::TestDialect::registerOperationsMemory() {
+// ALL: void test::TestDialect::registerOperationsEmpty() {
+
+// The hooks are private members of the dialect class; the dialect's own
+// declarations that follow stay public.
+// DIALECT-DECLS: class TestDialect
+// DIALECT-DECLS: private:
+// DIALECT-DECLS-NEXT: /// Registers the operations of all op partitions of the dialect.
+// DIALECT-DECLS-NEXT: void registerOperations() {
+// DIALECT-DECLS-NEXT:   registerOperationsArith();
+// DIALECT-DECLS-NEXT:   registerOperationsMemory();
+// DIALECT-DECLS-NEXT:   registerOperationsEmpty();
+// DIALECT-DECLS-NEXT: }
+// DIALECT-DECLS-NEXT: /// Registers the operations in op partition `Arith`.
+// DIALECT-DECLS-NEXT: void registerOperationsArith();
+// DIALECT-DECLS-NEXT: /// Registers the operations in op partition `memory`.
+// DIALECT-DECLS-NEXT: void registerOperationsMemory();
+// DIALECT-DECLS-NEXT: /// Registers the operations in op partition `empty`.
+// DIALECT-DECLS-NEXT: void registerOperationsEmpty();
+// DIALECT-DECLS-NEXT: public:
+// DIALECT-DECLS-NEXT: };
diff --git a/mlir/tools/mlir-tblgen/DialectGen.cpp b/mlir/tools/mlir-tblgen/DialectGen.cpp
index d6977b1f225794..101d5f81d5d106 100644
--- a/mlir/tools/mlir-tblgen/DialectGen.cpp
+++ b/mlir/tools/mlir-tblgen/DialectGen.cpp
@@ -12,6 +12,7 @@
 
 #include "CppGenUtilities.h"
 #include "DialectGenUtilities.h"
+#include "OpGenHelpers.h"
 #include "mlir/TableGen/Class.h"
 #include "mlir/TableGen/CodeGenHelpers.h"
 #include "mlir/TableGen/Format.h"
@@ -216,8 +217,29 @@ static const char *const discardableAttrHelperDecl = R"(
  public:
 )";
 
+/// Emit the op registration hooks of a dialect with op partitions as private
+/// members of the dialect class: one per partition, defined by `-gen-op-defs
+/// -op-partition=...`, and one that registers the ops of all partitions.
+static void emitOpPartitionRegistrationHooks(const Dialect &dialect,
+                                             raw_ostream &os) {
+  os << "\nprivate:\n"
+     << "  /// Registers the operations of all op partitions of the dialect.\n"
+     << llvm::formatv("  void {0}() {{\n", getOpRegistrationHookName());
+  for (StringRef partition : dialect.getOpPartitions())
+    os << llvm::formatv("    {0}();\n", getOpRegistrationHookName(partition));
+  os << "  }\n";
+  for (StringRef partition : dialect.getOpPartitions())
+    os << llvm::formatv(
+        "  /// Registers the operations in op partition `{0}`.\n"
+        "  void {1}();\n",
+        partition, getOpRegistrationHookName(partition));
+  os << "public:\n";
+}
+
 /// Generate the declaration for the given dialect class.
 static void emitDialectDecl(Dialect &dialect, raw_ostream &os) {
+  verifyDialectOpPartitions(dialect);
+
   // Emit all nested namespaces.
   {
     DialectNamespaceEmitter nsEmitter(os, dialect);
@@ -272,6 +294,9 @@ static void emitDialectDecl(Dialect &dialect, raw_ostream &os) {
                           dialect.getName());
     }
 
+    if (!dialect.getOpPartitions().empty())
+      emitOpPartitionRegistrationHooks(dialect, os);
+
     if (std::optional<StringRef> extraDecl = dialect.getExtraClassDeclaration())
       os << *extraDecl;
 
diff --git a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
index 5eda6ce65c82f2..472c163dff5836 100644
--- a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
+++ b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
@@ -4742,11 +4742,28 @@ static void emitOpClassDefs(const RecordKeeper &records,
   os << definitions;
 }
 
+/// When generating the ops of an op partition, forward declare the ops of
+/// all other partitions, so that the declarations can refer to ops of any
+/// partition of their dialect, like they could without partitions.
+static void emitOtherOpPartitionForwardDecls(const RecordKeeper &records,
+                                             raw_ostream &os) {
+  for (const Record *def : records.getAllDerivedDefinitions("Op")) {
+    Operator op(def);
+    StringRef partition = op.getPartitionName();
+    if (partition.empty() || isRequestedOpPartition(partition))
+      continue;
+
+    NamespaceEmitter emitter(os, op.getCppNamespace());
+    os << "class " << op.getCppClassName() << ";\n";
+  }
+}
+
 /// Emit op declarations for all op records.
 static bool emitOpDecls(const RecordKeeper &records, raw_ostream &os) {
   emitSourceFileHeader("Op Declarations", os, records);
 
   std::vector<const Record *> defs = getRequestedOpDefinitions(records);
+  emitOtherOpPartitionForwardDecls(records, os);
   emitOpClassDecls(records, defs, os);
 
   // If we are generating sharded op definitions, emit the sharded op
@@ -4810,6 +4827,50 @@ static void emitOpDefShard(const RecordKeeper &records,
   emitOpClassDefs(records, defs, os, indexStr);
 }
 
+/// Emit the registration hooks of the op partitions of `dialects` that are
+/// requested by "op-partition", or of all their partitions if none is. A hook
+/// is emitted even if its partition has no ops, because the dialect calls the
+/// hooks of all its partitions.
+static void emitOpPartitionRegistrationHooks(ArrayRef<Dialect> dialects,
+                                             ArrayRef<const Record *> defs,
+                                             raw_ostream &os) {
+  std::vector<Operator> ops(defs.begin(), defs.end());
+  for (const Dialect &dialect : dialects) {
+    for (StringRef partition : dialect.getOpPartitions()) {
+      if (!isRequestedOpPartition(partition))
+        continue;
+
+      os << formatv(opCommentHeader, dialect.getCppClassName(),
+                    (partition + " Op Registration Hook").str())
+         << formatv("void {0}::{1}::{2}() {{\n", dialect.getCppNamespace(),
+                    dialect.getCppClassName(),
+                    getOpRegistrationHookName(partition));
+      // The hooks register each op with a separate call instead of
+      // `addOperations<...>()`, whose single instantiation over all ops of a
+      // partition takes noticeably longer to compile.
+      for (const Operator &op : ops)
+        if (op.getDialect() == dialect && op.getPartitionName() == partition)
+          os << formatv(
+              "  ::mlir::RegisteredOperationName::insert<{0}>(*this);\n",
+              op.getQualCppClassName());
+      os << "}\n";
+    }
+  }
+}
+
+/// Returns the tag that makes the static verifier functions generated for the
+/// requested op partition unique, so that the definitions of several
+/// partitions can be included in one compilation unit. The partition name is
+/// prefixed with its length and the tag ends with `_`, so that the partition
+/// name and the file name that follows the tag cannot run together.
+static std::string getOpPartitionConstraintTag() {
+  StringRef partition = getRequestedOpPartition();
+  if (partition.empty())
+    return "";
+
+  return std::to_string(partition.size()) + partition.str() + "_";
+}
+
 /// Emit op definitions for all op records.
 static bool emitOpDefs(const RecordKeeper &records, raw_ostream &os) {
   emitSourceFileHeader("Op Definitions", os, records);
@@ -4818,9 +4879,11 @@ static bool emitOpDefs(const RecordKeeper &records, raw_ostream &os) {
   SmallVector<ArrayRef<const Record *>, 4> shardedDefs;
   shardOpDefinitions(defs, shardedDefs);
 
-  // If no shard was requested, emit the regular op list and class definitions.
+  // If no shard was requested, emit the class definitions and the registration
+  // hooks of the op partitions. Without a requested op partition, also emit the
+  // op list, for dialects that register their ops without hooks.
   if (shardedDefs.size() == 1) {
-    {
+    if (getRequestedOpPartition().empty()) {
       IfDefEmitter scope(os, "GET_OP_LIST");
       interleave(
           defs, os,
@@ -4829,7 +4892,8 @@ static bool emitOpDefs(const RecordKeeper &records, raw_ostream &os) {
     }
     {
       IfDefEmitter scope(os, "GET_OP_CLASSES");
-      emitOpClassDefs(records, defs, os);
+      emitOpClassDefs(records, defs, os, getOpPartitionConstraintTag());
+      emitOpPartitionRegistrationHooks(getOpDialects(records), defs, os);
     }
     return false;
   }
diff --git a/mlir/tools/mlir-tblgen/OpGenHelpers.cpp b/mlir/tools/mlir-tblgen/OpGenHelpers.cpp
index afc8272bc2a630..4f30ee333e1d61 100644
--- a/mlir/tools/mlir-tblgen/OpGenHelpers.cpp
+++ b/mlir/tools/mlir-tblgen/OpGenHelpers.cpp
@@ -11,6 +11,8 @@
 //===----------------------------------------------------------------------===//
 
 #include "OpGenHelpers.h"
+#include "llvm/ADT/SetVector.h"
+#include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FormatVariadic.h"
@@ -35,6 +37,11 @@ static cl::opt<unsigned> opShardCount(
     "op-shard-count",
     cl::desc("The number of shards into which the op classes will be divided"),
     cl::cat(opDefGenCat), cl::init(1));
+static cl::opt<std::string> opPartition(
+    "op-partition",
+    cl::desc("Only consider the ops in this op partition (see `Op::partition`) "
+             "and, for -gen-op-defs, emit its registration hook"),
+    cl::cat(opDefGenCat));
 
 static std::string getOperationName(const Record &def) {
   auto prefix = def.getValueAsDef("opDialect")->getValueAsString("name");
@@ -44,12 +51,54 @@ static std::string getOperationName(const Record &def) {
   return std::string(formatv("{0}.{1}", prefix, opName));
 }
 
+/// Like `Operator::getPartitionName`, for filtering without constructing an
+/// `Operator`.
+static StringRef getOpPartitionName(const Record &def) {
+  const Record *partition = def.getValueAsOptionalDef("partition");
+  return partition ? partition->getValueAsString("partitionName") : "";
+}
+
+std::string mlir::tblgen::getOpRegistrationHookName(StringRef partition) {
+  return "registerOperations" +
+         convertToCamelFromSnakeCase(partition, /*capitalizeFirst=*/true);
+}
+
+/// Verifies that the partition requested by "op-partition" exists and that
+/// "op-shard-count" is not used with partitions.
+static void verifyOpPartitions(ArrayRef<Dialect> dialects) {
+  for (const Dialect &dialect : dialects)
+    verifyDialectOpPartitions(dialect);
+
+  // The requested partition must belong to a dialect with ops.
+  if (!opPartition.empty() &&
+      llvm::none_of(dialects, [&](const Dialect &dialect) {
+        return llvm::is_contained(dialect.getOpPartitions(), opPartition);
+      }))
+    PrintFatalError("requested op partition '" + opPartition +
+                    "' is not declared in the `opPartitions` of any dialect "
+                    "with ops");
+
+  // Index sharding does not emit the registration hooks of partitions, which
+  // `registerOperations()` of a dialect with partitions calls. This also
+  // rejects -op-partition, as the requested partition belongs to a dialect.
+  if (opShardCount > 1) {
+    for (const Dialect &dialect : dialects)
+      if (!dialect.getOpPartitions().empty())
+        PrintFatalError(dialect.getDef(),
+                        "dialect '" + dialect.getName() +
+                            "' has `opPartitions`, which cannot be combined "
+                            "with -op-shard-count");
+  }
+}
+
 std::vector<const Record *>
 mlir::tblgen::getRequestedOpDefinitions(const RecordKeeper &records) {
   const Record *classDef = records.getClass("Op");
   if (!classDef)
     PrintFatalError("ERROR: Couldn't find the 'Op' class!\n");
 
+  verifyOpPartitions(getOpDialects(records));
+
   Regex includeRegex(opIncFilter), excludeRegex(opExcFilter);
   std::vector<const Record *> defs;
   for (const Record *def : records.getDefs()) {
@@ -61,6 +110,9 @@ mlir::tblgen::getRequestedOpDefinitions(const RecordKeeper &records) {
     // Unless there is an exclude filter and it matches.
     if (!opExcFilter.empty() && excludeRegex.match(getOperationName(*def)))
       continue;
+    // Only include ops of the requested partition, if any.
+    if (!isRequestedOpPartition(getOpPartitionName(*def)))
+      continue;
     defs.push_back(def);
   }
 
@@ -101,3 +153,30 @@ void mlir::tblgen::shardOpDefinitions(
     start += size;
   }
 }
+
+StringRef mlir::tblgen::getRequestedOpPartition() { return opPartition; }
+
+bool mlir::tblgen::isRequestedOpPartition(StringRef partition) {
+  return opPartition.empty() || partition == opPartition;
+}
+
+void mlir::tblgen::verifyDialectOpPartitions(const Dialect &dialect) {
+  StringMap<StringRef> hookNames;
+  for (StringRef partition : dialect.getOpPartitions()) {
+    auto [it, inserted] =
+        hookNames.try_emplace(getOpRegistrationHookName(partition), partition);
+    if (!inserted)
+      PrintFatalError(dialect.getDef(),
+                      "op partitions '" + it->second + "' and '" + partition +
+                          "' of dialect '" + dialect.getName() +
+                          "' have the same registration hook '" + it->first() +
+                          "'");
+  }
+}
+
+std::vector<Dialect> mlir::tblgen::getOpDialects(const RecordKeeper &records) {
+  SetVector<const Record *> dialectDefs;
+  for (const Record *def : records.getAllDerivedDefinitions("Op"))
+    dialectDefs.insert(def->getValueAsDef("opDialect"));
+  return std::vector<Dialect>(dialectDefs.begin(), dialectDefs.end());
+}
diff --git a/mlir/tools/mlir-tblgen/OpGenHelpers.h b/mlir/tools/mlir-tblgen/OpGenHelpers.h
index 3cd171d10c08ab..4ffe046cbc09de 100644
--- a/mlir/tools/mlir-tblgen/OpGenHelpers.h
+++ b/mlir/tools/mlir-tblgen/OpGenHelpers.h
@@ -14,17 +14,25 @@
 #define MLIR_TOOLS_MLIRTBLGEN_OPGENHELPERS_H_
 
 #include "mlir/Support/LLVM.h"
+#include "mlir/TableGen/Dialect.h"
 #include "llvm/TableGen/Record.h"
+#include <string>
 #include <vector>
 
 namespace mlir {
 namespace tblgen {
-
 /// Returns all the op definitions filtered by the user. The filtering is via
-/// command-line option "op-include-regex" and "op-exclude-regex".
+/// command-line options "op-include-regex", "op-exclude-regex" and
+/// "op-partition". Verifies "op-partition" and the op partitions of the
+/// dialects with ops.
 std::vector<const llvm::Record *>
 getRequestedOpDefinitions(const llvm::RecordKeeper &records);
 
+/// Returns the name of the private member function of a dialect class that
+/// registers the ops of the dialect in op partition `partition`, or all its ops
+/// if `partition` is empty.
+std::string getOpRegistrationHookName(StringRef partition = "");
+
 /// Checks whether `str` is a Python keyword or would shadow builtin function.
 /// Regenerate using python -c"print(set(sorted(__import__('keyword').kwlist)))"
 bool isPythonReserved(llvm::StringRef str);
@@ -34,6 +42,20 @@ void shardOpDefinitions(
     ArrayRef<const llvm::Record *> defs,
     SmallVectorImpl<ArrayRef<const llvm::Record *>> &shardedDefs);
 
+/// Returns the op partition set by "op-partition", or an empty string if all
+/// ops are requested.
+StringRef getRequestedOpPartition();
+
+/// Returns whether "op-partition" requests `partition`.
+/// Returns true if "op-partition" is not set.
+bool isRequestedOpPartition(StringRef partition);
+
+/// Verifies that the op partitions of `dialect` have unique registration hooks.
+void verifyDialectOpPartitions(const Dialect &dialect);
+
+/// Returns the dialects that have ops in `records`, in order of first
+/// appearance.
+std::vector<Dialect> getOpDialects(const llvm::RecordKeeper &records);
 } // namespace tblgen
 } // namespace mlir
 
diff --git a/mlir/unittests/IR/AdaptorTest.cpp b/mlir/unittests/IR/AdaptorTest.cpp
index 39e7eec5a956d6..f19264b985100a 100644
--- a/mlir/unittests/IR/AdaptorTest.cpp
+++ b/mlir/unittests/IR/AdaptorTest.cpp
@@ -6,8 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsCore.h"
 #include "TestOpsSyntax.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
diff --git a/mlir/unittests/IR/IRMapping.cpp b/mlir/unittests/IR/IRMapping.cpp
index 62814f7ba39266..cd7797069d7553 100644
--- a/mlir/unittests/IR/IRMapping.cpp
+++ b/mlir/unittests/IR/IRMapping.cpp
@@ -10,8 +10,7 @@
 #include "mlir/IR/Builders.h"
 #include "gtest/gtest.h"
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsPatterns.h"
 
 using namespace mlir;
 
diff --git a/mlir/unittests/IR/InterfaceAttachmentTest.cpp b/mlir/unittests/IR/InterfaceAttachmentTest.cpp
index 02cc9312e9f493..a107c40774a578 100644
--- a/mlir/unittests/IR/InterfaceAttachmentTest.cpp
+++ b/mlir/unittests/IR/InterfaceAttachmentTest.cpp
@@ -18,8 +18,7 @@
 #include "gtest/gtest.h"
 
 #include "TestAttributes.h"
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsPatterns.h"
 #include "TestTypes.h"
 #include "mlir/IR/OwningOpRef.h"
 
diff --git a/mlir/unittests/IR/InterfaceTest.cpp b/mlir/unittests/IR/InterfaceTest.cpp
index cd4e76a63e257d..d7554e7bceaa86 100644
--- a/mlir/unittests/IR/InterfaceTest.cpp
+++ b/mlir/unittests/IR/InterfaceTest.cpp
@@ -14,8 +14,7 @@
 #include "gtest/gtest.h"
 
 #include "TestAttributes.h"
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsInterfaces.h"
 #include "TestTypes.h"
 
 using namespace mlir;
diff --git a/mlir/unittests/IR/OperationSupportTest.cpp b/mlir/unittests/IR/OperationSupportTest.cpp
index fdeeb3d2cb3cc1..d44f17870ffc01 100644
--- a/mlir/unittests/IR/OperationSupportTest.cpp
+++ b/mlir/unittests/IR/OperationSupportTest.cpp
@@ -7,8 +7,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "mlir/IR/OperationSupport.h"
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsPatterns.h"
 #include "mlir/IR/Builders.h"
 #include "mlir/IR/BuiltinTypes.h"
 #include "llvm/ADT/BitVector.h"
diff --git a/mlir/unittests/IR/PatternMatchTest.cpp b/mlir/unittests/IR/PatternMatchTest.cpp
index f4eb3b027a2228..92b4623431f640 100644
--- a/mlir/unittests/IR/PatternMatchTest.cpp
+++ b/mlir/unittests/IR/PatternMatchTest.cpp
@@ -12,8 +12,7 @@
 #include <string>
 #include <vector>
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsPatterns.h"
 
 using namespace mlir;
 
diff --git a/mlir/unittests/IR/ValueTest.cpp b/mlir/unittests/IR/ValueTest.cpp
index 8f794d172844cd..dc40a1b505d29c 100644
--- a/mlir/unittests/IR/ValueTest.cpp
+++ b/mlir/unittests/IR/ValueTest.cpp
@@ -7,8 +7,6 @@
 //===----------------------------------------------------------------------===//
 
 #include "mlir/IR/Value.h"
-#include "TestDialect.h"
-#include "TestOps.h"
 #include "mlir/IR/Builders.h"
 #include "mlir/IR/BuiltinTypes.h"
 #include "mlir/IR/OperationSupport.h"
diff --git a/mlir/unittests/Interfaces/MemorySlotUtilsTest.cpp b/mlir/unittests/Interfaces/MemorySlotUtilsTest.cpp
index ffc1709201f26d..baad58d29f8cb2 100644
--- a/mlir/unittests/Interfaces/MemorySlotUtilsTest.cpp
+++ b/mlir/unittests/Interfaces/MemorySlotUtilsTest.cpp
@@ -8,7 +8,6 @@
 
 #include "mlir/Interfaces/Utils/MemorySlotUtils.h"
 #include "TestDialect.h"
-#include "TestOps.h"
 #include "mlir/Parser/Parser.h"
 #include "gtest/gtest.h"
 
diff --git a/mlir/unittests/TableGen/OpBuildGen.cpp b/mlir/unittests/TableGen/OpBuildGen.cpp
index e0e1ac99884bad..b3e620f3ce65ea 100644
--- a/mlir/unittests/TableGen/OpBuildGen.cpp
+++ b/mlir/unittests/TableGen/OpBuildGen.cpp
@@ -10,8 +10,7 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "TestDialect.h"
-#include "TestOps.h"
+#include "TestOpsCore.h"
 #include "mlir/IR/Attributes.h"
 #include "mlir/IR/Builders.h"
 #include "mlir/IR/BuiltinTypes.h"



More information about the llvm-branch-commits mailing list