30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/Sequence.h"
32#include "llvm/ADT/SmallVectorExtras.h"
39template <
typename OpTy>
43 typename OpTy::Properties properties{};
44 OpTy::populateDefaultProperties(
47 return OpTy::create(builder, loc, resultTypes, operands, properties,
73template <
typename OpTy>
81 auto nanMode = op.getNanMode();
82 if (nanMode == NanPropagationMode::PROPAGATE)
86 Value lhsIsNaN = arith::CmpFOp::create(rewriter, op.getLoc(),
87 arith::CmpFPredicate::UNO, lhs, lhs);
88 Value rhsIsNaN = arith::CmpFOp::create(rewriter, op.getLoc(),
89 arith::CmpFPredicate::UNO, rhs, rhs);
91 arith::SelectOp::create(rewriter, op.getLoc(), lhsIsNaN, rhs,
result);
92 return arith::SelectOp::create(rewriter, op.getLoc(), rhsIsNaN, lhs,
98 ConversionPatternRewriter &rewriter) {
104 if (isa<tosa::AbsOp>(op) && isa<FloatType>(elementTy))
108 if (isa<tosa::AbsOp>(op) && isa<IntegerType>(elementTy)) {
109 auto zero = arith::ConstantOp::create(rewriter, loc,
110 rewriter.getZeroAttr(elementTy));
111 auto neg = arith::SubIOp::create(rewriter, loc, zero, args[0]);
112 return arith::MaxSIOp::create(rewriter, loc, args[0], neg);
116 if (isa<tosa::AddOp>(op) && isa<FloatType>(elementTy))
120 if (isa<tosa::AddOp>(op) && isa<IntegerType>(elementTy))
125 if (isa<tosa::SubOp>(op) && isa<FloatType>(elementTy))
129 if (isa<tosa::SubOp>(op) && isa<IntegerType>(elementTy))
134 if (isa<tosa::IntDivOp>(op) && isa<IntegerType>(elementTy))
139 if (isa<tosa::ReciprocalOp>(op) && isa<FloatType>(elementTy)) {
141 arith::ConstantOp::create(rewriter, loc, FloatAttr::get(elementTy, 1));
142 return arith::DivFOp::create(rewriter, loc, one, args[0]);
146 if (isa<tosa::MulOp>(op)) {
147 auto shiftVal = cast<tosa::MulOp>(op).getShift();
149 bool shiftIsConstant =
true;
152 shift = shiftElem.
getValues<IntegerAttr>()[0].getInt();
154 shiftIsConstant =
false;
156 if (isa<FloatType>(elementTy)) {
158 (
void)rewriter.notifyMatchFailure(op,
159 "Cannot have shift value for float");
162 return arith::MulFOp::create(rewriter, loc, args[0], args[1]);
165 if (isa<IntegerType>(elementTy)) {
169 if (shift > 0 || !shiftIsConstant) {
176 a = arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(), a);
178 if (!
b.getType().isInteger(32))
179 b = arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(),
b);
181 auto shiftAmount = shiftIsConstant ? shiftConst : args[2];
182 auto roundingAttr = RoundingModeAttr::get(rewriter.getContext(),
183 RoundingMode::SINGLE_ROUND);
185 tosa::ApplyScaleOp::create(rewriter, loc, rewriter.getI32Type(), a,
186 b, shiftAmount, roundingAttr);
192 int bWidth =
b.getType().getIntOrFloatBitWidth();
193 int cWidth = resultTypes[0].getIntOrFloatBitWidth();
196 a = arith::ExtSIOp::create(rewriter, loc, resultTypes[0], a);
198 b = arith::ExtSIOp::create(rewriter, loc, resultTypes[0],
b);
200 return arith::MulIOp::create(rewriter, loc, resultTypes, a,
b);
205 if (isa<tosa::NegateOp>(op)) {
206 auto negate = cast<tosa::NegateOp>(op);
209 FailureOr<int64_t> maybeInZp = negate.getInput1ZeroPoint();
210 FailureOr<int64_t> maybeOutZp = negate.getOutputZeroPoint();
211 bool hasInZp = !failed(maybeInZp);
212 bool hasOutZp = !failed(maybeOutZp);
218 if (isa<FloatType>(elementTy))
219 return arith::NegFOp::create(rewriter, loc, resultTypes, args[0]);
221 if (isa<IntegerType>(elementTy)) {
223 Type intermediateType;
226 int intermediateBitWidth = 64;
228 if (hasInZp && hasOutZp) {
233 const int64_t zpAdd = inZp + outZp;
234 const APInt maxValue =
235 APInt::getSignedMaxValue(inputBitWidth).sext(128) +
240 if (maxValue.sle(APInt::getSignedMaxValue(16).getSExtValue())) {
241 intermediateBitWidth = 16;
242 }
else if (maxValue.sle(APInt::getSignedMaxValue(32).getSExtValue())) {
243 intermediateBitWidth = 32;
246 intermediateType = rewriter.getIntegerType(intermediateBitWidth);
247 zpAddValue = arith::ConstantOp::create(
248 rewriter, loc, rewriter.getIntegerAttr(intermediateType, zpAdd));
250 intermediateType = rewriter.getIntegerType(intermediateBitWidth);
251 Value arg1 = args[1];
252 Value arg2 = args[2];
254 if (arg1.
getType() != intermediateType)
255 arg1 = arith::ExtSIOp::create(rewriter, loc, intermediateType, arg1);
256 if (arg2.
getType() != intermediateType)
257 arg2 = arith::ExtSIOp::create(rewriter, loc, intermediateType, arg2);
259 arith::AddIOp::create(rewriter, loc, intermediateType, arg1, arg2);
265 if (ext.
getType() != intermediateType)
266 ext = arith::ExtSIOp::create(rewriter, loc, intermediateType, ext);
267 auto sub = arith::SubIOp::create(rewriter, loc, zpAddValue, ext);
271 rewriter, loc, intermediateType,
272 APInt::getSignedMinValue(inputBitWidth).getSExtValue());
274 rewriter, loc, intermediateType,
275 APInt::getSignedMaxValue(inputBitWidth).getSExtValue());
279 if (
clamp.getType() == elementTy)
281 return arith::TruncIOp::create(rewriter, loc, elementTy,
clamp);
286 if (isa<tosa::BitwiseAndOp>(op) && isa<IntegerType>(elementTy))
287 return arith::AndIOp::create(rewriter, loc, resultTypes, args);
290 if (isa<tosa::BitwiseOrOp>(op) && isa<IntegerType>(elementTy))
291 return arith::OrIOp::create(rewriter, loc, resultTypes, args);
294 if (isa<tosa::BitwiseNotOp>(op) && isa<IntegerType>(elementTy)) {
295 auto allOnesAttr = rewriter.getIntegerAttr(
296 elementTy, APInt::getAllOnes(elementTy.getIntOrFloatBitWidth()));
297 auto allOnes = arith::ConstantOp::create(rewriter, loc, allOnesAttr);
298 return arith::XOrIOp::create(rewriter, loc, resultTypes, args[0], allOnes);
302 if (isa<tosa::BitwiseXorOp>(op) && isa<IntegerType>(elementTy))
303 return arith::XOrIOp::create(rewriter, loc, resultTypes, args);
306 if (isa<tosa::LogicalLeftShiftOp>(op) && isa<IntegerType>(elementTy))
311 if (isa<tosa::LogicalRightShiftOp>(op) && isa<IntegerType>(elementTy))
316 if (isa<tosa::ArithmeticRightShiftOp>(op) && isa<IntegerType>(elementTy)) {
318 rewriter, loc, resultTypes, args);
319 bool round = cast<tosa::ArithmeticRightShiftOp>(op).getRound();
324 Type i1Ty = IntegerType::get(rewriter.getContext(), 1);
325 auto one = arith::ConstantOp::create(rewriter, loc,
326 IntegerAttr::get(elementTy, 1));
327 auto zero = arith::ConstantOp::create(rewriter, loc,
328 IntegerAttr::get(elementTy, 0));
330 arith::ConstantOp::create(rewriter, loc, IntegerAttr::get(i1Ty, 0));
332 arith::ConstantOp::create(rewriter, loc, IntegerAttr::get(i1Ty, 1));
335 auto shiftValueGreaterThanZero = arith::CmpIOp::create(
336 rewriter, loc, arith::CmpIPredicate::sgt, args[1], zero);
340 arith::SubIOp::create(rewriter, loc, resultTypes, args[1], one);
342 arith::ShRSIOp::create(rewriter, loc, resultTypes, args[0], subtract)
345 rewriter, loc,
TypeRange{i1Ty}, shifted);
347 arith::AndIOp::create(rewriter, loc, i1Ty, truncated, i1one);
349 auto shouldRound = arith::SelectOp::create(
350 rewriter, loc, i1Ty, shiftValueGreaterThanZero, isInputOdd, i1zero);
352 arith::ExtUIOp::create(rewriter, loc, resultTypes, shouldRound);
353 return arith::AddIOp::create(rewriter, loc, resultTypes,
result, extended);
357 if (isa<tosa::ClzOp>(op) && isa<IntegerType>(elementTy)) {
358 return math::CountLeadingZerosOp::create(rewriter, loc, elementTy, args[0]);
362 if (isa<tosa::LogicalAndOp>(op) && elementTy.isInteger(1))
363 return arith::AndIOp::create(rewriter, loc, resultTypes, args);
366 if (isa<tosa::LogicalNotOp>(op) && elementTy.isInteger(1)) {
367 auto one = arith::ConstantOp::create(rewriter, loc,
368 rewriter.getIntegerAttr(elementTy, 1));
369 return arith::XOrIOp::create(rewriter, loc, resultTypes, args[0], one);
373 if (isa<tosa::LogicalOrOp>(op) && elementTy.isInteger(1))
374 return arith::OrIOp::create(rewriter, loc, resultTypes, args);
377 if (isa<tosa::LogicalXorOp>(op) && elementTy.isInteger(1))
378 return arith::XOrIOp::create(rewriter, loc, resultTypes, args);
381 if (isa<tosa::PowOp>(op) && isa<FloatType>(elementTy))
386 if (isa<tosa::RsqrtOp>(op) && isa<FloatType>(elementTy))
391 if (isa<tosa::LogOp>(op) && isa<FloatType>(elementTy))
396 if (isa<tosa::ExpOp>(op) && isa<FloatType>(elementTy))
401 if (isa<tosa::SinOp>(op) && isa<FloatType>(elementTy))
406 if (isa<tosa::CosOp>(op) && isa<FloatType>(elementTy))
411 if (isa<tosa::TanhOp>(op) && isa<FloatType>(elementTy))
416 if (isa<tosa::ErfOp>(op) && llvm::isa<FloatType>(elementTy))
421 if (isa<tosa::GreaterOp>(op) && isa<FloatType>(elementTy))
422 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::OGT,
425 if (isa<tosa::GreaterOp>(op) && elementTy.isSignlessInteger())
426 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::sgt,
430 if (isa<tosa::GreaterEqualOp>(op) && isa<FloatType>(elementTy))
431 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::OGE,
434 if (isa<tosa::GreaterEqualOp>(op) && elementTy.isSignlessInteger())
435 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::sge,
439 if (isa<tosa::EqualOp>(op) && isa<FloatType>(elementTy))
440 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::OEQ,
443 if (isa<tosa::EqualOp>(op) && elementTy.isSignlessInteger())
444 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::eq,
448 if (isa<tosa::SelectOp>(op)) {
450 if (isa<FloatType>(elementTy) || isa<IntegerType>(elementTy))
451 return arith::SelectOp::create(rewriter, loc, args[0], args[1], args[2]);
455 if (isa<tosa::MaximumOp>(op) && isa<FloatType>(elementTy)) {
456 auto max = arith::MaximumFOp::create(rewriter, loc, args[0], args[1]);
458 rewriter, args[0], args[1],
max);
461 if (isa<tosa::MaximumOp>(op) && elementTy.isSignlessInteger()) {
462 return arith::MaxSIOp::create(rewriter, loc, args[0], args[1]);
466 if (isa<tosa::MinimumOp>(op) && isa<FloatType>(elementTy)) {
467 auto min = arith::MinimumFOp::create(rewriter, loc, args[0], args[1]);
469 rewriter, args[0], args[1],
min);
472 if (isa<tosa::MinimumOp>(op) && elementTy.isSignlessInteger()) {
473 return arith::MinSIOp::create(rewriter, loc, args[0], args[1]);
477 if (isa<tosa::CeilOp>(op) && isa<FloatType>(elementTy))
482 if (isa<tosa::FloorOp>(op) && isa<FloatType>(elementTy))
487 if (isa<tosa::ClampOp>(op) && isa<FloatType>(elementTy)) {
488 bool losesInfo =
false;
489 auto clampOp = cast<tosa::ClampOp>(op);
490 APFloat minApf = cast<FloatAttr>(clampOp.getMinValAttr()).getValue();
491 APFloat maxApf = cast<FloatAttr>(clampOp.getMaxValAttr()).getValue();
493 APFloat::rmNearestTiesToEven, &losesInfo);
495 APFloat::rmNearestTiesToEven, &losesInfo);
496 auto min = arith::ConstantOp::create(
497 rewriter, loc, elementTy, rewriter.getFloatAttr(elementTy, minApf));
498 auto max = arith::ConstantOp::create(
499 rewriter, loc, elementTy, rewriter.getFloatAttr(elementTy, maxApf));
502 const auto nanMode = clampOp.getNanMode();
505 if (!isa<FloatType>(elementTy))
510 if (nanMode == NanPropagationMode::PROPAGATE)
524 Value isNaN = arith::CmpFOp::create(
525 rewriter, op->
getLoc(), arith::CmpFPredicate::UNO, args[0], args[0]);
528 return arith::SelectOp::create(rewriter, op->
getLoc(), isNaN,
min,
result);
531 if (isa<tosa::ClampOp>(op) && isa<IntegerType>(elementTy)) {
532 auto intTy = cast<IntegerType>(elementTy);
533 auto clampOp = cast<tosa::ClampOp>(op);
535 cast<IntegerAttr>(clampOp.getMinValAttr()).getValue().getSExtValue();
537 cast<IntegerAttr>(clampOp.getMaxValAttr()).getValue().getSExtValue();
539 int64_t minRepresentable = std::numeric_limits<int64_t>::min();
540 int64_t maxRepresentable = std::numeric_limits<int64_t>::max();
541 if (intTy.isUnsignedInteger()) {
542 minRepresentable = 0;
543 if (intTy.getIntOrFloatBitWidth() <= 63) {
545 (
int64_t)APInt::getMaxValue(intTy.getIntOrFloatBitWidth())
548 }
else if (intTy.getIntOrFloatBitWidth() <= 64) {
550 minRepresentable = APInt::getSignedMinValue(intTy.getIntOrFloatBitWidth())
552 maxRepresentable = APInt::getSignedMaxValue(intTy.getIntOrFloatBitWidth())
557 min = std::max(
min, minRepresentable);
558 max = std::max(
max, minRepresentable);
559 min = std::min(
min, maxRepresentable);
560 max = std::min(
max, maxRepresentable);
563 intTy.getIntOrFloatBitWidth());
565 intTy.getIntOrFloatBitWidth());
567 intTy.isUnsignedInteger());
571 if (isa<tosa::SigmoidOp>(op) && isa<FloatType>(elementTy)) {
573 arith::ConstantOp::create(rewriter, loc, FloatAttr::get(elementTy, 1));
574 auto negate = arith::NegFOp::create(rewriter, loc, resultTypes, args[0]);
575 auto exp = mlir::math::ExpOp::create(rewriter, loc, resultTypes, negate);
576 auto added = arith::AddFOp::create(rewriter, loc, exp, one);
577 return arith::DivFOp::create(rewriter, loc, one, added);
581 if (isa<tosa::CastOp>(op)) {
582 Type srcTy = elementTy;
583 Type dstTy = resultTypes.front();
585 (
void)rewriter.notifyMatchFailure(op,
"unsupported type");
593 bool inputUnsigned = cast<tosa::CastOp>(op).getInputUnsigned();
598 if (isa<FloatType>(srcTy) && isa<FloatType>(dstTy) && bitExtend)
602 if (isa<FloatType>(srcTy) && isa<FloatType>(dstTy) && !bitExtend)
607 if (srcTy.
isInteger(1) && arith::UIToFPOp::areCastCompatible(srcTy, dstTy))
611 if (srcTy.
isInteger(1) && isa<IntegerType>(dstTy) && bitExtend)
618 auto unrealizedCast =
619 UnrealizedConversionCastOp::create(
623 return arith::UIToFPOp::create(rewriter, loc, resultTypes[0],
628 if (inputUnsigned && arith::UIToFPOp::areCastCompatible(srcTy, dstTy))
633 if (arith::SIToFPOp::areCastCompatible(srcTy, dstTy))
634 return arith::SIToFPOp::create(rewriter, loc, resultTypes, args,
638 if (isa<FloatType>(srcTy) && dstTy.
isInteger(1)) {
639 Value zero = arith::ConstantOp::create(rewriter, loc,
640 rewriter.getFloatAttr(srcTy, 0.0));
641 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::UNE,
645 if (arith::FPToSIOp::areCastCompatible(srcTy, dstTy)) {
646 auto rounded = math::RoundEvenOp::create(rewriter, loc, args[0]);
648 const auto &fltSemantics = cast<FloatType>(srcTy).getFloatSemantics();
652 APFloat::semanticsMaxExponent(fltSemantics)) {
655 auto conv = arith::FPToSIOp::create(rewriter, loc, dstTy, rounded);
656 auto posInf = arith::ConstantOp::create(
659 APFloat::getInf(fltSemantics)));
660 auto negInf = arith::ConstantOp::create(
662 rewriter.getFloatAttr(
664 APFloat::getInf(fltSemantics,
true)));
665 auto overflow = arith::CmpFOp::create(
666 rewriter, loc, arith::CmpFPredicate::UEQ, rounded, posInf);
667 auto underflow = arith::CmpFOp::create(
668 rewriter, loc, arith::CmpFPredicate::UEQ, rounded, negInf);
669 auto intMin = arith::ConstantOp::create(
671 rewriter.getIntegerAttr(
674 auto intMax = arith::ConstantOp::create(
676 rewriter.getIntegerAttr(
680 arith::SelectOp::create(rewriter, loc, overflow, intMax, conv);
681 return arith::SelectOp::create(rewriter, loc, underflow, intMin,
685 auto intMinFP = arith::ConstantOp::create(
687 rewriter.getFloatAttr(
693 if (cast<FloatType>(srcTy).getFPMantissaWidth() >=
699 auto intMaxFP = arith::ConstantOp::create(
701 rewriter.getFloatAttr(
708 return arith::FPToSIOp::create(rewriter, loc, dstTy, clamped);
715 auto intMaxPlusOneFP = arith::ConstantOp::create(
717 rewriter.getFloatAttr(
724 auto intMax = arith::ConstantOp::create(
726 rewriter.getIntegerAttr(
730 arith::MaximumFOp::create(rewriter, loc, rounded, intMinFP);
732 arith::FPToSIOp::create(rewriter, loc, dstTy, minClampedFP);
733 auto overflow = arith::CmpFOp::create(
734 rewriter, loc, arith::CmpFPredicate::UGE, rounded, intMaxPlusOneFP);
735 return arith::SelectOp::create(rewriter, loc, overflow, intMax,
741 if (isa<IntegerType>(srcTy) && dstTy.
isInteger(1)) {
744 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::ne,
749 if (inputUnsigned && isa<IntegerType>(srcTy) && isa<IntegerType>(dstTy) &&
754 if (isa<IntegerType>(srcTy) && isa<IntegerType>(dstTy) && bitExtend)
755 return arith::ExtSIOp::create(rewriter, loc, resultTypes, args,
758 if (isa<IntegerType>(srcTy) && isa<IntegerType>(dstTy) && !bitExtend) {
759 return arith::TruncIOp::create(rewriter, loc, dstTy, args[0]);
763 (
void)rewriter.notifyMatchFailure(
764 op,
"unhandled op for linalg body calculation for elementwise op");
783 return tensor::DimOp::create(rewriter, loc,
tensor, indexValue).getResult();
789 auto shapedType = dyn_cast<ShapedType>(
tensor.getType());
790 assert(shapedType && shapedType.hasRank() &&
"expected a ranked shaped type");
791 assert(
index >= 0 &&
index < shapedType.getRank() &&
"index out of bounds");
792 if (shapedType.isDynamicDim(
index))
798 auto isRanked = [](
Value value) {
799 return isa<RankedTensorType>(value.getType());
801 return llvm::all_of(operation->
getOperands(), isRanked) &&
802 llvm::all_of(operation->
getResults(), isRanked);
815std::pair<OpFoldResult, Value>
822 for (
auto operand : operands) {
823 auto size = cast<RankedTensorType>(operand.getType()).getDimSize(dim);
824 if (ShapedType::isStatic(size) && size > 1)
829 auto operandsWithDynamicDim =
830 llvm::filter_to_vector(operands, [&](
Value operand) {
831 return cast<RankedTensorType>(operand.
getType()).isDynamicDim(dim);
835 if (operandsWithDynamicDim.empty())
842 getTensorDim(rewriter, loc, indexPool, operandsWithDynamicDim[0], dim);
843 if (operandsWithDynamicDim.size() == 1)
844 return {targetSize, operandsWithDynamicDim[0]};
847 for (
size_t i = 1; i < operandsWithDynamicDim.size(); i++) {
849 getTensorDim(rewriter, loc, indexPool, operandsWithDynamicDim[i], dim);
850 targetSize = arith::MaxUIOp::create(rewriter, loc, targetSize, nextSize);
852 return {targetSize,
nullptr};
860 assert(!operands.empty());
861 auto rank = cast<RankedTensorType>(operands.front().
getType()).getRank();
864 for (
auto dim : llvm::seq<int64_t>(0, rank)) {
865 auto [targetSize, masterOperand] =
867 targetShape.push_back(targetSize);
868 masterOperands.push_back(masterOperand);
870 return {targetShape, masterOperands};
876 Value masterOperand) {
878 auto rankedTensorType = cast<RankedTensorType>(operand.
getType());
879 if (!rankedTensorType.isDynamicDim(dim))
886 if (operand == masterOperand)
890 auto rank = rankedTensorType.getRank();
892 for (
auto index : llvm::seq<int64_t>(0, rank)) {
895 affineExprs.push_back(affineExpr);
897 auto broadcastAffineMap =
903 auto one =
createIndex(rewriter, loc, indexPool, 1);
904 auto runtimeSize =
getTensorDim(rewriter, loc, indexPool, operand, dim);
905 auto broadcastNecessary = arith::CmpIOp::create(
906 rewriter, loc, arith::CmpIPredicate::eq, runtimeSize, one);
916 for (
auto index : llvm::seq<int64_t>(0, rank)) {
917 auto size =
index == dim ? targetSize
920 outputTensorShape.push_back(size);
922 Value outputTensor = tensor::EmptyOp::create(
923 opBuilder, loc, outputTensorShape, rankedTensorType.getElementType());
927 linalg::GenericOp::create(
928 opBuilder, loc, outputTensor.
getType(), operand, outputTensor,
932 linalg::YieldOp::create(opBuilder, loc, blockArgs.front());
937 auto castResultTensor = rewriter.
createOrFold<tensor::CastOp>(
938 loc, operand.
getType(), resultTensor);
941 scf::YieldOp::create(opBuilder, loc, castResultTensor);
946 scf::YieldOp::create(opBuilder, loc, operand);
950 auto ifOp = scf::IfOp::create(rewriter, loc, broadcastNecessary,
951 emitThenRegion, emitElseRegion);
952 return ifOp.getResult(0);
959 int64_t rank = cast<RankedTensorType>(operand.
getType()).getRank();
960 assert((
int64_t)targetShape.size() == rank);
961 assert((
int64_t)masterOperands.size() == rank);
962 for (
auto index : llvm::seq<int64_t>(0, rank))
975 if (operands.size() == 1)
979 bool hasDynamic =
false;
980 for (
auto op : operands) {
981 const auto tType = dyn_cast<RankedTensorType>(op.getType());
982 if (tType && !tType.hasStaticShape()) {
991 return llvm::map_to_vector(operands, [&](
Value operand) {
993 targetShape, masterOperands);
1002 auto resultType = cast_or_null<RankedTensorType>(
1005 return rewriter.notifyMatchFailure(operation,
"failed to convert type");
1007 Value outputTensor = tensor::EmptyOp::create(rewriter, loc, targetShape,
1008 resultType.getElementType());
1013 auto rank = resultType.getRank();
1014 auto affineMaps = llvm::map_to_vector(operands, [&](
Value operand) {
1015 auto shape = cast<ShapedType>(operand.
getType()).getShape();
1017 for (
auto it : llvm::enumerate(
shape)) {
1021 bool requiresBroadcast =
1022 (it.value() == 1 && resultType.getDimSize(it.index()) != 1);
1023 auto affineExpr = requiresBroadcast
1024 ? rewriter.getAffineConstantExpr(0)
1025 : rewriter.getAffineDimExpr(it.index());
1026 affineExprs.push_back(affineExpr);
1028 return AffineMap::get(rank, 0, affineExprs, rewriter.getContext());
1032 for (
Value scalar : scalarOperands) {
1033 auto scalarRank = cast<ShapedType>(scalar.getType()).getRank();
1035 rewriter.getAffineConstantExpr(0));
1036 affineMaps.push_back(
AffineMap::get(rank, 0, zeros, rewriter.getContext()));
1038 affineMaps.push_back(rewriter.getMultiDimIdentityMap(rank));
1041 llvm::append_range(inputs, scalarOperands);
1044 bool encounteredError =
false;
1045 auto linalgOp = linalg::GenericOp::create(
1046 rewriter, loc, outputTensor.
getType(), inputs, outputTensor, affineMaps,
1051 {resultType.getElementType()}, rewriter);
1053 encounteredError =
true;
1056 linalg::YieldOp::create(opBuilder, loc, opResult);
1058 if (encounteredError)
1059 return rewriter.notifyMatchFailure(
1060 operation,
"unable to create linalg.generic body for elementwise op");
1063 auto castResult = rewriter.createOrFold<tensor::CastOp>(
1064 loc, resultType, linalgOp->getResult(0));
1065 rewriter.replaceOp(operation, castResult);
1073 if (isa<tosa::MulOp>(operation))
1074 return operands.take_front(2);
1075 if (isa<tosa::NegateOp>(operation))
1076 return operands.take_front(1);
1084 if (isa<tosa::MulOp>(operation)) {
1088 return operands.drop_front(2);
1090 if (
auto negate = dyn_cast<tosa::NegateOp>(operation)) {
1091 if (succeeded(negate.getInput1ZeroPoint()) &&
1092 succeeded(negate.getOutputZeroPoint()))
1094 return operands.drop_front(1);
1101 ConversionPatternRewriter &rewriter,
1105 assert(operation->
getNumResults() == 1 &&
"elementwise op expects 1 result");
1107 "elementwise op expects at least 1 operand");
1109 return rewriter.notifyMatchFailure(operation,
1110 "Unranked tensors not supported");
1114 auto loc = operation->
getLoc();
1117 auto [targetShape, masterOperands] =
1119 auto broadcastOperands =
1121 targetShape, masterOperands);
1123 scalarOperands, targetShape, converter);
1130 bool allowNonFinites) {
1131 if (isa<tosa::ReduceSumOp>(op) && isa<FloatType>(elementTy))
1134 if (isa<tosa::ReduceSumOp>(op) && isa<IntegerType>(elementTy))
1137 if (isa<tosa::ReduceProductOp>(op) && isa<FloatType>(elementTy))
1140 if (isa<tosa::ReduceProductOp>(op) && isa<IntegerType>(elementTy))
1143 if (isa<tosa::ReduceMinOp>(op) && isa<FloatType>(elementTy))
1147 false, allowNonFinites));
1149 if (isa<tosa::ReduceMinOp>(op) && isa<IntegerType>(elementTy))
1153 if (isa<tosa::ReduceMaxOp>(op) && isa<FloatType>(elementTy))
1157 true, allowNonFinites));
1159 if (isa<tosa::ReduceMaxOp>(op) && isa<IntegerType>(elementTy))
1163 if (isa<tosa::ReduceAllOp>(op) && elementTy.
isInteger(1))
1166 if (isa<tosa::ReduceAnyOp>(op) && elementTy.
isInteger(1))
1169 if (isa<tosa::ArgMaxOp, tosa::ArgMinOp>(op) && isa<FloatType>(elementTy)) {
1170 const bool isMax = isa<tosa::ArgMaxOp>(op);
1171 const auto nanMode = isMax ? cast<tosa::ArgMaxOp>(op).getNanMode()
1172 : cast<tosa::ArgMinOp>(op).getNanMode();
1174 auto floatTy = dyn_cast<FloatType>(elementTy);
1175 const auto &semantics = floatTy.getFloatSemantics();
1177 const bool useNaN = nanMode == NanPropagationMode::IGNORE &&
1178 APFloat::semanticsHasNaN(semantics);
1180 useNaN ? APFloat::getQNaN(semantics)
1187 if (isa<tosa::ArgMaxOp>(op) && isa<IntegerType>(elementTy))
1191 if (isa<tosa::ArgMinOp>(op) && isa<IntegerType>(elementTy))
1205 if (isa<tosa::ReduceSumOp>(op) && isa<FloatType>(elementTy)) {
1207 rewriter, loc,
TypeRange{elementTy}, args);
1210 if (isa<tosa::ReduceSumOp>(op) && isa<IntegerType>(elementTy)) {
1212 rewriter, loc,
TypeRange{elementTy}, args);
1215 if (isa<tosa::ReduceProductOp>(op) && isa<FloatType>(elementTy)) {
1217 rewriter, loc,
TypeRange{elementTy}, args);
1220 if (isa<tosa::ReduceProductOp>(op) && isa<IntegerType>(elementTy)) {
1222 rewriter, loc,
TypeRange{elementTy}, args);
1225 if (isa<tosa::ReduceMinOp>(op) && isa<FloatType>(elementTy)) {
1226 return arith::MinimumFOp::create(rewriter, loc, args[0], args[1]);
1229 if (isa<tosa::ReduceMinOp>(op) && isa<IntegerType>(elementTy)) {
1230 return arith::MinSIOp::create(rewriter, loc, args[0], args[1]);
1233 if (isa<tosa::ReduceMaxOp>(op) && isa<FloatType>(elementTy)) {
1234 return arith::MaximumFOp::create(rewriter, loc, args[0], args[1]);
1237 if (isa<tosa::ReduceMaxOp>(op) && isa<IntegerType>(elementTy)) {
1238 return arith::MaxSIOp::create(rewriter, loc, args[0], args[1]);
1241 if (isa<tosa::ReduceAllOp>(op) && elementTy.
isInteger(1))
1242 return arith::AndIOp::create(rewriter, loc, args);
1244 if (isa<tosa::ReduceAnyOp>(op) && elementTy.
isInteger(1))
1245 return arith::OrIOp::create(rewriter, loc, args);
1253template <
typename OpTy>
1256 bool allowNonFinites) {
1257 auto loc = op->getLoc();
1258 auto inputTy = dyn_cast<RankedTensorType>(op->getOperand(0).getType());
1259 auto resultTy = dyn_cast<RankedTensorType>(op->getResult(0).getType());
1260 if (!inputTy || !resultTy)
1263 auto elementTy = resultTy.getElementType();
1264 Value input = op->getOperand(0);
1267 constexpr bool isArithmeticReduction =
1268 std::is_same_v<OpTy, tosa::ReduceSumOp> ||
1269 std::is_same_v<OpTy, tosa::ReduceProductOp>;
1272 bool widenAccTy = accTy != elementTy;
1276 for (
unsigned i = 0; i < inputTy.getRank(); i++) {
1278 reduceShape.push_back(inputTy.getDimSize(i));
1279 if (inputTy.isDynamicDim(i))
1280 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
1285 inputs.push_back(input);
1289 tensor::EmptyOp::create(rewriter, loc, reduceShape, accTy, dynDims)
1292 auto fillValueAttr =
1296 op,
"No initial value found for reduction operation");
1298 auto fillValue = arith::ConstantOp::create(rewriter, loc, fillValueAttr);
1300 linalg::FillOp::create(rewriter, loc,
ValueRange{fillValue},
1303 outputs.push_back(filledTensor);
1305 bool isNanIgnoreMode =
false;
1306 if constexpr (std::is_same_v<OpTy, tosa::ReduceMinOp> ||
1307 std::is_same_v<OpTy, tosa::ReduceMaxOp>) {
1309 if (isa<FloatType>(elementTy) &&
1310 op.getNanMode() == NanPropagationMode::IGNORE) {
1311 isNanIgnoreMode =
true;
1317 auto trueValue = arith::ConstantOp::create(rewriter, loc, trueAttr);
1318 auto emptyBoolTensor =
1319 tensor::EmptyOp::create(rewriter, loc, reduceShape,
1320 trueValue.getType(), dynDims)
1322 auto allResultsNaNTensor =
1323 linalg::FillOp::create(rewriter, loc,
ValueRange{trueValue},
1335 inputs.push_back(input);
1336 outputs.push_back(allResultsNaNTensor);
1340 bool didEncounterError =
false;
1341 linalg::LinalgOp linalgOp = linalg::ReduceOp::create(
1342 rewriter, loc, inputs, outputs, axis,
1344 std::array<Value, 2> binaryArgs{
1345 blockArgs[0], isNanIgnoreMode ? blockArgs[2] : blockArgs[1]};
1348 if (binaryArgs[0].
getType() != accTy)
1349 binaryArgs[0] = arith::ExtFOp::create(
1350 nestedBuilder, nestedLoc,
TypeRange{accTy},
1351 ValueRange{binaryArgs[0]}, arith::ExtFOp::Properties{});
1356 didEncounterError =
true;
1359 if (isNanIgnoreMode) {
1360 auto inputValue = blockArgs[0];
1361 auto initialValue = blockArgs[2];
1362 auto oldAllResultsNanFlagValue = blockArgs[3];
1365 Value isNaN = arith::CmpFOp::create(nestedBuilder, op->getLoc(),
1366 arith::CmpFPredicate::UNO,
1367 inputValue, inputValue);
1369 auto selectOp = arith::SelectOp::create(nestedBuilder, op->getLoc(),
1370 isNaN, initialValue,
result);
1373 auto newAllResultsNanFlagValue = arith::AndIOp::create(
1374 nestedBuilder, op->getLoc(), oldAllResultsNanFlagValue, isNaN);
1375 resultsToYield.push_back(selectOp);
1376 resultsToYield.push_back(newAllResultsNanFlagValue);
1378 resultsToYield.push_back(
result);
1380 linalg::YieldOp::create(nestedBuilder, loc, resultsToYield);
1383 if (!didEncounterError)
1385 op,
"unable to create linalg.generic body for reduce op");
1387 if (isNanIgnoreMode) {
1397 auto nanValue = arith::ConstantOp::create(rewriter, loc, nanValueAttr);
1398 auto emptyNanTensor =
1399 tensor::EmptyOp::create(rewriter, loc, reduceShape, accTy, dynDims)
1401 auto nanFilledTensor =
1402 linalg::FillOp::create(rewriter, loc,
ValueRange{nanValue},
1408 auto finalEmptyTensor =
1409 tensor::EmptyOp::create(rewriter, loc, reduceShape, accTy, dynDims)
1415 ins.push_back(linalgOp->getOpResult(1));
1416 ins.push_back(nanFilledTensor);
1417 ins.push_back(linalgOp->getResult(0));
1418 outs.push_back(finalEmptyTensor);
1420 linalg::ElementwiseOp::create(rewriter, op->getLoc(), ins, outs,
1421 mlir::linalg::ElementwiseKind::select);
1422 linalgOp = linalgSelect;
1426 Value reducedRes = linalgOp->getResult(0);
1429 tensor::EmptyOp::create(rewriter, loc, reduceShape, elementTy, dynDims)
1432 const unsigned reducedRank =
1433 cast<ShapedType>(reducedRes.
getType()).getRank();
1436 linalg::GenericOp::create(
1442 Value truncf = arith::TruncFOp::create(nestedBuilder, nestedLoc,
1443 elementTy, args[0]);
1444 linalg::YieldOp::create(nestedBuilder, nestedLoc, truncf);
1450 uint64_t expandInputRank = cast<ShapedType>(reducedRes.
getType()).getRank();
1451 reassociationMap.resize(expandInputRank);
1453 for (uint64_t i = 0; i < expandInputRank; i++) {
1454 int32_t dimToPush = i > axis ? i + 1 : i;
1458 if (expandInputRank != 0) {
1459 int32_t expandedDim = axis < expandInputRank ? axis : expandInputRank - 1;
1460 reassociationMap[expandedDim].push_back(
1477 auto type = cast<RankedTensorType>(operand.
getType());
1479 cast<RankedTensorType>(other.
getType()).getRank() - type.getRank();
1480 if (missingDims <= 0)
1485 for (
int64_t dim = 0; dim < missingDims; ++dim) {
1487 dimensions.push_back(dim);
1490 Value empty = tensor::EmptyOp::create(
1491 rewriter, loc,
shape, type.getElementType(), type.getEncoding());
1492 return linalg::BroadcastOp::create(rewriter, loc, operand, empty, dimensions)
1504 auto type = cast<RankedTensorType>(operand.
getType());
1506 sliceShape.erase(sliceShape.begin() + dim);
1507 auto sliceType = RankedTensorType::get(sliceShape, type.getElementType(),
1508 type.getEncoding());
1510 rewriter, loc, operand, sliceType);
1515 Value empty = tensor::EmptyOp::create(
1516 rewriter, loc,
shape, type.getElementType(), type.getEncoding());
1517 return linalg::BroadcastOp::create(rewriter, loc,
slice, empty,
1524static std::pair<Value, Value>
1528 int64_t bRank = cast<RankedTensorType>(
b.getType()).getRank();
1529 int64_t firstSharedDim = std::max(aRank, bRank) - std::min(aRank, bRank);
1535 for (
int64_t dim = firstSharedDim; dim < batchRank; ++dim) {
1536 auto aType = cast<RankedTensorType>(a.
getType());
1537 auto bType = cast<RankedTensorType>(
b.getType());
1538 int64_t aSize = aType.getDimSize(dim);
1539 int64_t bSize = bType.getDimSize(dim);
1540 if (aSize == bSize && ShapedType::isStatic(aSize))
1545 auto [size, masterOperand] =
1566 RankedTensorType outputType,
1568 const int64_t outputRank = outputType.getRank();
1569 const int64_t batchRank = outputRank - 2;
1570 auto normalizedOperands =
1572 a = normalizedOperands.first;
1573 b = normalizedOperands.second;
1576 outputShape.reserve(outputRank);
1577 for (
int64_t batchDim = 0; batchDim < batchRank; ++batchDim)
1580 outputShape.push_back(
1583 for (
auto [dim, size] : llvm::enumerate(outputShape))
1584 if (outputType.isDynamicDim(dim))
1585 dynamicDims.push_back(
1588 Value zero = arith::ConstantOp::create(
1589 rewriter, loc, rewriter.
getZeroAttr(outputType.getElementType()));
1590 Value emptyTensor = tensor::EmptyOp::create(rewriter, loc, outputType,
1592 Value zeroTensor = linalg::FillOp::create(rewriter, loc,
ValueRange{zero},
1596 return {a,
b, zeroTensor};
1600 if (requestedType.
isBF16())
1601 return Float32Type::get(requestedType.
getContext());
1602 return requestedType;
1608 RankedTensorType targetType) {
1609 auto inputType = cast<RankedTensorType>(input.
getType());
1611 if (inputType == targetType)
1614 assert(inputType.getShape() == targetType.getShape() &&
1615 "element conversion must preserve shape");
1616 assert(inputType.getEncoding() == targetType.getEncoding() &&
1617 "element conversion must preserve encoding");
1619 Type targetElementType = targetType.getElementType();
1621 assert(inputType.getElementType().isF32() && targetElementType.
isBF16() &&
1622 "expected FP32-to-BF16 truncation");
1625 for (
int64_t dim = 0; dim < targetType.getRank(); ++dim) {
1626 if (targetType.isDynamicDim(dim))
1627 dynamicDims.push_back(tensor::DimOp::create(rewriter, loc, input, dim));
1630 auto empty = tensor::EmptyOp::create(rewriter, loc, targetType, dynamicDims);
1633 auto converted = linalg::GenericOp::create(
1634 rewriter, loc, targetType,
ValueRange{input},
1639 Value truncated = arith::TruncFOp::create(builder, nestedLoc,
1640 targetElementType, args[0]);
1641 linalg::YieldOp::create(builder, nestedLoc, truncated);
1651class QuantizedMatMulTConverter :
public OpConversionPattern<tosa::MatMulTOp> {
1653 using OpConversionPattern<tosa::MatMulTOp>::OpConversionPattern;
1655 matchAndRewrite(tosa::MatMulTOp op, OpAdaptor adaptor,
1656 ConversionPatternRewriter &rewriter)
const final {
1658 auto aType = dyn_cast<RankedTensorType>(adaptor.getA().getType());
1659 auto bType = dyn_cast<RankedTensorType>(adaptor.getB().getType());
1660 auto outputType = dyn_cast<RankedTensorType>(op.getType());
1661 if (!aType || !bType || !outputType)
1662 return rewriter.notifyMatchFailure(op,
"only supports ranked tensors");
1664 FailureOr<int64_t> maybeAZp = op.getAZeroPoint();
1665 FailureOr<int64_t> maybeBZp = op.getBZeroPoint();
1666 if (failed(maybeAZp))
1667 return rewriter.notifyMatchFailure(
1668 op,
"input A zero point cannot be statically determined");
1669 if (failed(maybeBZp))
1670 return rewriter.notifyMatchFailure(
1671 op,
"input B zero point cannot be statically determined");
1673 const int64_t aZpVal = *maybeAZp;
1674 const int64_t bZpVal = *maybeBZp;
1676 if (aZpVal == 0 && bZpVal == 0)
1677 return rewriter.notifyMatchFailure(
1678 op,
"requires at least one nonzero zero point");
1680 const int64_t outputRank = outputType.getRank();
1681 const int64_t batchRank = outputRank - 2;
1682 auto [a,
b, zeroTensor] =
1685 Type outputElementType = outputType.getElementType();
1687 int64_t loopRank = outputRank + 1;
1689 llvm::map_to_vector(llvm::seq<int64_t>(0, loopRank), [&](
int64_t dim) {
1690 return rewriter.getAffineDimExpr(dim);
1693 dimensions.begin() + batchRank);
1694 aMap.push_back(dimensions[batchRank]);
1695 aMap.push_back(dimensions[batchRank + 2]);
1697 dimensions.begin() + batchRank);
1698 bMap.push_back(dimensions[batchRank + 1]);
1699 bMap.push_back(dimensions[batchRank + 2]);
1701 dimensions.begin() + batchRank);
1702 outputMap.push_back(dimensions[batchRank]);
1703 outputMap.push_back(dimensions[batchRank + 1]);
1708 SmallVector<utils::IteratorType> iteratorTypes(
1709 loopRank, utils::IteratorType::parallel);
1710 iteratorTypes.back() = utils::IteratorType::reduction;
1712 auto generic = linalg::GenericOp::create(
1713 rewriter, loc, outputType,
ValueRange{a,
b}, zeroTensor, indexingMaps,
1715 [=](OpBuilder &builder, Location nestedLoc,
ValueRange args) {
1716 auto extendToOutputType = [&](Value value) {
1717 if (value.getType() == outputElementType)
1719 return arith::ExtSIOp::create(builder, nestedLoc, outputElementType,
1724 Value aValue = extendToOutputType(args[0]);
1725 Value bValue = extendToOutputType(args[1]);
1726 Value aZp = arith::ConstantOp::create(
1728 builder.getIntegerAttr(outputElementType, aZpVal));
1729 Value bZp = arith::ConstantOp::create(
1731 builder.getIntegerAttr(outputElementType, bZpVal));
1733 arith::SubIOp::create(builder, nestedLoc, aValue, aZp);
1735 arith::SubIOp::create(builder, nestedLoc, bValue, bZp);
1737 arith::MulIOp::create(builder, nestedLoc, adjustedA, adjustedB);
1739 arith::AddIOp::create(builder, nestedLoc, args[2],
product);
1740 linalg::YieldOp::create(builder, nestedLoc, sum);
1742 rewriter.replaceOp(op, generic.getResult(0));
1747template <
typename SrcOp>
1748class PointwiseConverter :
public OpConversionPattern<SrcOp> {
1750 using OpConversionPattern<SrcOp>::OpConversionPattern;
1751 using typename OpConversionPattern<SrcOp>::OpAdaptor;
1754 matchAndRewrite(SrcOp op, OpAdaptor operands,
1755 ConversionPatternRewriter &rewriter)
const final {
1757 op, operands.getOperands(), rewriter, *
this->getTypeConverter());
1767 auto inputType = cast<RankedTensorType>(input.
getType());
1768 auto elemType = inputType.getElementType();
1769 auto collapsedType = RankedTensorType::get({}, elemType);
1771 return tensor::CollapseShapeOp::create(rewriter, loc, collapsedType, input,
1778 output.reserve(input.size());
1780 for (
auto v : llvm::map_range(
1781 input, [](int32_t val) {
return static_cast<int8_t
>(val); })) {
1782 output.push_back(v);
1794static void setupLinalgGenericOpInputAndIndexingMap(
1797 bool isConstant, tosa::RescaleOp op,
Value &constant,
int64_t &arg,
1798 bool isShift =
false) {
1800 assert(!(isConstant && values.empty()) &&
1801 "constant rescale operand must have values");
1803 auto loc = op.getLoc();
1804 auto inputTy = cast<ShapedType>(op.getInput().getType());
1805 unsigned rank = inputTy.getRank();
1811 if (values.size() == 1) {
1812 IntegerAttr intAttr = isShift
1815 constant = arith::ConstantOp::create(rewriter, loc, intAttr);
1819 auto tensorType = RankedTensorType::get(
1820 {
static_cast<int64_t>(values.size())}, elementType);
1826 genericInputs.push_back(
1827 arith::ConstantOp::create(rewriter, loc, EltAttr));
1835 auto operand = isShift ? op.getShift() : op.getMultiplier();
1836 auto tensorType = dyn_cast<RankedTensorType>(operand.getType());
1837 if (tensorType && tensorType.hasStaticShape() &&
1838 tensorType.getShape()[0] == 1) {
1843 genericInputs.push_back(collapse1xNTensorToN(rewriter, operand, loc));
1844 indexingMaps.push_back(broadcastMap);
1846 genericInputs.push_back(operand);
1852 arg = indexingMaps.size() - 1;
1857 FailureOr<int64_t> maybeZp,
Location loc,
1859 bool isOutputZp =
false) {
1862 const uint32_t attrBitwidth =
1863 isOutputZp ? 32 : (bitwidth > 32 ? bitwidth : 32);
1870 result = blockArgs[zpArg];
1871 auto zpTy =
result.getType();
1872 if (zpTy.getIntOrFloatBitWidth() < attrBitwidth) {
1875 if (zpTy.isUnsignedInteger()) {
1877 UnrealizedConversionCastOp::create(
1882 if (zpTy.isUnsignedInteger()) {
1883 return arith::ExtUIOp::create(builder, loc, extendType,
result);
1885 return arith::ExtSIOp::create(builder, loc, extendType,
result);
1889 return arith::ConstantOp::create(builder, loc,
1890 IntegerAttr::get(extendType, *maybeZp));
1897 using OpRewritePattern<tosa::RescaleOp>::OpRewritePattern;
1899 LogicalResult matchAndRewrite(tosa::RescaleOp op,
1900 PatternRewriter &rewriter)
const final {
1901 auto loc = op.getLoc();
1902 auto input = op.getInput();
1903 auto inputTy = cast<ShapedType>(op.getInput().getType());
1904 auto outputTy = cast<ShapedType>(op.getOutput().getType());
1905 unsigned rank = inputTy.getRank();
1908 if (op.getRoundingMode() == RoundingMode::INEXACT_ROUND)
1910 op,
"tosa.rescale with rounding mode = 'INEXACT_ROUND' is not "
1911 "currently supported");
1912 if (op.getRoundingMode() == RoundingMode::DOUBLE_ROUND && !op.getScale32())
1914 op,
"tosa.rescale requires scale32 for double_round to be true");
1916 if (!isa<IntegerType>(inputTy.getElementType()))
1920 auto outputElemTy = dyn_cast<IntegerType>(outputTy.getElementType());
1921 if (!outputElemTy || outputElemTy.getWidth() > 32)
1923 op,
"only support integer output types up to 32 bits");
1929 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
1930 if (succeeded(maybeIZp) && op.verifyInputZeroPoint(*maybeIZp).failed())
1932 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
1933 if (succeeded(maybeOZp) && op.verifyOutputZeroPoint(*maybeOZp).failed())
1936 SmallVector<Value> dynDims;
1937 for (
int i = 0; i < outputTy.getRank(); i++) {
1938 if (outputTy.isDynamicDim(i)) {
1939 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
1943 DenseElementsAttr shiftElems;
1945 DenseElementsAttr multiplierElems;
1946 bool isMultiplierConstant =
1949 llvm::SmallVector<int32_t> shiftValues;
1950 llvm::SmallVector<int32_t> multiplierValues;
1952 if (isMultiplierConstant) {
1954 llvm::map_to_vector(multiplierElems.
getValues<IntegerAttr>(),
1955 [](IntegerAttr attr) -> int32_t {
1956 return static_cast<int32_t>(attr.getInt());
1959 if (isShiftConstant) {
1960 shiftValues = llvm::map_to_vector(
1961 shiftElems.
getValues<IntegerAttr>(), [](IntegerAttr attr) -> int32_t {
1962 return static_cast<int32_t>(attr.getInt());
1965 if (isMultiplierConstant && isShiftConstant) {
1967 for (
int i = 0, s = multiplierValues.size(); i < s; i++) {
1968 if (shiftValues[i] > 63) {
1970 multiplierValues[i] = 0;
1975 doubleRound = op.getRoundingMode() == RoundingMode::DOUBLE_ROUND &&
1976 llvm::any_of(shiftValues, [](int32_t v) {
return v > 31; });
1978 doubleRound = op.getRoundingMode() == RoundingMode::DOUBLE_ROUND;
1980 RoundingMode roundingMode =
1981 doubleRound ? RoundingMode::DOUBLE_ROUND : RoundingMode::SINGLE_ROUND;
1983 SmallVector<AffineMap> indexingMaps = {
1985 SmallVector<Value, 4> genericInputs = {input};
1989 Value multiplierConstant;
1990 int64_t multiplierArg = 0;
1991 setupLinalgGenericOpInputAndIndexingMap(
1992 rewriter, multiplierValues, genericInputs, indexingMaps,
1993 isMultiplierConstant, op, multiplierConstant, multiplierArg);
1997 Value shiftConstant;
1998 int64_t shiftArg = 0;
1999 setupLinalgGenericOpInputAndIndexingMap(
2000 rewriter, shiftValues, genericInputs, indexingMaps, isShiftConstant, op,
2001 shiftConstant, shiftArg,
true);
2015 genericInputs.push_back(
2016 collapse1xNTensorToN(rewriter, op->getOperand(3), loc));
2017 indexingMaps.push_back(broadcastMap);
2018 iZpArg = indexingMaps.size() - 1;
2022 genericInputs.push_back(
2023 collapse1xNTensorToN(rewriter, op->getOperand(4), loc));
2024 indexingMaps.push_back(broadcastMap);
2025 oZpArg = indexingMaps.size() - 1;
2032 Value emptyTensor = tensor::EmptyOp::create(
2033 rewriter, loc, outputTy.getShape(), outputTy.getElementType(),
2034 ArrayRef<Value>({dynDims}));
2036 auto linalgOp = linalg::GenericOp::create(
2037 rewriter, loc, outputTy, genericInputs,
ValueRange{emptyTensor},
2039 [&](OpBuilder &nestedBuilder, Location nestedLoc,
2041 Value value = blockArgs[0];
2042 Type valueTy = value.
getType();
2044 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
2045 auto inputZp = getExtendZp(nestedBuilder, valueTy, maybeIZp,
2046 nestedLoc, blockArgs, iZpArg);
2048 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
2049 auto outputZp = getExtendZp(nestedBuilder, valueTy, maybeOZp,
2050 nestedLoc, blockArgs, oZpArg,
true);
2052 IntegerType outIntType =
2053 cast<IntegerType>(blockArgs.back().
getType());
2054 unsigned outBitWidth = outIntType.getWidth();
2055 assert(outBitWidth <= 32 &&
"Unexpected output zeropoint bitwidth");
2057 Value multiplier = multiplierConstant ? multiplierConstant
2058 : blockArgs[multiplierArg];
2059 Value shift = shiftConstant ? shiftConstant : blockArgs[shiftArg];
2062 value = UnrealizedConversionCastOp::create(
2063 nestedBuilder, nestedLoc,
2064 nestedBuilder.getIntegerType(
2070 if (op.getInputUnsigned()) {
2071 value = arith::ExtUIOp::create(nestedBuilder, nestedLoc,
2072 nestedBuilder.getI32Type(), value);
2074 value = arith::ExtSIOp::create(nestedBuilder, nestedLoc,
2075 nestedBuilder.getI32Type(), value);
2080 arith::SubIOp::create(nestedBuilder, nestedLoc, value, inputZp);
2082 value = tosa::ApplyScaleOp::create(nestedBuilder, loc,
2083 nestedBuilder.getI32Type(), value,
2084 multiplier, shift, roundingMode);
2088 arith::AddIOp::create(nestedBuilder, nestedLoc, value, outputZp);
2091 int32_t intMin = APInt::getSignedMinValue(outBitWidth).getSExtValue();
2092 int32_t intMax = APInt::getSignedMaxValue(outBitWidth).getSExtValue();
2095 if (op.getOutputUnsigned()) {
2097 intMax = APInt::getMaxValue(outBitWidth).getZExtValue();
2100 auto intMinVal = arith::ConstantOp::create(
2101 nestedBuilder, loc, nestedBuilder.getI32IntegerAttr(intMin));
2102 auto intMaxVal = arith::ConstantOp::create(
2103 nestedBuilder, loc, nestedBuilder.getI32IntegerAttr(intMax));
2106 nestedBuilder,
false);
2108 if (outIntType.getWidth() < 32) {
2109 value = arith::TruncIOp::create(
2110 nestedBuilder, nestedLoc,
2114 if (outIntType.isUnsignedInteger()) {
2115 value = UnrealizedConversionCastOp::create(nestedBuilder, nestedLoc,
2119 linalg::YieldOp::create(nestedBuilder, loc, value);
2122 rewriter.
replaceOp(op, linalgOp->getResults());
2132 using OpRewritePattern<tosa::ResizeOp>::OpRewritePattern;
2134 LogicalResult matchAndRewrite(tosa::ResizeOp op,
2135 PatternRewriter &rewriter)
const final {
2136 Location loc = op.getLoc();
2137 ImplicitLocOpBuilder builder(loc, rewriter);
2138 auto input = op.getInput();
2139 auto inputTy = cast<RankedTensorType>(input.getType());
2140 auto resultTy = cast<RankedTensorType>(op.getType());
2141 const bool isBilinear = op.getMode() == ResizeMode::BILINEAR;
2143 auto inputH = inputTy.getDimSize(1);
2144 auto inputW = inputTy.getDimSize(2);
2145 auto outputH = resultTy.getDimSize(1);
2146 auto outputW = resultTy.getDimSize(2);
2148 if (inputH != 1 || inputW != 1 || outputH != 1 || outputW != 1)
2150 op,
"tosa.resize is not a pure 1x1->1x1 image operation");
2152 if (op.getMode() != ResizeMode::NEAREST_NEIGHBOR &&
2153 op.getMode() != ResizeMode::BILINEAR)
2155 op,
"tosa.resize mode should be NEAREST_NEIGHBOR or BILINEAR");
2157 if (inputTy == resultTy) {
2162 SmallVector<int64_t> scale;
2168 SmallVector<ReassociationExprs, 4> reassociationMap(2);
2175 RankedTensorType::get({inputTy.getDimSize(0), inputTy.getDimSize(3)},
2176 inputTy.getElementType());
2177 Value collapse = tensor::CollapseShapeOp::create(builder, collapseTy, input,
2181 llvm::SmallVector<Value> outputDynSize;
2182 if (inputTy.isDynamicDim(0))
2183 outputDynSize.push_back(tensor::DimOp::create(builder, input, 0));
2184 if (inputTy.isDynamicDim(3))
2185 outputDynSize.push_back(tensor::DimOp::create(builder, input, 3));
2188 auto genericTy = collapseTy.clone(resultTy.getElementType());
2190 tensor::EmptyOp::create(builder, genericTy.getShape(),
2191 resultTy.getElementType(), outputDynSize);
2193 SmallVector<utils::IteratorType> iterators(genericTy.getRank(),
2194 utils::IteratorType::parallel);
2196 auto generic = linalg::GenericOp::create(
2198 ArrayRef<AffineMap>{genericMap, genericMap}, iterators,
2199 [=](OpBuilder &
b, Location loc,
ValueRange args) {
2200 Value value = args[0];
2202 if (inputTy.getElementType() != resultTy.getElementType()) {
2203 value = arith::ExtSIOp::create(
b, loc, resultTy.getElementType(),
2206 if (isBilinear && scale[0] != 0) {
2207 Value scaleY = arith::ConstantOp::create(
2208 b, loc,
b.getI32IntegerAttr(scale[0]));
2209 value = arith::MulIOp::create(
b, loc, value, scaleY);
2212 if (isBilinear && scale[2] != 0) {
2213 Value scaleX = arith::ConstantOp::create(
2214 b, loc,
b.getI32IntegerAttr(scale[2]));
2215 value = arith::MulIOp::create(
b, loc, value, scaleX);
2219 linalg::YieldOp::create(
b, loc, value);
2223 op, resultTy,
generic.getResults()[0], reassociationMap);
2235 LogicalResult matchAndRewrite(tosa::ResizeOp op,
2239 auto input = op.getInput();
2240 auto inputTy = dyn_cast<RankedTensorType>(input.getType());
2241 auto resultTy = dyn_cast<RankedTensorType>(op.getType());
2243 if (!inputTy || !resultTy)
2245 "requires ranked input/output types");
2247 auto batch = inputTy.getDimSize(0);
2248 auto channels = inputTy.getDimSize(3);
2249 auto inputH = inputTy.getDimSize(1);
2250 auto inputW = inputTy.getDimSize(2);
2251 auto outputH = resultTy.getDimSize(1);
2252 auto outputW = resultTy.getDimSize(2);
2254 if ((inputH != 1 || outputH == 1) && (inputW != 1 || outputW == 1))
2256 op,
"tosa.resize has no broadcasting behavior");
2261 resizeShape.push_back(batch);
2262 resizeShape.push_back(inputH == 1 ? 1 : outputH);
2263 resizeShape.push_back(inputW == 1 ? 1 : outputW);
2264 resizeShape.push_back(channels);
2266 auto resizeTy = resultTy.clone(resizeShape);
2268 tosa::ResizeOp::create(builder, resizeTy, input, op.getScale(),
2269 op.getOffset(), op.getBorder(), op.getMode());
2276 reassociationMap.push_back({});
2279 reassociationMap.push_back({});
2284 collapseShape.push_back(outputH);
2286 collapseShape.push_back(outputW);
2287 collapseShape.push_back(channels);
2289 auto collapseTy = resultTy.clone(collapseShape);
2290 Value collapse = tensor::CollapseShapeOp::create(builder, collapseTy,
2291 resize, reassociationMap);
2295 if (inputTy.isDynamicDim(0))
2296 outputDynSize.push_back(tensor::DimOp::create(builder, input, 0));
2297 if (inputTy.isDynamicDim(3))
2298 outputDynSize.push_back(tensor::DimOp::create(builder, input, 3));
2301 utils::IteratorType::parallel);
2302 Value empty = tensor::EmptyOp::create(
2303 builder, resultTy.getShape(), resultTy.getElementType(), outputDynSize);
2320 Value value = args[0];
2321 linalg::YieldOp::create(
b, loc, value);
2330 using OpRewritePattern<tosa::ResizeOp>::OpRewritePattern;
2332 LogicalResult matchAndRewrite(tosa::ResizeOp op,
2333 PatternRewriter &rewriter)
const final {
2334 Location loc = op.getLoc();
2335 ImplicitLocOpBuilder
b(loc, rewriter);
2336 auto input = op.getInput();
2337 auto inputTy = cast<ShapedType>(input.getType());
2338 auto resultTy = cast<ShapedType>(op.getType());
2339 auto resultETy = resultTy.getElementType();
2341 bool floatingPointMode = isa<FloatType>(resultETy);
2342 auto floatTy = resultETy;
2344 auto imageH = inputTy.getShape()[1];
2345 auto imageW = inputTy.getShape()[2];
2347 auto dynamicDimsOr =
2349 if (!dynamicDimsOr.has_value())
2351 op,
"unable to get dynamic dimensions of tosa.resize");
2353 if (op.getMode() != ResizeMode::NEAREST_NEIGHBOR &&
2354 op.getMode() != ResizeMode::BILINEAR)
2356 op,
"tosa.resize mode should be NEAREST_NEIGHBOR or BILINEAR");
2358 SmallVector<AffineMap, 2> affineMaps = {
2360 auto emptyTensor = tensor::EmptyOp::create(
b, resultTy.getShape(),
2361 resultETy, *dynamicDimsOr);
2362 auto genericOp = linalg::GenericOp::create(
2365 Value resize = genericOp.getResult(0);
2368 OpBuilder::InsertionGuard regionGuard(
b);
2369 b.createBlock(&genericOp.getRegion(), genericOp.getRegion().end(),
2371 Value batch = linalg::IndexOp::create(
b, 0);
2372 Value y = linalg::IndexOp::create(
b, 1);
2373 Value x = linalg::IndexOp::create(
b, 2);
2374 Value channel = linalg::IndexOp::create(
b, 3);
2377 arith::ConstantOp::create(
b,
b.getZeroAttr(
b.getI32Type()));
2378 Value zeroFp = arith::ConstantOp::create(
b,
b.getZeroAttr(floatTy));
2380 arith::ConstantOp::create(
b,
b.getI32IntegerAttr(imageH - 1));
2382 arith::ConstantOp::create(
b,
b.getI32IntegerAttr(imageW - 1));
2384 Value inY = arith::IndexCastOp::create(
b,
b.getI32Type(), y);
2385 Value inX = arith::IndexCastOp::create(
b,
b.getI32Type(), x);
2387 SmallVector<int64_t> scale, offset, border;
2392 op,
"tosa.resize scale/offset/border should have compile time "
2393 "constant values.");
2396 Value yScaleN, yScaleD, xScaleN, xScaleD;
2397 yScaleN = arith::ConstantOp::create(
b,
b.getI32IntegerAttr(scale[0]));
2398 yScaleD = arith::ConstantOp::create(
b,
b.getI32IntegerAttr(scale[1]));
2399 xScaleN = arith::ConstantOp::create(
b,
b.getI32IntegerAttr(scale[2]));
2400 xScaleD = arith::ConstantOp::create(
b,
b.getI32IntegerAttr(scale[3]));
2402 Value yOffset, xOffset, yBorder, xBorder;
2403 yOffset = arith::ConstantOp::create(
b,
b.getI32IntegerAttr(offset[0]));
2404 xOffset = arith::ConstantOp::create(
b,
b.getI32IntegerAttr(offset[1]));
2405 yBorder = arith::ConstantOp::create(
b,
b.getI32IntegerAttr(border[0]));
2406 xBorder = arith::ConstantOp::create(
b,
b.getI32IntegerAttr(border[1]));
2409 auto getIndexAndDeltaFp = [&](Value &index, Value &delta, Value in,
2410 Value scaleN, Value scaleD, Value offset,
2411 int size, ImplicitLocOpBuilder &
b) {
2419 Value val = arith::MulIOp::create(
b, in, scaleD);
2420 val = arith::AddIOp::create(
b, val, offset);
2421 index = arith::FloorDivSIOp::create(
b, val, scaleN);
2424 Value scaledIndex = arith::MulIOp::create(
b, index, scaleN);
2425 Value r = arith::SubIOp::create(
b, val, scaledIndex);
2426 Value rFp = arith::SIToFPOp::create(
b, floatTy, r);
2429 Value scaleNfp = arith::UIToFPOp::create(
b, floatTy, scaleN);
2430 delta = arith::DivFOp::create(
b, rFp, scaleNfp);
2434 auto getIndexAndDeltaInt = [&](Value &index, Value &delta, Value in,
2435 Value scaleN, Value scaleD, Value offset,
2436 int size, ImplicitLocOpBuilder &
b) {
2445 Value val = arith::MulIOp::create(
b, in, scaleD);
2446 val = arith::AddIOp::create(
b, val, offset);
2447 index = arith::FloorDivSIOp::create(
b, val, scaleN);
2448 delta = arith::MulIOp::create(
b, index, scaleN);
2449 delta = arith::SubIOp::create(
b, val, delta);
2452 Value ix, iy, dx, dy;
2453 if (floatingPointMode) {
2454 getIndexAndDeltaFp(iy, dy, inY, yScaleN, yScaleD, yOffset, imageH,
b);
2455 getIndexAndDeltaFp(ix, dx, inX, xScaleN, xScaleD, xOffset, imageW,
b);
2457 getIndexAndDeltaInt(iy, dy, inY, yScaleN, yScaleD, yOffset, imageH,
b);
2458 getIndexAndDeltaInt(ix, dx, inX, xScaleN, xScaleD, xOffset, imageW,
b);
2461 if (op.getMode() == ResizeMode::NEAREST_NEIGHBOR) {
2462 auto one = arith::ConstantOp::create(
b,
b.getI32IntegerAttr(1));
2464 auto getNearestIndexAndClamp = [&](Value val, Value dval, Value scale,
2465 Value
max,
int size,
2466 ImplicitLocOpBuilder &
b) -> Value {
2472 if (floatingPointMode) {
2474 arith::ConstantOp::create(
b,
b.getFloatAttr(floatTy, 0.5f));
2475 pred = arith::CmpFOp::create(
b, arith::CmpFPredicate::OGE, dval, h);
2477 Value dvalDouble = arith::ShLIOp::create(
b, dval, one);
2478 pred = arith::CmpIOp::create(
b, arith::CmpIPredicate::sge,
2482 auto offset = arith::SelectOp::create(
b, pred, one, zeroI32);
2483 val = arith::AddIOp::create(
b, val, offset);
2485 return arith::IndexCastOp::create(
b,
b.getIndexType(), val);
2488 iy = getNearestIndexAndClamp(iy, dy, yScaleN, hMax, imageH,
b);
2489 ix = getNearestIndexAndClamp(ix, dx, xScaleN, wMax, imageW,
b);
2491 Value
result = tensor::ExtractOp::create(
2494 linalg::YieldOp::create(
b,
result);
2497 assert(op.getMode() == ResizeMode::BILINEAR);
2499 auto oneVal = arith::ConstantOp::create(
b,
b.getI32IntegerAttr(1));
2501 auto getClampedIdxs = [&](Value &val0, Value &val1,
int size, Value in,
2502 Value
max, ImplicitLocOpBuilder &
b) {
2504 val1 = arith::AddIOp::create(
b, val0, oneVal);
2509 val0 = arith::IndexCastOp::create(
b,
b.getIndexType(), val0);
2510 val1 = arith::IndexCastOp::create(
b,
b.getIndexType(), val1);
2518 Value x0, x1, y0, y1;
2519 getClampedIdxs(y0, y1, imageH, iy, hMax,
b);
2520 getClampedIdxs(x0, x1, imageW, ix, wMax,
b);
2522 Value y0x0 = tensor::ExtractOp::create(
2524 Value y0x1 = tensor::ExtractOp::create(
2526 Value y1x0 = tensor::ExtractOp::create(
2528 Value y1x1 = tensor::ExtractOp::create(
2531 if (floatingPointMode) {
2533 arith::ConstantOp::create(
b,
b.getFloatAttr(floatTy, 1.0f));
2534 auto interpolate = [&](Value val0, Value val1, Value delta,
2536 ImplicitLocOpBuilder &
b) -> Value {
2539 Value oneMinusDelta = arith::SubFOp::create(
b, oneVal, delta);
2540 Value mul0 = arith::MulFOp::create(
b, val0, oneMinusDelta);
2541 Value mul1 = arith::MulFOp::create(
b, val1, delta);
2542 return arith::AddFOp::create(
b, mul0, mul1);
2548 Value topAcc = interpolate(y0x0, y0x1, dx, imageW,
b);
2553 Value bottomAcc = interpolate(y1x0, y1x1, dx, imageW,
b);
2557 Value
result = interpolate(topAcc, bottomAcc, dy, imageH,
b);
2558 linalg::YieldOp::create(
b,
result);
2561 y0x0 = arith::ExtSIOp::create(
b, resultETy, y0x0);
2562 y0x1 = arith::ExtSIOp::create(
b, resultETy, y0x1);
2563 y1x0 = arith::ExtSIOp::create(
b, resultETy, y1x0);
2564 y1x1 = arith::ExtSIOp::create(
b, resultETy, y1x1);
2567 if (resultETy.getIntOrFloatBitWidth() > deltaBitwidth) {
2568 dx = arith::ExtSIOp::create(
b, resultETy, dx);
2569 dy = arith::ExtSIOp::create(
b, resultETy, dy);
2572 Value yScaleNExt = yScaleN;
2573 Value xScaleNExt = xScaleN;
2575 const int64_t scaleBitwidth =
2577 if (resultETy.getIntOrFloatBitWidth() > scaleBitwidth) {
2578 yScaleNExt = arith::ExtSIOp::create(
b, resultETy, yScaleN);
2579 xScaleNExt = arith::ExtSIOp::create(
b, resultETy, xScaleN);
2582 auto interpolate = [](Value val0, Value val1, Value weight1,
2583 Value scale,
int inputSize,
2584 ImplicitLocOpBuilder &
b) -> Value {
2586 return arith::MulIOp::create(
b, val0, scale);
2587 Value weight0 = arith::SubIOp::create(
b, scale, weight1);
2588 Value mul0 = arith::MulIOp::create(
b, val0, weight0);
2589 Value mul1 = arith::MulIOp::create(
b, val1, weight1);
2590 return arith::AddIOp::create(
b, mul0, mul1);
2593 Value topAcc = interpolate(y0x0, y0x1, dx, xScaleNExt, imageW,
b);
2594 Value bottomAcc = interpolate(y1x0, y1x1, dx, xScaleNExt, imageW,
b);
2596 interpolate(topAcc, bottomAcc, dy, yScaleNExt, imageH,
b);
2597 linalg::YieldOp::create(
b,
result);
2610template <
typename SrcOp>
2613 using OpRewritePattern<SrcOp>::OpRewritePattern;
2615 LogicalResult matchAndRewrite(SrcOp op,
2616 PatternRewriter &rewriter)
const final {
2617 rewriter.
replaceOp(op, op.getOperation()->getOperands());
2622template <
typename SrcOp>
2625 ReduceConverter(MLIRContext *context,
bool allowNonFinites)
2626 : OpRewritePattern<SrcOp>(context), allowNonFinites(allowNonFinites) {}
2628 LogicalResult matchAndRewrite(SrcOp reduceOp,
2629 PatternRewriter &rewriter)
const final {
2635 bool allowNonFinites;
2640 using OpRewritePattern<tosa::ReverseOp>::OpRewritePattern;
2642 LogicalResult matchAndRewrite(tosa::ReverseOp op,
2643 PatternRewriter &rewriter)
const final {
2644 auto loc = op.getLoc();
2645 Value input = op.getInput1();
2646 auto inputTy = cast<ShapedType>(input.
getType());
2647 auto resultTy = cast<ShapedType>(op.getType());
2648 auto axis = op.getAxis();
2650 SmallVector<Value> dynDims;
2651 for (
int i = 0; i < inputTy.getRank(); i++) {
2652 if (inputTy.isDynamicDim(i)) {
2653 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
2657 Value axisDimSize = tensor::DimOp::create(rewriter, loc, input, axis);
2660 auto emptyTensor = tensor::EmptyOp::create(
2661 rewriter, loc, inputTy.getShape(),
2662 inputTy.getElementType(), ArrayRef<Value>({dynDims}))
2664 SmallVector<AffineMap, 2> affineMaps = {
2668 op, resultTy, ArrayRef<Value>({}),
ValueRange{emptyTensor}, affineMaps,
2670 [&](OpBuilder &nestedBuilder, Location nestedLoc,
ValueRange args) {
2671 llvm::SmallVector<Value>
indices;
2672 for (
unsigned int i = 0; i < inputTy.getRank(); i++) {
2674 linalg::IndexOp::create(rewriter, nestedLoc, i).getResult();
2678 arith::SubIOp::create(rewriter, nestedLoc, axisDimSize, one);
2679 index = arith::SubIOp::create(rewriter, nestedLoc, sizeMinusOne,
2686 auto extract = tensor::ExtractOp::create(nestedBuilder, nestedLoc,
2688 linalg::YieldOp::create(nestedBuilder, op.getLoc(),
2689 extract.getResult());
2699struct TileConverter :
public OpConversionPattern<tosa::TileOp> {
2700 using OpConversionPattern<tosa::TileOp>::OpConversionPattern;
2703 matchAndRewrite(tosa::TileOp op, OpAdaptor adaptor,
2704 ConversionPatternRewriter &rewriter)
const override {
2705 SmallVector<int64_t> multiples;
2706 if (
failed(op.getConstantMultiples(multiples)))
2711 if (llvm::any_of(multiples, [](int64_t v) {
return v <= 0 && v != -1; }))
2712 return rewriter.notifyMatchFailure(op,
2713 "unsupported non-positive multiples");
2715 auto loc = op.getLoc();
2716 auto input = op.getInput1();
2717 auto inputTy = cast<ShapedType>(input.
getType());
2718 auto inputShape = inputTy.getShape();
2719 auto resultTy = cast<ShapedType>(op.getType());
2720 auto elementTy = inputTy.getElementType();
2721 int64_t rank = inputTy.getRank();
2724 SmallVector<int64_t, 2> genericShape;
2725 for (
int i = 0; i < rank; i++) {
2726 int64_t dim = multiples[i];
2727 genericShape.push_back(dim == -1 ? ShapedType::kDynamic : dim);
2728 genericShape.push_back(inputShape[i]);
2731 SmallVector<Value> dynDims;
2732 for (
int i = 0; i < inputTy.getRank(); i++) {
2733 if (inputTy.isDynamicDim(i) || multiples[i] == -1) {
2734 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
2738 auto emptyTensor = tensor::EmptyOp::create(
2739 rewriter, op.getLoc(), genericShape, elementTy, dynDims);
2742 SmallVector<AffineExpr, 4> dimExprs;
2743 dimExprs.reserve(rank);
2744 for (
unsigned i = 0; i < rank; ++i)
2745 dimExprs.push_back(rewriter.getAffineDimExpr(i * 2 + 1));
2747 auto readAffineMap =
2749 rewriter.getContext());
2751 SmallVector<AffineMap, 2> affineMaps = {
2752 readAffineMap, rewriter.getMultiDimIdentityMap(genericShape.size())};
2754 auto genericOp = linalg::GenericOp::create(
2755 rewriter, loc, RankedTensorType::get(genericShape, elementTy), input,
2758 [&](OpBuilder &nestedBuilder, Location nestedLoc,
ValueRange args) {
2759 linalg::YieldOp::create(nestedBuilder, op.getLoc(), *args.begin());
2764 rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
2765 op, resultTy, genericOp.getResult(0), shapeValue);
2783template <
typename SrcOp>
2786 ArgMinMaxConverter(MLIRContext *context,
bool allowNonFinites)
2787 : OpRewritePattern<SrcOp>(context), allowNonFinites(allowNonFinites) {}
2789 LogicalResult matchAndRewrite(SrcOp argOp,
2790 PatternRewriter &rewriter)
const final {
2791 constexpr bool isMin = std::is_same_v<SrcOp, tosa::ArgMinOp>;
2793 auto loc = argOp.getLoc();
2794 Value input = argOp.getInput();
2795 auto inputTy = cast<ShapedType>(input.
getType());
2796 auto resultTy = cast<ShapedType>(argOp.getOutput().getType());
2797 auto inElementTy = inputTy.getElementType();
2798 auto outElementTy = resultTy.getElementType();
2799 int axis = argOp.getAxis();
2800 auto resultValueTy =
2801 RankedTensorType::get(resultTy.getShape(), inElementTy);
2803 if (!isa<IntegerType>(outElementTy))
2804 return rewriter.notifyMatchFailure(argOp,
2805 "requires integer-like result type");
2807 SmallVector<Value> dynDims;
2808 for (
int i = 0; i < inputTy.getRank(); i++) {
2809 if (inputTy.isDynamicDim(i) && i != axis) {
2810 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
2815 auto emptyTensorIdx =
2816 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
2817 outElementTy, dynDims)
2819 auto fillValueIdx = arith::ConstantOp::create(
2820 rewriter, loc, rewriter.getIntegerAttr(outElementTy, 0));
2821 auto filledTensorIdx =
2822 linalg::FillOp::create(rewriter, loc,
ValueRange{fillValueIdx},
2827 auto emptyTensorValue =
2828 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(), inElementTy,
2832 argOp, inElementTy, rewriter, allowNonFinites);
2835 return rewriter.notifyMatchFailure(argOp,
"unsupported element type");
2837 auto fillValue = arith::ConstantOp::create(rewriter, loc, fillValueAttr);
2838 auto filledTensorValue =
2839 linalg::FillOp::create(rewriter, loc,
ValueRange{fillValue},
2845 SmallVector<utils::IteratorType, 4> iteratorTypes;
2846 iteratorTypes.resize(inputTy.getRank(), utils::IteratorType::parallel);
2847 iteratorTypes[axis] = utils::IteratorType::reduction;
2849 SmallVector<AffineExpr, 2> srcExprs;
2850 SmallVector<AffineExpr, 2> dstExprs;
2851 for (
int i = 0, rank = inputTy.getRank(); i != rank; ++i) {
2857 bool didEncounterError =
false;
2859 rewriter.getContext());
2860 auto linalgOp = linalg::GenericOp::create(
2861 rewriter, loc, ArrayRef<Type>({resultTy, resultValueTy}), input,
2862 ValueRange({filledTensorIdx, filledTensorValue}), maps, iteratorTypes,
2863 [&](OpBuilder &nestedBuilder, Location nestedLoc,
2865 auto newValue = blockArgs[0];
2866 auto oldIndex = blockArgs[1];
2867 auto oldValue = blockArgs[2];
2869 Value newIndex = arith::IndexCastOp::create(
2870 rewriter, nestedLoc, oldIndex.getType(),
2871 linalg::IndexOp::create(rewriter, loc, axis));
2874 if (isa<FloatType>(inElementTy)) {
2875 if (argOp.getNanMode() == NanPropagationMode::IGNORE) {
2878 Value comparison = arith::CmpFOp::create(
2879 rewriter, nestedLoc,
2880 isMin ? arith::CmpFPredicate::ULT : arith::CmpFPredicate::UGT,
2881 newValue, oldValue);
2882 Value newNonNaN = arith::CmpFOp::create(rewriter, nestedLoc,
2883 arith::CmpFPredicate::ORD,
2884 newValue, newValue);
2885 predicate = arith::AndIOp::create(rewriter, nestedLoc,
2886 rewriter.getI1Type(),
2887 comparison, newNonNaN);
2892 Value comparison = arith::CmpFOp::create(
2893 rewriter, nestedLoc,
2894 isMin ? arith::CmpFPredicate::ULT : arith::CmpFPredicate::UGT,
2895 newValue, oldValue);
2896 Value oldNonNaN = arith::CmpFOp::create(rewriter, nestedLoc,
2897 arith::CmpFPredicate::ORD,
2898 oldValue, oldValue);
2899 predicate = arith::AndIOp::create(rewriter, nestedLoc,
2900 rewriter.getI1Type(),
2901 comparison, oldNonNaN);
2903 }
else if (isa<IntegerType>(inElementTy)) {
2904 predicate = arith::CmpIOp::create(rewriter, nestedLoc,
2905 isMin ? arith::CmpIPredicate::slt
2906 : arith::CmpIPredicate::sgt,
2907 newValue, oldValue);
2909 didEncounterError =
true;
2913 auto resultValue = arith::SelectOp::create(
2914 rewriter, nestedLoc, predicate, newValue, oldValue);
2915 auto resultIndex = arith::SelectOp::create(
2916 rewriter, nestedLoc, predicate, newIndex, oldIndex);
2917 linalg::YieldOp::create(nestedBuilder, nestedLoc,
2921 if (didEncounterError)
2922 return rewriter.notifyMatchFailure(argOp,
"unsupported element type");
2924 rewriter.replaceOp(argOp, linalgOp.getResult(0));
2929 bool allowNonFinites;
2932class GatherConverter :
public OpConversionPattern<tosa::GatherOp> {
2934 using OpConversionPattern<tosa::GatherOp>::OpConversionPattern;
2936 matchAndRewrite(tosa::GatherOp op, OpAdaptor adaptor,
2937 ConversionPatternRewriter &rewriter)
const final {
2938 auto input = adaptor.getOperands()[0];
2939 auto indices = adaptor.getOperands()[1];
2941 auto valuesTy = dyn_cast<RankedTensorType>(op.getValues().getType());
2942 auto resultTy = dyn_cast<RankedTensorType>(op.getType());
2943 if (!valuesTy || !resultTy)
2944 return rewriter.notifyMatchFailure(op,
"unranked tensors not supported");
2946 auto dynamicDims = inferDynamicDimsForGather(
2947 rewriter, op.getLoc(), adaptor.getValues(), adaptor.getIndices());
2949 auto resultElementTy = resultTy.getElementType();
2951 auto loc = op.getLoc();
2953 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
2954 resultElementTy, dynamicDims)
2957 SmallVector<AffineMap, 2> affineMaps = {
2959 resultTy.getRank(), 0,
2960 {rewriter.getAffineDimExpr(0), rewriter.getAffineDimExpr(1)},
2961 rewriter.getContext()),
2962 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
2964 auto genericOp = linalg::GenericOp::create(
2968 [&](OpBuilder &
b, Location loc,
ValueRange args) {
2969 auto indexValue = args[0];
2970 auto index0 = linalg::IndexOp::create(rewriter, loc, 0);
2971 Value index1 = arith::IndexCastOp::create(
2972 rewriter, loc, rewriter.getIndexType(), indexValue);
2973 auto index2 = linalg::IndexOp::create(rewriter, loc, 2);
2974 Value extract = tensor::ExtractOp::create(
2975 rewriter, loc, input,
ValueRange{index0, index1, index2});
2976 linalg::YieldOp::create(rewriter, loc, extract);
2978 rewriter.replaceOp(op, genericOp.getResult(0));
2982 static llvm::SmallVector<Value> inferDynamicDimsForGather(OpBuilder &builder,
2986 llvm::SmallVector<Value> results;
2988 auto addDynamicDimension = [&](Value source, int64_t dim) {
2990 if (
auto dimValue = llvm::dyn_cast_if_present<Value>(sz))
2991 results.push_back(dimValue);
2994 addDynamicDimension(values, 0);
2995 addDynamicDimension(
indices, 1);
2996 addDynamicDimension(values, 2);
3001class RowGatherConverter :
public OpConversionPattern<tosa::RowGatherOp> {
3003 using OpConversionPattern<tosa::RowGatherOp>::OpConversionPattern;
3005 matchAndRewrite(tosa::RowGatherOp op, OpAdaptor adaptor,
3006 ConversionPatternRewriter &rewriter)
const final {
3007 auto valuesTy = dyn_cast<RankedTensorType>(adaptor.getValues().getType());
3008 auto indicesTy = dyn_cast<RankedTensorType>(adaptor.getIndices().getType());
3010 dyn_cast<RankedTensorType>(adaptor.getRowCount().getType());
3011 auto resultTy = dyn_cast<RankedTensorType>(op.getType());
3012 if (!valuesTy || !indicesTy || !rowCountTy || !resultTy)
3013 return rewriter.notifyMatchFailure(op,
"unranked tensors not supported");
3015 Location loc = op.getLoc();
3017 Value rowCount = tensor::ExtractOp::create(
3018 rewriter, loc, adaptor.getRowCount(),
ValueRange{zero});
3019 Value rowCountIndex = arith::IndexCastOp::create(
3020 rewriter, loc, rewriter.getIndexType(), rowCount);
3022 SmallVector<Value> dynamicDims;
3023 if (resultTy.isDynamicDim(0))
3024 dynamicDims.push_back(
3025 tensor::DimOp::create(rewriter, loc, adaptor.getValues(), 0));
3026 if (resultTy.isDynamicDim(1)) {
3027 Value indicesWidth =
3028 tensor::DimOp::create(rewriter, loc, adaptor.getIndices(), 1);
3029 dynamicDims.push_back(
3030 arith::MulIOp::create(rewriter, loc, indicesWidth, rowCountIndex));
3032 if (resultTy.isDynamicDim(2))
3033 dynamicDims.push_back(
3034 tensor::DimOp::create(rewriter, loc, adaptor.getValues(), 2));
3037 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
3038 resultTy.getElementType(), dynamicDims);
3039 SmallVector<AffineMap> affineMaps = {
3040 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
3042 auto genericOp = linalg::GenericOp::create(
3043 rewriter, loc, ArrayRef<Type>{resultTy},
ValueRange{},
3046 [&](OpBuilder &builder, Location nestedLoc,
ValueRange) {
3047 Value batch = linalg::IndexOp::create(builder, nestedLoc, 0);
3048 Value outputRow = linalg::IndexOp::create(builder, nestedLoc, 1);
3049 Value channel = linalg::IndexOp::create(builder, nestedLoc, 2);
3050 Value indexSlot = arith::DivUIOp::create(builder, nestedLoc,
3051 outputRow, rowCountIndex);
3052 Value rowOffset = arith::RemUIOp::create(builder, nestedLoc,
3053 outputRow, rowCountIndex);
3054 Value index = tensor::ExtractOp::create(builder, nestedLoc,
3055 adaptor.getIndices(),
3057 Value row = arith::IndexCastOp::create(builder, nestedLoc,
3058 builder.getIndexType(), index);
3059 row = arith::AddIOp::create(builder, nestedLoc, row, rowOffset);
3061 tensor::ExtractOp::create(builder, nestedLoc, adaptor.getValues(),
3063 linalg::YieldOp::create(builder, nestedLoc,
result);
3065 rewriter.replaceOp(op, genericOp.getResult(0));
3075 using OpRewritePattern<tosa::TableOp>::OpRewritePattern;
3077 LogicalResult matchAndRewrite(tosa::TableOp op,
3078 PatternRewriter &rewriter)
const final {
3079 auto loc = op.getLoc();
3080 Value input = op.getInput1();
3081 Value table = op.getTable();
3082 auto inputTy = cast<ShapedType>(input.
getType());
3083 auto tableTy = cast<ShapedType>(table.
getType());
3084 auto resultTy = cast<ShapedType>(op.getType());
3086 auto inputElementTy = inputTy.getElementType();
3087 auto tableElementTy = tableTy.getElementType();
3088 auto resultElementTy = resultTy.getElementType();
3090 SmallVector<Value> dynDims;
3091 for (
int i = 0; i < resultTy.getRank(); ++i) {
3092 if (inputTy.isDynamicDim(i)) {
3094 tensor::DimOp::create(rewriter, loc, op.getOperand(0), i));
3099 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
3100 resultElementTy, dynDims)
3103 SmallVector<AffineMap, 2> affineMaps = {
3104 rewriter.getMultiDimIdentityMap(resultTy.getRank()),
3105 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
3107 auto genericOp = linalg::GenericOp::create(
3110 rewriter.replaceOp(op, genericOp.getResult(0));
3113 OpBuilder::InsertionGuard regionGuard(rewriter);
3114 Block *block = rewriter.createBlock(
3115 &genericOp.getRegion(), genericOp.getRegion().end(),
3116 TypeRange({inputElementTy, resultElementTy}), {loc, loc});
3119 rewriter.setInsertionPointToStart(block);
3120 if (inputElementTy.isInteger(8) && tableElementTy.isInteger(8) &&
3121 resultElementTy.isInteger(8)) {
3122 Value index = arith::IndexCastOp::create(
3123 rewriter, loc, rewriter.getIndexType(), inputValue);
3125 index = arith::AddIOp::create(rewriter, loc, rewriter.getIndexType(),
3128 tensor::ExtractOp::create(rewriter, loc, table,
ValueRange{index});
3129 linalg::YieldOp::create(rewriter, loc, extract);
3133 if (inputElementTy.isInteger(16) && tableElementTy.isInteger(16) &&
3134 resultElementTy.isInteger(32)) {
3135 Value extend = arith::ExtSIOp::create(
3136 rewriter, loc, rewriter.getI32Type(), inputValue);
3138 auto offset = arith::ConstantOp::create(
3139 rewriter, loc, rewriter.getI32IntegerAttr(32768));
3140 auto seven = arith::ConstantOp::create(rewriter, loc,
3141 rewriter.getI32IntegerAttr(7));
3142 auto one = arith::ConstantOp::create(rewriter, loc,
3143 rewriter.getI32IntegerAttr(1));
3144 auto b1111111 = arith::ConstantOp::create(
3145 rewriter, loc, rewriter.getI32IntegerAttr(127));
3151 auto extendAdd = arith::AddIOp::create(rewriter, loc, extend, offset);
3152 Value index = arith::ShRUIOp::create(rewriter, loc, extendAdd, seven);
3154 arith::AndIOp::create(rewriter, loc, extendAdd, b1111111);
3159 Value indexPlusOne = arith::AddIOp::create(rewriter, loc, index, one);
3161 index = arith::IndexCastOp::create(rewriter, loc,
3162 rewriter.getIndexType(), index);
3163 indexPlusOne = arith::IndexCastOp::create(
3164 rewriter, loc, rewriter.getIndexType(), indexPlusOne);
3167 tensor::ExtractOp::create(rewriter, loc, table,
ValueRange{index});
3168 Value
next = tensor::ExtractOp::create(rewriter, loc, table,
3172 arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(), base);
3174 arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(), next);
3178 Value baseScaled = arith::ShLIOp::create(rewriter, loc, base, seven);
3179 Value diff = arith::SubIOp::create(rewriter, loc, next, base);
3180 Value diffScaled = arith::MulIOp::create(rewriter, loc, diff, fraction);
3182 arith::AddIOp::create(rewriter, loc, baseScaled, diffScaled);
3184 linalg::YieldOp::create(rewriter, loc,
result);
3190 return rewriter.notifyMatchFailure(
3191 op,
"unable to create body for tosa.table op");
3196 using OpRewritePattern<RFFT2dOp>::OpRewritePattern;
3198 static bool isRankedTensor(Type type) {
return isa<RankedTensorType>(type); }
3200 static OpFoldResult halfPlusOne(OpBuilder &builder, Location loc,
3206 auto divBy2 = builder.
createOrFold<arith::DivUIOp>(loc, value, two);
3207 auto plusOne = builder.
createOrFold<arith::AddIOp>(loc, divBy2, one);
3211 static RankedTensorType
3212 computeOutputShape(OpBuilder &builder, Location loc, Value input,
3213 llvm::SmallVectorImpl<Value> &dynamicSizes) {
3219 dims[2] = halfPlusOne(builder, loc, dims[2]);
3221 llvm::SmallVector<int64_t, 3> staticSizes;
3224 auto elementType = cast<RankedTensorType>(input.
getType()).getElementType();
3225 return RankedTensorType::get(staticSizes, elementType);
3228 static Value createZeroTensor(PatternRewriter &rewriter, Location loc,
3229 RankedTensorType type,
3230 llvm::ArrayRef<Value> dynamicSizes) {
3232 tensor::EmptyOp::create(rewriter, loc, type, dynamicSizes);
3233 auto fillValueAttr = rewriter.
getZeroAttr(type.getElementType());
3234 auto fillValue = arith::ConstantOp::create(rewriter, loc, fillValueAttr);
3236 linalg::FillOp::create(rewriter, loc,
ValueRange{fillValue},
3239 return filledTensor;
3242 static Value castIndexToFloat(OpBuilder &builder, Location loc,
3243 FloatType type, Value value) {
3244 auto integerVal = arith::IndexCastUIOp::create(
3246 type.getIntOrFloatBitWidth() > 32 ? builder.
getI64Type()
3250 return arith::UIToFPOp::create(builder, loc, type, integerVal);
3253 static Value createLinalgIndex(OpBuilder &builder, Location loc,
3254 FloatType type, int64_t index) {
3255 auto indexVal = linalg::IndexOp::create(builder, loc, index);
3256 return castIndexToFloat(builder, loc, type, indexVal);
3259 template <
typename... Args>
3260 static llvm::SmallVector<AffineExpr, 4> affineDimsExpr(OpBuilder &builder,
3265 LogicalResult matchAndRewrite(RFFT2dOp rfft2d,
3266 PatternRewriter &rewriter)
const override {
3267 if (!llvm::all_of(rfft2d->getOperandTypes(), isRankedTensor) ||
3268 !llvm::all_of(rfft2d->getResultTypes(), isRankedTensor)) {
3270 "only supports ranked tensors");
3273 auto loc = rfft2d.getLoc();
3274 auto input = rfft2d.getInputReal();
3276 dyn_cast<FloatType>(cast<ShapedType>(input.
getType()).getElementType());
3279 "only supports float element types");
3282 llvm::SmallVector<Value> dynamicSizes;
3283 auto outputType = computeOutputShape(rewriter, loc, input, dynamicSizes);
3286 llvm::SmallVector<utils::IteratorType, 5> iteratorTypes = {
3287 utils::IteratorType::parallel, utils::IteratorType::parallel,
3288 utils::IteratorType::parallel, utils::IteratorType::reduction,
3289 utils::IteratorType::reduction};
3292 llvm::SmallVector<Value> genericOpInputs = {input};
3293 llvm::SmallVector<Value> genericOpOutputs = {
3294 createZeroTensor(rewriter, loc, outputType, dynamicSizes),
3295 createZeroTensor(rewriter, loc, outputType, dynamicSizes)};
3299 llvm::ArrayRef{affineDimsExpr(rewriter, 0, 3, 4),
3300 affineDimsExpr(rewriter, 0, 1, 2),
3301 affineDimsExpr(rewriter, 0, 1, 2)},
3305 auto dimH = rewriter.
createOrFold<tensor::DimOp>(loc, input, 1);
3306 auto dimW = rewriter.
createOrFold<tensor::DimOp>(loc, input, 2);
3309 auto zeroFloat = arith::ConstantOp::create(
3310 rewriter, loc, rewriter.
getZeroAttr(elementType));
3311 auto twoPiAttr = rewriter.
getFloatAttr(elementType, 6.283185307179586);
3312 auto twoPi = arith::ConstantOp::create(rewriter, loc, twoPiAttr);
3317 auto constH = castIndexToFloat(rewriter, loc, elementType, dimH);
3318 auto constW = castIndexToFloat(rewriter, loc, elementType, dimW);
3319 auto halfH = index::DivUOp::create(rewriter, loc, dimH, twoIndex);
3320 auto halfW = index::DivUOp::create(rewriter, loc, dimW, twoIndex);
3322 auto buildBody = [&](OpBuilder &builder, Location loc,
ValueRange args) {
3323 Value valReal = args[0];
3324 Value sumReal = args[1];
3325 Value sumImag = args[2];
3328 Value oy = linalg::IndexOp::create(builder, loc, 1);
3329 Value ox = linalg::IndexOp::create(builder, loc, 2);
3330 Value iy = linalg::IndexOp::create(builder, loc, 3);
3331 Value ix = linalg::IndexOp::create(builder, loc, 4);
3336 auto iyXoy = index::MulOp::create(builder, loc, iy, oy);
3337 auto ixXox = index::MulOp::create(builder, loc, ix, ox);
3339 auto iyRem = index::RemUOp::create(builder, loc, iyXoy, dimH);
3340 auto ixRem = index::RemUOp::create(builder, loc, ixXox, dimW);
3342 auto iyRemFloat = castIndexToFloat(builder, loc, elementType, iyRem);
3343 auto ixRemFloat = castIndexToFloat(builder, loc, elementType, ixRem);
3345 auto yComponent = arith::DivFOp::create(builder, loc, iyRemFloat, constH);
3346 auto xComponent = arith::DivFOp::create(builder, loc, ixRemFloat, constW);
3347 auto sumXY = arith::AddFOp::create(builder, loc, yComponent, xComponent);
3348 auto angle = arith::MulFOp::create(builder, loc, twoPi, sumXY);
3355 auto iyIs0 = arith::CmpIOp::create(builder, loc, arith::CmpIPredicate::eq,
3357 auto iyIsHalfH = arith::CmpIOp::create(
3358 builder, loc, arith::CmpIPredicate::eq, iyRem, halfH);
3359 auto ixIs0 = arith::CmpIOp::create(builder, loc, arith::CmpIPredicate::eq,
3361 auto ixIsHalfW = arith::CmpIOp::create(
3362 builder, loc, arith::CmpIPredicate::eq, ixRem, halfW);
3364 auto iyIsSinSkippable =
3365 arith::OrIOp::create(builder, loc, iyIs0, iyIsHalfH);
3366 auto ixIsSinSkippable =
3367 arith::OrIOp::create(builder, loc, ixIs0, ixIsHalfW);
3368 auto shouldSkipSin = arith::AndIOp::create(builder, loc, iyIsSinSkippable,
3373 auto cosAngle = math::CosOp::create(builder, loc, angle);
3374 auto sinAngle = math::SinOp::create(builder, loc, angle);
3375 auto imagWeight = arith::SelectOp::create(builder, loc, shouldSkipSin,
3376 zeroFloat, sinAngle);
3377 auto realComponent =
3378 arith::MulFOp::create(builder, loc, valReal, cosAngle);
3379 auto imagComponent =
3380 arith::MulFOp::create(builder, loc, valReal, imagWeight);
3385 arith::AddFOp::create(builder, loc, sumReal, realComponent);
3387 arith::SubFOp::create(builder, loc, sumImag, imagComponent);
3389 linalg::YieldOp::create(builder, loc,
ValueRange{outReal, outImag});
3393 rfft2d, rfft2d.getResultTypes(), genericOpInputs, genericOpOutputs,
3394 indexingMaps, iteratorTypes, buildBody);
3403 LogicalResult matchAndRewrite(FFT2dOp fft2d,
3404 PatternRewriter &rewriter)
const override {
3405 if (!llvm::all_of(fft2d->getOperandTypes(),
3406 RFFT2dConverter::isRankedTensor) ||
3407 !llvm::all_of(fft2d->getResultTypes(),
3408 RFFT2dConverter::isRankedTensor)) {
3412 Location loc = fft2d.getLoc();
3413 Value input_real = fft2d.getInputReal();
3414 Value input_imag = fft2d.getInputImag();
3415 BoolAttr inverse = fft2d.getInverseAttr();
3417 auto real_el_ty = cast<FloatType>(
3418 cast<ShapedType>(input_real.
getType()).getElementType());
3419 [[maybe_unused]]
auto imag_el_ty = cast<FloatType>(
3420 cast<ShapedType>(input_imag.
getType()).getElementType());
3422 assert(real_el_ty == imag_el_ty);
3425 SmallVector<Value> dynamicSizes;
3430 SmallVector<int64_t, 3> staticSizes;
3433 auto outputType = RankedTensorType::get(staticSizes, real_el_ty);
3436 SmallVector<utils::IteratorType, 5> iteratorTypes = {
3437 utils::IteratorType::parallel, utils::IteratorType::parallel,
3438 utils::IteratorType::parallel, utils::IteratorType::reduction,
3439 utils::IteratorType::reduction};
3442 SmallVector<Value> genericOpInputs = {input_real, input_imag};
3443 SmallVector<Value> genericOpOutputs = {
3444 RFFT2dConverter::createZeroTensor(rewriter, loc, outputType,
3446 RFFT2dConverter::createZeroTensor(rewriter, loc, outputType,
3451 ArrayRef{RFFT2dConverter::affineDimsExpr(rewriter, 0, 3, 4),
3452 RFFT2dConverter::affineDimsExpr(rewriter, 0, 3, 4),
3453 RFFT2dConverter::affineDimsExpr(rewriter, 0, 1, 2),
3454 RFFT2dConverter::affineDimsExpr(rewriter, 0, 1, 2)},
3458 auto dimH = rewriter.
createOrFold<tensor::DimOp>(loc, input_real, 1);
3459 auto dimW = rewriter.
createOrFold<tensor::DimOp>(loc, input_real, 2);
3462 auto twoPiAttr = rewriter.
getFloatAttr(real_el_ty, 6.283185307179586);
3463 auto twoPi = arith::ConstantOp::create(rewriter, loc, twoPiAttr);
3465 RFFT2dConverter::castIndexToFloat(rewriter, loc, real_el_ty, dimH);
3467 RFFT2dConverter::castIndexToFloat(rewriter, loc, real_el_ty, dimW);
3469 auto buildBody = [&](OpBuilder &builder, Location loc,
ValueRange args) {
3470 Value valReal = args[0];
3471 Value valImag = args[1];
3472 Value sumReal = args[2];
3473 Value sumImag = args[3];
3476 Value oy = linalg::IndexOp::create(builder, loc, 1);
3477 Value ox = linalg::IndexOp::create(builder, loc, 2);
3478 Value iy = linalg::IndexOp::create(builder, loc, 3);
3479 Value ix = linalg::IndexOp::create(builder, loc, 4);
3483 auto iyXoy = index::MulOp::create(builder, loc, iy, oy);
3484 auto ixXox = index::MulOp::create(builder, loc, ix, ox);
3486 auto iyRem = index::RemUOp::create(builder, loc, iyXoy, dimH);
3487 auto ixRem = index::RemUOp::create(builder, loc, ixXox, dimW);
3490 RFFT2dConverter::castIndexToFloat(builder, loc, real_el_ty, iyRem);
3492 RFFT2dConverter::castIndexToFloat(builder, loc, real_el_ty, ixRem);
3494 auto yComponent = arith::DivFOp::create(builder, loc, iyRemFloat, constH);
3495 auto xComponent = arith::DivFOp::create(builder, loc, ixRemFloat, constW);
3497 auto sumXY = arith::AddFOp::create(builder, loc, yComponent, xComponent);
3498 auto angle = arith::MulFOp::create(builder, loc, twoPi, sumXY);
3501 angle = arith::MulFOp::create(
3502 builder, loc, angle,
3503 arith::ConstantOp::create(rewriter, loc,
3509 auto cosAngle = math::CosOp::create(builder, loc, angle);
3510 auto sinAngle = math::SinOp::create(builder, loc, angle);
3512 auto rcos = arith::MulFOp::create(builder, loc, valReal, cosAngle);
3513 auto rsin = arith::MulFOp::create(builder, loc, valImag, sinAngle);
3514 auto realComponent = arith::AddFOp::create(builder, loc, rcos, rsin);
3516 auto icos = arith::MulFOp::create(builder, loc, valImag, cosAngle);
3517 auto isin = arith::MulFOp::create(builder, loc, valReal, sinAngle);
3519 auto imagComponent = arith::SubFOp::create(builder, loc, icos, isin);
3524 arith::AddFOp::create(builder, loc, sumReal, realComponent);
3526 arith::AddFOp::create(builder, loc, sumImag, imagComponent);
3528 linalg::YieldOp::create(builder, loc,
ValueRange{outReal, outImag});
3532 fft2d, fft2d.getResultTypes(), genericOpInputs, genericOpOutputs,
3533 indexingMaps, iteratorTypes, buildBody);
3546 patterns->
add<GenericResizeConverter>(patterns->
getContext(),
3550 patterns->
add<MaterializeResizeBroadcast>(patterns->
getContext(),
3555 PointwiseConverter<tosa::AddOp>,
3556 PointwiseConverter<tosa::SubOp>,
3557 PointwiseConverter<tosa::MulOp>,
3558 PointwiseConverter<tosa::IntDivOp>,
3559 PointwiseConverter<tosa::NegateOp>,
3560 PointwiseConverter<tosa::PowOp>,
3561 PointwiseConverter<tosa::ReciprocalOp>,
3562 PointwiseConverter<tosa::RsqrtOp>,
3563 PointwiseConverter<tosa::LogOp>,
3564 PointwiseConverter<tosa::ExpOp>,
3565 PointwiseConverter<tosa::AbsOp>,
3566 PointwiseConverter<tosa::SinOp>,
3567 PointwiseConverter<tosa::CosOp>,
3568 PointwiseConverter<tosa::TanhOp>,
3569 PointwiseConverter<tosa::ErfOp>,
3570 PointwiseConverter<tosa::BitwiseAndOp>,
3571 PointwiseConverter<tosa::BitwiseOrOp>,
3572 PointwiseConverter<tosa::BitwiseNotOp>,
3573 PointwiseConverter<tosa::BitwiseXorOp>,
3574 PointwiseConverter<tosa::LogicalAndOp>,
3575 PointwiseConverter<tosa::LogicalNotOp>,
3576 PointwiseConverter<tosa::LogicalOrOp>,
3577 PointwiseConverter<tosa::LogicalXorOp>,
3578 PointwiseConverter<tosa::CastOp>,
3579 PointwiseConverter<tosa::LogicalLeftShiftOp>,
3580 PointwiseConverter<tosa::LogicalRightShiftOp>,
3581 PointwiseConverter<tosa::ArithmeticRightShiftOp>,
3582 PointwiseConverter<tosa::ClzOp>,
3583 PointwiseConverter<tosa::SelectOp>,
3584 PointwiseConverter<tosa::GreaterOp>,
3585 PointwiseConverter<tosa::GreaterEqualOp>,
3586 PointwiseConverter<tosa::EqualOp>,
3587 PointwiseConverter<tosa::MaximumOp>,
3588 PointwiseConverter<tosa::MinimumOp>,
3589 PointwiseConverter<tosa::CeilOp>,
3590 PointwiseConverter<tosa::FloorOp>,
3591 PointwiseConverter<tosa::ClampOp>,
3592 PointwiseConverter<tosa::SigmoidOp>
3595 patterns->
add<QuantizedMatMulTConverter>(converter, patterns->
getContext());
3598 IdentityNConverter<tosa::IdentityOp>,
3611 ReduceConverter<tosa::ReduceAllOp>,
3612 ReduceConverter<tosa::ReduceAnyOp>,
3613 ReduceConverter<tosa::ReduceMinOp>,
3614 ReduceConverter<tosa::ReduceMaxOp>,
3615 ReduceConverter<tosa::ReduceSumOp>,
3616 ReduceConverter<tosa::ReduceProductOp>,
3617 ArgMinMaxConverter<tosa::ArgMaxOp>,
3618 ArgMinMaxConverter<tosa::ArgMinOp>>(patterns->
getContext(),
options.allowNonFinites);
return MutableOperandRange * this
static int64_t product(ArrayRef< int64_t > vals)
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static llvm::ManagedStatic< PassManagerOptions > options
static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound, Value upperBound)
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static TypedAttr createInitialValueForReduceOp(Operation *op, Type elementTy, PatternRewriter &rewriter, bool allowNonFinites)
static OpFoldResult getOrFoldTensorDim(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value tensor, int64_t index)
static Value createLinalgBodyCalculationForReduceOp(Operation *op, ValueRange args, Type elementTy, PatternRewriter &rewriter)
static std::pair< Value, Value > normalizeMatMulBatchDimensions(PatternRewriter &rewriter, Location loc, Value a, Value b, int64_t batchRank)
static OpTy createWithDefaultProperties(OpBuilder &builder, Location loc, TypeRange resultTypes, ValueRange operands)
static Value broadcastMatMulLeadingDimensions(PatternRewriter &rewriter, Location loc, Value operand, Value other)
static Value getTensorDim(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value tensor, int64_t index)
static Value createIndex(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, int64_t index)
static LogicalResult reduceMatchAndRewriteHelper(OpTy op, uint64_t axis, PatternRewriter &rewriter, bool allowNonFinites)
static ValueRange getScalarOperands(Operation *operation, ValueRange operands)
static Value broadcastDynamicDimensions(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value operand, ArrayRef< OpFoldResult > targetShape, ArrayRef< Value > masterOperands)
static Value broadcastDynamicDimension(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value operand, int64_t dim, OpFoldResult targetSize, Value masterOperand)
static LogicalResult elementwiseMatchAndRewriteHelper(Operation *operation, ValueRange operands, ConversionPatternRewriter &rewriter, const TypeConverter &converter)
static Value createLinalgBodyCalculationForElementwiseOp(Operation *op, ValueRange args, ArrayRef< Type > resultTypes, ConversionPatternRewriter &rewriter)
static LogicalResult emitElementwiseComputation(ConversionPatternRewriter &rewriter, Location loc, Operation *operation, ValueRange operands, ValueRange scalarOperands, ArrayRef< OpFoldResult > targetShape, const TypeConverter &converter)
static ValueRange getBroadcastableOperands(Operation *operation, ValueRange operands)
static Value materializeBinaryNanCheckIfRequired(OpTy op, PatternRewriter &rewriter, Value lhs, Value rhs, Value result)
static std::pair< SmallVector< OpFoldResult >, SmallVector< Value > > computeTargetShape(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, ValueRange operands)
static bool operandsAndResultsRanked(Operation *operation)
static Value broadcastMatMulSingletonDimension(PatternRewriter &rewriter, Location loc, Value operand, int64_t dim, OpFoldResult size)
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
static const llvm::fltSemantics * getFloatSemantics(TruncfSrcElemTypes etype)
Float semantics the element type attributes of xevm.truncf and xevm.extf stand for.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
AffineExpr getResult(unsigned idx) const
BlockArgument getArgument(unsigned i)
bool getValue() const
Return the boolean value of this attribute.
IntegerAttr getIndexAttr(int64_t value)
IntegerAttr getI32IntegerAttr(int32_t value)
IntegerAttr getIntegerAttr(Type type, int64_t value)
AffineMap getMultiDimIdentityMap(unsigned rank)
FloatAttr getFloatAttr(Type type, double value)
AffineExpr getAffineConstantExpr(int64_t constant)
IntegerType getIntegerType(unsigned width)
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
BoolAttr getBoolAttr(bool value)
TypedAttr getZeroAttr(Type type)
AffineExpr getAffineDimExpr(unsigned position)
MLIRContext * getContext() const
IntegerAttr getI8IntegerAttr(int8_t value)
An attribute that represents a reference to a dense vector or tensor object.
auto getValues() const
Return the held element values as a range of the given type.
An attribute that represents a reference to a dense integer vector or tensor object.
static DenseIntElementsAttr get(const ShapedType &type, Arg &&arg)
Get an instance of a DenseIntElementsAttr with the given arguments.
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
This class helps build Operations.
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
This class represents a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
Value getOperand(unsigned idx)
Location getLoc()
The source location the operation was defined or derived from.
unsigned getNumOperands()
result_type_range getResultTypes()
operand_range getOperands()
Returns an iterator on the underlying Value's.
result_range getResults()
unsigned getNumResults()
Return the number of results held by this operation.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
bool isInteger() const
Return true if this is an integer type (with the specified width).
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class provides an abstraction over the different types of ranges over Values.
type_range getType() const
Type front()
Return first type in the range.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
InFlightDiagnostic & next(InFlightDiagnostic &diag)
Starts a new message part in an in-flight diagnostic.
Value createCanonicalRankReducingExtractSliceOp(OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType)
Create a rank-reducing ExtractSliceOp @[0 .
OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value, int64_t dim)
Return the dimension of the given tensor value.
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Value clampFloatHelper(Location loc, Value arg, Value min, Value max, OpBuilder &rewriter)
llvm::DenseMap< int64_t, Value > IndexPool
Caches the arith.constant index values created for a set of dimension indices so that broadcasting he...
SmallVector< utils::IteratorType > getNParallelLoopsAttrs(unsigned nParallelLoops)
SmallVector< Value > condenseValues(const SmallVector< Value > &values)
std::optional< SmallVector< Value > > checkHasDynamicBatchDims(PatternRewriter &rewriter, Op op, ArrayRef< Value > params)
Value truncateToOutputType(PatternRewriter &rewriter, Location loc, Value input, RankedTensorType targetType)
Truncate an FP32 tensor to BF16 without changing shape or encoding.
MatMulTOperands prepareMatMulOperands(PatternRewriter &rewriter, Location loc, Value a, Value b, RankedTensorType outputType, bool transposeB)
Broadcast the batch dimensions of the ranked operands and create a zero-filled result tensor for eith...
std::pair< OpFoldResult, Value > computeTargetSize(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, ValueRange operands, int64_t dim)
Compute the broadcasted runtime size of dimension dim of an elementwise operation whose operands all ...
APFloat getFloatMinMaxIdentity(const llvm::fltSemantics &semantics, bool negative, bool allowNonFinites)
void populateTosaToLinalgConversionPatterns(const TypeConverter &converter, RewritePatternSet *patterns, const TosaToLinalgOptions &options=TosaToLinalgOptions())
Populates conversion passes from TOSA dialect to Linalg dialect.
Type getAccumulationType(Type requestedType)
Value getTosaConstShape(ImplicitLocOpBuilder &builder, llvm::ArrayRef< int64_t > shape)
SmallVector< int64_t > convertFromMlirShape(ArrayRef< int64_t > shape)
Value clampIntHelper(Location loc, Value arg, Value min, Value max, OpBuilder &rewriter, bool isUnsigned)
bool getConstShapeValues(Operation *op, llvm::SmallVector< int64_t > &result_shape)
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
void dispatchIndexOpFoldResults(ArrayRef< OpFoldResult > ofrs, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch multiple OpFoldResults according to the behavior of dispatchIndexOpFoldRe...
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...