#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Vector/IR/VectorOps.h"
#include "mlir/Dialect/Vector/Transforms/LoweringPatterns.h"
#include "mlir/IR/PatternMatch.h"
#define DEBUG_TYPE "vector-shuffle-lowering"
using namespace mlir;
using namespace mlir::vector;
namespace {
struct MixedSizeInputShuffleOpRewrite final
: OpRewritePattern<vector::ShuffleOp> {
using Base::Base;
LogicalResult matchAndRewrite(vector::ShuffleOp shuffleOp,
PatternRewriter &rewriter) const override {
auto v1Type = shuffleOp.getV1VectorType();
auto v2Type = shuffleOp.getV2VectorType();
if (v1Type.getRank() != 1 || v2Type.getRank() != 1)
return failure();
int64_t v1OrigNumElems = v1Type.getNumElements();
int64_t v2OrigNumElems = v2Type.getNumElements();
if (v1OrigNumElems == v2OrigNumElems)
return failure();
bool promoteV1 = v1OrigNumElems < v2OrigNumElems;
Value inputToPromote = promoteV1 ? shuffleOp.getV1() : shuffleOp.getV2();
VectorType promotedType = promoteV1 ? v2Type : v1Type;
int64_t origNumElems = promoteV1 ? v1OrigNumElems : v2OrigNumElems;
int64_t promotedNumElems = promoteV1 ? v2OrigNumElems : v1OrigNumElems;
SmallVector<int64_t> promoteMask(promotedNumElems, ShuffleOp::kPoisonIndex);
for (int64_t i = 0; i < origNumElems; ++i)
promoteMask[i] = i;
Value promotedInput =
vector::ShuffleOp::create(rewriter, shuffleOp.getLoc(), promotedType,
inputToPromote, inputToPromote, promoteMask);
Value promotedV1 = promoteV1 ? promotedInput : shuffleOp.getV1();
Value promotedV2 = promoteV1 ? shuffleOp.getV2() : promotedInput;
SmallVector<int64_t> newMask;
if (!promoteV1) {
newMask = to_vector(shuffleOp.getMask());
} else {
for (auto idx : shuffleOp.getMask()) {
int64_t newIdx = idx;
if (idx >= v1OrigNumElems) {
newIdx += promotedNumElems - v1OrigNumElems;
}
newMask.push_back(newIdx);
}
}
rewriter.replaceOpWithNewOp<vector::ShuffleOp>(
shuffleOp, shuffleOp.getResultVectorType(), promotedV1, promotedV2,
newMask);
return success();
}
};
}
void mlir::vector::populateVectorShuffleLoweringPatterns(
RewritePatternSet &patterns, PatternBenefit benefit) {
patterns.add<MixedSizeInputShuffleOpRewrite>(patterns.getContext(), benefit);
}