Skip to content

[Vector] Add canonicalization for select(pred, true, false) -> broadcast(pred) #147934

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 62 additions & 1 deletion mlir/lib/Dialect/Vector/IR/VectorOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2913,13 +2913,74 @@ struct BroadcastFolder : public OpRewritePattern<BroadcastOp> {
return success();
}
};

/// true: vector
/// false: vector
Comment on lines +2917 to +2918
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
/// true: vector
/// false: vector
/// true: vector of i1
/// false: vector of i1

/// pred: i1
///
/// select(pred, true, false) -> broadcast(pred)
/// select(pred, false, true) -> broadcast(not(pred))
///
/// Ideally, this would be a canonicalization pattern on arith::SelectOp, but
Copy link
Contributor

Choose a reason for hiding this comment

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

I think that this paragraph makes more sense near where you register this canonicalization.

/// we cannot have arith depending on vector. Also, it would implicitly force
/// users only using arith and vector dialect to use vector dialect. Instead,
Copy link
Contributor

Choose a reason for hiding this comment

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

Typo?

Suggested change
/// users only using arith and vector dialect to use vector dialect. Instead,
/// users only using arith to use vector dialect. Instead,

/// this canonicalization only runs if vector::BroadcastOp was a registered
/// operation.
struct FoldI1SelectToBroadcast : public OpRewritePattern<arith::SelectOp> {
using OpRewritePattern::OpRewritePattern;

LogicalResult matchAndRewrite(arith::SelectOp selectOp,
PatternRewriter &rewriter) const override {
auto vecType = dyn_cast<VectorType>(selectOp.getType());
if (!vecType || !vecType.getElementType().isInteger(1))
return failure();

// Vector conditionals do not need broadcast and are already handled by
// the arith.select folder.
Value pred = selectOp.getCondition();
if (isa<VectorType>(pred.getType()))
return failure();

std::optional<int64_t> trueInt =
getConstantIntValue(selectOp.getTrueValue());
std::optional<int64_t> falseInt =
getConstantIntValue(selectOp.getFalseValue());
if (!trueInt || !falseInt)
return failure();

// Redundant selects are already handled by arith.select canonicalizations.
if (trueInt.value() == falseInt.value()) {
return failure();
}

// The only remaining possibilities are:
//
// select(pred, true, false)
// select(pred, false, true)

// select(pred, false, true) -> select(not(pred), true, false)
if (trueInt.value() == 0) {
Value one = rewriter.create<arith::ConstantIntOp>(
selectOp.getLoc(), /*value=*/1, /*width=*/1);
pred = rewriter.create<arith::XOrIOp>(selectOp.getLoc(), pred, one);
}

/// select(pred, true, false) -> broadcast(pred)
rewriter.replaceOpWithNewOp<vector::BroadcastOp>(
selectOp, vecType.clone(rewriter.getI1Type()), pred);
return success();

return failure();
Comment on lines +2972 to +2973
Copy link
Member

Choose a reason for hiding this comment

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

dead return

Suggested change
return failure();

}
};

} // namespace

void BroadcastOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
// BroadcastToShapeCast is not a default canonicalization, it is opt-in by
// calling `populateCastAwayVectorLeadingOneDimPatterns`
results.add<BroadcastFolder>(context);
results.add<BroadcastFolder, FoldI1SelectToBroadcast>(context);
Copy link
Member

Choose a reason for hiding this comment

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

Do we have some precedent for canon patterns hooked up to the op they produce?

Copy link
Contributor

Choose a reason for hiding this comment

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

This is quite counter-intuitive :( But not that uncommon:

void TransferWriteOp::getCanonicalizationPatterns(RewritePatternSet &results,
MLIRContext *context) {
results.add<FoldWaw, SwapExtractSliceOfTransferWrite>(context);
}

SwapExtractSliceOfTransferWrite is a canonicalization for xfer_write that matches on tensor.insert_slice.

}

//===----------------------------------------------------------------------===//
Expand Down
32 changes: 32 additions & 0 deletions mlir/test/Dialect/Vector/canonicalize.mlir
Original file line number Diff line number Diff line change
Expand Up @@ -1057,6 +1057,38 @@ func.func @canonicalize_broadcast_shapecast_both_possible(%arg0: vector<1xf32>)

// -----

// CHECK-LABEL: func.func @canonicalize_i1_select_to_broadcast
// CHECK-SAME: (%[[PRED:.+]]: i1)
// CHECK: vector.broadcast %[[PRED]] : i1 to vector<4xi1>
func.func @canonicalize_i1_select_to_broadcast(%pred: i1) -> vector<4xi1> {
%true = arith.constant dense<true> : vector<4x4xi1>
%false = arith.constant dense<false> : vector<4x4xi1>
%selected = arith.select %pred, %true, %false : vector<4x4xi1>
// The select -> broadcast pattern only loads if vector dialect was loaded.
// Force loading vector dialect by adding a vector operation.
%vec = vector.extract %selected[0] : vector<4xi1> from vector<4x4xi1>
return %vec : vector<4xi1>
}

// -----

// CHECK-LABEL: func.func @canonicalize_i1_select_to_not_broadcast
// CHECK-SAME: (%[[PRED:.+]]: i1)
// CHECK: %[[TRUE:.+]] = arith.constant true
// CHECK: %[[NOT:.+]] = arith.xori %[[PRED]], %[[TRUE]] : i1
// CHECK: vector.broadcast %[[NOT]] : i1 to vector<4xi1>
func.func @canonicalize_i1_select_to_not_broadcast(%pred: i1) -> vector<4xi1> {
%true = arith.constant dense<true> : vector<4x4xi1>
%false = arith.constant dense<false> : vector<4x4xi1>
%selected = arith.select %pred, %false, %true : vector<4x4xi1>
// The select -> broadcast pattern only loads if vector dialect was loaded.
// Force loading vector dialect by adding a vector operation.
%vec = vector.extract %selected[0] : vector<4xi1> from vector<4x4xi1>
return %vec : vector<4xi1>
}

// -----

// CHECK-LABEL: fold_vector_transfer_masks
func.func @fold_vector_transfer_masks(%A: memref<?x?xf32>) -> (vector<4x8xf32>, vector<4x[4]xf32>) {
// CHECK: %[[C0:.+]] = arith.constant 0 : index
Expand Down
Loading