mirror of
https://github.com/intel/llvm.git
synced 2026-01-24 08:30:34 +08:00
[MLIR] Add folding constants canonicalization for mlir::index::AddOp. (#111084)
- [x] Add a simple canonicalization for `mlir::index::AddOp`.
This commit is contained in:
@@ -56,6 +56,8 @@ def Index_AddOp : IndexBinaryOp<"add", [Commutative, Pure]> {
|
||||
%c = index.add %a, %b
|
||||
```
|
||||
}];
|
||||
|
||||
let hasCanonicalizeMethod = 1;
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@@ -136,6 +136,28 @@ 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();
|
||||
}
|
||||
|
||||
//===----------------------------------------------------------------------===//
|
||||
// SubOp
|
||||
|
||||
@@ -32,6 +32,19 @@ func.func @add_overflow() -> (index, index) {
|
||||
return %2, %3 : index, index
|
||||
}
|
||||
|
||||
// CHECK-LABEL: @add
|
||||
func.func @add_fold_constants(%arg: index) -> (index) {
|
||||
%0 = index.constant 1
|
||||
%1 = index.constant 2
|
||||
%2 = index.add %arg, %0
|
||||
%3 = index.add %2, %1
|
||||
|
||||
// CHECK-DAG: [[C3:%.*]] = index.constant 3
|
||||
// CHECK-DAG: [[V0:%.*]] = index.add %arg0, [[C3]]
|
||||
// CHECK: return [[V0]]
|
||||
return %3 : index
|
||||
}
|
||||
|
||||
// CHECK-LABEL: @sub
|
||||
func.func @sub() -> index {
|
||||
%0 = index.constant -2000000000
|
||||
|
||||
Reference in New Issue
Block a user