#include "mlir/Dialect/AMDGPU/Utils/Chipset.h"
#include "mlir/Dialect/GPU/Transforms/Passes.h"
#include "mlir/Dialect/AMDGPU/IR/AMDGPUDialect.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/GPU/IR/GPUDialect.h"
#include "mlir/IR/PatternMatch.h"
#include <optional>
using namespace mlir;
namespace {
constexpr amdgpu::Chipset kGfx950 = amdgpu::Chipset(9, 5, 0);
struct PromoteShuffleToSwizzlePattern
: public OpRewritePattern<gpu::ShuffleOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(gpu::ShuffleOp op,
PatternRewriter &rewriter) const override {
if (op.getMode() != gpu::ShuffleMode::XOR)
return rewriter.notifyMatchFailure(op,
"only xor shuffle mode is supported");
if (!isConstantIntValue(op.getWidth(), 64))
return rewriter.notifyMatchFailure(op,
"only 64 width shuffle is supported");
std::optional<int64_t> offset = getConstantIntValue(op.getOffset());
if (!offset)
return rewriter.notifyMatchFailure(op,
"offset must be a constant integer");
int64_t offsetValue = *offset;
if (offsetValue < 0 || offsetValue >= 32)
return rewriter.notifyMatchFailure(op,
"offset must be in the range [0, 31]");
Location loc = op.getLoc();
Value res = amdgpu::SwizzleBitModeOp::create(
rewriter, loc, op.getResult(0).getType(), op.getValue(), 31,
0, offsetValue);
Value valid = arith::ConstantIntOp::create(rewriter, loc, 1, 1);
rewriter.replaceOp(op, {res, valid});
return success();
}
};
struct PromoteShuffleToPermlanePattern
: public OpRewritePattern<gpu::ShuffleOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(gpu::ShuffleOp op,
PatternRewriter &rewriter) const override {
if (op.getMode() != gpu::ShuffleMode::XOR)
return rewriter.notifyMatchFailure(op,
"only xor shuffle mode is supported");
if (!isConstantIntValue(op.getWidth(), 64))
return rewriter.notifyMatchFailure(op,
"only 64 width shuffle is supported");
std::optional<int64_t> offset = getConstantIntValue(op.getOffset());
if (!offset)
return rewriter.notifyMatchFailure(op,
"offset must be a constant integer");
int64_t offsetValue = *offset;
if (offsetValue != 16 && offsetValue != 32)
return rewriter.notifyMatchFailure(op, "offset must be either 15 or 31");
Location loc = op.getLoc();
Value res = amdgpu::PermlaneSwapOp::create(
rewriter, loc, op.getResult(0).getType(), op.getValue(), offsetValue);
Value valid = arith::ConstantIntOp::create(rewriter, loc, 1, 1);
rewriter.replaceOp(op, {res, valid});
return success();
}
};
}
void mlir::populateGpuPromoteShuffleToAMDGPUPatterns(
RewritePatternSet &patterns, std::optional<amdgpu::Chipset> maybeChipset) {
patterns.add<PromoteShuffleToSwizzlePattern>(patterns.getContext(),
1);
if (maybeChipset && *maybeChipset >= kGfx950)
patterns.add<PromoteShuffleToPermlanePattern>(patterns.getContext(),
2);
}