27#include "llvm/ADT/SmallVectorExtras.h"
28#include "llvm/ADT/TypeSwitch.h"
42static std::optional<linalg::ElementwiseKind>
44 using linalg::ElementwiseKind;
45 const bool isFloat = isa<FloatType>(elementTy);
47 const bool isBoolean = elementTy.
isInteger(1);
51 if (isa<tosa::AbsOp>(op))
52 return ElementwiseKind::abs;
53 if (isa<tosa::CeilOp>(op))
54 return ElementwiseKind::ceil;
55 if (isa<tosa::FloorOp>(op))
56 return ElementwiseKind::floor;
57 if (isa<tosa::ExpOp>(op))
58 return ElementwiseKind::exp;
59 if (isa<tosa::LogOp>(op))
60 return ElementwiseKind::log;
61 if (isa<tosa::RsqrtOp>(op))
62 return ElementwiseKind::rsqrt;
63 if (isa<tosa::SinOp>(op))
64 return ElementwiseKind::sin;
65 if (isa<tosa::CosOp>(op))
66 return ElementwiseKind::cos;
67 if (isa<tosa::TanhOp>(op))
68 return ElementwiseKind::tanh;
69 if (isa<tosa::ErfOp>(op))
70 return ElementwiseKind::erf;
71 if (isa<tosa::ReciprocalOp>(op))
72 return ElementwiseKind::reciprocal;
73 if (isa<tosa::PowOp>(op))
74 return ElementwiseKind::powf;
78 if (isFloat || (isSignlessInt && !isBoolean)) {
79 if (isa<tosa::AddOp>(op))
80 return ElementwiseKind::add;
81 if (isa<tosa::SubOp>(op))
82 return ElementwiseKind::sub;
86 if (isSignlessInt && !isBoolean && isa<tosa::IntDivOp>(op))
87 return ElementwiseKind::div;
93 if (
auto mulOp = dyn_cast<tosa::MulOp>(op)) {
95 const bool zeroShift =
98 const bool matchingTypes =
99 cast<ShapedType>(mulOp.getInput1().getType()).getElementType() ==
101 cast<ShapedType>(mulOp.getInput2().getType()).getElementType() ==
103 if ((isFloat || (isSignlessInt && !isBoolean)) && zeroShift &&
105 return ElementwiseKind::mul;
110 if (
auto negateOp = dyn_cast<tosa::NegateOp>(op)) {
112 FailureOr<int64_t> inZp = negateOp.getInput1ZeroPoint();
113 FailureOr<int64_t> outZp = negateOp.getOutputZeroPoint();
114 if (succeeded(inZp) && succeeded(outZp) && *inZp == 0 && *outZp == 0)
115 return ElementwiseKind::negf;
122 auto nanModeIsPropagate = [](
auto tosaOp) {
123 return tosaOp.getNanMode() == NanPropagationMode::PROPAGATE;
125 if (isFloat || (isSignlessInt && !isBoolean)) {
126 if (
auto maxOp = dyn_cast<tosa::MaximumOp>(op)) {
127 if (!isFloat || nanModeIsPropagate(maxOp))
128 return ElementwiseKind::max_signed;
130 if (
auto minOp = dyn_cast<tosa::MinimumOp>(op)) {
131 if (!isFloat || nanModeIsPropagate(minOp))
132 return ElementwiseKind::min_signed;
137 if ((isFloat || isSignlessInt || isBoolean) && isa<tosa::SelectOp>(op))
138 return ElementwiseKind::select;
143std::optional<linalg::ElementwiseKind>
150 auto operandTy = dyn_cast<RankedTensorType>(operand.getType());
151 if (!operandTy || !operandTy.hasStaticShape())
155 if (!resultTy || !resultTy.hasStaticShape())
164 if (llvm::all_of(pad, [](
int64_t p) {
return p == 0; }))
167 ShapedType inputTy = cast<ShapedType>(input.
getType());
168 Type inputETy = inputTy.getElementType();
169 auto inputShape = inputTy.getShape();
171 assert((inputShape.size() * 2) == pad.size());
176 for (
size_t i : llvm::seq(inputShape.size())) {
177 auto lowPad = pad[i * 2];
178 auto highPad = pad[i * 2 + 1];
179 if (ShapedType::isDynamic(inputShape[i]))
180 paddedShape.push_back(inputShape[i]);
182 paddedShape.push_back(inputShape[i] + highPad + lowPad);
187 Value padValue = dyn_cast<Value>(paddingValue);
189 auto padAttr = cast<TypedAttr>(cast<Attribute>(paddingValue));
190 padValue = arith::ConstantOp::create(rewriter, loc, padAttr);
193 return tensor::PadOp::create(rewriter, loc,
194 RankedTensorType::get(paddedShape, inputETy),
195 input, lowIndices, highIndices, padValue);
202 ShapedType resultTy = cast<ShapedType>(conv.
getType());
203 return linalg::GenericOp::create(
207 Value biasVal = args[0];
208 Type resType = args[1].getType();
209 if (resType != biasVal.
getType()) {
211 arith::ExtSIOp::create(builder, loc, resType, biasVal);
214 arith::AddIOp::create(builder, loc, biasVal, args[1]);
215 linalg::YieldOp::create(builder, loc, added);
224 ShapedType resultTy = cast<ShapedType>(
result.getType());
225 ShapedType sourceTy = cast<ShapedType>(source.
getType());
226 const int64_t resultRank = resultTy.getRank();
227 const int64_t sourceRank = sourceTy.getRank();
235 assert(sourceTy.hasStaticShape() &&
236 "Dynamic broadcasting shapes not supported!");
237 if (sourceRank == 1 && sourceTy.getDimSize(0) == 1) {
240 for (
auto dim : llvm::seq<int64_t>(0, sourceRank)) {
242 sourceDims.push_back(expr);
256 ShapedType resultTy = cast<ShapedType>(
result.getType());
257 const int64_t resultRank = resultTy.getRank();
264 return linalg::GenericOp::create(
268 Value biasVal = args[0];
269 Type resType = args[1].getType();
270 if (resType != biasVal.
getType()) {
272 resultTy.getElementType().isFloat()
273 ? arith::ExtFOp::create(
275 ValueRange{biasVal}, arith::ExtFOp::Properties{})
277 : arith::ExtSIOp::create(builder, loc, resType,
281 linalg::YieldOp::create(builder, loc, biasVal);
302 auto one = arith::ConstantOp::create(rewriter, loc,
303 IntegerAttr::get(inputDim.
getType(), 1));
305 Value paddedBefore = arith::AddIOp::create(builder, inputDim, padBefore);
307 Value paddedAfter = arith::AddIOp::create(builder, paddedBefore, padAfter);
309 Value subOne = arith::SubIOp::create(builder, kernelDim, one);
311 Value dilated = arith::MulIOp::create(builder, dilation, subOne);
312 Value addOne = arith::AddIOp::create(builder, dilated, one);
314 Value subtract = arith::SubIOp::create(builder, paddedAfter, addOne);
316 Value divide = arith::DivUIOp::create(builder, subtract, stride);
317 return arith::AddIOp::create(builder, divide, one);
326 ShapedType inputTy = cast<ShapedType>(input.
getType());
327 int64_t inputRank = inputTy.getRank();
330 dynDims.resize(resultTy.getRank());
332 for (uint32_t i = 0, s = inputSizeDims.size(); i < s; ++i) {
333 int64_t inputDim = inputSizeDims[i];
334 int64_t kernelDim = kernelSizeDims[i];
335 if (resultTy.isDynamicDim(inputDim)) {
336 auto padTop = padAttr[i * 2];
337 auto padBottom = padAttr[i * 2 + 1];
338 auto stride = strideAttr[i];
339 auto dilation = dilationAttr[i];
340 Value initDynDim = tensor::DimOp::create(rewriter, loc, input, inputDim);
342 tensor::DimOp::create(rewriter, loc, weight, kernelDim);
346 kernelDynDim, stride, dilation, rewriter);
351 for (
int i = 0; i < inputRank; i++) {
352 if (resultTy.isDynamicDim(i) && !dynDims[i])
353 dynDims[i] = tensor::DimOp::create(rewriter, loc, input, i);
365 reassociationMap.resize(outputRank);
366 for (
int i = 0; i < outputRank; i++) {
369 reassociationMap[outputRank - 1].push_back(
380 Value zero = arith::ConstantOp::create(rewriter, loc,
383 if (isa<FloatType>(zeroPointType)) {
384 isZero = arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::OEQ,
387 isZero = arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::eq,
390 cf::AssertOp::create(rewriter, loc, isZero, rewriter.
getStringAttr(message));
394template <
typename TosaConvOp,
typename LinalgConvOp,
typename LinalgConvQOp>
395class ConvConverter :
public OpConversionPattern<TosaConvOp> {
397 using OpConversionPattern<TosaConvOp>::OpConversionPattern;
399 matchAndRewrite(TosaConvOp op,
typename TosaConvOp::Adaptor adaptor,
400 ConversionPatternRewriter &rewriter)
const final {
401 Location loc = op->getLoc();
402 Value input = op->getOperand(0);
403 Value weight = op->getOperand(1);
404 Value bias = op->getOperand(2);
406 ShapedType inputTy = cast<ShapedType>(input.
getType());
407 ShapedType weightTy = cast<ShapedType>(weight.
getType());
408 ShapedType biasTy = cast<ShapedType>(bias.
getType());
409 ShapedType resultTy = cast<ShapedType>(op->getResult(0).getType());
411 Type inputETy = inputTy.getElementType();
418 Type accTy = RankedTensorType::get(resultTy.getShape(), accETy);
421 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
422 FailureOr<int64_t> maybeWZp = op.getWeightZeroPoint();
424 bool isInputZpConstant = succeeded(maybeIZp);
425 bool isWeightZpConstant = succeeded(maybeWZp);
427 Value nonConstantInputZpScalar;
428 Value nonConstantWeightZpScalar;
430 if (isInputZpConstant) {
431 const int64_t inputZpConstant = *maybeIZp;
432 if (op.verifyInputZeroPoint(inputZpConstant).failed())
433 return rewriter.notifyMatchFailure(
434 op,
"input zero point must be zero for non-int8 integer types");
437 nonConstantInputZpScalar = tensor::ExtractOp::create(
438 rewriter, loc, adaptor.getInputZp(),
ValueRange{index0});
440 rewriter, loc, nonConstantInputZpScalar,
441 "tosa.conv input zero point must be zero for non-int8 types");
444 if (isWeightZpConstant) {
445 const int64_t weightZpConstant = *maybeWZp;
446 if (op.verifyWeightZeroPoint(weightZpConstant).failed())
447 return rewriter.notifyMatchFailure(
448 op,
"weight zero point must be zero for non-int8 integer types");
451 nonConstantWeightZpScalar = tensor::ExtractOp::create(
452 rewriter, loc, adaptor.getWeightZp(),
ValueRange{index0});
454 rewriter, loc, nonConstantWeightZpScalar,
455 "tosa.conv weight zero point must be zero for non-int8 types");
462 (isInputZpConstant && *maybeIZp != 0) ||
463 (isWeightZpConstant && *maybeWZp != 0) ||
464 (!isInputZpConstant &&
465 nonConstantInputZpScalar.
getType().isSignlessInteger(8)) ||
466 (!isWeightZpConstant &&
467 nonConstantWeightZpScalar.
getType().isSignlessInteger(8));
469 if (!weightTy.hasStaticShape() || !biasTy.hasStaticShape())
470 return rewriter.notifyMatchFailure(
471 op,
"tosa.conv ops require static shapes for weight and bias");
474 return rewriter.notifyMatchFailure(
475 op,
"tosa.conv ops does not support unsigned integer input");
477 llvm::SmallVector<int64_t> inputSizeDims;
478 llvm::SmallVector<int64_t> kernelSizeDims;
479 for (
int i = 1; i < resultTy.getRank() - 1; i++) {
480 inputSizeDims.push_back(i);
481 kernelSizeDims.push_back(i);
485 loc, input, weight, resultTy, padAttr.
asArrayRef(),
487 inputSizeDims, kernelSizeDims, rewriter);
489 auto weightShape = weightTy.getShape();
492 llvm::SmallVector<int64_t> pad;
494 llvm::append_range(pad, padAttr.
asArrayRef());
495 pad.resize(pad.size() + 2, 0);
497 if (isInputZpConstant) {
498 const int64_t inputZpConstant = *maybeIZp;
499 TypedAttr padValue = rewriter.getZeroAttr(inputETy);
500 if (inputZpConstant != 0)
501 padValue = rewriter.getIntegerAttr(inputETy, inputZpConstant);
502 input =
applyPad(loc, input, pad, padValue, rewriter);
506 input =
applyPad(loc, input, pad, nonConstantInputZpScalar, rewriter);
509 if (4 == inputTy.getRank()) {
513 useConvQOp ? std::is_same_v<LinalgConvQOp, linalg::Conv2DNhwcHwcfQOp>
514 : std::is_same_v<LinalgConvOp, linalg::Conv2DNhwcHwcfOp>;
520 SmallVector<int32_t> weightPerm;
521 for (
int i = 1; i < resultTy.getRank(); i++)
522 weightPerm.push_back(i);
523 weightPerm.push_back(0);
525 SmallVector<int64_t> newWeightShape;
526 for (
auto dim : weightPerm)
527 newWeightShape.push_back(weightShape[dim]);
528 auto weightPermAttr = rewriter.getDenseI32ArrayAttr(weightPerm);
530 RankedTensorType::get(newWeightShape, weightTy.getElementType());
531 weight = tosa::TransposeOp::create(rewriter, loc, newWeightTy, weight,
539 if (5 == inputTy.getRank()) {
542 SmallVector<int32_t> weightPerm;
543 for (
int i = 1; i < resultTy.getRank(); i++)
544 weightPerm.push_back(i);
545 weightPerm.push_back(0);
547 SmallVector<int64_t> newWeightShape;
548 for (
auto dim : weightPerm)
549 newWeightShape.push_back(weightShape[dim]);
550 auto weightPermAttr = rewriter.getDenseI32ArrayAttr(weightPerm);
552 RankedTensorType::get(newWeightShape, weightTy.getElementType());
553 weight = tosa::TransposeOp::create(rewriter, loc, newWeightTy, weight,
558 ArrayRef<int64_t> stride = strideTosaAttr;
559 ArrayRef<int64_t> dilation = dilationTosaAttr;
562 auto strideAttr = rewriter.getI64TensorAttr(stride);
563 auto dilationAttr = rewriter.getI64TensorAttr(dilation);
565 Value biasEmptyTensor = tensor::EmptyOp::create(
566 rewriter, loc, resultTy.getShape(), accETy, filteredDims);
568 Value broadcastBias =
572 auto getQConvZpAsI32 = [&](FailureOr<int64_t> maybeZp,
573 Value nonConstantZpScalar) -> Value {
574 if (succeeded(maybeZp))
575 return arith::ConstantOp::create(
576 rewriter, loc, rewriter.getI32IntegerAttr(*maybeZp));
577 assert(nonConstantZpScalar &&
578 "expected a scalar for a non-constant zero point");
579 if (nonConstantZpScalar.getType().isSignlessInteger(8))
580 return arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(),
581 nonConstantZpScalar);
583 return arith::ConstantOp::create(rewriter, loc,
584 rewriter.getI32IntegerAttr(0));
587 Value iZpVal = getQConvZpAsI32(maybeIZp, nonConstantInputZpScalar);
588 Value kZpVal = getQConvZpAsI32(maybeWZp, nonConstantWeightZpScalar);
590 Value conv = LinalgConvQOp::create(
591 rewriter, loc, resultTy,
593 ValueRange{broadcastBias}, strideAttr, dilationAttr)
596 rewriter.replaceOp(op, conv);
600 Value conv = LinalgConvOp::create(
601 rewriter, loc, accTy,
ValueRange{input, weight},
602 ValueRange{broadcastBias}, strideAttr, dilationAttr)
607 if (resultTy != accTy)
608 conv = tosa::CastOp::create(rewriter, loc, resultTy, conv);
610 rewriter.replaceOp(op, conv);
615class DepthwiseConvConverter
616 :
public OpConversionPattern<tosa::DepthwiseConv2DOp> {
618 using OpConversionPattern<tosa::DepthwiseConv2DOp>::OpConversionPattern;
620 matchAndRewrite(tosa::DepthwiseConv2DOp op, OpAdaptor adaptor,
621 ConversionPatternRewriter &rewriter)
const final {
622 Location loc = op->getLoc();
623 Value input = op->getOperand(0);
624 Value weight = op->getOperand(1);
625 Value bias = op->getOperand(2);
627 ShapedType inputTy = cast<ShapedType>(input.
getType());
628 ShapedType weightTy = cast<ShapedType>(weight.
getType());
629 ShapedType biasTy = cast<ShapedType>(bias.
getType());
630 ShapedType resultTy = cast<ShapedType>(op->getResult(0).getType());
631 int64_t resultRank = resultTy.getRank();
633 Type inputETy = inputTy.getElementType();
634 Type resultETy = resultTy.getElementType();
636 auto padAttr = op.getPadAttr();
637 auto strideTosaAttr = op.getStrideAttr();
638 auto dilationTosaAttr = op.getDilationAttr();
642 if (!weightTy.hasStaticShape() || !biasTy.hasStaticShape())
643 return rewriter.notifyMatchFailure(
644 op,
"tosa.depthwise_conv ops require static shapes");
648 loc, input, weight, resultTy, padAttr.
asArrayRef(),
655 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
656 FailureOr<int64_t> maybeWZp = op.getWeightZeroPoint();
658 return rewriter.notifyMatchFailure(
659 op,
"input zero point cannot be statically determined");
661 return rewriter.notifyMatchFailure(
662 op,
"weight zero point cannot be statically determined");
664 const int64_t inputZpVal = *maybeIZp;
665 const int64_t weightZpVal = *maybeWZp;
667 if (op.verifyInputZeroPoint(inputZpVal).failed())
668 return rewriter.notifyMatchFailure(
669 op,
"input zero point must be zero for non-int8 integer types");
671 if (op.verifyWeightZeroPoint(weightZpVal).failed())
672 return rewriter.notifyMatchFailure(
673 op,
"weight zero point must be zero for non-int8 integer types");
675 bool hasNullZps = (inputZpVal == 0) && (weightZpVal == 0);
676 auto weightShape = weightTy.getShape();
677 auto resultShape = resultTy.getShape();
680 TypedAttr zeroAttr = rewriter.getZeroAttr(inputETy);
689 if (inputZpVal < intMin || inputZpVal > intMax)
690 return rewriter.notifyMatchFailure(
691 op,
"tosa.depthwise_conv op quantization has zp outside of input "
694 zeroAttr = rewriter.getIntegerAttr(inputETy, inputZpVal);
697 llvm::SmallVector<int64_t> pad;
699 llvm::append_range(pad, padAttr.
asArrayRef());
700 pad.resize(pad.size() + 2, 0);
702 input =
applyPad(loc, input, pad, zeroAttr, rewriter);
705 ArrayRef<int64_t> stride = strideTosaAttr;
706 ArrayRef<int64_t> dilation = dilationTosaAttr;
709 auto strideAttr = rewriter.getI64TensorAttr(stride);
710 auto dilationAttr = rewriter.getI64TensorAttr(dilation);
711 ShapedType linalgConvTy =
712 RankedTensorType::get({resultShape[0], resultShape[1], resultShape[2],
713 weightShape[2], weightShape[3]},
716 auto resultZeroAttr = rewriter.getZeroAttr(accETy);
717 Value emptyTensor = tensor::EmptyOp::create(
718 rewriter, loc, linalgConvTy.getShape(), accETy, filteredDims);
719 Value zero = arith::ConstantOp::create(rewriter, loc, resultZeroAttr);
720 Value zeroTensor = linalg::FillOp::create(rewriter, loc,
ValueRange{zero},
724 Value biasEmptyTensor = tensor::EmptyOp::create(
725 rewriter, loc, resultTy.getShape(), resultETy, filteredDims);
728 SmallVector<AffineMap, 4> indexingMaps;
730 indexingMaps.push_back(rewriter.getMultiDimIdentityMap(resultRank));
731 indexingMaps.push_back(rewriter.getMultiDimIdentityMap(resultRank));
734 Value conv = linalg::DepthwiseConv2DNhwcHwcmOp::create(
735 rewriter, loc, linalgConvTy,
ValueRange{input, weight},
736 ValueRange{zeroTensor}, strideAttr, dilationAttr)
741 if (accETy != resultETy)
742 conv = tosa::CastOp::create(
744 RankedTensorType::get(cast<ShapedType>(conv.
getType()).getShape(),
748 SmallVector<ReassociationExprs, 4> reassociationMap;
750 Value convReshape = tensor::CollapseShapeOp::create(
751 rewriter, loc, resultTy, conv, reassociationMap);
754 linalg::GenericOp::create(
755 rewriter, loc, resultTy,
ValueRange({bias, convReshape}),
757 [&](OpBuilder &nestedBuilder, Location nestedLoc,
760 if (llvm::isa<FloatType>(inputETy))
761 added = arith::AddFOp::create(nestedBuilder, loc, args[0],
764 added = arith::AddIOp::create(nestedBuilder, loc, args[0],
766 linalg::YieldOp::create(nestedBuilder, nestedLoc, added);
769 rewriter.replaceOp(op,
result);
771 IntegerAttr iZp = rewriter.getI32IntegerAttr(inputZpVal);
772 IntegerAttr wZp = rewriter.getI32IntegerAttr(weightZpVal);
773 auto iZpVal = arith::ConstantOp::create(rewriter, loc, iZp);
774 auto kZpVal = arith::ConstantOp::create(rewriter, loc, wZp);
775 Value conv = linalg::DepthwiseConv2DNhwcHwcmQOp::create(
776 rewriter, loc, linalgConvTy,
778 ValueRange{zeroTensor}, strideAttr, dilationAttr)
780 SmallVector<ReassociationExprs, 4> reassociationMap;
782 Value convReshape = tensor::CollapseShapeOp::create(
783 rewriter, loc, resultTy, conv, reassociationMap);
785 rewriter, loc, bias, convReshape, biasEmptyTensor, indexingMaps);
786 rewriter.replaceOp(op,
result);
797template <
typename TosaOp>
798class ElementwiseConverter :
public OpConversionPattern<TosaOp> {
800 using OpConversionPattern<TosaOp>::OpConversionPattern;
801 using typename OpConversionPattern<TosaOp>::OpAdaptor;
804 matchAndRewrite(TosaOp op, OpAdaptor adaptor,
805 ConversionPatternRewriter &rewriter)
const final {
806 std::optional<linalg::ElementwiseKind> kind =
809 return rewriter.notifyMatchFailure(
810 op,
"op has no linalg.elementwise counterpart");
812 Location loc = op.getLoc();
813 auto resultTy = cast<RankedTensorType>(op.getType());
814 const int64_t rank = resultTy.getRank();
816 const unsigned arity =
821 ValueRange inputs = adaptor.getOperands().take_front(arity);
825 SmallVector<AffineMap> indexingMaps;
826 for (Value operand : inputs) {
827 ArrayRef<int64_t> shape = cast<ShapedType>(operand.getType()).getShape();
828 SmallVector<AffineExpr> exprs;
829 for (
const auto &dim : llvm::enumerate(shape)) {
830 bool requiresBroadcast =
831 dim.value() == 1 && resultTy.getDimSize(dim.index()) != 1;
832 exprs.push_back(requiresBroadcast
833 ? rewriter.getAffineConstantExpr(0)
834 : rewriter.getAffineDimExpr(dim.index()));
837 rewriter.getContext()));
839 indexingMaps.push_back(rewriter.getMultiDimIdentityMap(rank));
842 Value emptyTensor = tensor::EmptyOp::create(
843 rewriter, loc, resultTy.getShape(), resultTy.getElementType());
845 rewriter.replaceOpWithNewOp<linalg::ElementwiseOp>(
847 rewriter.getAffineMapArrayAttr(indexingMaps));
853getMatMulBatchCollapseReassociation(
int64_t rank) {
855 for (
int64_t dim = 0; dim < rank - 2; ++dim)
857 reassociation[1].push_back(rank - 2);
858 reassociation[2].push_back(rank - 1);
859 return reassociation;
862class MatMulConverter :
public OpConversionPattern<tosa::MatMulOp> {
864 using OpConversionPattern<tosa::MatMulOp>::OpConversionPattern;
866 matchAndRewrite(tosa::MatMulOp op, OpAdaptor adaptor,
867 ConversionPatternRewriter &rewriter)
const final {
868 Location loc = op.getLoc();
869 auto aType = dyn_cast<RankedTensorType>(adaptor.getA().getType());
870 auto bType = dyn_cast<RankedTensorType>(adaptor.getB().getType());
871 auto outputType = dyn_cast<RankedTensorType>(op.getType());
872 if (!aType || !bType || !outputType)
873 return rewriter.notifyMatchFailure(op,
"only supports ranked tensors");
878 FailureOr<int64_t> maybeAZp = op.getAZeroPoint();
879 FailureOr<int64_t> maybeBZp = op.getBZeroPoint();
881 return rewriter.notifyMatchFailure(
882 op,
"input A zero point cannot be statically determined");
884 return rewriter.notifyMatchFailure(
885 op,
"input B zero point cannot be statically determined");
887 const int64_t aZpVal = *maybeAZp;
888 const int64_t bZpVal = *maybeBZp;
890 if (op.verifyAZeroPoint(aZpVal).failed())
891 return rewriter.notifyMatchFailure(
892 op,
"input A zero point must be zero for non-int8 integer types");
894 if (op.verifyBZeroPoint(bZpVal).failed())
895 return rewriter.notifyMatchFailure(
896 op,
"input B zero point must be zero for non-int8 integer types");
898 const int64_t outputRank = outputType.getRank();
899 auto [a,
b, zeroTensor] =
904 const bool hasNonzeroZeroPoint = aZpVal != 0 || bZpVal != 0;
905 if (hasNonzeroZeroPoint) {
906 aZp = arith::ConstantOp::create(rewriter, loc,
907 rewriter.getI32IntegerAttr(aZpVal));
908 bZp = arith::ConstantOp::create(rewriter, loc,
909 rewriter.getI32IntegerAttr(bZpVal));
913 if (outputRank == 2) {
914 if (!hasNonzeroZeroPoint) {
916 linalg::MatmulOp::create(rewriter, loc,
TypeRange{accType},
920 result = linalg::QuantizedMatmulOp::create(
925 }
else if (outputRank == 3) {
926 if (!hasNonzeroZeroPoint) {
927 result = linalg::BatchMatmulOp::create(
932 result = linalg::QuantizedBatchMatmulOp::create(
938 SmallVector<ReassociationIndices> reassociation =
939 getMatMulBatchCollapseReassociation(outputRank);
940 auto collapse = [&](Value value) {
941 auto type = cast<RankedTensorType>(value.getType());
943 tensor::CollapseShapeOp::inferCollapsedType(type, reassociation);
944 return tensor::CollapseShapeOp::create(rewriter, loc, collapsedType,
945 value, reassociation);
948 Value collapsedA = collapse(a);
949 Value collapsedB = collapse(
b);
950 Value collapsedInit = collapse(zeroTensor);
951 auto collapsedOutputType =
952 cast<RankedTensorType>(collapsedInit.
getType());
953 Value collapsedResult;
955 if (!hasNonzeroZeroPoint) {
957 linalg::BatchMatmulOp::create(
958 rewriter, loc,
TypeRange{collapsedOutputType},
962 collapsedResult = linalg::QuantizedBatchMatmulOp::create(
963 rewriter, loc,
TypeRange{collapsedOutputType},
969 result = tensor::ExpandShapeOp::create(
970 rewriter, loc, accType, collapsedResult, reassociation,
975 rewriter.replaceOp(op,
result);
980class MatMulTConverter :
public OpConversionPattern<tosa::MatMulTOp> {
982 using OpConversionPattern<tosa::MatMulTOp>::OpConversionPattern;
984 matchAndRewrite(tosa::MatMulTOp op, OpAdaptor adaptor,
985 ConversionPatternRewriter &rewriter)
const final {
986 Location loc = op.getLoc();
987 auto aType = dyn_cast<RankedTensorType>(adaptor.getA().getType());
988 auto bType = dyn_cast<RankedTensorType>(adaptor.getB().getType());
989 auto outputType = dyn_cast<RankedTensorType>(op.getType());
990 if (!aType || !bType || !outputType)
991 return rewriter.notifyMatchFailure(op,
"only supports ranked tensors");
996 FailureOr<int64_t> maybeAZp = op.getAZeroPoint();
997 FailureOr<int64_t> maybeBZp = op.getBZeroPoint();
999 return rewriter.notifyMatchFailure(
1000 op,
"input A zero point cannot be statically determined");
1002 return rewriter.notifyMatchFailure(
1003 op,
"input B zero point cannot be statically determined");
1005 const int64_t aZpVal = *maybeAZp;
1006 const int64_t bZpVal = *maybeBZp;
1008 if (aZpVal != 0 || bZpVal != 0)
1009 return rewriter.notifyMatchFailure(
1010 op,
"nonzero zero points require the generic MATMUL_T lowering");
1012 const int64_t outputRank = outputType.getRank();
1013 auto [a,
b, zeroTensor] =
1018 if (outputRank == 2) {
1023 }
else if (outputRank == 3) {
1029 SmallVector<ReassociationIndices> reassociation =
1030 getMatMulBatchCollapseReassociation(outputRank);
1031 auto collapse = [&](Value value) {
1032 auto type = cast<RankedTensorType>(value.getType());
1033 auto collapsedType =
1034 tensor::CollapseShapeOp::inferCollapsedType(type, reassociation);
1035 return tensor::CollapseShapeOp::create(rewriter, loc, collapsedType,
1036 value, reassociation);
1039 Value collapsedA = collapse(a);
1040 Value collapsedB = collapse(
b);
1041 Value collapsedInit = collapse(zeroTensor);
1042 auto collapsedOutputType =
1043 cast<RankedTensorType>(collapsedInit.
getType());
1045 Value collapsedResult =
1047 rewriter, loc,
TypeRange{collapsedOutputType},
1051 result = tensor::ExpandShapeOp::create(
1052 rewriter, loc, accType, collapsedResult, reassociation,
1057 rewriter.replaceOp(op,
result);
1062class MaxPool2dConverter :
public OpConversionPattern<tosa::MaxPool2dOp> {
1064 MaxPool2dConverter(
const TypeConverter &typeConverter, MLIRContext *context,
1065 bool allowNonFinites)
1066 : OpConversionPattern(typeConverter, context),
1067 allowNonFinites(allowNonFinites) {}
1070 static SmallVector<Value>
1071 computeDynamicOutputSizes(tosa::MaxPool2dOp op, OpAdaptor adaptor,
1072 ConversionPatternRewriter &rewriter) {
1073 TensorType resultTy = op.getType();
1074 Location loc = op.getLoc();
1076 Value input = adaptor.getInput();
1077 ArrayRef<int64_t> kernel = op.getKernel();
1078 ArrayRef<int64_t> pad = op.getPad();
1079 ArrayRef<int64_t> stride = op.getStride();
1081 SmallVector<Value> dynamicDims;
1084 if (resultTy.isDynamicDim(0))
1085 dynamicDims.push_back(tensor::DimOp::create(rewriter, loc, input, 0));
1088 for (int64_t dim : {1, 2}) {
1089 if (!resultTy.isDynamicDim(dim))
1093 int64_t index = dim - 1;
1096 Value ihw = tensor::DimOp::create(rewriter, loc, input, dim);
1103 pad[index * 2 + 1], khw, stride[index],
1105 dynamicDims.push_back(ohw);
1109 if (resultTy.isDynamicDim(3))
1110 dynamicDims.push_back(tensor::DimOp::create(rewriter, loc, input, 3));
1116 matchAndRewrite(tosa::MaxPool2dOp op, OpAdaptor adaptor,
1117 ConversionPatternRewriter &rewriter)
const final {
1118 Location loc = op.getLoc();
1119 Value input = adaptor.getInput();
1120 ShapedType inputTy = cast<ShapedType>(input.
getType());
1122 bool isUnsigned = op.getType().getElementType().isUnsignedInteger();
1123 ShapedType resultTy =
1124 getTypeConverter()->convertType<ShapedType>(op.getType());
1126 return rewriter.notifyMatchFailure(op,
"failed to convert type");
1127 Type resultETy = inputTy.getElementType();
1128 NanPropagationMode nanMode = op.getNanMode();
1130 SmallVector<Value> dynamicDims =
1131 computeDynamicOutputSizes(op, adaptor, rewriter);
1134 TypedAttr initialAttr;
1136 const llvm::fltSemantics &semantics =
1137 cast<FloatType>(resultETy).getFloatSemantics();
1138 if (llvm::APFloat::semanticsHasNaN(semantics))
1139 initialAttr = rewriter.getFloatAttr(
1141 nanMode == NanPropagationMode::IGNORE
1142 ? APFloat::getNaN(semantics)
1144 true, allowNonFinites));
1147 else if (isUnsigned)
1148 initialAttr = rewriter.getIntegerAttr(
1150 else if (isa<IntegerType>(resultETy))
1151 initialAttr = rewriter.getIntegerAttr(
1156 return rewriter.notifyMatchFailure(
1157 op,
"Unsupported initial value for tosa.maxpool_2d op");
1160 llvm::SmallVector<int64_t> pad;
1162 llvm::append_range(pad, op.getPad());
1163 pad.resize(pad.size() + 2, 0);
1168 Value paddedInput =
applyPad(loc, input, pad, initialAttr, rewriter);
1170 Value initialValue = arith::ConstantOp::create(rewriter, loc, initialAttr);
1172 ArrayRef<int64_t> kernel = op.getKernel();
1173 ArrayRef<int64_t> stride = op.getStride();
1175 Attribute strideAttr = rewriter.getI64VectorAttr(stride);
1176 Attribute dilationAttr = rewriter.getI64VectorAttr({1, 1});
1180 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
1181 resultTy.getElementType(), dynamicDims);
1183 Value filledEmptyTensor =
1184 linalg::FillOp::create(rewriter, loc, initialValue, emptyTensor)
1187 Value fakeWindowDims =
1188 tensor::EmptyOp::create(rewriter, loc, kernel, resultETy);
1191 rewriter.replaceOpWithNewOp<linalg::PoolingNhwcMaxUnsignedOp>(
1192 op, ArrayRef<Type>{resultTy},
ValueRange{paddedInput, fakeWindowDims},
1193 filledEmptyTensor, strideAttr, dilationAttr);
1194 return llvm::success();
1197 auto resultOp = linalg::PoolingNhwcMaxOp::create(
1198 rewriter, op->getLoc(), ArrayRef<Type>{resultTy},
1199 ValueRange{paddedInput, fakeWindowDims}, filledEmptyTensor, strideAttr,
1202 rewriter.replaceOp(op, resultOp);
1216 if (nanMode == NanPropagationMode::IGNORE) {
1217 auto genericOp = linalg::GenericOp::create(
1218 rewriter, loc, resultOp.getType(0), resultOp.getInputs(),
1219 resultOp.getOutputs(), resultOp.getIndexingMapsArray(),
1220 resultOp.getIteratorTypesArray(),
1221 [&](OpBuilder &opBuilder, Location loc,
ValueRange blockArgs) {
1223 auto oldBlock = resultOp.getRegion().begin();
1224 auto oldArgs = oldBlock->getArguments();
1225 auto &oldMaxOp = *resultOp.getBlock()->begin();
1226 map.map(oldArgs, blockArgs);
1227 auto *newOp = opBuilder.clone(oldMaxOp, map);
1229 arith::CmpFOp::create(opBuilder, loc, arith::CmpFPredicate::UNO,
1230 blockArgs.front(), blockArgs.front());
1231 Value accumulatorIsNaN =
1232 arith::CmpFOp::create(opBuilder, loc, arith::CmpFPredicate::UNO,
1233 blockArgs.back(), blockArgs.back());
1234 Value finiteMaximum =
1235 arith::SelectOp::create(opBuilder, loc, accumulatorIsNaN,
1236 blockArgs.front(), newOp->getResult(0));
1237 Value result = arith::SelectOp::create(
1238 opBuilder, loc, inputIsNaN, blockArgs.back(), finiteMaximum);
1239 linalg::YieldOp::create(opBuilder, loc, result);
1241 rewriter.replaceOp(resultOp, genericOp);
1248 bool allowNonFinites;
1253 using OpRewritePattern<tosa::AvgPool2dOp>::OpRewritePattern;
1255 LogicalResult matchAndRewrite(tosa::AvgPool2dOp op,
1256 PatternRewriter &rewriter)
const final {
1257 Location loc = op.getLoc();
1258 Value input = op.getInput();
1259 ShapedType inputTy = cast<ShapedType>(input.
getType());
1260 Type inElementTy = inputTy.getElementType();
1262 ShapedType resultTy = cast<ShapedType>(op.getType());
1263 Type resultETy = cast<ShapedType>(op.getType()).getElementType();
1265 Type accETy = op.getAccType();
1266 ShapedType accTy = resultTy.clone(accETy);
1268 auto dynamicDimsOr =
1270 if (!dynamicDimsOr.has_value())
1272 SmallVector<Value> dynamicDims = *dynamicDimsOr;
1274 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
1275 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
1277 return rewriter.notifyMatchFailure(
1278 op,
"input zero point could not be statically determined");
1280 return rewriter.notifyMatchFailure(
1281 op,
"output zero point could not be statically determined");
1283 const int64_t inputZpVal = *maybeIZp;
1284 const int64_t outputZpVal = *maybeOZp;
1287 llvm::SmallVector<int64_t> pad;
1289 llvm::append_range(pad, op.getPad());
1290 pad.resize(pad.size() + 2, 0);
1291 TypedAttr padAttr = rewriter.getZeroAttr(inElementTy);
1295 Value paddedInput =
applyPad(loc, input, pad, padAttr, rewriter);
1297 auto initialAttr = rewriter.getZeroAttr(accETy);
1298 Value initialValue = arith::ConstantOp::create(rewriter, loc, initialAttr);
1300 ArrayRef<int64_t> kernel = op.getKernel();
1301 ArrayRef<int64_t> stride = op.getStride();
1303 Attribute strideAttr = rewriter.getI64VectorAttr(stride);
1304 Attribute dilationAttr = rewriter.getI64VectorAttr({1, 1});
1307 Value poolEmptyTensor = tensor::EmptyOp::create(
1308 rewriter, loc, accTy.getShape(), accETy, dynamicDims);
1310 Value filledEmptyTensor =
1311 linalg::FillOp::create(rewriter, loc,
ValueRange{initialValue},
1315 Value fakeWindowDims =
1316 tensor::EmptyOp::create(rewriter, loc, kernel, accETy);
1319 Value poolingOp = linalg::PoolingNhwcSumOp::create(
1320 rewriter, loc, ArrayRef<Type>{accTy},
1322 filledEmptyTensor, strideAttr, dilationAttr)
1327 Value iH = tensor::DimOp::create(rewriter, loc, poolingOp, 1);
1328 Value iW = tensor::DimOp::create(rewriter, loc, poolingOp, 2);
1331 iH = arith::SubIOp::create(rewriter, loc, iH, one);
1332 iW = arith::SubIOp::create(rewriter, loc, iW, one);
1334 Value genericEmptyTensor = tensor::EmptyOp::create(
1335 rewriter, loc, resultTy.getShape(), resultETy, dynamicDims);
1337 auto affineMap = rewriter.getMultiDimIdentityMap(resultTy.getRank());
1338 auto genericOp = linalg::GenericOp::create(
1339 rewriter, loc, ArrayRef<Type>({resultTy}),
ValueRange{poolingOp},
1341 ArrayRef<AffineMap>({affineMap, affineMap}),
1343 [&](OpBuilder &
b, Location loc,
ValueRange args) {
1348 auto padFn = [&](Value valid, Value pos, int64_t pad) -> Value {
1353 Value dpos = arith::SubIOp::create(rewriter, loc, pos, padVal);
1355 Value offset = arith::MinSIOp::create(rewriter, loc, dpos, zero);
1356 return arith::AddIOp::create(rewriter, loc, valid, offset)
1360 auto coverageFn = [&](int64_t i, Value isize) -> Value {
1367 Value left = linalg::IndexOp::create(rewriter, loc, i);
1368 Value right = arith::SubIOp::create(rewriter, loc, isize, left);
1369 left = arith::MulIOp::create(rewriter, loc, left, strideVal);
1370 right = arith::MulIOp::create(rewriter, loc, right, strideVal);
1373 val = padFn(val, left, pad[i * 2]);
1374 val = padFn(val, right, pad[i * 2 + 1]);
1375 return arith::MaxSIOp::create(rewriter, loc, one, val);
1379 Value kH3 = coverageFn(1, iH);
1380 Value kW3 = coverageFn(2, iW);
1383 auto count = arith::IndexCastOp::create(
1384 rewriter, loc, rewriter.getI32Type(),
1385 arith::MulIOp::create(rewriter, loc, kH3, kW3));
1390 Value poolVal = args[0];
1391 if (isa<FloatType>(accETy)) {
1392 auto countF = arith::SIToFPOp::create(rewriter, loc, accETy, count);
1393 poolVal = arith::DivFOp::create(rewriter, loc, poolVal, countF)
1398 arith::TruncFOp::create(rewriter, loc, resultETy, poolVal);
1403 if (inputZpVal != 0) {
1404 auto inputZp = arith::ConstantOp::create(
1405 rewriter, loc,
b.getIntegerAttr(accETy, inputZpVal));
1407 arith::MulIOp::create(rewriter, loc, accETy, count, inputZp);
1409 arith::SubIOp::create(rewriter, loc, accETy, poolVal, offset);
1413 Value one32 = arith::ConstantOp::create(
1414 rewriter, loc, rewriter.getI32IntegerAttr(1));
1415 Value thirtyTwo32 = arith::ConstantOp::create(
1416 rewriter, loc, rewriter.getI32IntegerAttr(32));
1419 arith::SubIOp::create(rewriter, loc, count, one32);
1420 Value leadingZeros =
1421 math::CountLeadingZerosOp::create(rewriter, loc, countSubOne);
1423 arith::SubIOp::create(rewriter, loc, thirtyTwo32, leadingZeros);
1427 arith::ExtUIOp::create(rewriter, loc, rewriter.getI64Type(), k);
1428 Value thirtyShiftPlusOne = arith::ConstantOp::create(
1429 rewriter, loc, rewriter.getI64IntegerAttr((1 << 30) + 1));
1431 arith::ShLIOp::create(rewriter, loc, thirtyShiftPlusOne, k64);
1434 Value count64 = arith::ExtUIOp::create(
1435 rewriter, loc, rewriter.getI64Type(), count);
1437 arith::DivUIOp::create(rewriter, loc, numerator, count64);
1438 multiplier = arith::TruncIOp::create(
1439 rewriter, loc, rewriter.getI32Type(), multiplier);
1443 arith::TruncIOp::create(rewriter, loc, rewriter.getI8Type(), k);
1444 Value thirty8 = arith::ConstantOp::create(
1445 rewriter, loc, rewriter.getI8IntegerAttr(30));
1446 Value shift = arith::AddIOp::create(rewriter, loc, k8, thirty8);
1448 auto roundingAttr = RoundingModeAttr::get(
1449 rewriter.getContext(), RoundingMode::SINGLE_ROUND);
1451 auto scaled = tosa::ApplyScaleOp::create(
1452 rewriter, loc, rewriter.getI32Type(), poolVal,
1453 multiplier, shift, roundingAttr)
1458 if (outputZpVal != 0) {
1459 auto outputZp = arith::ConstantOp::create(
1461 b.getIntegerAttr(scaled.getType(), outputZpVal));
1462 scaled = arith::AddIOp::create(rewriter, loc, scaled, outputZp)
1470 rewriter, loc, accETy,
1471 APInt::getSignedMinValue(outBitwidth).getSExtValue());
1473 rewriter, loc, accETy,
1474 APInt::getSignedMaxValue(outBitwidth).getSExtValue());
1482 arith::TruncIOp::create(rewriter, loc, resultETy, poolVal);
1486 linalg::YieldOp::create(rewriter, loc, poolVal);
1489 rewriter.replaceOp(op, genericOp.getResult(0));
1496 using OpRewritePattern<tosa::TransposeOp>::OpRewritePattern;
1498 LogicalResult matchAndRewrite(tosa::TransposeOp op,
1499 PatternRewriter &rewriter)
const final {
1500 const llvm::ArrayRef<int32_t> constantPerms = op.getPerms();
1502 Location loc = op.getLoc();
1506 SmallVector<OpFoldResult> inputSizes =
1508 auto permutedSizes =
1512 tensor::EmptyOp::create(rewriter, loc, permutedSizes,
1513 op.getInput1().getType().getElementType());
1514 rewriter.replaceOpWithNewOp<linalg::TransposeOp>(
1515 op, op.getInput1(), permutedInit,
1516 llvm::map_to_vector(constantPerms,
1517 [](int32_t v) -> int64_t {
return v; }));
1525 const TosaToLinalgNamedOptions &
options) {
1526 if (
options.preferConv2DKernelLayoutHWCF) {
1527 patterns->
add<ConvConverter<tosa::Conv2DOp, linalg::Conv2DNhwcHwcfOp,
1528 linalg::Conv2DNhwcHwcfQOp>>(
1531 patterns->
add<ConvConverter<tosa::Conv2DOp, linalg::Conv2DNhwcFhwcOp,
1532 linalg::Conv2DNhwcFhwcQOp>>(
1537 ConvConverter<tosa::Conv3DOp, linalg::Conv3DNdhwcDhwcfOp, linalg::Conv3DNdhwcDhwcfQOp>,
1538 DepthwiseConvConverter,
1546 ElementwiseConverter<tosa::AbsOp>,
1547 ElementwiseConverter<tosa::CeilOp>,
1548 ElementwiseConverter<tosa::FloorOp>,
1549 ElementwiseConverter<tosa::ExpOp>,
1550 ElementwiseConverter<tosa::LogOp>,
1551 ElementwiseConverter<tosa::RsqrtOp>,
1552 ElementwiseConverter<tosa::SinOp>,
1553 ElementwiseConverter<tosa::CosOp>,
1554 ElementwiseConverter<tosa::TanhOp>,
1555 ElementwiseConverter<tosa::ErfOp>,
1556 ElementwiseConverter<tosa::ReciprocalOp>,
1557 ElementwiseConverter<tosa::PowOp>,
1558 ElementwiseConverter<tosa::AddOp>,
1559 ElementwiseConverter<tosa::SubOp>,
1560 ElementwiseConverter<tosa::IntDivOp>,
1561 ElementwiseConverter<tosa::MulOp>,
1562 ElementwiseConverter<tosa::NegateOp>,
1563 ElementwiseConverter<tosa::MaximumOp>,
1564 ElementwiseConverter<tosa::MinimumOp>,
1565 ElementwiseConverter<tosa::SelectOp>
memberIdxs push_back(ArrayAttr::get(parser.getContext(), values))
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 AffineMap getBroadcastingMap(PatternRewriter &rewriter, Value source, Value result)
static void createDepthwiseConvCollapseMap(int64_t outputRank, SmallVector< ReassociationExprs, 4 > &reassociationMap, OpBuilder &rewriter)
static mlir::Value linalgIntBroadcastExtSIAdd(PatternRewriter &rewriter, Location loc, Value bias, Value conv, Value result, ArrayRef< AffineMap > indexingMaps)
static mlir::Value getConvOrPoolOutputDim(Location loc, Value inputDim, int64_t padBeforeAttr, int64_t padAfterAttr, Value kernelDim, int64_t strideAttr, int64_t dilationAttr, OpBuilder &rewriter)
static void createZeroPointAssertionIfNonI8(PatternRewriter &rewriter, Location loc, Value zeroPoint, StringRef message)
static mlir::Value linalgBroadcastAndMaybeExt(PatternRewriter &rewriter, Location loc, Value source, Value result)
static mlir::Value reifyConstantDim(int64_t attr, ImplicitLocOpBuilder &builder)
static SmallVector< Value > inferDynamicDimsForConv(Location loc, Value input, Value weight, ShapedType resultTy, ArrayRef< int64_t > padAttr, ArrayRef< int64_t > strideAttr, ArrayRef< int64_t > dilationAttr, ArrayRef< int64_t > inputSizeDims, ArrayRef< int64_t > kernelSizeDims, OpBuilder &rewriter)
static std::optional< linalg::ElementwiseKind > getElementwiseKind(Operation *op, Type elementTy)
static mlir::Value applyPad(Location loc, Value input, ArrayRef< int64_t > pad, OpFoldResult paddingValue, OpBuilder &rewriter)
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: () -> ().
IntegerAttr getIndexAttr(int64_t value)
AffineMap getMultiDimIdentityMap(unsigned rank)
AffineExpr getAffineConstantExpr(int64_t constant)
StringAttr getStringAttr(const Twine &bytes)
TypedAttr getZeroAttr(Type type)
AffineExpr getAffineDimExpr(unsigned position)
MLIRContext * getContext() const
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.
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.
This class represents a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
operand_range getOperands()
Returns an iterator on the underlying Value's.
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.
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...
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
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).
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.
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)
ArrayRef< T > asArrayRef() const
static BatchMatmulTransposeBOp create(OpBuilder &builder, Location location, ValueRange inputs, ValueRange outputs, ArrayRef< NamedAttribute > attributes={})
static MatmulTransposeBOp create(OpBuilder &builder, Location location, ValueRange inputs, ValueRange outputs, ArrayRef< NamedAttribute > attributes={})
ArityGroupAndKind getArityGroupAndKind(ElementwiseKind kind)
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
SmallVector< T > applyTOSAPermutation(ArrayRef< T > input, ArrayRef< int32_t > perms)
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...
APFloat getFloatMinMaxIdentity(const llvm::fltSemantics &semantics, bool negative, bool allowNonFinites)
Type getAccumulationType(Type requestedType)
Value clampIntHelper(Location loc, Value arg, Value min, Value max, OpBuilder &rewriter, bool isUnsigned)
void populateTosaToLinalgNamedConversionPatterns(const TypeConverter &converter, RewritePatternSet *patterns, const TosaToLinalgNamedOptions &options)
Populates conversion passes from TOSA dialect to Linalg named operations.
std::optional< linalg::ElementwiseKind > isConvertibleToLinalgElementwise(Operation *op)
Returns the linalg.elementwise kind that the TosaToLinalgNamed conversion lowers op to,...
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
ElementwiseArityGroup arityGroup