MLIR 24.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 // Bail out of the canonicalization if (inner) cast(input_unsigned=false) ->
1174 // (outer) cast(input_unsigned=true)
1175 if (!innerCastOp.getInputUnsigned() && castOp.getInputUnsigned()) {
1176 return rewriter.notifyMatchFailure(
1177 castOp, "avoid rewriting cast(input_unsigned=false) -> "
1178 "cast(input_unsigned=true)");
1179 }
1180
1181 rewriter.replaceOpWithNewOp<tosa::CastOp>(castOp, outerOutputType,
1182 innerCastInput,
1183 innerCastOp.getInputUnsigned());
1184
1185 return success();
1186 }
1187
1188 bool supportsNaN(const llvm::fltSemantics &semantics) const {
1189 return semantics.nonFiniteBehavior !=
1190 llvm::fltNonfiniteBehavior::FiniteOnly;
1191 }
1192
1193 bool supportsInf(const llvm::fltSemantics &semantics) const {
1194 return semantics.nonFiniteBehavior == llvm::fltNonfiniteBehavior::IEEE754;
1195 }
1196
1197 bool isNarrowingCast(const ShapedType inType,
1198 const ShapedType outType) const {
1199
1200 if (inType.getElementType().isInteger() &&
1201 outType.getElementType().isInteger()) {
1202
1203 const auto inTypeSignedness =
1204 cast<IntegerType>(inType.getElementType()).getSignedness();
1205 const auto outTypeSignedness =
1206 cast<IntegerType>(outType.getElementType()).getSignedness();
1207
1208 return (inTypeSignedness != outTypeSignedness ||
1209 inType.getElementTypeBitWidth() >
1210 outType.getElementTypeBitWidth());
1211 }
1212
1213 if (inType.getElementType().isFloat() &&
1214 outType.getElementType().isFloat()) {
1215
1216 FloatType inElemTy = cast<FloatType>(inType.getElementType());
1217 FloatType outElemTy = cast<FloatType>(outType.getElementType());
1218 llvm::fltSemantics inTypeSemantics = inElemTy.getFloatSemantics();
1219 llvm::fltSemantics outTypeSemantics = outElemTy.getFloatSemantics();
1220
1221 // If the list of supported types needs to be updated in the future, the
1222 // check down below will need to be revised, for example to account for
1223 // unsigned floating point types, or types that use negative zero as the
1224 // representation for NaN.
1225 [[maybe_unused]] const auto isSupported = [](Type elemType) {
1226 return llvm::isa<Float8E4M3FNType, Float8E5M2Type, BFloat16Type,
1227 Float16Type, Float32Type>(elemType);
1228 };
1229
1230 assert(isSupported(inElemTy) &&
1231 "unsupported input element type in isNarrowingCast");
1232 assert(isSupported(outElemTy) &&
1233 "unsupported output element type in isNarrowingCast");
1234
1235 return (
1236 inTypeSemantics.maxExponent > outTypeSemantics.maxExponent ||
1237 inTypeSemantics.minExponent < outTypeSemantics.minExponent ||
1238 inTypeSemantics.precision > outTypeSemantics.precision ||
1239 (supportsNaN(inTypeSemantics) && !supportsNaN(outTypeSemantics)) ||
1240 (supportsInf(inTypeSemantics) && !supportsInf(outTypeSemantics)));
1241 }
1242
1243 // While some cases of int -> float casts can be non-narrowing, consider
1244 // them narrowing for the purposes of this optimization
1245 return true;
1246 }
1247};
1248
1250 : public OpRewritePattern<tosa::CastOp> {
1251 using OpRewritePattern<tosa::CastOp>::OpRewritePattern;
1252
1253 LogicalResult matchAndRewrite(tosa::CastOp castOp,
1254 PatternRewriter &rewriter) const override {
1255 const Value outerInput = castOp.getInput();
1256 auto innerCastOp = outerInput.getDefiningOp<tosa::CastOp>();
1257 if (!innerCastOp)
1258 return rewriter.notifyMatchFailure(castOp,
1259 "input must be a cast operation");
1260
1261 const Value innerInput = innerCastOp.getInput();
1262 const auto innerInputTy = llvm::cast<ShapedType>(innerInput.getType());
1263 const auto innerOutputTy = llvm::cast<ShapedType>(innerCastOp.getType());
1264 const auto outerOutputTy = llvm::cast<ShapedType>(castOp.getType());
1265
1266 if (!llvm::isa<tosa::BlockScaledType>(innerInputTy.getElementType()))
1267 return rewriter.notifyMatchFailure(
1268 castOp, "inner cast input must have block scaled element type");
1269
1270 if (innerInputTy != outerOutputTy)
1271 return rewriter.notifyMatchFailure(
1272 castOp, "inner input type must match outer output type");
1273
1274 const Type innerOutputElemType = innerOutputTy.getElementType();
1275 const bool isLosslessCast =
1276 isa<Float32Type, BFloat16Type>(innerOutputElemType);
1277 if (!isLosslessCast)
1278 return rewriter.notifyMatchFailure(
1279 castOp, "avoid cancelling casts that should be lossy");
1280
1281 rewriter.replaceOp(castOp, innerInput);
1282
1283 return success();
1284 }
1285};
1286
1287void CastOp::getCanonicalizationPatterns(RewritePatternSet &results,
1288 MLIRContext *context) {
1289 results.add<NonNarrowingCastsOptimization,
1290 CancellingBlockScaledCastsOptimization>(context);
1291}
1292
1294 : public OpRewritePattern<tosa::CastToBlockScaledOp> {
1295 using OpRewritePattern<tosa::CastToBlockScaledOp>::OpRewritePattern;
1296
1297 LogicalResult matchAndRewrite(tosa::CastToBlockScaledOp castToBlockScaledOp,
1298 PatternRewriter &rewriter) const override {
1299 const Value castToBlockScaledInput = castToBlockScaledOp.getInputData();
1300 auto castFromBlockScaledOp =
1301 castToBlockScaledInput.getDefiningOp<tosa::CastFromBlockScaledOp>();
1302 if (!castFromBlockScaledOp)
1303 return rewriter.notifyMatchFailure(
1304 castToBlockScaledOp,
1305 "input must be cast_from_block_scaled operation");
1306
1307 const Value innerData = castFromBlockScaledOp.getInputData();
1308 const Value innerScale = castFromBlockScaledOp.getInputScale();
1309 const auto innerDataTy = llvm::cast<ShapedType>(innerData.getType());
1310 const auto innerScaleTy = llvm::cast<ShapedType>(innerScale.getType());
1311
1312 const Value outerData = castToBlockScaledOp.getOutputData();
1313 const Value outerScale = castToBlockScaledOp.getOutputScale();
1314 const auto outerDataTy = llvm::cast<ShapedType>(outerData.getType());
1315 const auto outerScaleTy = llvm::cast<ShapedType>(outerScale.getType());
1316
1317 if (innerDataTy != outerDataTy || innerScaleTy != outerScaleTy) {
1318 return rewriter.notifyMatchFailure(
1319 castToBlockScaledOp,
1320 "inputs types to cast_from_block_scaled operation must match output "
1321 "types to cast_to_block_scaled");
1322 }
1323
1324 if (castFromBlockScaledOp.getBlockSize() !=
1325 castToBlockScaledOp.getBlockSize()) {
1326 return rewriter.notifyMatchFailure(
1327 castToBlockScaledOp, "block sizes for cast_from_block_scaled and "
1328 "cast_to_block_scaled must match");
1329 }
1330
1331 rewriter.replaceOp(castToBlockScaledOp, {innerData, innerScale});
1332
1333 return success();
1334 }
1335};
1336
1337void CastToBlockScaledOp::getCanonicalizationPatterns(
1338 RewritePatternSet &results, MLIRContext *context) {
1339 results.add<CancellingCastToFromBlockScaledOptimization>(context);
1340}
1341
1342struct RowGatherToGather : public OpRewritePattern<tosa::RowGatherOp> {
1343 using OpRewritePattern<tosa::RowGatherOp>::OpRewritePattern;
1344
1345 LogicalResult matchAndRewrite(tosa::RowGatherOp op,
1346 PatternRewriter &rewriter) const override {
1347 const FailureOr<int32_t> rowCount =
1349 if (failed(rowCount) || rowCount.value() != 1)
1350 return failure();
1351
1352 rewriter.replaceOpWithNewOp<tosa::GatherOp>(
1353 op, op.getOutput().getType(), op.getValues(), op.getIndices());
1354 return success();
1355 }
1356};
1357
1358void RowGatherOp::getCanonicalizationPatterns(RewritePatternSet &results,
1359 MLIRContext *context) {
1360 results.add<RowGatherToGather>(context);
1361}
1362
1363//===----------------------------------------------------------------------===//
1364// Operator Folders.
1365//===----------------------------------------------------------------------===//
1366
1367template <typename Folder>
1368static DenseElementsAttr
1370 bool foldDenseValues = false) {
1371 if (!lhs || !rhs)
1372 return {};
1373
1374 if (!returnTy.hasRank() || !returnTy.hasStaticShape())
1375 return {};
1376
1377 const auto lETy = llvm::cast<ShapedType>(lhs.getType()).getElementType();
1378 const auto rETy = llvm::cast<ShapedType>(rhs.getType()).getElementType();
1379 if (lETy != rETy)
1380 return {};
1381
1382 if (lhs.isSplat() && rhs.isSplat()) {
1383 if (isa<FloatType>(lETy)) {
1384 const APFloat l = lhs.getSplatValue<APFloat>();
1385 const APFloat r = rhs.getSplatValue<APFloat>();
1386 const auto maybeResult = Folder::fold(l, r);
1387 if (failed(maybeResult))
1388 return {};
1389 return DenseElementsAttr::get(returnTy, maybeResult.value());
1390 }
1391
1392 if (const auto lIntTy = llvm::dyn_cast<IntegerType>(lETy)) {
1393 const APInt l = lhs.getSplatValue<APInt>();
1394 const APInt r = rhs.getSplatValue<APInt>();
1395 const auto maybeResult = Folder::fold(l, r, lIntTy.isUnsigned());
1396 if (failed(maybeResult))
1397 return {};
1398 return DenseElementsAttr::get(returnTy, maybeResult.value());
1399 }
1400 }
1401
1402 if (foldDenseValues) {
1403 assert(lETy.isIntOrIndex() &&
1404 "Only integer types are currently supported.");
1405 SmallVector<APInt> resultValues;
1406 for (auto [l, r] :
1407 llvm::zip(lhs.getValues<APInt>(), rhs.getValues<APInt>())) {
1408 const auto maybeResult = Folder::fold(l, r, false);
1409 if (failed(maybeResult))
1410 return {};
1411 resultValues.push_back(maybeResult.value());
1412 }
1413 return DenseElementsAttr::get(returnTy, resultValues);
1414 }
1415
1416 return {};
1417}
1418
1419template <typename Folder>
1420static DenseElementsAttr unaryFolder(DenseElementsAttr val, ShapedType returnTy,
1421 bool foldDenseValues = false) {
1422 if (!val)
1423 return {};
1424
1425 if (!returnTy.hasRank() || !returnTy.hasStaticShape())
1426 return {};
1427
1428 const auto vETy = llvm::cast<ShapedType>(val.getType()).getElementType();
1429
1430 if (val.isSplat()) {
1431 if (const auto vIntTy = llvm::dyn_cast<IntegerType>(vETy)) {
1432 const APInt v = val.getSplatValue<APInt>();
1433 const auto maybeResult = Folder::fold(v, vIntTy.isUnsigned());
1434 if (failed(maybeResult))
1435 return {};
1436 return DenseElementsAttr::get(returnTy, maybeResult.value());
1437 }
1438 }
1439
1440 if (foldDenseValues) {
1441 mlir::Type elemTy = val.getElementType();
1442 if (elemTy.isIntOrIndex()) {
1443 SmallVector<APInt> resultValues;
1444 for (auto const &v : val.getValues<APInt>()) {
1445 const auto maybeResult = Folder::fold(v, false);
1446 if (failed(maybeResult))
1447 return {};
1448 resultValues.push_back(maybeResult.value());
1449 }
1450 return DenseElementsAttr::get(returnTy, resultValues);
1451 }
1452 }
1453
1454 // Folding arbitrarily sized tensor operations is not supported
1455 return {};
1456}
1457
1458static FailureOr<int64_t> getSingleI64From1ElementTensor(Value v) {
1459 DenseIntElementsAttr dense{};
1460 if (!matchPattern(v, m_Constant(&dense)))
1461 return failure();
1462
1463 assert(dense.isSplat());
1464 APInt a = dense.getSplatValue<APInt>();
1465 return a.getSExtValue();
1466}
1467
1469 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1470 const bool isUnsigned) {
1471 bool overflow;
1472 const APInt result =
1473 isUnsigned ? lhs.uadd_ov(rhs, overflow) : lhs.sadd_ov(rhs, overflow);
1474 if (overflow)
1475 return failure();
1476 return result;
1477 }
1478
1479 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1480 return lhs + rhs;
1481 }
1482};
1483
1485 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1486 const bool isUnsigned) {
1487 bool overflow;
1488 const APInt result =
1489 isUnsigned ? lhs.usub_ov(rhs, overflow) : lhs.ssub_ov(rhs, overflow);
1490 if (overflow)
1491 return failure();
1492 return result;
1493 }
1494
1495 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1496 return lhs - rhs;
1497 }
1498};
1499
1501 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1502 const bool isUnsigned) {
1503
1504 const unsigned originalWidth = lhs.getBitWidth();
1505
1506 // Check same type
1507 if (lhs.getBitWidth() != rhs.getBitWidth()) {
1508 return failure();
1509 }
1510
1511 // If either is `0`
1512 if (lhs == 0 || rhs == 0)
1513 return APInt::getZero(originalWidth);
1514
1515 bool overflow = false;
1516 APInt const result =
1517 isUnsigned ? lhs.umul_ov(rhs, overflow) : lhs.smul_ov(rhs, overflow);
1518
1519 if (overflow)
1520 return failure();
1521
1522 return result.trunc(originalWidth);
1523 }
1524
1525 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1526 return lhs * rhs;
1527 }
1528};
1529
1530static bool signsDiffer(const APInt &a, const APInt &b) {
1531 return a.isNegative() != b.isNegative();
1532}
1533
1534template <bool Ceil>
1536 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1537 bool isUnsigned) {
1538 if (lhs.getBitWidth() != rhs.getBitWidth())
1539 return failure();
1540 if (rhs.isZero())
1541 return failure();
1542
1543 if (isUnsigned) {
1544 APInt q{};
1545 APInt r{};
1546 APInt::udivrem(lhs, rhs, q, r);
1547 if (!r.isZero() && Ceil) {
1548 return q + 1;
1549 }
1550 return q;
1551 }
1552
1553 // Signed: start from trunc-toward-zero, then adjust to ceil.
1554 bool overflow{false};
1555 APInt const q = lhs.sdiv_ov(rhs, overflow);
1556 if (overflow)
1557 return failure();
1558 APInt const r = lhs.srem(rhs);
1559
1560 if (Ceil && !r.isZero() && !signsDiffer(lhs, rhs)) {
1561 // Same sign => exact quotient is positive; trunc is below ceil =>
1562 // increment q.
1563 return q + 1;
1564 }
1565 return q;
1566 }
1567
1568 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1569 return lhs / rhs;
1570 }
1571};
1572
1574 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1575 bool isUnsigned) {
1576 if (lhs.getBitWidth() != rhs.getBitWidth())
1577 return failure();
1578 if (lhs.isNegative() || (!rhs.isStrictlyPositive()))
1579 return failure();
1580
1581 if (isUnsigned) {
1582 return lhs.urem(rhs);
1583 }
1584
1585 return lhs.srem(rhs);
1586 }
1587
1588 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1589 auto t = lhs;
1590 auto const r = t.mod(rhs);
1591 if (llvm::APFloatBase::opStatus::opOK == r) {
1592 return t;
1593 }
1594 return failure();
1595 }
1596};
1597
1599 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1600 bool isUnsigned) {
1601 if (lhs.getBitWidth() != rhs.getBitWidth())
1602 return failure();
1603 return lhs.getSExtValue() >= rhs.getSExtValue() ? lhs : rhs;
1604 }
1605
1606 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1607 return lhs >= rhs ? lhs : rhs;
1608 }
1609};
1610
1612 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1613 bool isUnsigned) {
1614 if (lhs.getBitWidth() != rhs.getBitWidth())
1615 return failure();
1616 return lhs.getSExtValue() <= rhs.getSExtValue() ? lhs : rhs;
1617 }
1618
1619 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1620 return lhs <= rhs ? lhs : rhs;
1621 }
1622};
1623
1625 static FailureOr<APInt> fold(const APInt &value, bool isUnsigned) {
1626 auto const numBits = value.getBitWidth();
1627 if (isUnsigned) {
1628 auto const zextv = value.getZExtValue();
1629 if (zextv >= numBits)
1630 return failure();
1631 return APInt::getOneBitSet(numBits, zextv);
1632 }
1633 auto const sextv = value.getSExtValue();
1634 if (sextv < 0 || sextv >= numBits || (value.isNegative()))
1635 return failure();
1636 return APInt::getOneBitSet(numBits, sextv);
1637 }
1638};
1639
1640// The specification requires shape div operations to have non-negative lhs and
1641// strictly positive rhs so we can only fold when these conditions are met.
1642template <bool Ceil>
1644 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1645 bool isUnsigned) {
1646 assert(!isUnsigned &&
1647 "unsigned values are not supported for shape div folders");
1648 if (lhs.isNegative() || !rhs.isStrictlyPositive())
1649 return failure();
1650 return DivFoldAdaptor<Ceil>::fold(lhs, rhs, isUnsigned);
1651 }
1652
1653 static FailureOr<APFloat> fold(const APFloat &lhs, const APFloat &rhs) {
1654 return failure();
1655 }
1656};
1657
1659 static FailureOr<APInt> fold(const APInt &value, bool isUnsigned) {
1660 if (!value.isStrictlyPositive())
1661 return failure();
1662 return APInt(/*numBits=*/value.getBitWidth(), value.ceilLogBase2());
1663 }
1664};
1665
1667 static FailureOr<APInt> fold(const APInt &value, bool isUnsigned) {
1668 if (!value.isStrictlyPositive())
1669 return failure();
1670 return APInt(/*numBits=*/value.getBitWidth(), value.logBase2());
1671 }
1672};
1673
1675 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1676 const bool isUnsigned) {
1677 return isUnsigned ? APInt(1, lhs.ugt(rhs)) : APInt(1, lhs.sgt(rhs));
1678 }
1679
1680 static FailureOr<APInt> fold(const APFloat &lhs, const APFloat &rhs) {
1681 return APInt(1, lhs > rhs);
1682 }
1683};
1684
1686 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1687 const bool isUnsigned) {
1688 return isUnsigned ? APInt(1, lhs.uge(rhs)) : APInt(1, lhs.sge(rhs));
1689 }
1690
1691 static FailureOr<APInt> fold(const APFloat &lhs, const APFloat &rhs) {
1692 return APInt(1, lhs >= rhs);
1693 }
1694};
1695
1697 static FailureOr<APInt> fold(const APInt &lhs, const APInt &rhs,
1698 const bool isUnsigned) {
1699 return APInt(1, lhs == rhs);
1700 }
1701
1702 static FailureOr<APInt> fold(const APFloat &lhs, const APFloat &rhs) {
1703 return APInt(1, lhs == rhs);
1704 }
1705};
1706
1707static bool isSplatZero(Type elemType, DenseElementsAttr val) {
1708 if (llvm::isa<FloatType>(elemType))
1709 return val && val.isSplat() && val.getSplatValue<APFloat>().isZero();
1710 if (llvm::isa<IntegerType>(elemType))
1711 return val && val.isSplat() && val.getSplatValue<APInt>().isZero();
1712 return false;
1713}
1714
1715static bool isSplatOne(Type elemType, DenseElementsAttr val, int64_t shift) {
1716 if (llvm::isa<FloatType>(elemType))
1717 return val && val.isSplat() &&
1718 val.getSplatValue<APFloat>().isExactlyValue(1.0);
1719 if (llvm::isa<IntegerType>(elemType)) {
1720 const int64_t shifted = 1LL << shift;
1721 return val && val.isSplat() &&
1722 val.getSplatValue<APInt>().getSExtValue() == shifted;
1723 }
1724 return false;
1725}
1726
1727OpFoldResult AddOp::fold(FoldAdaptor adaptor) {
1728 auto lhsTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
1729 auto rhsTy = llvm::dyn_cast<RankedTensorType>(getInput2().getType());
1730 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1731 if (!lhsTy || !rhsTy || !resultTy)
1732 return {};
1733
1734 // Cannot create an ElementsAttr from non-int/float/index types
1735 if (!lhsTy.getElementType().isIntOrIndexOrFloat() ||
1736 !rhsTy.getElementType().isIntOrIndexOrFloat())
1737 return {};
1738
1739 auto resultETy = resultTy.getElementType();
1740 auto lhsAttr =
1741 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1742 auto rhsAttr =
1743 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1744
1745 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1746 lhsTy.getShape(), rhsTy.getShape());
1747 if (isBroadcastable && lhsTy == resultTy && isSplatZero(resultETy, rhsAttr))
1748 return getInput1();
1749 if (isBroadcastable && rhsTy == resultTy && isSplatZero(resultETy, lhsAttr))
1750 return getInput2();
1751
1752 if (!lhsAttr || !rhsAttr)
1753 return {};
1754
1755 return binaryFolder<AddFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1756}
1757
1758OpFoldResult ArgMaxOp::fold(FoldAdaptor adaptor) {
1759 auto inputTy = llvm::dyn_cast<RankedTensorType>(getInput().getType());
1760 auto outputTy = llvm::dyn_cast<RankedTensorType>(getType());
1761 if (!inputTy || !outputTy || !inputTy.hasStaticShape() ||
1762 !outputTy.hasStaticShape())
1763 return {};
1764
1765 const Type outputElementTy = getElementTypeOrSelf(outputTy);
1766 if (inputTy.getDimSize(getAxis()) == 1 && outputElementTy.isInteger()) {
1767 const auto outputElemIntTy = cast<IntegerType>(outputElementTy);
1768 const APInt zero = APInt::getZero(outputElemIntTy.getWidth());
1769 return DenseElementsAttr::get(outputTy, zero);
1770 }
1771
1772 return {};
1773}
1774
1775OpFoldResult IntDivOp::fold(FoldAdaptor adaptor) {
1776 auto lhsTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
1777 auto rhsTy = llvm::dyn_cast<RankedTensorType>(getInput2().getType());
1778 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1779 if (!lhsTy || !rhsTy || !resultTy)
1780 return {};
1781 if (lhsTy.getElementType() != rhsTy.getElementType())
1782 return {};
1783
1784 // IntDivOp inputs must be integer type, no need to check for quantized
1785 // type
1786 auto resultETy = resultTy.getElementType();
1787 auto lhsAttr =
1788 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1789 auto rhsAttr =
1790 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1791 if (lhsAttr && lhsAttr.isSplat() && rhsAttr && rhsAttr.isSplat()) {
1792 if (llvm::isa<IntegerType>(resultETy) && resultTy.hasStaticShape() &&
1793 lhsAttr.getSplatValue<APInt>().isZero() &&
1794 !rhsAttr.getSplatValue<APInt>().isZero()) {
1795 return lhsAttr.resizeSplat(resultTy);
1796 }
1797 }
1798
1799 if (rhsAttr && rhsAttr.isSplat()) {
1800 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1801 lhsTy.getShape(), rhsTy.getShape());
1802 if (isBroadcastable && lhsTy == resultTy &&
1803 llvm::isa<IntegerType>(resultETy) &&
1804 rhsAttr.getSplatValue<APInt>().isOne())
1805 return getInput1();
1806 }
1807
1808 if (rhsAttr && lhsAttr && rhsAttr.isSplat() && lhsAttr.isSplat() &&
1809 llvm::isa<IntegerType>(resultETy) && resultTy.hasStaticShape()) {
1810 APInt l = lhsAttr.getSplatValue<APInt>();
1811 APInt r = rhsAttr.getSplatValue<APInt>();
1812 if (!r.isZero()) {
1813 auto intTy = dyn_cast<mlir::IntegerType>(resultETy);
1814 auto const result =
1815 DivFoldAdaptor</*Ceil*/ false>::fold(l, r, intTy.isUnsigned());
1816 if (failed(result))
1817 return {};
1818 return DenseElementsAttr::get(resultTy, result.value());
1819 }
1820 }
1821
1822 return {};
1823}
1824
1825namespace {
1826// calculate lhs * rhs >> shift according to TOSA Spec
1827// return nullopt if result is not in range of int32_t when shift > 0
1828std::optional<APInt> mulInt(APInt lhs, APInt rhs, int32_t shift,
1829 unsigned bitwidth) {
1830 bool overflow = false;
1831 APInt result = lhs.sext(64).smul_ov(rhs.sext(64), overflow);
1832
1833 if (overflow)
1834 return std::nullopt;
1835
1836 if (shift > 0) {
1837 auto round = APInt(64, 1) << (shift - 1);
1838 result += round;
1839 result.ashrInPlace(shift);
1840 // REQUIRE(product >= minimum_s<i32_t>() && product <=
1841 // maximum_s<i32_t>())
1842 if (!(result.getSExtValue() >= INT32_MIN &&
1843 result.getSExtValue() <= INT32_MAX)) {
1844 // REQUIRE failed
1845 return std::nullopt;
1846 }
1847 }
1848
1849 return result.trunc(bitwidth);
1850}
1851
1852DenseElementsAttr mulBinaryFolder(DenseElementsAttr lhs, DenseElementsAttr rhs,
1853 RankedTensorType ty, int32_t shift) {
1854 // A constant result can only be built for a statically-shaped type.
1855 if (!ty.hasStaticShape())
1856 return {};
1857 if (rhs && lhs && rhs.isSplat() && lhs.isSplat()) {
1858 if (llvm::isa<IntegerType>(ty.getElementType())) {
1859 APInt l = lhs.getSplatValue<APInt>();
1860 APInt r = rhs.getSplatValue<APInt>();
1861
1862 if (shift == 0) {
1863 return DenseElementsAttr::get(ty, l * r);
1864 }
1865
1866 auto bitwidth = ty.getElementType().getIntOrFloatBitWidth();
1867 const std::optional<APInt> result = mulInt(l, r, shift, bitwidth);
1868 if (!result)
1869 return {};
1870 return DenseElementsAttr::get(ty, result.value());
1871 }
1872
1873 if (llvm::isa<FloatType>(ty.getElementType())) {
1874 APFloat l = lhs.getSplatValue<APFloat>();
1875 APFloat r = rhs.getSplatValue<APFloat>();
1876 APFloat result = l * r;
1877 return DenseElementsAttr::get(ty, result);
1878 }
1879 }
1880
1881 return {};
1882}
1883} // namespace
1884
1885OpFoldResult MulOp::fold(FoldAdaptor adaptor) {
1886 auto lhs = getInput1();
1887 auto rhs = getInput2();
1888 auto lhsTy = llvm::dyn_cast<RankedTensorType>(lhs.getType());
1889 auto rhsTy = llvm::dyn_cast<RankedTensorType>(rhs.getType());
1890 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1891 if (!lhsTy || !rhsTy || !resultTy)
1892 return {};
1893
1894 auto resultETy = resultTy.getElementType();
1895 auto lhsAttr =
1896 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1897 auto rhsAttr =
1898 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1899
1900 // Result right shift on i32_t data type only. For simplification,
1901 // synthesize a zero shift for other data type.
1902 int32_t shift = 0;
1903 if (resultETy.isInteger(32)) {
1904 ElementsAttr shift_elem;
1905 if (getShift().getImpl()) {
1906 if (!matchPattern(getShift(), m_Constant(&shift_elem)))
1907 // cannot be folded when the shift value is unknown.
1908 return {};
1909 shift = shift_elem.getValues<IntegerAttr>()[0].getInt();
1910 }
1911 }
1912
1913 if (rhsTy == resultTy && isSplatZero(resultETy, lhsAttr) &&
1914 resultTy.hasStaticShape())
1915 // constant values can only be resized if resulting type is static
1916 return lhsAttr.resizeSplat(resultTy);
1917 if (lhsTy == resultTy && isSplatZero(resultETy, rhsAttr) &&
1918 resultTy.hasStaticShape())
1919 return rhsAttr.resizeSplat(resultTy);
1920
1921 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1922 lhsTy.getShape(), rhsTy.getShape());
1923 if (isBroadcastable && rhsTy == resultTy &&
1924 isSplatOne(resultETy, lhsAttr, shift))
1925 return rhs;
1926 if (isBroadcastable && lhsTy == resultTy &&
1927 isSplatOne(resultETy, rhsAttr, shift))
1928 return lhs;
1929
1930 return mulBinaryFolder(lhsAttr, rhsAttr, resultTy, shift);
1931}
1932
1933OpFoldResult SubOp::fold(FoldAdaptor adaptor) {
1934 auto lhsTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
1935 auto rhsTy = llvm::dyn_cast<RankedTensorType>(getInput2().getType());
1936 auto resultTy = llvm::dyn_cast<RankedTensorType>(getType());
1937 if (!lhsTy || !rhsTy || !resultTy)
1938 return {};
1939
1940 // Cannot create an ElementsAttr from non-int/float/index types
1941 if (!lhsTy.getElementType().isIntOrIndexOrFloat() ||
1942 !rhsTy.getElementType().isIntOrIndexOrFloat())
1943 return {};
1944
1945 auto resultETy = resultTy.getElementType();
1946 auto lhsAttr =
1947 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1948 auto rhsAttr =
1949 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1950
1951 const bool isBroadcastable = OpTrait::util::staticallyKnownBroadcastable(
1952 lhsTy.getShape(), rhsTy.getShape());
1953 if (isBroadcastable && lhsTy == resultTy && isSplatZero(resultETy, rhsAttr))
1954 return getInput1();
1955
1956 if (!lhsAttr || !rhsAttr)
1957 return {};
1958
1959 return binaryFolder<SubFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1960}
1961
1962OpFoldResult GreaterOp::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<GreaterFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1973}
1974
1975OpFoldResult GreaterEqualOp::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
1982 if (!lhsAttr || !rhsAttr)
1983 return {};
1984
1985 return binaryFolder<GreaterEqualFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
1986}
1987
1988OpFoldResult EqualOp::fold(FoldAdaptor adaptor) {
1989 auto resultTy = llvm::cast<ShapedType>(getType());
1990 auto lhsAttr =
1991 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1());
1992 auto rhsAttr =
1993 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput2());
1994 Value lhs = getInput1();
1995 Value rhs = getInput2();
1996 auto lhsTy = llvm::cast<ShapedType>(lhs.getType());
1997
1998 // If we are comparing an integer value to itself it is always true. We
1999 // can not do this with float due to float values.
2000 if (llvm::isa<IntegerType>(lhsTy.getElementType()) && resultTy.hasRank() &&
2001 resultTy.hasStaticShape() && lhs == rhs) {
2002 return DenseElementsAttr::get(resultTy, true);
2003 }
2004
2005 if (!lhsAttr || !rhsAttr)
2006 return {};
2007
2008 return binaryFolder<EqualFoldAdaptor>(lhsAttr, rhsAttr, resultTy);
2009}
2010
2011OpFoldResult CastOp::fold(FoldAdaptor adaptor) {
2012 if (getInput().getType() == getType())
2013 return getInput();
2014
2015 auto operand = llvm::dyn_cast_if_present<ElementsAttr>(adaptor.getInput());
2016 if (!operand)
2017 return {};
2018
2019 auto inTy = llvm::cast<ShapedType>(getInput().getType());
2020 auto outTy = llvm::cast<ShapedType>(getType());
2021 if (!outTy.hasRank() || !outTy.hasStaticShape())
2022 return {};
2023 auto inETy = inTy.getElementType();
2024 auto outETy = outTy.getElementType();
2025
2026 if (operand.isSplat()) {
2027 if (llvm::isa<FloatType>(inETy) && llvm::isa<FloatType>(outETy)) {
2028 bool overflow;
2029 auto splatVal = operand.getSplatValue<APFloat>();
2030 auto &semantics = llvm::cast<FloatType>(outETy).getFloatSemantics();
2031 splatVal.convert(semantics, llvm::RoundingMode::NearestTiesToEven,
2032 &overflow);
2033 return SplatElementsAttr::get(outTy, splatVal);
2034 }
2035
2036 if (llvm::isa<IntegerType>(inETy) && llvm::isa<FloatType>(outETy)) {
2037 const bool unsign = llvm::cast<IntegerType>(inETy).isUnsignedInteger() ||
2038 adaptor.getInputUnsigned();
2039 APFloat splatVal(llvm::cast<FloatType>(outETy).getFloatSemantics());
2040 splatVal.convertFromAPInt(operand.getSplatValue<APInt>(), !unsign,
2041 llvm::RoundingMode::NearestTiesToEven);
2042 return SplatElementsAttr::get(outTy, splatVal);
2043 }
2044
2045 if (llvm::isa<FloatType>(inETy) && llvm::isa<IntegerType>(outETy)) {
2046 auto unsign = llvm::cast<IntegerType>(outETy).isUnsignedInteger();
2047 auto intVal = APSInt(
2048 llvm::cast<IntegerType>(outETy).getIntOrFloatBitWidth(), unsign);
2049 auto floatVal = operand.getSplatValue<APFloat>();
2050 bool exact;
2051 floatVal.convertToInteger(intVal, llvm::RoundingMode::NearestTiesToEven,
2052 &exact);
2053 return SplatElementsAttr::get(outTy, intVal);
2054 }
2055
2056 if (llvm::isa<IntegerType>(inETy) && llvm::isa<IntegerType>(outETy)) {
2057 const auto inIntType = llvm::cast<IntegerType>(inETy);
2058 const bool unsignIn =
2059 inIntType.isUnsignedInteger() || adaptor.getInputUnsigned();
2060 bool trunc =
2061 inETy.getIntOrFloatBitWidth() > outETy.getIntOrFloatBitWidth();
2062 auto intVal = operand.getSplatValue<APInt>();
2063 auto bitwidth = outETy.getIntOrFloatBitWidth();
2064
2065 // i1 types are boolean in TOSA
2066 if (outETy.isInteger(1)) {
2067 intVal = APInt(bitwidth, intVal.isZero() ? 0 : 1);
2068 } else if (trunc) {
2069 intVal = intVal.trunc(bitwidth);
2070 } else if (unsignIn || inIntType.isInteger(1)) {
2071 intVal = intVal.zext(bitwidth);
2072 } else {
2073 intVal = intVal.sext(bitwidth);
2074 }
2075
2076 return SplatElementsAttr::get(outTy, intVal);
2077 }
2078 }
2079
2080 return {};
2081}
2082
2083OpFoldResult ConstOp::fold(FoldAdaptor adaptor) { return getValuesAttr(); }
2084
2085OpFoldResult ConstShapeOp::fold(FoldAdaptor adaptor) { return getValuesAttr(); }
2086
2087#define REDUCE_FOLDER(OP) \
2088 OpFoldResult OP::fold(FoldAdaptor adaptor) { \
2089 ShapedType inputTy = llvm::cast<ShapedType>(getInput().getType()); \
2090 if (!inputTy.hasRank()) \
2091 return {}; \
2092 if (inputTy != getType()) \
2093 return {}; \
2094 if (inputTy.getRank() == 0 || inputTy.getDimSize(getAxis()) == 1) \
2095 return getInput(); \
2096 return {}; \
2097 }
2098
2099REDUCE_FOLDER(ReduceAllOp)
2100REDUCE_FOLDER(ReduceAnyOp)
2101REDUCE_FOLDER(ReduceMaxOp)
2102REDUCE_FOLDER(ReduceMinOp)
2103REDUCE_FOLDER(ReduceProductOp)
2104REDUCE_FOLDER(ReduceSumOp)
2105#undef REDUCE_FOLDER
2106
2107OpFoldResult ReshapeOp::fold(FoldAdaptor adaptor) {
2108 auto inputTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
2109 auto outputTy = llvm::dyn_cast<RankedTensorType>(getType());
2110
2111 if (!inputTy || !outputTy)
2112 return {};
2113
2114 // Fold when the input and output types are the same. This is only safe
2115 // when there is at most 1 dynamic dimension. For 2 or more dynamic
2116 // dimensions, there may still be a productive reshape.
2117 if (inputTy == outputTy && inputTy.getNumDynamicDims() < 2)
2118 return getInput1();
2119
2120 // reshape(reshape(x)) -> reshape(x)
2121 if (auto reshapeOp = llvm::dyn_cast_if_present<tosa::ReshapeOp>(
2122 getInput1().getDefiningOp())) {
2123 getInput1Mutable().assign(reshapeOp.getInput1());
2124 return getResult();
2125 }
2126
2127 // Cannot create an ElementsAttr from non-int/float/index types
2128 if (!inputTy.getElementType().isIntOrIndexOrFloat())
2129 return {};
2130
2131 // Constants must have static shape.
2132 if (!outputTy.hasStaticShape())
2133 return {};
2134
2135 // Reshaping a resource-backed constant only requires updating its type.
2136 if (auto operand = llvm::dyn_cast_if_present<DenseResourceElementsAttr>(
2137 adaptor.getInput1()))
2138 return DenseResourceElementsAttr::get(outputTy, operand.getRawHandle());
2139
2140 // reshape(const(x)) -> const(reshape-attr(x))
2141 if (auto operand =
2142 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1())) {
2143 // Okay to duplicate splat constants.
2144 if (operand.isSplat())
2145 return SplatElementsAttr::get(outputTy,
2146 operand.getSplatValue<Attribute>());
2147
2148 // Don't duplicate other constants.
2149 if (!getInput1().hasOneUse())
2150 return {};
2151
2153 if (!tosa::getConstShapeValues(getShape().getDefiningOp(), shapeVec))
2154 return {};
2155
2156 return operand.reshape(
2157 llvm::cast<ShapedType>(operand.getType()).clone(shapeVec));
2158 }
2159
2160 return {};
2161}
2162
2163OpFoldResult PadOp::fold(FoldAdaptor adaptor) {
2164 // If the pad is all zeros we can fold this operation away.
2165 if (adaptor.getPadding() && getInput1().getType() == getType()) {
2166 auto densePad = llvm::dyn_cast<DenseElementsAttr>(adaptor.getPadding());
2167 if (densePad && densePad.isSplat() &&
2168 densePad.getSplatValue<APInt>().isZero()) {
2169 return getInput1();
2170 }
2171 }
2172
2173 return {};
2174}
2175
2176// Fold away cases where a tosa.resize operation returns a copy
2177// of the input image.
2178OpFoldResult ResizeOp::fold(FoldAdaptor adaptor) {
2179 auto scaleAttr =
2180 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getScale());
2181 auto offsetAttr =
2182 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getOffset());
2183 auto borderAttr =
2184 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getBorder());
2185 if (!scaleAttr || !offsetAttr || !borderAttr) {
2186 return {};
2187 }
2188
2189 auto scale = tosa::convertFromIntAttr(scaleAttr, /* rank = */ 4);
2190 auto offset = tosa::convertFromIntAttr(offsetAttr, /* rank = */ 2);
2191 auto border = tosa::convertFromIntAttr(borderAttr, /* rank = */ 2);
2192 if (scale.size() != 4 || offset.size() != 2 || border.size() != 2) {
2193 return {};
2194 }
2195
2196 // Check unit scaling.
2197 if (scale[0] != scale[1] || scale[2] != scale[3]) {
2198 return {};
2199 }
2200
2201 // There should be no offset.
2202 if (offset[0] != 0 || offset[1] != 0) {
2203 return {};
2204 }
2205
2206 // There should be no border.
2207 if (border[0] != 0 || border[1] != 0) {
2208 return {};
2209 }
2210
2211 return foldToInputIfTypeMatches(getType(), getInput());
2212}
2213
2214OpFoldResult ReverseOp::fold(FoldAdaptor adaptor) {
2215 auto operand = getInput1();
2216 auto operandTy = llvm::cast<ShapedType>(operand.getType());
2217 auto axis = getAxis();
2218 // If the dim-length is 1, or reversing axis is unit-dim, also a no-op.
2219 const bool isSplatInput =
2220 llvm::isa_and_nonnull<SplatElementsAttr>(adaptor.getInput1());
2221 if (!operandTy.hasRank() ||
2222 (!isSplatInput && operandTy.getDimSize(axis) != 1))
2223 return {};
2224 return foldToInputIfTypeMatches(getType(), operand);
2225}
2226
2227OpFoldResult SliceOp::fold(FoldAdaptor adaptor) {
2228 auto inputTy = llvm::dyn_cast<RankedTensorType>(getInput1().getType());
2229 auto outputTy = llvm::dyn_cast<RankedTensorType>(getType());
2230
2231 if (!inputTy || !outputTy)
2232 return {};
2233
2234 if (inputTy == outputTy && inputTy.hasStaticShape())
2235 return getInput1();
2236
2237 // Check if this is a no-op slice (starts at 0 and size matches input)
2238
2239 DenseElementsAttr startElems;
2240 if (!matchPattern(getStart(), m_Constant(&startElems)))
2241 return {};
2242
2243 // Check if all start values are zero
2244 bool startIsZeros =
2245 llvm::all_of(startElems.getValues<APInt>(),
2246 [](const APInt &val) { return val.isZero(); });
2247
2248 if (startIsZeros) {
2249
2250 // Check if size matches input shape
2251 DenseElementsAttr sizeElems;
2252 if (!matchPattern(getSize(), m_Constant(&sizeElems)))
2253 return {};
2254
2255 auto inputShape = inputTy.getShape();
2256 auto sizeValues = sizeElems.getValues<APInt>();
2257
2258 bool sizeMatchesInput = true;
2259 for (const auto &[i, sizeVal] : llvm::enumerate(sizeValues)) {
2260 int64_t size = sizeVal.getSExtValue();
2261
2262 if (inputTy.isDynamicDim(i)) {
2263 // For dynamic dimensions, check for kInferableDimSize indicating full
2264 // dimension is sliced
2265 if (size != kInferableDimSize) {
2266 sizeMatchesInput = false;
2267 break;
2268 }
2269 } else {
2270 // For static dimensions, check that size must match exactly or be
2271 // kInferableDimSize indicating full dimension is sliced
2272 if (size != kInferableDimSize && size != inputShape[i]) {
2273 sizeMatchesInput = false;
2274 break;
2275 }
2276 }
2277 }
2278
2279 if (sizeMatchesInput)
2280 return getInput1();
2281 }
2282
2283 // The following checks require the input to be a constant
2284 if (!adaptor.getInput1())
2285 return {};
2286
2287 // Cannot create an ElementsAttr from non-int/float/index types
2288 if (!inputTy.getElementType().isIntOrIndexOrFloat() ||
2289 !outputTy.getElementType().isIntOrIndexOrFloat())
2290 return {};
2291
2292 auto operand = llvm::cast<ElementsAttr>(adaptor.getInput1());
2293 if (operand.isSplat() && outputTy.hasStaticShape()) {
2294 return SplatElementsAttr::get(outputTy, operand.getSplatValue<Attribute>());
2295 }
2296
2297 if (inputTy.hasStaticShape() && outputTy.hasStaticShape() &&
2298 outputTy.getNumElements() == 1) {
2299 llvm::SmallVector<uint64_t> indices =
2300 llvm::to_vector(startElems.getValues<uint64_t>());
2301 if (auto values = operand.tryGetValues<Attribute>())
2302 return SplatElementsAttr::get(outputTy, (*values)[indices]);
2303 }
2304
2305 return {};
2306}
2307
2308OpFoldResult tosa::SelectOp::fold(FoldAdaptor adaptor) {
2309 const Value pred = getPred();
2310 const Value onTrue = getOnTrue();
2311 const Value onFalse = getOnFalse();
2312
2313 const auto predTy = llvm::dyn_cast<RankedTensorType>(pred.getType());
2314 const auto onTrueTy = llvm::dyn_cast<RankedTensorType>(onTrue.getType());
2315 const auto onFalseTy = llvm::dyn_cast<RankedTensorType>(onFalse.getType());
2316 if (!predTy || !onTrueTy || !onFalseTy)
2317 return {};
2318
2319 const Type resultTy = getType();
2320
2321 const ArrayRef<int64_t> predShape = predTy.getShape();
2322 const ArrayRef<int64_t> onTrueShape = onTrueTy.getShape();
2323
2324 if (onTrue == onFalse && onTrueTy == resultTy &&
2325 OpTrait::util::staticallyKnownBroadcastable(predShape, onTrueShape))
2326 return onTrue;
2327
2328 auto predicate =
2329 llvm::dyn_cast_if_present<DenseIntElementsAttr>(adaptor.getInput1());
2330 if (!predicate)
2331 return {};
2332 if (!predicate.isSplat())
2333 return {};
2334
2335 const bool predicateValue = predicate.getSplatValue<APInt>().getBoolValue();
2336
2337 SmallVector<SmallVector<int64_t>, 3> shapes;
2338 shapes.emplace_back(predShape);
2339 shapes.emplace_back(onTrueShape);
2340 shapes.emplace_back(onFalseTy.getShape());
2341 const bool isBroadcastable =
2343
2344 if (predicateValue == true && onTrueTy == resultTy && isBroadcastable)
2345 return onTrue;
2346 if (predicateValue == false && onFalseTy == resultTy && isBroadcastable)
2347 return onFalse;
2348 return {};
2349}
2350
2351static LogicalResult verifyTileIsBroadcast(tosa::TileOp tileOp) {
2352 const auto inputType =
2353 dyn_cast<RankedTensorType>(tileOp.getInput1().getType());
2354 const auto outputType = dyn_cast<RankedTensorType>(tileOp.getType());
2355 if (!inputType || !outputType)
2356 return failure();
2357
2358 SmallVector<int64_t> multiples;
2359 if (failed(tileOp.getConstantMultiples(multiples)))
2360 return failure();
2361
2362 for (const auto [index, multiple] : llvm::enumerate(multiples)) {
2363 if (multiple == 1)
2364 continue;
2365 if (outputType.isDynamicDim(index))
2366 return failure();
2367 if (inputType.getDimSize(index) != 1)
2368 return failure();
2369 }
2370
2371 return success();
2372}
2373
2375 : public OpRewritePattern<tosa::TileOp> {
2376 using OpRewritePattern<tosa::TileOp>::OpRewritePattern;
2377
2378 LogicalResult matchAndRewrite(tosa::TileOp tileOp,
2379 PatternRewriter &rewriter) const override {
2380 Value tileOutput = tileOp.getOutput();
2381 if (!tileOutput.hasOneUse())
2382 return rewriter.notifyMatchFailure(tileOp,
2383 "tile output must have one use");
2384
2385 Operation *user = *tileOutput.user_begin();
2386 const bool isBinaryElementwise =
2387 user->getNumOperands() == 2 &&
2389 if (!isBinaryElementwise && !isa<tosa::MulOp>(user))
2390 return rewriter.notifyMatchFailure(
2391 tileOp, "consumer must be binary broadcastable");
2392
2393 if (failed(verifyTileIsBroadcast(tileOp)))
2394 return rewriter.notifyMatchFailure(
2395 tileOp, "tile must only expand statically-known singleton dims");
2396
2397 Value lhsOperand = user->getOperand(0);
2398 Value rhsOperand = user->getOperand(1);
2399 Value otherOperand = lhsOperand == tileOutput ? rhsOperand : lhsOperand;
2400 Value tileInput = tileOp.getInput1();
2401
2402 const ShapedType newOtherType = cast<ShapedType>(otherOperand.getType());
2403 const ShapedType newTileType = cast<ShapedType>(tileInput.getType());
2404 SmallVector<int64_t> broadcastedShape;
2406 newOtherType.getShape(), newTileType.getShape(), broadcastedShape);
2407
2408 const ShapedType outputType = cast<ShapedType>(user->getResultTypes()[0]);
2409 if (!llvm::equal(broadcastedShape, outputType.getShape()))
2410 return rewriter.notifyMatchFailure(
2411 tileOp, "tile output must be broadcastable to consumer operands");
2412
2413 rewriter.setInsertionPoint(user);
2414 IRMapping mapper;
2415 mapper.map(tileOutput, tileOp.getInput1());
2416 Operation *newUser = rewriter.clone(*user, mapper);
2417 rewriter.replaceOp(user, newUser->getResults());
2418 return success();
2419 }
2420};
2421
2422void TileOp::getCanonicalizationPatterns(RewritePatternSet &results,
2423 MLIRContext *context) {
2424 results.add<RemoveBroadcastTileFromBinaryElementwise>(context);
2425}
2426
2427OpFoldResult TileOp::fold(FoldAdaptor adaptor) {
2428 if (getInput1().getType() == getType()) {
2429 if (auto multiples = llvm::dyn_cast_if_present<DenseElementsAttr>(
2430 adaptor.getMultiples())) {
2431 if (multiples.isSplat() &&
2432 multiples.getSplatValue<APInt>().getSExtValue() == 1)
2433 return getInput1();
2434 if (auto int_array_attr =
2435 llvm::dyn_cast<DenseIntElementsAttr>(multiples)) {
2436 if (llvm::all_of(int_array_attr.getValues<APInt>(),
2437 [](APInt v) { return v.getSExtValue() == 1; }))
2438 return getInput1();
2439 }
2440 }
2441 }
2442 return {};
2443}
2444
2445OpFoldResult TransposeOp::fold(FoldAdaptor adaptor) {
2446 auto resultTy = llvm::cast<ShapedType>(getType());
2447
2448 // Transposing splat values just means reshaping.
2449 if (auto input =
2450 llvm::dyn_cast_if_present<DenseElementsAttr>(adaptor.getInput1())) {
2451 if (input.isSplat() && resultTy.hasRank() && resultTy.hasStaticShape() &&
2452 input.getType().getElementType() == resultTy.getElementType())
2453 return input.reshape(resultTy);
2454 }
2455
2456 // Transpose is not the identity transpose.
2457 const llvm::ArrayRef<int32_t> perms = getPerms();
2458
2459 if (!llvm::equal(llvm::seq<int32_t>(0, perms.size()), perms))
2460 return {};
2461
2462 return foldToInputIfTypeMatches(getType(), getInput1());
2463}
2464
2465OpFoldResult tosa::NegateOp::fold(FoldAdaptor adaptor) {
2466 // Element-wise negate(negate(x)) = x
2467 // iff all zero points are constant 0
2468 auto definingOp = getInput1().getDefiningOp<tosa::NegateOp>();
2469 if (!definingOp) {
2470 // defining op of input1 is not a negate, cannot fold
2471 return {};
2472 }
2473
2474 if (FailureOr<int64_t> maybeIZp = getInput1ZeroPoint();
2475 failed(maybeIZp) || *maybeIZp != 0) {
2476 // input1 zero point is not constant 0, cannot fold
2477 return {};
2478 }
2479 if (FailureOr<int64_t> maybeOZp = getOutputZeroPoint();
2480 failed(maybeOZp) || *maybeOZp != 0) {
2481 // output zero point is not constant 0, cannot fold
2482 return {};
2483 }
2484 if (FailureOr<int64_t> maybeIZp = definingOp.getInput1ZeroPoint();
2485 failed(maybeIZp) || *maybeIZp != 0) {
2486 // definingOp's input1 zero point is not constant 0, cannot fold
2487 return {};
2488 }
2489 if (FailureOr<int64_t> maybeOZp = definingOp.getOutputZeroPoint();
2490 failed(maybeOZp) || *maybeOZp != 0) {
2491 // definingOp's output zero point is not constant 0, cannot fold
2492 return {};
2493 }
2494
2495 return foldToInputIfTypeMatches(getType(), definingOp.getInput1());
2496}
2497
2498OpFoldResult tosa::AbsOp::fold(FoldAdaptor adaptor) {
2499 auto input = getInput1();
2500 // Element-wise abs(abs(x)) = abs(x)
2501 if (input.getDefiningOp<tosa::AbsOp>())
2502 return foldToInputIfTypeMatches(getType(), input);
2503
2504 return {};
2505}
2506
2507OpFoldResult tosa::ReciprocalOp::fold(FoldAdaptor adaptor) {
2508 auto input = adaptor.getInput1();
2509
2510 auto inputAttr = llvm::dyn_cast_if_present<DenseElementsAttr>(input);
2511 // Fold splat inputs only.
2512 if (!inputAttr || !inputAttr.isSplat())
2513 return {};
2514
2515 auto shapeType = llvm::cast<ShapedType>(getType());
2516 if (!shapeType.hasRank() || !shapeType.hasStaticShape())
2517 return {};
2518 if (auto floatType = llvm::dyn_cast<FloatType>(inputAttr.getElementType())) {
2519 auto floatVal = inputAttr.getSplatValue<APFloat>();
2520 return DenseElementsAttr::get(shapeType,
2521 ReciprocalOp::calcOneElement(floatVal));
2522 }
2523
2524 return {};
2525}
2526
2527template <typename Op, typename OpFoldAdaptor>
2529 auto input1ConstShape =
2530 dyn_cast<tosa::ConstShapeOp>(op->getInput().getDefiningOp());
2531 if (!input1ConstShape)
2532 return {};
2533
2534 const auto input1Attr = cast<DenseElementsAttr>(input1ConstShape.getValues());
2535
2536 return unaryFolder<OpFoldAdaptor>(input1Attr, input1Attr.getType(),
2537 /*foldDenseValues=*/true);
2538}
2539
2540template <typename Op, typename OpFoldAdaptor>
2542 auto input1ConstShape =
2543 dyn_cast<tosa::ConstShapeOp>(op->getInput1().getDefiningOp());
2544 auto input2ConstShape =
2545 dyn_cast<tosa::ConstShapeOp>(op->getInput2().getDefiningOp());
2546 if (!input1ConstShape || !input2ConstShape)
2547 return {};
2548
2549 const auto input1Attr = cast<DenseElementsAttr>(input1ConstShape.getValues());
2550 const auto input2Attr = cast<DenseElementsAttr>(input2ConstShape.getValues());
2551
2552 return binaryFolder<OpFoldAdaptor>(input1Attr, input2Attr,
2553 input1Attr.getType(),
2554 /*foldDenseValues=*/true);
2555}
2556
2557OpFoldResult tosa::DimOp::fold(FoldAdaptor adaptor) {
2558 const auto inputTy = llvm::dyn_cast<ShapedType>(getInput1().getType());
2559 if (!inputTy || !inputTy.hasRank())
2560 return {};
2561 const int32_t axis = getAxis();
2562 const int64_t dimSize = inputTy.getDimSize(axis);
2563 if (ShapedType::isDynamic(dimSize))
2564 return {};
2565
2566 OpBuilder builder(getContext());
2567 const auto resultAttrTy =
2568 RankedTensorType::get(/*rank=*/1, builder.getIndexType());
2569 return DenseElementsAttr::get(resultAttrTy, dimSize);
2570}
2571
2572OpFoldResult concatShapeFold(tosa::ConcatShapeOp *op) {
2573 auto const inputs = op->getInput();
2574
2575 if (inputs.empty())
2576 return {};
2577
2578 SmallVector<APInt> concatDims;
2579 concatDims.reserve(/*max elem*/ 64);
2580 for (auto const &v : inputs) {
2581 auto vConstShape = dyn_cast<tosa::ConstShapeOp>(v.getDefiningOp());
2582 if (!vConstShape)
2583 return {};
2584
2585 const auto vAttr = cast<DenseElementsAttr>(vConstShape.getValues());
2586 assert(vAttr);
2587
2588 auto const vAttrVals = vAttr.getValues<APInt>();
2589 for (auto const &v : vAttrVals) {
2590 concatDims.push_back(v);
2591 }
2592 }
2593
2594 auto *ctx = op->getContext();
2595 assert(ctx != nullptr && "ctx is nullptr");
2596 auto const rankedTy = RankedTensorType::get(
2597 {static_cast<int64_t>(concatDims.size())}, IndexType::get(ctx));
2598
2599 return DenseElementsAttr::get(rankedTy, concatDims);
2600}
2601
2602OpFoldResult sliceShapeFold(tosa::SliceShapeOp *op) {
2603 auto const input1 = op->getInput();
2604 auto const input2 = op->getStart();
2605 auto const input3 = op->getSize();
2606
2607 auto input1ConstShape = dyn_cast<tosa::ConstShapeOp>(input1.getDefiningOp());
2608
2609 if (!input1ConstShape)
2610 return {};
2611
2612 auto const input1Attr = cast<DenseElementsAttr>(input1ConstShape.getValues());
2613 if (!input1Attr)
2614 return {};
2615
2616 auto const input1Vals = input1Attr.getValues<APInt>();
2617 auto const totalInput1 = input1Vals.size();
2618
2619 auto const start = getSingleI64From1ElementTensor(input2);
2620 auto const size = getSingleI64From1ElementTensor(input3);
2621
2622 if (failed(start) || failed(size))
2623 return {};
2624
2625 auto const startV = static_cast<int32_t>(start.value());
2626 auto const sizeV = static_cast<int32_t>(size.value());
2627
2628 if ((sizeV <= 0) || (startV < 0) ||
2629 (static_cast<size_t>(startV + sizeV) > totalInput1))
2630 return {};
2631
2632 SmallVector<APInt> sliceOfInput;
2633 sliceOfInput.reserve(totalInput1);
2634
2635 for (auto i = startV; i < (startV + sizeV); i++) {
2636 sliceOfInput.push_back(input1Vals[i]);
2637 }
2638
2639 auto *ctx = op->getContext();
2640 assert(ctx != nullptr && "ctx is nullptr");
2641
2642 auto const rankedTy = RankedTensorType::get(
2643 {static_cast<int64_t>(sliceOfInput.size())}, IndexType::get(ctx));
2644
2645 return DenseElementsAttr::get(rankedTy, sliceOfInput);
2646}
2647
2648OpFoldResult tosa::AddShapeOp::fold(FoldAdaptor adaptor) {
2650}
2651
2652OpFoldResult tosa::SubShapeOp::fold(FoldAdaptor adaptor) {
2654}
2655
2656OpFoldResult tosa::MulShapeOp::fold(FoldAdaptor adaptor) {
2658}
2659
2660OpFoldResult tosa::DivCeilShapeOp::fold(FoldAdaptor adaptor) {
2661 return binaryFold<DivCeilShapeOp, ShapeDivFoldAdaptor</*Ceil*/ true>>(this);
2662}
2663
2664OpFoldResult tosa::DivFloorShapeOp::fold(FoldAdaptor adaptor) {
2665 return binaryFold<DivFloorShapeOp, ShapeDivFoldAdaptor</*Ceil*/ false>>(this);
2666}
2667
2668OpFoldResult tosa::ModShapeOp::fold(FoldAdaptor adaptor) {
2670}
2671
2672OpFoldResult tosa::MaxShapeOp::fold(FoldAdaptor adaptor) {
2674}
2675
2676OpFoldResult tosa::MinShapeOp::fold(FoldAdaptor adaptor) {
2678}
2679
2680OpFoldResult tosa::Exp2ShapeOp::fold(FoldAdaptor adaptor) {
2682}
2683
2684OpFoldResult tosa::Log2CeilShapeOp::fold(FoldAdaptor adaptor) {
2686}
2687
2688OpFoldResult tosa::Log2FloorShapeOp::fold(FoldAdaptor adaptor) {
2690}
2691
2692OpFoldResult tosa::ConcatShapeOp::fold(FoldAdaptor adaptor) {
2693 return concatShapeFold(this);
2694}
2695
2696OpFoldResult tosa::SliceShapeOp::fold(FoldAdaptor adaptor) {
2697 return sliceShapeFold(this);
2698}
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:171
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:175
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition Builders.h:94
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:571
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
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:63
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:794
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:102
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