MLIR 24.0.0git
TosaToLinalg.cpp
Go to the documentation of this file.
1//===- TosaToLinalg.cpp - Lowering Tosa to Linalg Dialect -----------------===//
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// These rewriters lower from the Tosa to the Linalg dialect.
10//
11//===----------------------------------------------------------------------===//
12
14#include "TosaToLinalgUtils.h"
26#include "mlir/IR/Matchers.h"
30#include "llvm/ADT/STLExtras.h"
31#include "llvm/ADT/Sequence.h"
32#include "llvm/ADT/SmallVectorExtras.h"
33
34#include <type_traits>
35
36using namespace mlir;
37using namespace mlir::tosa;
38
39template <typename OpTy>
41 TypeRange resultTypes,
42 ValueRange operands) {
43 typename OpTy::Properties properties{};
44 OpTy::populateDefaultProperties(
45 OperationName(OpTy::getOperationName(), builder.getContext()),
46 properties);
47 return OpTy::create(builder, loc, resultTypes, operands, properties,
48 /*discardableAttributes=*/{});
49}
50
51// Helper function to materialize the semantically correct compare and select
52// operations given a binary operation with a specific NaN propagation mode.
53//
54// In the case of "PROPAGATE" semantics no compare and selection is required and
55// this function does nothing.
56//
57// In the case of "IGNORE" semantics this function materializes a comparison of
58// the current operands to the op which will return true for any NaN
59// argument and then selects between the non-NaN operation argument and the
60// calculated result based on whether the lhs or rhs is NaN or not. In pseudo
61// code:
62//
63// In the case that the op is operating on non floating point types we ignore
64// the attribute completely, this is consistent with the TOSA spec which has
65// the following wording: "This attribute is ignored by non floating-point
66// types."
67//
68// binary<op>(lhs, rhs):
69// result = op(lhs, rhs)
70// if lhs == NaN return rhs
71// if rhs == NaN return lhs
72// return result
73template <typename OpTy>
74static Value
76 Value lhs, Value rhs, Value result) {
77 // NaN propagation has no meaning for non floating point types.
78 if (!isa<FloatType>(getElementTypeOrSelf(lhs)))
79 return result;
80
81 auto nanMode = op.getNanMode();
82 if (nanMode == NanPropagationMode::PROPAGATE)
83 return result;
84
85 // Unordered comparison of NaN against itself will always return true.
86 Value lhsIsNaN = arith::CmpFOp::create(rewriter, op.getLoc(),
87 arith::CmpFPredicate::UNO, lhs, lhs);
88 Value rhsIsNaN = arith::CmpFOp::create(rewriter, op.getLoc(),
89 arith::CmpFPredicate::UNO, rhs, rhs);
90 Value rhsOrResult =
91 arith::SelectOp::create(rewriter, op.getLoc(), lhsIsNaN, rhs, result);
92 return arith::SelectOp::create(rewriter, op.getLoc(), rhsIsNaN, lhs,
93 rhsOrResult);
94}
95
97 Operation *op, ValueRange args, ArrayRef<Type> resultTypes,
98 ConversionPatternRewriter &rewriter) {
99 Location loc = op->getLoc();
100 auto elementTy =
101 cast<ShapedType>(op->getOperand(0).getType()).getElementType();
102
103 // tosa::AbsOp
104 if (isa<tosa::AbsOp>(op) && isa<FloatType>(elementTy))
105 return createWithDefaultProperties<math::AbsFOp>(rewriter, loc, resultTypes,
106 args);
107
108 if (isa<tosa::AbsOp>(op) && isa<IntegerType>(elementTy)) {
109 auto zero = arith::ConstantOp::create(rewriter, loc,
110 rewriter.getZeroAttr(elementTy));
111 auto neg = arith::SubIOp::create(rewriter, loc, zero, args[0]);
112 return arith::MaxSIOp::create(rewriter, loc, args[0], neg);
113 }
114
115 // tosa::AddOp
116 if (isa<tosa::AddOp>(op) && isa<FloatType>(elementTy))
118 resultTypes, args);
119
120 if (isa<tosa::AddOp>(op) && isa<IntegerType>(elementTy))
122 resultTypes, args);
123
124 // tosa::SubOp
125 if (isa<tosa::SubOp>(op) && isa<FloatType>(elementTy))
127 resultTypes, args);
128
129 if (isa<tosa::SubOp>(op) && isa<IntegerType>(elementTy))
131 resultTypes, args);
132
133 // tosa::IntDivOp
134 if (isa<tosa::IntDivOp>(op) && isa<IntegerType>(elementTy))
136 resultTypes, args);
137
138 // tosa::ReciprocalOp
139 if (isa<tosa::ReciprocalOp>(op) && isa<FloatType>(elementTy)) {
140 auto one =
141 arith::ConstantOp::create(rewriter, loc, FloatAttr::get(elementTy, 1));
142 return arith::DivFOp::create(rewriter, loc, one, args[0]);
143 }
144
145 // tosa::MulOp
146 if (isa<tosa::MulOp>(op)) {
147 auto shiftVal = cast<tosa::MulOp>(op).getShift();
148 DenseElementsAttr shiftElem;
149 bool shiftIsConstant = true;
150 int32_t shift = 0;
151 if (matchPattern(shiftVal, m_Constant(&shiftElem)))
152 shift = shiftElem.getValues<IntegerAttr>()[0].getInt();
153 else
154 shiftIsConstant = false;
155
156 if (isa<FloatType>(elementTy)) {
157 if (shift != 0) {
158 (void)rewriter.notifyMatchFailure(op,
159 "Cannot have shift value for float");
160 return nullptr;
161 }
162 return arith::MulFOp::create(rewriter, loc, args[0], args[1]);
163 }
164
165 if (isa<IntegerType>(elementTy)) {
166 Value a = args[0];
167 Value b = args[1];
168
169 if (shift > 0 || !shiftIsConstant) {
170 Value shiftConst;
171 if (shiftIsConstant)
172 shiftConst = arith::ConstantIntOp::create(rewriter, loc, shift,
173 /*bitwidth=*/8);
174
175 if (!a.getType().isInteger(32))
176 a = arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(), a);
177
178 if (!b.getType().isInteger(32))
179 b = arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(), b);
180
181 auto shiftAmount = shiftIsConstant ? shiftConst : args[2];
182 auto roundingAttr = RoundingModeAttr::get(rewriter.getContext(),
183 RoundingMode::SINGLE_ROUND);
184 auto result =
185 tosa::ApplyScaleOp::create(rewriter, loc, rewriter.getI32Type(), a,
186 b, shiftAmount, roundingAttr);
187
188 return result;
189 }
190
191 int aWidth = a.getType().getIntOrFloatBitWidth();
192 int bWidth = b.getType().getIntOrFloatBitWidth();
193 int cWidth = resultTypes[0].getIntOrFloatBitWidth();
194
195 if (aWidth < cWidth)
196 a = arith::ExtSIOp::create(rewriter, loc, resultTypes[0], a);
197 if (bWidth < cWidth)
198 b = arith::ExtSIOp::create(rewriter, loc, resultTypes[0], b);
199
200 return arith::MulIOp::create(rewriter, loc, resultTypes, a, b);
201 }
202 }
203
204 // tosa::NegateOp
205 if (isa<tosa::NegateOp>(op)) {
206 auto negate = cast<tosa::NegateOp>(op);
207
208 int64_t inZp = 0, outZp = 0;
209 FailureOr<int64_t> maybeInZp = negate.getInput1ZeroPoint();
210 FailureOr<int64_t> maybeOutZp = negate.getOutputZeroPoint();
211 bool hasInZp = !failed(maybeInZp);
212 bool hasOutZp = !failed(maybeOutZp);
213 if (hasInZp)
214 inZp = *maybeInZp;
215 if (hasOutZp)
216 outZp = *maybeOutZp;
217
218 if (isa<FloatType>(elementTy))
219 return arith::NegFOp::create(rewriter, loc, resultTypes, args[0]);
220
221 if (isa<IntegerType>(elementTy)) {
222 Value zpAddValue;
223 Type intermediateType;
224 // Compute the maximum value that can occur in the intermediate buffer.
225 const int32_t inputBitWidth = elementTy.getIntOrFloatBitWidth();
226 int intermediateBitWidth = 64;
227
228 if (hasInZp && hasOutZp) {
229 // Compute the maximum value that can occur in the intermediate buffer.
230 const int64_t zpAdd = inZp + outZp;
231 const int64_t maxValue =
232 APInt::getSignedMaxValue(inputBitWidth).getSExtValue() +
233 std::abs(zpAdd) + 1;
234
235 // Convert that maximum value into the maximum bitwidth needed to
236 // represent it.
237 if (maxValue <= APInt::getSignedMaxValue(16).getSExtValue()) {
238 intermediateBitWidth = 16;
239 } else if (maxValue <= APInt::getSignedMaxValue(32).getSExtValue()) {
240 intermediateBitWidth = 32;
241 }
242
243 intermediateType = rewriter.getIntegerType(intermediateBitWidth);
244 zpAddValue = arith::ConstantOp::create(
245 rewriter, loc, rewriter.getIntegerAttr(intermediateType, zpAdd));
246 } else {
247 intermediateType = rewriter.getIntegerType(intermediateBitWidth);
248 Value arg1 = args[1];
249 Value arg2 = args[2];
250 // Avoid verifier-invalid no-op sign-extends; only widen when needed.
251 if (arg1.getType() != intermediateType)
252 arg1 = arith::ExtSIOp::create(rewriter, loc, intermediateType, arg1);
253 if (arg2.getType() != intermediateType)
254 arg2 = arith::ExtSIOp::create(rewriter, loc, intermediateType, arg2);
255 zpAddValue =
256 arith::AddIOp::create(rewriter, loc, intermediateType, arg1, arg2);
257 }
258
259 // The negation can be applied by doing:
260 // outputValue = inZp + outZp - inputValue
261 Value ext = args[0];
262 if (ext.getType() != intermediateType)
263 ext = arith::ExtSIOp::create(rewriter, loc, intermediateType, ext);
264 auto sub = arith::SubIOp::create(rewriter, loc, zpAddValue, ext);
265
266 // Clamp to the negation range.
268 rewriter, loc, intermediateType,
269 APInt::getSignedMinValue(inputBitWidth).getSExtValue());
271 rewriter, loc, intermediateType,
272 APInt::getSignedMaxValue(inputBitWidth).getSExtValue());
273 auto clamp = clampIntHelper(loc, sub, min, max, rewriter, false);
274
275 // Truncate to the final value, skipping no-op trunci when widths match.
276 if (clamp.getType() == elementTy)
277 return clamp;
278 return arith::TruncIOp::create(rewriter, loc, elementTy, clamp);
279 }
280 }
281
282 // tosa::BitwiseAndOp
283 if (isa<tosa::BitwiseAndOp>(op) && isa<IntegerType>(elementTy))
284 return arith::AndIOp::create(rewriter, loc, resultTypes, args);
285
286 // tosa::BitwiseOrOp
287 if (isa<tosa::BitwiseOrOp>(op) && isa<IntegerType>(elementTy))
288 return arith::OrIOp::create(rewriter, loc, resultTypes, args);
289
290 // tosa::BitwiseNotOp
291 if (isa<tosa::BitwiseNotOp>(op) && isa<IntegerType>(elementTy)) {
292 auto allOnesAttr = rewriter.getIntegerAttr(
293 elementTy, APInt::getAllOnes(elementTy.getIntOrFloatBitWidth()));
294 auto allOnes = arith::ConstantOp::create(rewriter, loc, allOnesAttr);
295 return arith::XOrIOp::create(rewriter, loc, resultTypes, args[0], allOnes);
296 }
297
298 // tosa::BitwiseXOrOp
299 if (isa<tosa::BitwiseXorOp>(op) && isa<IntegerType>(elementTy))
300 return arith::XOrIOp::create(rewriter, loc, resultTypes, args);
301
302 // tosa::LogicalLeftShiftOp
303 if (isa<tosa::LogicalLeftShiftOp>(op) && isa<IntegerType>(elementTy))
305 resultTypes, args);
306
307 // tosa::LogicalRightShiftOp
308 if (isa<tosa::LogicalRightShiftOp>(op) && isa<IntegerType>(elementTy))
310 resultTypes, args);
311
312 // tosa::ArithmeticRightShiftOp
313 if (isa<tosa::ArithmeticRightShiftOp>(op) && isa<IntegerType>(elementTy)) {
315 rewriter, loc, resultTypes, args);
316 bool round = cast<tosa::ArithmeticRightShiftOp>(op).getRound();
317 if (!round) {
318 return result;
319 }
320
321 Type i1Ty = IntegerType::get(rewriter.getContext(), /*width=*/1);
322 auto one = arith::ConstantOp::create(rewriter, loc,
323 IntegerAttr::get(elementTy, 1));
324 auto zero = arith::ConstantOp::create(rewriter, loc,
325 IntegerAttr::get(elementTy, 0));
326 auto i1zero =
327 arith::ConstantOp::create(rewriter, loc, IntegerAttr::get(i1Ty, 0));
328 auto i1one =
329 arith::ConstantOp::create(rewriter, loc, IntegerAttr::get(i1Ty, 1));
330
331 // Checking that input2 != 0
332 auto shiftValueGreaterThanZero = arith::CmpIOp::create(
333 rewriter, loc, arith::CmpIPredicate::sgt, args[1], zero);
334
335 // Checking for the last bit of input1 to be 1
336 auto subtract =
337 arith::SubIOp::create(rewriter, loc, resultTypes, args[1], one);
338 auto shifted =
339 arith::ShRSIOp::create(rewriter, loc, resultTypes, args[0], subtract)
340 ->getResults();
342 rewriter, loc, TypeRange{i1Ty}, shifted);
343 auto isInputOdd =
344 arith::AndIOp::create(rewriter, loc, i1Ty, truncated, i1one);
345 // shifted, truncated, isInputOdd can be poison when input2 is 0.
346 auto shouldRound = arith::SelectOp::create(
347 rewriter, loc, i1Ty, shiftValueGreaterThanZero, isInputOdd, i1zero);
348 auto extended =
349 arith::ExtUIOp::create(rewriter, loc, resultTypes, shouldRound);
350 return arith::AddIOp::create(rewriter, loc, resultTypes, result, extended);
351 }
352
353 // tosa::ClzOp
354 if (isa<tosa::ClzOp>(op) && isa<IntegerType>(elementTy)) {
355 return math::CountLeadingZerosOp::create(rewriter, loc, elementTy, args[0]);
356 }
357
358 // tosa::LogicalAnd
359 if (isa<tosa::LogicalAndOp>(op) && elementTy.isInteger(1))
360 return arith::AndIOp::create(rewriter, loc, resultTypes, args);
361
362 // tosa::LogicalNot
363 if (isa<tosa::LogicalNotOp>(op) && elementTy.isInteger(1)) {
364 auto one = arith::ConstantOp::create(rewriter, loc,
365 rewriter.getIntegerAttr(elementTy, 1));
366 return arith::XOrIOp::create(rewriter, loc, resultTypes, args[0], one);
367 }
368
369 // tosa::LogicalOr
370 if (isa<tosa::LogicalOrOp>(op) && elementTy.isInteger(1))
371 return arith::OrIOp::create(rewriter, loc, resultTypes, args);
372
373 // tosa::LogicalXor
374 if (isa<tosa::LogicalXorOp>(op) && elementTy.isInteger(1))
375 return arith::XOrIOp::create(rewriter, loc, resultTypes, args);
376
377 // tosa::PowOp
378 if (isa<tosa::PowOp>(op) && isa<FloatType>(elementTy))
380 resultTypes, args);
381
382 // tosa::RsqrtOp
383 if (isa<tosa::RsqrtOp>(op) && isa<FloatType>(elementTy))
385 resultTypes, args);
386
387 // tosa::LogOp
388 if (isa<tosa::LogOp>(op) && isa<FloatType>(elementTy))
390 resultTypes, args);
391
392 // tosa::ExpOp
393 if (isa<tosa::ExpOp>(op) && isa<FloatType>(elementTy))
395 resultTypes, args);
396
397 // tosa::SinOp
398 if (isa<tosa::SinOp>(op) && isa<FloatType>(elementTy))
400 resultTypes, args);
401
402 // tosa::CosOp
403 if (isa<tosa::CosOp>(op) && isa<FloatType>(elementTy))
405 resultTypes, args);
406
407 // tosa::TanhOp
408 if (isa<tosa::TanhOp>(op) && isa<FloatType>(elementTy))
410 resultTypes, args);
411
412 // tosa::ErfOp
413 if (isa<tosa::ErfOp>(op) && llvm::isa<FloatType>(elementTy))
415 resultTypes, args);
416
417 // tosa::GreaterOp
418 if (isa<tosa::GreaterOp>(op) && isa<FloatType>(elementTy))
419 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::OGT,
420 args[0], args[1]);
421
422 if (isa<tosa::GreaterOp>(op) && elementTy.isSignlessInteger())
423 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::sgt,
424 args[0], args[1]);
425
426 // tosa::GreaterEqualOp
427 if (isa<tosa::GreaterEqualOp>(op) && isa<FloatType>(elementTy))
428 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::OGE,
429 args[0], args[1]);
430
431 if (isa<tosa::GreaterEqualOp>(op) && elementTy.isSignlessInteger())
432 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::sge,
433 args[0], args[1]);
434
435 // tosa::EqualOp
436 if (isa<tosa::EqualOp>(op) && isa<FloatType>(elementTy))
437 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::OEQ,
438 args[0], args[1]);
439
440 if (isa<tosa::EqualOp>(op) && elementTy.isSignlessInteger())
441 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::eq,
442 args[0], args[1]);
443
444 // tosa::SelectOp
445 if (isa<tosa::SelectOp>(op)) {
446 elementTy = cast<ShapedType>(op->getOperand(1).getType()).getElementType();
447 if (isa<FloatType>(elementTy) || isa<IntegerType>(elementTy))
448 return arith::SelectOp::create(rewriter, loc, args[0], args[1], args[2]);
449 }
450
451 // tosa::MaximumOp
452 if (isa<tosa::MaximumOp>(op) && isa<FloatType>(elementTy)) {
453 auto max = arith::MaximumFOp::create(rewriter, loc, args[0], args[1]);
454 return materializeBinaryNanCheckIfRequired(llvm::cast<tosa::MaximumOp>(op),
455 rewriter, args[0], args[1], max);
456 }
457
458 if (isa<tosa::MaximumOp>(op) && elementTy.isSignlessInteger()) {
459 return arith::MaxSIOp::create(rewriter, loc, args[0], args[1]);
460 }
461
462 // tosa::MinimumOp
463 if (isa<tosa::MinimumOp>(op) && isa<FloatType>(elementTy)) {
464 auto min = arith::MinimumFOp::create(rewriter, loc, args[0], args[1]);
465 return materializeBinaryNanCheckIfRequired(llvm::cast<tosa::MinimumOp>(op),
466 rewriter, args[0], args[1], min);
467 }
468
469 if (isa<tosa::MinimumOp>(op) && elementTy.isSignlessInteger()) {
470 return arith::MinSIOp::create(rewriter, loc, args[0], args[1]);
471 }
472
473 // tosa::CeilOp
474 if (isa<tosa::CeilOp>(op) && isa<FloatType>(elementTy))
475 return createWithDefaultProperties<math::CeilOp>(rewriter, loc, resultTypes,
476 args);
477
478 // tosa::FloorOp
479 if (isa<tosa::FloorOp>(op) && isa<FloatType>(elementTy))
481 resultTypes, args);
482
483 // tosa::ClampOp
484 if (isa<tosa::ClampOp>(op) && isa<FloatType>(elementTy)) {
485 bool losesInfo = false;
486 auto clampOp = cast<tosa::ClampOp>(op);
487 APFloat minApf = cast<FloatAttr>(clampOp.getMinValAttr()).getValue();
488 APFloat maxApf = cast<FloatAttr>(clampOp.getMaxValAttr()).getValue();
489 minApf.convert(cast<FloatType>(elementTy).getFloatSemantics(),
490 APFloat::rmNearestTiesToEven, &losesInfo);
491 maxApf.convert(cast<FloatType>(elementTy).getFloatSemantics(),
492 APFloat::rmNearestTiesToEven, &losesInfo);
493 auto min = arith::ConstantOp::create(
494 rewriter, loc, elementTy, rewriter.getFloatAttr(elementTy, minApf));
495 auto max = arith::ConstantOp::create(
496 rewriter, loc, elementTy, rewriter.getFloatAttr(elementTy, maxApf));
497 auto result = clampFloatHelper(loc, args[0], min, max, rewriter);
498
499 const auto nanMode = clampOp.getNanMode();
500
501 // NaN propagation has no meaning for non floating point types.
502 if (!isa<FloatType>(elementTy))
503 return result;
504
505 // In the case of "PROPAGATE" semantics no compare and selection is
506 // required.
507 if (nanMode == NanPropagationMode::PROPAGATE)
508 return result;
509
510 // In the case of "IGNORE" semantics materialize a comparison
511 // of the current operand to the reduction which will return true for a NaN
512 // argument and then selects between the initial reduction value and the
513 // calculated result based on whether the argument is NaN or not. In pseudo
514 // code:
515 //
516 // reduce<op>(x, init):
517 // result = op(init, x)
518 // return init if x == NaN else result
519
520 // Unordered comparison of NaN against itself will always return true.
521 Value isNaN = arith::CmpFOp::create(
522 rewriter, op->getLoc(), arith::CmpFPredicate::UNO, args[0], args[0]);
523 // TOSA specifies that in "ignore" NaN mode the result is "min" if the input
524 // is NaN.
525 return arith::SelectOp::create(rewriter, op->getLoc(), isNaN, min, result);
526 }
527
528 if (isa<tosa::ClampOp>(op) && isa<IntegerType>(elementTy)) {
529 auto intTy = cast<IntegerType>(elementTy);
530 auto clampOp = cast<tosa::ClampOp>(op);
531 int64_t min =
532 cast<IntegerAttr>(clampOp.getMinValAttr()).getValue().getSExtValue();
533 int64_t max =
534 cast<IntegerAttr>(clampOp.getMaxValAttr()).getValue().getSExtValue();
535
536 int64_t minRepresentable = std::numeric_limits<int64_t>::min();
537 int64_t maxRepresentable = std::numeric_limits<int64_t>::max();
538 if (intTy.isUnsignedInteger()) {
539 minRepresentable = 0;
540 if (intTy.getIntOrFloatBitWidth() <= 63) {
541 maxRepresentable =
542 (int64_t)APInt::getMaxValue(intTy.getIntOrFloatBitWidth())
543 .getZExtValue();
544 }
545 } else if (intTy.getIntOrFloatBitWidth() <= 64) {
546 // Ensure that min & max fit into signed n-bit constants.
547 minRepresentable = APInt::getSignedMinValue(intTy.getIntOrFloatBitWidth())
548 .getSExtValue();
549 maxRepresentable = APInt::getSignedMaxValue(intTy.getIntOrFloatBitWidth())
550 .getSExtValue();
551 }
552 // Ensure that the bounds are representable as n-bit signed/unsigned
553 // integers.
554 min = std::max(min, minRepresentable);
555 max = std::max(max, minRepresentable);
556 min = std::min(min, maxRepresentable);
557 max = std::min(max, maxRepresentable);
558
559 auto minVal = arith::ConstantIntOp::create(rewriter, loc, min,
560 intTy.getIntOrFloatBitWidth());
561 auto maxVal = arith::ConstantIntOp::create(rewriter, loc, max,
562 intTy.getIntOrFloatBitWidth());
563 return clampIntHelper(loc, args[0], minVal, maxVal, rewriter,
564 intTy.isUnsignedInteger());
565 }
566
567 // tosa::SigmoidOp
568 if (isa<tosa::SigmoidOp>(op) && isa<FloatType>(elementTy)) {
569 auto one =
570 arith::ConstantOp::create(rewriter, loc, FloatAttr::get(elementTy, 1));
571 auto negate = arith::NegFOp::create(rewriter, loc, resultTypes, args[0]);
572 auto exp = mlir::math::ExpOp::create(rewriter, loc, resultTypes, negate);
573 auto added = arith::AddFOp::create(rewriter, loc, exp, one);
574 return arith::DivFOp::create(rewriter, loc, one, added);
575 }
576
577 // tosa::CastOp
578 if (isa<tosa::CastOp>(op)) {
579 Type srcTy = elementTy;
580 Type dstTy = resultTypes.front();
581 if (!srcTy.isIntOrFloat() || !dstTy.isIntOrFloat()) {
582 (void)rewriter.notifyMatchFailure(op, "unsupported type");
583 return nullptr;
584 }
585
586 bool bitExtend =
588
589 // With `input_unsigned`, the integer input is read as unsigned.
590 bool inputUnsigned = cast<tosa::CastOp>(op).getInputUnsigned();
591
592 if (srcTy == dstTy)
593 return args.front();
594
595 if (isa<FloatType>(srcTy) && isa<FloatType>(dstTy) && bitExtend)
597 resultTypes, args);
598
599 if (isa<FloatType>(srcTy) && isa<FloatType>(dstTy) && !bitExtend)
601 resultTypes, args);
602
603 // 1-bit integers need to be treated as signless.
604 if (srcTy.isInteger(1) && arith::UIToFPOp::areCastCompatible(srcTy, dstTy))
606 resultTypes, args);
607
608 if (srcTy.isInteger(1) && isa<IntegerType>(dstTy) && bitExtend)
610 resultTypes, args);
611
612 // Unsigned integers need an unrealized cast so that they can be passed
613 // to UIToFP.
614 if (srcTy.isUnsignedInteger() && isa<FloatType>(dstTy)) {
615 auto unrealizedCast =
616 UnrealizedConversionCastOp::create(
617 rewriter, loc,
618 rewriter.getIntegerType(srcTy.getIntOrFloatBitWidth()), args[0])
619 .getResult(0);
620 return arith::UIToFPOp::create(rewriter, loc, resultTypes[0],
621 unrealizedCast);
622 }
623
624 // Unsigned inputs are converted with UIToFP.
625 if (inputUnsigned && arith::UIToFPOp::areCastCompatible(srcTy, dstTy))
627 resultTypes, args);
628
629 // All other si-to-fp conversions should be handled by SIToFP.
630 if (arith::SIToFPOp::areCastCompatible(srcTy, dstTy))
631 return arith::SIToFPOp::create(rewriter, loc, resultTypes, args,
633
634 // Casting to boolean, floats need to only be checked as not-equal to zero.
635 if (isa<FloatType>(srcTy) && dstTy.isInteger(1)) {
636 Value zero = arith::ConstantOp::create(rewriter, loc,
637 rewriter.getFloatAttr(srcTy, 0.0));
638 return arith::CmpFOp::create(rewriter, loc, arith::CmpFPredicate::UNE,
639 args.front(), zero);
640 }
641
642 if (arith::FPToSIOp::areCastCompatible(srcTy, dstTy)) {
643 auto rounded = math::RoundEvenOp::create(rewriter, loc, args[0]);
644
645 const auto &fltSemantics = cast<FloatType>(srcTy).getFloatSemantics();
646 // Check whether neither int min nor int max can be represented in the
647 // input floating-point type due to too short exponent range.
648 if (static_cast<int>(dstTy.getIntOrFloatBitWidth()) - 1 >
649 APFloat::semanticsMaxExponent(fltSemantics)) {
650 // Use cmp + select to replace infinites by int min / int max. Other
651 // integral values can be represented in the integer space.
652 auto conv = arith::FPToSIOp::create(rewriter, loc, dstTy, rounded);
653 auto posInf = arith::ConstantOp::create(
654 rewriter, loc,
655 rewriter.getFloatAttr(getElementTypeOrSelf(srcTy),
656 APFloat::getInf(fltSemantics)));
657 auto negInf = arith::ConstantOp::create(
658 rewriter, loc,
659 rewriter.getFloatAttr(
661 APFloat::getInf(fltSemantics, /*Negative=*/true)));
662 auto overflow = arith::CmpFOp::create(
663 rewriter, loc, arith::CmpFPredicate::UEQ, rounded, posInf);
664 auto underflow = arith::CmpFOp::create(
665 rewriter, loc, arith::CmpFPredicate::UEQ, rounded, negInf);
666 auto intMin = arith::ConstantOp::create(
667 rewriter, loc,
668 rewriter.getIntegerAttr(
670 APInt::getSignedMinValue(dstTy.getIntOrFloatBitWidth())));
671 auto intMax = arith::ConstantOp::create(
672 rewriter, loc,
673 rewriter.getIntegerAttr(
675 APInt::getSignedMaxValue(dstTy.getIntOrFloatBitWidth())));
676 auto maxClamped =
677 arith::SelectOp::create(rewriter, loc, overflow, intMax, conv);
678 return arith::SelectOp::create(rewriter, loc, underflow, intMin,
679 maxClamped);
680 }
681
682 auto intMinFP = arith::ConstantOp::create(
683 rewriter, loc,
684 rewriter.getFloatAttr(
686 APInt::getSignedMinValue(dstTy.getIntOrFloatBitWidth())
687 .getSExtValue()));
688
689 // Check whether the mantissa has enough bits to represent int max.
690 if (cast<FloatType>(srcTy).getFPMantissaWidth() >=
691 dstTy.getIntOrFloatBitWidth() - 1) {
692 // Int min can also be represented since it is a power of two and thus
693 // consists of a single leading bit. Therefore we can clamp the input
694 // in the floating-point domain.
695
696 auto intMaxFP = arith::ConstantOp::create(
697 rewriter, loc,
698 rewriter.getFloatAttr(
700 APInt::getSignedMaxValue(dstTy.getIntOrFloatBitWidth())
701 .getSExtValue()));
702
703 Value clamped =
704 clampFloatHelper(loc, rounded, intMinFP, intMaxFP, rewriter);
705 return arith::FPToSIOp::create(rewriter, loc, dstTy, clamped);
706 }
707
708 // Due to earlier check we know exponant range is big enough to represent
709 // int min. We can therefore rely on int max + 1 being representable as
710 // well because it's just int min with a positive sign. So clamp the min
711 // value and compare against that to select the max int value if needed.
712 auto intMaxPlusOneFP = arith::ConstantOp::create(
713 rewriter, loc,
714 rewriter.getFloatAttr(
716 static_cast<double>(
717 APInt::getSignedMaxValue(dstTy.getIntOrFloatBitWidth())
718 .getSExtValue()) +
719 1.0f));
720
721 auto intMax = arith::ConstantOp::create(
722 rewriter, loc,
723 rewriter.getIntegerAttr(
725 APInt::getSignedMaxValue(dstTy.getIntOrFloatBitWidth())));
726 auto minClampedFP =
727 arith::MaximumFOp::create(rewriter, loc, rounded, intMinFP);
728 auto minClamped =
729 arith::FPToSIOp::create(rewriter, loc, dstTy, minClampedFP);
730 auto overflow = arith::CmpFOp::create(
731 rewriter, loc, arith::CmpFPredicate::UGE, rounded, intMaxPlusOneFP);
732 return arith::SelectOp::create(rewriter, loc, overflow, intMax,
733 minClamped);
734 }
735
736 // Casting to boolean, integers need to only be checked as not-equal to
737 // zero.
738 if (isa<IntegerType>(srcTy) && dstTy.isInteger(1)) {
739 Value zero = arith::ConstantIntOp::create(rewriter, loc, 0,
740 srcTy.getIntOrFloatBitWidth());
741 return arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::ne,
742 args.front(), zero);
743 }
744
745 // Unsigned inputs are zero-extended.
746 if (inputUnsigned && isa<IntegerType>(srcTy) && isa<IntegerType>(dstTy) &&
747 bitExtend)
749 resultTypes, args);
750
751 if (isa<IntegerType>(srcTy) && isa<IntegerType>(dstTy) && bitExtend)
752 return arith::ExtSIOp::create(rewriter, loc, resultTypes, args,
754
755 if (isa<IntegerType>(srcTy) && isa<IntegerType>(dstTy) && !bitExtend) {
756 return arith::TruncIOp::create(rewriter, loc, dstTy, args[0]);
757 }
758 }
759
760 (void)rewriter.notifyMatchFailure(
761 op, "unhandled op for linalg body calculation for elementwise op");
762 return nullptr;
763}
764
766
767// Emit an 'arith.constant' op for the given index if it has not been created
768// yet, or return an existing constant. This will prevent an excessive creation
769// of redundant constants, easing readability of emitted code for unit tests.
771 IndexPool &indexPool, int64_t index) {
772 auto [it, inserted] = indexPool.try_emplace(index);
773 if (inserted)
774 it->second =
775 arith::ConstantOp::create(rewriter, loc, rewriter.getIndexAttr(index));
776 return it->second;
777}
778
780 IndexPool &indexPool, Value tensor, int64_t index) {
781 auto indexValue = createIndex(rewriter, loc, indexPool, index);
782 return tensor::DimOp::create(rewriter, loc, tensor, indexValue).getResult();
783}
784
786 IndexPool &indexPool, Value tensor,
787 int64_t index) {
788 auto shapedType = dyn_cast<ShapedType>(tensor.getType());
789 assert(shapedType && shapedType.hasRank() && "expected a ranked shaped type");
790 assert(index >= 0 && index < shapedType.getRank() && "index out of bounds");
791 if (shapedType.isDynamicDim(index))
792 return getTensorDim(rewriter, loc, indexPool, tensor, index);
793 return rewriter.getIndexAttr(shapedType.getDimSize(index));
794}
795
796static bool operandsAndResultsRanked(Operation *operation) {
797 auto isRanked = [](Value value) {
798 return isa<RankedTensorType>(value.getType());
799 };
800 return llvm::all_of(operation->getOperands(), isRanked) &&
801 llvm::all_of(operation->getResults(), isRanked);
802}
803
804// Compute the runtime dimension size for dimension 'dim' of the output by
805// inspecting input 'operands', all of which are expected to have the same rank.
806// This function returns a pair {targetSize, masterOperand}.
807//
808// The runtime size of the output dimension is returned either as a statically
809// computed attribute or as a runtime SSA value.
810//
811// If the target size was inferred directly from one dominating operand, that
812// operand is returned in 'masterOperand'. If the target size is inferred from
813// multiple operands, 'masterOperand' is set to nullptr.
814static std::pair<OpFoldResult, Value>
816 ValueRange operands, int64_t dim) {
817 // If any input operand contains a static size greater than 1 for this
818 // dimension, that is the target size. An occurrence of an additional static
819 // dimension greater than 1 with a different value is undefined behavior.
820 for (auto operand : operands) {
821 auto size = cast<RankedTensorType>(operand.getType()).getDimSize(dim);
822 if (ShapedType::isStatic(size) && size > 1)
823 return {rewriter.getIndexAttr(size), operand};
824 }
825
826 // Filter operands with dynamic dimension
827 auto operandsWithDynamicDim =
828 llvm::filter_to_vector(operands, [&](Value operand) {
829 return cast<RankedTensorType>(operand.getType()).isDynamicDim(dim);
830 });
831
832 // If no operand has a dynamic dimension, it means all sizes were 1
833 if (operandsWithDynamicDim.empty())
834 return {rewriter.getIndexAttr(1), operands.front()};
835
836 // Emit code that computes the runtime size for this dimension. If there is
837 // only one operand with a dynamic dimension, it is considered the master
838 // operand that determines the runtime size of the output dimension.
839 auto targetSize =
840 getTensorDim(rewriter, loc, indexPool, operandsWithDynamicDim[0], dim);
841 if (operandsWithDynamicDim.size() == 1)
842 return {targetSize, operandsWithDynamicDim[0]};
843
844 // Calculate maximum size among all dynamic dimensions
845 for (size_t i = 1; i < operandsWithDynamicDim.size(); i++) {
846 auto nextSize =
847 getTensorDim(rewriter, loc, indexPool, operandsWithDynamicDim[i], dim);
848 targetSize = arith::MaxUIOp::create(rewriter, loc, targetSize, nextSize);
849 }
850 return {targetSize, nullptr};
851}
852
853// Compute the runtime output size for all dimensions. This function returns
854// a pair {targetShape, masterOperands}.
855static std::pair<SmallVector<OpFoldResult>, SmallVector<Value>>
857 IndexPool &indexPool, ValueRange operands) {
858 assert(!operands.empty());
859 auto rank = cast<RankedTensorType>(operands.front().getType()).getRank();
860 SmallVector<OpFoldResult> targetShape;
861 SmallVector<Value> masterOperands;
862 for (auto dim : llvm::seq<int64_t>(0, rank)) {
863 auto [targetSize, masterOperand] =
864 computeTargetSize(rewriter, loc, indexPool, operands, dim);
865 targetShape.push_back(targetSize);
866 masterOperands.push_back(masterOperand);
867 }
868 return {targetShape, masterOperands};
869}
870
872 IndexPool &indexPool, Value operand,
873 int64_t dim, OpFoldResult targetSize,
874 Value masterOperand) {
875 // Nothing to do if this is a static dimension
876 auto rankedTensorType = cast<RankedTensorType>(operand.getType());
877 if (!rankedTensorType.isDynamicDim(dim))
878 return operand;
879
880 // If the target size for this dimension was directly inferred by only taking
881 // this operand into account, there is no need to broadcast. This is an
882 // optimization that will prevent redundant control flow, and constitutes the
883 // main motivation for tracking "master operands".
884 if (operand == masterOperand)
885 return operand;
886
887 // Affine maps for 'linalg.generic' op
888 auto rank = rankedTensorType.getRank();
889 SmallVector<AffineExpr> affineExprs;
890 for (auto index : llvm::seq<int64_t>(0, rank)) {
891 auto affineExpr = index == dim ? rewriter.getAffineConstantExpr(0)
892 : rewriter.getAffineDimExpr(index);
893 affineExprs.push_back(affineExpr);
894 }
895 auto broadcastAffineMap =
896 AffineMap::get(rank, 0, affineExprs, rewriter.getContext());
897 auto identityAffineMap = rewriter.getMultiDimIdentityMap(rank);
898 SmallVector<AffineMap> affineMaps = {broadcastAffineMap, identityAffineMap};
899
900 // Check if broadcast is necessary
901 auto one = createIndex(rewriter, loc, indexPool, 1);
902 auto runtimeSize = getTensorDim(rewriter, loc, indexPool, operand, dim);
903 auto broadcastNecessary = arith::CmpIOp::create(
904 rewriter, loc, arith::CmpIPredicate::eq, runtimeSize, one);
905
906 // Emit 'then' region of 'scf.if'
907 auto emitThenRegion = [&](OpBuilder &opBuilder, Location loc) {
908 // It is not safe to cache constants across regions.
909 // New constants could potentially violate dominance requirements.
910 IndexPool localPool;
911
912 // Emit 'tensor.empty' op
913 SmallVector<OpFoldResult> outputTensorShape;
914 for (auto index : llvm::seq<int64_t>(0, rank)) {
915 auto size = index == dim ? targetSize
916 : getOrFoldTensorDim(rewriter, loc, localPool,
917 operand, index);
918 outputTensorShape.push_back(size);
919 }
920 Value outputTensor = tensor::EmptyOp::create(
921 opBuilder, loc, outputTensorShape, rankedTensorType.getElementType());
922
923 // Emit 'linalg.generic' op
924 auto resultTensor =
925 linalg::GenericOp::create(
926 opBuilder, loc, outputTensor.getType(), operand, outputTensor,
927 affineMaps, getNParallelLoopsAttrs(rank),
928 [&](OpBuilder &opBuilder, Location loc, ValueRange blockArgs) {
929 // Emit 'linalg.yield' op
930 linalg::YieldOp::create(opBuilder, loc, blockArgs.front());
931 })
932 .getResult(0);
933
934 // Cast to original operand type if necessary
935 auto castResultTensor = rewriter.createOrFold<tensor::CastOp>(
936 loc, operand.getType(), resultTensor);
937
938 // Emit 'scf.yield' op
939 scf::YieldOp::create(opBuilder, loc, castResultTensor);
940 };
941
942 // Emit 'else' region of 'scf.if'
943 auto emitElseRegion = [&](OpBuilder &opBuilder, Location loc) {
944 scf::YieldOp::create(opBuilder, loc, operand);
945 };
946
947 // Emit 'scf.if' op
948 auto ifOp = scf::IfOp::create(rewriter, loc, broadcastNecessary,
949 emitThenRegion, emitElseRegion);
950 return ifOp.getResult(0);
951}
952
954 IndexPool &indexPool, Value operand,
955 ArrayRef<OpFoldResult> targetShape,
956 ArrayRef<Value> masterOperands) {
957 int64_t rank = cast<RankedTensorType>(operand.getType()).getRank();
958 assert((int64_t)targetShape.size() == rank);
959 assert((int64_t)masterOperands.size() == rank);
960 for (auto index : llvm::seq<int64_t>(0, rank))
961 operand =
962 broadcastDynamicDimension(rewriter, loc, indexPool, operand, index,
963 targetShape[index], masterOperands[index]);
964 return operand;
965}
966
969 IndexPool &indexPool, ValueRange operands,
970 ArrayRef<OpFoldResult> targetShape,
971 ArrayRef<Value> masterOperands) {
972 // No need to broadcast for unary operations
973 if (operands.size() == 1)
974 return operands;
975
976 // No need to broadcast for static shape
977 bool hasDynamic = false;
978 for (auto op : operands) {
979 const auto tType = dyn_cast<RankedTensorType>(op.getType());
980 if (tType && !tType.hasStaticShape()) {
981 hasDynamic = true;
982 break;
983 }
984 }
985 if (!hasDynamic)
986 return operands;
987
988 // Broadcast dynamic dimensions operand by operand
989 return llvm::map_to_vector(operands, [&](Value operand) {
990 return broadcastDynamicDimensions(rewriter, loc, indexPool, operand,
991 targetShape, masterOperands);
992 });
993}
994
995static LogicalResult
996emitElementwiseComputation(ConversionPatternRewriter &rewriter, Location loc,
997 Operation *operation, ValueRange operands,
998 ArrayRef<OpFoldResult> targetShape,
999 const TypeConverter &converter) {
1000 // Generate output tensor
1001 auto resultType = cast_or_null<RankedTensorType>(
1002 converter.convertType(operation->getResultTypes().front()));
1003 if (!resultType) {
1004 return rewriter.notifyMatchFailure(operation, "failed to convert type");
1005 }
1006 Value outputTensor = tensor::EmptyOp::create(rewriter, loc, targetShape,
1007 resultType.getElementType());
1008
1009 // Create affine maps. Input affine maps broadcast static dimensions of size
1010 // 1. The output affine map is an identity map.
1011 //
1012 auto rank = resultType.getRank();
1013 auto affineMaps = llvm::map_to_vector(operands, [&](Value operand) {
1014 auto shape = cast<ShapedType>(operand.getType()).getShape();
1015 SmallVector<AffineExpr> affineExprs;
1016 for (auto it : llvm::enumerate(shape)) {
1017 // Prefer producting identity maps whenever possible (i.e. no broadcasting
1018 // needed) because some transforms (like reshape folding)
1019 // do not support affine constant exprs.
1020 bool requiresBroadcast =
1021 (it.value() == 1 && resultType.getDimSize(it.index()) != 1);
1022 auto affineExpr = requiresBroadcast
1023 ? rewriter.getAffineConstantExpr(0)
1024 : rewriter.getAffineDimExpr(it.index());
1025 affineExprs.push_back(affineExpr);
1026 }
1027 return AffineMap::get(rank, 0, affineExprs, rewriter.getContext());
1028 });
1029 affineMaps.push_back(rewriter.getMultiDimIdentityMap(rank));
1030
1031 // Emit 'linalg.generic' op
1032 bool encounteredError = false;
1033 auto linalgOp = linalg::GenericOp::create(
1034 rewriter, loc, outputTensor.getType(), operands, outputTensor, affineMaps,
1036 [&](OpBuilder &opBuilder, Location loc, ValueRange blockArgs) {
1038 operation, blockArgs.take_front(operation->getNumOperands()),
1039 {resultType.getElementType()}, rewriter);
1040 if (!opResult) {
1041 encounteredError = true;
1042 return;
1043 }
1044 linalg::YieldOp::create(opBuilder, loc, opResult);
1045 });
1046 if (encounteredError)
1047 return rewriter.notifyMatchFailure(
1048 operation, "unable to create linalg.generic body for elementwise op");
1049
1050 // Cast 'linalg.generic' result into original result type if needed
1051 auto castResult = rewriter.createOrFold<tensor::CastOp>(
1052 loc, resultType, linalgOp->getResult(0));
1053 rewriter.replaceOp(operation, castResult);
1054 return success();
1055}
1056
1058 ValueRange operands) {
1059 // Shift cannot broadcast
1060 if (isa<tosa::MulOp>(operation)) {
1061 DenseElementsAttr shiftElems;
1062 // Shift cannot broadcast when it is constant
1063 if (matchPattern(operation->getOperand(2), m_Constant(&shiftElems)))
1064 return operands.take_front(2);
1065 else
1066 return operands.take_front(3);
1067 }
1068 if (auto negate = dyn_cast<tosa::NegateOp>(operation)) {
1069 FailureOr<int64_t> maybeInZp = negate.getInput1ZeroPoint();
1070 FailureOr<int64_t> maybeOutZp = negate.getOutputZeroPoint();
1071 if (failed(maybeOutZp) && failed(maybeInZp))
1072 return operands;
1073 // Input1_zp and output_zp cannot broadcast when they are constants.
1074 return operands.take_front(1);
1075 }
1076 return operands;
1077}
1078
1079static LogicalResult
1081 ConversionPatternRewriter &rewriter,
1082 const TypeConverter &converter) {
1083
1084 // Collect op properties
1085 assert(operation->getNumResults() == 1 && "elementwise op expects 1 result");
1086 assert(operation->getNumOperands() >= 1 &&
1087 "elementwise op expects at least 1 operand");
1088 if (!operandsAndResultsRanked(operation))
1089 return rewriter.notifyMatchFailure(operation,
1090 "Unranked tensors not supported");
1091
1092 // Lower operation
1093 IndexPool indexPool;
1094 auto loc = operation->getLoc();
1095 auto operandsToBroadcast = getBroadcastableOperands(operation, operands);
1096 auto [targetShape, masterOperands] =
1097 computeTargetShape(rewriter, loc, indexPool, operandsToBroadcast);
1098 auto broadcastOperands =
1099 broadcastDynamicDimensions(rewriter, loc, indexPool, operandsToBroadcast,
1100 targetShape, masterOperands);
1101 return emitElementwiseComputation(rewriter, loc, operation, broadcastOperands,
1102 targetShape, converter);
1103}
1104
1105// Returns the constant initial value for a given reduction operation. The
1106// attribute type varies depending on the element type required.
1107static TypedAttr createInitialValueForReduceOp(Operation *op, Type elementTy,
1108 PatternRewriter &rewriter,
1109 bool allowNonFinites) {
1110 if (isa<tosa::ReduceSumOp>(op) && isa<FloatType>(elementTy))
1111 return rewriter.getFloatAttr(elementTy, 0.0);
1112
1113 if (isa<tosa::ReduceSumOp>(op) && isa<IntegerType>(elementTy))
1114 return rewriter.getIntegerAttr(elementTy, 0);
1115
1116 if (isa<tosa::ReduceProductOp>(op) && isa<FloatType>(elementTy))
1117 return rewriter.getFloatAttr(elementTy, 1.0);
1118
1119 if (isa<tosa::ReduceProductOp>(op) && isa<IntegerType>(elementTy))
1120 return rewriter.getIntegerAttr(elementTy, 1);
1121
1122 if (isa<tosa::ReduceMinOp>(op) && isa<FloatType>(elementTy))
1123 return rewriter.getFloatAttr(
1124 elementTy,
1125 getFloatMinMaxIdentity(cast<FloatType>(elementTy).getFloatSemantics(),
1126 /*negative=*/false, allowNonFinites));
1127
1128 if (isa<tosa::ReduceMinOp>(op) && isa<IntegerType>(elementTy))
1129 return rewriter.getIntegerAttr(
1130 elementTy, APInt::getSignedMaxValue(elementTy.getIntOrFloatBitWidth()));
1131
1132 if (isa<tosa::ReduceMaxOp>(op) && isa<FloatType>(elementTy))
1133 return rewriter.getFloatAttr(
1134 elementTy,
1135 getFloatMinMaxIdentity(cast<FloatType>(elementTy).getFloatSemantics(),
1136 /*negative=*/true, allowNonFinites));
1137
1138 if (isa<tosa::ReduceMaxOp>(op) && isa<IntegerType>(elementTy))
1139 return rewriter.getIntegerAttr(
1140 elementTy, APInt::getSignedMinValue(elementTy.getIntOrFloatBitWidth()));
1141
1142 if (isa<tosa::ReduceAllOp>(op) && elementTy.isInteger(1))
1143 return rewriter.getIntegerAttr(elementTy, APInt::getAllOnes(1));
1144
1145 if (isa<tosa::ReduceAnyOp>(op) && elementTy.isInteger(1))
1146 return rewriter.getIntegerAttr(elementTy, APInt::getZero(1));
1147
1148 if (isa<tosa::ArgMaxOp>(op) && isa<FloatType>(elementTy))
1149 return rewriter.getFloatAttr(
1150 elementTy,
1151 getFloatMinMaxIdentity(cast<FloatType>(elementTy).getFloatSemantics(),
1152 /*negative=*/true, allowNonFinites));
1153
1154 if (isa<tosa::ArgMaxOp>(op) && isa<IntegerType>(elementTy))
1155 return rewriter.getIntegerAttr(
1156 elementTy, APInt::getSignedMinValue(elementTy.getIntOrFloatBitWidth()));
1157
1158 return {};
1159}
1160
1161// Creates the body calculation for a reduction. The operations vary depending
1162// on the input type.
1164 ValueRange args,
1165 Type elementTy,
1166 PatternRewriter &rewriter) {
1167 Location loc = op->getLoc();
1168 if (isa<tosa::ReduceSumOp>(op) && isa<FloatType>(elementTy)) {
1170 rewriter, loc, TypeRange{elementTy}, args);
1171 }
1172
1173 if (isa<tosa::ReduceSumOp>(op) && isa<IntegerType>(elementTy)) {
1175 rewriter, loc, TypeRange{elementTy}, args);
1176 }
1177
1178 if (isa<tosa::ReduceProductOp>(op) && isa<FloatType>(elementTy)) {
1180 rewriter, loc, TypeRange{elementTy}, args);
1181 }
1182
1183 if (isa<tosa::ReduceProductOp>(op) && isa<IntegerType>(elementTy)) {
1185 rewriter, loc, TypeRange{elementTy}, args);
1186 }
1187
1188 if (isa<tosa::ReduceMinOp>(op) && isa<FloatType>(elementTy)) {
1189 return arith::MinimumFOp::create(rewriter, loc, args[0], args[1]);
1190 }
1191
1192 if (isa<tosa::ReduceMinOp>(op) && isa<IntegerType>(elementTy)) {
1193 return arith::MinSIOp::create(rewriter, loc, args[0], args[1]);
1194 }
1195
1196 if (isa<tosa::ReduceMaxOp>(op) && isa<FloatType>(elementTy)) {
1197 return arith::MaximumFOp::create(rewriter, loc, args[0], args[1]);
1198 }
1199
1200 if (isa<tosa::ReduceMaxOp>(op) && isa<IntegerType>(elementTy)) {
1201 return arith::MaxSIOp::create(rewriter, loc, args[0], args[1]);
1202 }
1203
1204 if (isa<tosa::ReduceAllOp>(op) && elementTy.isInteger(1))
1205 return arith::AndIOp::create(rewriter, loc, args);
1206
1207 if (isa<tosa::ReduceAnyOp>(op) && elementTy.isInteger(1))
1208 return arith::OrIOp::create(rewriter, loc, args);
1209
1210 return {};
1211}
1212
1213// Performs the match and rewrite for reduction operations. This includes
1214// declaring a correctly sized initial value, and the linalg.generic operation
1215// that reduces across the specified axis.
1216template <typename OpTy>
1217static LogicalResult reduceMatchAndRewriteHelper(OpTy op, uint64_t axis,
1218 PatternRewriter &rewriter,
1219 bool allowNonFinites) {
1220 auto loc = op->getLoc();
1221 auto inputTy = dyn_cast<RankedTensorType>(op->getOperand(0).getType());
1222 auto resultTy = dyn_cast<RankedTensorType>(op->getResult(0).getType());
1223 if (!inputTy || !resultTy)
1224 return rewriter.notifyMatchFailure(op, "unranked tensors not supported");
1225
1226 auto elementTy = resultTy.getElementType();
1227 Value input = op->getOperand(0);
1228
1229 // Figure out the accType if needed
1230 bool widenAccTy = std::is_same_v<OpTy, tosa::ReduceSumOp> &&
1231 isa<FloatType>(elementTy) &&
1232 cast<FloatType>(elementTy).isBF16();
1233 Type accTy = widenAccTy ? rewriter.getF32Type() : elementTy;
1234
1235 SmallVector<int64_t> reduceShape;
1236 SmallVector<Value> dynDims;
1237 for (unsigned i = 0; i < inputTy.getRank(); i++) {
1238 if (axis != i) {
1239 reduceShape.push_back(inputTy.getDimSize(i));
1240 if (inputTy.isDynamicDim(i))
1241 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
1242 }
1243 }
1244
1245 SmallVector<Value> inputs, outputs;
1246 inputs.push_back(input);
1247
1248 // First fill the output buffer with the init value.
1249 auto emptyTensor =
1250 tensor::EmptyOp::create(rewriter, loc, reduceShape, accTy, dynDims)
1251 .getResult();
1252
1253 auto fillValueAttr =
1254 createInitialValueForReduceOp(op, accTy, rewriter, allowNonFinites);
1255 if (!fillValueAttr)
1256 return rewriter.notifyMatchFailure(
1257 op, "No initial value found for reduction operation");
1258
1259 auto fillValue = arith::ConstantOp::create(rewriter, loc, fillValueAttr);
1260 auto filledTensor =
1261 linalg::FillOp::create(rewriter, loc, ValueRange{fillValue},
1262 ValueRange{emptyTensor})
1263 .result();
1264 outputs.push_back(filledTensor);
1265
1266 bool isNanIgnoreMode = false;
1267 if constexpr (std::is_same_v<OpTy, tosa::ReduceMinOp> ||
1268 std::is_same_v<OpTy, tosa::ReduceMaxOp>) {
1269 // NaN propagation has no meaning for non floating point types.
1270 if (isa<FloatType>(elementTy) &&
1271 op.getNanMode() == NanPropagationMode::IGNORE) {
1272 isNanIgnoreMode = true;
1273 // Because the TOSA spec requires the result be NaN iff all elements in
1274 // the reduction are NaN we can't simply perform a compare and select.
1275 // Additionally we have to keep track of whether we've seen any non-NaN
1276 // values and then do a final select based on this predicate.
1277 auto trueAttr = rewriter.getBoolAttr(true);
1278 auto trueValue = arith::ConstantOp::create(rewriter, loc, trueAttr);
1279 auto emptyBoolTensor =
1280 tensor::EmptyOp::create(rewriter, loc, reduceShape,
1281 trueValue.getType(), dynDims)
1282 .getResult();
1283 auto allResultsNaNTensor =
1284 linalg::FillOp::create(rewriter, loc, ValueRange{trueValue},
1285 ValueRange{emptyBoolTensor})
1286 .result();
1287 // Note that because the linalg::ReduceOp has two variadic arguments
1288 // (inputs and outputs) and it has the SameVariadicOperandSize trait we
1289 // need to have the same number of inputs and outputs.
1290 //
1291 // The second input isn't actually used anywhere since the value used to
1292 // update the NaN flag is calculated inside the body of the reduction and
1293 // then used to update an out value.
1294 // In order to satisfy type constraints we just pass another copy of the
1295 // input here.
1296 inputs.push_back(input);
1297 outputs.push_back(allResultsNaNTensor);
1298 }
1299 }
1300
1301 bool didEncounterError = false;
1302 linalg::LinalgOp linalgOp = linalg::ReduceOp::create(
1303 rewriter, loc, inputs, outputs, axis,
1304 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange blockArgs) {
1305 std::array<Value, 2> binaryArgs{
1306 blockArgs[0], isNanIgnoreMode ? blockArgs[2] : blockArgs[1]};
1307
1308 // If reduction type differs then extend (applicable to reduce_sum)
1309 if (binaryArgs[0].getType() != accTy)
1310 binaryArgs[0] = arith::ExtFOp::create(
1311 nestedBuilder, nestedLoc, TypeRange{accTy},
1312 ValueRange{binaryArgs[0]}, arith::ExtFOp::Properties{});
1313
1314 auto result = createLinalgBodyCalculationForReduceOp(op, binaryArgs,
1315 accTy, rewriter);
1316 if (result)
1317 didEncounterError = true;
1318
1319 SmallVector<Value> resultsToYield;
1320 if (isNanIgnoreMode) {
1321 auto inputValue = blockArgs[0];
1322 auto initialValue = blockArgs[2];
1323 auto oldAllResultsNanFlagValue = blockArgs[3];
1324
1325 // Unordered comparison of NaN against itself will always return true.
1326 Value isNaN = arith::CmpFOp::create(nestedBuilder, op->getLoc(),
1327 arith::CmpFPredicate::UNO,
1328 inputValue, inputValue);
1329 // If we've encountered a NaN, take the non-NaN value.
1330 auto selectOp = arith::SelectOp::create(nestedBuilder, op->getLoc(),
1331 isNaN, initialValue, result);
1332 // Update the flag which keeps track of whether we have seen a non-NaN
1333 // value.
1334 auto newAllResultsNanFlagValue = arith::AndIOp::create(
1335 nestedBuilder, op->getLoc(), oldAllResultsNanFlagValue, isNaN);
1336 resultsToYield.push_back(selectOp);
1337 resultsToYield.push_back(newAllResultsNanFlagValue);
1338 } else {
1339 resultsToYield.push_back(result);
1340 }
1341 linalg::YieldOp::create(nestedBuilder, loc, resultsToYield);
1342 });
1343
1344 if (!didEncounterError)
1345 return rewriter.notifyMatchFailure(
1346 op, "unable to create linalg.generic body for reduce op");
1347
1348 if (isNanIgnoreMode) {
1349 // Materialize a check to see whether we encountered any non-NaN values, if
1350 // we didn't we need to select a tensor of NaNs since the result will just
1351 // be the initial identity value propagated through all the compares and
1352 // selects inside the reduction.
1353
1354 // Create a tensor full of NaNs.
1355 auto nanValueAttr = rewriter.getFloatAttr(
1356 accTy,
1357 APFloat::getNaN(cast<FloatType>(elementTy).getFloatSemantics(), false));
1358 auto nanValue = arith::ConstantOp::create(rewriter, loc, nanValueAttr);
1359 auto emptyNanTensor =
1360 tensor::EmptyOp::create(rewriter, loc, reduceShape, accTy, dynDims)
1361 .getResult();
1362 auto nanFilledTensor =
1363 linalg::FillOp::create(rewriter, loc, ValueRange{nanValue},
1364 ValueRange{emptyNanTensor})
1365 .result();
1366
1367 // Create an empty tensor, non need to fill this since it will be
1368 // overwritten by the select.
1369 auto finalEmptyTensor =
1370 tensor::EmptyOp::create(rewriter, loc, reduceShape, accTy, dynDims)
1371 .getResult();
1372
1373 // Do a selection between the tensors akin to:
1374 // result = NaN if "all results NaN" else result.
1375 SmallVector<Value> ins, outs;
1376 ins.push_back(linalgOp->getOpResult(1));
1377 ins.push_back(nanFilledTensor);
1378 ins.push_back(linalgOp->getResult(0));
1379 outs.push_back(finalEmptyTensor);
1380 auto linalgSelect =
1381 linalg::ElementwiseOp::create(rewriter, op->getLoc(), ins, outs,
1382 mlir::linalg::ElementwiseKind::select);
1383 linalgOp = linalgSelect;
1384 }
1385
1386 // Truncate back to resultTy if needed
1387 Value reducedRes = linalgOp->getResult(0);
1388 if (widenAccTy) {
1389 auto resEmptyOp =
1390 tensor::EmptyOp::create(rewriter, loc, reduceShape, elementTy, dynDims)
1391 .getResult();
1392
1393 const unsigned reducedRank =
1394 cast<ShapedType>(reducedRes.getType()).getRank();
1395 auto identityMap = rewriter.getMultiDimIdentityMap(reducedRank);
1396 reducedRes =
1397 linalg::GenericOp::create(
1398 rewriter, loc, resEmptyOp.getType(), ValueRange{reducedRes},
1399 ValueRange{resEmptyOp},
1400 ArrayRef<AffineMap>{identityMap, identityMap},
1401 getNParallelLoopsAttrs(reducedRank),
1402 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange args) {
1403 Value truncf = arith::TruncFOp::create(nestedBuilder, nestedLoc,
1404 elementTy, args[0]);
1405 linalg::YieldOp::create(nestedBuilder, nestedLoc, truncf);
1406 })
1407 .getResults()[0];
1408 }
1409
1410 SmallVector<ReassociationExprs, 4> reassociationMap;
1411 uint64_t expandInputRank = cast<ShapedType>(reducedRes.getType()).getRank();
1412 reassociationMap.resize(expandInputRank);
1413
1414 for (uint64_t i = 0; i < expandInputRank; i++) {
1415 int32_t dimToPush = i > axis ? i + 1 : i;
1416 reassociationMap[i].push_back(rewriter.getAffineDimExpr(dimToPush));
1417 }
1418
1419 if (expandInputRank != 0) {
1420 int32_t expandedDim = axis < expandInputRank ? axis : expandInputRank - 1;
1421 reassociationMap[expandedDim].push_back(
1422 rewriter.getAffineDimExpr(expandedDim + 1));
1423 }
1424
1425 // Lower directly to `tensor::ExpandShapeOp` instead of `tosa::ReshapeOp`,
1426 // since here we know which dimension to expand, and `tosa::ReshapeOp` would
1427 // not have access to such information. This matters when handling dynamically
1428 // sized tensors.
1429 rewriter.replaceOpWithNewOp<tensor::ExpandShapeOp>(op, resultTy, reducedRes,
1430 reassociationMap);
1431 return success();
1432}
1433
1434// Insert missing leading batch dimensions, taking their sizes from `other`.
1436 Location loc, Value operand,
1437 Value other) {
1438 auto type = cast<RankedTensorType>(operand.getType());
1439 int64_t missingDims =
1440 cast<RankedTensorType>(other.getType()).getRank() - type.getRank();
1441 if (missingDims <= 0)
1442 return operand;
1443
1445 SmallVector<int64_t> dimensions;
1446 for (int64_t dim = 0; dim < missingDims; ++dim) {
1447 shape.push_back(tensor::getMixedSize(rewriter, loc, other, dim));
1448 dimensions.push_back(dim);
1449 }
1450 llvm::append_range(shape, tensor::getMixedSizes(rewriter, loc, operand));
1451 Value empty = tensor::EmptyOp::create(
1452 rewriter, loc, shape, type.getElementType(), type.getEncoding());
1453 return linalg::BroadcastOp::create(rewriter, loc, operand, empty, dimensions)
1454 .getResult()
1455 .front();
1456}
1457
1458// Expand an existing singleton batch dimension to `size`, preserving the rank.
1459// Missing dimensions are handled by broadcastMatMulTLeadingDimensions.
1460// linalg.broadcast inserts dimensions, so first remove the singleton dimension
1461// with a rank-reducing slice, then reinsert it at the target size.
1463 Location loc, Value operand,
1464 int64_t dim,
1465 OpFoldResult size) {
1466 auto type = cast<RankedTensorType>(operand.getType());
1467 SmallVector<int64_t> sliceShape(type.getShape());
1468 sliceShape.erase(sliceShape.begin() + dim);
1469 auto sliceType = RankedTensorType::get(sliceShape, type.getElementType(),
1470 type.getEncoding());
1472 rewriter, loc, operand, sliceType);
1473
1475 tensor::getMixedSizes(rewriter, loc, operand);
1476 shape[dim] = size;
1477 Value empty = tensor::EmptyOp::create(
1478 rewriter, loc, shape, type.getElementType(), type.getEncoding());
1479 return linalg::BroadcastOp::create(rewriter, loc, slice, empty,
1480 ArrayRef<int64_t>{dim})
1481 .getResult()
1482 .front();
1483}
1484
1485// Align the ranks, then broadcast each shared batch dimension independently.
1486static std::pair<Value, Value>
1488 Value a, Value b, int64_t batchRank) {
1489 int64_t aRank = cast<RankedTensorType>(a.getType()).getRank();
1490 int64_t bRank = cast<RankedTensorType>(b.getType()).getRank();
1491 int64_t firstSharedDim = std::max(aRank, bRank) - std::min(aRank, bRank);
1492 a = broadcastMatMulTLeadingDimensions(rewriter, loc, a, b);
1493 b = broadcastMatMulTLeadingDimensions(rewriter, loc, b, a);
1494
1495 IndexPool indexPool;
1496 // The inserted leading dimensions already match their partner's sizes.
1497 for (int64_t dim = firstSharedDim; dim < batchRank; ++dim) {
1498 auto aType = cast<RankedTensorType>(a.getType());
1499 auto bType = cast<RankedTensorType>(b.getType());
1500 int64_t aSize = aType.getDimSize(dim);
1501 int64_t bSize = bType.getDimSize(dim);
1502 if (aSize == bSize && ShapedType::isStatic(aSize))
1503 continue;
1504
1505 // Compute the shared broadcast target only for batch dimensions.
1506 // The matrix dimensions may differ between A and B.
1507 auto [size, masterOperand] =
1508 computeTargetSize(rewriter, loc, indexPool, ValueRange{a, b}, dim);
1509 if (aSize == 1) {
1510 a = broadcastMatMulTSingletonDimension(rewriter, loc, a, dim, size);
1511 continue;
1512 }
1513 if (bSize == 1) {
1514 b = broadcastMatMulTSingletonDimension(rewriter, loc, b, dim, size);
1515 continue;
1516 }
1517 a = broadcastDynamicDimension(rewriter, loc, indexPool, a, dim, size,
1518 masterOperand);
1519 b = broadcastDynamicDimension(rewriter, loc, indexPool, b, dim, size,
1520 masterOperand);
1521 }
1522 return {a, b};
1523}
1524
1527 Value a, Value b,
1528 RankedTensorType outputType) {
1529 const int64_t outputRank = outputType.getRank();
1530 const int64_t batchRank = outputRank - 2;
1531 auto normalizedOperands =
1532 normalizeMatMulTBatchDimensions(rewriter, loc, a, b, batchRank);
1533 a = normalizedOperands.first;
1534 b = normalizedOperands.second;
1535
1536 SmallVector<OpFoldResult> outputShape;
1537 outputShape.reserve(outputRank);
1538 for (int64_t batchDim = 0; batchDim < batchRank; ++batchDim)
1539 outputShape.push_back(tensor::getMixedSize(rewriter, loc, a, batchDim));
1540 outputShape.push_back(tensor::getMixedSize(rewriter, loc, a, outputRank - 2));
1541 outputShape.push_back(tensor::getMixedSize(rewriter, loc, b, outputRank - 2));
1542 SmallVector<Value> dynamicDims;
1543 for (auto [dim, size] : llvm::enumerate(outputShape))
1544 if (outputType.isDynamicDim(dim))
1545 dynamicDims.push_back(
1546 getValueOrCreateConstantIndexOp(rewriter, loc, size));
1547
1548 Value zero = arith::ConstantOp::create(
1549 rewriter, loc, rewriter.getZeroAttr(outputType.getElementType()));
1550 Value emptyTensor = tensor::EmptyOp::create(
1551 rewriter, loc, outputType.getShape(), outputType.getElementType(),
1552 condenseValues(dynamicDims));
1553 Value zeroTensor = linalg::FillOp::create(rewriter, loc, ValueRange{zero},
1554 ValueRange{emptyTensor})
1555 .result();
1556
1557 return {a, b, zeroTensor};
1558}
1559
1560namespace {
1561// Linalg has quantized matmul and batch matmul operations, but neither has a
1562// transpose-B variant. Lower nonzero zero points separately to linalg.generic
1563// so the reduction can accumulate (A - aZp) * (B - bZp).
1564class QuantizedMatMulTConverter : public OpConversionPattern<tosa::MatMulTOp> {
1565public:
1566 using OpConversionPattern<tosa::MatMulTOp>::OpConversionPattern;
1567 LogicalResult
1568 matchAndRewrite(tosa::MatMulTOp op, OpAdaptor adaptor,
1569 ConversionPatternRewriter &rewriter) const final {
1570 Location loc = op.getLoc();
1571 auto aType = dyn_cast<RankedTensorType>(adaptor.getA().getType());
1572 auto bType = dyn_cast<RankedTensorType>(adaptor.getB().getType());
1573 auto outputType = dyn_cast<RankedTensorType>(op.getType());
1574 if (!aType || !bType || !outputType)
1575 return rewriter.notifyMatchFailure(op, "only supports ranked tensors");
1576
1577 FailureOr<int64_t> maybeAZp = op.getAZeroPoint();
1578 FailureOr<int64_t> maybeBZp = op.getBZeroPoint();
1579 if (failed(maybeAZp))
1580 return rewriter.notifyMatchFailure(
1581 op, "input A zero point cannot be statically determined");
1582 if (failed(maybeBZp))
1583 return rewriter.notifyMatchFailure(
1584 op, "input B zero point cannot be statically determined");
1585
1586 const int64_t aZpVal = *maybeAZp;
1587 const int64_t bZpVal = *maybeBZp;
1588
1589 if (aZpVal == 0 && bZpVal == 0)
1590 return rewriter.notifyMatchFailure(
1591 op, "requires at least one nonzero zero point");
1592
1593 const int64_t outputRank = outputType.getRank();
1594 const int64_t batchRank = outputRank - 2;
1595 auto [a, b, zeroTensor] = prepareMatMulTOperands(
1596 rewriter, loc, adaptor.getA(), adaptor.getB(), outputType);
1597 Type outputElementType = outputType.getElementType();
1598
1599 int64_t loopRank = outputRank + 1;
1600 SmallVector<AffineExpr> dimensions =
1601 llvm::map_to_vector(llvm::seq<int64_t>(0, loopRank), [&](int64_t dim) {
1602 return rewriter.getAffineDimExpr(dim);
1603 });
1604 SmallVector<AffineExpr> aMap(dimensions.begin(),
1605 dimensions.begin() + batchRank);
1606 aMap.push_back(dimensions[batchRank]);
1607 aMap.push_back(dimensions[batchRank + 2]);
1608 SmallVector<AffineExpr> bMap(dimensions.begin(),
1609 dimensions.begin() + batchRank);
1610 bMap.push_back(dimensions[batchRank + 1]);
1611 bMap.push_back(dimensions[batchRank + 2]);
1612 SmallVector<AffineExpr> outputMap(dimensions.begin(),
1613 dimensions.begin() + batchRank);
1614 outputMap.push_back(dimensions[batchRank]);
1615 outputMap.push_back(dimensions[batchRank + 1]);
1616 SmallVector<AffineMap> indexingMaps = {
1617 AffineMap::get(loopRank, 0, aMap, rewriter.getContext()),
1618 AffineMap::get(loopRank, 0, bMap, rewriter.getContext()),
1619 AffineMap::get(loopRank, 0, outputMap, rewriter.getContext())};
1620 SmallVector<utils::IteratorType> iteratorTypes(
1621 loopRank, utils::IteratorType::parallel);
1622 iteratorTypes.back() = utils::IteratorType::reduction;
1623
1624 auto generic = linalg::GenericOp::create(
1625 rewriter, loc, outputType, ValueRange{a, b}, zeroTensor, indexingMaps,
1626 iteratorTypes,
1627 [=](OpBuilder &builder, Location nestedLoc, ValueRange args) {
1628 auto extendToOutputType = [&](Value value) {
1629 if (value.getType() == outputElementType)
1630 return value;
1631 return arith::ExtSIOp::create(builder, nestedLoc, outputElementType,
1632 value)
1633 .getResult();
1634 };
1635
1636 Value aValue = extendToOutputType(args[0]);
1637 Value bValue = extendToOutputType(args[1]);
1638 Value aZp = arith::ConstantOp::create(
1639 builder, nestedLoc,
1640 builder.getIntegerAttr(outputElementType, aZpVal));
1641 Value bZp = arith::ConstantOp::create(
1642 builder, nestedLoc,
1643 builder.getIntegerAttr(outputElementType, bZpVal));
1644 Value adjustedA =
1645 arith::SubIOp::create(builder, nestedLoc, aValue, aZp);
1646 Value adjustedB =
1647 arith::SubIOp::create(builder, nestedLoc, bValue, bZp);
1648 Value product =
1649 arith::MulIOp::create(builder, nestedLoc, adjustedA, adjustedB);
1650 Value sum =
1651 arith::AddIOp::create(builder, nestedLoc, args[2], product);
1652 linalg::YieldOp::create(builder, nestedLoc, sum);
1653 });
1654 rewriter.replaceOp(op, generic.getResult(0));
1655 return success();
1656 }
1657};
1658
1659template <typename SrcOp>
1660class PointwiseConverter : public OpConversionPattern<SrcOp> {
1661public:
1662 using OpConversionPattern<SrcOp>::OpConversionPattern;
1663 using typename OpConversionPattern<SrcOp>::OpAdaptor;
1664
1665 LogicalResult
1666 matchAndRewrite(SrcOp op, OpAdaptor operands,
1667 ConversionPatternRewriter &rewriter) const final {
1669 op, operands.getOperands(), rewriter, *this->getTypeConverter());
1670 }
1671};
1672
1673// Collapse tensor<1xiN> into tensor<iN>
1674// E.g. tensor.collapse_shape %arg1 [] : tensor<1xi16> into tensor<i16>
1675static Value collapse1xNTensorToN(PatternRewriter &rewriter, Value input,
1676 Location loc) {
1678 // Create the collapsed type
1679 auto inputType = cast<RankedTensorType>(input.getType());
1680 auto elemType = inputType.getElementType();
1681 auto collapsedType = RankedTensorType::get({}, elemType);
1682 // Emit the collapse op
1683 return tensor::CollapseShapeOp::create(rewriter, loc, collapsedType, input,
1684 reassociation);
1685}
1686
1688convertToI8(const llvm::SmallVector<int32_t> &input) {
1690 output.reserve(input.size());
1691
1692 for (auto v : llvm::map_range(
1693 input, [](int32_t val) { return static_cast<int8_t>(val); })) {
1694 output.push_back(v);
1695 }
1696 return output;
1697}
1698
1699// The shift or multiplier may be either constant or non-constant, depending on
1700// whether dynamic extension is enabled.
1701// - If the shift or multiplier is non-constant, add it as an input to
1702// linalg::GenericOp by:
1703// 1. Pushing it into 'genericInputs'.
1704// 2. Appending a corresponding affine map to 'indexingMaps'.
1705// - If the shift or multiplier is constant, set 'constant' instead.
1706static void setupLinalgGenericOpInputAndIndexingMap(
1708 SmallVector<Value, 4> &genericInputs, SmallVector<AffineMap> &indexingMaps,
1709 bool isConstant, tosa::RescaleOp op, Value &constant, int64_t &arg,
1710 bool isShift = false) {
1711
1712 auto loc = op.getLoc();
1713 auto inputTy = cast<ShapedType>(op.getInput().getType());
1714 unsigned rank = inputTy.getRank();
1715 SmallVector<AffineExpr, 2> exprs = {rewriter.getAffineDimExpr(rank - 1)};
1716
1717 if (isConstant) {
1718 // If we are rescaling per-channel then we need to store the
1719 // values in a buffer.
1720 if (values.size() == 1) {
1721 IntegerAttr intAttr = isShift
1722 ? rewriter.getI8IntegerAttr(values.front())
1723 : rewriter.getI32IntegerAttr(values.front());
1724 constant = arith::ConstantOp::create(rewriter, loc, intAttr);
1725 } else {
1726 auto elementType =
1727 isShift ? rewriter.getIntegerType(8) : rewriter.getI32Type();
1728 auto tensorType = RankedTensorType::get(
1729 {static_cast<int64_t>(values.size())}, elementType);
1730 DenseIntElementsAttr EltAttr;
1731 if (isShift)
1732 EltAttr = DenseIntElementsAttr::get(tensorType, convertToI8(values));
1733 else
1734 EltAttr = DenseIntElementsAttr::get(tensorType, values);
1735 genericInputs.push_back(
1736 arith::ConstantOp::create(rewriter, loc, EltAttr));
1737 indexingMaps.push_back(AffineMap::get(/*dimCount=*/rank,
1738 /*symbolCount=*/0, exprs,
1739 rewriter.getContext()));
1740 }
1741 } else {
1742 // If we are not rescaling per-channel then we need to collapse 1xN to N
1743 // and push broadcastMap.
1744 auto operand = isShift ? op.getShift() : op.getMultiplier();
1745 auto tensorType = dyn_cast<RankedTensorType>(operand.getType());
1746 if (tensorType && tensorType.hasStaticShape() &&
1747 tensorType.getShape()[0] == 1) {
1748 // broadcastMap = affine_map<(d0, d1) -> ()>
1749 // It would affect as broadcast for scalar values in linalg::GenericOp.
1750 AffineMap broadcastMap =
1751 AffineMap::get(rank, 0, {}, rewriter.getContext());
1752 genericInputs.push_back(collapse1xNTensorToN(rewriter, operand, loc));
1753 indexingMaps.push_back(broadcastMap);
1754 } else {
1755 genericInputs.push_back(operand);
1756 indexingMaps.push_back(AffineMap::get(/*dimCount=*/rank,
1757 /*symbolCount=*/0, exprs,
1758 rewriter.getContext()));
1759 }
1760 }
1761 arg = indexingMaps.size() - 1;
1762}
1763
1764// Return the extended Zp to be used in subsequent arithmetic operations.
1765static Value getExtendZp(OpBuilder &builder, Type valueTy,
1766 FailureOr<int64_t> maybeZp, Location loc,
1767 ValueRange blockArgs, int64_t zpArg,
1768 bool isOutputZp = false) {
1769 Value result;
1770 const int32_t bitwidth = valueTy.getIntOrFloatBitWidth();
1771 const uint32_t attrBitwidth =
1772 isOutputZp ? 32 : (bitwidth > 32 ? bitwidth : 32);
1773 auto extendType = builder.getIntegerType(attrBitwidth);
1774 // The Zp value can be either constant or non-constant, depending on
1775 // whether dynamic extension is enabled.
1776 // If 'maybeZp' fails, it indicates that Zp is non-constant and will
1777 // be passed as an input to linalg::GenericOp.
1778 if (failed(maybeZp)) {
1779 result = blockArgs[zpArg];
1780 auto zpTy = result.getType();
1781 if (zpTy.getIntOrFloatBitWidth() < attrBitwidth) {
1782 // For ExtUIOp, the input must be signless.
1783 // UnrealizedConversionCastOp will cast the input to signless type.
1784 if (zpTy.isUnsignedInteger()) {
1785 result =
1786 UnrealizedConversionCastOp::create(
1787 builder, loc,
1788 builder.getIntegerType(zpTy.getIntOrFloatBitWidth()), result)
1789 .getResult(0);
1790 }
1791 if (zpTy.isUnsignedInteger()) {
1792 return arith::ExtUIOp::create(builder, loc, extendType, result);
1793 } else {
1794 return arith::ExtSIOp::create(builder, loc, extendType, result);
1795 }
1796 }
1797 } else {
1798 return arith::ConstantOp::create(builder, loc,
1799 IntegerAttr::get(extendType, *maybeZp));
1800 }
1801 return result;
1802}
1803
1804class RescaleConverter : public OpRewritePattern<tosa::RescaleOp> {
1805public:
1806 using OpRewritePattern<tosa::RescaleOp>::OpRewritePattern;
1807
1808 LogicalResult matchAndRewrite(tosa::RescaleOp op,
1809 PatternRewriter &rewriter) const final {
1810 auto loc = op.getLoc();
1811 auto input = op.getInput();
1812 auto inputTy = cast<ShapedType>(op.getInput().getType());
1813 auto outputTy = cast<ShapedType>(op.getOutput().getType());
1814 unsigned rank = inputTy.getRank();
1815
1816 // This is an illegal configuration. terminate and log an error
1817 if (op.getRoundingMode() == RoundingMode::INEXACT_ROUND)
1818 return rewriter.notifyMatchFailure(
1819 op, "tosa.rescale with rounding mode = 'INEXACT_ROUND' is not "
1820 "currently supported");
1821 if (op.getRoundingMode() == RoundingMode::DOUBLE_ROUND && !op.getScale32())
1822 return rewriter.notifyMatchFailure(
1823 op, "tosa.rescale requires scale32 for double_round to be true");
1824
1825 if (!isa<IntegerType>(inputTy.getElementType()))
1826 return rewriter.notifyMatchFailure(op, "only support integer type");
1827
1828 SmallVector<Value> dynDims;
1829 for (int i = 0; i < outputTy.getRank(); i++) {
1830 if (outputTy.isDynamicDim(i)) {
1831 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
1832 }
1833 }
1834
1835 DenseElementsAttr shiftElems;
1836 bool isShiftConstant = false;
1837 if (matchPattern(op.getShift(), m_Constant(&shiftElems)))
1838 isShiftConstant = true;
1839
1840 DenseElementsAttr multiplierElems;
1841 bool isMultiplierConstant = false;
1842 if (matchPattern(op.getMultiplier(), m_Constant(&multiplierElems)))
1843 isMultiplierConstant = true;
1844
1845 llvm::SmallVector<int32_t> shiftValues;
1846 llvm::SmallVector<int32_t> multiplierValues;
1847 bool doubleRound;
1848
1849 if (isMultiplierConstant && isShiftConstant) {
1850 // explicit cast is required here
1851 shiftValues = llvm::map_to_vector(
1852 shiftElems.getValues<IntegerAttr>(), [](IntegerAttr attr) -> int32_t {
1853 return static_cast<int32_t>(attr.getInt());
1854 });
1855 multiplierValues =
1856 llvm::map_to_vector(multiplierElems.getValues<IntegerAttr>(),
1857 [](IntegerAttr attr) -> int32_t {
1858 return static_cast<int32_t>(attr.getInt());
1859 });
1860
1861 // If we shift by more than the bitwidth, this just sets to 0.
1862 for (int i = 0, s = multiplierValues.size(); i < s; i++) {
1863 if (shiftValues[i] > 63) {
1864 shiftValues[i] = 0;
1865 multiplierValues[i] = 0;
1866 }
1867 }
1868 // Double round only occurs if shift is greater than 31, check that this
1869 // is ever true.
1870 doubleRound = op.getRoundingMode() == RoundingMode::DOUBLE_ROUND &&
1871 llvm::any_of(shiftValues, [](int32_t v) { return v > 31; });
1872 } else
1873 doubleRound = op.getRoundingMode() == RoundingMode::DOUBLE_ROUND;
1874
1875 RoundingMode roundingMode =
1876 doubleRound ? RoundingMode::DOUBLE_ROUND : RoundingMode::SINGLE_ROUND;
1877
1878 SmallVector<AffineMap> indexingMaps = {
1879 rewriter.getMultiDimIdentityMap(rank)};
1880 SmallVector<Value, 4> genericInputs = {input};
1881
1882 // If we are rescaling per-channel then we need to store the multiplier
1883 // values in a buffer.
1884 Value multiplierConstant;
1885 int64_t multiplierArg = 0;
1886 setupLinalgGenericOpInputAndIndexingMap(
1887 rewriter, multiplierValues, genericInputs, indexingMaps,
1888 isMultiplierConstant, op, multiplierConstant, multiplierArg);
1889
1890 // If we are rescaling per-channel then we need to store the shift
1891 // values in a buffer.
1892 Value shiftConstant;
1893 int64_t shiftArg = 0;
1894 setupLinalgGenericOpInputAndIndexingMap(
1895 rewriter, shiftValues, genericInputs, indexingMaps, isShiftConstant, op,
1896 shiftConstant, shiftArg, true);
1897
1898 // broadcastMap = affine_map<(d0, d1) -> ()>
1899 // It would affect as broadcast for scalar values in linalg::GenericOp.
1900 AffineMap broadcastMap = AffineMap::get(rank, 0, {}, rewriter.getContext());
1901 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
1902 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
1903 // The inputZp and outputZp may be either constant or non-constant,
1904 // depending on whether dynamic extension is enabled.
1905 // - If the zp's are non-constant, add them as an inputs to
1906 // linalg::GenericOp by:
1907 // 1. Pushing it into 'genericInputs'.
1908 // 2. Appending a corresponding affine map to 'indexingMaps'.
1909 // - If the zp's are constant, they would be generated as arith.constant.
1910 int64_t iZpArg = 0;
1911 if (failed(maybeIZp)) {
1912 genericInputs.push_back(
1913 collapse1xNTensorToN(rewriter, op->getOperand(3), loc));
1914 indexingMaps.push_back(broadcastMap);
1915 iZpArg = indexingMaps.size() - 1;
1916 }
1917 int64_t oZpArg = 0;
1918 if (failed(maybeOZp)) {
1919 genericInputs.push_back(
1920 collapse1xNTensorToN(rewriter, op->getOperand(4), loc));
1921 indexingMaps.push_back(broadcastMap);
1922 oZpArg = indexingMaps.size() - 1;
1923 }
1924
1925 // Indexing maps for output values.
1926 indexingMaps.push_back(rewriter.getMultiDimIdentityMap(rank));
1927
1928 // Construct the indexing maps needed for linalg.generic ops.
1929 Value emptyTensor = tensor::EmptyOp::create(
1930 rewriter, loc, outputTy.getShape(), outputTy.getElementType(),
1931 ArrayRef<Value>({dynDims}));
1932
1933 auto linalgOp = linalg::GenericOp::create(
1934 rewriter, loc, outputTy, genericInputs, ValueRange{emptyTensor},
1935 indexingMaps, getNParallelLoopsAttrs(rank),
1936 [&](OpBuilder &nestedBuilder, Location nestedLoc,
1937 ValueRange blockArgs) {
1938 Value value = blockArgs[0];
1939 Type valueTy = value.getType();
1940
1941 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
1942 auto inputZp = getExtendZp(nestedBuilder, valueTy, maybeIZp,
1943 nestedLoc, blockArgs, iZpArg);
1944
1945 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
1946 auto outputZp = getExtendZp(nestedBuilder, valueTy, maybeOZp,
1947 nestedLoc, blockArgs, oZpArg, true);
1948
1949 IntegerType outIntType =
1950 cast<IntegerType>(blockArgs.back().getType());
1951 unsigned outBitWidth = outIntType.getWidth();
1952 assert(outBitWidth <= 32 && "Unexpected output zeropoint bitwidth");
1953
1954 Value multiplier = multiplierConstant ? multiplierConstant
1955 : blockArgs[multiplierArg];
1956 Value shift = shiftConstant ? shiftConstant : blockArgs[shiftArg];
1957
1958 if (valueTy.isUnsignedInteger()) {
1959 value = UnrealizedConversionCastOp::create(
1960 nestedBuilder, nestedLoc,
1961 nestedBuilder.getIntegerType(
1962 valueTy.getIntOrFloatBitWidth()),
1963 value)
1964 .getResult(0);
1965 }
1966 if (valueTy.getIntOrFloatBitWidth() < 32) {
1967 if (op.getInputUnsigned()) {
1968 value = arith::ExtUIOp::create(nestedBuilder, nestedLoc,
1969 nestedBuilder.getI32Type(), value);
1970 } else {
1971 value = arith::ExtSIOp::create(nestedBuilder, nestedLoc,
1972 nestedBuilder.getI32Type(), value);
1973 }
1974 }
1975
1976 value =
1977 arith::SubIOp::create(nestedBuilder, nestedLoc, value, inputZp);
1978
1979 value = tosa::ApplyScaleOp::create(nestedBuilder, loc,
1980 nestedBuilder.getI32Type(), value,
1981 multiplier, shift, roundingMode);
1982
1983 // Move to the new zero-point.
1984 value =
1985 arith::AddIOp::create(nestedBuilder, nestedLoc, value, outputZp);
1986
1987 // Saturate to the output size.
1988 int32_t intMin = APInt::getSignedMinValue(outBitWidth).getSExtValue();
1989 int32_t intMax = APInt::getSignedMaxValue(outBitWidth).getSExtValue();
1990
1991 // Unsigned integers have a difference output value.
1992 if (op.getOutputUnsigned()) {
1993 intMin = 0;
1994 intMax = APInt::getMaxValue(outBitWidth).getZExtValue();
1995 }
1996
1997 auto intMinVal = arith::ConstantOp::create(
1998 nestedBuilder, loc, nestedBuilder.getI32IntegerAttr(intMin));
1999 auto intMaxVal = arith::ConstantOp::create(
2000 nestedBuilder, loc, nestedBuilder.getI32IntegerAttr(intMax));
2001
2002 value = clampIntHelper(nestedLoc, value, intMinVal, intMaxVal,
2003 nestedBuilder, /*isUnsigned=*/false);
2004
2005 if (outIntType.getWidth() < 32) {
2006 value = arith::TruncIOp::create(
2007 nestedBuilder, nestedLoc,
2008 rewriter.getIntegerType(outIntType.getWidth()), value);
2009 }
2010
2011 if (outIntType.isUnsignedInteger()) {
2012 value = UnrealizedConversionCastOp::create(nestedBuilder, nestedLoc,
2013 outIntType, value)
2014 .getResult(0);
2015 }
2016 linalg::YieldOp::create(nestedBuilder, loc, value);
2017 });
2018
2019 rewriter.replaceOp(op, linalgOp->getResults());
2020 return success();
2021 }
2022};
2023
2024// Handle the resize case where the input is a 1x1 image. This case
2025// can entirely avoiding having extract operations which target much
2026// more difficult to optimize away.
2027class ResizeUnaryConverter : public OpRewritePattern<tosa::ResizeOp> {
2028public:
2029 using OpRewritePattern<tosa::ResizeOp>::OpRewritePattern;
2030
2031 LogicalResult matchAndRewrite(tosa::ResizeOp op,
2032 PatternRewriter &rewriter) const final {
2033 Location loc = op.getLoc();
2034 ImplicitLocOpBuilder builder(loc, rewriter);
2035 auto input = op.getInput();
2036 auto inputTy = cast<RankedTensorType>(input.getType());
2037 auto resultTy = cast<RankedTensorType>(op.getType());
2038 const bool isBilinear = op.getMode() == ResizeMode::BILINEAR;
2039
2040 auto inputH = inputTy.getDimSize(1);
2041 auto inputW = inputTy.getDimSize(2);
2042 auto outputH = resultTy.getDimSize(1);
2043 auto outputW = resultTy.getDimSize(2);
2044
2045 if (inputH != 1 || inputW != 1 || outputH != 1 || outputW != 1)
2046 return rewriter.notifyMatchFailure(
2047 op, "tosa.resize is not a pure 1x1->1x1 image operation");
2048
2049 if (op.getMode() != ResizeMode::NEAREST_NEIGHBOR &&
2050 op.getMode() != ResizeMode::BILINEAR)
2051 return rewriter.notifyMatchFailure(
2052 op, "tosa.resize mode should be NEAREST_NEIGHBOR or BILINEAR");
2053
2054 if (inputTy == resultTy) {
2055 rewriter.replaceOp(op, input);
2056 return success();
2057 }
2058
2059 SmallVector<int64_t> scale;
2060 if (!tosa::getConstShapeValues(op.getScale().getDefiningOp(), scale)) {
2061 return failure();
2062 }
2063
2064 // Collapse the unit width and height away.
2065 SmallVector<ReassociationExprs, 4> reassociationMap(2);
2066 reassociationMap[0].push_back(builder.getAffineDimExpr(0));
2067 reassociationMap[1].push_back(builder.getAffineDimExpr(1));
2068 reassociationMap[1].push_back(builder.getAffineDimExpr(2));
2069 reassociationMap[1].push_back(builder.getAffineDimExpr(3));
2070
2071 auto collapseTy =
2072 RankedTensorType::get({inputTy.getDimSize(0), inputTy.getDimSize(3)},
2073 inputTy.getElementType());
2074 Value collapse = tensor::CollapseShapeOp::create(builder, collapseTy, input,
2075 reassociationMap);
2076
2077 // Get any dynamic shapes that appear in the input format.
2078 llvm::SmallVector<Value> outputDynSize;
2079 if (inputTy.isDynamicDim(0))
2080 outputDynSize.push_back(tensor::DimOp::create(builder, input, 0));
2081 if (inputTy.isDynamicDim(3))
2082 outputDynSize.push_back(tensor::DimOp::create(builder, input, 3));
2083
2084 // Generate the elementwise operation for casting scaling the input value.
2085 auto genericTy = collapseTy.clone(resultTy.getElementType());
2086 Value empty =
2087 tensor::EmptyOp::create(builder, genericTy.getShape(),
2088 resultTy.getElementType(), outputDynSize);
2089 auto genericMap = rewriter.getMultiDimIdentityMap(genericTy.getRank());
2090 SmallVector<utils::IteratorType> iterators(genericTy.getRank(),
2091 utils::IteratorType::parallel);
2092
2093 auto generic = linalg::GenericOp::create(
2094 builder, genericTy, ValueRange{collapse}, ValueRange{empty},
2095 ArrayRef<AffineMap>{genericMap, genericMap}, iterators,
2096 [=](OpBuilder &b, Location loc, ValueRange args) {
2097 Value value = args[0];
2098 // This is the quantized case.
2099 if (inputTy.getElementType() != resultTy.getElementType()) {
2100 value = arith::ExtSIOp::create(b, loc, resultTy.getElementType(),
2101 value);
2102
2103 if (isBilinear && scale[0] != 0) {
2104 Value scaleY = arith::ConstantOp::create(
2105 b, loc, b.getI32IntegerAttr(scale[0]));
2106 value = arith::MulIOp::create(b, loc, value, scaleY);
2107 }
2108
2109 if (isBilinear && scale[2] != 0) {
2110 Value scaleX = arith::ConstantOp::create(
2111 b, loc, b.getI32IntegerAttr(scale[2]));
2112 value = arith::MulIOp::create(b, loc, value, scaleX);
2113 }
2114 }
2115
2116 linalg::YieldOp::create(b, loc, value);
2117 });
2118
2119 rewriter.replaceOpWithNewOp<tensor::ExpandShapeOp>(
2120 op, resultTy, generic.getResults()[0], reassociationMap);
2121 return success();
2122 }
2123};
2124
2125// TOSA resize with width or height of 1 may be broadcasted to a wider
2126// dimension. This is done by materializing a new tosa.resize without
2127// the broadcasting behavior, and an explicit broadcast afterwards.
2128class MaterializeResizeBroadcast : public OpRewritePattern<tosa::ResizeOp> {
2129public:
2130 using OpRewritePattern<tosa::ResizeOp>::OpRewritePattern;
2131
2132 LogicalResult matchAndRewrite(tosa::ResizeOp op,
2133 PatternRewriter &rewriter) const final {
2134 Location loc = op.getLoc();
2135 ImplicitLocOpBuilder builder(loc, rewriter);
2136 auto input = op.getInput();
2137 auto inputTy = dyn_cast<RankedTensorType>(input.getType());
2138 auto resultTy = dyn_cast<RankedTensorType>(op.getType());
2139
2140 if (!inputTy || !resultTy)
2141 return rewriter.notifyMatchFailure(op,
2142 "requires ranked input/output types");
2143
2144 auto batch = inputTy.getDimSize(0);
2145 auto channels = inputTy.getDimSize(3);
2146 auto inputH = inputTy.getDimSize(1);
2147 auto inputW = inputTy.getDimSize(2);
2148 auto outputH = resultTy.getDimSize(1);
2149 auto outputW = resultTy.getDimSize(2);
2150
2151 if ((inputH != 1 || outputH == 1) && (inputW != 1 || outputW == 1))
2152 return rewriter.notifyMatchFailure(
2153 op, "tosa.resize has no broadcasting behavior");
2154
2155 // For any dimension that is broadcastable we generate a width of 1
2156 // on the output.
2157 llvm::SmallVector<int64_t> resizeShape;
2158 resizeShape.push_back(batch);
2159 resizeShape.push_back(inputH == 1 ? 1 : outputH);
2160 resizeShape.push_back(inputW == 1 ? 1 : outputW);
2161 resizeShape.push_back(channels);
2162
2163 auto resizeTy = resultTy.clone(resizeShape);
2164 auto resize =
2165 tosa::ResizeOp::create(builder, resizeTy, input, op.getScale(),
2166 op.getOffset(), op.getBorder(), op.getMode());
2167
2168 // Collapse an unit result dims.
2169 SmallVector<ReassociationExprs, 4> reassociationMap(2);
2170 reassociationMap[0].push_back(builder.getAffineDimExpr(0));
2171 reassociationMap.back().push_back(builder.getAffineDimExpr(1));
2172 if (inputH != 1)
2173 reassociationMap.push_back({});
2174 reassociationMap.back().push_back(builder.getAffineDimExpr(2));
2175 if (inputW != 1)
2176 reassociationMap.push_back({});
2177 reassociationMap.back().push_back(builder.getAffineDimExpr(3));
2178
2179 llvm::SmallVector<int64_t> collapseShape = {batch};
2180 if (inputH != 1)
2181 collapseShape.push_back(outputH);
2182 if (inputW != 1)
2183 collapseShape.push_back(outputW);
2184 collapseShape.push_back(channels);
2185
2186 auto collapseTy = resultTy.clone(collapseShape);
2187 Value collapse = tensor::CollapseShapeOp::create(builder, collapseTy,
2188 resize, reassociationMap);
2189
2190 // Broadcast the collapsed shape to the output result.
2191 llvm::SmallVector<Value> outputDynSize;
2192 if (inputTy.isDynamicDim(0))
2193 outputDynSize.push_back(tensor::DimOp::create(builder, input, 0));
2194 if (inputTy.isDynamicDim(3))
2195 outputDynSize.push_back(tensor::DimOp::create(builder, input, 3));
2196
2197 SmallVector<utils::IteratorType> iterators(resultTy.getRank(),
2198 utils::IteratorType::parallel);
2199 Value empty = tensor::EmptyOp::create(
2200 builder, resultTy.getShape(), resultTy.getElementType(), outputDynSize);
2201
2202 SmallVector<AffineExpr, 4> inputExprs{rewriter.getAffineDimExpr(0)};
2203 if (inputH != 1)
2204 inputExprs.push_back(rewriter.getAffineDimExpr(1));
2205 if (inputW != 1)
2206 inputExprs.push_back(rewriter.getAffineDimExpr(2));
2207 inputExprs.push_back(rewriter.getAffineDimExpr(3));
2208
2209 auto inputMap = AffineMap::get(resultTy.getRank(), /*symbolCount=*/0,
2210 inputExprs, rewriter.getContext());
2211
2212 auto outputMap = rewriter.getMultiDimIdentityMap(resultTy.getRank());
2213 rewriter.replaceOpWithNewOp<linalg::GenericOp>(
2214 op, resultTy, ValueRange{collapse}, ValueRange{empty},
2215 ArrayRef<AffineMap>{inputMap, outputMap}, iterators,
2216 [=](OpBuilder &b, Location loc, ValueRange args) {
2217 Value value = args[0];
2218 linalg::YieldOp::create(b, loc, value);
2219 });
2220
2221 return success();
2222 }
2223};
2224
2225class GenericResizeConverter : public OpRewritePattern<tosa::ResizeOp> {
2226public:
2227 using OpRewritePattern<tosa::ResizeOp>::OpRewritePattern;
2228
2229 LogicalResult matchAndRewrite(tosa::ResizeOp op,
2230 PatternRewriter &rewriter) const final {
2231 Location loc = op.getLoc();
2232 ImplicitLocOpBuilder b(loc, rewriter);
2233 auto input = op.getInput();
2234 auto inputTy = cast<ShapedType>(input.getType());
2235 auto resultTy = cast<ShapedType>(op.getType());
2236 auto resultETy = resultTy.getElementType();
2237
2238 bool floatingPointMode = isa<FloatType>(resultETy);
2239 auto floatTy = resultETy;
2240
2241 auto imageH = inputTy.getShape()[1];
2242 auto imageW = inputTy.getShape()[2];
2243
2244 auto dynamicDimsOr =
2245 checkHasDynamicBatchDims(rewriter, op, {input, op.getOutput()});
2246 if (!dynamicDimsOr.has_value())
2247 return rewriter.notifyMatchFailure(
2248 op, "unable to get dynamic dimensions of tosa.resize");
2249
2250 if (op.getMode() != ResizeMode::NEAREST_NEIGHBOR &&
2251 op.getMode() != ResizeMode::BILINEAR)
2252 return rewriter.notifyMatchFailure(
2253 op, "tosa.resize mode should be NEAREST_NEIGHBOR or BILINEAR");
2254
2255 SmallVector<AffineMap, 2> affineMaps = {
2256 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
2257 auto emptyTensor = tensor::EmptyOp::create(b, resultTy.getShape(),
2258 resultETy, *dynamicDimsOr);
2259 auto genericOp = linalg::GenericOp::create(
2260 b, resultTy, ValueRange({}), ValueRange{emptyTensor}, affineMaps,
2261 getNParallelLoopsAttrs(resultTy.getRank()));
2262 Value resize = genericOp.getResult(0);
2263
2264 {
2265 OpBuilder::InsertionGuard regionGuard(b);
2266 b.createBlock(&genericOp.getRegion(), genericOp.getRegion().end(),
2267 TypeRange({resultETy}), loc);
2268 Value batch = linalg::IndexOp::create(b, 0);
2269 Value y = linalg::IndexOp::create(b, 1);
2270 Value x = linalg::IndexOp::create(b, 2);
2271 Value channel = linalg::IndexOp::create(b, 3);
2272
2273 Value zeroI32 =
2274 arith::ConstantOp::create(b, b.getZeroAttr(b.getI32Type()));
2275 Value zeroFp = arith::ConstantOp::create(b, b.getZeroAttr(floatTy));
2276 Value hMax =
2277 arith::ConstantOp::create(b, b.getI32IntegerAttr(imageH - 1));
2278 Value wMax =
2279 arith::ConstantOp::create(b, b.getI32IntegerAttr(imageW - 1));
2280
2281 Value inY = arith::IndexCastOp::create(b, b.getI32Type(), y);
2282 Value inX = arith::IndexCastOp::create(b, b.getI32Type(), x);
2283
2284 SmallVector<int64_t> scale, offset, border;
2285 if (!tosa::getConstShapeValues(op.getScale().getDefiningOp(), scale) ||
2286 !tosa::getConstShapeValues(op.getOffset().getDefiningOp(), offset) ||
2287 !tosa::getConstShapeValues(op.getBorder().getDefiningOp(), border)) {
2288 return rewriter.notifyMatchFailure(
2289 op, "tosa.resize scale/offset/border should have compile time "
2290 "constant values.");
2291 }
2292
2293 Value yScaleN, yScaleD, xScaleN, xScaleD;
2294 yScaleN = arith::ConstantOp::create(b, b.getI32IntegerAttr(scale[0]));
2295 yScaleD = arith::ConstantOp::create(b, b.getI32IntegerAttr(scale[1]));
2296 xScaleN = arith::ConstantOp::create(b, b.getI32IntegerAttr(scale[2]));
2297 xScaleD = arith::ConstantOp::create(b, b.getI32IntegerAttr(scale[3]));
2298
2299 Value yOffset, xOffset, yBorder, xBorder;
2300 yOffset = arith::ConstantOp::create(b, b.getI32IntegerAttr(offset[0]));
2301 xOffset = arith::ConstantOp::create(b, b.getI32IntegerAttr(offset[1]));
2302 yBorder = arith::ConstantOp::create(b, b.getI32IntegerAttr(border[0]));
2303 xBorder = arith::ConstantOp::create(b, b.getI32IntegerAttr(border[1]));
2304
2305 // Compute the ix and dx values for both the X and Y dimensions.
2306 auto getIndexAndDeltaFp = [&](Value &index, Value &delta, Value in,
2307 Value scaleN, Value scaleD, Value offset,
2308 int size, ImplicitLocOpBuilder &b) {
2309 if (size == 1) {
2310 index = zeroI32;
2311 delta = zeroFp;
2312 return;
2313 }
2314 // x = x * scale_d + offset;
2315 // ix = floor(x / scale_n)
2316 Value val = arith::MulIOp::create(b, in, scaleD);
2317 val = arith::AddIOp::create(b, val, offset);
2318 index = arith::FloorDivSIOp::create(b, val, scaleN);
2319
2320 // rx = x - ix * scale_n (x % scale_n, if values are positive)
2321 Value scaledIndex = arith::MulIOp::create(b, index, scaleN);
2322 Value r = arith::SubIOp::create(b, val, scaledIndex);
2323 Value rFp = arith::SIToFPOp::create(b, floatTy, r);
2324
2325 // dx = rx / scale_n
2326 Value scaleNfp = arith::UIToFPOp::create(b, floatTy, scaleN);
2327 delta = arith::DivFOp::create(b, rFp, scaleNfp);
2328 };
2329
2330 // Compute the ix and dx values for the X and Y dimensions - int case.
2331 auto getIndexAndDeltaInt = [&](Value &index, Value &delta, Value in,
2332 Value scaleN, Value scaleD, Value offset,
2333 int size, ImplicitLocOpBuilder &b) {
2334 if (size == 1) {
2335 index = zeroI32;
2336 delta = zeroI32;
2337 return;
2338 }
2339 // x = x * scale_d + offset;
2340 // ix = floor(x / scale_n)
2341 // dx = x - ix * scale_n;
2342 Value val = arith::MulIOp::create(b, in, scaleD);
2343 val = arith::AddIOp::create(b, val, offset);
2344 index = arith::FloorDivSIOp::create(b, val, scaleN);
2345 delta = arith::MulIOp::create(b, index, scaleN);
2346 delta = arith::SubIOp::create(b, val, delta);
2347 };
2348
2349 Value ix, iy, dx, dy;
2350 if (floatingPointMode) {
2351 getIndexAndDeltaFp(iy, dy, inY, yScaleN, yScaleD, yOffset, imageH, b);
2352 getIndexAndDeltaFp(ix, dx, inX, xScaleN, xScaleD, xOffset, imageW, b);
2353 } else {
2354 getIndexAndDeltaInt(iy, dy, inY, yScaleN, yScaleD, yOffset, imageH, b);
2355 getIndexAndDeltaInt(ix, dx, inX, xScaleN, xScaleD, xOffset, imageW, b);
2356 }
2357
2358 if (op.getMode() == ResizeMode::NEAREST_NEIGHBOR) {
2359 auto one = arith::ConstantOp::create(b, b.getI32IntegerAttr(1));
2360
2361 auto getNearestIndexAndClamp = [&](Value val, Value dval, Value scale,
2362 Value max, int size,
2363 ImplicitLocOpBuilder &b) -> Value {
2364 if (size == 1) {
2366 }
2367
2368 Value pred;
2369 if (floatingPointMode) {
2370 auto h =
2371 arith::ConstantOp::create(b, b.getFloatAttr(floatTy, 0.5f));
2372 pred = arith::CmpFOp::create(b, arith::CmpFPredicate::OGE, dval, h);
2373 } else {
2374 Value dvalDouble = arith::ShLIOp::create(b, dval, one);
2375 pred = arith::CmpIOp::create(b, arith::CmpIPredicate::sge,
2376 dvalDouble, scale);
2377 }
2378
2379 auto offset = arith::SelectOp::create(b, pred, one, zeroI32);
2380 val = arith::AddIOp::create(b, val, offset);
2381 val = clampIntHelper(loc, val, zeroI32, max, b, /*isUnsigned=*/false);
2382 return arith::IndexCastOp::create(b, b.getIndexType(), val);
2383 };
2384
2385 iy = getNearestIndexAndClamp(iy, dy, yScaleN, hMax, imageH, b);
2386 ix = getNearestIndexAndClamp(ix, dx, xScaleN, wMax, imageW, b);
2387
2388 Value result = tensor::ExtractOp::create(
2389 b, input, ValueRange{batch, iy, ix, channel});
2390
2391 linalg::YieldOp::create(b, result);
2392 } else {
2393 // The mode here must be BILINEAR.
2394 assert(op.getMode() == ResizeMode::BILINEAR);
2395
2396 auto oneVal = arith::ConstantOp::create(b, b.getI32IntegerAttr(1));
2397
2398 auto getClampedIdxs = [&](Value &val0, Value &val1, int size, Value in,
2399 Value max, ImplicitLocOpBuilder &b) {
2400 val0 = in;
2401 val1 = arith::AddIOp::create(b, val0, oneVal);
2402 val0 =
2403 clampIntHelper(loc, val0, zeroI32, max, b, /*isUnsigned=*/false);
2404 val1 =
2405 clampIntHelper(loc, val1, zeroI32, max, b, /*isUnsigned=*/false);
2406 val0 = arith::IndexCastOp::create(b, b.getIndexType(), val0);
2407 val1 = arith::IndexCastOp::create(b, b.getIndexType(), val1);
2408 };
2409
2410 // Linalg equivalent to the section below:
2411 // int16_t iy0 = apply_max(iy, 0);
2412 // int16_t iy1 = apply_min(iy + 1, IH - 1);
2413 // int16_t ix0 = apply_max(ix, 0);
2414 // int16_t ix1 = apply_min(ix + 1, IW - 1);
2415 Value x0, x1, y0, y1;
2416 getClampedIdxs(y0, y1, imageH, iy, hMax, b);
2417 getClampedIdxs(x0, x1, imageW, ix, wMax, b);
2418
2419 Value y0x0 = tensor::ExtractOp::create(
2420 b, input, ValueRange{batch, y0, x0, channel});
2421 Value y0x1 = tensor::ExtractOp::create(
2422 b, input, ValueRange{batch, y0, x1, channel});
2423 Value y1x0 = tensor::ExtractOp::create(
2424 b, input, ValueRange{batch, y1, x0, channel});
2425 Value y1x1 = tensor::ExtractOp::create(
2426 b, input, ValueRange{batch, y1, x1, channel});
2427
2428 if (floatingPointMode) {
2429 auto oneVal =
2430 arith::ConstantOp::create(b, b.getFloatAttr(floatTy, 1.0f));
2431 auto interpolate = [&](Value val0, Value val1, Value delta,
2432 int inputSize,
2433 ImplicitLocOpBuilder &b) -> Value {
2434 if (inputSize == 1)
2435 return val0;
2436 Value oneMinusDelta = arith::SubFOp::create(b, oneVal, delta);
2437 Value mul0 = arith::MulFOp::create(b, val0, oneMinusDelta);
2438 Value mul1 = arith::MulFOp::create(b, val1, delta);
2439 return arith::AddFOp::create(b, mul0, mul1);
2440 };
2441
2442 // Linalg equivalent to the section below:
2443 // topAcc = v00 * (unit_x - dx);
2444 // topAcc += v01 * dx;
2445 Value topAcc = interpolate(y0x0, y0x1, dx, imageW, b);
2446
2447 // Linalg equivalent to the section below:
2448 // bottomAcc = v10 * (unit_x - dx);
2449 // bottomAcc += v11 * dx;
2450 Value bottomAcc = interpolate(y1x0, y1x1, dx, imageW, b);
2451
2452 // Linalg equivalent to the section below:
2453 // result = topAcc * (unit_y - dy) + bottomAcc * dy
2454 Value result = interpolate(topAcc, bottomAcc, dy, imageH, b);
2455 linalg::YieldOp::create(b, result);
2456 } else {
2457 // Perform in quantized space.
2458 y0x0 = arith::ExtSIOp::create(b, resultETy, y0x0);
2459 y0x1 = arith::ExtSIOp::create(b, resultETy, y0x1);
2460 y1x0 = arith::ExtSIOp::create(b, resultETy, y1x0);
2461 y1x1 = arith::ExtSIOp::create(b, resultETy, y1x1);
2462
2463 const int64_t deltaBitwidth = dx.getType().getIntOrFloatBitWidth();
2464 if (resultETy.getIntOrFloatBitWidth() > deltaBitwidth) {
2465 dx = arith::ExtSIOp::create(b, resultETy, dx);
2466 dy = arith::ExtSIOp::create(b, resultETy, dy);
2467 }
2468
2469 Value yScaleNExt = yScaleN;
2470 Value xScaleNExt = xScaleN;
2471
2472 const int64_t scaleBitwidth =
2473 xScaleN.getType().getIntOrFloatBitWidth();
2474 if (resultETy.getIntOrFloatBitWidth() > scaleBitwidth) {
2475 yScaleNExt = arith::ExtSIOp::create(b, resultETy, yScaleN);
2476 xScaleNExt = arith::ExtSIOp::create(b, resultETy, xScaleN);
2477 }
2478
2479 auto interpolate = [](Value val0, Value val1, Value weight1,
2480 Value scale, int inputSize,
2481 ImplicitLocOpBuilder &b) -> Value {
2482 if (inputSize == 1)
2483 return arith::MulIOp::create(b, val0, scale);
2484 Value weight0 = arith::SubIOp::create(b, scale, weight1);
2485 Value mul0 = arith::MulIOp::create(b, val0, weight0);
2486 Value mul1 = arith::MulIOp::create(b, val1, weight1);
2487 return arith::AddIOp::create(b, mul0, mul1);
2488 };
2489
2490 Value topAcc = interpolate(y0x0, y0x1, dx, xScaleNExt, imageW, b);
2491 Value bottomAcc = interpolate(y1x0, y1x1, dx, xScaleNExt, imageW, b);
2492 Value result =
2493 interpolate(topAcc, bottomAcc, dy, yScaleNExt, imageH, b);
2494 linalg::YieldOp::create(b, result);
2495 }
2496 }
2497 }
2498
2499 rewriter.replaceOp(op, resize);
2500 return success();
2501 }
2502};
2503
2504// At the codegen level any identity operations should be removed. Any cases
2505// where identity is load-bearing (e.g. cross device computation) should be
2506// handled before lowering to codegen.
2507template <typename SrcOp>
2508class IdentityNConverter : public OpRewritePattern<SrcOp> {
2509public:
2510 using OpRewritePattern<SrcOp>::OpRewritePattern;
2511
2512 LogicalResult matchAndRewrite(SrcOp op,
2513 PatternRewriter &rewriter) const final {
2514 rewriter.replaceOp(op, op.getOperation()->getOperands());
2515 return success();
2516 }
2517};
2518
2519template <typename SrcOp>
2520class ReduceConverter : public OpRewritePattern<SrcOp> {
2521public:
2522 ReduceConverter(MLIRContext *context, bool allowNonFinites)
2523 : OpRewritePattern<SrcOp>(context), allowNonFinites(allowNonFinites) {}
2524
2525 LogicalResult matchAndRewrite(SrcOp reduceOp,
2526 PatternRewriter &rewriter) const final {
2527 return reduceMatchAndRewriteHelper(reduceOp, reduceOp.getAxis(), rewriter,
2528 allowNonFinites);
2529 }
2530
2531private:
2532 bool allowNonFinites;
2533};
2534
2535class ReverseConverter : public OpRewritePattern<tosa::ReverseOp> {
2536public:
2537 using OpRewritePattern<tosa::ReverseOp>::OpRewritePattern;
2538
2539 LogicalResult matchAndRewrite(tosa::ReverseOp op,
2540 PatternRewriter &rewriter) const final {
2541 auto loc = op.getLoc();
2542 Value input = op.getInput1();
2543 auto inputTy = cast<ShapedType>(input.getType());
2544 auto resultTy = cast<ShapedType>(op.getType());
2545 auto axis = op.getAxis();
2546
2547 SmallVector<Value> dynDims;
2548 for (int i = 0; i < inputTy.getRank(); i++) {
2549 if (inputTy.isDynamicDim(i)) {
2550 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
2551 }
2552 }
2553
2554 Value axisDimSize = tensor::DimOp::create(rewriter, loc, input, axis);
2555
2556 // First fill the output buffer with the init value.
2557 auto emptyTensor = tensor::EmptyOp::create(
2558 rewriter, loc, inputTy.getShape(),
2559 inputTy.getElementType(), ArrayRef<Value>({dynDims}))
2560 .getResult();
2561 SmallVector<AffineMap, 2> affineMaps = {
2562 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
2563
2564 rewriter.replaceOpWithNewOp<linalg::GenericOp>(
2565 op, resultTy, ArrayRef<Value>({}), ValueRange{emptyTensor}, affineMaps,
2566 getNParallelLoopsAttrs(resultTy.getRank()),
2567 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange args) {
2568 llvm::SmallVector<Value> indices;
2569 for (unsigned int i = 0; i < inputTy.getRank(); i++) {
2570 Value index =
2571 linalg::IndexOp::create(rewriter, nestedLoc, i).getResult();
2572 if (i == axis) {
2573 auto one = arith::ConstantIndexOp::create(rewriter, nestedLoc, 1);
2574 auto sizeMinusOne =
2575 arith::SubIOp::create(rewriter, nestedLoc, axisDimSize, one);
2576 index = arith::SubIOp::create(rewriter, nestedLoc, sizeMinusOne,
2577 index);
2578 }
2579
2580 indices.push_back(index);
2581 }
2582
2583 auto extract = tensor::ExtractOp::create(nestedBuilder, nestedLoc,
2584 input, indices);
2585 linalg::YieldOp::create(nestedBuilder, op.getLoc(),
2586 extract.getResult());
2587 });
2588 return success();
2589 }
2590};
2591
2592// This converter translate a tile operation to a reshape, broadcast, reshape.
2593// The first reshape minimally expands each tiled dimension to include a
2594// proceding size-1 dim. This dim is then broadcasted to the appropriate
2595// multiple.
2596struct TileConverter : public OpConversionPattern<tosa::TileOp> {
2597 using OpConversionPattern<tosa::TileOp>::OpConversionPattern;
2598
2599 LogicalResult
2600 matchAndRewrite(tosa::TileOp op, OpAdaptor adaptor,
2601 ConversionPatternRewriter &rewriter) const override {
2602 auto loc = op.getLoc();
2603 auto input = op.getInput1();
2604 auto inputTy = cast<ShapedType>(input.getType());
2605 auto inputShape = inputTy.getShape();
2606 auto resultTy = cast<ShapedType>(op.getType());
2607 auto elementTy = inputTy.getElementType();
2608 int64_t rank = inputTy.getRank();
2609
2610 SmallVector<int64_t> multiples;
2611 if (failed(op.getConstantMultiples(multiples)))
2612 return failure();
2613
2614 // Broadcast the newly added dimensions to their appropriate multiple.
2615 SmallVector<int64_t, 2> genericShape;
2616 for (int i = 0; i < rank; i++) {
2617 int64_t dim = multiples[i];
2618 genericShape.push_back(dim == -1 ? ShapedType::kDynamic : dim);
2619 genericShape.push_back(inputShape[i]);
2620 }
2621
2622 SmallVector<Value> dynDims;
2623 for (int i = 0; i < inputTy.getRank(); i++) {
2624 if (inputTy.isDynamicDim(i) || multiples[i] == -1) {
2625 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
2626 }
2627 }
2628
2629 auto emptyTensor = tensor::EmptyOp::create(
2630 rewriter, op.getLoc(), genericShape, elementTy, dynDims);
2631
2632 // We needs to map the input shape to the non-broadcasted dimensions.
2633 SmallVector<AffineExpr, 4> dimExprs;
2634 dimExprs.reserve(rank);
2635 for (unsigned i = 0; i < rank; ++i)
2636 dimExprs.push_back(rewriter.getAffineDimExpr(i * 2 + 1));
2637
2638 auto readAffineMap =
2639 AffineMap::get(/*dimCount=*/rank * 2, /*symbolCount=*/0, dimExprs,
2640 rewriter.getContext());
2641
2642 SmallVector<AffineMap, 2> affineMaps = {
2643 readAffineMap, rewriter.getMultiDimIdentityMap(genericShape.size())};
2644
2645 auto genericOp = linalg::GenericOp::create(
2646 rewriter, loc, RankedTensorType::get(genericShape, elementTy), input,
2647 ValueRange{emptyTensor}, affineMaps,
2648 getNParallelLoopsAttrs(genericShape.size()),
2649 [&](OpBuilder &nestedBuilder, Location nestedLoc, ValueRange args) {
2650 linalg::YieldOp::create(nestedBuilder, op.getLoc(), *args.begin());
2651 });
2652
2653 auto shapeValue = getTosaConstShape(
2654 rewriter, loc, mlir::tosa::convertFromMlirShape(resultTy.getShape()));
2655 rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
2656 op, resultTy, genericOp.getResult(0), shapeValue);
2657 return success();
2658 }
2659};
2660
2661// Tosa argmax lowering represents the ArgMax op as an linalg.indexed_generic
2662// op, producing two output buffers.
2663//
2664// The first output buffer contains the index of the found maximum value. It is
2665// initialized to 0 and is resulting integer type.
2666//
2667// The second output buffer contains the maximum value found. It is initialized
2668// to the minimum representable value of the input element type. After being
2669// populated by indexed_generic, this buffer is disgarded as only the index is
2670// requested.
2671//
2672// The indexed_generic op updates both the maximum value and index if the
2673// current value exceeds the running max.
2674class ArgMaxConverter : public OpRewritePattern<tosa::ArgMaxOp> {
2675public:
2676 ArgMaxConverter(MLIRContext *context, bool allowNonFinites)
2677 : OpRewritePattern<tosa::ArgMaxOp>(context),
2678 allowNonFinites(allowNonFinites) {}
2679
2680 LogicalResult matchAndRewrite(tosa::ArgMaxOp argmaxOp,
2681 PatternRewriter &rewriter) const final {
2682 auto loc = argmaxOp.getLoc();
2683 Value input = argmaxOp.getInput();
2684 auto inputTy = cast<ShapedType>(input.getType());
2685 auto resultTy = cast<ShapedType>(argmaxOp.getOutput().getType());
2686 auto inElementTy = inputTy.getElementType();
2687 auto outElementTy = resultTy.getElementType();
2688 int axis = argmaxOp.getAxis();
2689 auto resultMaxTy = RankedTensorType::get(resultTy.getShape(), inElementTy);
2690
2691 if (!isa<IntegerType>(outElementTy))
2692 return rewriter.notifyMatchFailure(
2693 argmaxOp,
2694 "tosa.arg_max to linalg.* requires integer-like result type");
2695
2696 SmallVector<Value> dynDims;
2697 for (int i = 0; i < inputTy.getRank(); i++) {
2698 if (inputTy.isDynamicDim(i) && i != axis) {
2699 dynDims.push_back(tensor::DimOp::create(rewriter, loc, input, i));
2700 }
2701 }
2702
2703 // First fill the output buffer for the index.
2704 auto emptyTensorIdx =
2705 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
2706 outElementTy, dynDims)
2707 .getResult();
2708 auto fillValueIdx = arith::ConstantOp::create(
2709 rewriter, loc, rewriter.getIntegerAttr(outElementTy, 0));
2710 auto filledTensorIdx =
2711 linalg::FillOp::create(rewriter, loc, ValueRange{fillValueIdx},
2712 ValueRange{emptyTensorIdx})
2713 .result();
2714
2715 // Second fill the output buffer for the running max.
2716 auto emptyTensorMax =
2717 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(), inElementTy,
2718 dynDims)
2719 .getResult();
2720 auto fillValueMaxAttr = createInitialValueForReduceOp(
2721 argmaxOp, inElementTy, rewriter, allowNonFinites);
2722
2723 if (!fillValueMaxAttr)
2724 return rewriter.notifyMatchFailure(
2725 argmaxOp, "unsupported tosa.argmax element type");
2726
2727 auto fillValueMax =
2728 arith::ConstantOp::create(rewriter, loc, fillValueMaxAttr);
2729 auto filledTensorMax =
2730 linalg::FillOp::create(rewriter, loc, ValueRange{fillValueMax},
2731 ValueRange{emptyTensorMax})
2732 .result();
2733
2734 // We need to reduce along the arg-max axis, with parallel operations along
2735 // the rest.
2736 SmallVector<utils::IteratorType, 4> iteratorTypes;
2737 iteratorTypes.resize(inputTy.getRank(), utils::IteratorType::parallel);
2738 iteratorTypes[axis] = utils::IteratorType::reduction;
2739
2740 SmallVector<AffineExpr, 2> srcExprs;
2741 SmallVector<AffineExpr, 2> dstExprs;
2742 for (int i = 0, rank = inputTy.getRank(); i != rank; ++i) {
2743 srcExprs.push_back(mlir::getAffineDimExpr(i, rewriter.getContext()));
2744 if (axis != i)
2745 dstExprs.push_back(mlir::getAffineDimExpr(i, rewriter.getContext()));
2746 }
2747
2748 bool didEncounterError = false;
2749 auto maps = AffineMap::inferFromExprList({srcExprs, dstExprs, dstExprs},
2750 rewriter.getContext());
2751 auto linalgOp = linalg::GenericOp::create(
2752 rewriter, loc, ArrayRef<Type>({resultTy, resultMaxTy}), input,
2753 ValueRange({filledTensorIdx, filledTensorMax}), maps, iteratorTypes,
2754 [&](OpBuilder &nestedBuilder, Location nestedLoc,
2755 ValueRange blockArgs) {
2756 auto newValue = blockArgs[0];
2757 auto oldIndex = blockArgs[1];
2758 auto oldValue = blockArgs[2];
2759
2760 Value newIndex = arith::IndexCastOp::create(
2761 rewriter, nestedLoc, oldIndex.getType(),
2762 linalg::IndexOp::create(rewriter, loc, axis));
2763
2764 Value predicate;
2765 if (isa<FloatType>(inElementTy)) {
2766 if (argmaxOp.getNanMode() == NanPropagationMode::IGNORE) {
2767 // Only update index & max value for non NaN values. If all
2768 // values are NaNs, the initial index will be return which is 0.
2769 predicate = arith::CmpFOp::create(rewriter, nestedLoc,
2770 arith::CmpFPredicate::OGT,
2771 newValue, oldValue);
2772 } else {
2773 // Update max value if either of the following is true:
2774 // - new value is bigger
2775 // - cur max is not NaN and new value is NaN
2776 Value gt = arith::CmpFOp::create(rewriter, nestedLoc,
2777 arith::CmpFPredicate::UGT,
2778 newValue, oldValue);
2779 Value oldNonNaN = arith::CmpFOp::create(rewriter, nestedLoc,
2780 arith::CmpFPredicate::ORD,
2781 oldValue, oldValue);
2782 predicate = arith::AndIOp::create(
2783 rewriter, nestedLoc, rewriter.getI1Type(), gt, oldNonNaN);
2784 }
2785 } else if (isa<IntegerType>(inElementTy)) {
2786 predicate = arith::CmpIOp::create(rewriter, nestedLoc,
2787 arith::CmpIPredicate::sgt,
2788 newValue, oldValue);
2789 } else {
2790 didEncounterError = true;
2791 return;
2792 }
2793
2794 auto resultMax = arith::SelectOp::create(
2795 rewriter, nestedLoc, predicate, newValue, oldValue);
2796 auto resultIndex = arith::SelectOp::create(
2797 rewriter, nestedLoc, predicate, newIndex, oldIndex);
2798 linalg::YieldOp::create(nestedBuilder, nestedLoc,
2799 ValueRange({resultIndex, resultMax}));
2800 });
2801
2802 if (didEncounterError)
2803 return rewriter.notifyMatchFailure(
2804 argmaxOp, "unsupported tosa.argmax element type");
2805
2806 rewriter.replaceOp(argmaxOp, linalgOp.getResult(0));
2807 return success();
2808 }
2809
2810private:
2811 bool allowNonFinites;
2812};
2813
2814class GatherConverter : public OpConversionPattern<tosa::GatherOp> {
2815public:
2816 using OpConversionPattern<tosa::GatherOp>::OpConversionPattern;
2817 LogicalResult
2818 matchAndRewrite(tosa::GatherOp op, OpAdaptor adaptor,
2819 ConversionPatternRewriter &rewriter) const final {
2820 auto input = adaptor.getOperands()[0];
2821 auto indices = adaptor.getOperands()[1];
2822
2823 auto valuesTy = dyn_cast<RankedTensorType>(op.getValues().getType());
2824 auto resultTy = dyn_cast<RankedTensorType>(op.getType());
2825 if (!valuesTy || !resultTy)
2826 return rewriter.notifyMatchFailure(op, "unranked tensors not supported");
2827
2828 auto dynamicDims = inferDynamicDimsForGather(
2829 rewriter, op.getLoc(), adaptor.getValues(), adaptor.getIndices());
2830
2831 auto resultElementTy = resultTy.getElementType();
2832
2833 auto loc = op.getLoc();
2834 auto emptyTensor =
2835 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
2836 resultElementTy, dynamicDims)
2837 .getResult();
2838
2839 SmallVector<AffineMap, 2> affineMaps = {
2841 /*dimCount=*/resultTy.getRank(), /*symbolCount=*/0,
2842 {rewriter.getAffineDimExpr(0), rewriter.getAffineDimExpr(1)},
2843 rewriter.getContext()),
2844 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
2845
2846 auto genericOp = linalg::GenericOp::create(
2847 rewriter, loc, ArrayRef<Type>({resultTy}), ValueRange{indices},
2848 ValueRange{emptyTensor}, affineMaps,
2849 getNParallelLoopsAttrs(resultTy.getRank()),
2850 [&](OpBuilder &b, Location loc, ValueRange args) {
2851 auto indexValue = args[0];
2852 auto index0 = linalg::IndexOp::create(rewriter, loc, 0);
2853 Value index1 = arith::IndexCastOp::create(
2854 rewriter, loc, rewriter.getIndexType(), indexValue);
2855 auto index2 = linalg::IndexOp::create(rewriter, loc, 2);
2856 Value extract = tensor::ExtractOp::create(
2857 rewriter, loc, input, ValueRange{index0, index1, index2});
2858 linalg::YieldOp::create(rewriter, loc, extract);
2859 });
2860 rewriter.replaceOp(op, genericOp.getResult(0));
2861 return success();
2862 }
2863
2864 static llvm::SmallVector<Value> inferDynamicDimsForGather(OpBuilder &builder,
2865 Location loc,
2866 Value values,
2867 Value indices) {
2868 llvm::SmallVector<Value> results;
2869
2870 auto addDynamicDimension = [&](Value source, int64_t dim) {
2871 auto sz = tensor::getMixedSize(builder, loc, source, dim);
2872 if (auto dimValue = llvm::dyn_cast_if_present<Value>(sz))
2873 results.push_back(dimValue);
2874 };
2875
2876 addDynamicDimension(values, 0);
2877 addDynamicDimension(indices, 1);
2878 addDynamicDimension(values, 2);
2879 return results;
2880 }
2881};
2882
2883class RowGatherConverter : public OpConversionPattern<tosa::RowGatherOp> {
2884public:
2885 using OpConversionPattern<tosa::RowGatherOp>::OpConversionPattern;
2886 LogicalResult
2887 matchAndRewrite(tosa::RowGatherOp op, OpAdaptor adaptor,
2888 ConversionPatternRewriter &rewriter) const final {
2889 auto valuesTy = dyn_cast<RankedTensorType>(adaptor.getValues().getType());
2890 auto indicesTy = dyn_cast<RankedTensorType>(adaptor.getIndices().getType());
2891 auto rowCountTy =
2892 dyn_cast<RankedTensorType>(adaptor.getRowCount().getType());
2893 auto resultTy = dyn_cast<RankedTensorType>(op.getType());
2894 if (!valuesTy || !indicesTy || !rowCountTy || !resultTy)
2895 return rewriter.notifyMatchFailure(op, "unranked tensors not supported");
2896
2897 Location loc = op.getLoc();
2898 Value zero = arith::ConstantIndexOp::create(rewriter, loc, 0);
2899 Value rowCount = tensor::ExtractOp::create(
2900 rewriter, loc, adaptor.getRowCount(), ValueRange{zero});
2901 Value rowCountIndex = arith::IndexCastOp::create(
2902 rewriter, loc, rewriter.getIndexType(), rowCount);
2903
2904 SmallVector<Value> dynamicDims;
2905 if (resultTy.isDynamicDim(0))
2906 dynamicDims.push_back(
2907 tensor::DimOp::create(rewriter, loc, adaptor.getValues(), 0));
2908 if (resultTy.isDynamicDim(1)) {
2909 Value indicesWidth =
2910 tensor::DimOp::create(rewriter, loc, adaptor.getIndices(), 1);
2911 dynamicDims.push_back(
2912 arith::MulIOp::create(rewriter, loc, indicesWidth, rowCountIndex));
2913 }
2914 if (resultTy.isDynamicDim(2))
2915 dynamicDims.push_back(
2916 tensor::DimOp::create(rewriter, loc, adaptor.getValues(), 2));
2917
2918 Value emptyTensor =
2919 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
2920 resultTy.getElementType(), dynamicDims);
2921 SmallVector<AffineMap> affineMaps = {
2922 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
2923
2924 auto genericOp = linalg::GenericOp::create(
2925 rewriter, loc, ArrayRef<Type>{resultTy}, ValueRange{},
2926 ValueRange{emptyTensor}, affineMaps,
2927 getNParallelLoopsAttrs(resultTy.getRank()),
2928 [&](OpBuilder &builder, Location nestedLoc, ValueRange) {
2929 Value batch = linalg::IndexOp::create(builder, nestedLoc, 0);
2930 Value outputRow = linalg::IndexOp::create(builder, nestedLoc, 1);
2931 Value channel = linalg::IndexOp::create(builder, nestedLoc, 2);
2932 Value indexSlot = arith::DivUIOp::create(builder, nestedLoc,
2933 outputRow, rowCountIndex);
2934 Value rowOffset = arith::RemUIOp::create(builder, nestedLoc,
2935 outputRow, rowCountIndex);
2936 Value index = tensor::ExtractOp::create(builder, nestedLoc,
2937 adaptor.getIndices(),
2938 ValueRange{batch, indexSlot});
2939 Value row = arith::IndexCastOp::create(builder, nestedLoc,
2940 builder.getIndexType(), index);
2941 row = arith::AddIOp::create(builder, nestedLoc, row, rowOffset);
2942 Value result =
2943 tensor::ExtractOp::create(builder, nestedLoc, adaptor.getValues(),
2944 ValueRange{batch, row, channel});
2945 linalg::YieldOp::create(builder, nestedLoc, result);
2946 });
2947 rewriter.replaceOp(op, genericOp.getResult(0));
2948 return success();
2949 }
2950};
2951
2952// Lowerings the TableOp to a series of gathers and numerica operations. This
2953// includes interpolation between the high/low values. For the I8 varient, this
2954// simplifies to a single gather operation.
2955class TableConverter : public OpRewritePattern<tosa::TableOp> {
2956public:
2957 using OpRewritePattern<tosa::TableOp>::OpRewritePattern;
2958
2959 LogicalResult matchAndRewrite(tosa::TableOp op,
2960 PatternRewriter &rewriter) const final {
2961 auto loc = op.getLoc();
2962 Value input = op.getInput1();
2963 Value table = op.getTable();
2964 auto inputTy = cast<ShapedType>(input.getType());
2965 auto tableTy = cast<ShapedType>(table.getType());
2966 auto resultTy = cast<ShapedType>(op.getType());
2967
2968 auto inputElementTy = inputTy.getElementType();
2969 auto tableElementTy = tableTy.getElementType();
2970 auto resultElementTy = resultTy.getElementType();
2971
2972 SmallVector<Value> dynDims;
2973 for (int i = 0; i < resultTy.getRank(); ++i) {
2974 if (inputTy.isDynamicDim(i)) {
2975 dynDims.push_back(
2976 tensor::DimOp::create(rewriter, loc, op.getOperand(0), i));
2977 }
2978 }
2979
2980 auto emptyTensor =
2981 tensor::EmptyOp::create(rewriter, loc, resultTy.getShape(),
2982 resultElementTy, dynDims)
2983 .getResult();
2984
2985 SmallVector<AffineMap, 2> affineMaps = {
2986 rewriter.getMultiDimIdentityMap(resultTy.getRank()),
2987 rewriter.getMultiDimIdentityMap(resultTy.getRank())};
2988
2989 auto genericOp = linalg::GenericOp::create(
2990 rewriter, loc, resultTy, ValueRange({input}), ValueRange{emptyTensor},
2991 affineMaps, getNParallelLoopsAttrs(resultTy.getRank()));
2992 rewriter.replaceOp(op, genericOp.getResult(0));
2993
2994 {
2995 OpBuilder::InsertionGuard regionGuard(rewriter);
2996 Block *block = rewriter.createBlock(
2997 &genericOp.getRegion(), genericOp.getRegion().end(),
2998 TypeRange({inputElementTy, resultElementTy}), {loc, loc});
2999
3000 auto inputValue = block->getArgument(0);
3001 rewriter.setInsertionPointToStart(block);
3002 if (inputElementTy.isInteger(8) && tableElementTy.isInteger(8) &&
3003 resultElementTy.isInteger(8)) {
3004 Value index = arith::IndexCastOp::create(
3005 rewriter, loc, rewriter.getIndexType(), inputValue);
3006 Value offset = arith::ConstantIndexOp::create(rewriter, loc, 128);
3007 index = arith::AddIOp::create(rewriter, loc, rewriter.getIndexType(),
3008 index, offset);
3009 Value extract =
3010 tensor::ExtractOp::create(rewriter, loc, table, ValueRange{index});
3011 linalg::YieldOp::create(rewriter, loc, extract);
3012 return success();
3013 }
3014
3015 if (inputElementTy.isInteger(16) && tableElementTy.isInteger(16) &&
3016 resultElementTy.isInteger(32)) {
3017 Value extend = arith::ExtSIOp::create(
3018 rewriter, loc, rewriter.getI32Type(), inputValue);
3019
3020 auto offset = arith::ConstantOp::create(
3021 rewriter, loc, rewriter.getI32IntegerAttr(32768));
3022 auto seven = arith::ConstantOp::create(rewriter, loc,
3023 rewriter.getI32IntegerAttr(7));
3024 auto one = arith::ConstantOp::create(rewriter, loc,
3025 rewriter.getI32IntegerAttr(1));
3026 auto b1111111 = arith::ConstantOp::create(
3027 rewriter, loc, rewriter.getI32IntegerAttr(127));
3028
3029 // Compute the index and fractional part from the input value:
3030 // value = value + 32768
3031 // index = value >> 7;
3032 // fraction = 0x01111111 & value
3033 auto extendAdd = arith::AddIOp::create(rewriter, loc, extend, offset);
3034 Value index = arith::ShRUIOp::create(rewriter, loc, extendAdd, seven);
3035 Value fraction =
3036 arith::AndIOp::create(rewriter, loc, extendAdd, b1111111);
3037
3038 // Extract the base and next values from the table.
3039 // base = (int32_t) table[index];
3040 // next = (int32_t) table[index + 1];
3041 Value indexPlusOne = arith::AddIOp::create(rewriter, loc, index, one);
3042
3043 index = arith::IndexCastOp::create(rewriter, loc,
3044 rewriter.getIndexType(), index);
3045 indexPlusOne = arith::IndexCastOp::create(
3046 rewriter, loc, rewriter.getIndexType(), indexPlusOne);
3047
3048 Value base =
3049 tensor::ExtractOp::create(rewriter, loc, table, ValueRange{index});
3050 Value next = tensor::ExtractOp::create(rewriter, loc, table,
3051 ValueRange{indexPlusOne});
3052
3053 base =
3054 arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(), base);
3055 next =
3056 arith::ExtSIOp::create(rewriter, loc, rewriter.getI32Type(), next);
3057
3058 // Use the fractional part to interpolate between the input values:
3059 // result = (base << 7) + (next - base) * fraction
3060 Value baseScaled = arith::ShLIOp::create(rewriter, loc, base, seven);
3061 Value diff = arith::SubIOp::create(rewriter, loc, next, base);
3062 Value diffScaled = arith::MulIOp::create(rewriter, loc, diff, fraction);
3063 Value result =
3064 arith::AddIOp::create(rewriter, loc, baseScaled, diffScaled);
3065
3066 linalg::YieldOp::create(rewriter, loc, result);
3067
3068 return success();
3069 }
3070 }
3071
3072 return rewriter.notifyMatchFailure(
3073 op, "unable to create body for tosa.table op");
3074 }
3075};
3076
3077struct RFFT2dConverter final : public OpRewritePattern<RFFT2dOp> {
3078 using OpRewritePattern<RFFT2dOp>::OpRewritePattern;
3079
3080 static bool isRankedTensor(Type type) { return isa<RankedTensorType>(type); }
3081
3082 static OpFoldResult halfPlusOne(OpBuilder &builder, Location loc,
3083 OpFoldResult ofr) {
3084 auto one = arith::ConstantIndexOp::create(builder, loc, 1);
3085 auto two = arith::ConstantIndexOp::create(builder, loc, 2);
3086
3087 auto value = getValueOrCreateConstantIndexOp(builder, loc, ofr);
3088 auto divBy2 = builder.createOrFold<arith::DivUIOp>(loc, value, two);
3089 auto plusOne = builder.createOrFold<arith::AddIOp>(loc, divBy2, one);
3090 return getAsOpFoldResult(plusOne);
3091 }
3092
3093 static RankedTensorType
3094 computeOutputShape(OpBuilder &builder, Location loc, Value input,
3095 llvm::SmallVectorImpl<Value> &dynamicSizes) {
3096 // Get [N, H, W]
3097 auto dims = tensor::getMixedSizes(builder, loc, input);
3098
3099 // Set W = (W / 2) + 1 to account for the half-sized W dimension of the
3100 // output tensors.
3101 dims[2] = halfPlusOne(builder, loc, dims[2]);
3102
3103 llvm::SmallVector<int64_t, 3> staticSizes;
3104 dispatchIndexOpFoldResults(dims, dynamicSizes, staticSizes);
3105
3106 auto elementType = cast<RankedTensorType>(input.getType()).getElementType();
3107 return RankedTensorType::get(staticSizes, elementType);
3108 }
3109
3110 static Value createZeroTensor(PatternRewriter &rewriter, Location loc,
3111 RankedTensorType type,
3112 llvm::ArrayRef<Value> dynamicSizes) {
3113 auto emptyTensor =
3114 tensor::EmptyOp::create(rewriter, loc, type, dynamicSizes);
3115 auto fillValueAttr = rewriter.getZeroAttr(type.getElementType());
3116 auto fillValue = arith::ConstantOp::create(rewriter, loc, fillValueAttr);
3117 auto filledTensor =
3118 linalg::FillOp::create(rewriter, loc, ValueRange{fillValue},
3119 ValueRange{emptyTensor})
3120 .result();
3121 return filledTensor;
3122 }
3123
3124 static Value castIndexToFloat(OpBuilder &builder, Location loc,
3125 FloatType type, Value value) {
3126 auto integerVal = arith::IndexCastUIOp::create(
3127 builder, loc,
3128 type.getIntOrFloatBitWidth() > 32 ? builder.getI64Type()
3129 : builder.getI32Type(),
3130 value);
3131
3132 return arith::UIToFPOp::create(builder, loc, type, integerVal);
3133 }
3134
3135 static Value createLinalgIndex(OpBuilder &builder, Location loc,
3136 FloatType type, int64_t index) {
3137 auto indexVal = linalg::IndexOp::create(builder, loc, index);
3138 return castIndexToFloat(builder, loc, type, indexVal);
3139 }
3140
3141 template <typename... Args>
3142 static llvm::SmallVector<AffineExpr, 4> affineDimsExpr(OpBuilder &builder,
3143 Args... args) {
3144 return {builder.getAffineDimExpr(args)...};
3145 }
3146
3147 LogicalResult matchAndRewrite(RFFT2dOp rfft2d,
3148 PatternRewriter &rewriter) const override {
3149 if (!llvm::all_of(rfft2d->getOperandTypes(), isRankedTensor) ||
3150 !llvm::all_of(rfft2d->getResultTypes(), isRankedTensor)) {
3151 return rewriter.notifyMatchFailure(rfft2d,
3152 "only supports ranked tensors");
3153 }
3154
3155 auto loc = rfft2d.getLoc();
3156 auto input = rfft2d.getInputReal();
3157 auto elementType =
3158 dyn_cast<FloatType>(cast<ShapedType>(input.getType()).getElementType());
3159 if (!elementType)
3160 return rewriter.notifyMatchFailure(rfft2d,
3161 "only supports float element types");
3162
3163 // Compute the output type and set of dynamic sizes
3164 llvm::SmallVector<Value> dynamicSizes;
3165 auto outputType = computeOutputShape(rewriter, loc, input, dynamicSizes);
3166
3167 // Iterator types for the linalg.generic implementation
3168 llvm::SmallVector<utils::IteratorType, 5> iteratorTypes = {
3169 utils::IteratorType::parallel, utils::IteratorType::parallel,
3170 utils::IteratorType::parallel, utils::IteratorType::reduction,
3171 utils::IteratorType::reduction};
3172
3173 // Inputs/outputs to the linalg.generic implementation
3174 llvm::SmallVector<Value> genericOpInputs = {input};
3175 llvm::SmallVector<Value> genericOpOutputs = {
3176 createZeroTensor(rewriter, loc, outputType, dynamicSizes),
3177 createZeroTensor(rewriter, loc, outputType, dynamicSizes)};
3178
3179 // Indexing maps for input and output tensors
3180 auto indexingMaps = AffineMap::inferFromExprList(
3181 llvm::ArrayRef{affineDimsExpr(rewriter, 0, 3, 4),
3182 affineDimsExpr(rewriter, 0, 1, 2),
3183 affineDimsExpr(rewriter, 0, 1, 2)},
3184 rewriter.getContext());
3185
3186 // Width and height dimensions of the original input.
3187 auto dimH = rewriter.createOrFold<tensor::DimOp>(loc, input, 1);
3188 auto dimW = rewriter.createOrFold<tensor::DimOp>(loc, input, 2);
3189
3190 // Constants and dimension sizes
3191 auto zeroFloat = arith::ConstantOp::create(
3192 rewriter, loc, rewriter.getZeroAttr(elementType));
3193 auto twoPiAttr = rewriter.getFloatAttr(elementType, 6.283185307179586);
3194 auto twoPi = arith::ConstantOp::create(rewriter, loc, twoPiAttr);
3195
3196 auto zeroIndex = arith::ConstantIndexOp::create(rewriter, loc, 0);
3197 auto twoIndex = arith::ConstantIndexOp::create(rewriter, loc, 2);
3198
3199 auto constH = castIndexToFloat(rewriter, loc, elementType, dimH);
3200 auto constW = castIndexToFloat(rewriter, loc, elementType, dimW);
3201 auto halfH = index::DivUOp::create(rewriter, loc, dimH, twoIndex);
3202 auto halfW = index::DivUOp::create(rewriter, loc, dimW, twoIndex);
3203
3204 auto buildBody = [&](OpBuilder &builder, Location loc, ValueRange args) {
3205 Value valReal = args[0];
3206 Value sumReal = args[1];
3207 Value sumImag = args[2];
3208
3209 // Indices for angle computation
3210 Value oy = linalg::IndexOp::create(builder, loc, 1);
3211 Value ox = linalg::IndexOp::create(builder, loc, 2);
3212 Value iy = linalg::IndexOp::create(builder, loc, 3);
3213 Value ix = linalg::IndexOp::create(builder, loc, 4);
3214
3215 // Calculating angle without integer parts of components as sin/cos are
3216 // periodic: angle = 2 * pi() * ( ( (iy * oy) % H) / H + ( (ix * ox) % W )
3217 // / W);
3218 auto iyXoy = index::MulOp::create(builder, loc, iy, oy);
3219 auto ixXox = index::MulOp::create(builder, loc, ix, ox);
3220
3221 auto iyRem = index::RemUOp::create(builder, loc, iyXoy, dimH);
3222 auto ixRem = index::RemUOp::create(builder, loc, ixXox, dimW);
3223
3224 auto iyRemFloat = castIndexToFloat(builder, loc, elementType, iyRem);
3225 auto ixRemFloat = castIndexToFloat(builder, loc, elementType, ixRem);
3226
3227 auto yComponent = arith::DivFOp::create(builder, loc, iyRemFloat, constH);
3228 auto xComponent = arith::DivFOp::create(builder, loc, ixRemFloat, constW);
3229 auto sumXY = arith::AddFOp::create(builder, loc, yComponent, xComponent);
3230 auto angle = arith::MulFOp::create(builder, loc, twoPi, sumXY);
3231
3232 // We will check the indices to see if this is a position that should use
3233 // a 0.0 weight for the imaginary value computation following the TOSA
3234 // specification with `tosa_extra_multiplies=true`.
3235 //
3236 // These are the relevant locations: (0,0), (0,W/2), (H/2,0), (H/2, W/2).
3237 auto iyIs0 = arith::CmpIOp::create(builder, loc, arith::CmpIPredicate::eq,
3238 iyRem, zeroIndex);
3239 auto iyIsHalfH = arith::CmpIOp::create(
3240 builder, loc, arith::CmpIPredicate::eq, iyRem, halfH);
3241 auto ixIs0 = arith::CmpIOp::create(builder, loc, arith::CmpIPredicate::eq,
3242 ixRem, zeroIndex);
3243 auto ixIsHalfW = arith::CmpIOp::create(
3244 builder, loc, arith::CmpIPredicate::eq, ixRem, halfW);
3245
3246 auto iyIsSinSkippable =
3247 arith::OrIOp::create(builder, loc, iyIs0, iyIsHalfH);
3248 auto ixIsSinSkippable =
3249 arith::OrIOp::create(builder, loc, ixIs0, ixIsHalfW);
3250 auto shouldSkipSin = arith::AndIOp::create(builder, loc, iyIsSinSkippable,
3251 ixIsSinSkippable);
3252
3253 // realComponent = valReal * cos(angle)
3254 // imagComponent = valReal * (shouldSkipSin ? 0.0 : sin(angle))
3255 auto cosAngle = math::CosOp::create(builder, loc, angle);
3256 auto sinAngle = math::SinOp::create(builder, loc, angle);
3257 auto imagWeight = arith::SelectOp::create(builder, loc, shouldSkipSin,
3258 zeroFloat, sinAngle);
3259 auto realComponent =
3260 arith::MulFOp::create(builder, loc, valReal, cosAngle);
3261 auto imagComponent =
3262 arith::MulFOp::create(builder, loc, valReal, imagWeight);
3263
3264 // outReal = sumReal + realComponent
3265 // outImag = sumImag - imagComponent
3266 auto outReal =
3267 arith::AddFOp::create(builder, loc, sumReal, realComponent);
3268 auto outImag =
3269 arith::SubFOp::create(builder, loc, sumImag, imagComponent);
3270
3271 linalg::YieldOp::create(builder, loc, ValueRange{outReal, outImag});
3272 };
3273
3274 rewriter.replaceOpWithNewOp<linalg::GenericOp>(
3275 rfft2d, rfft2d.getResultTypes(), genericOpInputs, genericOpOutputs,
3276 indexingMaps, iteratorTypes, buildBody);
3277
3278 return success();
3279 }
3280};
3281
3282struct FFT2dConverter final : OpRewritePattern<FFT2dOp> {
3283 using Base::Base;
3284
3285 LogicalResult matchAndRewrite(FFT2dOp fft2d,
3286 PatternRewriter &rewriter) const override {
3287 if (!llvm::all_of(fft2d->getOperandTypes(),
3288 RFFT2dConverter::isRankedTensor) ||
3289 !llvm::all_of(fft2d->getResultTypes(),
3290 RFFT2dConverter::isRankedTensor)) {
3291 return rewriter.notifyMatchFailure(fft2d, "only supports ranked tensors");
3292 }
3293
3294 Location loc = fft2d.getLoc();
3295 Value input_real = fft2d.getInputReal();
3296 Value input_imag = fft2d.getInputImag();
3297 BoolAttr inverse = fft2d.getInverseAttr();
3298
3299 auto real_el_ty = cast<FloatType>(
3300 cast<ShapedType>(input_real.getType()).getElementType());
3301 [[maybe_unused]] auto imag_el_ty = cast<FloatType>(
3302 cast<ShapedType>(input_imag.getType()).getElementType());
3303
3304 assert(real_el_ty == imag_el_ty);
3305
3306 // Compute the output type and set of dynamic sizes
3307 SmallVector<Value> dynamicSizes;
3308
3309 // Get [N, H, W]
3310 auto dims = tensor::getMixedSizes(rewriter, loc, input_real);
3311
3312 SmallVector<int64_t, 3> staticSizes;
3313 dispatchIndexOpFoldResults(dims, dynamicSizes, staticSizes);
3314
3315 auto outputType = RankedTensorType::get(staticSizes, real_el_ty);
3316
3317 // Iterator types for the linalg.generic implementation
3318 SmallVector<utils::IteratorType, 5> iteratorTypes = {
3319 utils::IteratorType::parallel, utils::IteratorType::parallel,
3320 utils::IteratorType::parallel, utils::IteratorType::reduction,
3321 utils::IteratorType::reduction};
3322
3323 // Inputs/outputs to the linalg.generic implementation
3324 SmallVector<Value> genericOpInputs = {input_real, input_imag};
3325 SmallVector<Value> genericOpOutputs = {
3326 RFFT2dConverter::createZeroTensor(rewriter, loc, outputType,
3327 dynamicSizes),
3328 RFFT2dConverter::createZeroTensor(rewriter, loc, outputType,
3329 dynamicSizes)};
3330
3331 // Indexing maps for input and output tensors
3332 auto indexingMaps = AffineMap::inferFromExprList(
3333 ArrayRef{RFFT2dConverter::affineDimsExpr(rewriter, 0, 3, 4),
3334 RFFT2dConverter::affineDimsExpr(rewriter, 0, 3, 4),
3335 RFFT2dConverter::affineDimsExpr(rewriter, 0, 1, 2),
3336 RFFT2dConverter::affineDimsExpr(rewriter, 0, 1, 2)},
3337 rewriter.getContext());
3338
3339 // Width and height dimensions of the original input.
3340 auto dimH = rewriter.createOrFold<tensor::DimOp>(loc, input_real, 1);
3341 auto dimW = rewriter.createOrFold<tensor::DimOp>(loc, input_real, 2);
3342
3343 // Constants and dimension sizes
3344 auto twoPiAttr = rewriter.getFloatAttr(real_el_ty, 6.283185307179586);
3345 auto twoPi = arith::ConstantOp::create(rewriter, loc, twoPiAttr);
3346 Value constH =
3347 RFFT2dConverter::castIndexToFloat(rewriter, loc, real_el_ty, dimH);
3348 Value constW =
3349 RFFT2dConverter::castIndexToFloat(rewriter, loc, real_el_ty, dimW);
3350
3351 auto buildBody = [&](OpBuilder &builder, Location loc, ValueRange args) {
3352 Value valReal = args[0];
3353 Value valImag = args[1];
3354 Value sumReal = args[2];
3355 Value sumImag = args[3];
3356
3357 // Indices for angle computation
3358 Value oy = linalg::IndexOp::create(builder, loc, 1);
3359 Value ox = linalg::IndexOp::create(builder, loc, 2);
3360 Value iy = linalg::IndexOp::create(builder, loc, 3);
3361 Value ix = linalg::IndexOp::create(builder, loc, 4);
3362
3363 // float_t angle = sign_val * 2 * pi() * ( ( (iy * oy) % H) / H + ( (ix *
3364 // ox) % W ) / W);
3365 auto iyXoy = index::MulOp::create(builder, loc, iy, oy);
3366 auto ixXox = index::MulOp::create(builder, loc, ix, ox);
3367
3368 auto iyRem = index::RemUOp::create(builder, loc, iyXoy, dimH);
3369 auto ixRem = index::RemUOp::create(builder, loc, ixXox, dimW);
3370
3371 auto iyRemFloat =
3372 RFFT2dConverter::castIndexToFloat(builder, loc, real_el_ty, iyRem);
3373 auto ixRemFloat =
3374 RFFT2dConverter::castIndexToFloat(builder, loc, real_el_ty, ixRem);
3375
3376 auto yComponent = arith::DivFOp::create(builder, loc, iyRemFloat, constH);
3377 auto xComponent = arith::DivFOp::create(builder, loc, ixRemFloat, constW);
3378
3379 auto sumXY = arith::AddFOp::create(builder, loc, yComponent, xComponent);
3380 auto angle = arith::MulFOp::create(builder, loc, twoPi, sumXY);
3381
3382 if (inverse.getValue()) {
3383 angle = arith::MulFOp::create(
3384 builder, loc, angle,
3385 arith::ConstantOp::create(rewriter, loc,
3386 rewriter.getFloatAttr(real_el_ty, -1.0)));
3387 }
3388
3389 // realComponent = val_real * cos(a) + val_imag * sin(a);
3390 // imagComponent = -val_real * sin(a) + val_imag * cos(a);
3391 auto cosAngle = math::CosOp::create(builder, loc, angle);
3392 auto sinAngle = math::SinOp::create(builder, loc, angle);
3393
3394 auto rcos = arith::MulFOp::create(builder, loc, valReal, cosAngle);
3395 auto rsin = arith::MulFOp::create(builder, loc, valImag, sinAngle);
3396 auto realComponent = arith::AddFOp::create(builder, loc, rcos, rsin);
3397
3398 auto icos = arith::MulFOp::create(builder, loc, valImag, cosAngle);
3399 auto isin = arith::MulFOp::create(builder, loc, valReal, sinAngle);
3400
3401 auto imagComponent = arith::SubFOp::create(builder, loc, icos, isin);
3402
3403 // outReal = sumReal + realComponent
3404 // outImag = sumImag - imagComponent
3405 auto outReal =
3406 arith::AddFOp::create(builder, loc, sumReal, realComponent);
3407 auto outImag =
3408 arith::AddFOp::create(builder, loc, sumImag, imagComponent);
3409
3410 linalg::YieldOp::create(builder, loc, ValueRange{outReal, outImag});
3411 };
3412
3413 rewriter.replaceOpWithNewOp<linalg::GenericOp>(
3414 fft2d, fft2d.getResultTypes(), genericOpInputs, genericOpOutputs,
3415 indexingMaps, iteratorTypes, buildBody);
3416
3417 return success();
3418 }
3419};
3420
3421} // namespace
3422
3424 const TypeConverter &converter, RewritePatternSet *patterns,
3426
3427 // We have multiple resize coverters to handle degenerate cases.
3428 patterns->add<GenericResizeConverter>(patterns->getContext(),
3429 /*benefit=*/100);
3430 patterns->add<ResizeUnaryConverter>(patterns->getContext(),
3431 /*benefit=*/200);
3432 patterns->add<MaterializeResizeBroadcast>(patterns->getContext(),
3433 /*benefit=*/300);
3434
3435 patterns->add<
3436 // clang-format off
3437 PointwiseConverter<tosa::AddOp>,
3438 PointwiseConverter<tosa::SubOp>,
3439 PointwiseConverter<tosa::MulOp>,
3440 PointwiseConverter<tosa::IntDivOp>,
3441 PointwiseConverter<tosa::NegateOp>,
3442 PointwiseConverter<tosa::PowOp>,
3443 PointwiseConverter<tosa::ReciprocalOp>,
3444 PointwiseConverter<tosa::RsqrtOp>,
3445 PointwiseConverter<tosa::LogOp>,
3446 PointwiseConverter<tosa::ExpOp>,
3447 PointwiseConverter<tosa::AbsOp>,
3448 PointwiseConverter<tosa::SinOp>,
3449 PointwiseConverter<tosa::CosOp>,
3450 PointwiseConverter<tosa::TanhOp>,
3451 PointwiseConverter<tosa::ErfOp>,
3452 PointwiseConverter<tosa::BitwiseAndOp>,
3453 PointwiseConverter<tosa::BitwiseOrOp>,
3454 PointwiseConverter<tosa::BitwiseNotOp>,
3455 PointwiseConverter<tosa::BitwiseXorOp>,
3456 PointwiseConverter<tosa::LogicalAndOp>,
3457 PointwiseConverter<tosa::LogicalNotOp>,
3458 PointwiseConverter<tosa::LogicalOrOp>,
3459 PointwiseConverter<tosa::LogicalXorOp>,
3460 PointwiseConverter<tosa::CastOp>,
3461 PointwiseConverter<tosa::LogicalLeftShiftOp>,
3462 PointwiseConverter<tosa::LogicalRightShiftOp>,
3463 PointwiseConverter<tosa::ArithmeticRightShiftOp>,
3464 PointwiseConverter<tosa::ClzOp>,
3465 PointwiseConverter<tosa::SelectOp>,
3466 PointwiseConverter<tosa::GreaterOp>,
3467 PointwiseConverter<tosa::GreaterEqualOp>,
3468 PointwiseConverter<tosa::EqualOp>,
3469 PointwiseConverter<tosa::MaximumOp>,
3470 PointwiseConverter<tosa::MinimumOp>,
3471 PointwiseConverter<tosa::CeilOp>,
3472 PointwiseConverter<tosa::FloorOp>,
3473 PointwiseConverter<tosa::ClampOp>,
3474 PointwiseConverter<tosa::SigmoidOp>
3475 >(converter, patterns->getContext());
3476
3477 patterns->add<QuantizedMatMulTConverter>(converter, patterns->getContext());
3478
3479 patterns->add<
3480 IdentityNConverter<tosa::IdentityOp>,
3481 GatherConverter,
3482 RowGatherConverter,
3483 RescaleConverter,
3484 ReverseConverter,
3485 RFFT2dConverter,
3486 FFT2dConverter,
3487 TableConverter,
3488 TileConverter>(patterns->getContext());
3489
3490 // Reductions seeded with a float min/max identity need to know whether
3491 // non-finite values are available on the target.
3492 patterns->add<
3493 ReduceConverter<tosa::ReduceAllOp>,
3494 ReduceConverter<tosa::ReduceAnyOp>,
3495 ReduceConverter<tosa::ReduceMinOp>,
3496 ReduceConverter<tosa::ReduceMaxOp>,
3497 ReduceConverter<tosa::ReduceSumOp>,
3498 ReduceConverter<tosa::ReduceProductOp>,
3499 ArgMaxConverter>(patterns->getContext(), options.allowNonFinites);
3500 // clang-format on
3501}
return success()
static int64_t product(ArrayRef< int64_t > vals)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static llvm::ManagedStatic< PassManagerOptions > options
static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound, Value upperBound)
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static TypedAttr createInitialValueForReduceOp(Operation *op, Type elementTy, PatternRewriter &rewriter, bool allowNonFinites)
static OpFoldResult getOrFoldTensorDim(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value tensor, int64_t index)
static std::pair< Value, Value > normalizeMatMulTBatchDimensions(PatternRewriter &rewriter, Location loc, Value a, Value b, int64_t batchRank)
static LogicalResult emitElementwiseComputation(ConversionPatternRewriter &rewriter, Location loc, Operation *operation, ValueRange operands, ArrayRef< OpFoldResult > targetShape, const TypeConverter &converter)
static Value createLinalgBodyCalculationForReduceOp(Operation *op, ValueRange args, Type elementTy, PatternRewriter &rewriter)
static OpTy createWithDefaultProperties(OpBuilder &builder, Location loc, TypeRange resultTypes, ValueRange operands)
static Value getTensorDim(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value tensor, int64_t index)
static Value createIndex(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, int64_t index)
static std::pair< OpFoldResult, Value > computeTargetSize(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, ValueRange operands, int64_t dim)
DenseMap< int64_t, Value > IndexPool
static LogicalResult reduceMatchAndRewriteHelper(OpTy op, uint64_t axis, PatternRewriter &rewriter, bool allowNonFinites)
static Value broadcastDynamicDimensions(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value operand, ArrayRef< OpFoldResult > targetShape, ArrayRef< Value > masterOperands)
static Value broadcastDynamicDimension(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, Value operand, int64_t dim, OpFoldResult targetSize, Value masterOperand)
static LogicalResult elementwiseMatchAndRewriteHelper(Operation *operation, ValueRange operands, ConversionPatternRewriter &rewriter, const TypeConverter &converter)
static Value broadcastMatMulTSingletonDimension(PatternRewriter &rewriter, Location loc, Value operand, int64_t dim, OpFoldResult size)
static Value createLinalgBodyCalculationForElementwiseOp(Operation *op, ValueRange args, ArrayRef< Type > resultTypes, ConversionPatternRewriter &rewriter)
static Value broadcastMatMulTLeadingDimensions(PatternRewriter &rewriter, Location loc, Value operand, Value other)
static ValueRange getBroadcastableOperands(Operation *operation, ValueRange operands)
static Value materializeBinaryNanCheckIfRequired(OpTy op, PatternRewriter &rewriter, Value lhs, Value rhs, Value result)
static std::pair< SmallVector< OpFoldResult >, SmallVector< Value > > computeTargetShape(PatternRewriter &rewriter, Location loc, IndexPool &indexPool, ValueRange operands)
static bool operandsAndResultsRanked(Operation *operation)
static const llvm::fltSemantics * getFloatSemantics(TruncfSrcElemTypes etype)
Float semantics the element type attributes of xevm.truncf and xevm.extf stand for.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
static SmallVector< AffineMap, 4 > inferFromExprList(ArrayRef< ArrayRef< AffineExpr > > exprsList, MLIRContext *context)
Returns a vector of AffineMaps; each with as many results as exprs.size(), as many dims as the larges...
BlockArgument getArgument(unsigned i)
Definition Block.h:154
bool getValue() const
Return the boolean value of this attribute.
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
IntegerAttr getI32IntegerAttr(int32_t value)
Definition Builders.cpp:208
FloatType getF32Type()
Definition Builders.cpp:51
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
AffineMap getMultiDimIdentityMap(unsigned rank)
Definition Builders.cpp:396
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
AffineExpr getAffineConstantExpr(int64_t constant)
Definition Builders.cpp:381
IntegerType getI64Type()
Definition Builders.cpp:73
IntegerType getI32Type()
Definition Builders.cpp:71
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
Ty getType(Args &&...args)
Get or construct an instance of the type Ty with provided arguments.
Definition Builders.h:94
BoolAttr getBoolAttr(bool value)
Definition Builders.cpp:108
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
AffineExpr getAffineDimExpr(unsigned position)
Definition Builders.cpp:373
MLIRContext * getContext() const
Definition Builders.h:56
IntegerAttr getI8IntegerAttr(int8_t value)
Definition Builders.cpp:230
An attribute that represents a reference to a dense vector or tensor object.
auto getValues() const
Return the held element values as a range of the given type.
An attribute that represents a reference to a dense integer vector or tensor object.
static DenseIntElementsAttr get(const ShapedType &type, Arg &&arg)
Get an instance of a DenseIntElementsAttr with the given arguments.
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Definition Builders.h:632
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:210
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition Builders.h:528
This class represents a single result from folding an operation.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Value getOperand(unsigned idx)
Definition Operation.h:375
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
unsigned getNumOperands()
Definition Operation.h:371
result_type_range getResultTypes()
Definition Operation.h:453
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:403
result_range getResults()
Definition Operation.h:440
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:429
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
Definition Types.cpp:90
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:389
type_range getType() const
Type front()
Return first type in the range.
Definition TypeRange.h:164
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
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:398
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
Definition ArithOps.cpp:297
InFlightDiagnostic & next(InFlightDiagnostic &diag)
Starts a new message part in an in-flight diagnostic.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:734
Value createCanonicalRankReducingExtractSliceOp(OpBuilder &b, Location loc, Value tensor, RankedTensorType targetType)
Create a rank-reducing ExtractSliceOp @[0 .
OpFoldResult getMixedSize(OpBuilder &builder, Location loc, Value value, int64_t dim)
Return the dimension of the given tensor value.
Definition TensorOps.cpp:82
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given tensor value.
Definition TensorOps.cpp:91
Value clampFloatHelper(Location loc, Value arg, Value min, Value max, OpBuilder &rewriter)
SmallVector< utils::IteratorType > getNParallelLoopsAttrs(unsigned nParallelLoops)
SmallVector< Value > condenseValues(const SmallVector< Value > &values)
std::optional< SmallVector< Value > > checkHasDynamicBatchDims(PatternRewriter &rewriter, Op op, ArrayRef< Value > params)
APFloat getFloatMinMaxIdentity(const llvm::fltSemantics &semantics, bool negative, bool allowNonFinites)
MatMulTOperands prepareMatMulTOperands(PatternRewriter &rewriter, Location loc, Value a, Value b, RankedTensorType outputType)
Broadcast the batch dimensions of the ranked operands and create a zero-filled result tensor for eith...
void populateTosaToLinalgConversionPatterns(const TypeConverter &converter, RewritePatternSet *patterns, const TosaToLinalgOptions &options=TosaToLinalgOptions())
Populates conversion passes from TOSA dialect to Linalg dialect.
Value getTosaConstShape(ImplicitLocOpBuilder &builder, llvm::ArrayRef< int64_t > shape)
SmallVector< int64_t > convertFromMlirShape(ArrayRef< int64_t > shape)
Value clampIntHelper(Location loc, Value arg, Value min, Value max, OpBuilder &rewriter, bool isUnsigned)
bool getConstShapeValues(Operation *op, llvm::SmallVector< int64_t > &result_shape)
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
Definition Matchers.h:490
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
void dispatchIndexOpFoldResults(ArrayRef< OpFoldResult > ofrs, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch multiple OpFoldResults according to the behavior of dispatchIndexOpFoldRe...
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:114
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
OpFoldResult getAsOpFoldResult(Value val)
Given a value, try to extract a constant Attribute.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...