MLIR 23.0.0git
TosaCanonicalizations.cpp
Go to the documentation of this file.
1//===- TosaCanonicalizations.cpp - Canonicalization patterns & folders ----===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// \file
10// TOSA canonicalization patterns and folders.
11//
12//===----------------------------------------------------------------------===//
13
20#include "mlir/Dialect/Traits.h"
23#include "mlir/IR/IRMapping.h"
24#include "mlir/IR/Matchers.h"
29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/APInt.h"
31
32#include <functional>
33
34using namespace mlir;
35using namespace mlir::tosa;
36
37namespace {
38OpFoldResult foldToInputIfTypeMatches(Type typeRef, Value input) {
39 return input.getType() == typeRef ? OpFoldResult(input) : OpFoldResult{};
40}
41} // namespace
42
43//===----------------------------------------------------------------------===//
44// Operator Canonicalizers.
45//===----------------------------------------------------------------------===//
46
47//===----------------------------------------------------------------------===//
48// Tensor Data Engine Operators.
49//===----------------------------------------------------------------------===//
50
51// Check that the zero point of the tensor and padding operations are aligned.
52static bool checkMatchingPadConstAndZp(Value padConst, Value zp) {
53 // Check that padConst is a constant value and a scalar tensor
54 DenseElementsAttr padConstAttr;
55 if (!matchPattern(padConst, m_Constant(&padConstAttr)) ||
56 (padConstAttr.size() != 1)) {
57 return false;
58 }
59
60 // Check that floating point pad is zero
61 if (auto padConstFpAttr = mlir::dyn_cast<DenseFPElementsAttr>(padConstAttr)) {
62 float padConstVal = (*padConstFpAttr.begin()).convertToFloat();
63 return padConstVal == 0.0f;
64 }
65
66 // Check that the zp and padConst align for the integer (quantized) case
67 if (auto padConstIntAttr =
68 mlir::dyn_cast<DenseIntElementsAttr>(padConstAttr)) {
70 // Check that zp is a constant value and a scalar tensor
71 if (!matchPattern(zp, m_Constant(&zpAttr)) || (padConstAttr.size() != 1)) {
72 return false;
73 }
74
75 // Check equality
76 int64_t zpVal = (*zpAttr.begin()).getSExtValue();
77 int64_t padConstVal = (*padConstIntAttr.begin()).getSExtValue();
78 return zpVal == padConstVal;
79 }
80
81 // Bail-out on unsupported type
82 return false;
83}
84
85namespace {
86template <typename OpTy>
87struct PoolPadFoldAdaptor;
88
89template <>
90struct PoolPadFoldAdaptor<tosa::MaxPool2dOp> {
91 using OpTy = tosa::MaxPool2dOp;
92 static bool checkKernelCompliance(OpTy op, const ArrayRef<int64_t> newPad) {
93 const llvm::ArrayRef<int64_t> kernel = op.getKernel();
94 if (newPad[2] >= kernel[1] || newPad[3] >= kernel[1] ||
95 newPad[0] >= kernel[0] || newPad[1] >= kernel[0])
96 return false;
97 return true;
98 }
99 static bool checkPadConstCompliance(OpTy, Value padConst) {
100 // Check that padConst is a constant value and a scalar tensor
101 DenseElementsAttr padConstAttr;
102 if (!matchPattern(padConst, m_Constant(&padConstAttr)) ||
103 padConstAttr.size() != 1) {
104 return false;
105 }
106
107 // Pad needs to be in the minimum value to be able to merge
108 if (auto padConstFpAttr =
109 mlir::dyn_cast<DenseFPElementsAttr>(padConstAttr)) {
110 const APFloat padConstVal = *padConstFpAttr.begin();
111 const APFloat lowestVal =
112 APFloat::getLargest(padConstVal.getSemantics(), true);
113 return padConstVal == lowestVal;
114 }
115 if (auto padConstIntAttr =
116 mlir::dyn_cast<DenseIntElementsAttr>(padConstAttr)) {
117 const APInt padConstVal = *padConstIntAttr.begin();
118 const unsigned int bitWidth = padConstVal.getBitWidth();
119 const APInt lowestVal =
120 padConstIntAttr.getElementType().isUnsignedInteger()
121 ? APInt::getZero(bitWidth)
122 : APInt::getSignedMinValue(bitWidth);
123 return padConstVal == lowestVal;
124 }
125
126 // Bail-out on unsupported type
127 return false;
128 }
129 static void replaceOpWithNewPad(PatternRewriter &rewriter, OpTy op,
130 Value padInput, ArrayRef<int64_t> newPad) {
131 rewriter.replaceOpWithNewOp<tosa::MaxPool2dOp>(
132 op, op.getType(), padInput, op.getKernel(), op.getStride(),
133 rewriter.getDenseI64ArrayAttr(newPad), op.getNanMode());
134 }
135};
136
137template <typename OpTy>
138struct ConvPadFoldAdaptor {
139 static bool checkKernelCompliance(OpTy, const ArrayRef<int64_t>) {
140 return true;
141 }
142 static bool checkPadConstCompliance(OpTy op, Value padConst) {
143 return checkMatchingPadConstAndZp(padConst, op.getInputZp());
144 }
145 static void replaceOpWithNewPad(PatternRewriter &rewriter, OpTy op,
146 Value padInput, ArrayRef<int64_t> newPad) {
147 rewriter.replaceOpWithNewOp<OpTy>(
148 op, op.getResult().getType(), padInput, op.getWeight(), op.getBias(),
149 op.getInputZp(), op.getWeightZp(), newPad, op.getStrideAttr(),
150 op.getDilationAttr(), op.getAccType(), op.getLocalBound());
151 }
152};
153
154// Pattern attempts to fold a `tosa.pad` operator to a following tensor
155// operation like `tosa.conv2d` by merging the padding associated with the
156// pad operator directly to the implicit padding of the tensor operation.
157// This helps eliminate the explicit padding operator if unused.
158template <typename OpTy, typename AdaptorTy>
159struct FoldPadToTensorOp : public OpRewritePattern<OpTy> {
160 using OpRewritePattern<OpTy>::OpRewritePattern;
161
162 LogicalResult matchAndRewrite(OpTy tensorOp,
163 PatternRewriter &rewriter) const override {
164 // Check producer is a tosa::PadOp
165 auto padOp = tensorOp.getInput().template getDefiningOp<tosa::PadOp>();
166 if (!padOp)
167 return rewriter.notifyMatchFailure(tensorOp,
168 "Producer must be a tosa::PadOp.");
169
170 // Validate that tensor operation has sane padding
171 const std::vector<int64_t> &tensorOpPad = tensorOp.getPad().vec();
172 if (tensorOpPad.size() != 4) // pad_top, pad_bottom, pad_left, pad_right
173 return rewriter.notifyMatchFailure(
174 tensorOp, "Tensor operation padding shall have 4 elements.");
175
176 // Validate tosa::PadOp padding
177 DenseIntElementsAttr padOpPadding;
178 if (!matchPattern(padOp.getPadding(), m_Constant(&padOpPadding))) {
179 return rewriter.notifyMatchFailure(
180 tensorOp,
181 "The `padding` input specified on the tosa::PadOp must be constant.");
182 }
183 // N_before, N_after, H_before, H_after, W_before, W_after, C_before,
184 // C_after
185 if (padOpPadding.size() != 8)
186 return rewriter.notifyMatchFailure(tensorOp,
187 "Pad padding should have 8 elements.");
188 int64_t padNBefore = (*(padOpPadding.begin() + 0)).getLimitedValue();
189 int64_t padNAfter = (*(padOpPadding.begin() + 1)).getLimitedValue();
190 int64_t padHBefore = (*(padOpPadding.begin() + 2)).getLimitedValue();
191 int64_t padHAfter = (*(padOpPadding.begin() + 3)).getLimitedValue();
192 int64_t padWBefore = (*(padOpPadding.begin() + 4)).getLimitedValue();
193 int64_t padWAfter = (*(padOpPadding.begin() + 5)).getLimitedValue();
194 int64_t padCBefore = (*(padOpPadding.begin() + 6)).getLimitedValue();
195 int64_t padCAfter = (*(padOpPadding.begin() + 7)).getLimitedValue();
196
197 if (padNBefore != 0 || padNAfter != 0 || padCBefore != 0 || padCAfter != 0)
198 return rewriter.notifyMatchFailure(
199 tensorOp, "Folding padding in N or C dimensions is not supported.");
200
201 // Fold padding from Pad into the tensor operation
202 // 4 elements - pad_top, pad_bottom, pad_left, pad_right
203 SmallVector<int64_t> foldedPad(tensorOpPad.size());
204 foldedPad[0] = padHBefore + tensorOpPad[0];
205 foldedPad[1] = padHAfter + tensorOpPad[1];
206 foldedPad[2] = padWBefore + tensorOpPad[2];
207 foldedPad[3] = padWAfter + tensorOpPad[3];
208
209 // Check kernel related restrictions
210 if (!AdaptorTy::checkKernelCompliance(tensorOp, foldedPad)) {
211 return rewriter.notifyMatchFailure(
212 tensorOp, "Padding size not aligned with kernel restrictions.");
213 }
214
215 // Check padding constant restrictions
216 if (!AdaptorTy::checkPadConstCompliance(tensorOp, padOp.getPadConst())) {
217 return rewriter.notifyMatchFailure(
218 tensorOp,
219 "Padding constant is not aligned with operator zero-point.");
220 }
221
222 // Check that padding doesn't grow more than 8K level (8192) for now
223 if (llvm::any_of(foldedPad, [](int64_t padVal) { return padVal > 8192; })) {
224 return rewriter.notifyMatchFailure(
225 tensorOp, "Padding size more than the 8K level limit.");
226 }
227
228 // Create operator
229 AdaptorTy::replaceOpWithNewPad(rewriter, tensorOp, padOp.getInput1(),
230 foldedPad);
231
232 return success();
233 }
234};
235} // namespace
236
237void Conv2DOp::getCanonicalizationPatterns(RewritePatternSet &results,
238 MLIRContext *context) {
239 results.add<
240 FoldPadToTensorOp<tosa::Conv2DOp, ConvPadFoldAdaptor<tosa::Conv2DOp>>>(
241 context);
242}
243
244void DepthwiseConv2DOp::getCanonicalizationPatterns(RewritePatternSet &results,
245 MLIRContext *context) {
246 results.add<FoldPadToTensorOp<tosa::DepthwiseConv2DOp,
247 ConvPadFoldAdaptor<tosa::DepthwiseConv2DOp>>>(
248 context);
249}
250
252 : public OpRewritePattern<tosa::AvgPool2dAdaptiveOp> {
254
255 LogicalResult matchAndRewrite(tosa::AvgPool2dAdaptiveOp op,
256 PatternRewriter &rewriter) const override {
260 if (!tosa::getConstShapeValues(op.getKernel().getDefiningOp(), kernel) ||
261 !tosa::getConstShapeValues(op.getStride().getDefiningOp(), stride) ||
262 !tosa::getConstShapeValues(op.getPad().getDefiningOp(), pad))
263 return rewriter.notifyMatchFailure(
264 op, "expected constant kernel, stride, and pad operands");
265
266 auto replacement = tosa::AvgPool2dOp::create(
267 rewriter, op.getLoc(), op.getType(), op.getInput(), op.getInputZp(),
268 op.getOutputZp(), rewriter.getDenseI64ArrayAttr(kernel),
269 rewriter.getDenseI64ArrayAttr(stride),
270 rewriter.getDenseI64ArrayAttr(pad), op.getAccTypeAttr());
271 rewriter.replaceOp(op, replacement.getOutput());
272 return success();
273 }
274};
275
276struct AvgPool2dIsNoOp : public OpRewritePattern<tosa::AvgPool2dOp> {
278
279 LogicalResult matchAndRewrite(tosa::AvgPool2dOp op,
280 PatternRewriter &rewriter) const override {
281 // Prevent canonicalization if input/output shapes don't align
282 if (op.getInput().getType() != op.getOutput().getType())
283 return rewriter.notifyMatchFailure(
284 op, "expected input and output types to match");
285
286 const auto inputType = llvm::cast<ShapedType>(op.getInput().getType());
287 if (!llvm::isa<FloatType>(inputType.getElementType()))
288 return rewriter.notifyMatchFailure(op,
289 "expected floating-point input type");
290
291 // For statically known zero points, the verifier ensures zero points are
292 // zero for floating-point types
293 if (!matchPattern(op.getInputZp(), m_Constant()) ||
294 !matchPattern(op.getOutputZp(), m_Constant()))
295 return rewriter.notifyMatchFailure(
296 op,
297 "expected input and output zero points to be statically verifiable");
298
299 if (!llvm::all_of(op.getKernel(), [](int64_t val) { return val == 1; }))
300 return rewriter.notifyMatchFailure(op, "expected unit kernel");
301
302 if (!llvm::all_of(op.getStride(), [](int64_t val) { return val == 1; }))
303 return rewriter.notifyMatchFailure(op, "expected unit stride");
304
305 if (!llvm::all_of(op.getPad(), [](int64_t val) { return val == 0; }))
306 return rewriter.notifyMatchFailure(op, "expected zero padding");
307
308 rewriter.replaceOp(op, op.getInput());
309 return success();
310 }
311};
312
313void AvgPool2dOp::getCanonicalizationPatterns(RewritePatternSet &results,
314 MLIRContext *context) {
315 results.add<AvgPool2dIsNoOp>(context);
316}
317
318void AvgPool2dAdaptiveOp::getCanonicalizationPatterns(
319 RewritePatternSet &results, MLIRContext *context) {
320 results.add<AvgPool2dAdaptiveToAvgPool2d>(context);
321}
322
323struct MaxPool2dIsNoOp : public OpRewritePattern<tosa::MaxPool2dOp> {
325
326 LogicalResult matchAndRewrite(tosa::MaxPool2dOp op,
327 PatternRewriter &rewriter) const override {
328 Value input = op.getInput();
329 Value output = op.getOutput();
330 ShapedType inputType = llvm::cast<ShapedType>(input.getType());
331 ShapedType outputType = llvm::cast<ShapedType>(output.getType());
332
333 if (input.getType() == output.getType() &&
334 llvm::all_of(op.getKernel(), [](int64_t val) { return val == 1; }) &&
335 llvm::all_of(op.getStride(), [](int64_t val) { return val == 1; }) &&
336 llvm::all_of(op.getPad(), [](int64_t val) { return val == 0; }) &&
337 op.getNanMode() == tosa::NanPropagationMode::PROPAGATE) {
338 rewriter.replaceOp(op, input);
339 return success();
340 }
341
342 if (!inputType.hasStaticShape() || !outputType.hasStaticShape()) {
343 return failure();
344 }
345
346 // If the output and input shapes are 1x1, then this is a no op.
347 ArrayRef<int64_t> outputShape = outputType.getShape();
348 if (outputShape[1] != 1 || outputShape[2] != 1) {
349 return failure();
350 }
351
352 ArrayRef<int64_t> inputShape = inputType.getShape();
353 if (inputShape[1] != 1 || inputShape[2] != 1) {
354 return failure();
355 }
356
357 rewriter.replaceOp(op, input);
358 return success();
359 }
360};
361
362void MaxPool2dOp::getCanonicalizationPatterns(RewritePatternSet &results,
363 MLIRContext *context) {
364 results.add<MaxPool2dIsNoOp,
365 FoldPadToTensorOp<tosa::MaxPool2dOp,
366 PoolPadFoldAdaptor<tosa::MaxPool2dOp>>>(
367 context);
368}
369
371 : public OpRewritePattern<tosa::MaxPool2dAdaptiveOp> {
373
374 LogicalResult matchAndRewrite(tosa::MaxPool2dAdaptiveOp op,
375 PatternRewriter &rewriter) const override {
379 if (!tosa::getConstShapeValues(op.getKernel().getDefiningOp(), kernel) ||
380 !tosa::getConstShapeValues(op.getStride().getDefiningOp(), stride) ||
381 !tosa::getConstShapeValues(op.getPad().getDefiningOp(), pad))
382 return rewriter.notifyMatchFailure(
383 op, "expected constant kernel, stride, and pad operands");
384
385 auto replacement = tosa::MaxPool2dOp::create(
386 rewriter, op.getLoc(), op.getType(), op.getInput(),
387 rewriter.getDenseI64ArrayAttr(kernel),
388 rewriter.getDenseI64ArrayAttr(stride),
389 rewriter.getDenseI64ArrayAttr(pad), op.getNanModeAttr());
390 rewriter.replaceOp(op, replacement.getOutput());
391 return success();
392 }
393};
394
395void MaxPool2dAdaptiveOp::getCanonicalizationPatterns(
396 RewritePatternSet &results, MLIRContext *context) {
397 results.add<MaxPool2dAdaptiveToMaxPool2d>(context);
398}
399
400//===----------------------------------------------------------------------===//
401// Data Layout / Memory Reinterpretation.
402//===----------------------------------------------------------------------===//
403
404struct ConcatOptimization : public OpRewritePattern<tosa::ConcatOp> {
405 using OpRewritePattern<tosa::ConcatOp>::OpRewritePattern;
406
407 LogicalResult matchAndRewrite(tosa::ConcatOp op,
408 PatternRewriter &rewriter) const override {
409 if (op.getInput1().size() != 1)
410 return failure();
411 if (op.getInput1().front().getType() != op.getType()) {
412 rewriter
413 .replaceOpWithNewOp<tensor::CastOp>(op, op.getType(),
414 op.getInput1().front())
415 .getResult();
416 return success();
417 }
418
419 rewriter.replaceOp(op, op.getInput1().front());
420 return success();
421 }
422};
423
424struct ConsecutiveConcatOptimization : public OpRewritePattern<tosa::ConcatOp> {
425 using OpRewritePattern<tosa::ConcatOp>::OpRewritePattern;
426
427 LogicalResult matchAndRewrite(tosa::ConcatOp op,
428 PatternRewriter &rewriter) const override {
429 // Rewrite consecutive concats on the same axis into a single op.
430 // Keep track of the operands so we are able to construct a new concat
431 // later. Conservatively assume that we double the number of operands when
432 // canonicalizing
433 SmallVector<Value, 8> concatOperands;
434 concatOperands.reserve(2 * op.getNumOperands());
435
436 int32_t maxNumOperands = 0;
437 if (auto targetEnvAttr = tosa::lookupTargetEnv(op))
438 maxNumOperands =
439 getTosaLevelFromEnum(targetEnvAttr.getLevel()).MAX_TENSOR_LIST_SIZE;
440
441 // Find all operands that are foldable concats
442 bool foundRewritableConcat = false;
443 for (Value operand : op.getOperands()) {
444 concatOperands.emplace_back(operand);
445
446 auto producer = operand.getDefiningOp<tosa::ConcatOp>();
447 if (!producer)
448 continue;
449
450 // Not rewritable if axes are not the same
451 if (op.getAxis() != producer.getAxis())
452 continue;
453
454 // Replace the original operand with all incoming operands
455 foundRewritableConcat = true;
456 concatOperands.pop_back();
457 llvm::append_range(concatOperands, producer->getOperands());
458 }
459
460 if (!foundRewritableConcat)
461 return rewriter.notifyMatchFailure(op,
462 "No rewritable concat operand found.");
463
464 if (maxNumOperands > 0 &&
465 concatOperands.size() > static_cast<size_t>(maxNumOperands))
466 return rewriter.notifyMatchFailure(
467 op, "Rewriting would exceed the maximum number of operands for the "
468 "target environment level.");
469
470 rewriter.replaceOpWithNewOp<tosa::ConcatOp>(
471 op, op.getType(), concatOperands, op.getAxisAttr());
472 return success();
473 }
474};
475
476void ConcatOp::getCanonicalizationPatterns(RewritePatternSet &results,
477 MLIRContext *context) {
479}
480
481LogicalResult SelectOp::canonicalize(SelectOp op, PatternRewriter &rewriter) {
482 auto notOp = op.getInput1().getDefiningOp<tosa::LogicalNotOp>();
483 if (!notOp)
484 return failure();
485 rewriter.modifyOpInPlace(op, [&]() {
486 op.getOperation()->setOperands(
487 {notOp.getInput1(), op.getOnFalse(), op.getOnTrue()});
488 });
489 return success();
490}
491
493 : public OpRewritePattern<tosa::TransposeOp> {
495
496 LogicalResult matchAndRewrite(tosa::TransposeOp transposeOp,
497 PatternRewriter &rewriter) const override {
498 // Input is also TransposeOp - transpose(transpose(A)).
499 auto innerTranspose =
500 transposeOp.getInput1().getDefiningOp<tosa::TransposeOp>();
501 if (!innerTranspose)
502 return rewriter.notifyMatchFailure(transposeOp,
503 "input must be transpose operation");
504
505 const llvm::ArrayRef<int32_t> transposePerms = transposeOp.getPerms();
506 const llvm::ArrayRef<int32_t> innerTransposePerms =
507 innerTranspose.getPerms();
508
509 if (transposePerms.size() != innerTransposePerms.size())
510 return rewriter.notifyMatchFailure(
511 transposeOp,
512 "transpose and inner transpose perms sizes must be equal");
513 if (transposePerms.empty())
514 return rewriter.notifyMatchFailure(
515 transposeOp, "transpose perms sizes must be positive");
516
517 // Consolidate transposes into one transpose.
518 SmallVector<int32_t> perms(transposePerms.size());
519 for (int i = 0, s = transposePerms.size(); i < s; ++i)
520 perms[i] = innerTransposePerms[transposePerms[i]];
521
522 rewriter.replaceOpWithNewOp<tosa::TransposeOp>(
523 transposeOp, transposeOp.getResult().getType(),
524 innerTranspose.getInput1(), rewriter.getDenseI32ArrayAttr(perms));
525
526 return success();
527 }
528};
529
530// Determines the case when tosa.transpose is a tosa.reshape operation.
531struct TransposeIsReshape : public OpRewritePattern<tosa::TransposeOp> {
533
534 LogicalResult matchAndRewrite(tosa::TransposeOp op,
535 PatternRewriter &rewriter) const override {
536 if (op.getInput1().getDefiningOp<tosa::TransposeOp>())
537 return rewriter.notifyMatchFailure(
538 op, "Src is from transpose, can compose transposes");
539
540 Value result = op.getResult();
541 for (Operation *subop : result.getUsers()) {
542 if (isa_and_nonnull<tosa::TransposeOp>(subop))
543 return rewriter.notifyMatchFailure(
544 op, "Dest is used by transpose, can compose transposes");
545 }
546
547 auto input = op.getInput1();
548 auto inputTy = llvm::cast<ShapedType>(input.getType());
549 if (!inputTy.hasRank())
550 return rewriter.notifyMatchFailure(op, "Unranked input.");
551
552 int64_t numDynDims = 0;
553 for (int i = 0; i < inputTy.getRank(); ++i)
554 if (inputTy.isDynamicDim(i))
555 numDynDims++;
556
557 if (numDynDims > 1)
558 return rewriter.notifyMatchFailure(op, "Has more than one dynamic dim.");
559
560 const llvm::ArrayRef<int32_t> permValues = op.getPerms();
561
562 SmallVector<int64_t> nonZeroPerms;
563 nonZeroPerms.reserve(permValues.size());
564 for (auto idx : permValues) {
565 auto sz = inputTy.getDimSize(idx);
566 if (sz != 1)
567 nonZeroPerms.push_back(idx);
568 }
569
570 for (int i = 1, s = nonZeroPerms.size(); i < s; ++i)
571 if (nonZeroPerms[i - 1] > nonZeroPerms[i])
572 return rewriter.notifyMatchFailure(op,
573 "Transpose changes memory layout.");
574
575 SmallVector<int64_t> newShape;
576 newShape.reserve(inputTy.getRank());
577 for (int i = 0, s = inputTy.getRank(); i < s; ++i)
578 newShape.push_back(inputTy.getDimSize(permValues[i]));
579
580 rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
581 op, op.getType(), op.getInput1(),
582 getTosaConstShape(rewriter, op.getLoc(), newShape));
583 return success();
584 }
585};
586
587void TransposeOp::getCanonicalizationPatterns(RewritePatternSet &results,
588 MLIRContext *context) {
589 results.add<ConsolidateTransposeOptimization, TransposeIsReshape>(context);
590}
591
592struct ClampIsNoOp : public OpRewritePattern<tosa::ClampOp> {
594
595 LogicalResult matchAndRewrite(tosa::ClampOp op,
596 PatternRewriter &rewriter) const override {
597 Value input = op.getInput();
598 auto inputType = llvm::cast<ShapedType>(op.getInput().getType());
599 auto inputElementType = inputType.getElementType();
600
601 if (isa<FloatType>(inputElementType)) {
602 // Unlike integer types, floating point types can represent infinity.
603 const auto minClamp =
604 llvm::cast<mlir::FloatAttr>(op.getMinValAttr()).getValue();
605 const auto maxClamp =
606 llvm::cast<mlir::FloatAttr>(op.getMaxValAttr()).getValue();
607 const bool isMin = minClamp.isNegInfinity();
608 const bool isMax = maxClamp.isInfinity();
609
610 if (isMin && isMax) {
611 rewriter.replaceOp(op, input);
612 return success();
613 }
614 return failure();
615 }
616
617 // i1 types are boolean in TOSA
618 const bool isBoolean = inputElementType.isInteger(1);
619 if (inputElementType.isUnsignedInteger() || isBoolean) {
620 const int64_t minClamp = llvm::cast<mlir::IntegerAttr>(op.getMinValAttr())
621 .getValue()
622 .getZExtValue();
623 const int64_t maxClamp = llvm::cast<mlir::IntegerAttr>(op.getMaxValAttr())
624 .getValue()
625 .getZExtValue();
626
627 const unsigned bitWidth = inputElementType.getIntOrFloatBitWidth();
628 const int64_t intMin = APInt::getMinValue(bitWidth).getZExtValue();
629 const int64_t intMax = APInt::getMaxValue(bitWidth).getZExtValue();
630
631 if (minClamp <= intMin && maxClamp >= intMax) {
632 rewriter.replaceOp(op, input);
633 return success();
634 }
635 return failure();
636 }
637
638 if (llvm::isa<IntegerType>(inputElementType)) {
639 const int64_t minClamp =
640 llvm::cast<mlir::IntegerAttr>(op.getMinValAttr()).getInt();
641 const int64_t maxClamp =
642 llvm::cast<mlir::IntegerAttr>(op.getMaxValAttr()).getInt();
643
644 const unsigned bitWidth = inputElementType.getIntOrFloatBitWidth();
645 const int64_t intMin = APInt::getSignedMinValue(bitWidth).getSExtValue();
646 const int64_t intMax = APInt::getSignedMaxValue(bitWidth).getSExtValue();
647
648 if (minClamp <= intMin && maxClamp >= intMax) {
649 rewriter.replaceOp(op, input);
650 return success();
651 }
652 return failure();
653 }
654
655 return failure();
656 }
657};
658
659// Attempts the following transformation:
660//
661// For integers a, b, a', and b' such that [a, b] ∩ [a', b'] ≠ ∅ and input
662// tensor X the following identity holds:
663//
664// CLAMP(CLAMP(X, a, b), a', b') = CLAMP(X, max(a, a'), min(b, b'))
665//
666// subject to the following valid NaN propagation semantics:
667// --------------------------------------------
668// | OUTER CLAMP | INNER CLAMP | RESULT MODE |
669// |-------------|--------------|-------------|
670// | PROPAGATE | PROPAGATE | PROPAGATE |
671// | PROPAGATE | IGNORE | IGNORE |
672// | IGNORE | PROPAGATE | INVALID |
673// | IGNORE | IGNORE | IGNORE |
674// |------------------------------------------|
675
676struct ClampClampOptimization : public OpRewritePattern<tosa::ClampOp> {
677 using OpRewritePattern<tosa::ClampOp>::OpRewritePattern;
678
679 // Helper structure to describe the range of a clamp operation.
680 template <typename T>
681 struct ClampRange {
682 ClampRange(const T &start, const T &end) : start(start), end(end) {}
685
686 // Helper function to determine if two Clamp ranges intersect.
687 bool intersects(const ClampRange<T> &otherRange) {
688 return start < otherRange.end && otherRange.start < end;
689 }
690 };
691
692 LogicalResult matchAndRewrite(tosa::ClampOp op,
693 PatternRewriter &rewriter) const override {
694 Value input = op.getInput();
695
696 // Check the input to the CLAMP op is itself a CLAMP.
697 auto clampOp = input.getDefiningOp<tosa::ClampOp>();
698 if (!clampOp)
699 return failure();
700
701 // Check we have a valid NaN propagation combination.
702 const auto opNanMode = op.getNanMode();
703 const auto clampNanMode = clampOp.getNanMode();
704 if (opNanMode == NanPropagationMode::IGNORE &&
705 clampNanMode == NanPropagationMode::PROPAGATE)
706 return failure();
707
708 auto maxValAttr = op.getMaxValAttr();
709 auto minValAttr = op.getMinValAttr();
710 auto clampOpMaxValAttr = clampOp.getMaxValAttr();
711 auto clampOpMinValAttr = clampOp.getMinValAttr();
712
713 auto inputEType = llvm::cast<ShapedType>(input.getType()).getElementType();
714 if (auto quantType =
715 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(inputEType)) {
716 inputEType = getStorageElementTypeFromQuantized(quantType);
717 }
718
719 Attribute newMinValAttr, newMaxValAttr;
720 if (mlir::isa<FloatType>(inputEType)) {
721 auto floatMaxValAttr = cast<mlir::FloatAttr>(maxValAttr);
722 auto floatMinValAttr = cast<mlir::FloatAttr>(minValAttr);
723 auto clampOpFloatMaxValAttr = cast<mlir::FloatAttr>(clampOpMaxValAttr);
724 auto clampOpFloatMinValAttr = cast<mlir::FloatAttr>(clampOpMinValAttr);
725
726 // Check we have intersecting ranges.
727 const auto opMinFloat = floatMinValAttr.getValue();
728 const auto opMaxFloat = floatMaxValAttr.getValue();
729 const auto clampOpMinFloat = clampOpFloatMinValAttr.getValue();
730 const auto clampOpMaxFloat = clampOpFloatMaxValAttr.getValue();
731 ClampRange<APFloat> opRangeFloatRange(opMinFloat, opMaxFloat);
732 ClampRange<APFloat> clampRangeFloatRange(clampOpMinFloat,
733 clampOpMaxFloat);
734 if (!opRangeFloatRange.intersects(clampRangeFloatRange))
735 return failure();
736
737 // Run the transformation.
738 auto newMinVal = std::max(opMinFloat, clampOpMinFloat);
739 auto newMaxVal = std::min(opMaxFloat, clampOpMaxFloat);
740 newMinValAttr = rewriter.getFloatAttr(inputEType, newMinVal);
741 newMaxValAttr = rewriter.getFloatAttr(inputEType, newMaxVal);
742 } else {
743 assert(mlir::isa<IntegerType>(inputEType));
744 auto intMaxValAttr = cast<mlir::IntegerAttr>(maxValAttr);
745 auto intMinValAttr = cast<mlir::IntegerAttr>(minValAttr);
746 auto clampOpIntMaxValAttr = cast<mlir::IntegerAttr>(clampOpMaxValAttr);
747 auto clampOpIntMinValAttr = cast<mlir::IntegerAttr>(clampOpMinValAttr);
748
749 if (inputEType.isUnsignedInteger()) {
750 // Check we have intersecting ranges.
751 const auto opMinInt = intMinValAttr.getUInt();
752 const auto opMaxInt = intMaxValAttr.getUInt();
753 const auto clampOpMinInt = clampOpIntMinValAttr.getUInt();
754 const auto clampOpMaxInt = clampOpIntMaxValAttr.getUInt();
755 ClampRange<std::uint64_t> opRangeIntRange(opMinInt, opMaxInt);
756 ClampRange<std::uint64_t> clampRangeIntRange(clampOpMinInt,
757 clampOpMaxInt);
758 if (!opRangeIntRange.intersects(clampRangeIntRange))
759 return failure();
760
761 // Run the transformation.
762 auto newMinVal = std::max(opMinInt, clampOpMinInt);
763 auto newMaxVal = std::min(opMaxInt, clampOpMaxInt);
764 newMinValAttr = rewriter.getIntegerAttr(inputEType, newMinVal);
765 newMaxValAttr = rewriter.getIntegerAttr(inputEType, newMaxVal);
766 } else {
767 // Check we have intersecting ranges.
768 const auto opMinInt = intMinValAttr.getInt();
769 const auto opMaxInt = intMaxValAttr.getInt();
770 const auto clampOpMinInt = clampOpIntMinValAttr.getInt();
771 const auto clampOpMaxInt = clampOpIntMaxValAttr.getInt();
772 ClampRange<std::int64_t> opRangeIntRange(opMinInt, opMaxInt);
773 ClampRange<std::int64_t> clampRangeIntRange(clampOpMinInt,
774 clampOpMaxInt);
775 if (!opRangeIntRange.intersects(clampRangeIntRange))
776 return failure();
777
778 // Run the transformation.
779 auto newMinVal = std::max(opMinInt, clampOpMinInt);
780 auto newMaxVal = std::min(opMaxInt, clampOpMaxInt);
781 newMinValAttr = rewriter.getIntegerAttr(inputEType, newMinVal);
782 newMaxValAttr = rewriter.getIntegerAttr(inputEType, newMaxVal);
783 }
784 }
785
786 auto newMode = (opNanMode != clampNanMode)
787 ? tosa::NanPropagationMode::IGNORE
788 : opNanMode;
789
790 auto newModeAttr =
791 NanPropagationModeAttr::get(rewriter.getContext(), newMode);
792
793 rewriter.replaceOpWithNewOp<tosa::ClampOp>(
794 op, op.getType(), clampOp.getInput(), newMinValAttr, newMaxValAttr,
795 newModeAttr);
796 return success();
797 }
798};
799
800void ClampOp::getCanonicalizationPatterns(RewritePatternSet &results,
801 MLIRContext *context) {
802 results.add<ClampIsNoOp>(context);
803 results.add<ClampClampOptimization>(context);
804}
805
806struct ConcatSliceOptimization : public OpRewritePattern<tosa::SliceOp> {
807 using OpRewritePattern<tosa::SliceOp>::OpRewritePattern;
808
809 LogicalResult matchAndRewrite(tosa::SliceOp sliceOp,
810 PatternRewriter &rewriter) const override {
811 Value sliceInput = sliceOp.getInput1();
812 auto concatOp = sliceInput.getDefiningOp<tosa::ConcatOp>();
813 if (!concatOp)
814 return rewriter.notifyMatchFailure(
815 sliceOp, "slice input must be concat operation");
816
817 OperandRange inputs = concatOp.getInput1();
818 auto concatType = dyn_cast<RankedTensorType>(concatOp.getType());
819 if (!concatType || !concatType.hasStaticShape())
820 return rewriter.notifyMatchFailure(
821 sliceOp, "slice input must be a static ranked tensor");
822 int32_t axis = concatOp.getAxis();
823
824 DenseElementsAttr startElems;
825 DenseElementsAttr sizeElems;
826
827 if (!matchPattern(sliceOp.getStart(), m_Constant(&startElems)))
828 return rewriter.notifyMatchFailure(
829 sliceOp, "start of slice must be a static ranked shape");
830
831 if (!matchPattern(sliceOp.getSize(), m_Constant(&sizeElems)))
832 return rewriter.notifyMatchFailure(
833 sliceOp, "size of slice must be a static ranked shape");
834
835 llvm::SmallVector<int64_t> sliceStarts =
836 llvm::to_vector(startElems.getValues<int64_t>());
837 llvm::SmallVector<int64_t> sliceSizes =
838 llvm::to_vector(sizeElems.getValues<int64_t>());
839
840 // Validate slice on the concatenated axis. Slicing along this
841 // axis should span only one of the inputs to the concatenate
842 // operation.
843 std::optional<Value> replaceWithSlice;
844 for (auto input : inputs) {
845 auto inputType = dyn_cast<RankedTensorType>(input.getType());
846 if (!inputType || !inputType.hasStaticShape())
847 return rewriter.notifyMatchFailure(
848 sliceOp, "concat input must be a static ranked tensor");
849
850 if (sliceStarts[axis] >= 0 && (sliceStarts[axis] + sliceSizes[axis]) <=
851 inputType.getDimSize(axis)) {
852 auto start_op =
853 getTosaConstShape(rewriter, sliceOp.getLoc(), sliceStarts);
854 auto size_op =
855 getTosaConstShape(rewriter, sliceOp.getLoc(), sliceSizes);
856 replaceWithSlice =
857 tosa::SliceOp::create(rewriter, sliceOp.getLoc(), sliceOp.getType(),
858 input, start_op, size_op)
859 .getResult();
860 break;
861 }
862 sliceStarts[axis] -= inputType.getDimSize(axis);
863 }
864
865 if (!replaceWithSlice)
866 return rewriter.notifyMatchFailure(
867 sliceOp, "corresponding concat input not found for slice");
868
869 rewriter.replaceOp(sliceOp, replaceWithSlice.value());
870 return success();
871 }
872};
873
874struct PadSliceOptimization : public OpRewritePattern<tosa::SliceOp> {
875 using OpRewritePattern<tosa::SliceOp>::OpRewritePattern;
876
877 LogicalResult matchAndRewrite(tosa::SliceOp sliceOp,
878 PatternRewriter &rewriter) const override {
879 Value sliceInput = sliceOp.getInput1();
880
881 // Check if producer is a PadOp
882 auto padOp = sliceInput.getDefiningOp<tosa::PadOp>();
883 if (!padOp)
884 return rewriter.notifyMatchFailure(sliceOp,
885 "slice input must be a pad operation");
886
887 // Check PadOp has a single consumer
888 if (!padOp->hasOneUse())
889 return rewriter.notifyMatchFailure(sliceOp,
890 "pad shall have a single consumer");
891
892 // Check input is statically ranked
893 auto inputTy = dyn_cast<RankedTensorType>(padOp.getInput1().getType());
894 auto padTy = dyn_cast<RankedTensorType>(padOp.getType());
895 if (!inputTy || !padTy || !inputTy.hasRank())
896 return rewriter.notifyMatchFailure(sliceOp,
897 "slice input must be a ranked tensor");
898
899 // Validate and extract tosa::PadOp padding
900 DenseIntElementsAttr paddingElems;
901 if (!matchPattern(padOp.getPadding(), m_Constant(&paddingElems))) {
902 return rewriter.notifyMatchFailure(
903 sliceOp,
904 "`padding` input specified on the tosa::PadOp must be constant.");
905 }
906 llvm::SmallVector<int64_t> padPaddings =
907 llvm::to_vector(paddingElems.getValues<int64_t>());
908
909 // Extract slice parameters
910 DenseElementsAttr startElems;
911 if (!matchPattern(sliceOp.getStart(), m_Constant(&startElems)))
912 return rewriter.notifyMatchFailure(
913 sliceOp, "start of slice must be a static ranked shape");
914 llvm::SmallVector<int64_t> sliceStarts =
915 llvm::to_vector(startElems.getValues<int64_t>());
916
917 DenseElementsAttr sizeElems;
918 if (!matchPattern(sliceOp.getSize(), m_Constant(&sizeElems)))
919 return rewriter.notifyMatchFailure(
920 sliceOp, "size of slice must be a static ranked shape");
921 llvm::SmallVector<int64_t> sliceSizes =
922 llvm::to_vector(sizeElems.getValues<int64_t>());
923
924 // Check if dynamic dimensions are sliced
925 const int64_t rank = inputTy.getRank();
926 if (llvm::any_of(llvm::seq<int64_t>(0, rank), [&](int64_t i) {
927 const bool isDimDynamic = inputTy.isDynamicDim(i);
928 const bool isDimSliced =
929 (sliceStarts[i] != 0) || (sliceSizes[i] != kInferableDimSize);
930
931 return isDimDynamic && isDimSliced;
932 })) {
933 return rewriter.notifyMatchFailure(
934 sliceOp, "axis that are sliced shall be statically known.");
935 }
936
937 // Update the parameters
938 llvm::SmallVector<int64_t> newSliceStarts(rank, 0);
939 llvm::SmallVector<int64_t> newPadPaddings(2 * rank, 0);
940 llvm::SmallVector<int64_t> newPadShape(rank, ShapedType::kDynamic);
941 bool updated = false;
942
943 for (int64_t i = 0; i < rank; ++i) {
944 const int64_t padLo = padPaddings[i * 2];
945 const int64_t padHi = padPaddings[i * 2 + 1];
946 const int64_t sliceStart = sliceStarts[i];
947 const int64_t sliceSize = sliceSizes[i];
948 const int64_t sliceEnd = sliceStart + sliceSize;
949
950 // If dimension is dynamic pass-through
951 if (inputTy.isDynamicDim(i)) {
952 newPadPaddings[i * 2] = padLo;
953 newPadPaddings[i * 2 + 1] = padHi;
954 newSliceStarts[i] = sliceStart;
955 continue;
956 }
957
958 // Handle static dimensions
959 const int64_t dimSize = inputTy.getShape()[i];
960 const int64_t dimTotal = padLo + dimSize + padHi;
961
962 // Check slice within bounds
963 if (sliceStart < 0 || sliceEnd > dimTotal)
964 return rewriter.notifyMatchFailure(sliceOp, "slice is out-of-bounds");
965
966 // Compute updated slice start parameter
967 const int64_t newSliceStart = std::max<int64_t>(sliceStart - padLo, 0);
968 newSliceStarts[i] = newSliceStart;
969 updated |= newSliceStart != sliceStart;
970
971 // Compute updated pad parameters
972 const int64_t newPadLo = std::max<int64_t>(padLo - sliceStart, 0);
973 const int64_t newPadHi =
974 std::max<int64_t>(sliceEnd - (padLo + dimSize), 0);
975 newPadPaddings[i * 2] = newPadLo;
976 newPadPaddings[i * 2 + 1] = newPadHi;
977 updated |= (newPadLo != padLo) || (newPadHi != padHi);
978
979 // Calculate new pad output shape
980 newPadShape[i] =
981 newPadPaddings[i * 2] + dimSize + newPadPaddings[i * 2 + 1];
982 }
983
984 // Check that we actually need to proceed with the rewrite
985 if (!updated)
986 return rewriter.notifyMatchFailure(
987 sliceOp, "terminate condition; nothing to rewrite");
988
989 // Create a PadOp with updated padding
990 auto newPaddingsOp =
991 getTosaConstShape(rewriter, sliceOp.getLoc(), newPadPaddings);
992 auto newPadTy =
993 RankedTensorType::get(newPadShape, inputTy.getElementType());
994 auto newPadOp = tosa::PadOp::create(rewriter, padOp.getLoc(), newPadTy,
995 padOp.getInput1(), newPaddingsOp,
996 padOp.getPadConst());
997
998 // Update SliceOp and point to new PadOp
999 auto newStartOp =
1000 getTosaConstShape(rewriter, sliceOp.getLoc(), newSliceStarts);
1001 rewriter.replaceOpWithNewOp<tosa::SliceOp>(sliceOp, sliceOp.getType(),
1002 newPadOp.getResult(), newStartOp,
1003 sliceOp.getSize());
1004
1005 return success();
1006 }
1007};
1008
1009// Update size operand of tosa.slice if size has dynamic dims but corresponding
1010// output dim is static
1012 : public OpRewritePattern<tosa::SliceOp> {
1013 using OpRewritePattern<tosa::SliceOp>::OpRewritePattern;
1014
1015 LogicalResult matchAndRewrite(tosa::SliceOp sliceOp,
1016 PatternRewriter &rewriter) const override {
1017 ShapedType resultType = cast<ShapedType>(sliceOp.getType());
1018 if (!resultType.hasRank())
1019 return rewriter.notifyMatchFailure(sliceOp, "output must be ranked");
1020
1021 ElementsAttr sizeElems;
1022 if (!matchPattern(sliceOp.getSize(), m_Constant(&sizeElems))) {
1023 return rewriter.notifyMatchFailure(
1024 sliceOp, "size of slice must be a static ranked shape");
1025 }
1026
1027 llvm::SmallVector<int64_t> sliceSizes =
1028 llvm::to_vector(sizeElems.getValues<int64_t>());
1029
1030 bool replaceSliceSize{false};
1031 // if size op has kInferableDimSize indicating dynamic shape but
1032 // corresponding dim on the output is statically known, update size to match
1033 // with known output dim shape
1034 for (const auto &[index, size] : llvm::enumerate(sliceSizes)) {
1035 if (size == kInferableDimSize && !resultType.isDynamicDim(index)) {
1036 sliceSizes[index] = resultType.getDimSize(index);
1037 replaceSliceSize = true;
1038 }
1039 }
1040
1041 if (!replaceSliceSize) {
1042 return rewriter.notifyMatchFailure(
1043 sliceOp, "no dimension of size of slice is dynamic that resolves "
1044 "to static output shape");
1045 }
1046
1047 auto size_op = getTosaConstShape(rewriter, sliceOp.getLoc(), sliceSizes);
1048 auto newSliceOp =
1049 tosa::SliceOp::create(rewriter, sliceOp.getLoc(), sliceOp.getType(),
1050 sliceOp.getInput1(), sliceOp.getStart(), size_op);
1051
1052 rewriter.replaceOp(sliceOp, newSliceOp.getResult());
1053 return success();
1054 }
1055};
1056
1057void SliceOp::getCanonicalizationPatterns(RewritePatternSet &results,
1058 MLIRContext *context) {
1059 results.add<ConcatSliceOptimization, PadSliceOptimization,
1060 SliceDynamicSizeCanonicalization>(context);
1061}
1062
1064 using OpRewritePattern<tosa::CastOp>::OpRewritePattern;
1065
1066 LogicalResult matchAndRewrite(tosa::CastOp castOp,
1067 PatternRewriter &rewriter) const override {
1068 const Value castInput = castOp.getInput();
1069 auto innerCastOp = castInput.getDefiningOp<tosa::CastOp>();
1070 if (!innerCastOp)
1071 return rewriter.notifyMatchFailure(castOp,
1072 "input must be cast operation");
1073
1074 const Value innerCastInput = innerCastOp.getInput();
1075
1076 const ShapedType innerInputType =
1077 llvm::cast<ShapedType>(innerCastInput.getType());
1078 const ShapedType innerOutputType =
1079 llvm::cast<ShapedType>(innerCastOp.getType());
1080 const ShapedType outerOutputType = llvm::cast<ShapedType>(castOp.getType());
1081
1082 const Type innerInputElemType = innerInputType.getElementType();
1083 const Type innerOutputElemType = innerOutputType.getElementType();
1084 const Type outerOutputElemType = outerOutputType.getElementType();
1085
1086 const SmallVector<Type, 3> types = {innerInputElemType, innerOutputElemType,
1087 outerOutputElemType};
1088
1089 if (llvm::any_of(types, [](const Type type) {
1090 // Support a specific set of floating point types since we need to be
1091 // careful in not introducing unsupported type combinations
1092 return !(type.isInteger() ||
1093 llvm::isa<Float8E4M3FNType, Float8E5M2Type, BFloat16Type,
1094 Float16Type, Float32Type>(type));
1095 }))
1096 return rewriter.notifyMatchFailure(
1097 castOp, "only integer and f32, f16, bf16, f8E4M3FN, f8E5M2 types are "
1098 "supported");
1099
1100 if (llvm::isa<Float8E5M2Type>(innerInputElemType) &&
1101 llvm::isa<Float8E4M3FNType>(outerOutputElemType)) {
1102 return rewriter.notifyMatchFailure(
1103 castOp, "avoid introducing f8E5M2 -> f8E4M3FN casts which are not "
1104 "legal in TOSA");
1105 }
1106
1107 if (llvm::isa<Float8E4M3FNType>(innerInputElemType) &&
1108 llvm::isa<Float8E5M2Type>(outerOutputElemType)) {
1109 return rewriter.notifyMatchFailure(
1110 castOp, "avoid introducing f8E4M3FN -> f8E5M2 casts which are not "
1111 "legal in TOSA");
1112 }
1113
1114 if (llvm::isa<Float8E5M2Type, Float8E4M3FNType>(innerInputElemType) &&
1115 outerOutputElemType.isInteger()) {
1116 return rewriter.notifyMatchFailure(
1117 castOp, "avoid introducing fp8 -> integer casts which are not "
1118 "legal in TOSA");
1119 }
1120
1121 if (innerInputElemType.isInteger() &&
1122 llvm::isa<Float8E5M2Type, Float8E4M3FNType>(outerOutputElemType)) {
1123 return rewriter.notifyMatchFailure(
1124 castOp, "avoid introducing integer -> fp8 casts which are not "
1125 "legal in TOSA");
1126 }
1127
1128 if (llvm::isa<Float16Type>(innerInputElemType) &&
1129 llvm::isa<BFloat16Type>(outerOutputElemType)) {
1130 return rewriter.notifyMatchFailure(
1131 castOp, "avoid introducing fp16 -> bf16 casts which are not "
1132 "legal in TOSA");
1133 }
1134
1135 if (llvm::isa<BFloat16Type>(innerInputElemType) &&
1136 llvm::isa<Float16Type>(outerOutputElemType)) {
1137 return rewriter.notifyMatchFailure(
1138 castOp, "avoid introducing bf16 -> fp16 casts which are not "
1139 "legal in TOSA");
1140 }
1141
1142 const auto isIntegerOneOfWidth = [](Type type, size_t bitwidth1,
1143 size_t bitwidth2) {
1144 return type.isInteger(bitwidth1) || type.isInteger(bitwidth2);
1145 };
1146
1147 if (isIntegerOneOfWidth(innerInputElemType, 8, 16) &&
1148 outerOutputElemType.isInteger(64)) {
1149 return rewriter.notifyMatchFailure(
1150 castOp, "avoid introducing i8/i16 -> i64 casts which are not "
1151 "legal in TOSA");
1152 }
1153
1154 if (isIntegerOneOfWidth(innerInputElemType, 1, 64) &&
1155 !outerOutputElemType.isInteger()) {
1156 return rewriter.notifyMatchFailure(
1157 castOp, "avoid introducing bool/i64 to float casts which are not "
1158 "supported in all versions of TOSA");
1159 }
1160
1161 if (!innerInputElemType.isInteger() &&
1162 isIntegerOneOfWidth(outerOutputElemType, 1, 64)) {
1163 return rewriter.notifyMatchFailure(
1164 castOp, "avoid introducing float to bool/i64 casts which are not "
1165 "supported in all versions of TOSA");
1166 }
1167
1168 // Check that the cast we're considering for removal is non-narrowing
1169 if (isNarrowingCast(innerInputType, innerOutputType))
1170 return rewriter.notifyMatchFailure(castOp,
1171 "inner cast operation is narrowing");
1172
1173 rewriter.replaceOpWithNewOp<tosa::CastOp>(castOp, outerOutputType,
1174 innerCastInput);
1175
1176 return success();
1177 }
1178
1179 bool supportsNaN(const llvm::fltSemantics &semantics) const {
1180 return semantics.nonFiniteBehavior !=
1181 llvm::fltNonfiniteBehavior::FiniteOnly;
1182 }
1183
1184 bool supportsInf(const llvm::fltSemantics &semantics) const {
1185 return semantics.nonFiniteBehavior == llvm::fltNonfiniteBehavior::IEEE754;
1186 }
1187
1188 bool isNarrowingCast(const ShapedType inType,
1189 const ShapedType outType) const {
1190
1191 if (inType.getElementType().isInteger() &&
1192 outType.getElementType().isInteger()) {
1193
1194 const auto inTypeSignedness =
1195 cast<IntegerType>(inType.getElementType()).getSignedness();
1196 const auto outTypeSignedness =
1197 cast<IntegerType>(outType.getElementType()).getSignedness();
1198
1199 return (inTypeSignedness != outTypeSignedness ||
1200 inType.getElementTypeBitWidth() >
1201 outType.getElementTypeBitWidth());
1202 }
1203
1204 if (inType.getElementType().isFloat() &&
1205 outType.getElementType().isFloat()) {
1206
1207 FloatType inElemTy = cast<FloatType>(inType.getElementType());
1208 FloatType outElemTy = cast<FloatType>(outType.getElementType());
1209 llvm::fltSemantics inTypeSemantics = inElemTy.getFloatSemantics();
1210 llvm::fltSemantics outTypeSemantics = outElemTy.getFloatSemantics();
1211
1212 // If the list of supported types needs to be updated in the future, the
1213 // check down below will need to be revised, for example to account for
1214 // unsigned floating point types, or types that use negative zero as the
1215 // representation for NaN.
1216 [[maybe_unused]] const auto isSupported = [](Type elemType) {
1217 return llvm::isa<Float8E4M3FNType, Float8E5M2Type, BFloat16Type,
1218 Float16Type, Float32Type>(elemType);
1219 };
1220
1221 assert(isSupported(inElemTy) &&
1222 "unsupported input element type in isNarrowingCast");
1223 assert(isSupported(outElemTy) &&
1224 "unsupported output element type in isNarrowingCast");
1225
1226 return (
1227 inTypeSemantics.maxExponent > outTypeSemantics.maxExponent ||
1228 inTypeSemantics.minExponent < outTypeSemantics.minExponent ||
1229 inTypeSemantics.precision > outTypeSemantics.precision ||
1230 (supportsNaN(inTypeSemantics) && !supportsNaN(outTypeSemantics)) ||
1231 (supportsInf(inTypeSemantics) && !supportsInf(outTypeSemantics)));
1232 }
1233
1234 // While some cases of int -> float casts can be non-narrowing, consider
1235 // them narrowing for the purposes of this optimization
1236 return true;
1237 }
1238};
1239
1241 : public OpRewritePattern<tosa::CastOp> {
1242 using OpRewritePattern<tosa::CastOp>::OpRewritePattern;
1243
1244 LogicalResult matchAndRewrite(tosa::CastOp castOp,
1245 PatternRewriter &rewriter) const override {
1246 const Value outerInput = castOp.getInput();
1247 auto innerCastOp = outerInput.getDefiningOp<tosa::CastOp>();
1248 if (!innerCastOp)
1249 return rewriter.notifyMatchFailure(castOp,
1250 "input must be a cast operation");
1251
1252 const Value innerInput = innerCastOp.getInput();
1253 const auto innerInputTy = llvm::cast<ShapedType>(innerInput.getType());
1254 const auto innerOutputTy = llvm::cast<ShapedType>(innerCastOp.getType());
1255 const auto outerOutputTy = llvm::cast<ShapedType>(castOp.getType());
1256
1257 if (!llvm::isa<tosa::BlockScaledType>(innerInputTy.getElementType()))
1258 return rewriter.notifyMatchFailure(
1259 castOp, "inner cast input must have block scaled element type");
1260
1261 if (innerInputTy != outerOutputTy)
1262 return rewriter.notifyMatchFailure(
1263 castOp, "inner input type must match outer output type");
1264
1265 const Type innerOutputElemType = innerOutputTy.getElementType();
1266 const bool isLosslessCast = isa<Float32Type>(innerOutputElemType);
1267 if (!isLosslessCast)
1268 return rewriter.notifyMatchFailure(
1269 castOp, "avoid cancelling casts that should be lossy");
1270
1271 rewriter.replaceOp(castOp, innerInput);
1272
1273 return success();
1274 }
1275};
1276
1277void CastOp::getCanonicalizationPatterns(RewritePatternSet &results,
1278 MLIRContext *context) {
1279 results.add<NonNarrowingCastsOptimization,
1280 CancellingBlockScaledCastsOptimization>(context);
1281}
1282
1284 : public OpRewritePattern<tosa::CastToBlockScaledOp> {
1285 using OpRewritePattern<tosa::CastToBlockScaledOp>::OpRewritePattern;
1286
1287 LogicalResult matchAndRewrite(tosa::CastToBlockScaledOp castToBlockScaledOp,
1288 PatternRewriter &rewriter) const override {
1289 const Value castToBlockScaledInput = castToBlockScaledOp.getInputData();
1290 auto castFromBlockScaledOp =
1291 castToBlockScaledInput.getDefiningOp<tosa::CastFromBlockScaledOp>();
1292 if (!castFromBlockScaledOp)
1293 return rewriter.notifyMatchFailure(
1294 castToBlockScaledOp,
1295 "input must be cast_from_block_scaled operation");
1296
1297 const Value innerData = castFromBlockScaledOp.getInputData();
1298 const Value innerScale = castFromBlockScaledOp.getInputScale();
1299 const auto innerDataTy = llvm::cast<ShapedType>(innerData.getType());
1300 const auto innerScaleTy = llvm::cast<ShapedType>(innerScale.getType());
1301
1302 const Value outerData = castToBlockScaledOp.getOutputData();
1303 const Value outerScale = castToBlockScaledOp.getOutputScale();
1304 const auto outerDataTy = llvm::cast<ShapedType>(outerData.getType());
1305 const auto outerScaleTy = llvm::cast<ShapedType>(outerScale.getType());
1306
1307 if (innerDataTy != outerDataTy || innerScaleTy != outerScaleTy) {
1308 return rewriter.notifyMatchFailure(
1309 castToBlockScaledOp,
1310 "inputs types to cast_from_block_scaled operation must match output "
1311 "types to cast_to_block_scaled");
1312 }
1313
1314 if (castFromBlockScaledOp.getBlockSize() !=
1315 castToBlockScaledOp.getBlockSize()) {
1316 return rewriter.notifyMatchFailure(
1317 castToBlockScaledOp, "block sizes for cast_from_block_scaled and "
1318 "cast_to_block_scaled must match");
1319 }
1320
1321 rewriter.replaceOp(castToBlockScaledOp, {innerData, innerScale});
1322
1323 return success();
1324 }
1325};
1326
1327void CastToBlockScaledOp::getCanonicalizationPatterns(
1328 RewritePatternSet &results, MLIRContext *context) {
1329 results.add<CancellingCastToFromBlockScaledOptimization>(context);
1330}
1331
1332struct RowGatherToGather : public OpRewritePattern<tosa::RowGatherOp> {
1333 using OpRewritePattern<tosa::RowGatherOp>::OpRewritePattern;
1334
1335 LogicalResult matchAndRewrite(tosa::RowGatherOp op,
1336 PatternRewriter &rewriter) const override {
1337 const FailureOr<int32_t> rowCount =
1339 if (failed(rowCount) || rowCount.value() != 1)
1340 return failure();
1341
1342 rewriter.replaceOpWithNewOp<tosa::GatherOp>(
1343 op, op.getOutput().getType(), op.getValues(), op.getIndices());
1344 return success();
1345 }
1346};
1347
1348void RowGatherOp::getCanonicalizationPatterns(RewritePatternSet &results,
1349 MLIRContext *context) {
1350 results.add<RowGatherToGather>(context);
1351}
1352
1353//===----------------------------------------------------------------------===//
1354// Operator Folders.
1355//===----------------------------------------------------------------------===//
1356
1357template <typename Folder>
1358static DenseElementsAttr
1360 bool foldDenseValues = false) {
1361 if (!lhs || !rhs)
1362 return {};
1363
1364 if (!returnTy.hasRank() || !returnTy.hasStaticShape())
1365 return {};
1366
1367 const auto lETy = llvm::cast<ShapedType>(lhs.getType()).getElementType();
1368 const auto rETy = llvm::cast<ShapedType>(rhs.getType()).getElementType();
1369 if (lETy != rETy)
1370 return {};
1371
1372 if (lhs.isSplat() && rhs.isSplat()) {
1373 if (isa<FloatType>(lETy)) {
1374 const APFloat l = lhs.getSplatValue<APFloat>();
1375 const APFloat r = rhs.getSplatValue<APFloat>();
1376 const auto maybeResult = Folder::fold(l, r);
1377 if (failed(maybeResult))
1378 return {};
1379 return DenseElementsAttr::get(returnTy, maybeResult.value());
1380 }
1381
1382 if (const auto lIntTy = llvm::dyn_cast<IntegerType>(lETy)) {
1383 const APInt l = lhs.getSplatValue<APInt>();
1384 const APInt r = rhs.getSplatValue<APInt>();
1385 const auto maybeResult = Folder::fold(l, r, lIntTy.isUnsigned());
1386 if (failed(maybeResult))
1387 return {};
1388 return DenseElementsAttr::get(returnTy, maybeResult.value());
1389 }
1390 }
1391
1392 if (foldDenseValues) {
1393 assert(lETy.isIntOrIndex() &&
1394 "Only integer types are currently supported.");
1395 SmallVector<APInt> resultValues;
1396 for (auto [l, r] :
1397 llvm::zip(lhs.getValues<APInt>(), rhs.getValues<APInt>())) {
1398 const auto maybeResult = Folder::fold(l, r, false);
1399 if (failed(maybeResult))
1400 return {};
1401 resultValues.push_back(maybeResult.value());
1402 }
1403 return DenseElementsAttr::get(returnTy, resultValues);
1404 }
1405
1406 return {};
1407}
1408
1409template <typename Folder>
1410static DenseElementsAttr unaryFolder(DenseElementsAttr val, ShapedType returnTy,
1411 bool foldDenseValues = false) {
1412 if (!val)
1413 return {};
1414
1415 if (!returnTy.hasRank() || !returnTy.hasStaticShape())
1416 return {};
1417
1418 const auto vETy = llvm::cast<ShapedType>(val.getType()).getElementType();
1419
1420 if (val.isSplat()) {
1421 if (const auto vIntTy = llvm::dyn_cast<IntegerType>(vETy)) {
1422 const APInt v = val.getSplatValue<APInt>();
1423 const auto maybeResult = Folder::fold(v, vIntTy.isUnsigned());
1424 if (failed(maybeResult))
1425 return {};
1426 return DenseElementsAttr::get(returnTy, maybeResult.value());
1427 }
1428 }
1429
1430 if (foldDenseValues) {
1431 mlir::Type elemTy = val.getElementType();
1432 if (elemTy.isIntOrIndex()) {
1433 SmallVector<APInt> resultValues;
1434 for (auto const &v : val.getValues<APInt>()) {
1435 const auto maybeResult = Folder::fold(v, false);
1436 if (failed(maybeResult))
1437 return {};
1438 resultValues.push_back(maybeResult.value());
1439 }
1440 return DenseElementsAttr::get(returnTy, resultValues);
1441 }
1442 }
1443
1444 // Folding arbitrarily sized tensor operations is not supported
1445 return {};
1446}
1447
1448static FailureOr<int64_t> getSingleI64From1ElementTensor(Value v) {
1449 DenseIntElementsAttr dense{};
1450 if (!matchPattern(v, m_Constant(&dense)))
1451 return failure();
1452
1453 assert(dense.isSplat());
1454 APInt a = dense.getSplatValue<APInt>();
1455 return a.getSExtValue();
1456}
1457
1459 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1460 const bool isUnsigned) {
1461 bool overflow;
1462 const APInt result =
1463 isUnsigned ? lhs.uadd_ov(rhs, overflow) : lhs.sadd_ov(rhs, overflow);
1464 if (overflow)
1465 return failure();
1466 return result;
1467 }
1468
1469 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1470 return lhs + rhs;
1471 }
1472};
1473
1475 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1476 const bool isUnsigned) {
1477 bool overflow;
1478 const APInt result =
1479 isUnsigned ? lhs.usub_ov(rhs, overflow) : lhs.ssub_ov(rhs, overflow);
1480 if (overflow)
1481 return failure();
1482 return result;
1483 }
1484
1485 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1486 return lhs - rhs;
1487 }
1488};
1489
1491 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1492 const bool isUnsigned) {
1493
1494 const unsigned originalWidth = lhs.getBitWidth();
1495
1496 // Check same type
1497 if (lhs.getBitWidth() != rhs.getBitWidth()) {
1498 return failure();
1499 }
1500
1501 // If either is `0`
1502 if (lhs == 0 || rhs == 0)
1503 return APInt::getZero(originalWidth);
1504
1505 bool overflow = false;
1506 APInt const result =
1507 isUnsigned ? lhs.umul_ov(rhs, overflow) : lhs.smul_ov(rhs, overflow);
1508
1509 if (overflow)
1510 return failure();
1511
1512 return result.trunc(originalWidth);
1513 }
1514
1515 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1516 return lhs * rhs;
1517 }
1518};
1519
1520static bool signsDiffer(const APInt &a, const APInt &b) {
1521 return a.isNegative() != b.isNegative();
1522}
1523
1524template <bool Ceil>
1526 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1527 bool isUnsigned) {
1528 if (lhs.getBitWidth() != rhs.getBitWidth())
1529 return failure();
1530 if (rhs.isZero())
1531 return failure();
1532
1533 if (isUnsigned) {
1534 APInt q{};
1535 APInt r{};
1536 APInt::udivrem(lhs, rhs, q, r);
1537 if (!r.isZero() && Ceil) {
1538 return q + 1;
1539 }
1540 return q;
1541 }
1542
1543 // Signed: start from trunc-toward-zero, then adjust to ceil.
1544 bool overflow{false};
1545 APInt const q = lhs.sdiv_ov(rhs, overflow);
1546 if (overflow)
1547 return failure();
1548 APInt const r = lhs.srem(rhs);
1549
1550 if (Ceil && !r.isZero() && !signsDiffer(lhs, rhs)) {
1551 // Same sign => exact quotient is positive; trunc is below ceil =>
1552 // increment q.
1553 return q + 1;
1554 }
1555 return q;
1556 }
1557
1558 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1559 return lhs / rhs;
1560 }
1561};
1562
1564 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1565 bool isUnsigned) {
1566 if (lhs.getBitWidth() != rhs.getBitWidth())
1567 return failure();
1568 if (lhs.isNegative() || (!rhs.isStrictlyPositive()))
1569 return failure();
1570
1571 if (isUnsigned) {
1572 return lhs.urem(rhs);
1573 }
1574
1575 return lhs.srem(rhs);
1576 }
1577
1578 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1579 auto t = lhs;
1580 auto const r = t.mod(rhs);
1581 if (llvm::APFloatBase::opStatus::opOK == r) {
1582 return t;
1583 }
1584 return failure();
1585 }
1586};
1587
1589 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1590 bool isUnsigned) {
1591 if (lhs.getBitWidth() != rhs.getBitWidth())
1592 return failure();
1593 return lhs.getSExtValue() >= rhs.getSExtValue() ? lhs : rhs;
1594 }
1595
1596 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1597 return lhs >= rhs ? lhs : rhs;
1598 }
1599};
1600
1602 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1603 bool isUnsigned) {
1604 if (lhs.getBitWidth() != rhs.getBitWidth())
1605 return failure();
1606 return lhs.getSExtValue() <= rhs.getSExtValue() ? lhs : rhs;
1607 }
1608
1609 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1610 return lhs <= rhs ? lhs : rhs;
1611 }
1612};
1613
1615 static FailureOr<APInt> fold(const APInt &value, bool isUnsigned) {
1616 auto const numBits = value.getBitWidth();
1617 if (isUnsigned) {
1618 auto const zextv = value.getZExtValue();
1619 if (zextv >= numBits)
1620 return failure();
1621 return APInt::getOneBitSet(numBits, zextv);
1622 }
1623 auto const sextv = value.getSExtValue();
1624 if (sextv < 0 || sextv >= numBits || (value.isNegative()))
1625 return failure();
1626 return APInt::getOneBitSet(numBits, sextv);
1627 }
1628};
1629
1630// The specification requires shape div operations to have non-negative lhs and
1631// strictly positive rhs so we can only fold when these conditions are met.
1632template <bool Ceil>
1634 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1635 bool isUnsigned) {
1636 assert(!isUnsigned &&
1637 "unsigned values are not supported for shape div folders");
1638 if (lhs.isNegative() || !rhs.isStrictlyPositive())
1639 return failure();
1640 return DivFoldAdaptor<Ceil>::fold(lhs, rhs, isUnsigned);
1641 }
1642
1643 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1644 return failure();
1645 }
1646};
1647
1649 static FailureOr<APInt> fold(const APInt &value, bool isUnsigned) {
1650 if (!value.isStrictlyPositive())
1651 return failure();
1652 return APInt(/*numBits=*/value.getBitWidth(), value.ceilLogBase2());
1653 }
1654};
1655
1657 static FailureOr<APInt> fold(const APInt &value, bool isUnsigned) {
1658 if (!value.isStrictlyPositive())
1659 return failure();
1660 return APInt(/*numBits=*/value.getBitWidth(), value.logBase2());
1661 }
1662};
1663
1665 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1666 const bool isUnsigned) {
1667 return isUnsigned ? APInt(1, lhs.ugt(rhs)) : APInt(1, lhs.sgt(rhs));
1668 }
1669
1670 static FailureOr<APInt> fold(const APFloat &lhs, const APFloat &rhs) {
1671 return APInt(1, lhs > rhs);
1672 }
1673};
1674
1676 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1677 const bool isUnsigned) {
1678 return isUnsigned ? APInt(1, lhs.uge(rhs)) : APInt(1, lhs.sge(rhs));
1679 }
1680
1681 static FailureOr<APInt> fold(const APFloat &lhs, const APFloat &rhs) {
1682 return APInt(1, lhs >= rhs);
1683 }
1684};
1685
1687 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1688 const bool isUnsigned) {
1689 return APInt(1, lhs == rhs);
1690 }
1691
1692 static FailureOr<APInt> fold(const APFloat &lhs, const APFloat &rhs) {
1693 return APInt(1, lhs == rhs);
1694 }
1695};
1696
1697static bool isSplatZero(Type elemType, DenseElementsAttr val) {
1698 if (llvm::isa<FloatType>(elemType))
1699 return val && val.isSplat() && val.getSplatValue<APFloat>().isZero();
1700 if (llvm::isa<IntegerType>(elemType))
1701 return val && val.isSplat() && val.getSplatValue<APInt>().isZero();
1702 return false;
1703}
1704
1705static bool isSplatOne(Type elemType, DenseElementsAttr val, int64_t shift) {
1706 if (llvm::isa<FloatType>(elemType))
1707 return val && val.isSplat() &&
1708 val.getSplatValue<APFloat>().isExactlyValue(1.0);
1709 if (llvm::isa<IntegerType>(elemType)) {
1710 const int64_t shifted = 1LL << shift;
1711 return val && val.isSplat() &&
1712 val.getSplatValue<APInt>().getSExtValue() == shifted;
1713 }
1714 return false;
1715}
1716
1717OpFoldResult AddOp::fold(FoldAdaptor adaptor) {
1718 auto lhsTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
1719 auto rhsTy = llvm::dyn_cast<RankedTensorType>(getInput2().getType());
1720 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1721 if (!lhsTy || !rhsTy || !resultTy)
1722 return {};
1723
1724 // Cannot create an ElementsAttr from non-int/float/index types
1725 if (!lhsTy.getElementType().isIntOrIndexOrFloat() ||
1726 !rhsTy.getElementType().isIntOrIndexOrFloat())
1727 return {};
1728
1729 auto resultETy = resultTy.getElementType();
1730 auto lhsAttr =
1731 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1732 auto rhsAttr =
1733 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1734
1735 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1736 lhsTy.getShape(), rhsTy.getShape());
1737 if (isBroadcastable && lhsTy == resultTy && isSplatZero(resultETy, rhsAttr))
1738 return getInput1();
1739 if (isBroadcastable && rhsTy == resultTy && isSplatZero(resultETy, lhsAttr))
1740 return getInput2();
1741
1742 if (!lhsAttr || !rhsAttr)
1743 return {};
1744
1745 return binaryFolder<AddFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1746}
1747
1748OpFoldResult ArgMaxOp::fold(FoldAdaptor adaptor) {
1749 auto inputTy = llvm::dyn_cast<RankedTensorType>(getInput().getType());
1750 auto outputTy = llvm::dyn_cast<RankedTensorType>(getType());
1751 if (!inputTy || !outputTy || !inputTy.hasStaticShape() ||
1752 !outputTy.hasStaticShape())
1753 return {};
1754
1755 const Type outputElementTy = getElementTypeOrSelf(outputTy);
1756 if (inputTy.getDimSize(getAxis()) == 1 && outputElementTy.isInteger()) {
1757 const auto outputElemIntTy = cast<IntegerType>(outputElementTy);
1758 const APInt zero = APInt::getZero(outputElemIntTy.getWidth());
1759 return DenseElementsAttr::get(outputTy, zero);
1760 }
1761
1762 return {};
1763}
1764
1765OpFoldResult IntDivOp::fold(FoldAdaptor adaptor) {
1766 auto lhsTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
1767 auto rhsTy = llvm::dyn_cast<RankedTensorType>(getInput2().getType());
1768 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1769 if (!lhsTy || !rhsTy || !resultTy)
1770 return {};
1771 if (lhsTy.getElementType() != rhsTy.getElementType())
1772 return {};
1773
1774 // IntDivOp inputs must be integer type, no need to check for quantized
1775 // type
1776 auto resultETy = resultTy.getElementType();
1777 auto lhsAttr =
1778 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1779 auto rhsAttr =
1780 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1781 if (lhsAttr && lhsAttr.isSplat() && rhsAttr && rhsAttr.isSplat()) {
1782 if (llvm::isa<IntegerType>(resultETy) && resultTy.hasStaticShape() &&
1783 lhsAttr.getSplatValue<APInt>().isZero() &&
1784 !rhsAttr.getSplatValue<APInt>().isZero()) {
1785 return lhsAttr.resizeSplat(resultTy);
1786 }
1787 }
1788
1789 if (rhsAttr && rhsAttr.isSplat()) {
1790 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1791 lhsTy.getShape(), rhsTy.getShape());
1792 if (isBroadcastable && lhsTy == resultTy &&
1793 llvm::isa<IntegerType>(resultETy) &&
1794 rhsAttr.getSplatValue<APInt>().isOne())
1795 return getInput1();
1796 }
1797
1798 if (rhsAttr && lhsAttr && rhsAttr.isSplat() && lhsAttr.isSplat() &&
1799 llvm::isa<IntegerType>(resultETy)) {
1800 APInt l = lhsAttr.getSplatValue<APInt>();
1801 APInt r = rhsAttr.getSplatValue<APInt>();
1802 if (!r.isZero()) {
1803 auto intTy = dyn_cast<mlir::IntegerType>(resultETy);
1804 auto const result =
1805 DivFoldAdaptor</*Ceil*/ false>::fold(l, r, intTy.isUnsigned());
1806 if (failed(result))
1807 return {};
1808 return DenseElementsAttr::get(resultTy, result.value());
1809 }
1810 }
1811
1812 return {};
1813}
1814
1815namespace {
1816// calculate lhs * rhs >> shift according to TOSA Spec
1817// return nullopt if result is not in range of int32_t when shift > 0
1818std::optional<APInt> mulInt(APInt lhs, APInt rhs, int32_t shift,
1819 unsigned bitwidth) {
1820 bool overflow = false;
1821 APInt result = lhs.sext(64).smul_ov(rhs.sext(64), overflow);
1822
1823 if (overflow)
1824 return std::nullopt;
1825
1826 if (shift > 0) {
1827 auto round = APInt(64, 1) << (shift - 1);
1828 result += round;
1829 result.ashrInPlace(shift);
1830 // REQUIRE(product >= minimum_s<i32_t>() && product <=
1831 // maximum_s<i32_t>())
1832 if (!(result.getSExtValue() >= INT32_MIN &&
1833 result.getSExtValue() <= INT32_MAX)) {
1834 // REQUIRE failed
1835 return std::nullopt;
1836 }
1837 }
1838
1839 return result.trunc(bitwidth);
1840}
1841
1842DenseElementsAttr mulBinaryFolder(DenseElementsAttr lhs, DenseElementsAttr rhs,
1843 RankedTensorType ty, int32_t shift) {
1844 if (rhs && lhs && rhs.isSplat() && lhs.isSplat()) {
1845 if (llvm::isa<IntegerType>(ty.getElementType())) {
1846 APInt l = lhs.getSplatValue<APInt>();
1847 APInt r = rhs.getSplatValue<APInt>();
1848
1849 if (shift == 0) {
1850 return DenseElementsAttr::get(ty, l * r);
1851 }
1852
1853 auto bitwidth = ty.getElementType().getIntOrFloatBitWidth();
1854 const std::optional<APInt> result = mulInt(l, r, shift, bitwidth);
1855 if (!result)
1856 return {};
1857 return DenseElementsAttr::get(ty, result.value());
1858 }
1859
1860 if (llvm::isa<FloatType>(ty.getElementType())) {
1861 APFloat l = lhs.getSplatValue<APFloat>();
1862 APFloat r = rhs.getSplatValue<APFloat>();
1863 APFloat result = l * r;
1864 return DenseElementsAttr::get(ty, result);
1865 }
1866 }
1867
1868 return {};
1869}
1870} // namespace
1871
1872OpFoldResult MulOp::fold(FoldAdaptor adaptor) {
1873 auto lhs = getInput1();
1874 auto rhs = getInput2();
1875 auto lhsTy = llvm::dyn_cast<RankedTensorType>(lhs.getType());
1876 auto rhsTy = llvm::dyn_cast<RankedTensorType>(rhs.getType());
1877 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1878 if (!lhsTy || !rhsTy || !resultTy)
1879 return {};
1880
1881 auto resultETy = resultTy.getElementType();
1882 auto lhsAttr =
1883 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1884 auto rhsAttr =
1885 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1886
1887 // Result right shift on i32_t data type only. For simplification,
1888 // synthesize a zero shift for other data type.
1889 int32_t shift = 0;
1890 if (resultETy.isInteger(32)) {
1891 ElementsAttr shift_elem;
1892 if (getShift().getImpl()) {
1893 if (!matchPattern(getShift(), m_Constant(&shift_elem)))
1894 // cannot be folded when the shift value is unknown.
1895 return {};
1896 shift = shift_elem.getValues<IntegerAttr>()[0].getInt();
1897 }
1898 }
1899
1900 if (rhsTy == resultTy && isSplatZero(resultETy, lhsAttr) &&
1901 resultTy.hasStaticShape())
1902 // constant values can only be resized if resulting type is static
1903 return lhsAttr.resizeSplat(resultTy);
1904 if (lhsTy == resultTy && isSplatZero(resultETy, rhsAttr) &&
1905 resultTy.hasStaticShape())
1906 return rhsAttr.resizeSplat(resultTy);
1907
1908 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1909 lhsTy.getShape(), rhsTy.getShape());
1910 if (isBroadcastable && rhsTy == resultTy &&
1911 isSplatOne(resultETy, lhsAttr, shift))
1912 return rhs;
1913 if (isBroadcastable && lhsTy == resultTy &&
1914 isSplatOne(resultETy, rhsAttr, shift))
1915 return lhs;
1916
1917 return mulBinaryFolder(lhsAttr, rhsAttr, resultTy, shift);
1918}
1919
1920OpFoldResult SubOp::fold(FoldAdaptor adaptor) {
1921 auto lhsTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
1922 auto rhsTy = llvm::dyn_cast<RankedTensorType>(getInput2().getType());
1923 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1924 if (!lhsTy || !rhsTy || !resultTy)
1925 return {};
1926
1927 // Cannot create an ElementsAttr from non-int/float/index types
1928 if (!lhsTy.getElementType().isIntOrIndexOrFloat() ||
1929 !rhsTy.getElementType().isIntOrIndexOrFloat())
1930 return {};
1931
1932 auto resultETy = resultTy.getElementType();
1933 auto lhsAttr =
1934 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1935 auto rhsAttr =
1936 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1937
1938 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1939 lhsTy.getShape(), rhsTy.getShape());
1940 if (isBroadcastable && lhsTy == resultTy && isSplatZero(resultETy, rhsAttr))
1941 return getInput1();
1942
1943 if (!lhsAttr || !rhsAttr)
1944 return {};
1945
1946 return binaryFolder<SubFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1947}
1948
1949OpFoldResult GreaterOp::fold(FoldAdaptor adaptor) {
1950 auto resultTy = llvm::cast<ShapedType>(getType());
1951 auto lhsAttr =
1952 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1953 auto rhsAttr =
1954 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1955
1956 if (!lhsAttr || !rhsAttr)
1957 return {};
1958
1959 return binaryFolder<GreaterFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1960}
1961
1962OpFoldResult GreaterEqualOp::fold(FoldAdaptor adaptor) {
1963 auto resultTy = llvm::cast<ShapedType>(getType());
1964 auto lhsAttr =
1965 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1966 auto rhsAttr =
1967 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1968
1969 if (!lhsAttr || !rhsAttr)
1970 return {};
1971
1972 return binaryFolder<GreaterEqualFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1973}
1974
1975OpFoldResult EqualOp::fold(FoldAdaptor adaptor) {
1976 auto resultTy = llvm::cast<ShapedType>(getType());
1977 auto lhsAttr =
1978 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1979 auto rhsAttr =
1980 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1981 Value lhs = getInput1();
1982 Value rhs = getInput2();
1983 auto lhsTy = llvm::cast<ShapedType>(lhs.getType());
1984
1985 // If we are comparing an integer value to itself it is always true. We
1986 // can not do this with float due to float values.
1987 if (llvm::isa<IntegerType>(lhsTy.getElementType()) && resultTy.hasRank() &&
1988 resultTy.hasStaticShape() && lhs == rhs) {
1989 return DenseElementsAttr::get(resultTy, true);
1990 }
1991
1992 if (!lhsAttr || !rhsAttr)
1993 return {};
1994
1995 return binaryFolder<EqualFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1996}
1997
1998OpFoldResult CastOp::fold(FoldAdaptor adaptor) {
1999 if (getInput().getType() == getType())
2000 return getInput();
2001
2002 auto operand = llvm::dyn_cast_if_present<ElementsAttr>(adaptor.getInput());
2003 if (!operand)
2004 return {};
2005
2006 auto inTy = llvm::cast<ShapedType>(getInput().getType());
2007 auto outTy = llvm::cast<ShapedType>(getType());
2008 if (!outTy.hasRank() || !outTy.hasStaticShape())
2009 return {};
2010 auto inETy = inTy.getElementType();
2011 auto outETy = outTy.getElementType();
2012
2013 if (operand.isSplat()) {
2014 if (llvm::isa<FloatType>(inETy) && llvm::isa<FloatType>(outETy)) {
2015 bool overflow;
2016 auto splatVal = operand.getSplatValue<APFloat>();
2017 auto &semantics = llvm::cast<FloatType>(outETy).getFloatSemantics();
2018 splatVal.convert(semantics, llvm::RoundingMode::NearestTiesToEven,
2019 &overflow);
2020 return SplatElementsAttr::get(outTy, splatVal);
2021 }
2022
2023 if (llvm::isa<IntegerType>(inETy) && llvm::isa<FloatType>(outETy)) {
2024 auto unsign = llvm::cast<IntegerType>(inETy).isUnsignedInteger();
2025 APFloat splatVal(llvm::cast<FloatType>(outETy).getFloatSemantics());
2026 splatVal.convertFromAPInt(operand.getSplatValue<APInt>(), !unsign,
2027 llvm::RoundingMode::NearestTiesToEven);
2028 return SplatElementsAttr::get(outTy, splatVal);
2029 }
2030
2031 if (llvm::isa<FloatType>(inETy) && llvm::isa<IntegerType>(outETy)) {
2032 auto unsign = llvm::cast<IntegerType>(outETy).isUnsignedInteger();
2033 auto intVal = APSInt(
2034 llvm::cast<IntegerType>(outETy).getIntOrFloatBitWidth(), unsign);
2035 auto floatVal = operand.getSplatValue<APFloat>();
2036 bool exact;
2037 floatVal.convertToInteger(intVal, llvm::RoundingMode::NearestTiesToEven,
2038 &exact);
2039 return SplatElementsAttr::get(outTy, intVal);
2040 }
2041
2042 if (llvm::isa<IntegerType>(inETy) && llvm::isa<IntegerType>(outETy)) {
2043 const auto inIntType = llvm::cast<IntegerType>(inETy);
2044 auto unsignIn = inIntType.isUnsignedInteger();
2045 bool trunc =
2046 inETy.getIntOrFloatBitWidth() > outETy.getIntOrFloatBitWidth();
2047 auto intVal = operand.getSplatValue<APInt>();
2048 auto bitwidth = outETy.getIntOrFloatBitWidth();
2049
2050 // i1 types are boolean in TOSA
2051 if (outETy.isInteger(1)) {
2052 intVal = APInt(bitwidth, intVal.isZero() ? 0 : 1);
2053 } else if (trunc) {
2054 intVal = intVal.trunc(bitwidth);
2055 } else if (unsignIn || inIntType.isInteger(1)) {
2056 intVal = intVal.zext(bitwidth);
2057 } else {
2058 intVal = intVal.sext(bitwidth);
2059 }
2060
2061 return SplatElementsAttr::get(outTy, intVal);
2062 }
2063 }
2064
2065 return {};
2066}
2067
2068OpFoldResult ConstOp::fold(FoldAdaptor adaptor) { return getValuesAttr(); }
2069
2070OpFoldResult ConstShapeOp::fold(FoldAdaptor adaptor) { return getValuesAttr(); }
2071
2072#define REDUCE_FOLDER(OP) \
2073 OpFoldResult OP::fold(FoldAdaptor adaptor) { \
2074 ShapedType inputTy = llvm::cast<ShapedType>(getInput().getType()); \
2075 if (!inputTy.hasRank()) \
2076 return {}; \
2077 if (inputTy != getType()) \
2078 return {}; \
2079 if (inputTy.getRank() == 0 || inputTy.getDimSize(getAxis()) == 1) \
2080 return getInput(); \
2081 return {}; \
2082 }
2083
2084REDUCE_FOLDER(ReduceAllOp)
2085REDUCE_FOLDER(ReduceAnyOp)
2086REDUCE_FOLDER(ReduceMaxOp)
2087REDUCE_FOLDER(ReduceMinOp)
2088REDUCE_FOLDER(ReduceProductOp)
2089REDUCE_FOLDER(ReduceSumOp)
2090#undef REDUCE_FOLDER
2091
2092OpFoldResult ReshapeOp::fold(FoldAdaptor adaptor) {
2093 auto inputTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
2094 auto outputTy = llvm::dyn_cast<RankedTensorType>(getType());
2095
2096 if (!inputTy || !outputTy)
2097 return {};
2098
2099 // Fold when the input and output types are the same. This is only safe
2100 // when there is at most 1 dynamic dimension. For 2 or more dynamic
2101 // dimensions, there may still be a productive reshape.
2102 if (inputTy == outputTy && inputTy.getNumDynamicDims() < 2)
2103 return getInput1();
2104
2105 // reshape(reshape(x)) -> reshape(x)
2106 if (auto reshapeOp = llvm::dyn_cast_if_present<tosa::ReshapeOp>(
2107 getInput1().getDefiningOp())) {
2108 getInput1Mutable().assign(reshapeOp.getInput1());
2109 return getResult();
2110 }
2111
2112 // Cannot create an ElementsAttr from non-int/float/index types
2113 if (!inputTy.getElementType().isIntOrIndexOrFloat())
2114 return {};
2115
2116 // reshape(const(x)) -> const(reshape-attr(x))
2117 if (auto operand =
2118 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1())) {
2119 // Constants must have static shape.
2120 if (!outputTy.hasStaticShape())
2121 return {};
2122
2123 // Okay to duplicate splat constants.
2124 if (operand.isSplat())
2125 return SplatElementsAttr::get(outputTy,
2126 operand.getSplatValue<Attribute>());
2127
2128 // Don't duplicate other constants.
2129 if (!getInput1().hasOneUse())
2130 return {};
2131
2133 if (!tosa::getConstShapeValues(getShape().getDefiningOp(), shapeVec))
2134 return {};
2135
2136 return operand.reshape(
2137 llvm::cast<ShapedType>(operand.getType()).clone(shapeVec));
2138 }
2139
2140 return {};
2141}
2142
2143OpFoldResult PadOp::fold(FoldAdaptor adaptor) {
2144 // If the pad is all zeros we can fold this operation away.
2145 if (adaptor.getPadding() && getInput1().getType() == getType()) {
2146 auto densePad = llvm::dyn_cast<DenseElementsAttr>(adaptor.getPadding());
2147 if (densePad && densePad.isSplat() &&
2148 densePad.getSplatValue<APInt>().isZero()) {
2149 return getInput1();
2150 }
2151 }
2152
2153 return {};
2154}
2155
2156// Fold away cases where a tosa.resize operation returns a copy
2157// of the input image.
2158OpFoldResult ResizeOp::fold(FoldAdaptor adaptor) {
2159 auto scaleAttr =
2160 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getScale());
2161 auto offsetAttr =
2162 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getOffset());
2163 auto borderAttr =
2164 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getBorder());
2165 if (!scaleAttr || !offsetAttr || !borderAttr) {
2166 return {};
2167 }
2168
2169 auto scale = tosa::convertFromIntAttr(scaleAttr, /* rank = */ 4);
2170 auto offset = tosa::convertFromIntAttr(offsetAttr, /* rank = */ 2);
2171 auto border = tosa::convertFromIntAttr(borderAttr, /* rank = */ 2);
2172 if (scale.size() != 4 || offset.size() != 2 || border.size() != 2) {
2173 return {};
2174 }
2175
2176 // Check unit scaling.
2177 if (scale[0] != scale[1] || scale[2] != scale[3]) {
2178 return {};
2179 }
2180
2181 // There should be no offset.
2182 if (offset[0] != 0 || offset[1] != 0) {
2183 return {};
2184 }
2185
2186 // There should be no border.
2187 if (border[0] != 0 || border[1] != 0) {
2188 return {};
2189 }
2190
2191 return foldToInputIfTypeMatches(getType(), getInput());
2192}
2193
2194OpFoldResult ReverseOp::fold(FoldAdaptor adaptor) {
2195 auto operand = getInput1();
2196 auto operandTy = llvm::cast<ShapedType>(operand.getType());
2197 auto axis = getAxis();
2198 // If the dim-length is 1, or reversing axis is unit-dim, also a no-op.
2199 const bool isSplatInput =
2200 llvm::isa_and_nonnull<SplatElementsAttr>(adaptor.getInput1());
2201 if (!operandTy.hasRank() ||
2202 (!isSplatInput && operandTy.getDimSize(axis) != 1))
2203 return {};
2204 return foldToInputIfTypeMatches(getType(), operand);
2205}
2206
2207OpFoldResult SliceOp::fold(FoldAdaptor adaptor) {
2208 auto inputTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
2209 auto outputTy = llvm::dyn_cast<RankedTensorType>(getType());
2210
2211 if (!inputTy || !outputTy)
2212 return {};
2213
2214 if (inputTy == outputTy && inputTy.hasStaticShape())
2215 return getInput1();
2216
2217 // Check if this is a no-op slice (starts at 0 and size matches input)
2218
2219 DenseElementsAttr startElems;
2220 if (!matchPattern(getStart(), m_Constant(&startElems)))
2221 return {};
2222
2223 // Check if all start values are zero
2224 bool startIsZeros =
2225 llvm::all_of(startElems.getValues<APInt>(),
2226 [](const APInt &val) { return val.isZero(); });
2227
2228 if (startIsZeros) {
2229
2230 // Check if size matches input shape
2231 DenseElementsAttr sizeElems;
2232 if (!matchPattern(getSize(), m_Constant(&sizeElems)))
2233 return {};
2234
2235 auto inputShape = inputTy.getShape();
2236 auto sizeValues = sizeElems.getValues<APInt>();
2237
2238 bool sizeMatchesInput = true;
2239 for (const auto &[i, sizeVal] : llvm::enumerate(sizeValues)) {
2240 int64_t size = sizeVal.getSExtValue();
2241
2242 if (inputTy.isDynamicDim(i)) {
2243 // For dynamic dimensions, check for kInferableDimSize indicating full
2244 // dimension is sliced
2245 if (size != kInferableDimSize) {
2246 sizeMatchesInput = false;
2247 break;
2248 }
2249 } else {
2250 // For static dimensions, check that size must match exactly or be
2251 // kInferableDimSize indicating full dimension is sliced
2252 if (size != kInferableDimSize && size != inputShape[i]) {
2253 sizeMatchesInput = false;
2254 break;
2255 }
2256 }
2257 }
2258
2259 if (sizeMatchesInput)
2260 return getInput1();
2261 }
2262
2263 // The following checks require the input to be a constant
2264 if (!adaptor.getInput1())
2265 return {};
2266
2267 // Cannot create an ElementsAttr from non-int/float/index types
2268 if (!inputTy.getElementType().isIntOrIndexOrFloat() ||
2269 !outputTy.getElementType().isIntOrIndexOrFloat())
2270 return {};
2271
2272 auto operand = llvm::cast<ElementsAttr>(adaptor.getInput1());
2273 if (operand.isSplat() && outputTy.hasStaticShape()) {
2274 return SplatElementsAttr::get(outputTy, operand.getSplatValue<Attribute>());
2275 }
2276
2277 if (inputTy.hasStaticShape() && outputTy.hasStaticShape() &&
2278 outputTy.getNumElements() == 1) {
2279 llvm::SmallVector<uint64_t> indices =
2280 llvm::to_vector(startElems.getValues<uint64_t>());
2281 if (auto values = operand.tryGetValues<Attribute>())
2282 return SplatElementsAttr::get(outputTy, (*values)[indices]);
2283 }
2284
2285 return {};
2286}
2287
2288OpFoldResult tosa::SelectOp::fold(FoldAdaptor adaptor) {
2289 const Value pred = getPred();
2290 const Value onTrue = getOnTrue();
2291 const Value onFalse = getOnFalse();
2292
2293 const auto predTy = llvm::dyn_cast<RankedTensorType>(pred.getType());
2294 const auto onTrueTy = llvm::dyn_cast<RankedTensorType>(onTrue.getType());
2295 const auto onFalseTy = llvm::dyn_cast<RankedTensorType>(onFalse.getType());
2296 if (!predTy || !onTrueTy || !onFalseTy)
2297 return {};
2298
2299 const Type resultTy = getType();
2300
2301 const ArrayRef<int64_t> predShape = predTy.getShape();
2302 const ArrayRef<int64_t> onTrueShape = onTrueTy.getShape();
2303
2304 if (onTrue == onFalse && onTrueTy == resultTy &&
2305 OpTrait::util::staticallyKnownBroadcastable(predShape, onTrueShape))
2306 return onTrue;
2307
2308 auto predicate =
2309 llvm::dyn_cast_if_present<DenseIntElementsAttr>(adaptor.getInput1());
2310 if (!predicate)
2311 return {};
2312 if (!predicate.isSplat())
2313 return {};
2314
2315 const bool predicateValue = predicate.getSplatValue<APInt>().getBoolValue();
2316
2317 SmallVector<SmallVector<int64_t>, 3> shapes;
2318 shapes.emplace_back(predShape);
2319 shapes.emplace_back(onTrueShape);
2320 shapes.emplace_back(onFalseTy.getShape());
2321 const bool isBroadcastable =
2323
2324 if (predicateValue == true && onTrueTy == resultTy && isBroadcastable)
2325 return onTrue;
2326 if (predicateValue == false && onFalseTy == resultTy && isBroadcastable)
2327 return onFalse;
2328 return {};
2329}
2330
2331static LogicalResult verifyTileIsBroadcast(tosa::TileOp tileOp) {
2332 const auto inputType =
2333 dyn_cast<RankedTensorType>(tileOp.getInput1().getType());
2334 const auto outputType = dyn_cast<RankedTensorType>(tileOp.getType());
2335 if (!inputType || !outputType)
2336 return failure();
2337
2338 SmallVector<int64_t> multiples;
2339 if (failed(tileOp.getConstantMultiples(multiples)))
2340 return failure();
2341
2342 for (const auto [index, multiple] : llvm::enumerate(multiples)) {
2343 if (multiple == 1)
2344 continue;
2345 if (outputType.isDynamicDim(index))
2346 return failure();
2347 if (inputType.getDimSize(index) != 1)
2348 return failure();
2349 }
2350
2351 return success();
2352}
2353
2355 : public OpRewritePattern<tosa::TileOp> {
2356 using OpRewritePattern<tosa::TileOp>::OpRewritePattern;
2357
2358 LogicalResult matchAndRewrite(tosa::TileOp tileOp,
2359 PatternRewriter &rewriter) const override {
2360 Value tileOutput = tileOp.getOutput();
2361 if (!tileOutput.hasOneUse())
2362 return rewriter.notifyMatchFailure(tileOp,
2363 "tile output must have one use");
2364
2365 Operation *user = *tileOutput.user_begin();
2366 const bool isBinaryElementwise =
2367 user->getNumOperands() == 2 &&
2369 if (!isBinaryElementwise && !isa<tosa::MulOp>(user))
2370 return rewriter.notifyMatchFailure(
2371 tileOp, "consumer must be binary broadcastable");
2372
2373 if (failed(verifyTileIsBroadcast(tileOp)))
2374 return rewriter.notifyMatchFailure(
2375 tileOp, "tile must only expand statically-known singleton dims");
2376
2377 Value lhsOperand = user->getOperand(0);
2378 Value rhsOperand = user->getOperand(1);
2379 Value otherOperand = lhsOperand == tileOutput ? rhsOperand : lhsOperand;
2380 Value tileInput = tileOp.getInput1();
2381
2382 const ShapedType newOtherType = cast<ShapedType>(otherOperand.getType());
2383 const ShapedType newTileType = cast<ShapedType>(tileInput.getType());
2384 SmallVector<int64_t> broadcastedShape;
2386 newOtherType.getShape(), newTileType.getShape(), broadcastedShape);
2387
2388 const ShapedType outputType = cast<ShapedType>(user->getResultTypes()[0]);
2389 if (!llvm::equal(broadcastedShape, outputType.getShape()))
2390 return rewriter.notifyMatchFailure(
2391 tileOp, "tile output must be broadcastable to consumer operands");
2392
2393 rewriter.setInsertionPoint(user);
2394 IRMapping mapper;
2395 mapper.map(tileOutput, tileOp.getInput1());
2396 Operation *newUser = rewriter.clone(*user, mapper);
2397 rewriter.replaceOp(user, newUser->getResults());
2398 return success();
2399 }
2400};
2401
2402void TileOp::getCanonicalizationPatterns(RewritePatternSet &results,
2403 MLIRContext *context) {
2404 results.add<RemoveBroadcastTileFromBinaryElementwise>(context);
2405}
2406
2407OpFoldResult TileOp::fold(FoldAdaptor adaptor) {
2408 if (getInput1().getType() == getType()) {
2409 if (auto multiples = llvm::dyn_cast_if_present<DenseElementsAttr>(
2410 adaptor.getMultiples())) {
2411 if (multiples.isSplat() &&
2412 multiples.getSplatValue<APInt>().getSExtValue() == 1)
2413 return getInput1();
2414 if (auto int_array_attr =
2415 llvm::dyn_cast<DenseIntElementsAttr>(multiples)) {
2416 if (llvm::all_of(int_array_attr.getValues<APInt>(),
2417 [](APInt v) { return v.getSExtValue() == 1; }))
2418 return getInput1();
2419 }
2420 }
2421 }
2422 return {};
2423}
2424
2425OpFoldResult TransposeOp::fold(FoldAdaptor adaptor) {
2426 auto resultTy = llvm::cast<ShapedType>(getType());
2427
2428 // Transposing splat values just means reshaping.
2429 if (auto input =
2430 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1())) {
2431 if (input.isSplat() && resultTy.hasRank() && resultTy.hasStaticShape() &&
2432 input.getType().getElementType() == resultTy.getElementType())
2433 return input.reshape(resultTy);
2434 }
2435
2436 // Transpose is not the identity transpose.
2437 const llvm::ArrayRef<int32_t> perms = getPerms();
2438
2439 if (!llvm::equal(llvm::seq<int32_t>(0, perms.size()), perms))
2440 return {};
2441
2442 return foldToInputIfTypeMatches(getType(), getInput1());
2443}
2444
2445OpFoldResult tosa::NegateOp::fold(FoldAdaptor adaptor) {
2446 // Element-wise negate(negate(x)) = x
2447 // iff all zero points are constant 0
2448 auto definingOp = getInput1().getDefiningOp<tosa::NegateOp>();
2449 if (!definingOp) {
2450 // defining op of input1 is not a negate, cannot fold
2451 return {};
2452 }
2453
2454 if (FailureOr<int64_t> maybeIZp = getInput1ZeroPoint();
2455 failed(maybeIZp) || *maybeIZp != 0) {
2456 // input1 zero point is not constant 0, cannot fold
2457 return {};
2458 }
2459 if (FailureOr<int64_t> maybeOZp = getOutputZeroPoint();
2460 failed(maybeOZp) || *maybeOZp != 0) {
2461 // output zero point is not constant 0, cannot fold
2462 return {};
2463 }
2464 if (FailureOr<int64_t> maybeIZp = definingOp.getInput1ZeroPoint();
2465 failed(maybeIZp) || *maybeIZp != 0) {
2466 // definingOp's input1 zero point is not constant 0, cannot fold
2467 return {};
2468 }
2469 if (FailureOr<int64_t> maybeOZp = definingOp.getOutputZeroPoint();
2470 failed(maybeOZp) || *maybeOZp != 0) {
2471 // definingOp's output zero point is not constant 0, cannot fold
2472 return {};
2473 }
2474
2475 return foldToInputIfTypeMatches(getType(), definingOp.getInput1());
2476}
2477
2478OpFoldResult tosa::AbsOp::fold(FoldAdaptor adaptor) {
2479 auto input = getInput1();
2480 // Element-wise abs(abs(x)) = abs(x)
2481 if (input.getDefiningOp<tosa::AbsOp>())
2482 return foldToInputIfTypeMatches(getType(), input);
2483
2484 return {};
2485}
2486
2487OpFoldResult tosa::ReciprocalOp::fold(FoldAdaptor adaptor) {
2488 auto input = adaptor.getInput1();
2489
2490 auto inputAttr = llvm::dyn_cast_if_present<DenseElementsAttr>(input);
2491 // Fold splat inputs only.
2492 if (!inputAttr || !inputAttr.isSplat())
2493 return {};
2494
2495 auto shapeType = llvm::cast<ShapedType>(getType());
2496 if (!shapeType.hasRank() || !shapeType.hasStaticShape())
2497 return {};
2498 if (auto floatType = llvm::dyn_cast<FloatType>(inputAttr.getElementType())) {
2499 auto floatVal = inputAttr.getSplatValue<APFloat>();
2500 return DenseElementsAttr::get(shapeType,
2501 ReciprocalOp::calcOneElement(floatVal));
2502 }
2503
2504 return {};
2505}
2506
2507template <typename Op, typename OpFoldAdaptor>
2509 auto input1ConstShape =
2510 dyn_cast<tosa::ConstShapeOp>(op->getInput().getDefiningOp());
2511 if (!input1ConstShape)
2512 return {};
2513
2514 const auto input1Attr = cast<DenseElementsAttr>(input1ConstShape.getValues());
2515
2516 return unaryFolder<OpFoldAdaptor>(input1Attr, input1Attr.getType(),
2517 /*foldDenseValues=*/true);
2518}
2519
2520template <typename Op, typename OpFoldAdaptor>
2522 auto input1ConstShape =
2523 dyn_cast<tosa::ConstShapeOp>(op->getInput1().getDefiningOp());
2524 auto input2ConstShape =
2525 dyn_cast<tosa::ConstShapeOp>(op->getInput2().getDefiningOp());
2526 if (!input1ConstShape || !input2ConstShape)
2527 return {};
2528
2529 const auto input1Attr = cast<DenseElementsAttr>(input1ConstShape.getValues());
2530 const auto input2Attr = cast<DenseElementsAttr>(input2ConstShape.getValues());
2531
2532 return binaryFolder<OpFoldAdaptor>(input1Attr, input2Attr,
2533 input1Attr.getType(),
2534 /*foldDenseValues=*/true);
2535}
2536
2537OpFoldResult tosa::DimOp::fold(FoldAdaptor adaptor) {
2538 const auto inputTy = llvm::dyn_cast<ShapedType>(getInput1().getType());
2539 if (!inputTy || !inputTy.hasRank())
2540 return {};
2541 const int32_t axis = getAxis();
2542 const int64_t dimSize = inputTy.getDimSize(axis);
2543 if (ShapedType::isDynamic(dimSize))
2544 return {};
2545
2546 OpBuilder builder(getContext());
2547 const auto resultAttrTy =
2548 RankedTensorType::get(/*rank=*/1, builder.getIndexType());
2549 return DenseElementsAttr::get(resultAttrTy, dimSize);
2550}
2551
2552OpFoldResult concatShapeFold(tosa::ConcatShapeOp *op) {
2553 auto const inputs = op->getInput();
2554
2555 if (inputs.empty())
2556 return {};
2557
2558 SmallVector<APInt> concatDims;
2559 concatDims.reserve(/*max elem*/ 64);
2560 for (auto const &v : inputs) {
2561 auto vConstShape = dyn_cast<tosa::ConstShapeOp>(v.getDefiningOp());
2562 if (!vConstShape)
2563 return {};
2564
2565 const auto vAttr = cast<DenseElementsAttr>(vConstShape.getValues());
2566 assert(vAttr);
2567
2568 auto const vAttrVals = vAttr.getValues<APInt>();
2569 for (auto const &v : vAttrVals) {
2570 concatDims.push_back(v);
2571 }
2572 }
2573
2574 auto *ctx = op->getContext();
2575 assert(ctx != nullptr && "ctx is nullptr");
2576 auto const rankedTy = RankedTensorType::get(
2577 {static_cast<int64_t>(concatDims.size())}, IndexType::get(ctx));
2578
2579 return DenseElementsAttr::get(rankedTy, concatDims);
2580}
2581
2582OpFoldResult sliceShapeFold(tosa::SliceShapeOp *op) {
2583 auto const input1 = op->getInput();
2584 auto const input2 = op->getStart();
2585 auto const input3 = op->getSize();
2586
2587 auto input1ConstShape = dyn_cast<tosa::ConstShapeOp>(input1.getDefiningOp());
2588
2589 if (!input1ConstShape)
2590 return {};
2591
2592 auto const input1Attr = cast<DenseElementsAttr>(input1ConstShape.getValues());
2593 if (!input1Attr)
2594 return {};
2595
2596 auto const input1Vals = input1Attr.getValues<APInt>();
2597 auto const totalInput1 = input1Vals.size();
2598
2599 auto const start = getSingleI64From1ElementTensor(input2);
2600 auto const size = getSingleI64From1ElementTensor(input3);
2601
2602 if (failed(start) || failed(size))
2603 return {};
2604
2605 auto const startV = static_cast<int32_t>(start.value());
2606 auto const sizeV = static_cast<int32_t>(size.value());
2607
2608 if ((sizeV <= 0) || (startV < 0) ||
2609 (static_cast<size_t>(startV + sizeV) > totalInput1))
2610 return {};
2611
2612 SmallVector<APInt> sliceOfInput;
2613 sliceOfInput.reserve(totalInput1);
2614
2615 for (auto i = startV; i < (startV + sizeV); i++) {
2616 sliceOfInput.push_back(input1Vals[i]);
2617 }
2618
2619 auto *ctx = op->getContext();
2620 assert(ctx != nullptr && "ctx is nullptr");
2621
2622 auto const rankedTy = RankedTensorType::get(
2623 {static_cast<int64_t>(sliceOfInput.size())}, IndexType::get(ctx));
2624
2625 return DenseElementsAttr::get(rankedTy, sliceOfInput);
2626}
2627
2628OpFoldResult tosa::AddShapeOp::fold(FoldAdaptor adaptor) {
2630}
2631
2632OpFoldResult tosa::SubShapeOp::fold(FoldAdaptor adaptor) {
2634}
2635
2636OpFoldResult tosa::MulShapeOp::fold(FoldAdaptor adaptor) {
2638}
2639
2640OpFoldResult tosa::DivCeilShapeOp::fold(FoldAdaptor adaptor) {
2641 return binaryFold<DivCeilShapeOp, ShapeDivFoldAdaptor</*Ceil*/ true>>(this);
2642}
2643
2644OpFoldResult tosa::DivFloorShapeOp::fold(FoldAdaptor adaptor) {
2645 return binaryFold<DivFloorShapeOp, ShapeDivFoldAdaptor</*Ceil*/ false>>(this);
2646}
2647
2648OpFoldResult tosa::ModShapeOp::fold(FoldAdaptor adaptor) {
2650}
2651
2652OpFoldResult tosa::MaxShapeOp::fold(FoldAdaptor adaptor) {
2654}
2655
2656OpFoldResult tosa::MinShapeOp::fold(FoldAdaptor adaptor) {
2658}
2659
2660OpFoldResult tosa::Exp2ShapeOp::fold(FoldAdaptor adaptor) {
2662}
2663
2664OpFoldResult tosa::Log2CeilShapeOp::fold(FoldAdaptor adaptor) {
2666}
2667
2668OpFoldResult tosa::Log2FloorShapeOp::fold(FoldAdaptor adaptor) {
2670}
2671
2672OpFoldResult tosa::ConcatShapeOp::fold(FoldAdaptor adaptor) {
2673 return concatShapeFold(this);
2674}
2675
2676OpFoldResult tosa::SliceShapeOp::fold(FoldAdaptor adaptor) {
2677 return sliceShapeFold(this);
2678}
return success()
static bool isSplatZero(Type elemType, DenseElementsAttr val)
Returns true if 'val' is a splat of zero, false otherwise.
lhs
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
b getContext())
*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 the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
#define REDUCE_FOLDER(OP)
OpFoldResult concatShapeFold(tosa::ConcatShapeOp *op)
static DenseElementsAttr binaryFolder(DenseElementsAttr lhs, DenseElementsAttr rhs, ShapedType returnTy, bool foldDenseValues=false)
static DenseElementsAttr unaryFolder(DenseElementsAttr val, ShapedType returnTy, bool foldDenseValues=false)
static LogicalResult verifyTileIsBroadcast(tosa::TileOp tileOp)
OpFoldResult sliceShapeFold(tosa::SliceShapeOp *op)
static FailureOr< int64_t > getSingleI64From1ElementTensor(Value v)
OpFoldResult binaryFold(Op *op)
static bool isSplatOne(Type elemType, DenseElementsAttr val, int64_t shift)
OpFoldResult unaryShapeFold(Op *op)
static bool checkMatchingPadConstAndZp(Value padConst, Value zp)
static bool signsDiffer(const APInt &a, const APInt &b)
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
Attributes are known-constant values of operations.
Definition Attributes.h:25
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:167
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:233
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:171
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:259
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition Builders.h:93
MLIRContext * getContext() const
Definition Builders.h:56
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.
std::enable_if_t<!std::is_base_of< Attribute, T >::value||std::is_same< Attribute, T >::value, T > getSplatValue() const
Return the splat value for this attribute.
int64_t size() const
Returns the number of elements held by this attribute.
bool isSplat() const
Returns true if this attribute corresponds to a splat, i.e.
Type getElementType() const
Return the element type of this DenseElementsAttr.
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
ShapedType getType() const
Return the type of this ElementsAttr, guaranteed to be a vector or tensor with static shape.
An attribute that represents a reference to a dense integer vector or tensor object.
iterator begin() const
Iterator access to the integer element values.
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:63
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:567
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:400
This class represents a single result from folding an operation.
This class indicates that an op is tosa-elementwise (permits broadcasting, unlike Elementwise trait).
Definition TosaOps.h:67
This provides public APIs that all operations should have.
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:375
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:774
unsigned getNumOperands()
Definition Operation.h:371
result_type_range getResultTypes()
Definition Operation.h:453
result_range getResults()
Definition Operation.h:440
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
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,...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
Definition Types.cpp:114
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
user_iterator user_begin() const
Definition Value.h:216
bool hasOneUse() const
Returns true if this value has exactly one use.
Definition Value.h:197
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
bool staticallyKnownBroadcastable(ArrayRef< SmallVector< int64_t, 6 > > shapes)
Returns true if a broadcast between n shapes is guaranteed to be successful and not result in an erro...
Definition Traits.cpp:24
bool getBroadcastedShape(ArrayRef< int64_t > shape1, ArrayRef< int64_t > shape2, SmallVectorImpl< int64_t > &resultShape)
Returns true and sets resultShape to the broadcasted shape from the two given shapes if they are broa...
Definition Traits.cpp:59
DynamicAPInt round(const Fraction &f)
Definition Fraction.h:136
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:717
TosaLevel getTosaLevelFromEnum(const Level level)
Definition TargetEnv.cpp:15
constexpr int64_t kInferableDimSize
Represents a dimension in the shape of a tensor that can be inferred based on the other provided dime...
Definition TosaOps.h:106
SmallVector< int64_t > convertFromIntAttr(const DenseElementsAttr &attr, const int rank)
TargetEnvAttr lookupTargetEnv(Operation *op)
FailureOr< T > getConstantScalarIntValue(Value val)
Value getTosaConstShape(ImplicitLocOpBuilder &builder, llvm::ArrayRef< int64_t > shape)
Type getStorageElementTypeFromQuantized(quant::QuantizedType quantizedType)
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.
Definition Matchers.h:490
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:307
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
LogicalResult matchAndRewrite(tosa::AvgPool2dAdaptiveOp op, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::AvgPool2dOp op, PatternRewriter &rewriter) const override
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
LogicalResult matchAndRewrite(tosa::CastOp castOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::CastToBlockScaledOp castToBlockScaledOp, PatternRewriter &rewriter) const override
bool intersects(const ClampRange< T > &otherRange)
ClampRange(const T &start, const T &end)
LogicalResult matchAndRewrite(tosa::ClampOp op, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::ClampOp op, PatternRewriter &rewriter) const override
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
LogicalResult matchAndRewrite(tosa::ConcatOp op, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::SliceOp sliceOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::ConcatOp op, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::TransposeOp transposeOp, PatternRewriter &rewriter) const override
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
static FailureOr< APInt > fold(const APInt &value, bool isUnsigned)
static FailureOr< APInt > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
static FailureOr< APInt > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &value, bool isUnsigned)
static FailureOr< APInt > fold(const APInt &value, bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, bool isUnsigned)
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
LogicalResult matchAndRewrite(tosa::MaxPool2dAdaptiveOp op, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::MaxPool2dOp op, PatternRewriter &rewriter) const override
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
bool isNarrowingCast(const ShapedType inType, const ShapedType outType) const
LogicalResult matchAndRewrite(tosa::CastOp castOp, PatternRewriter &rewriter) const override
bool supportsInf(const llvm::fltSemantics &semantics) const
bool supportsNaN(const llvm::fltSemantics &semantics) const
LogicalResult matchAndRewrite(tosa::SliceOp sliceOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::TileOp tileOp, PatternRewriter &rewriter) const override
LogicalResult matchAndRewrite(tosa::RowGatherOp op, PatternRewriter &rewriter) const override
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, bool isUnsigned)
LogicalResult matchAndRewrite(tosa::SliceOp sliceOp, PatternRewriter &rewriter) const override
static FailureOr< APFloat > fold(const APFloat &lhs, const APFloat &rhs)
static FailureOr< APInt > fold(const APInt &lhs, const APInt &rhs, const bool isUnsigned)
LogicalResult matchAndRewrite(tosa::TransposeOp op, PatternRewriter &rewriter) const override
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
Patterns must specify the root operation name they match against, and can also specify the benefit of...
int32_t MAX_TENSOR_LIST_SIZE
Definition TargetEnv.h:30