Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MLIR] Add canonicalizations to all eligible index binary ops #114000

Merged
merged 3 commits into from
Nov 4, 2024

Conversation

nacgarg
Copy link
Contributor

@nacgarg nacgarg commented Oct 29, 2024

Generalizes the following canonicalization pattern to all associative and commutative binary ops in the index dialect.

x = v + c1
y = x + c2
   -->
y = x + (c1 + c2)

This includes:

  • AddOp
  • MulOp
  • MaxSOp
  • MaxUOp
  • MinSOp
  • MinUOp
  • AndOp
  • OrOp
  • XOrOp

The operation folding is implemented using the existing folders since createAndFold is used in the canonicalization.

@nacgarg nacgarg requested a review from Mogball as a code owner October 29, 2024 04:22
Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Oct 29, 2024

@llvm/pr-subscribers-mlir-index

@llvm/pr-subscribers-mlir

Author: Nachi G (nacgarg)

Changes

Generalizes the following canonicalization pattern to all associative and commutative binary ops in the index dialect.

x = v + c1
y = x + c2
   -->
y = x + (c1 + c2)

This includes:

  • AddOp
  • MulOp
  • MaxSOp
  • MaxUOp
  • MinSOp
  • MinUOp
  • AndOp
  • OrOp
  • XOrOp

The operation folding is implemented using the existing folders since createAndFold is used in the canonicalization.


Full diff: https://github.com/llvm/llvm-project/pull/114000.diff

3 Files Affected:

  • (modified) mlir/include/mlir/Dialect/Index/IR/IndexOps.td (+16)
  • (modified) mlir/lib/Dialect/Index/IR/IndexOps.cpp (+59-20)
  • (modified) mlir/test/Dialect/Index/index-canonicalize.mlir (+105-1)
diff --git a/mlir/include/mlir/Dialect/Index/IR/IndexOps.td b/mlir/include/mlir/Dialect/Index/IR/IndexOps.td
index ce1355316b09b8..230a3815bdd81e 100644
--- a/mlir/include/mlir/Dialect/Index/IR/IndexOps.td
+++ b/mlir/include/mlir/Dialect/Index/IR/IndexOps.td
@@ -95,6 +95,8 @@ def Index_MulOp : IndexBinaryOp<"mul", [Commutative, Pure]> {
     %c = index.mul %a, %b
     ```
   }];
+
+  let hasCanonicalizeMethod = 1;
 }
 
 //===----------------------------------------------------------------------===//
@@ -263,6 +265,8 @@ def Index_MaxSOp : IndexBinaryOp<"maxs", [Commutative, Pure]> {
     %c = index.maxs %a, %b
     ```
   }];
+
+  let hasCanonicalizeMethod = 1;
 }
 
 //===----------------------------------------------------------------------===//
@@ -283,6 +287,8 @@ def Index_MaxUOp : IndexBinaryOp<"maxu", [Commutative, Pure]> {
     %c = index.maxu %a, %b
     ```
   }];
+
+  let hasCanonicalizeMethod = 1;
 }
 
 //===----------------------------------------------------------------------===//
@@ -302,6 +308,8 @@ def Index_MinSOp : IndexBinaryOp<"mins", [Commutative, Pure]> {
     %c = index.mins %a, %b
     ```
   }];
+
+  let hasCanonicalizeMethod = 1;
 }
 
 //===----------------------------------------------------------------------===//
@@ -322,6 +330,8 @@ def Index_MinUOp : IndexBinaryOp<"minu", [Commutative, Pure]> {
     %c = index.minu %a, %b
     ```
   }];
+
+  let hasCanonicalizeMethod = 1;
 }
 
 //===----------------------------------------------------------------------===//
@@ -404,6 +414,8 @@ def Index_AndOp : IndexBinaryOp<"and", [Commutative, Pure]> {
     %c = index.and %a, %b
     ```
   }];
+
+  let hasCanonicalizeMethod = 1;
 }
 
 //===----------------------------------------------------------------------===//
@@ -423,6 +435,8 @@ def Index_OrOp : IndexBinaryOp<"or", [Commutative, Pure]> {
     %c = index.or %a, %b
     ```
   }];
+
+  let hasCanonicalizeMethod = 1;
 }
 
 //===----------------------------------------------------------------------===//
@@ -442,6 +456,8 @@ def Index_XOrOp : IndexBinaryOp<"xor", [Commutative, Pure]> {
     %c = index.xor %a, %b
     ```
   }];
+
+  let hasCanonicalizeMethod = 1;
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/mlir/lib/Dialect/Index/IR/IndexOps.cpp b/mlir/lib/Dialect/Index/IR/IndexOps.cpp
index 0b58eb80f93032..a650b05767bbb7 100644
--- a/mlir/lib/Dialect/Index/IR/IndexOps.cpp
+++ b/mlir/lib/Dialect/Index/IR/IndexOps.cpp
@@ -118,6 +118,31 @@ static OpFoldResult foldBinaryOpChecked(
   return IntegerAttr::get(IndexType::get(lhs.getContext()), *result64);
 }
 
+/// Helper for associative and commutative binary ops that can be transformed:
+/// `x = op(v, c1); y = op(x, c2)` -> `tmp = op(c1, c2); y = op(v, tmp)`
+/// where c1 and c2 are constants. It is expected that `tmp` will be folded.
+template <typename BinaryOp>
+static LogicalResult
+canonicalizeAssociativeCommutativeBinaryOp(BinaryOp op,
+                                           PatternRewriter &rewriter) {
+  IntegerAttr c1, c2;
+  if (!mlir::matchPattern(op.getRhs(), mlir::m_Constant(&c1)))
+    return rewriter.notifyMatchFailure(op.getLoc(), "RHS is not a constant");
+
+  auto lhsOp = op.getLhs().template getDefiningOp<BinaryOp>();
+  if (!lhsOp)
+    return rewriter.notifyMatchFailure(op.getLoc(), "LHS is not a add");
+
+  if (!mlir::matchPattern(lhsOp.getRhs(), mlir::m_Constant(&c2)))
+    return rewriter.notifyMatchFailure(op.getLoc(), "RHS is not a constant");
+
+  auto c = rewriter.createOrFold<BinaryOp>(op->getLoc(), op.getRhs(),
+                                           lhsOp.getRhs());
+
+  rewriter.replaceOpWithNewOp<BinaryOp>(op, lhsOp.getLhs(), c);
+  return success();
+}
+
 //===----------------------------------------------------------------------===//
 // AddOp
 //===----------------------------------------------------------------------===//
@@ -136,27 +161,9 @@ OpFoldResult AddOp::fold(FoldAdaptor adaptor) {
 
   return {};
 }
-/// Canonicalize
-/// ` x = v + c1; y = x + c2` to `x = v + (c1 + c2)`
-LogicalResult AddOp::canonicalize(AddOp op, PatternRewriter &rewriter) {
-  IntegerAttr c1, c2;
-  if (!mlir::matchPattern(op.getRhs(), mlir::m_Constant(&c1)))
-    return rewriter.notifyMatchFailure(op.getLoc(), "RHS is not a constant");
-
-  auto add = op.getLhs().getDefiningOp<mlir::index::AddOp>();
-  if (!add)
-    return rewriter.notifyMatchFailure(op.getLoc(), "LHS is not a add");
-
-  if (!mlir::matchPattern(add.getRhs(), mlir::m_Constant(&c2)))
-    return rewriter.notifyMatchFailure(op.getLoc(), "RHS is not a constant");
-
-  auto c = rewriter.create<mlir::index::ConstantOp>(op->getLoc(),
-                                                    c1.getInt() + c2.getInt());
-  auto newAdd =
-      rewriter.create<mlir::index::AddOp>(op->getLoc(), add.getLhs(), c);
 
-  rewriter.replaceOp(op, newAdd);
-  return success();
+LogicalResult AddOp::canonicalize(AddOp op, PatternRewriter &rewriter) {
+  return canonicalizeAssociativeCommutativeBinaryOp(op, rewriter);
 }
 
 //===----------------------------------------------------------------------===//
@@ -200,6 +207,10 @@ OpFoldResult MulOp::fold(FoldAdaptor adaptor) {
   return {};
 }
 
+LogicalResult MulOp::canonicalize(MulOp op, PatternRewriter &rewriter) {
+  return canonicalizeAssociativeCommutativeBinaryOp(op, rewriter);
+}
+
 //===----------------------------------------------------------------------===//
 // DivSOp
 //===----------------------------------------------------------------------===//
@@ -352,6 +363,10 @@ OpFoldResult MaxSOp::fold(FoldAdaptor adaptor) {
                              });
 }
 
+LogicalResult MaxSOp::canonicalize(MaxSOp op, PatternRewriter &rewriter) {
+  return canonicalizeAssociativeCommutativeBinaryOp(op, rewriter);
+}
+
 //===----------------------------------------------------------------------===//
 // MaxUOp
 //===----------------------------------------------------------------------===//
@@ -363,6 +378,10 @@ OpFoldResult MaxUOp::fold(FoldAdaptor adaptor) {
                              });
 }
 
+LogicalResult MaxUOp::canonicalize(MaxUOp op, PatternRewriter &rewriter) {
+  return canonicalizeAssociativeCommutativeBinaryOp(op, rewriter);
+}
+
 //===----------------------------------------------------------------------===//
 // MinSOp
 //===----------------------------------------------------------------------===//
@@ -374,6 +393,10 @@ OpFoldResult MinSOp::fold(FoldAdaptor adaptor) {
                              });
 }
 
+LogicalResult MinSOp::canonicalize(MinSOp op, PatternRewriter &rewriter) {
+  return canonicalizeAssociativeCommutativeBinaryOp(op, rewriter);
+}
+
 //===----------------------------------------------------------------------===//
 // MinUOp
 //===----------------------------------------------------------------------===//
@@ -385,6 +408,10 @@ OpFoldResult MinUOp::fold(FoldAdaptor adaptor) {
                              });
 }
 
+LogicalResult MinUOp::canonicalize(MinUOp op, PatternRewriter &rewriter) {
+  return canonicalizeAssociativeCommutativeBinaryOp(op, rewriter);
+}
+
 //===----------------------------------------------------------------------===//
 // ShlOp
 //===----------------------------------------------------------------------===//
@@ -442,6 +469,10 @@ OpFoldResult AndOp::fold(FoldAdaptor adaptor) {
       [](const APInt &lhs, const APInt &rhs) { return lhs & rhs; });
 }
 
+LogicalResult AndOp::canonicalize(AndOp op, PatternRewriter &rewriter) {
+  return canonicalizeAssociativeCommutativeBinaryOp(op, rewriter);
+}
+
 //===----------------------------------------------------------------------===//
 // OrOp
 //===----------------------------------------------------------------------===//
@@ -452,6 +483,10 @@ OpFoldResult OrOp::fold(FoldAdaptor adaptor) {
       [](const APInt &lhs, const APInt &rhs) { return lhs | rhs; });
 }
 
+LogicalResult OrOp::canonicalize(OrOp op, PatternRewriter &rewriter) {
+  return canonicalizeAssociativeCommutativeBinaryOp(op, rewriter);
+}
+
 //===----------------------------------------------------------------------===//
 // XOrOp
 //===----------------------------------------------------------------------===//
@@ -462,6 +497,10 @@ OpFoldResult XOrOp::fold(FoldAdaptor adaptor) {
       [](const APInt &lhs, const APInt &rhs) { return lhs ^ rhs; });
 }
 
+LogicalResult XOrOp::canonicalize(XOrOp op, PatternRewriter &rewriter) {
+  return canonicalizeAssociativeCommutativeBinaryOp(op, rewriter);
+}
+
 //===----------------------------------------------------------------------===//
 // CastSOp
 //===----------------------------------------------------------------------===//
diff --git a/mlir/test/Dialect/Index/index-canonicalize.mlir b/mlir/test/Dialect/Index/index-canonicalize.mlir
index a29b09c11f7f62..cecc29a13fc901 100644
--- a/mlir/test/Dialect/Index/index-canonicalize.mlir
+++ b/mlir/test/Dialect/Index/index-canonicalize.mlir
@@ -32,7 +32,7 @@ func.func @add_overflow() -> (index, index) {
   return %2, %3 : index, index
 }
 
-// CHECK-LABEL: @add
+// CHECK-LABEL: @add_fold_constants
 func.func @add_fold_constants(%arg: index) -> (index) {
   %0 = index.constant 1
   %1 = index.constant 2
@@ -65,6 +65,19 @@ func.func @mul() -> index {
   return %2 : index
 }
 
+// CHECK-LABEL: @mul_fold_constants
+func.func @mul_fold_constants(%arg: index) -> (index) {
+  %0 = index.constant 2
+  %1 = index.constant 3
+  %2 = index.mul %arg, %0
+  %3 = index.mul %2, %1
+
+  // CHECK-DAG: [[C6:%.*]] = index.constant 6
+  // CHECK-DAG: [[V0:%.*]] = index.mul %arg0, [[C6]]
+  // CHECK: return [[V0]]
+  return %3 : index
+}
+
 // CHECK-LABEL: @divs
 func.func @divs() -> index {
   %0 = index.constant -2
@@ -300,6 +313,19 @@ func.func @maxs_edge() -> index {
   return %0 : index
 }
 
+// CHECK-LABEL: @maxs_fold_constants
+func.func @maxs_fold_constants(%arg: index) -> (index) {
+  %0 = index.constant 2
+  %1 = index.constant 3
+  %2 = index.maxs %arg, %0
+  %3 = index.maxs %2, %1
+
+  // CHECK-DAG: [[C3:%.*]] = index.constant 3
+  // CHECK-DAG: [[V0:%.*]] = index.maxs %arg0, [[C3]]
+  // CHECK: return [[V0]]
+  return %3 : index
+}
+
 // CHECK-LABEL: @maxu
 func.func @maxu() -> index {
   %lhs = index.constant -1
@@ -310,6 +336,19 @@ func.func @maxu() -> index {
   return %0 : index
 }
 
+// CHECK-LABEL: @maxu_fold_constants
+func.func @maxu_fold_constants(%arg: index) -> (index) {
+  %0 = index.constant 2
+  %1 = index.constant 3
+  %2 = index.maxu %arg, %0
+  %3 = index.maxu %2, %1
+
+  // CHECK-DAG: [[C3:%.*]] = index.constant 3
+  // CHECK-DAG: [[V0:%.*]] = index.maxu %arg0, [[C3]]
+  // CHECK: return [[V0]]
+  return %3 : index
+}
+
 // CHECK-LABEL: @mins
 func.func @mins() -> index {
   %lhs = index.constant -4
@@ -340,6 +379,19 @@ func.func @mins_nofold_2() -> index {
   return %0 : index
 }
 
+// CHECK-LABEL: @mins_fold_constants
+func.func @mins_fold_constants(%arg: index) -> (index) {
+  %0 = index.constant 2
+  %1 = index.constant 3
+  %2 = index.mins %arg, %0
+  %3 = index.mins %2, %1
+
+  // CHECK-DAG: [[C2:%.*]] = index.constant 2
+  // CHECK-DAG: [[V0:%.*]] = index.mins %arg0, [[C2]]
+  // CHECK: return [[V0]]
+  return %3 : index
+}
+
 // CHECK-LABEL: @minu
 func.func @minu() -> index {
   %lhs = index.constant -1
@@ -350,6 +402,19 @@ func.func @minu() -> index {
   return %0 : index
 }
 
+// CHECK-LABEL: @minu_fold_constants
+func.func @minu_fold_constants(%arg: index) -> (index) {
+  %0 = index.constant 2
+  %1 = index.constant 3
+  %2 = index.minu %arg, %0
+  %3 = index.minu %2, %1
+
+  // CHECK-DAG: [[C2:%.*]] = index.constant 2
+  // CHECK-DAG: [[V0:%.*]] = index.minu %arg0, [[C2]]
+  // CHECK: return [[V0]]
+  return %3 : index
+}
+
 // CHECK-LABEL: @shl
 func.func @shl() -> index {
   %lhs = index.constant 128
@@ -465,6 +530,19 @@ func.func @and() -> index {
   return %0 : index
 }
 
+// CHECK-LABEL: @and_fold_constants
+func.func @and_fold_constants(%arg: index) -> (index) {
+  %0 = index.constant 5
+  %1 = index.constant 1
+  %2 = index.and %arg, %0
+  %3 = index.and %2, %1
+
+  // CHECK-DAG: [[C1:%.*]] = index.constant 1
+  // CHECK-DAG: [[V0:%.*]] = index.and %arg0, [[C1]]
+  // CHECK: return [[V0]]
+  return %3 : index
+}
+
 // CHECK-LABEL: @or
 func.func @or() -> index {
   %lhs = index.constant 5
@@ -475,6 +553,19 @@ func.func @or() -> index {
   return %0 : index
 }
 
+// CHECK-LABEL: @or_fold_constants
+func.func @or_fold_constants(%arg: index) -> (index) {
+  %0 = index.constant 5
+  %1 = index.constant 1
+  %2 = index.or %arg, %0
+  %3 = index.or %2, %1
+
+  // CHECK-DAG: [[C5:%.*]] = index.constant 5
+  // CHECK-DAG: [[V0:%.*]] = index.or %arg0, [[C5]]
+  // CHECK: return [[V0]]
+  return %3 : index
+}
+
 // CHECK-LABEL: @xor
 func.func @xor() -> index {
   %lhs = index.constant 5
@@ -485,6 +576,19 @@ func.func @xor() -> index {
   return %0 : index
 }
 
+// CHECK-LABEL: @xor_fold_constants
+func.func @xor_fold_constants(%arg: index) -> (index) {
+  %0 = index.constant 5
+  %1 = index.constant 1
+  %2 = index.xor %arg, %0
+  %3 = index.xor %2, %1
+
+  // CHECK-DAG: [[C4:%.*]] = index.constant 4
+  // CHECK-DAG: [[V0:%.*]] = index.xor %arg0, [[C4]]
+  // CHECK: return [[V0]]
+  return %3 : index
+}
+
 // CHECK-LABEL: @cmp
 func.func @cmp(%arg0: index) -> (i1, i1, i1, i1, i1, i1) {
   %a = index.constant 0

mlir/test/Dialect/Index/index-canonicalize.mlir Outdated Show resolved Hide resolved
mlir/test/Dialect/Index/index-canonicalize.mlir Outdated Show resolved Hide resolved
mlir/test/Dialect/Index/index-canonicalize.mlir Outdated Show resolved Hide resolved
mlir/lib/Dialect/Index/IR/IndexOps.cpp Outdated Show resolved Hide resolved
@nacgarg nacgarg requested a review from weiweichen October 30, 2024 20:54
Copy link
Member

@PeimingLiu PeimingLiu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks.

LGTM

@PeimingLiu PeimingLiu merged commit 795b4ef into llvm:main Nov 4, 2024
7 checks passed
Copy link

github-actions bot commented Nov 4, 2024

@nacgarg Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

PhilippRados pushed a commit to PhilippRados/llvm-project that referenced this pull request Nov 6, 2024
…#114000)

Generalizes the following canonicalization pattern to all associative
and commutative binary ops in the `index` dialect.

```
x = v + c1
y = x + c2
   -->
y = x + (c1 + c2)
```

This includes:
- `AddOp`
- `MulOp`
- `MaxSOp`
- `MaxUOp`
- `MinSOp`
- `MinUOp`
- `AndOp`
- `OrOp`
- `XOrOp`

The operation folding is implemented using the existing folders since
`createAndFold` is used in the canonicalization.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants