#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Arith/Utils/Utils.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/Dialect/Utils/StructuredOpsUtils.h"
#include "mlir/Dialect/Vector/IR/VectorOps.h"
#include "mlir/Dialect/Vector/Transforms/LoweringPatterns.h"
#include "mlir/Dialect/Vector/Utils/VectorUtils.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/TypeUtilities.h"
#define DEBUG_TYPE "vector-broadcast-lowering"
using namespace mlir;
using namespace mlir::vector;
namespace {
struct UnrollGather : OpRewritePattern<vector::GatherOp> {
using Base::Base;
LogicalResult matchAndRewrite(vector::GatherOp op,
PatternRewriter &rewriter) const override {
Value indexVec = op.getIndices();
Value maskVec = op.getMask();
Value passThruVec = op.getPassThru();
auto unrollGatherFn = [&](PatternRewriter &rewriter, Location loc,
VectorType subTy, int64_t index) {
int64_t thisIdx[1] = {index};
Value indexSubVec =
vector::ExtractOp::create(rewriter, loc, indexVec, thisIdx);
Value maskSubVec =
vector::ExtractOp::create(rewriter, loc, maskVec, thisIdx);
Value passThruSubVec =
vector::ExtractOp::create(rewriter, loc, passThruVec, thisIdx);
return vector::GatherOp::create(rewriter, loc, subTy, op.getBase(),
op.getOffsets(), indexSubVec, maskSubVec,
passThruSubVec, op.getAlignmentAttr());
};
return unrollVectorOp(op, rewriter, unrollGatherFn);
}
};
struct RemoveStrideFromGatherSource : OpRewritePattern<vector::GatherOp> {
using Base::Base;
LogicalResult matchAndRewrite(vector::GatherOp op,
PatternRewriter &rewriter) const override {
Value base = op.getBase();
auto subview = base.getDefiningOp<memref::SubViewOp>();
if (!subview)
return failure();
auto sourceType = subview.getSource().getType();
if (sourceType.getRank() != 2)
return failure();
auto layout = subview.getResult().getType().getLayout();
auto stridedLayoutAttr = llvm::dyn_cast<StridedLayoutAttr>(layout);
if (!stridedLayoutAttr)
return failure();
if (stridedLayoutAttr.getStrides().size() != 1)
return failure();
int64_t srcTrailingDim = sourceType.getShape().back();
if (stridedLayoutAttr.getStrides()[0] != srcTrailingDim)
return failure();
SmallVector<ReassociationIndices> reassoc = {{0, 1}};
Value collapsed = memref::CollapseShapeOp::create(
rewriter, op.getLoc(), subview.getSource(), reassoc);
IntegerAttr stride = rewriter.getIndexAttr(srcTrailingDim);
VectorType vType = op.getIndices().getType();
Value mulCst = arith::ConstantOp::create(
rewriter, op.getLoc(), vType, DenseElementsAttr::get(vType, stride));
Value newIdxs =
arith::MulIOp::create(rewriter, op.getLoc(), op.getIndices(), mulCst);
Value newGather = vector::GatherOp::create(
rewriter, op.getLoc(), op.getResult().getType(), collapsed,
op.getOffsets(), newIdxs, op.getMask(), op.getPassThru(),
op.getAlignmentAttr());
rewriter.replaceOp(op, newGather);
return success();
}
};
struct Gather1DToConditionalLoads : OpRewritePattern<vector::GatherOp> {
using Base::Base;
LogicalResult matchAndRewrite(vector::GatherOp op,
PatternRewriter &rewriter) const override {
VectorType resultTy = op.getType();
if (resultTy.getRank() != 1)
return rewriter.notifyMatchFailure(op, "unsupported rank");
if (resultTy.isScalable())
return rewriter.notifyMatchFailure(op, "not a fixed-width vector");
Location loc = op.getLoc();
Type elemTy = resultTy.getElementType();
VectorType elemVecTy = VectorType::get({1}, elemTy);
Value condMask = op.getMask();
Value base = op.getBase();
if (auto memType = dyn_cast<MemRefType>(base.getType())) {
if (auto stridesAttr =
dyn_cast_if_present<StridedLayoutAttr>(memType.getLayout())) {
if (stridesAttr.getStrides().back() != 1 &&
resultTy.getNumElements() != 1)
return failure();
}
}
Value indexVec = rewriter.createOrFold<arith::IndexCastOp>(
loc, op.getIndexVectorType().clone(rewriter.getIndexType()),
op.getIndices());
auto baseOffsets = llvm::to_vector(op.getOffsets());
Value lastBaseOffset = baseOffsets.back();
Value result = op.getPassThru();
BoolAttr nontemporalAttr = nullptr;
IntegerAttr alignmentAttr = op.getAlignmentAttr();
for (int64_t i = 0, e = resultTy.getNumElements(); i < e; ++i) {
int64_t thisIdx[1] = {i};
Value condition =
vector::ExtractOp::create(rewriter, loc, condMask, thisIdx);
Value index = vector::ExtractOp::create(rewriter, loc, indexVec, thisIdx);
baseOffsets.back() =
rewriter.createOrFold<arith::AddIOp>(loc, lastBaseOffset, index);
auto loadBuilder = [&](OpBuilder &b, Location loc) {
Value extracted;
if (isa<MemRefType>(base.getType())) {
Value load =
vector::LoadOp::create(b, loc, elemVecTy, base, baseOffsets,
nontemporalAttr, alignmentAttr);
int64_t zeroIdx[1] = {0};
extracted = vector::ExtractOp::create(b, loc, load, zeroIdx);
} else {
extracted = tensor::ExtractOp::create(b, loc, base, baseOffsets);
}
Value newResult =
vector::InsertOp::create(b, loc, extracted, result, thisIdx);
scf::YieldOp::create(b, loc, newResult);
};
auto passThruBuilder = [result](OpBuilder &b, Location loc) {
scf::YieldOp::create(b, loc, result);
};
result = scf::IfOp::create(rewriter, loc, condition,
loadBuilder,
passThruBuilder)
.getResult(0);
}
rewriter.replaceOp(op, result);
return success();
}
};
}
void mlir::vector::populateVectorGatherLoweringPatterns(
RewritePatternSet &patterns, PatternBenefit benefit) {
patterns.add<UnrollGather>(patterns.getContext(), benefit);
}
void mlir::vector::populateVectorGatherToConditionalLoadPatterns(
RewritePatternSet &patterns, PatternBenefit benefit) {
patterns.add<RemoveStrideFromGatherSource, Gather1DToConditionalLoads>(
patterns.getContext(), benefit);
}