MLIR 24.0.0git
TosaOps.cpp
Go to the documentation of this file.
1//===- TosaOps.cpp - MLIR Dialect for TOSA --------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// \file
10// This file implements the TOSA Specification:
11// https://www.mlplatform.org/tosa/tosa_spec.html
12//
13//===----------------------------------------------------------------------===//
14
25#include "mlir/IR/Matchers.h"
29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/SmallVectorExtras.h"
31#include "llvm/ADT/TypeSwitch.h"
32
33#include <numeric>
34#include <type_traits>
35
36using namespace mlir;
37using namespace mlir::tosa;
38
39#include "mlir/Dialect/Tosa/IR/TosaOpsDialect.cpp.inc"
41
42//===----------------------------------------------------------------------===//
43// Tosa dialect interface includes.
44//===----------------------------------------------------------------------===//
45
46#include "mlir/Dialect/Tosa/IR/TosaEnums.cpp.inc"
47#include "mlir/Dialect/Tosa/IR/TosaInterfaces.cpp.inc"
48
49namespace {
50#include "mlir/Dialect/Tosa/IR/TosaDialectBytecode.cpp.inc"
51
52//===----------------------------------------------------------------------===//
53// Dialect Function Inliner Interface.
54//===----------------------------------------------------------------------===//
55struct TosaInlinerInterface : public DialectInlinerInterface {
56 using DialectInlinerInterface::DialectInlinerInterface;
57
58 //===--------------------------------------------------------------------===//
59 // Analysis Hooks.
60 //===--------------------------------------------------------------------===//
61
62 /// All operations can be inlined by default.
63 bool isLegalToInline(Operation *op, Region *region, bool wouldBeCloned,
64 IRMapping &map) const final {
65 return true;
66 }
67
68 /// All regions with If and While parent operators can be inlined.
69 bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
70 IRMapping &map) const final {
71 return (isa<tosa::IfOp>(dest->getParentOp()) ||
72 isa<tosa::WhileOp>(dest->getParentOp()));
73 }
74};
75
76/// This class implements the bytecode interface for the Tosa dialect.
77struct TosaDialectBytecodeInterface : public BytecodeDialectInterface {
78 TosaDialectBytecodeInterface(Dialect *dialect)
79 : BytecodeDialectInterface(dialect) {}
80
81 //===--------------------------------------------------------------------===//
82 // Attributes
83
84 Attribute readAttribute(DialectBytecodeReader &reader) const override {
85 return ::readAttribute(getContext(), reader);
86 }
87
88 LogicalResult writeAttribute(Attribute attr,
89 DialectBytecodeWriter &writer) const override {
90 return ::writeAttribute(attr, writer);
91 }
92
93 //===--------------------------------------------------------------------===//
94 // Types
95
96 Type readType(DialectBytecodeReader &reader) const override {
97 return ::readType(getContext(), reader);
98 }
99
100 LogicalResult writeType(Type type,
101 DialectBytecodeWriter &writer) const override {
102 return ::writeType(type, writer);
103 }
104
105 void writeVersion(DialectBytecodeWriter &writer) const final {
106 // TODO: Populate.
107 }
108
109 std::unique_ptr<DialectVersion>
110 readVersion(DialectBytecodeReader &reader) const final {
111 // TODO: Populate
112 reader.emitError("Dialect does not support versioning");
113 return nullptr;
114 }
115
116 LogicalResult upgradeFromVersion(Operation *topLevelOp,
117 const DialectVersion &version) const final {
118 return success();
119 }
120};
121
122} // namespace
123
124//===----------------------------------------------------------------------===//
125// TOSA control flow support.
126//===----------------------------------------------------------------------===//
127
128/// Returns the while loop body.
129SmallVector<Region *> tosa::WhileOp::getLoopRegions() {
130 return {&getBodyGraph()};
131}
132
133//===----------------------------------------------------------------------===//
134// TOSA variable operator support.
135//===----------------------------------------------------------------------===//
136
138 return map_to_vector(shape, [](int64_t dim) {
139 return dim == -1 ? ShapedType::kDynamic : dim;
140 });
141}
142
143// returns type of variable op
144RankedTensorType mlir::tosa::getVariableType(tosa::VariableOp variableOp) {
145 Type elementType = variableOp.getType();
146 DenseIntElementsAttr varShapeAttr = variableOp.getVarShape();
147 auto shape = convertToMlirShape(to_vector(varShapeAttr.getValues<int64_t>()));
148 return RankedTensorType::get(shape, elementType);
149}
150
151//===----------------------------------------------------------------------===//
152// Tosa dialect initialization.
153//===----------------------------------------------------------------------===//
154
155void TosaDialect::initialize() {
156 addTypes<
157#define GET_TYPEDEF_LIST
158#include "mlir/Dialect/Tosa/IR/TosaOpsTypesBase.cpp.inc"
159 >();
160 addOperations<
161#define GET_OP_LIST
162#include "mlir/Dialect/Tosa/IR/TosaOps.cpp.inc"
163 >();
164 addAttributes<
165#define GET_ATTRDEF_LIST
166#include "mlir/Dialect/Tosa/IR/TosaAttributes.cpp.inc"
167 >();
168 addInterfaces<TosaDialectBytecodeInterface, TosaInlinerInterface>();
169 declarePromisedInterfaces<
170 shard::ShardingInterface, ClampOp, SigmoidOp, TanhOp, AddOp,
171 ArithmeticRightShiftOp, BitwiseAndOp, BitwiseOrOp, BitwiseXorOp, IntDivOp,
172 LogicalAndOp, LogicalLeftShiftOp, LogicalRightShiftOp, LogicalOrOp,
173 LogicalXorOp, MaximumOp, MinimumOp, MulOp, PowOp, SubOp, AbsOp,
174 BitwiseNotOp, CeilOp, ClzOp, ExpOp, FloorOp, LogOp, LogicalNotOp,
175 NegateOp, ReciprocalOp, RsqrtOp, SelectOp, EqualOp, GreaterOp,
176 GreaterEqualOp, MatMulOp>();
177}
178
179Operation *TosaDialect::materializeConstant(OpBuilder &builder, Attribute value,
180 Type type, Location loc) {
181 // Tosa dialect constants only support ElementsAttr unlike standard dialect
182 // constant which supports all attributes.
183 if (llvm::isa<shapeType>(type) && llvm::isa<DenseIntElementsAttr>(value)) {
184 return tosa::ConstShapeOp::create(builder, loc, type,
185 llvm::cast<DenseIntElementsAttr>(value));
186 }
187 if (llvm::isa<ElementsAttr>(value))
188 return tosa::ConstOp::create(builder, loc, type,
189 llvm::cast<ElementsAttr>(value));
190 return nullptr;
191}
192
193//===----------------------------------------------------------------------===//
194// Parsers and printers
195//===----------------------------------------------------------------------===//
196
197namespace {
198
199ParseResult getShapeAndElementType(OpAsmParser &parser, Type parsedType,
200 DenseElementsAttr &varShapeAttr,
201 TypeAttr &typeAttr) {
202 if (auto shapedType = dyn_cast<ShapedType>(parsedType)) {
203 if (!shapedType.hasRank())
204 return parser.emitError(parser.getCurrentLocation())
205 << "expected ranked type";
206
207 auto elementType = shapedType.getElementType();
208 typeAttr = TypeAttr::get(elementType);
209 ArrayRef<int64_t> shape = shapedType.getShape();
210 Builder builder(parser.getContext());
211 varShapeAttr = builder.getIndexTensorAttr(convertFromMlirShape(shape));
212 return success();
213 }
214 return parser.emitError(parser.getCurrentLocation())
215 << "expected shaped type";
216}
217
218} // namespace
219
220// parses the optional initial value or type for a tosa variable
221// with initial value:
222// tosa.variable @name = dense<0.0> : tensor<1x8xf32>
223//
224// without initial value:
225// tosa.variable @name : tensor<1x8xf32>
227 OpAsmParser &parser, DenseElementsAttr &varShapeAttr, TypeAttr &typeAttr,
228 Attribute &initialValueAttr) {
229 if (succeeded(parser.parseOptionalEqual())) {
230 if (failed(parser.parseAttribute(initialValueAttr))) {
231 return parser.emitError(parser.getCurrentLocation())
232 << "expected attribute";
233 }
234 if (auto typedAttr = dyn_cast<TypedAttr>(initialValueAttr)) {
235 return getShapeAndElementType(parser, typedAttr.getType(), varShapeAttr,
236 typeAttr);
237 }
238 return parser.emitError(parser.getCurrentLocation())
239 << "expected Typed attr";
240 }
241
242 initialValueAttr = nullptr;
243 Type parsedType;
244 if (failed(parser.parseColonType(parsedType))) {
245 return parser.emitError(parser.getCurrentLocation())
246 << "expected type after colon";
247 }
248 return getShapeAndElementType(parser, parsedType, varShapeAttr, typeAttr);
249}
250
252 OpAsmPrinter &p, Operation *op, DenseElementsAttr varShapeAttr,
253 TypeAttr typeAttr, Attribute initialValueAttr) {
254 bool needsSpace = false;
255 if (!dyn_cast_or_null<TypedAttr>(initialValueAttr)) {
256 auto shape =
257 convertToMlirShape(to_vector(varShapeAttr.getValues<int64_t>()));
258 Type elementType = typeAttr.getValue();
259 RankedTensorType tensorType =
260 RankedTensorType::get(ArrayRef<int64_t>(shape), elementType);
261 auto tensorTypeAttr = TypeAttr::get(tensorType);
262 p << ": ";
263 p.printAttribute(tensorTypeAttr);
264 needsSpace = true; // subsequent attr value needs a space separator
265 }
266 if (initialValueAttr) {
267 if (needsSpace)
268 p << ' ';
269 p << "= ";
270 p.printAttribute(initialValueAttr);
271 }
272}
273
274//===----------------------------------------------------------------------===//
275// Tosa utilities.
276//===----------------------------------------------------------------------===//
277
278static std::optional<int64_t> idivCheck(const int64_t lhs, const int64_t rhs) {
279 if (lhs % rhs != 0)
280 return std::nullopt;
281 return lhs / rhs;
282}
283
285 auto srcType = getElementTypeOrSelf(type);
286 if (auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(srcType))
287 srcType = getStorageElementTypeFromQuantized(quantType);
288 return srcType;
289}
290
294
295static LogicalResult verifyRescaleValueAndZpTypes(Operation *op, Value val,
296 Value valZp, StringRef name) {
298 Type eZpType = getStorageElementTypeOrSelf(valZp.getType());
299
300 bool bothInts =
301 mlir::isa<IntegerType>(eType) && mlir::isa<IntegerType>(eZpType);
302 bool sameBitWidth =
303 (eType.getIntOrFloatBitWidth() == eZpType.getIntOrFloatBitWidth());
304
305 if (!bothInts || !sameBitWidth) {
306 return op->emitOpError()
307 << "expected " << name << " and " << name
308 << "_zp to both be integer of the same bitwidth, but got " << eType
309 << " vs. " << eZpType;
310 }
311 return success();
312}
313
314// Create a pad-const const tensor with value of `val` of required data-type
316 Value src, int32_t val) {
317 const auto srcType = getElementTypeOrSelf(src);
318 const auto srcElemType = getStorageElementTypeOrSelf(src);
319 const auto padConstType = mlir::RankedTensorType::get({1}, srcType);
320 const auto padConstEType = mlir::RankedTensorType::get({1}, srcElemType);
321 const auto padConstAttr{
322 llvm::isa<FloatType>(srcElemType)
323 ? DenseElementsAttr::get(padConstEType,
324 builder.getFloatAttr(srcElemType, val))
325 : DenseElementsAttr::get(padConstEType,
326 builder.getIntegerAttr(srcElemType, val))};
327 return tosa::ConstOp::create(builder, loc, padConstType, padConstAttr);
328}
329
331 if (auto blockScaledTy = dyn_cast<tosa::BlockScaledType>(type))
332 return getBitWidth(blockScaledTy.getValueType());
333 if (dyn_cast<tosa::mxint8Type>(type))
334 return 8;
335 return type.getIntOrFloatBitWidth();
336}
337
338// Update dim size if current dim is dynamic, otherwise raise an error if sizes
339// do not match
340LogicalResult tryUpdateDimOrFailure(Operation *op, int64_t &currDim,
341 const int64_t newDim,
342 const StringRef operandName,
343 const StringRef dimName) {
344 if (ShapedType::isDynamic(currDim)) {
345 currDim = newDim;
346 return success();
347 } else if (ShapedType::isStatic(newDim) && currDim != newDim) {
348 return op->emitOpError("expected ")
349 << dimName << " of " << operandName << " to match size " << currDim
350 << ", got " << newDim;
351 }
352 return success();
353}
354
357 auto printDim = [&](int64_t dim) {
358 if (ShapedType::isDynamic(dim))
359 diag << "?";
360 else
361 diag << dim;
362 };
363
364 llvm::interleaveComma(shape, diag, printDim);
365}
366
367static LogicalResult
369 ArrayRef<int64_t> expectedShape,
370 StringRef outputName = "output") {
371 assert(outputType.hasRank() && "expected output type to be ranked");
372
373 if (succeeded(verifyCompatibleShape(outputType.getShape(), expectedShape)))
374 return success();
375
376 InFlightDiagnostic diag = op->emitOpError("expected ");
377 diag << outputName << " shape ";
378 printShapeToDiagnostic(diag, outputType.getShape());
379 diag << " to be compatible with inferred shape ";
380 printShapeToDiagnostic(diag, expectedShape);
381 return diag;
382}
383
385 Operation *op, const int64_t inputSize, const int64_t kernelSize,
386 const int64_t outputSize, const int64_t padBefore, const int64_t padAfter,
387 const int64_t stride, const int64_t dilation, const llvm::StringRef dimName,
388 const llvm::StringRef dimAxis, const llvm::StringRef padBeforeName,
389 const llvm::StringRef padAfterName) {
390 if (inputSize == ShapedType::kDynamic || kernelSize == ShapedType::kDynamic)
391 return success();
392
393 // ERROR_IF: O != idiv_check(I - 1 + pa + pb - (K - 1) * d, s) + 1
394
395 const std::optional<int64_t> calculatedOutSizeMinusOne = idivCheck(
396 inputSize - 1 + padBefore + padAfter - (kernelSize - 1) * dilation,
397 stride);
398 if (!calculatedOutSizeMinusOne.has_value())
399 return op->emitOpError("expected input_")
400 << dimName << " - 1 + pad_" << padBeforeName << " + pad_"
401 << padAfterName << " - (kernel_" << dimName << " - 1) * dilation_"
402 << dimAxis << " to be wholly divisible by stride_" << dimAxis
403 << ", got (" << inputSize << " - 1 + " << padBefore << " + "
404 << padAfter << " - (" << kernelSize << " - 1) * " << dilation
405 << ") / " << stride;
406
407 const int64_t calculatedOutSize = calculatedOutSizeMinusOne.value() + 1;
408 if (outputSize != ShapedType::kDynamic && calculatedOutSize != outputSize)
409 return op->emitOpError("calculated output ")
410 << dimName << " did not match expected: "
411 << "calculated=" << calculatedOutSize << ", expected=" << outputSize;
412
413 return success();
414}
415
416//===----------------------------------------------------------------------===//
417// mxint8Type DenseElementTypeInterface implementation.
418//===----------------------------------------------------------------------===//
419size_t mlir::tosa::mxint8Type::getDenseElementBitSize() const { return 8; }
420
422mlir::tosa::mxint8Type::convertToAttribute(ArrayRef<char> rawData) const {
423 assert(rawData.size() == 1 && "expected 1 byte for tosa.mxint8 element");
424 const auto intType = IntegerType::get(getContext(), 8);
425 return intType.convertToAttribute(rawData);
426}
427
428LogicalResult mlir::tosa::mxint8Type::convertFromAttribute(
430 const auto intAttr = dyn_cast<IntegerAttr>(attr);
431 if (!intAttr)
432 return failure();
433 const Type attrType = intAttr.getType();
434 if (!attrType.isSignlessInteger(8))
435 return failure();
436 return cast<IntegerType>(attrType).convertFromAttribute(attr, result);
437}
438
439//===----------------------------------------------------------------------===//
440// TOSA block scaling utilities.
441//===----------------------------------------------------------------------===//
442
445 bool allowScaleValues) {
446 const auto tensorType = llvm::cast<ShapedType>(type);
447 const BlockScaledType elemType =
448 llvm::dyn_cast<BlockScaledType>(tensorType.getElementType());
449 if (!elemType)
450 return success();
451
452 if (!allowScaleValues && elemType.hasScaleValues()) {
453 if (emitError)
454 emitError()
455 << "block scaled tensor type with scale values is not allowed";
456 return failure();
457 }
458
459 if (!tensorType.hasRank())
460 return success();
461
462 if (tensorType.getRank() == 0) {
463 if (emitError)
464 emitError() << "block scaled tensor type must have rank greater than "
465 "zero";
466 return failure();
467 }
468
469 const ArrayRef<int64_t> tensorShape = tensorType.getShape();
470 const uint32_t blockSize =
471 BlockShapeAttr::getBlockShapeValue(elemType.getBlockShape());
472
473 if (allowScaleValues && elemType.hasScaleValues() &&
474 tensorType.hasStaticShape()) {
475 const size_t numBlocks = tensorType.getNumElements() / blockSize;
476 if (elemType.getScaleValues().size() != numBlocks) {
477 if (emitError)
478 emitError() << "block scaled tensor type with scale values must have "
479 "scale values for each block, expected "
480 << numBlocks << ", got "
481 << elemType.getScaleValues().size();
482 return failure();
483 }
484 }
485
486 const int64_t blockedDimension = tensorShape.back();
487 if (ShapedType::isDynamic(blockedDimension))
488 return success();
489
490 if (blockedDimension % blockSize != 0) {
491 if (emitError)
492 emitError() << "last dimension of block scaled tensor type ("
493 << blockedDimension << ") must be divisible by block size ("
494 << blockSize << ")";
495
496 return failure();
497 }
498
499 return success();
500}
501
503 MLIRContext *ctx = type.getContext();
504 std::string message;
506 ctx, [&](Diagnostic &diag) { message = diag.str(); });
507
509 type, [ctx] { return emitError(UnknownLoc::get(ctx)); })) &&
510 !message.empty()) {
511 return ": " + message;
512 }
513
514 return "";
515}
516
517static ParseResult parseScaleValues(AsmParser &parser,
518 SmallVector<Attribute> &scaleValues,
519 Type scaleType) {
520 const auto parseScaleValue = [&]() -> ParseResult {
521 const SMLoc loc = parser.getCurrentLocation();
522
523 double floatValue;
524 if (parser.parseFloat(floatValue))
525 return failure();
526
527 if (floatValue < 0.0)
528 return parser.emitError(loc, "scale value must be non-negative, got ")
529 << floatValue;
530
531 Type attrType = scaleType;
532 if (succeeded(parser.parseOptionalColon()) && parser.parseType(attrType))
533 return failure();
534
535 if (attrType != scaleType)
536 return parser.emitError(loc, "parsed attribute type ")
537 << attrType << " does not match expected scale type " << scaleType;
538
539 scaleValues.push_back(FloatAttr::get(attrType, floatValue));
540 return success();
541 };
542
543 return parser.parseCommaSeparatedList(parseScaleValue);
544}
545
546static void printScaleValues(AsmPrinter &printer,
547 ArrayRef<Attribute> scaleValues, Type) {
548 llvm::interleaveComma(scaleValues, printer, [&](Attribute scaleValue) {
549 printer.printAttributeWithoutType(scaleValue);
550 });
551}
552
553size_t mlir::tosa::BlockScaledType::getDenseElementBitSize() const {
554 const Type valueType = getValueType();
555 if (isa<tosa::mxint8Type>(valueType))
556 return 8;
557 return valueType.getIntOrFloatBitWidth();
558}
559
561mlir::tosa::BlockScaledType::convertToAttribute(ArrayRef<char> rawData) const {
562 // Block scaled values are stored as a single byte. This is because possible
563 // value data types are either 8-bit or sub-byte. Sub-byte types are aligned
564 // to 8-bits.
565 assert(rawData.size() == 1 && "expected 1 byte for block_scaled element");
566 const Type valueType = getValueType();
567 if (const auto mxint8Value = dyn_cast<tosa::mxint8Type>(valueType))
568 return mxint8Value.convertToAttribute(rawData);
569 if (!isa<FloatType>(valueType))
570 return {};
571 return mlir::detail::convertFloatTypeToAttribute(valueType, rawData);
572}
573
574LogicalResult mlir::tosa::BlockScaledType::convertFromAttribute(
576 const Type valueType = getValueType();
577 if (const auto mxint8Value = dyn_cast<tosa::mxint8Type>(valueType))
578 return mxint8Value.convertFromAttribute(attr, result);
579
580 const auto floatAttr = dyn_cast<FloatAttr>(attr);
581 if (!floatAttr || floatAttr.getType() != valueType)
582 return failure();
583 // const APFloat value = floatAttr.getValue();
584 return mlir::detail::convertFloatTypeFromAttribute(valueType, floatAttr,
585 result);
586}
587
588//===----------------------------------------------------------------------===//
589// TOSA Operator shape inference
590//===----------------------------------------------------------------------===//
591
592template <typename A, std::enable_if_t<std::is_same_v<A, ArgMaxOp::Adaptor> ||
593 std::is_same_v<A, ArgMinOp::Adaptor>,
594 int> = 0>
596 MLIRContext *context, ::std::optional<Location> location, A adaptor,
597 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
598 ShapeAdaptor inputShape(adaptor.getInput().getType());
599 IntegerAttr axis = adaptor.getProperties().axis;
600 int32_t axisVal = axis.getValue().getSExtValue();
601
602 if (!inputShape.hasRank()) {
603 inferredReturnShapes.push_back(ShapedTypeComponents());
604 return success();
605 }
606
607 const auto inputRank = inputShape.getRank();
608 SmallVector<int64_t> outShape;
609 outShape.reserve(inputRank - 1);
610 for (int i = 0, s = inputRank; i < s; i++) {
611 if (i == axisVal)
612 continue;
613 outShape.push_back(inputShape.getDimSize(i));
614 }
615
616 inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
617 return success();
618}
619
620//===----------------------------------------------------------------------===//
621// TOSA Operator Verifiers.
622//===----------------------------------------------------------------------===//
623template <typename T>
624LogicalResult argMaxMinVerify(T op) {
625 const ShapedType resultType = llvm::cast<ShapedType>(op.getType());
626
627 if (const auto resultETy = resultType.getElementType();
628 !resultETy.isIntOrIndex())
629 return op.emitOpError("result tensor is not of integer type");
630
631 const auto inputType = llvm::cast<ShapedType>(op.getInput().getType());
632 if (!inputType.hasRank())
633 return success();
634
635 // Ensure axis is within the tensor rank
636 const int64_t axis = op.getAxisAttr().getInt();
637 if (((axis < 0) || axis >= inputType.getRank()))
638 return op.emitOpError("specified axis is outside the rank of the tensor");
639
640 if (!resultType.hasRank())
641 return success();
642
643 const ArrayRef<int64_t> inputShape = inputType.getShape();
644 const ArrayRef<int64_t> outputShape = resultType.getShape();
645 llvm::SmallVector<int64_t> expectedOutputShape(inputShape);
646 expectedOutputShape.erase(expectedOutputShape.begin() + axis);
647 if (failed(verifyCompatibleShape(expectedOutputShape, outputShape)))
648 return op.emitOpError("expected output shape '")
649 << expectedOutputShape << "', got '" << outputShape << "'";
650
651 return success();
652}
653
654template <typename T>
655static LogicalResult verifyConvOp(T op) {
656 const auto inputType = llvm::dyn_cast<TensorType>(op.getInput().getType());
657 const auto weightType = llvm::dyn_cast<TensorType>(op.getWeight().getType());
658
659 auto inputEType = inputType.getElementType();
660 auto weightEType = weightType.getElementType();
661 auto biasEType =
662 llvm::cast<ShapedType>(op.getBias().getType()).getElementType();
663 auto resultEType =
664 llvm::cast<ShapedType>(op.getResult().getType()).getElementType();
665 bool biasIsFloat = llvm::isa<FloatType>(biasEType);
666 bool resultIsFloat = llvm::isa<FloatType>(resultEType);
667
668 if (auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(inputEType))
669 inputEType = getStorageElementTypeFromQuantized(quantType);
670
671 if (auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(weightEType))
672 weightEType = getStorageElementTypeFromQuantized(quantType);
673
674 if (auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(biasEType))
675 biasEType = getStorageElementTypeFromQuantized(quantType);
676
677 if (auto quantType = llvm::dyn_cast<mlir::quant::QuantizedType>(resultEType))
678 resultEType = getStorageElementTypeFromQuantized(quantType);
679
680 if (biasIsFloat && resultIsFloat && (biasEType != resultEType)) {
681 // for now, only enforce bias element type == result element type for
682 // float types.
683 op.emitOpError(
684 "expect both bias and result to have same element type, got ")
685 << biasEType << " and " << resultEType;
686 return failure();
687 }
688
689 const bool isInputBlockScaled = llvm::isa<BlockScaledType>(inputEType);
690 const bool isWeightBlockScaled = llvm::isa<BlockScaledType>(weightEType);
691 const bool isInputFloat = llvm::isa<FloatType>(inputEType);
692 const bool isWeightFloat = llvm::isa<FloatType>(weightEType);
693
694 const bool isInputBSorFloat = isInputBlockScaled || isInputFloat;
695 const bool isWeightBSorFloat = isWeightBlockScaled || isWeightFloat;
696
697 // Either both must be float or both non-float.
698 if (isInputBSorFloat != isWeightBSorFloat) {
699 op.emitOpError(
700 "expect both input and weight to be float or not together, got ")
701 << inputEType << " and " << weightEType;
702 return failure();
703 }
704
705 auto inputZpEType = getStorageElementTypeOrSelf(op.getInputZp().getType());
706 if (!isInputBlockScaled && inputEType != inputZpEType) {
707 return op.emitOpError("expect both input and its zero point are the same "
708 "element type, got ")
709 << inputEType << " and " << inputZpEType;
710 }
711 if (isInputBlockScaled && !llvm::isa<Float32Type>(inputZpEType)) {
712 return op.emitOpError(
713 "expect block scaled input to have fp32 zero point, got ")
714 << inputEType << " and " << inputZpEType;
715 }
716
717 auto weightZpEType = getStorageElementTypeOrSelf(op.getWeightZp().getType());
718 if (!isWeightBlockScaled && weightEType != weightZpEType) {
719 return op.emitOpError("expect both weight and its zero point are the same "
720 "element type, got ")
721 << weightEType << " and " << weightZpEType;
722 }
723 if (isWeightBlockScaled && !llvm::isa<Float32Type>(weightZpEType)) {
724 return op.emitOpError(
725 "expect block scaled weight to have fp32 zero point, got ")
726 << weightEType << " and " << weightZpEType;
727 }
728
729 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
730 if (succeeded(maybeIZp) && op.verifyInputZeroPoint(*maybeIZp).failed())
731 return failure();
732
733 FailureOr<int64_t> maybeWZp = op.getWeightZeroPoint();
734 if (succeeded(maybeWZp) && op.verifyWeightZeroPoint(*maybeWZp).failed())
735 return failure();
736
737 return success();
738}
739
740LogicalResult tosa::ConstOp::verify() {
741 Operation &op = *getOperation();
742 auto attrType = llvm::dyn_cast<TensorType>(getValuesAttr().getType());
743 auto outputType = llvm::dyn_cast<TensorType>(getOutput().getType());
744
745 if (!attrType || !outputType) {
746 emitOpError("expected tensors for attr/result type");
747 return failure();
748 }
749
750 const Type attrElemType = attrType.getElementType();
751 const Type resultElemType = outputType.getElementType();
752
753 if (auto result =
754 llvm::dyn_cast<mlir::quant::QuantizedType>(resultElemType)) {
755 if (getStorageElementTypeFromQuantized(result) == attrElemType)
756 return success();
757 }
758
759 if (auto attrBlockScaledType =
760 llvm::dyn_cast<mlir::tosa::BlockScaledType>(attrElemType)) {
761 if (!attrBlockScaledType.hasScaleValues())
762 return op.emitOpError(
763 "attribute block scaled type must have scale values");
764
765 const auto emitAttributeError = [&op]() {
766 return op.emitOpError("attribute block scaled type is invalid: ");
767 };
768
769 if (failed(verifyBlockScaledTensorType(attrType, emitAttributeError, true)))
770 return failure();
771
772 const BlockScaledType resultBlockScaledType =
773 llvm::dyn_cast<mlir::tosa::BlockScaledType>(resultElemType);
774 if (!resultBlockScaledType)
775 return op.emitOpError(
776 "result type must be block scaled type if attribute is block "
777 "scaled type");
778
779 if (attrBlockScaledType.getValueType() !=
780 resultBlockScaledType.getValueType() ||
781 attrBlockScaledType.getScaleType() !=
782 resultBlockScaledType.getScaleType() ||
783 attrBlockScaledType.getBlockShape() !=
784 resultBlockScaledType.getBlockShape())
785 return op.emitOpError(
786 "expected block scaled element type to be compatible "
787 "between attr and result, got ")
788 << attrBlockScaledType << " vs. " << resultBlockScaledType;
789
790 return success();
791 }
792
793 if (attrElemType != resultElemType)
794 return emitOpError("expected same attr/result element types");
795
796 return success();
797}
798
799//===----------------------------------------------------------------------===//
800// ERROR_IF functions.
801// ERROR_IF is a predicate that must set an error if the condition holds.
802//===----------------------------------------------------------------------===//
803
804template <typename T>
805static LogicalResult verifyConvOpErrorIf(T op) {
806 llvm::ArrayRef<int64_t> padding = op.getPad();
807 if (llvm::any_of(padding, [](int64_t p) { return p < 0; }))
808 return op.emitOpError("expect all padding values to be >= 0, got ")
809 << padding;
810
811 llvm::ArrayRef<int64_t> strides = op.getStride();
812 if (llvm::any_of(strides, [](int64_t s) { return s < 1; }))
813 return op.emitOpError("expect all stride values to be >= 1, got ")
814 << strides;
815
816 llvm::ArrayRef<int64_t> dilations = op.getDilation();
817 if (llvm::any_of(dilations, [](int64_t d) { return d < 1; }))
818 return op.emitOpError("expect all dilation values to be >= 1, got ")
819 << dilations;
820
821 const RankedTensorType outputType =
822 llvm::dyn_cast<RankedTensorType>(op.getOutput().getType());
823 if (!outputType)
824 // Skip following checks if output is not ranked
825 return success();
826
827 const RankedTensorType inputType =
828 llvm::dyn_cast<RankedTensorType>(op.getInput().getType());
829 const RankedTensorType weightType =
830 llvm::dyn_cast<RankedTensorType>(op.getWeight().getType());
831
832 if (inputType && weightType) {
833 // input = [_,IH,IW,_], weight = [_,KH,KW,_], output = [_,OH,OW,_]
834 if constexpr (std::is_same<T, tosa::Conv2DOp>::value) {
835 if (failed(verifyConvOutputSize(
836 op, inputType.getDimSize(1), weightType.getDimSize(1),
837 outputType.getDimSize(1), padding[0], padding[1], strides[0],
838 dilations[0], "height", "y", "top", "bottom")))
839 return failure();
840
841 if (failed(verifyConvOutputSize(
842 op, inputType.getDimSize(2), weightType.getDimSize(2),
843 outputType.getDimSize(2), padding[2], padding[3], strides[1],
844 dilations[1], "width", "x", "left", "right")))
845 return failure();
846 }
847
848 // input = [_,IH,IW,_], weight = [KH,KW,_,_], output = [_,OH,OW,_]
849 if constexpr (std::is_same<T, tosa::DepthwiseConv2DOp>::value) {
850 if (failed(verifyConvOutputSize(
851 op, inputType.getDimSize(1), weightType.getDimSize(0),
852 outputType.getDimSize(1), padding[0], padding[1], strides[0],
853 dilations[0], "height", "y", "top", "bottom")))
854 return failure();
855
856 if (failed(verifyConvOutputSize(
857 op, inputType.getDimSize(2), weightType.getDimSize(1),
858 outputType.getDimSize(2), padding[2], padding[3], strides[1],
859 dilations[1], "width", "x", "left", "right")))
860 return failure();
861 }
862
863 // input = [_,ID,IH,IW,_], weight = [_,KD,KH,KW,_], output = [_,OD,OH,OW,_]
864 if constexpr (std::is_same<T, tosa::Conv3DOp>::value) {
865 if (failed(verifyConvOutputSize(
866 op, inputType.getDimSize(1), weightType.getDimSize(1),
867 outputType.getDimSize(1), padding[0], padding[1], strides[0],
868 dilations[0], "depth", "d", "front", "back")))
869 return failure();
870
871 if (failed(verifyConvOutputSize(
872 op, inputType.getDimSize(2), weightType.getDimSize(2),
873 outputType.getDimSize(2), padding[2], padding[3], strides[1],
874 dilations[1], "height", "y", "top", "bottom")))
875 return failure();
876
877 if (failed(verifyConvOutputSize(
878 op, inputType.getDimSize(3), weightType.getDimSize(3),
879 outputType.getDimSize(3), padding[4], padding[5], strides[2],
880 dilations[2], "width", "x", "left", "right")))
881 return failure();
882 }
883 }
884
885 const RankedTensorType biasType =
886 llvm::dyn_cast<RankedTensorType>(op.getBias().getType());
887 if (!biasType)
888 // Skip following checks if bias is not ranked
889 return success();
890
891 const int64_t biasChannels = biasType.getDimSize(0);
892 const int64_t outputChannels =
893 outputType.getDimSize(outputType.getRank() - 1);
894 if (biasChannels == ShapedType::kDynamic ||
895 outputChannels == ShapedType::kDynamic)
896 // Skip following checks if biasChannels or outputChannels is dynamic dim
897 return success();
898
899 if (biasChannels != outputChannels && biasChannels != 1)
900 return op.emitOpError(
901 "bias channels expected to be equal to output channels (")
902 << outputChannels << ") or 1, got " << biasChannels;
903
904 return success();
905}
906
907// Verify whether same type and shape of the given two types.
908static LogicalResult errorIfTypeOrShapeMismatch(Operation *op, Type type1,
909 StringRef name1, Type type2,
910 StringRef name2) {
911 auto shapeType1 = dyn_cast<ShapedType>(type1);
912 auto shapeType2 = dyn_cast<ShapedType>(type2);
913 if (!shapeType1 || !shapeType2)
914 return failure();
915
916 auto elemType1 = shapeType1.getElementType();
917 auto elemType2 = shapeType2.getElementType();
918 if (elemType1 != elemType2)
919 return op->emitOpError()
920 << "require same element type for " << name1 << " (" << elemType1
921 << ") and " << name2 << " (" << elemType2 << ")";
922
923 if (failed(verifyCompatibleShape(type1, type2)))
924 return op->emitOpError()
925 << "require same shapes for " << name1 << " (" << type1 << ") and "
926 << name2 << " (" << type2 << ")";
927
928 return success();
929}
930
931// Verify whether same length, type, and shape of the given two tensor lists.
932static LogicalResult errorIfTypeOrShapeMismatch(Operation *op, ValueRange list1,
933 StringRef name1,
934 ValueRange list2,
935 StringRef name2) {
936 if (list1.size() != list2.size())
937 return op->emitOpError()
938 << "require same number of values in " << name1 << " ("
939 << list1.size() << ") and " << name2 << " (" << list2.size() << ")";
940
941 for (auto [type1, type2] :
942 llvm::zip_equal(list1.getTypes(), list2.getTypes())) {
943 if (errorIfTypeOrShapeMismatch(op, type1, name1, type2, name2).failed())
944 return failure();
945 }
946
947 return success();
948}
949
950static inline LogicalResult errorIfShapeNotSizeOne(Operation *op, Type type) {
951 ShapeAdaptor shapeAdaptor(type);
952 if (!shapeAdaptor.hasRank() || !shapeAdaptor.hasStaticShape())
953 return success();
954
955 return shapeAdaptor.getNumElements() == 1 ? success() : failure();
956}
957
958template <typename T>
959static LogicalResult verifyVariableOpErrorIf(T op, Type type, StringRef name) {
960 Operation *symTableOp =
961 op->template getParentWithTrait<OpTrait::SymbolTable>();
962 if (!symTableOp)
963 // If the operation is not the scope of a symbol table, we cannot
964 // verify it against it's declaration.
965 return success();
966
967 SymbolTable symTable(symTableOp);
968 const auto varOp = symTable.lookup<tosa::VariableOp>(op.getName());
969
970 // Verify prior declaration
971 if (!varOp)
972 return op->emitOpError("'")
973 << op.getName() << "' has not been declared by 'tosa.variable'";
974
975 // Verify type and shape
976 auto variableType = getVariableType(varOp);
977 if (errorIfTypeOrShapeMismatch(op, type, name, variableType,
978 "the input tensor")
979 .failed())
980 return failure();
981 return success();
982}
983
984// verify that inType and outType have same element types
985static LogicalResult verifySameElementTypes(Operation *op, Type aType,
986 Type bType,
987 StringRef aName = "input",
988 StringRef bName = "output") {
989 auto aTType = llvm::dyn_cast<TensorType>(aType);
990 auto bTType = llvm::dyn_cast<TensorType>(bType);
991 if (!aTType) {
992 op->emitOpError("expect shaped tensor for") << aName << ", got " << aType;
993 return failure();
994 }
995 if (!bTType) {
996 op->emitOpError("expect shaped tensor for") << bName << ", got" << bType;
997 return failure();
998 }
999 auto aElementType = aTType.getElementType();
1000 auto bElementType = bTType.getElementType();
1001 auto aQuantType =
1002 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(aElementType);
1003 auto bQuantType =
1004 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(bElementType);
1005 if ((aElementType.isIntOrIndexOrFloat() || aQuantType) &&
1006 (bElementType.isIntOrIndexOrFloat() || bQuantType) &&
1007 aElementType != bElementType) {
1008 // only check if both element types are int/index/float/UniformQuantized
1009 // eg, not sure how to check quant::QuantizedType
1010 // this happens in test_conv2d_q_grouped_convolution in
1011 // tfl-to-tosa-pipeline.mlir
1012 op->emitOpError("expect ")
1013 << aName << " and " << bName << " to have same element type, got "
1014 << aElementType << " and " << bElementType;
1015 return failure();
1016 }
1017 return success();
1018}
1019
1020LogicalResult tosa::ArgMaxOp::verify() { return argMaxMinVerify(*this); }
1021
1022LogicalResult tosa::ArgMinOp::verify() { return argMaxMinVerify(*this); }
1023
1024static LogicalResult verifyPoolingOpImpl(Operation *op,
1025 ArrayRef<int64_t> kernel,
1026 ArrayRef<int64_t> strides,
1027 ArrayRef<int64_t> padding, Value input,
1028 Value output) {
1029 if (failed(verifySameElementTypes(op, input.getType(), output.getType())))
1030 return failure();
1031
1032 const bool hasKernel = kernel.size() > 0;
1033 const bool hasStrides = strides.size() > 0;
1034 const bool hasPad = padding.size() > 0;
1035
1036 if (hasKernel && llvm::any_of(kernel, [](int64_t s) { return s < 1; }))
1037 return op->emitOpError("expect all kernel values to be >= 1, got ")
1038 << kernel;
1039
1040 if (hasStrides && llvm::any_of(strides, [](int64_t s) { return s < 1; }))
1041 return op->emitOpError("expect all stride values to be >= 1, got ")
1042 << strides;
1043
1044 if (hasPad && llvm::any_of(padding, [](int64_t p) { return p < 0; }))
1045 return op->emitOpError("expect all padding values to be >= 0, got ")
1046 << padding;
1047
1048 if (hasKernel && hasPad) {
1049 // Padding must be less than kernel size to avoid a divide-by-zero
1050 const int64_t kernelX = kernel[1];
1051 const int64_t padLeft = padding[2];
1052 const int64_t padRight = padding[3];
1053 if (padRight >= kernelX || padLeft >= kernelX)
1054 return op->emitOpError("expected left/right padding to be less than the "
1055 "width of the kernel, got pad_left=")
1056 << padLeft << ", pad_right=" << padRight
1057 << ", kernel_x=" << kernelX;
1058
1059 const int64_t kernelY = kernel[0];
1060 const int64_t padTop = padding[0];
1061 const int64_t padBottom = padding[1];
1062 if (padTop >= kernelY || padBottom >= kernelY)
1063 return op->emitOpError("expected top/bottom padding to be less than the "
1064 "height of the kernel, got pad_top=")
1065 << padTop << ", pad_bottom=" << padBottom
1066 << ", kernel_y=" << kernelY;
1067 }
1068
1069 const auto inputType = llvm::dyn_cast<RankedTensorType>(input.getType());
1070 const auto outputType = llvm::dyn_cast<RankedTensorType>(output.getType());
1071 if (!inputType || !outputType)
1072 return success();
1073
1074 if (hasKernel && hasStrides && hasPad) {
1075 const auto verifyOutputSize =
1076 [op](const int64_t inputSize, const int64_t outputSize,
1077 const int64_t kernelSize, const int64_t strideSize,
1078 const int64_t padBefore, const int64_t padAfter,
1079 const llvm::StringRef dimName, const llvm::StringRef dimAxis,
1080 const llvm::StringRef padBeforeName,
1081 const llvm::StringRef padAfterName) -> LogicalResult {
1082 if (ShapedType::isDynamic(inputSize))
1083 return success();
1084
1085 const std::optional<int64_t> calculatedOutSizeMinusOne =
1086 idivCheck(inputSize + padBefore + padAfter - kernelSize, strideSize);
1087 if (!calculatedOutSizeMinusOne.has_value())
1088 return op->emitOpError("expected input_")
1089 << dimName << " + pad_" << padBeforeName << " + pad_"
1090 << padAfterName << " - kernel_" << dimAxis
1091 << " to be wholly divisible by stride_" << dimAxis << ", got ("
1092 << inputSize << " + " << padBefore << " + " << padAfter << " - "
1093 << kernelSize << ") / " << strideSize;
1094
1095 const int64_t calculatedOutSize = calculatedOutSizeMinusOne.value() + 1;
1096 if (ShapedType::isStatic(outputSize) && calculatedOutSize != outputSize)
1097 return op->emitOpError("calculated output ")
1098 << dimName << " did not match expected: " << "calculated="
1099 << calculatedOutSize << ", expected=" << outputSize;
1100
1101 return success();
1102 };
1103
1104 if (failed(verifyOutputSize(inputType.getDimSize(1),
1105 outputType.getDimSize(1), kernel[0], strides[0],
1106 padding[0], padding[1], "height", "y", "top",
1107 "bottom")))
1108 return failure();
1109
1110 if (failed(verifyOutputSize(
1111 inputType.getDimSize(2), outputType.getDimSize(2), kernel[1],
1112 strides[1], padding[2], padding[3], "width", "x", "left", "right")))
1113 return failure();
1114 }
1115 return success();
1116}
1117
1118template <typename T>
1119static LogicalResult verifyPoolingOp(T op) {
1120 return verifyPoolingOpImpl(op.getOperation(), op.getKernel(), op.getStride(),
1121 op.getPad(), op.getInput(), op.getOutput());
1122}
1123
1124template <typename T>
1125static LogicalResult verifyAvgPoolCommonTypeAndZpChecks(T op) {
1126 const Type inputETy = getStorageElementTypeOrSelf(op.getInput().getType());
1127 const Type resultETy = getStorageElementTypeOrSelf(op.getOutput().getType());
1128 const Type inputZpETy =
1129 getStorageElementTypeOrSelf(op.getInputZp().getType());
1130 const Type outputZpETy =
1131 getStorageElementTypeOrSelf(op.getOutputZp().getType());
1132
1133 auto accType = op.getAccType();
1134 if (llvm::isa<IntegerType>(inputETy) && !accType.isInteger(32))
1135 return op.emitOpError("accumulator type for integer tensor is not i32");
1136
1137 if (inputETy.isF16() && !(accType.isF16() || accType.isF32()))
1138 return op.emitOpError("accumulator type for f16 tensor is not f16/f32");
1139
1140 if (inputETy.isBF16() && !accType.isF32())
1141 return op.emitOpError("accumulator type for bf16 tensor is not f32");
1142
1143 if (inputETy.isF32() && !accType.isF32())
1144 return op.emitOpError("accumulator type for f32 tensor is not f32");
1145
1146 if (inputETy != inputZpETy)
1147 return op.emitOpError("expect both input and its zero point are the same "
1148 "element type, got ")
1149 << inputETy << " and " << inputZpETy;
1150
1151 if (resultETy != outputZpETy)
1152 return op.emitOpError("expect both output and its zero point are the same "
1153 "element type, got ")
1154 << resultETy << " and " << outputZpETy;
1155
1156 FailureOr<int64_t> maybeIZp = op.getInputZeroPoint();
1157 if (succeeded(maybeIZp) && op.verifyInputZeroPoint(*maybeIZp).failed())
1158 return failure();
1159
1160 FailureOr<int64_t> maybeOZp = op.getOutputZeroPoint();
1161 if (succeeded(maybeOZp) && op.verifyOutputZeroPoint(*maybeOZp).failed())
1162 return failure();
1163
1164 return success();
1165}
1166
1167namespace {
1168struct AdaptivePoolingConstShapeValues {
1169 llvm::SmallVector<int64_t> kernel;
1170 llvm::SmallVector<int64_t> stride;
1171 llvm::SmallVector<int64_t> pad;
1172};
1173} // namespace
1174
1175template <typename T>
1177 std::is_same_v<T, tosa::AvgPool2dAdaptiveOp> ||
1178 std::is_same_v<T, tosa::MaxPool2dAdaptiveOp>;
1179
1180template <typename T,
1181 typename std::enable_if<IsSupportedAdaptivePoolConstShapeVerifyOp<T>,
1182 int>::type = 0>
1184 T op, AdaptivePoolingConstShapeValues &values) {
1185 tosa::getConstShapeValues(op.getKernel().getDefiningOp(), values.kernel);
1186 tosa::getConstShapeValues(op.getStride().getDefiningOp(), values.stride);
1187 tosa::getConstShapeValues(op.getPad().getDefiningOp(), values.pad);
1188}
1189
1190LogicalResult tosa::AvgPool2dOp::verify() {
1191 if (failed(verifyPoolingOp(*this)))
1192 return failure();
1194 return failure();
1195 return success();
1196}
1197
1198LogicalResult tosa::AvgPool2dAdaptiveOp::verify() {
1199 AdaptivePoolingConstShapeValues values;
1201
1202 // If pad/stride/kernel are not constant, this is okay, we just can't check
1203 // their values. extractAdaptivePoolingConstShapeOperands will return an empty
1204 // list for each non CTC input. verifyPoolingOpImpl will need to handle values
1205 // not being present, and return success if they cannot be checked.
1206
1207 if (failed(verifyPoolingOpImpl(getOperation(), values.kernel, values.stride,
1208 values.pad, getInput(), getOutput())))
1209 return failure();
1210
1212 return failure();
1213
1214 return success();
1215}
1216
1217LogicalResult tosa::ClampOp::verify() {
1218 mlir::Type inputETy =
1219 llvm::cast<ShapedType>(getInput().getType()).getElementType();
1220 if (auto quantType =
1221 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(inputETy)) {
1222 inputETy = getStorageElementTypeFromQuantized(quantType);
1223 }
1224 mlir::Type outputETy =
1225 llvm::cast<ShapedType>(getOutput().getType()).getElementType();
1226 if (auto quantType =
1227 llvm::dyn_cast<mlir::quant::UniformQuantizedType>(outputETy)) {
1228 outputETy = getStorageElementTypeFromQuantized(quantType);
1229 }
1230 if (inputETy != outputETy)
1231 return emitOpError("input/output element types are incompatible.");
1232
1233 auto maxValAttr = getMaxValAttr();
1234 auto minValAttr = getMinValAttr();
1235
1236 unsigned dataTypeBitWidth = inputETy.getIntOrFloatBitWidth();
1237
1238 if (inputETy.isInteger(dataTypeBitWidth)) {
1239 // if input datatype is integer, check that the min_val/max_val attributes
1240 // are integer attributes, and that their type is the same as the input's
1241 // datatype
1242 auto intMaxValAttr = mlir::dyn_cast<mlir::IntegerAttr>(maxValAttr);
1243 auto intMinValAttr = mlir::dyn_cast<mlir::IntegerAttr>(minValAttr);
1244 if (!intMaxValAttr || !intMinValAttr ||
1245 (intMaxValAttr.getType() != intMinValAttr.getType()) ||
1246 (intMaxValAttr.getType() != inputETy))
1247 return emitOpError("min/max attributes types are incompatible with "
1248 "input/output element types.");
1249
1250 const bool isUnsigned = inputETy.isUnsignedInteger();
1251 const bool isBoolean = inputETy.isInteger(1);
1252 const APInt minVal = intMinValAttr.getValue();
1253 const APInt maxVal = intMaxValAttr.getValue();
1254 if ((isUnsigned || isBoolean) ? maxVal.ult(minVal) : maxVal.slt(minVal))
1255 return emitOpError("expected min_val <= max_val, got min_val=")
1256 << minValAttr << ", max_val=" << maxValAttr;
1257 } else {
1258 // otherwise, input datatype is float, check that the min_val/max_val
1259 // attributes share the same type and that their type is the same as the
1260 // input's datatype
1261 auto floatMaxValAttr = mlir::dyn_cast<mlir::FloatAttr>(maxValAttr);
1262 auto floatMinValAttr = mlir::dyn_cast<mlir::FloatAttr>(minValAttr);
1263 if (!floatMaxValAttr || !floatMinValAttr ||
1264 (floatMaxValAttr.getType() != floatMinValAttr.getType()) ||
1265 (floatMaxValAttr.getType() != inputETy))
1266 return emitOpError("min/max attributes types are incompatible with "
1267 "input/output element types.");
1268
1269 const APFloat minVal = floatMinValAttr.getValue();
1270 const APFloat maxVal = floatMaxValAttr.getValue();
1271 if (minVal.isNaN() || maxVal.isNaN())
1272 return emitOpError("min/max attributes should not be 'NaN', got min_val=")
1273 << minValAttr << ", max_val=" << maxValAttr;
1274
1275 if (maxVal < minVal)
1276 return emitOpError("expected min_val <= max_val, got min_val=")
1277 << minValAttr << ", max_val=" << maxValAttr;
1278 }
1279
1280 return success();
1281}
1282
1283//===----------------------------------------------------------------------===//
1284// TOSA Operator Quantization Builders.
1285//===----------------------------------------------------------------------===//
1286
1287/// This builder is called on all convolution operators except TransposeConv,
1288/// which has specialized output shape semantics. The builder also defines the
1289/// bitwidth of the output given the bit width of the input & weight content.
1291 Type outputType, Value input, Value weight,
1292 Value bias, DenseI64ArrayAttr pad,
1293 DenseI64ArrayAttr stride,
1294 DenseI64ArrayAttr dilation,
1295 TypeAttr accType) {
1296 auto zps = createZPsAsConst(builder, input, weight);
1297 result.addOperands({input, weight, bias, zps.first, zps.second});
1298 result.addAttribute("pad", pad);
1299 result.addAttribute("stride", stride);
1300 result.addAttribute("dilation", dilation);
1301 result.addAttribute("acc_type", accType);
1302 Type finalOutputType = outputType;
1303 auto quantAttr = buildConvOpQuantizationAttr(builder, input, weight);
1304 if (quantAttr) {
1305 finalOutputType =
1306 buildConvOpResultTypeInfo(builder, outputType, input, weight);
1307 }
1308 result.addTypes(finalOutputType);
1309}
1310
1311/// Handles tosa.transpose_conv2d which has outpad and output shape
1312/// attributes.
1313static void
1315 Type outputType, Value input, Value weight,
1316 Value bias, DenseI64ArrayAttr outpad,
1317 DenseI64ArrayAttr stride, TypeAttr accType) {
1318 auto zps = createZPsAsConst(builder, input, weight);
1319 result.addOperands({input, weight, bias, zps.first, zps.second});
1320 result.addAttribute("out_pad", outpad);
1321 result.addAttribute("stride", stride);
1322 result.addAttribute("acc_type", accType);
1323 Type finalOutputType = outputType;
1324 auto quantAttr = buildConvOpQuantizationAttr(builder, input, weight);
1325 if (quantAttr) {
1326 finalOutputType =
1327 buildConvOpResultTypeInfo(builder, outputType, input, weight);
1328 }
1329 result.addTypes(finalOutputType);
1330}
1331
1334 Type outputType, Value a, Value b) {
1335 const std::pair<Value, Value> zps = createZPsAsConst(builder, a, b);
1336 result.addOperands({a, b, zps.first, zps.second});
1337
1338 Type finalOutputType{outputType};
1339 if (buildMatMulOpQuantizationAttr(builder, a, b)) {
1340 auto eType = getStorageElementTypeOrSelf(a.getType());
1341 auto inputBits = eType.getIntOrFloatBitWidth();
1342
1343 auto outputShapedType = llvm::dyn_cast<ShapedType>(outputType);
1344 assert(outputShapedType && "Output must be a shaped type");
1345
1346 IntegerType accElementType;
1347 if (inputBits == 16)
1348 accElementType = builder.getIntegerType(48);
1349 else
1350 accElementType = builder.getI32Type();
1351
1352 finalOutputType = outputShapedType.clone(accElementType);
1353 }
1354 result.addTypes(finalOutputType);
1355}
1356
1358 OperationState &result, Type outputType,
1359 Value a, Value b) {
1360 buildMatMulLikeOpWithQuantInfo(builder, result, outputType, a, b);
1361}
1362
1364 OperationState &result, Type outputType,
1365 Value a, Value b) {
1366 buildMatMulLikeOpWithQuantInfo(builder, result, outputType, a, b);
1367}
1368
1369/// Both the tosa.avg_pool2d and unary ops use the same
1370/// UnaryOpQuantizationAttr but avg_pool operator has its own builder as it
1371/// has additional parameters not part of the unary ops.
1372static void
1374 Type outputType, Value input,
1375 DenseArrayAttr kernel, DenseArrayAttr stride,
1376 DenseArrayAttr pad, TypeAttr accType) {
1377 const Location loc{result.location};
1378 int64_t inputZp{0};
1379 int64_t outputZp{0};
1380
1381 if (auto quantAttr =
1382 buildUnaryOpQuantizationAttr(builder, input, outputType)) {
1383 inputZp = quantAttr.getInputZp();
1384 outputZp = quantAttr.getOutputZp();
1385 }
1386 const std::optional<Value> inputZpOp =
1387 createZeroPointTensor(builder, loc, input.getType(), inputZp);
1388 if (!inputZpOp) {
1389 (void)emitError(
1390 loc,
1391 "Failed to create input zero point tensor for quantized AVG_POOL2D op");
1392 }
1393 const std::optional<Value> outputZpOp =
1394 createZeroPointTensor(builder, loc, outputType, outputZp);
1395 if (!outputZpOp) {
1396 (void)emitError(loc, "Failed to create output zero point tensor for "
1397 "quantized AVG_POOL2D op");
1398 }
1399
1400 if (inputZpOp && outputZpOp) {
1401 result.addOperands({input, inputZpOp.value(), outputZpOp.value()});
1402 } else {
1403 // failed to create one or more zero points above: just add input as
1404 // operands this will trigger error in building the op because of missing
1405 // zero points
1406 result.addOperands({input});
1407 }
1408 result.addAttribute("kernel", kernel);
1409 result.addAttribute("stride", stride);
1410 result.addAttribute("pad", pad);
1411 result.addAttribute("acc_type", accType);
1412 result.types.push_back(outputType);
1413}
1414
1415/// This builder mirrors avg_pool2d quant-info handling and materializes
1416/// kernel/stride/pad as const_shape operands for avg_pool2d_adaptive.
1418 OpBuilder &builder, OperationState &result, Type outputType, Value input,
1420 TypeAttr accType) {
1421 const Location loc{result.location};
1422 int64_t inputZp{0};
1423 int64_t outputZp{0};
1424
1425 if (auto quantAttr =
1426 buildUnaryOpQuantizationAttr(builder, input, outputType)) {
1427 inputZp = quantAttr.getInputZp();
1428 outputZp = quantAttr.getOutputZp();
1429 }
1430 const std::optional<Value> inputZpOp =
1431 createZeroPointTensor(builder, loc, input.getType(), inputZp);
1432 if (!inputZpOp) {
1433 (void)emitError(loc,
1434 "Failed to create input zero point tensor for quantized "
1435 "AVG_POOL2D_ADAPTIVE op");
1436 }
1437 const std::optional<Value> outputZpOp =
1438 createZeroPointTensor(builder, loc, outputType, outputZp);
1439 if (!outputZpOp) {
1440 (void)emitError(loc, "Failed to create output zero point tensor for "
1441 "quantized AVG_POOL2D_ADAPTIVE op");
1442 }
1443
1444 if (inputZpOp && outputZpOp) {
1445 ImplicitLocOpBuilder b(loc, builder);
1446 Value kernelShape = getTosaConstShape(b, kernel.asArrayRef());
1447 Value strideShape = getTosaConstShape(b, stride.asArrayRef());
1448 Value padShape = getTosaConstShape(b, pad.asArrayRef());
1449 result.addOperands({input, inputZpOp.value(), outputZpOp.value(),
1450 kernelShape, strideShape, padShape});
1451 } else {
1452 // Failed to create one or more zero points above: just add input as
1453 // operands. This will trigger error in building the op because of missing
1454 // operands.
1455 result.addOperands({input});
1456 }
1457 result.addAttribute("acc_type", accType);
1458 result.types.push_back(outputType);
1459}
1460
1461/// This builder is called on single-parameter negate operator
1462/// to construct input and output zero points based on their
1463/// types.
1465 OperationState &result, Type outputType,
1466 Value input) {
1467 const Location loc{result.location};
1468 int64_t input1Zp{0};
1469 int64_t outputZp{0};
1470 auto quantAttr = buildUnaryOpQuantizationAttr(builder, input, outputType);
1471 if (quantAttr) {
1472 input1Zp = quantAttr.getInputZp();
1473 outputZp = quantAttr.getOutputZp();
1474 }
1475 const std::optional<Value> input1ZpOp =
1476 createZeroPointTensor(builder, loc, input.getType(), input1Zp);
1477 if (!input1ZpOp) {
1478 (void)emitError(
1479 loc, "Failed to create input1 zero point for quantized NEGATE op");
1480 }
1481
1482 const std::optional<Value> outputZpOp =
1483 createZeroPointTensor(builder, loc, input.getType(), outputZp);
1484 if (!outputZpOp) {
1485 (void)emitError(
1486 loc, "Failed to create output zero point for quantized NEGATE op");
1487 }
1488
1489 if (input1ZpOp && outputZpOp) {
1490 result.addOperands({input, input1ZpOp.value(), outputZpOp.value()});
1491 } else {
1492 // failed to create one or more zero points above: just add input as
1493 // operands. This will trigger error in building the op because of
1494 // missing zero points
1495 result.addOperands({input});
1496 }
1497
1498 result.types.push_back(outputType);
1499}
1500
1501/// This builder is called on TOSA pad operator that needs to create its own
1502/// OptionalAttr quantization_attr parameter to scale the padding values
1503/// correctly. No pad_const is interpreted as zero-padding.
1505 Type outputType, Value input,
1506 Value paddings) {
1507 const Location loc{result.location};
1508 int32_t zp{0};
1509 const auto quantAttr = buildPadOpQuantizationAttr(builder, input);
1510 if (quantAttr) {
1511 zp = static_cast<int32_t>(quantAttr.getInputZp());
1512 }
1513 const auto padConstOp{createPadConstTensor(builder, loc, input, zp)};
1514 result.addOperands({input, paddings, padConstOp});
1515 result.types.push_back(outputType);
1516}
1517
1519 StringRef name, Type variableType,
1520 Attribute initialValue) {
1521 const Location loc{result.location};
1522 auto nameAttr = builder.getStringAttr(name);
1523
1524 auto shapedType = dyn_cast<ShapedType>(variableType);
1525 if (!shapedType) {
1526 (void)emitError(loc, "variable type must be a shaped type");
1527 return;
1528 }
1529 if (!shapedType.hasRank()) {
1530 (void)emitError(loc, "variable type must be a ranked type");
1531 return;
1532 }
1533
1534 auto elementType = shapedType.getElementType();
1535 auto elementTypeAttr = TypeAttr::get(elementType);
1536 ArrayRef<int64_t> shape = shapedType.getShape();
1537 auto varShapeAttr = builder.getIndexTensorAttr(convertFromMlirShape(shape));
1538
1539 result.addAttribute("sym_name", nameAttr);
1540 result.addAttribute("var_shape", varShapeAttr);
1541 result.addAttribute("type", elementTypeAttr);
1542 result.addAttribute("initial_value", initialValue);
1543}
1544
1545//===----------------------------------------------------------------------===//
1546// TOSA Operator Return Type Inference.
1547//===----------------------------------------------------------------------===//
1548static FailureOr<int64_t> resolveBroadcastDim(const int64_t dim1,
1549 const int64_t dim2) {
1550 if (dim1 == 1)
1551 return dim2;
1552 if (dim2 == 1)
1553 return dim1;
1554
1555 if (ShapedType::isStatic(dim1) && ShapedType::isStatic(dim2) && dim1 != dim2)
1556 return failure();
1557
1558 // Prefer static dimension over dynamic
1559 return ShapedType::isDynamic(dim1) ? dim2 : dim1;
1560}
1561
1562static LogicalResult resolveBroadcastShape(const ValueShapeRange &operands,
1563 SmallVector<int64_t> &outShape) {
1564 int64_t outRank = 0;
1565 for (int i = 0, e = operands.size(); i != e; ++i) {
1566 auto shape = operands.getShape(i);
1567 if (!shape.hasRank()) {
1568 // TODO(jennik): Update function to have better case handling for
1569 // invalid operands and for ranked tensors.
1570 return failure();
1571 }
1572 outRank = std::max<int64_t>(outRank, shape.getRank());
1573 }
1574
1575 outShape.resize(outRank, 1);
1576
1577 for (int i = 0, e = operands.size(); i != e; ++i) {
1578 auto shape = operands.getShape(i);
1579 auto rankDiff = outShape.size() - shape.getRank();
1580
1581 for (size_t i = 0, e = shape.getRank(); i < e; ++i) {
1582 auto dim1 = outShape[i + rankDiff];
1583 auto dim2 = shape.getDimSize(i);
1584
1585 const FailureOr<int64_t> maybeResolvedDim =
1586 resolveBroadcastDim(dim1, dim2);
1587 if (failed(maybeResolvedDim))
1588 return failure();
1589 const int64_t resolvedDim = *maybeResolvedDim;
1590 outShape[i + rankDiff] = resolvedDim;
1591 }
1592 }
1593
1594 return success();
1595}
1596
1597LogicalResult tosa::ArgMaxOp::inferReturnTypeComponents(
1598 MLIRContext *context, ::std::optional<Location> location,
1599 ArgMaxOp::Adaptor adaptor,
1600 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1601 return inferArgMaxMinReturnTypeComponents(context, location, adaptor,
1602 inferredReturnShapes);
1603}
1604
1605LogicalResult tosa::ArgMinOp::inferReturnTypeComponents(
1606 MLIRContext *context, ::std::optional<Location> location,
1607 ArgMinOp::Adaptor adaptor,
1608 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1609 return inferArgMaxMinReturnTypeComponents(context, location, adaptor,
1610 inferredReturnShapes);
1611}
1612
1613LogicalResult tosa::RFFT2dOp::inferReturnTypeComponents(
1614 MLIRContext *context, ::std::optional<Location> location,
1615 RFFT2dOp::Adaptor adaptor,
1616 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1617 ShapeAdaptor inputShape(adaptor.getInputReal().getType());
1618
1619 if (!inputShape.hasRank())
1620 return failure();
1621
1622 llvm::SmallVector<int64_t> outputShape;
1623 outputShape.resize(3, ShapedType::kDynamic);
1624 outputShape[0] = inputShape.getDimSize(0);
1625 outputShape[1] = inputShape.getDimSize(1);
1626 int64_t inWidth = inputShape.getDimSize(2);
1627
1628 // Note that we can support this calculation symbolically
1629 // in the future e.g. [x, y, z] -> [x, y, z / 2 + 1]
1630 if (inWidth != ShapedType::kDynamic)
1631 outputShape[2] = inWidth / 2 + 1;
1632
1633 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1634 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1635
1636 return success();
1637}
1638
1639static LogicalResult verifyDimIsPowerOfTwo(Operation *op, const int64_t dimSize,
1640 const llvm::StringRef dimName) {
1641 const bool isPowerOfTwo = (dimSize & (dimSize - 1)) == 0 && dimSize > 0;
1642 if (!isPowerOfTwo)
1643 return op->emitOpError("expected ")
1644 << dimName << " to be a power of two, got " << dimSize;
1645
1646 return success();
1647}
1648
1649LogicalResult tosa::RFFT2dOp::verify() {
1650 const auto outputTypes = getResultTypes();
1651 if (failed(verifyCompatibleShapes(outputTypes)))
1652 return emitOpError("expected output shapes to match, got ") << outputTypes;
1653
1654 const auto inputType =
1655 llvm::dyn_cast<RankedTensorType>(getInputReal().getType());
1656 if (!inputType)
1657 return success();
1658
1659 const int64_t height = inputType.getDimSize(1);
1660 if (ShapedType::isStatic(height) &&
1661 failed(verifyDimIsPowerOfTwo(*this, height, "height")))
1662 return failure();
1663
1664 const int64_t width = inputType.getDimSize(2);
1665 if (ShapedType::isStatic(width) &&
1666 failed(verifyDimIsPowerOfTwo(*this, width, "width")))
1667 return failure();
1668
1669 const auto outputType = llvm::dyn_cast<RankedTensorType>(outputTypes[0]);
1670 if (!outputType)
1671 return success();
1672
1673 // Batch and height input/output dimensions should match
1674 if (failed(verifyCompatibleShape(inputType.getShape().drop_back(),
1675 outputType.getShape().drop_back())))
1676 return emitOpError("expected batch and height dimensions of input/output "
1677 "to match, got input=")
1678 << inputType << " output=" << outputType;
1679
1680 // Output width dimension expected to be input_width / 2 + 1
1681 const int64_t outputWidth = outputType.getDimSize(2);
1682 if (ShapedType::isStatic(width) && ShapedType::isStatic(outputWidth) &&
1683 (outputWidth != (width / 2) + 1))
1684 return emitOpError(
1685 "expected output width to be equal to input_width / 2 + 1, got ")
1686 << outputWidth;
1687
1688 return success();
1689}
1690
1691LogicalResult tosa::FFT2dOp::inferReturnTypeComponents(
1692 MLIRContext *context, ::std::optional<Location> location,
1693 FFT2dOp::Adaptor adaptor,
1694 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1695 inferredReturnShapes.push_back(
1696 ShapedTypeComponents(ShapeAdaptor(adaptor.getInputReal().getType())));
1697 inferredReturnShapes.push_back(
1698 ShapedTypeComponents(ShapeAdaptor(adaptor.getInputImag().getType())));
1699 return success();
1700}
1701
1702LogicalResult tosa::FFT2dOp::verify() {
1703 const auto inputRealType =
1704 llvm::dyn_cast<RankedTensorType>(getInputReal().getType());
1705 const auto inputImagType =
1706 llvm::dyn_cast<RankedTensorType>(getInputImag().getType());
1707 if (!inputRealType || !inputImagType)
1708 return success();
1709
1710 const auto trySelectStaticDim = [](const int64_t a, const int64_t b) {
1711 return ShapedType::isDynamic(a) ? a : b;
1712 };
1713
1714 const int64_t height = trySelectStaticDim(inputRealType.getDimSize(1),
1715 inputImagType.getDimSize(1));
1716 if (ShapedType::isStatic(height) &&
1717 failed(verifyDimIsPowerOfTwo(*this, height, "height")))
1718 return failure();
1719
1720 const int64_t width = trySelectStaticDim(inputRealType.getDimSize(2),
1721 inputImagType.getDimSize(2));
1722 if (ShapedType::isStatic(width) &&
1723 failed(verifyDimIsPowerOfTwo(*this, width, "width")))
1724 return failure();
1725
1726 return success();
1727}
1728
1729LogicalResult tosa::ConcatOp::inferReturnTypeComponents(
1730 MLIRContext *context, ::std::optional<Location> location,
1731 ConcatOp::Adaptor adaptor,
1732 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1733 // Infer all dimension sizes by reducing based on inputs.
1734 const Properties &prop = adaptor.getProperties();
1735 int32_t axis = prop.axis.getValue().getSExtValue();
1736 llvm::SmallVector<int64_t> outputShape;
1737 bool hasRankedInput = false;
1738 for (auto operand : adaptor.getOperands()) {
1739 ShapeAdaptor operandShape(operand.getType());
1740 if (!operandShape.hasRank())
1741 continue;
1742
1743 // Copy the Operand's rank.
1744 if (!hasRankedInput)
1745 outputShape.resize(operandShape.getRank(), ShapedType::kDynamic);
1746
1747 // Copy shapes until the dim is non-dynamic.
1748 for (int i = 0, s = operandShape.getRank(); i < s; i++) {
1749 if (i == axis || operandShape.isDynamicDim(i))
1750 continue;
1751 if (outputShape[i] == ShapedType::kDynamic)
1752 outputShape[i] = operandShape.getDimSize(i);
1753 if (outputShape[i] != operandShape.getDimSize(i))
1754 return emitOptionalError(location,
1755 "Cannot concat tensors with different sizes"
1756 " on the non-axis dimension ",
1757 i);
1758 }
1759
1760 hasRankedInput = true;
1761 }
1762
1763 if (adaptor.getInput1().empty())
1764 return failure();
1765
1766 Type inputType =
1767 llvm::cast<TensorType>(adaptor.getInput1().getType()[0]).getElementType();
1768 if (!hasRankedInput) {
1769 inferredReturnShapes.push_back(ShapedTypeComponents(inputType));
1770 return success();
1771 }
1772
1773 // Determine the dimension size along the concatenation axis.
1774 int64_t concatDimSize = 0;
1775 for (auto operand : adaptor.getOperands()) {
1776 ShapeAdaptor operandShape(operand.getType());
1777
1778 // We need to know the length of the concatenation axis of all inputs to
1779 // determine the dimension size of the output shape.
1780 if (!operandShape.hasRank() || operandShape.isDynamicDim(axis)) {
1781 concatDimSize = ShapedType::kDynamic;
1782 break;
1783 }
1784
1785 concatDimSize += operandShape.getDimSize(axis);
1786 }
1787
1788 outputShape[axis] = concatDimSize;
1789
1790 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape, inputType));
1791 return success();
1792}
1793
1794LogicalResult tosa::ConcatOp::verify() {
1795 // check that each input has same element type as output
1796 auto outType = getOutput().getType();
1797 const Operation::operand_range inputList = getInput1();
1798
1799 // Check there is at least one input
1800 if (inputList.empty())
1801 return emitOpError("expect at least one input");
1802
1803 if (!llvm::all_of(inputList, [&](auto input) {
1804 return succeeded(verifySameElementTypes(
1805 *this, /* inType = */ input.getType(), outType));
1806 })) {
1807 return failure();
1808 }
1809
1810 const int32_t axis = getAxis();
1811 ShapeAdaptor firstRankedInputShape = nullptr;
1812 for (const auto &input : inputList) {
1813 const Type inputType = input.getType();
1814 ShapeAdaptor currShape(inputType);
1815 if (currShape.hasRank()) {
1816 firstRankedInputShape = currShape;
1817 // Check axis is in expected range
1818 if (axis < 0 || axis >= firstRankedInputShape.getRank())
1819 return emitOpError("expect axis to be within range 0 < axis < "
1820 "rank(input1[firstRankedTensorIdx]), got ")
1821 << axis;
1822 break;
1823 }
1824 }
1825
1826 const auto allOperandsHasRank = [](const Value input) {
1827 return ShapeAdaptor(input.getType()).hasRank();
1828 };
1829 if (llvm::all_of(inputList, allOperandsHasRank)) {
1830 const int64_t firstInputRank = firstRankedInputShape.getRank();
1831
1832 for (const auto &[index, input] : llvm::enumerate(inputList.drop_front())) {
1833 const ShapeAdaptor inputShape(input.getType());
1834 const int64_t inputRank = inputShape.getRank();
1835 const size_t operandNum = index + 1;
1836
1837 // Check that each operand has the same rank
1838 if (inputRank != firstInputRank)
1839 return emitOpError(
1840 "expect all operands to have the same rank, but got ")
1841 << firstInputRank << " vs " << inputRank << " on operands 0 and "
1842 << operandNum;
1843
1844 // Check non-axis dims match
1845 for (int i = 0; i < inputRank; i++) {
1846 const int64_t inputDim = inputShape.getDimSize(i);
1847 const int64_t firstInputDim = firstRankedInputShape.getDimSize(i);
1848 if (i == axis || firstRankedInputShape.isDynamicDim(i) ||
1849 inputShape.isDynamicDim(i))
1850 continue;
1851 if (inputDim != firstInputDim)
1852 return emitOpError("expect all operand shapes to have the same sizes "
1853 "on non-axis dimensions, but got ")
1854 << inputDim << " vs " << firstInputDim << " at index " << i
1855 << " on operands 0 and " << operandNum;
1856 }
1857 }
1858
1859 const ShapeAdaptor outputShape(outType);
1860 if (outputShape.hasRank() && outputShape.getRank() != firstInputRank)
1861 return emitOpError("expect output rank to match inputs rank, got ")
1862 << outputShape.getRank() << " vs " << firstInputRank;
1863
1864 // ERROR_IF(axis_sum != shape[axis]);
1865 int64_t axisSum = 0;
1866 for (const auto &input : inputList) {
1867 const ShapeAdaptor inputShape(input.getType());
1868 if (inputShape.isDynamicDim(axis)) {
1869 // make axisSum negative to indicate invalid value
1870 axisSum = -1;
1871 break;
1872 }
1873 axisSum += inputShape.getDimSize(axis);
1874 }
1875
1876 if (axisSum >= 0 && outputShape.hasRank() &&
1877 !outputShape.isDynamicDim(axis) &&
1878 axisSum != outputShape.getDimSize(axis))
1879 return emitOpError("requires sum of axis dimensions of input1 "
1880 "equal to output axis dimension, got ")
1881 << axisSum << " and " << outputShape.getDimSize(axis);
1882 }
1883
1884 return success();
1885}
1886
1887LogicalResult tosa::EqualOp::inferReturnTypeComponents(
1888 MLIRContext *context, ::std::optional<Location> location,
1889 ValueShapeRange operands, DictionaryAttr attributes, PropertyRef properties,
1890 RegionRange regions,
1891 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1892 auto elementType = IntegerType::get(context, /*width=*/1);
1893
1895 if (resolveBroadcastShape(operands, outShape).failed()) {
1896 inferredReturnShapes.push_back(ShapedTypeComponents(elementType));
1897 return success();
1898 }
1899
1900 inferredReturnShapes.push_back(ShapedTypeComponents(outShape, elementType));
1901 return success();
1902}
1903
1904bool tosa::EqualOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
1905 if (l.size() != r.size() || l.size() != 1)
1906 return false;
1907 return succeeded(verifyCompatibleShape(l[0], r[0]));
1908}
1909
1910// MATMUL batch shapes are right aligned and may have different ranks. Missing
1911// leading dimensions are treated as one, while an unranked input remains
1912// unknown because it may contain any number of batch dimensions.
1914 int64_t axis) {
1915 if (!shape.hasRank())
1916 return ShapedType::kDynamic;
1917 const int64_t inputAxis = axis - (outputRank - shape.getRank());
1918 return inputAxis < 0 ? 1 : shape.getDimSize(inputAxis);
1919}
1920
1921static FailureOr<SmallVector<int64_t>>
1923 int64_t outputRank, bool transposeB) {
1924 if (outputRank < 2 ||
1925 (aShape.hasRank() &&
1926 (aShape.getRank() < 2 || aShape.getRank() > outputRank)) ||
1927 (bShape.hasRank() &&
1928 (bShape.getRank() < 2 || bShape.getRank() > outputRank)))
1929 return failure();
1930
1931 SmallVector<int64_t> outputShape(outputRank, ShapedType::kDynamic);
1932 for (int64_t axis = 0; axis < outputRank - 2; ++axis) {
1933 const int64_t aDim = getMatMulBatchDim(aShape, outputRank, axis);
1934 const int64_t bDim = getMatMulBatchDim(bShape, outputRank, axis);
1935 FailureOr<int64_t> resolvedDim = resolveBroadcastDim(aDim, bDim);
1936 if (failed(resolvedDim))
1937 return failure();
1938 outputShape[axis] = *resolvedDim;
1939 }
1940
1941 if (aShape.hasRank())
1942 outputShape[outputRank - 2] = aShape.getDimSize(aShape.getRank() - 2);
1943 if (bShape.hasRank())
1944 outputShape[outputRank - 1] =
1945 bShape.getDimSize(bShape.getRank() - (transposeB ? 2 : 1));
1946 return outputShape;
1947}
1948
1950 const ShapeAdaptor &aShape, const ShapeAdaptor &bShape, bool transposeB,
1951 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1952 if ((aShape.hasRank() && aShape.getRank() < 2) ||
1953 (bShape.hasRank() && bShape.getRank() < 2))
1954 return failure();
1955
1956 // An unranked input can have an arbitrary batch prefix, so the output rank
1957 // cannot yet be inferred.
1958 if (!aShape.hasRank() || !bShape.hasRank()) {
1959 inferredReturnShapes.emplace_back();
1960 return success();
1961 }
1962
1963 const int64_t aChannels = aShape.getDimSize(aShape.getRank() - 1);
1964 const int64_t bChannels =
1965 bShape.getDimSize(bShape.getRank() - (transposeB ? 1 : 2));
1966 if (ShapedType::isStatic(aChannels) && ShapedType::isStatic(bChannels) &&
1967 aChannels != bChannels)
1968 return failure();
1969
1970 const int64_t outputRank = std::max(aShape.getRank(), bShape.getRank());
1971 FailureOr<SmallVector<int64_t>> outputShape =
1972 resolveMatMulOutputShape(aShape, bShape, outputRank, transposeB);
1973 if (failed(outputShape))
1974 return failure();
1975
1976 inferredReturnShapes.emplace_back(*outputShape);
1977 return success();
1978}
1979
1980LogicalResult tosa::MatMulOp::inferReturnTypeComponents(
1981 MLIRContext *context, ::std::optional<Location> location,
1982 MatMulOp::Adaptor adaptor,
1983 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1984 return inferMatMulReturnTypeComponents(ShapeAdaptor(adaptor.getA().getType()),
1985 ShapeAdaptor(adaptor.getB().getType()),
1986 /*transposeB=*/false,
1987 inferredReturnShapes);
1988}
1989
1990template <typename T>
1991static LogicalResult verifyMatMulQuantizedOperandsType(T op, Type aElementType,
1992 Type bElementType) {
1993 const auto aQuantizedEType =
1994 llvm::dyn_cast<quant::UniformQuantizedType>(aElementType);
1995 const auto bQuantizedEType =
1996 llvm::dyn_cast<quant::UniformQuantizedType>(bElementType);
1997
1998 if (aQuantizedEType || bQuantizedEType) {
1999 if (!aQuantizedEType || !bQuantizedEType) {
2000 return op.emitOpError("expect operands to be both quantized or both not "
2001 "quantized, got ")
2002 << aElementType << " and " << bElementType;
2003 }
2004 // both a and b have quantized element types
2005 auto aQuantWidth = aQuantizedEType.getStorageTypeIntegralWidth();
2006 auto bQuantWidth = bQuantizedEType.getStorageTypeIntegralWidth();
2007 if (aQuantWidth != bQuantWidth) {
2008 return op.emitOpError("expect quantized operands to have same widths, "
2009 "got ")
2010 << aQuantWidth << " and " << bQuantWidth;
2011 }
2012 }
2013
2014 return success();
2015}
2016
2017template <typename T>
2018static LogicalResult verifyMatMulZeroPointType(T op, Value input, Value zp,
2019 StringRef inputName,
2020 StringRef zpName) {
2021 const Type inputElementType = getElementTypeOrSelf(input.getType());
2022 const Type inputStorageElementType = getStorageElementTypeOrSelf(input);
2023 const Type zpElementType = getStorageElementTypeOrSelf(zp);
2024 Type expectedElementType = inputStorageElementType;
2025
2026 if (isa<BlockScaledType>(inputElementType))
2027 expectedElementType = Float32Type::get(op.getContext());
2028
2029 if (expectedElementType == zpElementType)
2030 return success();
2031
2032 InFlightDiagnostic diag = op.emitOpError("expect input ");
2033 diag << inputName << " and " << zpName;
2034 if (isa<BlockScaledType>(inputElementType))
2035 diag << " have compatible element types, got " << inputElementType
2036 << " and " << zpElementType;
2037 else
2038 diag << " have the same element type, got " << inputStorageElementType
2039 << " and " << zpElementType;
2040 return diag;
2041}
2042
2044 SmallVector<int64_t> batchShape;
2045 if (!shape.hasRank() || shape.getRank() < 2)
2046 return batchShape;
2047 batchShape.reserve(shape.getRank() - 2);
2048 for (int64_t i = 0, e = shape.getRank() - 2; i < e; ++i)
2049 batchShape.push_back(shape.getDimSize(i));
2050 return batchShape;
2051}
2052
2053template <typename T>
2054static LogicalResult verifyMatMulShapes(T op, bool transposeB) {
2055 const ShapeAdaptor aShape(op.getA().getType());
2056 const ShapeAdaptor bShape(op.getB().getType());
2057 const auto outputType = cast<ShapedType>(op.getResult().getType());
2058
2059 int64_t channels = aShape.hasRank() ? aShape.getDimSize(aShape.getRank() - 1)
2060 : ShapedType::kDynamic;
2061 if (bShape.hasRank() &&
2062 failed(tryUpdateDimOrFailure(
2063 op, channels,
2064 bShape.getDimSize(bShape.getRank() - (transposeB ? 1 : 2)), "b",
2065 "channels")))
2066 return failure();
2067
2068 const int64_t minimumOutputRank =
2069 std::max(aShape.hasRank() ? aShape.getRank() : 2,
2070 bShape.hasRank() ? bShape.getRank() : 2);
2071 if (outputType.hasRank() && outputType.getRank() < minimumOutputRank)
2072 return op.emitOpError("expected output rank of at least ")
2073 << minimumOutputRank << ", got " << outputType.getRank();
2074
2075 const bool bothInputsRanked = aShape.hasRank() && bShape.hasRank();
2076 if (!bothInputsRanked && !outputType.hasRank())
2077 return success();
2078
2079 // When an input is unranked, use the declared output rank to validate every
2080 // result dimension constrained by the ranked input.
2081 const int64_t expectedOutputRank =
2082 bothInputsRanked ? minimumOutputRank : outputType.getRank();
2083 FailureOr<SmallVector<int64_t>> expectedOutputShape =
2084 resolveMatMulOutputShape(aShape, bShape, expectedOutputRank, transposeB);
2085 if (failed(expectedOutputShape)) {
2086 InFlightDiagnostic diag = op.emitOpError(
2087 "expected batch dimensions of a and b to be broadcast compatible, "
2088 "got a=[");
2090 diag << "] and b=[";
2092 diag << "]";
2093 return diag;
2094 }
2095
2096 if (outputType.hasRank())
2098 op.getOperation(), outputType, *expectedOutputShape);
2099 return success();
2100}
2101
2102LogicalResult MatMulOp::verify() {
2103 const Type aElementType = getElementTypeOrSelf(getA());
2104 const Type bElementType = getElementTypeOrSelf(getB());
2105
2106 if (failed(
2107 verifyMatMulQuantizedOperandsType(*this, aElementType, bElementType)))
2108 return failure();
2109
2110 if (failed(verifyMatMulZeroPointType(*this, getA(), getAZp(), "a", "a_zp")) ||
2111 failed(verifyMatMulZeroPointType(*this, getB(), getBZp(), "b", "b_zp")))
2112 return failure();
2113
2114 FailureOr<int64_t> maybeAZp = getAZeroPoint();
2115 if (succeeded(maybeAZp) && verifyAZeroPoint(*maybeAZp).failed())
2116 return failure();
2117
2118 FailureOr<int64_t> maybeBZp = getBZeroPoint();
2119 if (succeeded(maybeBZp) && verifyBZeroPoint(*maybeBZp).failed())
2120 return failure();
2121
2122 return verifyMatMulShapes(*this, /*transposeB=*/false);
2123}
2124
2125LogicalResult tosa::MatMulTOp::inferReturnTypeComponents(
2126 MLIRContext *context, ::std::optional<Location> location,
2127 MatMulTOp::Adaptor adaptor,
2128 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2129 return inferMatMulReturnTypeComponents(ShapeAdaptor(adaptor.getA().getType()),
2130 ShapeAdaptor(adaptor.getB().getType()),
2131 /*transposeB=*/true,
2132 inferredReturnShapes);
2133}
2134
2135LogicalResult MatMulTOp::verify() {
2136 const Type aElementType = getElementTypeOrSelf(getA());
2137 const Type bElementType = getElementTypeOrSelf(getB());
2138
2139 if (failed(
2140 verifyMatMulQuantizedOperandsType(*this, aElementType, bElementType)))
2141 return failure();
2142
2143 if (failed(verifyMatMulZeroPointType(*this, getA(), getAZp(), "a", "a_zp")) ||
2144 failed(verifyMatMulZeroPointType(*this, getB(), getBZp(), "b", "b_zp")))
2145 return failure();
2146
2147 FailureOr<int64_t> maybeAZp = getAZeroPoint();
2148 if (succeeded(maybeAZp) && verifyAZeroPoint(*maybeAZp).failed())
2149 return failure();
2150
2151 FailureOr<int64_t> maybeBZp = getBZeroPoint();
2152 if (succeeded(maybeBZp) && verifyBZeroPoint(*maybeBZp).failed())
2153 return failure();
2154
2155 return verifyMatMulShapes(*this, /*transposeB=*/true);
2156}
2157
2158LogicalResult tosa::MatmulTBlockScaledOp::inferReturnTypeComponents(
2159 MLIRContext *context, ::std::optional<Location> location,
2160 MatmulTBlockScaledOp::Adaptor adaptor,
2161 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2162 SmallVector<int64_t, 3> outShape(3, ShapedType::kDynamic);
2163
2164 const auto aDataShape = cast<ShapedType>(adaptor.getAData().getType());
2165 if (aDataShape.hasRank()) {
2166 outShape[0] = aDataShape.getDimSize(0);
2167 outShape[1] = aDataShape.getDimSize(1);
2168 }
2169
2170 const auto aScaleShape = cast<ShapedType>(adaptor.getAScale().getType());
2171 if (aScaleShape.hasRank()) {
2172 outShape[0] = ShapedType::isDynamic(outShape[0]) ? aScaleShape.getDimSize(0)
2173 : outShape[0];
2174 outShape[1] = ShapedType::isDynamic(outShape[1]) ? aScaleShape.getDimSize(1)
2175 : outShape[1];
2176 }
2177
2178 // If B batch size is 1, it is broadcast across A's batch size
2179 const auto bDataShape = cast<ShapedType>(adaptor.getBData().getType());
2180 if (bDataShape.hasRank()) {
2181 const int64_t bDataBatchSize = bDataShape.getDimSize(0);
2182 if (bDataBatchSize != 1)
2183 outShape[0] =
2184 ShapedType::isDynamic(outShape[0]) ? bDataBatchSize : outShape[0];
2185 outShape[2] = bDataShape.getDimSize(1);
2186 }
2187
2188 const auto bScaleShape = cast<ShapedType>(adaptor.getBScale().getType());
2189 if (bScaleShape.hasRank()) {
2190 const int64_t bScaleBatchSize = bScaleShape.getDimSize(0);
2191 if (bScaleBatchSize != 1)
2192 outShape[0] =
2193 ShapedType::isDynamic(outShape[0]) ? bScaleBatchSize : outShape[0];
2194 outShape[2] = ShapedType::isDynamic(outShape[2]) ? bScaleShape.getDimSize(1)
2195 : outShape[2];
2196 }
2197
2198 inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
2199 return success();
2200}
2201
2202LogicalResult MatmulTBlockScaledOp::verify() {
2203 // Verify same input data types
2204 const Type aDataType = getAData().getType();
2205 const Type bDataType = getBData().getType();
2206 if (failed(verifySameElementTypes(*this, aDataType, bDataType, "A_data",
2207 "B_data")))
2208 return failure();
2209
2210 // Verify input shape compatibility
2211 int64_t N = ShapedType::kDynamic;
2212 int64_t D = ShapedType::kDynamic;
2213 int64_t H = ShapedType::kDynamic;
2214 int64_t W = ShapedType::kDynamic;
2215 int64_t C = ShapedType::kDynamic;
2216 int64_t multiplesOfC = ShapedType::kDynamic;
2217
2218 const ShapeAdaptor aDataShape = ShapeAdaptor(aDataType);
2219 if (aDataShape.hasRank()) {
2220 N = aDataShape.getDimSize(0);
2221 H = aDataShape.getDimSize(1);
2222 C = aDataShape.getDimSize(2);
2223 }
2224
2225 const ShapeAdaptor aScaleShape = ShapeAdaptor(getAScale().getType());
2226 if (aScaleShape.hasRank()) {
2227 if (failed(tryUpdateDimOrFailure(*this, N, aScaleShape.getDimSize(0),
2228 "a_scale", "batch")) ||
2229 failed(tryUpdateDimOrFailure(*this, H, aScaleShape.getDimSize(1),
2230 "a_scale", "height")))
2231 return failure();
2232 multiplesOfC = aScaleShape.getDimSize(2);
2233 }
2234
2235 const ShapeAdaptor bDataShape = ShapeAdaptor(bDataType);
2236 if (bDataShape.hasRank()) {
2237 if (failed(tryUpdateDimOrFailure(*this, D, bDataShape.getDimSize(0),
2238 "b_data", "batch")) ||
2239 failed(tryUpdateDimOrFailure(*this, C, bDataShape.getDimSize(2),
2240 "b_data", "channels")))
2241 return failure();
2242 W = bDataShape.getDimSize(1);
2243 }
2244
2245 const ShapeAdaptor bScaleShape = ShapeAdaptor(getBScale().getType());
2246 if (bScaleShape.hasRank()) {
2247 if (failed(tryUpdateDimOrFailure(*this, D, bScaleShape.getDimSize(0),
2248 "b_scale", "batch")) ||
2249 failed(tryUpdateDimOrFailure(*this, W, bScaleShape.getDimSize(1),
2250 "b_scale", "width")) ||
2251 failed(tryUpdateDimOrFailure(*this, multiplesOfC,
2252 bScaleShape.getDimSize(2), "b_scale",
2253 "C/block_size")))
2254 return failure();
2255 }
2256
2257 // Verify batch size is broadcast compatible
2258 if (ShapedType::isStatic(N) && ShapedType::isStatic(D) && N != D && D != 1)
2259 return emitOpError("expect B matrix batch size to be broadcast compatible "
2260 "with A, got D=")
2261 << D << " vs N=" << N;
2262
2263 // Verify C is a multiple of block size
2264 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(getBlockSize());
2265 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
2266 return emitOpError("expect block size to be 32, got ") << blockSize;
2267 if (ShapedType::isStatic(C) && C % blockSize != 0)
2268 return emitOpError("expect C to be a multiple of block size, got C=")
2269 << C << ", block_size=" << blockSize;
2270
2271 // Verify multiplesOfC is C / block size
2272 if (ShapedType::isStatic(C) && ShapedType::isStatic(multiplesOfC) &&
2273 multiplesOfC != C / blockSize)
2274 return emitOpError(
2275 "expect scale operands dimension 2 to equal C/block_size (")
2276 << C << "/" << blockSize << ")" << ", got " << multiplesOfC;
2277
2278 // Verify output shape
2279 N = ShapedType::isDynamic(N) ? D : N;
2280 const SmallVector<int64_t, 3> expectedOutputShape = {N, H, W};
2281 const auto outputType = cast<ShapedType>(getResult().getType());
2282 if (outputType.hasRank() &&
2283 failed(
2284 verifyCompatibleShape(outputType.getShape(), expectedOutputShape))) {
2285 InFlightDiagnostic opError = emitOpError("expected output shape ");
2286 printShapeToDiagnostic(opError, outputType.getShape());
2287 opError << " to be compatible with expected output shape ";
2288 printShapeToDiagnostic(opError, expectedOutputShape);
2289 return opError;
2290 }
2291
2292 return success();
2293}
2294
2295LogicalResult tosa::PadOp::inferReturnTypeComponents(
2296 MLIRContext *context, ::std::optional<Location> location,
2297 PadOp::Adaptor adaptor,
2298 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2299 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2300 auto paddingRank =
2301 cast<tosa::shapeType>(adaptor.getPadding().getType()).getRank();
2302 SmallVector<int64_t> outputShape;
2303
2304 // If the input rank is unknown, we can infer the output rank using the
2305 // padding shape's rank divided by 2.
2306 if (!inputShape.hasRank()) {
2307 outputShape.resize(paddingRank / 2, ShapedType::kDynamic);
2308 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
2309 return success();
2310 }
2311
2312 SmallVector<int64_t> paddingValues;
2313 // If the paddings value is not a constant, all dimensions must be dynamic.
2314 if (!tosa::getConstShapeValues(adaptor.getPadding().getDefiningOp(),
2315 paddingValues)) {
2316 outputShape.resize(inputShape.getRank(), ShapedType::kDynamic);
2317 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
2318 return success();
2319 }
2320
2321 outputShape.reserve(inputShape.getRank());
2322 for (int i = 0, s = inputShape.getRank(); i < s; i++) {
2323 if (inputShape.isDynamicDim(i)) {
2324 outputShape.push_back(ShapedType::kDynamic);
2325 continue;
2326 }
2327 auto padFront = paddingValues[i * 2];
2328 auto padBack = paddingValues[i * 2 + 1];
2329 outputShape.push_back(inputShape.getDimSize(i) + padFront + padBack);
2330 }
2331
2332 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
2333 return success();
2334}
2335
2336LogicalResult tosa::PadOp::verify() {
2337 if (verifySameElementTypes(*this, /* inType = */ getInput1().getType(),
2338 /* outType = */ getOutput().getType())
2339 .failed()) {
2340 return failure();
2341 }
2342
2343 if (auto padConst = getPadConst()) {
2344 if (verifySameElementTypes(*this, /* inType = */ padConst.getType(),
2345 /* outType = */ getOutput().getType())
2346 .failed()) {
2347 return failure();
2348 }
2349 }
2350
2351 RankedTensorType inputType =
2352 llvm::dyn_cast<RankedTensorType>(getInput1().getType());
2353 RankedTensorType outputType =
2354 llvm::dyn_cast<RankedTensorType>(getOutput().getType());
2355 if (!inputType || !outputType)
2356 return success();
2357
2358 if (failed(verifyRanksMatch(getOperation(), inputType, outputType, "input",
2359 "output")))
2360 return failure();
2361
2362 auto inputRank = inputType.getRank();
2363 auto paddingRank = cast<tosa::shapeType>(getPadding().getType()).getRank();
2364 if (paddingRank != inputRank * 2)
2365 return emitOpError() << "padding tensor must have " << inputRank
2366 << " * 2 = " << inputRank * 2 << " elements, but got "
2367 << paddingRank;
2368
2369 return success();
2370}
2371
2372LogicalResult tosa::SliceOp::inferReturnTypeComponents(
2373 MLIRContext *context, ::std::optional<Location> location,
2374 SliceOp::Adaptor adaptor,
2375 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2376
2377 Type inputType = getElementTypeOrSelf(adaptor.getInput1().getType());
2380
2381 if (!tosa::getConstShapeValues(adaptor.getStart().getDefiningOp(), start) ||
2382 !tosa::getConstShapeValues(adaptor.getSize().getDefiningOp(), size)) {
2383 auto rank = cast<tosa::shapeType>(adaptor.getSize().getType()).getRank();
2384 SmallVector<int64_t> fallback(rank, ShapedType::kDynamic);
2385 inferredReturnShapes.push_back(ShapedTypeComponents(fallback, inputType));
2386 return success();
2387 }
2388
2389 // if size[i] is -1, all remaining elements in dimension i are included
2390 // in the slice, similar to TF.
2391 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2392 // initialize outputShape to all unknown
2393 SmallVector<int64_t> outputShape(size.size(), ShapedType::kDynamic);
2394 if (inputShape.hasRank()) {
2395 for (size_t i = 0; i < size.size(); i++) {
2396 if (size[i] != 0 && size[i] >= -1 && start[i] >= 0 &&
2397 (ShapedType::isDynamic(inputShape.getDimSize(i)) ||
2398 start[i] < inputShape.getDimSize(i))) {
2399 // size[i] is not 0 and not < -1, and start[i] is in valid range
2400 if (ShapedType::isDynamic(inputShape.getDimSize(i))) {
2401 // input shape has unknown dim[i] - only valid if size[i] > 0
2402 if (size[i] > 0) {
2403 outputShape[i] = size[i];
2404 }
2405 } else {
2406 // input shape has known dim[i]
2407 if (size[i] == -1) {
2408 outputShape[i] = inputShape.getDimSize(i) - start[i];
2409 } else if (start[i] + size[i] <= inputShape.getDimSize(i)) {
2410 // start[i] + size[i] is within bound of input shape's dim[i]
2411 outputShape[i] = size[i];
2412 }
2413 }
2414 }
2415 }
2416 } else {
2417 outputShape = convertToMlirShape(size);
2418 }
2419 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
2420 return success();
2421}
2422
2423LogicalResult tosa::SliceOp::verify() {
2424 const Value input = getInput1();
2425 const Value output = getOutput();
2426 if (verifySameElementTypes(*this, /* inType = */ input.getType(),
2427 /* outType = */ output.getType())
2428 .failed())
2429 return failure();
2430
2431 const Value start = getStart();
2432 const Value size = getSize();
2433 const ShapeAdaptor inputShape(input.getType());
2434 const ShapeAdaptor outputShape(output.getType());
2435
2436 if (inputShape.hasRank()) {
2437 const auto inputRank = inputShape.getRank();
2438 if (outputShape.hasRank() && inputRank != outputShape.getRank())
2439 return emitOpError(
2440 "expect input1 and output to have the same ranks, got ")
2441 << inputRank << " and " << outputShape.getRank();
2442
2443 const auto startShapeRank =
2444 llvm::cast<tosa::shapeType>(start.getType()).getRank();
2445 if (inputRank != startShapeRank)
2446 return emitOpError("length of start is not equal to rank of input shape");
2447
2448 const auto sizeShapeRank =
2449 llvm::cast<tosa::shapeType>(size.getType()).getRank();
2450 if (inputRank != sizeShapeRank)
2451 return emitOpError("length of size is not equal to rank of input shape");
2452 }
2453
2454 return success();
2455}
2456
2457LogicalResult tosa::MulOp::inferReturnTypeComponents(
2458 MLIRContext *context, ::std::optional<Location> location,
2459 ValueShapeRange operands, DictionaryAttr attributes, PropertyRef properties,
2460 RegionRange regions,
2461 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2462 // mul op's output shape only depend on input1 and input2, not on shift
2463 ValueShapeRange twoInputs = operands.drop_back();
2465 if (resolveBroadcastShape(twoInputs, outShape).failed()) {
2466 inferredReturnShapes.push_back(ShapedTypeComponents());
2467 } else {
2468 inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
2469 }
2470 return success();
2471}
2472
2473LogicalResult tosa::MulOp::verify() {
2474 const Value output = getOutput();
2475 auto resElemType = getElementTypeOrSelf(output);
2476
2477 // Verify if the element type among operands and result match tosa
2478 // specification.
2479 if (auto resIntType = dyn_cast<IntegerType>(resElemType)) {
2480 IntegerType lhsIntType =
2481 dyn_cast<IntegerType>(getElementTypeOrSelf(getInput1()));
2482 IntegerType rhsIntType =
2483 dyn_cast<IntegerType>(getElementTypeOrSelf(getInput2()));
2484 if (!lhsIntType || !rhsIntType || lhsIntType != rhsIntType)
2485 return emitOpError("requires the same element type for all operands");
2486
2487 // Though the spec requires the element type of result to be i32, a more
2488 // relaxed way is provided at dialect level for easier cooperating with
2489 // other dialects.
2490 if (lhsIntType.getWidth() > resIntType.getWidth())
2491 return emitOpError("invalid data type size for operands or result");
2492
2493 } else {
2494 // For other supported type, the spec requires requires the same element
2495 // type for all operands (excludes `shift` operand) and results.
2496 for (int i = 0; i < 2; ++i) {
2497 if (getElementTypeOrSelf(getOperand(i)) != resElemType)
2498 return emitOpError(
2499 "requires the same element type for all operands and results");
2500 }
2501 }
2502
2503 // Verify the op has same ranks for all main operands (excludes extra operands
2504 // such as shift of mul op, so this is the only difference with the built-in
2505 // `SameOperandsAndResultRank` trait) and results types, if known.
2506 TypeRange operandTypes = getOperandTypes();
2507 ShapedType aType = cast<ShapedType>(operandTypes[0]);
2508 ShapedType bType = cast<ShapedType>(operandTypes[1]);
2509
2510 const bool aHasRank = aType.hasRank();
2511 const bool bHasRank = bType.hasRank();
2512
2513 bool hasExpectedOutputShape = false;
2514 SmallVector<int64_t> expectedOutputShape;
2515
2516 if (aHasRank && bHasRank) {
2517 const int64_t aRank = aType.getRank();
2518 const int64_t bRank = bType.getRank();
2519 if (aRank != bRank)
2520 return emitOpError("a and b operands don't have matching ranks, got ")
2521 << aRank << " and " << bRank;
2522
2523 // check for broadcast compatible shapes
2525 aType.getShape(), bType.getShape(), expectedOutputShape))
2526 return emitOpError("a and b operands don't have broadcast-compatible "
2527 "shapes, got ")
2528 << aType << " and " << bType;
2529 hasExpectedOutputShape = true;
2530 }
2531
2532 ShapedType resultType = cast<ShapedType>(output.getType());
2533 if (!resultType.hasRank())
2534 return success();
2535
2536 const int64_t resultRank = resultType.getRank();
2537 if (aHasRank && resultRank != aType.getRank())
2538 return emitOpError("result type has different rank than a, got ")
2539 << resultRank << " vs " << aType.getRank();
2540 if (bHasRank && resultRank != bType.getRank())
2541 return emitOpError("result type has different rank than b, got ")
2542 << resultRank << " vs " << bType.getRank();
2543
2544 if (hasExpectedOutputShape &&
2545 failed(verifyOutputShapeCompatibleWithExpected(getOperation(), resultType,
2546 expectedOutputShape)))
2547 return failure();
2548
2549 return success();
2550}
2551
2552LogicalResult tosa::TableOp::inferReturnTypeComponents(
2553 MLIRContext *context, ::std::optional<Location> location,
2554 TableOp::Adaptor adaptor,
2555 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2556 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2557
2558 if (!inputShape.hasRank()) {
2559 inferredReturnShapes.push_back(ShapedTypeComponents());
2560 return success();
2561 }
2562
2563 inferredReturnShapes.resize(1);
2564 inputShape.getDims(inferredReturnShapes[0]);
2565 return success();
2566}
2567
2568LogicalResult tosa::TableOp::verify() {
2569 const TensorType inputType = getInput1().getType();
2570 const TensorType outputType = getOutput().getType();
2571
2572 if (!inputType.hasRank() || !outputType.hasRank())
2573 return success();
2574
2575 if (failed(verifyRanksMatch(getOperation(), inputType, outputType, "input",
2576 "result")))
2577 return failure();
2578
2579 auto inputDims = inputType.getShape();
2580 auto outputDims = outputType.getShape();
2581 for (auto it : llvm::enumerate(llvm::zip(inputDims, outputDims))) {
2582 int64_t dim = it.index();
2583 auto [inputDim, outputDim] = it.value();
2584 if (ShapedType::isStatic(outputDim) && outputDim != inputDim) {
2585 return emitOpError() << "dim(result, " << dim << ") = " << outputDim
2586 << " doesn't match dim(input, " << dim
2587 << ") = " << inputDim;
2588 }
2589 }
2590 return success();
2591}
2592
2593LogicalResult
2594tosa::TileOp::getConstantMultiples(SmallVector<int64_t> &multiples) {
2595 // Multiples must be constants.
2596 DenseIntElementsAttr multiplesAttr;
2597 if (!matchPattern(getMultiples(), m_Constant(&multiplesAttr)))
2598 return failure();
2599 multiples =
2600 llvm::map_to_vector(multiplesAttr.getValues<APInt>(),
2601 [](const APInt &val) { return val.getSExtValue(); });
2602 return success();
2603}
2604
2605LogicalResult tosa::TileOp::inferReturnTypeComponents(
2606 MLIRContext *context, ::std::optional<Location> location,
2607 TileOp::Adaptor adaptor,
2608 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2609 Type inputType = getElementTypeOrSelf(adaptor.getInput1().getType());
2610 SmallVector<int64_t> multiples;
2611 if (!tosa::getConstShapeValues(adaptor.getMultiples().getDefiningOp(),
2612 multiples)) {
2613 auto rank =
2614 cast<tosa::shapeType>(adaptor.getMultiples().getType()).getRank();
2615 SmallVector<int64_t> fallback(rank, ShapedType::kDynamic);
2616 inferredReturnShapes.push_back(ShapedTypeComponents(fallback, inputType));
2617 return success();
2618 }
2619 multiples = convertToMlirShape(multiples);
2620
2621 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2622 SmallVector<int64_t> outputShape;
2623 if (!inputShape.hasRank()) {
2624 outputShape.resize(multiples.size(), ShapedType::kDynamic);
2625 inferredReturnShapes.push_back(
2626 ShapedTypeComponents(outputShape, inputType));
2627 return success();
2628 }
2629 if (static_cast<size_t>(inputShape.getRank()) != multiples.size())
2630 return failure();
2631
2632 // Any non dynamic dimension can be multiplied to a known size.
2633 outputShape.reserve(multiples.size());
2634 for (int i = 0, s = inputShape.getRank(); i < s; i++) {
2635 if (multiples[i] == ShapedType::kDynamic) {
2636 outputShape.push_back(ShapedType::kDynamic);
2637 } else {
2638 int64_t dim = inputShape.getDimSize(i);
2639 if (dim != ShapedType::kDynamic)
2640 dim *= multiples[i];
2641 outputShape.push_back(dim);
2642 }
2643 }
2644
2645 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape, inputType));
2646 return success();
2647}
2648
2649LogicalResult tosa::TileOp::verify() {
2650 if (verifySameElementTypes(*this, /* intype = */ getInput1().getType(),
2651 /* outType = */ getOutput().getType())
2652 .failed()) {
2653 return failure();
2654 }
2655 ShapedType inputType = llvm::cast<ShapedType>(getInput1().getType());
2656 ShapedType outputType = llvm::cast<ShapedType>(getType());
2657
2658 shapeType multiplesType =
2659 llvm::cast<tosa::shapeType>(getMultiples().getType());
2660
2661 auto multiplesRank = multiplesType.getRank();
2662
2663 if (inputType.hasRank()) {
2664 if (inputType.getRank() != multiplesRank)
2665 return emitOpError("expect 'multiples' to have rank ")
2666 << inputType.getRank() << " but got " << multiplesRank << ".";
2667 if (outputType.hasRank() &&
2668 failed(verifyRanksMatch(getOperation(), inputType, outputType, "input",
2669 "output")))
2670 return failure();
2671 } else if (outputType.hasRank() && outputType.getRank() != multiplesRank)
2672 return emitOpError("expect 'multiples' array to have length ")
2673 << outputType.getRank() << " but got " << multiplesRank << ".";
2674
2675 SmallVector<int64_t> multiples;
2676 if (getConstantMultiples(multiples).succeeded() &&
2677 llvm::any_of(multiples, [](int64_t v) { return v <= 0 && v != -1; }))
2678 return emitOpError(
2679 "expect element of 'multiples' to be positive integer or -1.");
2680
2681 return success();
2682}
2683
2684bool tosa::ReshapeOp::isCompatibleReturnTypes(TypeRange l, TypeRange r) {
2685 if (l.size() != r.size() || l.size() != 1)
2686 return false;
2687 return getElementTypeOrSelf(l[0]) == getElementTypeOrSelf(r[0]);
2688}
2689
2690LogicalResult tosa::ReshapeOp::inferReturnTypeComponents(
2691 MLIRContext *context, ::std::optional<Location> location,
2692 ReshapeOp::Adaptor adaptor,
2693 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2694 ShapeAdaptor inputShape(adaptor.getInput1().getType());
2695 Type inputType = getElementTypeOrSelf(adaptor.getInput1().getType());
2696 llvm::SmallVector<int64_t> newShapeValue;
2697 if (!tosa::getConstShapeValues(adaptor.getShape().getDefiningOp(),
2698 newShapeValue)) {
2699 auto rank = cast<tosa::shapeType>(adaptor.getShape().getType()).getRank();
2700 SmallVector<int64_t> fallback(rank, ShapedType::kDynamic);
2701 inferredReturnShapes.push_back(ShapedTypeComponents(fallback, inputType));
2702 return success();
2703 }
2704 newShapeValue = convertToMlirShape(newShapeValue);
2705
2706 // We cannot infer from the total number of elements so we must take the
2707 // shape attribute as exact.
2708 if (!inputShape.hasRank() || !inputShape.hasStaticShape()) {
2709 inferredReturnShapes.push_back(
2710 ShapedTypeComponents(newShapeValue, inputType));
2711 return success();
2712 }
2713
2714 // Determine the number of elements covered by the slice of all static
2715 // dimensions. This allows us to infer the length of the remaining dynamic
2716 // dimension.
2717 int64_t numElements = inputShape.getNumElements();
2718 int64_t staticMul = 1;
2719 for (auto val : newShapeValue) {
2720 if (ShapedType::isStatic(val)) {
2721 staticMul *= val;
2722 }
2723 }
2724
2725 // Determine the length of the dynamic dimension.
2726 for (auto &val : newShapeValue) {
2727 if (ShapedType::isDynamic(val))
2728 val = numElements / staticMul;
2729 }
2730
2731 inferredReturnShapes.push_back(
2732 ShapedTypeComponents(newShapeValue, inputType));
2733 return success();
2734}
2735
2736llvm::LogicalResult tosa::ReshapeOp::verify() {
2737 if (verifySameElementTypes(*this, /* inType = */ getInput1().getType(),
2738 /* outType = */ getOutput().getType())
2739 .failed()) {
2740 return failure();
2741 }
2742 TensorType inputType = getInput1().getType();
2743
2744 SmallVector<int64_t> shapeValues;
2745 if (!tosa::getConstShapeValues(getShape().getDefiningOp(), shapeValues)) {
2746 // skip following checks if shape is not constant
2747 return mlir::success();
2748 }
2749
2750 int missingDims = llvm::count(shapeValues, kInferableDimSize);
2751 if (missingDims > 1)
2752 return emitOpError() << "expected at most one target dimension to be "
2754
2755 const auto outputType = dyn_cast<RankedTensorType>(getType());
2756 if (!outputType)
2757 return success();
2758
2759 if ((int64_t)shapeValues.size() != outputType.getRank())
2760 return emitOpError() << "new shape does not match result rank";
2761
2762 for (auto [newShapeDim, outputShapeDim] :
2763 zip(shapeValues, outputType.getShape())) {
2764 if (newShapeDim != kInferableDimSize &&
2765 newShapeDim != ShapedType::kDynamic &&
2766 outputShapeDim != ShapedType::kDynamic && newShapeDim != outputShapeDim)
2767 return emitOpError() << "new shape is inconsistent with result shape";
2768
2769 if (newShapeDim != ShapedType::kDynamic && newShapeDim < kInferableDimSize)
2770 return emitOpError() << "new shape has invalid tensor dimension size "
2771 << newShapeDim;
2772 }
2773
2774 if (inputType.hasStaticShape()) {
2775 int64_t inputElementsNum = inputType.getNumElements();
2776 if (outputType.hasStaticShape()) {
2777 int64_t outputElementsNum = outputType.getNumElements();
2778 if (inputElementsNum != outputElementsNum) {
2779 return emitOpError() << "cannot reshape " << inputElementsNum
2780 << " elements into " << outputElementsNum;
2781 }
2782 }
2783
2784 int64_t newShapeElementsNum =
2785 llvm::accumulate(shapeValues, int64_t(1), [](int64_t acc, int64_t dim) {
2786 return (dim > 0) ? acc * dim : acc;
2787 });
2788 bool isStaticNewShape =
2789 llvm::all_of(shapeValues, [](int64_t s) { return s > 0; });
2790 if ((isStaticNewShape && inputElementsNum != newShapeElementsNum) ||
2791 (!isStaticNewShape && newShapeElementsNum > inputElementsNum)) {
2792 return emitOpError() << "cannot reshape " << inputElementsNum
2793 << " elements into " << newShapeElementsNum;
2794 }
2795 }
2796
2797 return mlir::success();
2798}
2799
2800bool tosa::ReshapeBlockScaledOp::isCompatibleReturnTypes(TypeRange l,
2801 TypeRange r) {
2802 if (l.size() != r.size() || l.size() < 1 || l.size() > 2)
2803 return false;
2804 bool ok = (getElementTypeOrSelf(l[0]) == getElementTypeOrSelf(r[0]));
2805 if (l.size() == 2)
2806 ok = ok && (getElementTypeOrSelf(l[1]) == getElementTypeOrSelf(r[1]));
2807 return ok;
2808}
2809
2810LogicalResult tosa::ReshapeBlockScaledOp::inferReturnTypeComponents(
2811 MLIRContext *context, ::std::optional<Location> location,
2812 ReshapeBlockScaledOp::Adaptor adaptor,
2813 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
2814
2815 const auto numInputs = adaptor.getInput().size();
2816 ShapeAdaptor inputShape(adaptor.getInput()[0].getType());
2817 Type inputType = getElementTypeOrSelf(adaptor.getInput()[0].getType());
2818 llvm::SmallVector<int64_t> newShapeValue;
2819 const auto newShape = adaptor.getNewValueShape();
2820 if (!tosa::getConstShapeValues(newShape.getDefiningOp(), newShapeValue)) {
2821 auto rank = cast<tosa::shapeType>(newShape.getType()).getRank();
2822 SmallVector<int64_t> fallback(rank, ShapedType::kDynamic);
2823 inferredReturnShapes.push_back(ShapedTypeComponents(fallback, inputType));
2824 if (numInputs == 2)
2825 inferredReturnShapes.push_back(ShapedTypeComponents(
2826 fallback, getElementTypeOrSelf(adaptor.getInput()[1].getType())));
2827 return success();
2828 }
2829
2830 const uint32_t blockSize =
2831 BlockSizeAttr::getBlockSizeValue(adaptor.getBlockSize());
2832
2833 llvm::SmallVector<int64_t> newScaleShapeValue;
2834 if (numInputs == 2) {
2835 newScaleShapeValue.assign(newShapeValue.begin(), newShapeValue.end());
2836 if (!newScaleShapeValue.empty() &&
2837 ShapedType::isStatic(newScaleShapeValue.back()))
2838 newScaleShapeValue.back() /= blockSize;
2839 }
2840
2841 inferredReturnShapes.push_back(
2842 ShapedTypeComponents(newShapeValue, inputType));
2843 if (numInputs == 2) {
2844 // Fix up scale shape - with special case for last dimension
2845 for (size_t idx = 0; idx < newShapeValue.size(); idx++) {
2846 if (ShapedType::isDynamic(newScaleShapeValue[idx])) {
2847 newScaleShapeValue[idx] = newShapeValue[idx];
2848 if (idx + 1 == newShapeValue.size())
2849 newScaleShapeValue[idx] /= blockSize;
2850 }
2851 }
2852
2853 inferredReturnShapes.push_back(ShapedTypeComponents(
2854 newScaleShapeValue,
2855 getElementTypeOrSelf(adaptor.getInput()[1].getType())));
2856 }
2857 return success();
2858}
2859
2860llvm::LogicalResult tosa::ReshapeBlockScaledOp::verify() {
2861 const Operation::operand_range inputList = getInput();
2862 const Operation::result_range outputList = getResults();
2863
2864 if (inputList.size() == 0)
2865 return emitOpError("requires at least one input");
2866
2867 if (inputList.size() > 2)
2868 return emitOpError("requires at most two inputs");
2869
2870 if (inputList.size() != outputList.size())
2871 return emitOpError("requires number of results to match inputs");
2872
2873 if (verifySameElementTypes(*this, /* inType = */ inputList[0].getType(),
2874 /* outType = */ outputList[0].getType())
2875 .failed()) {
2876 return failure();
2877 }
2878
2879 if (inputList.size() == 2 &&
2880 cast<tosa::shapeType>(getNewValueShape().getType()).getRank() == 0)
2881 return emitOpError("requires new shape to have a rank greater than 0");
2882
2883 const auto inputType = llvm::cast<ShapedType>(inputList[0].getType());
2884 if (!inputType.hasRank())
2885 return success();
2886 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(getBlockSize());
2887
2888 if (inputList.size() == 2) {
2889 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
2890 return emitOpError("expect block size to be 32, got ") << blockSize;
2891 if (llvm::any_of(inputList, [](Value v) {
2892 const auto input = cast<ShapedType>(v.getType());
2893 return input.hasRank() && input.getRank() == 0;
2894 }))
2895 return emitOpError(
2896 "requires all input shapes have a rank greater than 0");
2897 if (llvm::any_of(outputList, [](Value v) {
2898 const auto output = cast<ShapedType>(v.getType());
2899 return output.hasRank() && output.getRank() == 0;
2900 }))
2901 return emitOpError(
2902 "requires all result shapes have a rank greater than 0");
2903
2904 if (verifySameElementTypes(*this, /* inType = */ inputList[1].getType(),
2905 /* outType = */ outputList[1].getType())
2906 .failed()) {
2907 return failure();
2908 }
2909
2910 const auto inputScaleType = llvm::cast<ShapedType>(inputList[1].getType());
2911 if (inputScaleType.hasRank()) {
2912 if (inputType.getRank() != inputScaleType.getRank())
2913 return emitOpError("input shapes do not have same rank");
2914
2915 // Check all but the last dimension that the input shape dimensions match
2916 for (auto dimIdx = 0; dimIdx < inputType.getRank() - 1; dimIdx++) {
2917 const int64_t inputValueDim = inputType.getDimSize(dimIdx);
2918 const int64_t inputScaleDim = inputScaleType.getShape()[dimIdx];
2919 if (ShapedType::isStatic(inputValueDim) &&
2920 ShapedType::isStatic(inputScaleDim) &&
2921 inputValueDim != inputScaleDim)
2922 return emitOpError("input shapes for data and scale do not match on "
2923 "dimension ")
2924 << dimIdx;
2925 }
2926
2927 // Verify last dimension of input is a multiple of block size
2928 const int64_t lastValueDim =
2929 inputType.getDimSize(inputType.getRank() - 1);
2930 if (ShapedType::isStatic(lastValueDim)) {
2931 if (lastValueDim % blockSize != 0)
2932 return emitOpError("expect last dimension of input_data (")
2933 << lastValueDim << ") to be divisible by block_size ("
2934 << blockSize << ")";
2935
2936 const int64_t lastScaleDim =
2937 inputScaleType.getDimSize(inputScaleType.getRank() - 1);
2938 // Verify last dimension of scale is lastValueDim / block size
2939 if (ShapedType::isStatic(lastScaleDim) &&
2940 lastScaleDim != lastValueDim / blockSize)
2941 return emitOpError("expect last dimension of scale_data (")
2942 << lastScaleDim << ") to be " << lastValueDim << "/"
2943 << blockSize;
2944 }
2945 }
2946 } else {
2947 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_1))
2948 return emitOpError("expect block size to be 1, got ") << blockSize;
2949 }
2950
2951 // Get the new value shape dimension values.
2952 SmallVector<int64_t> shapeValues;
2953 if (!tosa::getConstShapeValues(getNewValueShape().getDefiningOp(),
2954 shapeValues)) {
2955 // skip following checks if shape is not constant
2956 return mlir::success();
2957 }
2958
2959 if (inputList.size() == 2) {
2960 const int64_t lastShapeDim = shapeValues.back();
2961 if (ShapedType::isStatic(lastShapeDim) && lastShapeDim % blockSize != 0)
2962 return emitOpError("expect last dimension of new shape (")
2963 << lastShapeDim << ") to be divisible by block_size (" << blockSize
2964 << ")";
2965 }
2966
2967 const auto outputType = llvm::cast<ShapedType>(outputList[0].getType());
2968 if (!outputType.hasRank())
2969 return success();
2970
2971 if (static_cast<int64_t>(shapeValues.size()) != outputType.getRank())
2972 return emitOpError() << "result does not match new shape rank";
2973
2974 for (auto [newShapeDim, outputShapeDim] :
2975 zip(shapeValues, outputType.getShape())) {
2976 if (ShapedType::isStatic(newShapeDim) &&
2977 ShapedType::isStatic(outputShapeDim) && newShapeDim != outputShapeDim)
2978 return emitOpError() << "result shape is inconsistent with new shape";
2979 }
2980
2981 if (outputList.size() == 2) {
2982 // Set up scale shape from new shape given
2983 SmallVector<int64_t> scaleShapeValues(shapeValues.begin(),
2984 shapeValues.end());
2985 scaleShapeValues.back() /= blockSize;
2986
2987 const auto outputScaleType =
2988 llvm::cast<ShapedType>(outputList[1].getType());
2989 if (outputScaleType.hasRank()) {
2990 if ((int64_t)scaleShapeValues.size() != outputScaleType.getRank())
2991 return emitOpError() << "result scale does not match new shape rank";
2992
2993 for (auto [newScaleShapeDim, outputScaleShapeDim] :
2994 zip(scaleShapeValues, outputScaleType.getShape())) {
2995 if (ShapedType::isStatic(newScaleShapeDim) &&
2996 ShapedType::isStatic(outputScaleShapeDim) &&
2997 newScaleShapeDim != outputScaleShapeDim)
2998 return emitOpError()
2999 << "result scale shape is inconsistent with new shape";
3000 }
3001 }
3002 }
3003
3004 if (inputType.hasStaticShape()) {
3005 int64_t inputElementsNum = inputType.getNumElements();
3006 if (outputType.hasStaticShape()) {
3007 int64_t outputElementsNum = outputType.getNumElements();
3008 if (inputElementsNum != outputElementsNum) {
3009 return emitOpError() << "cannot reshape " << inputElementsNum
3010 << " elements into " << outputElementsNum;
3011 }
3012 }
3013
3014 int64_t newShapeElementsNum =
3015 llvm::accumulate(shapeValues, int64_t(1), [](int64_t acc, int64_t dim) {
3016 return (dim > 0) ? acc * dim : acc;
3017 });
3018 bool isStaticNewShape =
3019 llvm::all_of(shapeValues, [](int64_t s) { return s > 0; });
3020 if ((isStaticNewShape && inputElementsNum != newShapeElementsNum) ||
3021 (!isStaticNewShape && newShapeElementsNum > inputElementsNum)) {
3022 return emitOpError() << "cannot reshape " << inputElementsNum
3023 << " elements into " << newShapeElementsNum;
3024 }
3025 }
3026
3027 return mlir::success();
3028}
3029
3030// return failure if val is not a constant
3031// set zp to -1 if val is non-zero float or val is not integer nor float
3032// otherwise set zp to val's constant value
3033static FailureOr<int64_t> getZeroPoint(Value val, bool signExtend) {
3034 ElementsAttr zpAttr;
3035 if (!matchPattern(val, m_Constant(&zpAttr))) {
3036 return failure();
3037 }
3038
3039 Type zpElemType = zpAttr.getElementType();
3040
3041 if (llvm::isa<FloatType>(zpElemType)) {
3042 if (zpAttr.getValues<APFloat>()[0].isZero()) {
3043 return 0;
3044 }
3045 // return non-zero value to trigger error check
3046 return -1;
3047 }
3048
3049 if (llvm::isa<IntegerType>(zpElemType)) {
3050 if (signExtend)
3051 return zpAttr.getValues<APInt>()[0].getSExtValue();
3052 return zpAttr.getValues<APInt>()[0].getZExtValue();
3053 }
3054
3055 // return non-zero value to trigger error check
3056 return -1;
3057}
3058
3059template <typename T>
3060static LogicalResult verifyZeroPoint(T op, Value val, const int64_t &zp,
3061 const std::string &operand) {
3062 Type zpElemType = getElementTypeOrSelf(val);
3063
3064 if (!zpElemType.isInteger(8) && zp != 0) {
3065 // convert operand to lower case for error message
3066 std::string lower = operand;
3067 llvm::transform(lower, lower.begin(), ::tolower);
3068 return op.emitOpError()
3069 << lower << " zero point must be zero for non-int8 integer types";
3070 }
3071
3072 return success();
3073}
3074
3075static LogicalResult verifyZeroPoint(tosa::RescaleOp op, Value zpVal,
3076 const int64_t &zp,
3077 const std::string &operand) {
3078 bool isInputZp = (operand == "Input");
3079
3080 bool tensorUnsigned =
3081 isInputZp ? op.getInputUnsigned() : op.getOutputUnsigned();
3082 StringRef tensorName = isInputZp ? "input" : "output";
3083
3084 Type zpElemType = getElementTypeOrSelf(zpVal);
3085
3086 if (zp != 0) {
3087 if (!zpElemType.isInteger(8) &&
3088 !(zpElemType.isInteger(16) && tensorUnsigned)) {
3089 return op.emitOpError()
3090 << "expect " << tensorName << "_zp of 0, got " << zp;
3091 }
3092 if (zpElemType.isInteger(16) && tensorUnsigned && zp != 32768) {
3093 return op.emitOpError() << "expect " << tensorName
3094 << "_zp of 0 or 32768 for unsigned int16 "
3095 << tensorName << ", got " << zp;
3096 }
3097 }
3098
3099 return success();
3100}
3101
3102#define ZERO_POINT_HELPER(OP, OPERAND_NAME, SIGN_EXTEND) \
3103 FailureOr<int64_t> tosa::OP::get##OPERAND_NAME##ZeroPoint() { \
3104 return getZeroPoint(get##OPERAND_NAME##Zp(), SIGN_EXTEND); \
3105 } \
3106 LogicalResult tosa::OP::verify##OPERAND_NAME##ZeroPoint(int64_t zp) { \
3107 return verifyZeroPoint(*this, get##OPERAND_NAME##Zp(), zp, #OPERAND_NAME); \
3108 }
3109
3110ZERO_POINT_HELPER(Conv2DOp, Input, true)
3111ZERO_POINT_HELPER(Conv2DOp, Weight, true)
3112ZERO_POINT_HELPER(Conv3DOp, Input, true)
3113ZERO_POINT_HELPER(Conv3DOp, Weight, true)
3114ZERO_POINT_HELPER(DepthwiseConv2DOp, Input, true)
3115ZERO_POINT_HELPER(DepthwiseConv2DOp, Weight, true)
3116ZERO_POINT_HELPER(TransposeConv2DOp, Input, true)
3117ZERO_POINT_HELPER(TransposeConv2DOp, Weight, true)
3118ZERO_POINT_HELPER(AvgPool2dOp, Input, true)
3119ZERO_POINT_HELPER(AvgPool2dOp, Output, true)
3120ZERO_POINT_HELPER(AvgPool2dAdaptiveOp, Input, true)
3121ZERO_POINT_HELPER(AvgPool2dAdaptiveOp, Output, true)
3122ZERO_POINT_HELPER(MatMulOp, A, true)
3123ZERO_POINT_HELPER(MatMulOp, B, true)
3124ZERO_POINT_HELPER(MatMulTOp, A, true)
3125ZERO_POINT_HELPER(MatMulTOp, B, true)
3126ZERO_POINT_HELPER(NegateOp, Input1, true)
3127ZERO_POINT_HELPER(NegateOp, Output, true)
3128ZERO_POINT_HELPER(RescaleOp, Input, !getInputUnsigned())
3129ZERO_POINT_HELPER(RescaleOp, Output, !getOutputUnsigned())
3130#undef ZERO_POINT_HELPER
3131
3132LogicalResult tosa::TransposeOp::inferReturnTypeComponents(
3133 MLIRContext *context, ::std::optional<Location> location,
3134 TransposeOp::Adaptor adaptor,
3135 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3136 ShapeAdaptor inputShape(adaptor.getInput1().getType());
3137
3138 // If input rank and permutation length is unknown, the output rank is
3139 // unknown.
3140 if (!inputShape.hasRank()) {
3141 inferredReturnShapes.push_back(ShapedTypeComponents());
3142 return success();
3143 }
3144
3145 const auto inputRank = inputShape.getRank();
3146
3147 // This would imply the number of permutations does not match the rank of
3148 // the input which is illegal.
3149 if (adaptor.getPerms().size() != static_cast<size_t>(inputRank)) {
3150 return failure();
3151 }
3152
3153 SmallVector<int64_t> outputShape;
3154 // Rank-0 means no permutations matter.
3155 if (inputRank == 0) {
3156 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3157 return success();
3158 }
3159
3160 // Check whether the input dimensions are all the same.
3161 bool allTheSame = true;
3162 for (int i = 1, s = inputRank; i < s; i++) {
3163 if (inputShape.getDimSize(0) != inputShape.getDimSize(i)) {
3164 allTheSame = false;
3165 break;
3166 }
3167 }
3168
3169 // If all of the input dimensions are the same we don't care about the
3170 // permutation.
3171 if (allTheSame) {
3172 outputShape.resize(inputRank, inputShape.getDimSize(0));
3173 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3174 return success();
3175 }
3176
3177 outputShape.resize(inputRank, ShapedType::kDynamic);
3178
3179 // Constant permutation values must be within the input rank.
3180 if (llvm::any_of(adaptor.getPerms(),
3181 [inputRank](const auto i) { return i >= inputRank; }))
3182 return failure();
3183
3184 outputShape.reserve(inputRank);
3185 for (int i = 0, s = inputRank; i < s; i++) {
3186 outputShape[i] = inputShape.getDimSize(adaptor.getPerms()[i]);
3187 }
3188
3189 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3190 return success();
3191}
3192
3193LogicalResult tosa::TransposeOp::verify() {
3194 if (verifySameElementTypes(*this, /* inType = */ getInput1().getType(),
3195 /* outType = */ getOutput().getType())
3196 .failed()) {
3197 return failure();
3198 }
3199
3200 const ShapeAdaptor inputShape(getInput1().getType());
3201 const ShapeAdaptor outputShape(getOutput().getType());
3202
3203 const llvm::ArrayRef<int32_t> constantPerms = getPerms();
3204
3205 if (inputShape.hasRank() &&
3206 constantPerms.size() != static_cast<size_t>(inputShape.getRank()))
3207 return emitOpError() << "expected perms attribute to have size "
3208 << inputShape.getRank()
3209 << " (input rank) but got size "
3210 << constantPerms.size();
3211
3212 if (inputShape.hasRank() && outputShape.hasRank() &&
3213 inputShape.getRank() != outputShape.getRank())
3214 return emitOpError()
3215 << "expected input tensor rank to equal result tensor rank";
3216
3217 if (outputShape.hasRank() &&
3218 constantPerms.size() != static_cast<size_t>(outputShape.getRank()))
3219 return emitOpError() << "expected perms attribute to have size "
3220 << outputShape.getRank()
3221 << " (output rank) but got size "
3222 << constantPerms.size();
3223
3224 if (!llvm::all_of(constantPerms,
3225 [&constantPerms](int32_t s) {
3226 return s >= 0 &&
3227 static_cast<size_t>(s) < constantPerms.size();
3228 }) ||
3229 !isPermutationVector(llvm::map_to_vector(
3230 constantPerms, [](int32_t v) -> int64_t { return v; })))
3231 return emitOpError() << "expected valid permutation indices";
3232
3233 if (isa<BlockScaledType>(getInput1().getType().getElementType()) &&
3234 constantPerms.back() != static_cast<int32_t>(constantPerms.size()) - 1) {
3235 return emitOpError() << "expected no-op permutation on innermost dimension "
3236 "for block scaled input";
3237 }
3238
3239 // ERROR_IF(tensor_size(shape1) != tensor_size(shape))
3240 if (inputShape.hasStaticShape() && outputShape.hasStaticShape() &&
3241 inputShape.getNumElements() != outputShape.getNumElements())
3242 return emitOpError() << "expected input1 and output to have same numbers "
3243 "of elements, got "
3244 << inputShape.getNumElements() << " and "
3245 << outputShape.getNumElements();
3246
3247 // Verify that the types of the input and output tensors are properly
3248 // permuted.
3249 if (inputShape.hasRank() && outputShape.hasRank()) {
3250 for (auto i = 0; i < outputShape.getRank(); i++) {
3251 if (inputShape.isDynamicDim(constantPerms[i]) ||
3252 outputShape.isDynamicDim(i))
3253 continue;
3254
3255 if (inputShape.getDimSize(constantPerms[i]) != outputShape.getDimSize(i))
3256 return emitOpError()
3257 << "expected output tensor dim " << i << " to match "
3258 << "input dim " << constantPerms[i] << " with value of "
3259 << inputShape.getDimSize(constantPerms[i]);
3260 }
3261 }
3262
3263 return success();
3264}
3265
3266LogicalResult TransposeOp::reifyResultShapes(
3267 OpBuilder &builder, ReifiedRankedShapedTypeDims &reifiedReturnShapes) {
3268
3269 const llvm::ArrayRef<int32_t> transposePerms = getPerms();
3270
3271 Value input = getInput1();
3272 auto inputType = cast<TensorType>(input.getType());
3273
3274 SmallVector<OpFoldResult> returnedDims(inputType.getRank());
3275 for (auto dim : transposePerms) {
3276 int32_t dimInInput = transposePerms[dim];
3277 if (inputType.isDynamicDim(dimInInput))
3278 returnedDims[dim] =
3279 tensor::DimOp::create(builder, getLoc(), input, dimInInput)
3280 .getResult();
3281 else
3282 returnedDims[dim] =
3283 builder.getIndexAttr(inputType.getDimSize(dimInInput));
3284 }
3285
3286 reifiedReturnShapes.emplace_back(std::move(returnedDims));
3287 return success();
3288}
3289
3290LogicalResult tosa::GatherOp::inferReturnTypeComponents(
3291 MLIRContext *context, ::std::optional<Location> location,
3292 GatherOp::Adaptor adaptor,
3293 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3294 llvm::SmallVector<int64_t> outputShape;
3295 outputShape.resize(3, ShapedType::kDynamic);
3296
3297 ShapeAdaptor valuesShape(adaptor.getValues().getType());
3298 if (valuesShape.hasRank()) {
3299 outputShape[0] = valuesShape.getDimSize(0);
3300 outputShape[2] = valuesShape.getDimSize(2);
3301 }
3302
3303 ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3304 if (indicesShape.hasRank()) {
3305 if (outputShape[0] == ShapedType::kDynamic)
3306 outputShape[0] = indicesShape.getDimSize(0);
3307 if (outputShape[1] == ShapedType::kDynamic)
3308 outputShape[1] = indicesShape.getDimSize(1);
3309 }
3310
3311 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3312 return success();
3313}
3314
3315LogicalResult tosa::RowGatherOp::inferReturnTypeComponents(
3316 MLIRContext *context, ::std::optional<Location> location,
3317 RowGatherOp::Adaptor adaptor,
3318 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3319 llvm::SmallVector<int64_t> outputShape;
3320 outputShape.resize(3, ShapedType::kDynamic);
3321
3322 const ShapeAdaptor valuesShape(adaptor.getValues().getType());
3323 if (valuesShape.hasRank()) {
3324 outputShape[0] = valuesShape.getDimSize(0);
3325 outputShape[2] = valuesShape.getDimSize(2);
3326 }
3327
3328 const ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3329 if (indicesShape.hasRank()) {
3330 if (outputShape[0] == ShapedType::kDynamic)
3331 outputShape[0] = indicesShape.getDimSize(0);
3332
3333 const FailureOr<int32_t> maybeRowCount =
3334 getConstantScalarIntValue<int32_t>(adaptor.getRowCount());
3335 if (succeeded(maybeRowCount)) {
3336 const int64_t indicesW = indicesShape.getDimSize(1);
3337 if (ShapedType::isStatic(indicesW))
3338 outputShape[1] = indicesW * maybeRowCount.value();
3339 }
3340 }
3341
3342 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3343 return success();
3344}
3345
3346LogicalResult tosa::RowGatherBlockScaledOp::inferReturnTypeComponents(
3347 MLIRContext *context, ::std::optional<Location> location,
3348 RowGatherBlockScaledOp::Adaptor adaptor,
3349 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3350 const auto values = adaptor.getValues();
3351 if (values.empty())
3352 return failure();
3353
3354 SmallVector<int64_t> dataShape(3, ShapedType::kDynamic);
3355 const ShapeAdaptor valuesShape(values.front().getType());
3356 if (valuesShape.hasRank()) {
3357 dataShape[0] = valuesShape.getDimSize(0);
3358 dataShape[2] = valuesShape.getDimSize(2);
3359 }
3360
3361 const ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3362 if (indicesShape.hasRank()) {
3363 if (dataShape[0] == ShapedType::kDynamic)
3364 dataShape[0] = indicesShape.getDimSize(0);
3365
3366 if (auto rowCount =
3367 getConstantScalarIntValue<int32_t>(adaptor.getRowCount());
3368 succeeded(rowCount) && rowCount.value() > 0) {
3369 const int64_t indicesW = indicesShape.getDimSize(1);
3370 if (ShapedType::isStatic(indicesW))
3371 dataShape[1] = indicesW * rowCount.value();
3372 }
3373 }
3374
3375 inferredReturnShapes.push_back(ShapedTypeComponents(dataShape));
3376 if (values.size() == 1)
3377 return success();
3378
3379 SmallVector<int64_t> scaleShape = dataShape;
3380 const uint32_t blockSize =
3381 BlockSizeAttr::getBlockSizeValue(adaptor.getBlockSize());
3382 if (ShapedType::isStatic(dataShape[2]))
3383 scaleShape[2] = dataShape[2] / blockSize;
3384
3385 inferredReturnShapes.push_back(ShapedTypeComponents(scaleShape));
3386 return success();
3387}
3388
3389LogicalResult tosa::GatherOp::verify() {
3390 if (verifySameElementTypes(*this, /* inType = */ getValues().getType(),
3391 /* outType = */ getOutput().getType())
3392 .failed()) {
3393 return failure();
3394 }
3395
3396 const ShapeAdaptor valuesShape(getValues().getType());
3397 const ShapeAdaptor indicesShape(getIndices().getType());
3398 const ShapeAdaptor outputShape(getOutput().getType());
3399
3400 int64_t n = ShapedType::kDynamic;
3401 int64_t w = ShapedType::kDynamic;
3402 int64_t c = ShapedType::kDynamic;
3403
3404 if (valuesShape.hasRank()) {
3405 n = valuesShape.getDimSize(0);
3406 c = valuesShape.getDimSize(2);
3407 }
3408 if (indicesShape.hasRank()) {
3409 const int64_t indicesN = indicesShape.getDimSize(0);
3410 w = indicesShape.getDimSize(1);
3411 if (n == ShapedType::kDynamic)
3412 n = indicesN;
3413 else if (indicesN != ShapedType::kDynamic && n != indicesN)
3414 return emitOpError() << "requires indices dimension 0 to have size " << n
3415 << ", got " << indicesN;
3416 }
3417 if (outputShape.hasRank()) {
3418 const int64_t outputN = outputShape.getDimSize(0);
3419 const int64_t outputW = outputShape.getDimSize(1);
3420 const int64_t outputC = outputShape.getDimSize(2);
3421 if (n != ShapedType::kDynamic && outputN != ShapedType::kDynamic &&
3422 n != outputN)
3423 return emitOpError() << "requires output dimension 0 to have size " << n
3424 << ", got " << outputN;
3425
3426 if (w != ShapedType::kDynamic && outputW != ShapedType::kDynamic &&
3427 w != outputW)
3428 return emitOpError() << "requires output dimension 1 to have size " << w
3429 << ", got " << outputW;
3430 if (c != ShapedType::kDynamic && outputC != ShapedType::kDynamic &&
3431 c != outputC)
3432 return emitOpError() << "requires output dimension 2 to have size " << c
3433 << ", got " << outputC;
3434 }
3435 return success();
3436}
3437
3438LogicalResult tosa::RowGatherOp::verify() {
3439 if (failed(verifySameElementTypes(*this, /* inType = */ getValues().getType(),
3440 /* outType = */ getOutput().getType())))
3441 return failure();
3442
3443 const FailureOr<int32_t> maybeRowCount =
3445 if (succeeded(maybeRowCount) && maybeRowCount.value() <= 0)
3446 return emitOpError() << "requires row_count to be > 0, got "
3447 << maybeRowCount.value();
3448
3449 int64_t n = ShapedType::kDynamic;
3450 int64_t c = ShapedType::kDynamic;
3451 int64_t w = ShapedType::kDynamic;
3452
3453 const ShapeAdaptor valuesShape(getValues().getType());
3454 if (valuesShape.hasRank()) {
3455 n = valuesShape.getDimSize(0);
3456 c = valuesShape.getDimSize(2);
3457 }
3458
3459 const ShapeAdaptor indicesShape(getIndices().getType());
3460 if (indicesShape.hasRank()) {
3461 if (failed(tryUpdateDimOrFailure(*this, n, indicesShape.getDimSize(0),
3462 "indices", "batch")))
3463 return failure();
3464 w = indicesShape.getDimSize(1);
3465 }
3466
3467 const ShapeAdaptor outputShape(getOutput().getType());
3468 if (outputShape.hasRank()) {
3469 if (failed(tryUpdateDimOrFailure(*this, n, outputShape.getDimSize(0),
3470 "output", "batch")) ||
3471 failed(tryUpdateDimOrFailure(*this, c, outputShape.getDimSize(2),
3472 "output", "channels")))
3473 return failure();
3474
3475 if (succeeded(maybeRowCount) && maybeRowCount.value() > 0 &&
3476 ShapedType::isStatic(w)) {
3477 const int64_t expectedOutputRows = w * maybeRowCount.value();
3478 if (ShapedType::isStatic(outputShape.getDimSize(1)) &&
3479 outputShape.getDimSize(1) != expectedOutputRows)
3480 return emitOpError()
3481 << "requires output dimension to be equal to "
3482 "indices[1]*row_count ("
3483 << expectedOutputRows << "), got " << outputShape.getDimSize(1);
3484 }
3485 }
3486
3487 return success();
3488}
3489
3490LogicalResult tosa::RowGatherBlockScaledOp::verify() {
3491 const OperandRange values = getValues();
3492 const ResultRange output = getOutput();
3493 if (values.empty() || values.size() > 2)
3494 return emitOpError()
3495 << "expects values tensor list length to be 1 or 2, got "
3496 << values.size();
3497 if (output.size() != values.size())
3498 return emitOpError()
3499 << "expects output tensor list length to match values tensor list "
3500 "length, got "
3501 << output.size() << " results for " << values.size()
3502 << " input tensors";
3503
3504 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(getBlockSize());
3505 if (values.size() == 1 && blockSize != 1)
3506 return emitOpError()
3507 << "requires block_size to be BLOCK_SIZE_1 when values tensor list "
3508 "length is 1";
3509 if (values.size() == 2 && blockSize == 1)
3510 return emitOpError()
3511 << "requires block_size to not be BLOCK_SIZE_1 when values tensor "
3512 "list length is 2";
3513
3514 if (failed(verifySameElementTypes(*this, values[0].getType(),
3515 output[0].getType(), "values[0]",
3516 "output[0]")))
3517 return failure();
3518 if (values.size() == 2 && failed(verifySameElementTypes(
3519 *this, values[1].getType(), output[1].getType(),
3520 "values[1]", "output[1]")))
3521 return failure();
3522
3523 if (auto rowCount = getConstantScalarIntValue<int32_t>(getRowCount());
3524 succeeded(rowCount) && rowCount.value() <= 0)
3525 return emitOpError() << "requires row_count to be > 0, got "
3526 << rowCount.value();
3527
3528 int64_t n = ShapedType::kDynamic;
3529 int64_t k = ShapedType::kDynamic;
3530 int64_t c = ShapedType::kDynamic;
3531 int64_t w = ShapedType::kDynamic;
3532 int64_t multiplesOfC = ShapedType::kDynamic;
3533
3534 const ShapeAdaptor valuesDataShape(values[0].getType());
3535 if (valuesDataShape.hasRank()) {
3536 n = valuesDataShape.getDimSize(0);
3537 k = valuesDataShape.getDimSize(1);
3538 c = valuesDataShape.getDimSize(2);
3539 }
3540
3541 if (ShapedType::isStatic(c) && c % blockSize != 0)
3542 return emitOpError() << "expects channels of values[0] (" << c
3543 << ") to be divisible by block_size (" << blockSize
3544 << ")";
3545
3546 const ShapeAdaptor indicesShape(getIndices().getType());
3547 if (indicesShape.hasRank()) {
3548 if (failed(tryUpdateDimOrFailure(*this, n, indicesShape.getDimSize(0),
3549 "indices", "batch")))
3550 return failure();
3551 w = indicesShape.getDimSize(1);
3552 }
3553
3554 const ShapeAdaptor outputDataShape(output[0].getType());
3555 if (outputDataShape.hasRank()) {
3556 if (failed(tryUpdateDimOrFailure(*this, n, outputDataShape.getDimSize(0),
3557 "output[0]", "batch")) ||
3558 failed(tryUpdateDimOrFailure(*this, c, outputDataShape.getDimSize(2),
3559 "output[0]", "channels")))
3560 return failure();
3561
3562 if (auto rowCount = getConstantScalarIntValue<int32_t>(getRowCount());
3563 succeeded(rowCount) && rowCount.value() > 0 &&
3564 ShapedType::isStatic(w)) {
3565 const int64_t expectedOutputRows = w * rowCount.value();
3566 if (ShapedType::isStatic(outputDataShape.getDimSize(1)) &&
3567 outputDataShape.getDimSize(1) != expectedOutputRows)
3568 return emitOpError() << "requires output[0] dimension 1 to have size "
3569 << expectedOutputRows << ", got "
3570 << outputDataShape.getDimSize(1);
3571 }
3572 }
3573
3574 if (values.size() == 2) {
3575 const ShapeAdaptor valuesScaleShape(values[1].getType());
3576 if (valuesScaleShape.hasRank()) {
3577 if (failed(tryUpdateDimOrFailure(*this, n, valuesScaleShape.getDimSize(0),
3578 "values[1]", "batch")) ||
3579 failed(tryUpdateDimOrFailure(*this, k, valuesScaleShape.getDimSize(1),
3580 "values[1]", "rows")))
3581 return failure();
3582 multiplesOfC = valuesScaleShape.getDimSize(2);
3583 }
3584
3585 const ShapeAdaptor outputScaleShape(output[1].getType());
3586 if (outputScaleShape.hasRank()) {
3587 if (failed(tryUpdateDimOrFailure(*this, n, outputScaleShape.getDimSize(0),
3588 "output[1]", "batch")))
3589 return failure();
3590
3591 if (auto rowCount = getConstantScalarIntValue<int32_t>(getRowCount());
3592 succeeded(rowCount) && rowCount.value() > 0 &&
3593 ShapedType::isStatic(w)) {
3594 const int64_t expectedOutputRows = w * rowCount.value();
3595 if (ShapedType::isStatic(outputScaleShape.getDimSize(1)) &&
3596 outputScaleShape.getDimSize(1) != expectedOutputRows)
3597 return emitOpError() << "requires output[1] dimension 1 to have size "
3598 << expectedOutputRows << ", got "
3599 << outputScaleShape.getDimSize(1);
3600 }
3601
3602 if (ShapedType::isDynamic(multiplesOfC))
3603 multiplesOfC = outputScaleShape.getDimSize(2);
3604 else if (ShapedType::isStatic(outputScaleShape.getDimSize(2)) &&
3605 multiplesOfC != outputScaleShape.getDimSize(2))
3606 return emitOpError()
3607 << "expected channels of output[1] to match size "
3608 << multiplesOfC << ", got " << outputScaleShape.getDimSize(2);
3609 }
3610
3611 if (ShapedType::isStatic(c) && ShapedType::isStatic(multiplesOfC) &&
3612 multiplesOfC != c / blockSize)
3613 return emitOpError()
3614 << "expects channels of scale tensors to equal C/block_size (" << c
3615 << "/" << blockSize << "), got " << multiplesOfC;
3616 }
3617
3618 return success();
3619}
3620
3621LogicalResult tosa::ResizeOp::inferReturnTypeComponents(
3622 MLIRContext *context, ::std::optional<Location> location,
3623 ResizeOp::Adaptor adaptor,
3624 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3625 llvm::SmallVector<int64_t, 4> outputShape;
3626 outputShape.resize(4, ShapedType::kDynamic);
3627
3628 ShapeAdaptor inputShape(adaptor.getInput().getType());
3629 if (!inputShape.hasRank())
3630 return failure();
3631
3632 outputShape[0] = inputShape.getDimSize(0);
3633 outputShape[3] = inputShape.getDimSize(3);
3634 int64_t inputHeight = inputShape.getDimSize(1);
3635 int64_t inputWidth = inputShape.getDimSize(2);
3636
3637 if ((inputHeight == ShapedType::kDynamic) ||
3638 (inputWidth == ShapedType::kDynamic))
3639 return failure();
3640
3641 SmallVector<int64_t> scaleInt, offsetInt, borderInt;
3642 if (!tosa::getConstShapeValues(adaptor.getScale().getDefiningOp(),
3643 scaleInt) ||
3644 !tosa::getConstShapeValues(adaptor.getOffset().getDefiningOp(),
3645 offsetInt) ||
3646 !tosa::getConstShapeValues(adaptor.getBorder().getDefiningOp(),
3647 borderInt)) {
3648 return failure();
3649 }
3650
3651 // Non-positive scale values are invalid, so the output shape cannot be
3652 // inferred here. They are reported by the ERROR_IF check in tosa-validate.
3653 if (llvm::any_of(scaleInt, [](int64_t s) { return s <= 0; }))
3654 return failure();
3655
3656 // Compute the output shape based on attributes: scale, offset, and border.
3657 const int64_t outputHeight =
3658 (((inputHeight - 1) * scaleInt[0] - offsetInt[0] + borderInt[0]) /
3659 scaleInt[1]) +
3660 1;
3661
3662 const int64_t outputWidth =
3663 (((inputWidth - 1) * scaleInt[2] - offsetInt[1] + borderInt[1]) /
3664 scaleInt[3]) +
3665 1;
3666
3667 if (outputHeight < 0 || outputWidth < 0) {
3668 return emitOptionalError(
3669 location,
3670 "calculated output height and width must be non-negative, "
3671 "got height = ",
3672 outputHeight, ", width = ", outputWidth);
3673 }
3674
3675 outputShape[1] = outputHeight;
3676 outputShape[2] = outputWidth;
3677 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3678 return success();
3679}
3680
3681LogicalResult tosa::ResizeOp::verify() {
3682 const Type inputElementType = getElementTypeOrSelf(getInput().getType());
3683
3684 if (isa<BlockScaledType>(inputElementType) &&
3685 getMode() != ResizeMode::NEAREST_NEIGHBOR)
3686 return emitOpError("requires NEAREST_NEIGHBOR mode for block scaled input");
3687
3688 return success();
3689}
3690
3691LogicalResult tosa::ScatterOp::inferReturnTypeComponents(
3692 MLIRContext *context, ::std::optional<Location> location,
3693 ScatterOp::Adaptor adaptor,
3694 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3695 llvm::SmallVector<int64_t> outputShape;
3696 outputShape.resize(3, ShapedType::kDynamic);
3697
3698 ShapeAdaptor valuesInShape(adaptor.getValuesIn().getType());
3699 if (valuesInShape.hasRank()) {
3700 outputShape[0] = valuesInShape.getDimSize(0);
3701 outputShape[1] = valuesInShape.getDimSize(1);
3702 outputShape[2] = valuesInShape.getDimSize(2);
3703 }
3704
3705 ShapeAdaptor indicesShape(adaptor.getIndices().getType());
3706 if (indicesShape.hasRank()) {
3707 if (outputShape[0] == ShapedType::kDynamic)
3708 outputShape[0] = indicesShape.getDimSize(0);
3709 }
3710
3711 ShapeAdaptor inputShape(adaptor.getInput().getType());
3712 if (inputShape.hasRank()) {
3713 if (outputShape[0] == ShapedType::kDynamic)
3714 outputShape[0] = inputShape.getDimSize(0);
3715 if (outputShape[2] == ShapedType::kDynamic)
3716 outputShape[2] = inputShape.getDimSize(2);
3717 }
3718
3719 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
3720 return success();
3721}
3722
3723LogicalResult tosa::ScatterOp::verify() {
3724 if (verifySameElementTypes(*this, /* inType = */ getValuesIn().getType(),
3725 /* outType = */ getValuesOut().getType())
3726 .failed() ||
3727 verifySameElementTypes(*this, /* inType = */ getInput().getType(),
3728 /* outType = */ getValuesOut().getType())
3729 .failed()) {
3730 return failure();
3731 }
3732
3733 const ShapeAdaptor valuesInShape(getValuesIn().getType());
3734 const ShapeAdaptor indicesShape(getIndices().getType());
3735 const ShapeAdaptor inputShape(getInput().getType());
3736 const ShapeAdaptor outputShape(getValuesOut().getType());
3737
3738 int64_t n = ShapedType::kDynamic;
3739 int64_t k = ShapedType::kDynamic;
3740 int64_t w = ShapedType::kDynamic;
3741 int64_t c = ShapedType::kDynamic;
3742 if (valuesInShape.hasRank()) {
3743 n = valuesInShape.getDimSize(0);
3744 k = valuesInShape.getDimSize(1);
3745 c = valuesInShape.getDimSize(2);
3746 }
3747 if (indicesShape.hasRank()) {
3748 const int64_t indicesN = indicesShape.getDimSize(0);
3749 w = indicesShape.getDimSize(1);
3750 if (n == ShapedType::kDynamic)
3751 n = indicesN;
3752 else if (indicesN != ShapedType::kDynamic && n != indicesN)
3753 return emitOpError() << "requires indices dimension 0 to have size " << n
3754 << ", got " << indicesN;
3755 }
3756 if (inputShape.hasRank()) {
3757 const int64_t inputN = inputShape.getDimSize(0);
3758 const int64_t inputW = inputShape.getDimSize(1);
3759 const int64_t inputC = inputShape.getDimSize(2);
3760 if (n == ShapedType::kDynamic)
3761 n = inputN;
3762 else if (inputN != ShapedType::kDynamic && n != inputN)
3763 return emitOpError() << "requires input dimension 0 to have size " << n
3764 << ", got " << inputN;
3765 if (w == ShapedType::kDynamic)
3766 w = inputW;
3767 else if (inputW != ShapedType::kDynamic && w != inputW)
3768 return emitOpError() << "requires input dimension 1 to have size " << w
3769 << ", got " << inputW;
3770
3771 if (c == ShapedType::kDynamic)
3772 c = inputC;
3773 else if (inputC != ShapedType::kDynamic && c != inputC)
3774 return emitOpError() << "requires input dimension 2 to have size " << c
3775 << ", got " << inputC;
3776 }
3777 if (outputShape.hasRank()) {
3778 const int64_t outputN = outputShape.getDimSize(0);
3779 const int64_t outputK = outputShape.getDimSize(1);
3780 const int64_t outputC = outputShape.getDimSize(2);
3781 if (n != ShapedType::kDynamic && outputN != ShapedType::kDynamic &&
3782 n != outputN)
3783 return emitOpError() << "requires values_out dimension 0 to have size "
3784 << n << ", got " << outputN;
3785 if (k == ShapedType::kDynamic)
3786 k = outputK;
3787 else if (outputK != ShapedType::kDynamic && k != outputK)
3788 return emitOpError() << "requires values_out dimension 1 to have size "
3789 << k << ", got " << outputK;
3790 if (c != ShapedType::kDynamic && outputC != ShapedType::kDynamic &&
3791 c != outputC)
3792 return emitOpError() << "requires values_out dimension 2 to have size "
3793 << c << ", got " << outputC;
3794 }
3795 if (k != ShapedType::kDynamic && w != ShapedType::kDynamic && !(k >= w))
3796 return emitOpError() << "requires dimensions K >= W, got K=" << k
3797 << " and W=" << w;
3798
3799 return success();
3800}
3801
3802static LogicalResult ReduceInferReturnTypes(
3803 ShapeAdaptor operandShape, Type inputType, IntegerAttr axis,
3804 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3805 int64_t axisVal = axis.getValue().getSExtValue();
3806 if (!operandShape.hasRank() || operandShape.getRank() <= axisVal) {
3807 inferredReturnShapes.push_back(ShapedTypeComponents(inputType));
3808 return success();
3809 }
3810
3811 SmallVector<int64_t> outputShape;
3812 operandShape.getDims(outputShape);
3813 outputShape[axisVal] = 1;
3814 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape, inputType));
3815 return success();
3816}
3817
3818#define COMPATIBLE_RETURN_TYPES(OP) \
3819 bool OP::isCompatibleReturnTypes(TypeRange l, TypeRange r) { \
3820 if (l.size() != r.size() || l.size() != 1) \
3821 return false; \
3822 if (getElementTypeOrSelf(l[0]) != getElementTypeOrSelf(r[0])) \
3823 return false; \
3824 return succeeded(verifyCompatibleShape(l[0], r[0])); \
3825 }
3826
3827#define REDUCE_SHAPE_INFER(OP) \
3828 LogicalResult OP::inferReturnTypeComponents( \
3829 MLIRContext *context, ::std::optional<Location> location, \
3830 OP::Adaptor adaptor, \
3831 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) { \
3832 Type inputType = \
3833 llvm::cast<TensorType>(adaptor.getInput().getType()).getElementType(); \
3834 ShapeAdaptor inputShape(adaptor.getInput().getType()); \
3835 const Properties &prop = adaptor.getProperties(); \
3836 return ReduceInferReturnTypes(inputShape, inputType, prop.axis, \
3837 inferredReturnShapes); \
3838 } \
3839 COMPATIBLE_RETURN_TYPES(OP)
3840
3841REDUCE_SHAPE_INFER(tosa::ReduceAllOp)
3842REDUCE_SHAPE_INFER(tosa::ReduceAnyOp)
3843REDUCE_SHAPE_INFER(tosa::ReduceMaxOp)
3844REDUCE_SHAPE_INFER(tosa::ReduceMinOp)
3845REDUCE_SHAPE_INFER(tosa::ReduceProductOp)
3846REDUCE_SHAPE_INFER(tosa::ReduceSumOp)
3847#undef REDUCE_SHAPE_INFER
3848COMPATIBLE_RETURN_TYPES(tosa::ConcatOp)
3849#undef COMPATIBLE_RETURN_TYPES
3850
3851template <typename T>
3852static LogicalResult verifyReduceOp(T op) {
3853 // All TOSA reduce Ops have input, output and axis.
3854 TensorType inputType = op.getInput().getType();
3855 TensorType outputType = op.getOutput().getType();
3856 int32_t reduceAxis = op.getAxis();
3857
3858 if (reduceAxis < 0) {
3859 op.emitOpError("reduce axis must not be negative");
3860 return failure();
3861 }
3862 if (inputType.hasRank()) {
3863 int64_t inputRank = inputType.getRank();
3864 // We allow for a special case where the input/output shape has rank 0 and
3865 // axis is also 0.
3866 if (reduceAxis >= inputRank && (reduceAxis != 0 || inputRank != 0)) {
3867 op.emitOpError("expect input tensor rank (")
3868 << inputRank << ") to be larger than reduce axis (" << reduceAxis
3869 << ")";
3870 return failure();
3871 }
3872 }
3873 if (outputType.hasRank()) {
3874 int64_t outputRank = outputType.getRank();
3875 if (inputType.hasRank() && outputRank != inputType.getRank()) {
3876 op.emitOpError(
3877 "expect output tensor rank to be equal to input tensor rank");
3878 return failure();
3879 }
3880 if (reduceAxis >= outputRank && (reduceAxis != 0 || outputRank != 0)) {
3881 op.emitOpError("expect output tensor rank (")
3882 << outputRank << ") to be larger than reduce axis (" << reduceAxis
3883 << ")";
3884 return failure();
3885 }
3886 // We can only verify the reduced dimension size to be 1 if this is not
3887 // the special case of output rank == 0.
3888 if (outputRank != 0) {
3889 auto outputShape = outputType.getShape();
3890 if (!outputType.isDynamicDim(reduceAxis) &&
3891 outputShape[reduceAxis] != 1) {
3892 op.emitOpError("expect reduced dimension size to be 1, got ")
3893 << outputShape[reduceAxis];
3894 return failure();
3895 }
3896 }
3897 }
3898 return success();
3899}
3900
3901LogicalResult tosa::ReduceAllOp::verify() { return verifyReduceOp(*this); }
3902LogicalResult tosa::ReduceAnyOp::verify() { return verifyReduceOp(*this); }
3903LogicalResult tosa::ReduceMaxOp::verify() { return verifyReduceOp(*this); }
3904LogicalResult tosa::ReduceMinOp::verify() { return verifyReduceOp(*this); }
3905LogicalResult tosa::ReduceProductOp::verify() { return verifyReduceOp(*this); }
3906LogicalResult tosa::ReduceSumOp::verify() { return verifyReduceOp(*this); }
3907
3908static LogicalResult NAryInferReturnTypes(
3909 const ValueShapeRange &operands,
3910 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3912 if (resolveBroadcastShape(operands, outShape).failed()) {
3913 inferredReturnShapes.push_back(ShapedTypeComponents());
3914 } else {
3915 inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
3916 }
3917 return success();
3918}
3919
3920#define NARY_SHAPE_INFER(OP) \
3921 LogicalResult OP::inferReturnTypeComponents( \
3922 MLIRContext *context, ::std::optional<Location> location, \
3923 ValueShapeRange operands, DictionaryAttr attributes, \
3924 PropertyRef properties, RegionRange regions, \
3925 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) { \
3926 return NAryInferReturnTypes(operands, inferredReturnShapes); \
3927 }
3928
3929NARY_SHAPE_INFER(tosa::AbsOp)
3930NARY_SHAPE_INFER(tosa::AddOp)
3931NARY_SHAPE_INFER(tosa::ArithmeticRightShiftOp)
3932NARY_SHAPE_INFER(tosa::BitwiseAndOp)
3933NARY_SHAPE_INFER(tosa::BitwiseOrOp)
3934NARY_SHAPE_INFER(tosa::BitwiseXorOp)
3935NARY_SHAPE_INFER(tosa::BitwiseNotOp)
3936NARY_SHAPE_INFER(tosa::CastOp)
3937NARY_SHAPE_INFER(tosa::CeilOp)
3938NARY_SHAPE_INFER(tosa::ClampOp)
3939NARY_SHAPE_INFER(tosa::ClzOp)
3940NARY_SHAPE_INFER(tosa::CosOp)
3941NARY_SHAPE_INFER(tosa::ExpOp)
3942NARY_SHAPE_INFER(tosa::FloorOp)
3943NARY_SHAPE_INFER(tosa::GreaterEqualOp)
3944NARY_SHAPE_INFER(tosa::GreaterOp)
3945NARY_SHAPE_INFER(tosa::IdentityOp)
3946NARY_SHAPE_INFER(tosa::IntDivOp)
3947NARY_SHAPE_INFER(tosa::LogOp)
3948NARY_SHAPE_INFER(tosa::LogicalAndOp)
3949NARY_SHAPE_INFER(tosa::LogicalLeftShiftOp)
3950NARY_SHAPE_INFER(tosa::LogicalNotOp)
3951NARY_SHAPE_INFER(tosa::LogicalOrOp)
3952NARY_SHAPE_INFER(tosa::LogicalRightShiftOp)
3953NARY_SHAPE_INFER(tosa::LogicalXorOp)
3954NARY_SHAPE_INFER(tosa::MaximumOp)
3955NARY_SHAPE_INFER(tosa::MinimumOp)
3956NARY_SHAPE_INFER(tosa::PowOp)
3957NARY_SHAPE_INFER(tosa::ReciprocalOp)
3958NARY_SHAPE_INFER(tosa::ReverseOp)
3959NARY_SHAPE_INFER(tosa::RsqrtOp)
3960NARY_SHAPE_INFER(tosa::SinOp)
3961NARY_SHAPE_INFER(tosa::SelectOp)
3962NARY_SHAPE_INFER(tosa::SubOp)
3963NARY_SHAPE_INFER(tosa::TanhOp)
3964NARY_SHAPE_INFER(tosa::ErfOp)
3965NARY_SHAPE_INFER(tosa::SigmoidOp)
3966#undef PRED_SHAPE_INFER
3967
3968LogicalResult tosa::NegateOp::inferReturnTypeComponents(
3969 MLIRContext *context, ::std::optional<Location> location,
3970 NegateOp::Adaptor adaptor,
3971 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
3972 ShapeAdaptor inputShape(adaptor.getInput1().getType());
3973 inferredReturnShapes.push_back(ShapedTypeComponents(inputShape));
3974 return success();
3975}
3976
3977LogicalResult tosa::NegateOp::verify() {
3978 // Verify same element type
3979 const Type input1Type = getInput1().getType();
3980 const Type outputType = getOutput().getType();
3981 if (verifySameElementTypes(*this, input1Type, outputType).failed())
3982 return failure();
3983
3984 // Verify same shape
3985 const SmallVector<Type, 2> types = {input1Type, outputType};
3986 if (failed(verifyCompatibleShapes(types)))
3987 return emitOpError() << "requires the same shape for input1 and output";
3988
3989 const Type input1EType = getStorageElementTypeOrSelf(getInput1().getType());
3990 const Type input1ZpEType =
3991 getStorageElementTypeOrSelf(getInput1Zp().getType());
3992 if (input1EType != input1ZpEType) {
3993 return emitOpError("expect both input1 and its zero point are the same "
3994 "element type, got ")
3995 << input1EType << " and " << input1ZpEType;
3996 }
3997 const Type outputEType = getStorageElementTypeOrSelf(getOutput().getType());
3998 const Type outputZpEType =
3999 getStorageElementTypeOrSelf(getOutputZp().getType());
4000 if (outputEType != outputZpEType) {
4001 return emitOpError("expect both output and its zero point are the same "
4002 "element type, got ")
4003 << outputEType << " and " << outputZpEType;
4004 }
4005
4006 FailureOr<int64_t> maybeIZp = getInput1ZeroPoint();
4007 if (succeeded(maybeIZp) && verifyInput1ZeroPoint(*maybeIZp).failed())
4008 return failure();
4009
4010 FailureOr<int64_t> maybeOZp = getOutputZeroPoint();
4011 if (succeeded(maybeOZp) && verifyOutputZeroPoint(*maybeOZp).failed())
4012 return failure();
4013
4014 return success();
4015}
4016
4017static LogicalResult poolingInferReturnTypes(
4018 ShapeAdaptor inputShape, ArrayRef<int64_t> kernel, ArrayRef<int64_t> stride,
4020 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4021 llvm::SmallVector<int64_t> outputShape;
4022 outputShape.resize(4, ShapedType::kDynamic);
4023
4024 // We only know the rank if the input type is unranked.
4025 if (!inputShape.hasRank()) {
4026 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4027 return success();
4028 }
4029
4030 // Batch and number of channels are identical for pooling layer.
4031 outputShape[0] = inputShape.getDimSize(0);
4032 outputShape[3] = inputShape.getDimSize(3);
4033
4034 int64_t height = inputShape.getDimSize(1);
4035 int64_t width = inputShape.getDimSize(2);
4036
4037 if (ShapedType::isStatic(height)) {
4038 int64_t padded = height + pad[0] + pad[1] - kernel[0];
4039 outputShape[1] = padded / stride[0] + 1;
4040 }
4041
4042 if (ShapedType::isStatic(width)) {
4043 int64_t padded = width + pad[2] + pad[3] - kernel[1];
4044 outputShape[2] = padded / stride[1] + 1;
4045 }
4046
4047 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4048 return success();
4049}
4050
4051template <typename AdaptorT>
4053
4055protected:
4056 static void updateIfDynamic(int64_t &current, int64_t candidate) {
4057 if (ShapedType::isDynamic(current))
4058 current = candidate;
4059 }
4060};
4061
4062template <>
4063class ConvInferShapeAdaptor<Conv2DOp::Adaptor>
4064 : public ConvInferShapeAdaptorBase {
4065public:
4066 explicit ConvInferShapeAdaptor(Conv2DOp::Adaptor adaptor)
4067 : adaptor(adaptor) {}
4068
4070 SmallVectorImpl<int64_t> &inputSpatial) {
4071 const ShapeAdaptor inputShape(adaptor.getInput().getType());
4072 if (!inputShape.hasRank())
4073 return;
4074
4075 const int64_t outputBatch = inputShape.getDimSize(0);
4076 const int64_t inputHeight = inputShape.getDimSize(1);
4077 const int64_t inputWidth = inputShape.getDimSize(2);
4078
4079 outputShape[0] = outputBatch;
4080 inputSpatial[0] = inputHeight;
4081 inputSpatial[1] = inputWidth;
4082 }
4083
4085 SmallVectorImpl<int64_t> &weightSpatial) {
4086 const ShapeAdaptor weightShape(adaptor.getWeight().getType());
4087 if (!weightShape.hasRank())
4088 return;
4089
4090 const int64_t outputChannels = weightShape.getDimSize(0);
4091 const int64_t kernelHeight = weightShape.getDimSize(1);
4092 const int64_t kernelWidth = weightShape.getDimSize(2);
4093
4094 outputShape[3] = outputChannels;
4095 weightSpatial[0] = kernelHeight;
4096 weightSpatial[1] = kernelWidth;
4097 }
4098
4099 int64_t getNumSpatialDims() const { return 2; }
4100 int64_t getOutputRank() const { return 4; }
4101
4103 SmallVector<int64_t> &strideValues,
4104 SmallVector<int64_t> &dilationValues) {
4105 padValues.assign(adaptor.getPad().begin(), adaptor.getPad().end());
4106 strideValues.assign(adaptor.getStride().begin(), adaptor.getStride().end());
4107 dilationValues.assign(adaptor.getDilation().begin(),
4108 adaptor.getDilation().end());
4109 return success();
4110 }
4111
4112private:
4113 Conv2DOp::Adaptor adaptor;
4114};
4115
4116template <>
4117class ConvInferShapeAdaptor<Conv2DBlockScaledOp::Adaptor>
4118 : public ConvInferShapeAdaptorBase {
4119public:
4120 explicit ConvInferShapeAdaptor(Conv2DBlockScaledOp::Adaptor adaptor)
4121 : adaptor(adaptor) {}
4122
4124 SmallVectorImpl<int64_t> &inputSpatial) {
4125 const ShapeAdaptor inputDataShape(adaptor.getInputData().getType());
4126 if (inputDataShape.hasRank()) {
4127 const int64_t outputBatch = inputDataShape.getDimSize(0);
4128 const int64_t inputHeight = inputDataShape.getDimSize(1);
4129 const int64_t inputWidth = inputDataShape.getDimSize(2);
4130
4131 outputShape[0] = outputBatch;
4132 inputSpatial[0] = inputHeight;
4133 inputSpatial[1] = inputWidth;
4134 }
4135
4136 const ShapeAdaptor inputScaleShape(adaptor.getInputScale().getType());
4137 if (!inputScaleShape.hasRank())
4138 return;
4139
4140 const int64_t scaleBatch = inputScaleShape.getDimSize(0);
4141 const int64_t scaleHeight = inputScaleShape.getDimSize(1);
4142 const int64_t scaleWidth = inputScaleShape.getDimSize(2);
4143
4144 updateIfDynamic(outputShape[0], scaleBatch);
4145 updateIfDynamic(inputSpatial[0], scaleHeight);
4146 updateIfDynamic(inputSpatial[1], scaleWidth);
4147 }
4148
4150 SmallVectorImpl<int64_t> &weightSpatial) {
4151 const ShapeAdaptor weightDataShape(adaptor.getWeightData().getType());
4152 if (weightDataShape.hasRank()) {
4153 const int64_t outputChannels = weightDataShape.getDimSize(0);
4154 const int64_t kernelHeight = weightDataShape.getDimSize(1);
4155 const int64_t kernelWidth = weightDataShape.getDimSize(2);
4156
4157 outputShape[3] = outputChannels;
4158 weightSpatial[0] = kernelHeight;
4159 weightSpatial[1] = kernelWidth;
4160 }
4161
4162 const ShapeAdaptor weightScaleShape(adaptor.getWeightScale().getType());
4163 if (!weightScaleShape.hasRank())
4164 return;
4165
4166 const int64_t scaleOutputChannels = weightScaleShape.getDimSize(0);
4167 const int64_t scaleKernelHeight = weightScaleShape.getDimSize(1);
4168 const int64_t scaleKernelWidth = weightScaleShape.getDimSize(2);
4169
4170 updateIfDynamic(outputShape[3], scaleOutputChannels);
4171 updateIfDynamic(weightSpatial[0], scaleKernelHeight);
4172 updateIfDynamic(weightSpatial[1], scaleKernelWidth);
4173 }
4174
4175 int64_t getNumSpatialDims() const { return 2; }
4176 int64_t getOutputRank() const { return 4; }
4177
4179 SmallVector<int64_t> &strideValues,
4180 SmallVector<int64_t> &dilationValues) {
4181 if (!tosa::getConstShapeValues(adaptor.getPad().getDefiningOp(),
4182 padValues) ||
4183 !tosa::getConstShapeValues(adaptor.getStride().getDefiningOp(),
4184 strideValues) ||
4185 !tosa::getConstShapeValues(adaptor.getDilation().getDefiningOp(),
4186 dilationValues))
4187 return failure();
4188 return success();
4189 }
4190
4191private:
4192 Conv2DBlockScaledOp::Adaptor adaptor;
4193};
4194
4195template <>
4196class ConvInferShapeAdaptor<Conv3DOp::Adaptor>
4197 : public ConvInferShapeAdaptorBase {
4198public:
4199 explicit ConvInferShapeAdaptor(Conv3DOp::Adaptor adaptor)
4200 : adaptor(adaptor) {}
4201
4203 SmallVectorImpl<int64_t> &inputSpatial) {
4204 const ShapeAdaptor inputShape(adaptor.getInput().getType());
4205 if (!inputShape.hasRank())
4206 return;
4207
4208 const int64_t outputBatch = inputShape.getDimSize(0);
4209 const int64_t inputDepth = inputShape.getDimSize(1);
4210 const int64_t inputHeight = inputShape.getDimSize(2);
4211 const int64_t inputWidth = inputShape.getDimSize(3);
4212
4213 outputShape[0] = outputBatch;
4214 inputSpatial[0] = inputDepth;
4215 inputSpatial[1] = inputHeight;
4216 inputSpatial[2] = inputWidth;
4217 }
4218
4220 SmallVectorImpl<int64_t> &weightSpatial) {
4221 const ShapeAdaptor weightShape(adaptor.getWeight().getType());
4222 if (!weightShape.hasRank())
4223 return;
4224
4225 const int64_t outputChannels = weightShape.getDimSize(0);
4226 const int64_t kernelDepth = weightShape.getDimSize(1);
4227 const int64_t kernelHeight = weightShape.getDimSize(2);
4228 const int64_t kernelWidth = weightShape.getDimSize(3);
4229
4230 outputShape[4] = outputChannels;
4231 weightSpatial[0] = kernelDepth;
4232 weightSpatial[1] = kernelHeight;
4233 weightSpatial[2] = kernelWidth;
4234 }
4235
4236 int64_t getNumSpatialDims() const { return 3; }
4237 int64_t getOutputRank() const { return 5; }
4238
4240 SmallVector<int64_t> &strideValues,
4241 SmallVector<int64_t> &dilationValues) {
4242 padValues.assign(adaptor.getPad().begin(), adaptor.getPad().end());
4243 strideValues.assign(adaptor.getStride().begin(), adaptor.getStride().end());
4244 dilationValues.assign(adaptor.getDilation().begin(),
4245 adaptor.getDilation().end());
4246 return success();
4247 }
4248
4249private:
4250 Conv3DOp::Adaptor adaptor;
4251};
4252
4253template <typename AdaptorT>
4255 AdaptorT adaptor,
4256 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4257 ConvInferShapeAdaptor<AdaptorT> convShapeAdaptor(adaptor);
4258 llvm::SmallVector<int64_t> outputShape(convShapeAdaptor.getOutputRank(),
4259 ShapedType::kDynamic);
4260 llvm::SmallVector<int64_t> inputSpatial(convShapeAdaptor.getNumSpatialDims(),
4261 ShapedType::kDynamic);
4262 llvm::SmallVector<int64_t> weightSpatial(convShapeAdaptor.getNumSpatialDims(),
4263 ShapedType::kDynamic);
4264
4265 convShapeAdaptor.inferInputShape(outputShape, inputSpatial);
4266 convShapeAdaptor.inferWeightShape(outputShape, weightSpatial);
4267
4268 const ShapeAdaptor biasShape = adaptor.getBias().getType();
4269 if (biasShape.hasRank()) {
4270 const int64_t biasSize = biasShape.getDimSize(0);
4271 if (biasSize != 1) {
4272 const size_t outputChannelDim = convShapeAdaptor.getOutputRank() - 1;
4273 outputShape[outputChannelDim] =
4274 ShapedType::isDynamic(outputShape[outputChannelDim])
4275 ? biasSize
4276 : outputShape[outputChannelDim];
4277 }
4278 }
4279
4280 SmallVector<int64_t> padValues;
4281 SmallVector<int64_t> strideValues;
4282 SmallVector<int64_t> dilationValues;
4283 if (failed(convShapeAdaptor.getSpatialParameters(padValues, strideValues,
4284 dilationValues))) {
4285 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4286 return success();
4287 }
4288
4289 for (int64_t dim = 0; dim < convShapeAdaptor.getNumSpatialDims(); ++dim) {
4290 if (!ShapedType::isStatic(inputSpatial[dim]) ||
4291 !ShapedType::isStatic(weightSpatial[dim]))
4292 continue;
4293 const int64_t inputSize =
4294 inputSpatial[dim] + padValues[2 * dim] + padValues[2 * dim + 1];
4295 const int64_t filterSize =
4296 (weightSpatial[dim] - 1) * dilationValues[dim] + 1;
4297 const int64_t unstridedResult = inputSize - filterSize + 1;
4298 outputShape[dim + 1] = (unstridedResult - 1) / strideValues[dim] + 1;
4299 }
4300
4301 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4302 return success();
4303}
4304
4305LogicalResult Conv2DOp::inferReturnTypeComponents(
4306 MLIRContext *context, ::std::optional<Location> location,
4307 Conv2DOp::Adaptor adaptor,
4308 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4309 return inferConvReturnTypeComponents(adaptor, inferredReturnShapes);
4310}
4311
4312LogicalResult Conv2DOp::verify() {
4313 if (verifyConvOp(*this).failed() || verifyConvOpErrorIf(*this).failed())
4314 return failure();
4315 return success();
4316}
4317
4318LogicalResult Conv2DBlockScaledOp::inferReturnTypeComponents(
4319 MLIRContext *context, ::std::optional<Location> location,
4320 Conv2DBlockScaledOp::Adaptor adaptor,
4321 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4322 return inferConvReturnTypeComponents(adaptor, inferredReturnShapes);
4323}
4324
4325LogicalResult Conv2DBlockScaledOp::verify() {
4326 if (failed(verifySameElementTypes(*this, getInputData().getType(),
4327 getWeightData().getType(), "input_data",
4328 "weight_data")) ||
4329 failed(verifySameElementTypes(*this, getInputScale().getType(),
4330 getWeightScale().getType(), "input_scale",
4331 "weight_scale")) ||
4332 failed(verifySameElementTypes(*this, getBias().getType(),
4333 getOutput().getType(), "bias", "output")))
4334 return failure();
4335
4336 // Verify input shape compatibility
4337 int64_t N = ShapedType::kDynamic;
4338 int64_t IH = ShapedType::kDynamic;
4339 int64_t IW = ShapedType::kDynamic;
4340 int64_t IC = ShapedType::kDynamic;
4341 int64_t multiplesOfIC = ShapedType::kDynamic;
4342 int64_t OC = ShapedType::kDynamic;
4343 int64_t KH = ShapedType::kDynamic;
4344 int64_t KW = ShapedType::kDynamic;
4345
4346 const ShapeAdaptor inputDataShape(getInputData().getType());
4347 if (inputDataShape.hasRank()) {
4348 N = inputDataShape.getDimSize(0);
4349 IH = inputDataShape.getDimSize(1);
4350 IW = inputDataShape.getDimSize(2);
4351 IC = inputDataShape.getDimSize(3);
4352 }
4353
4354 const ShapeAdaptor inputScaleShape(getInputScale().getType());
4355 if (inputScaleShape.hasRank()) {
4356 if (failed(tryUpdateDimOrFailure(*this, N, inputScaleShape.getDimSize(0),
4357 "input_scale", "batch size")) ||
4358 failed(tryUpdateDimOrFailure(*this, IH, inputScaleShape.getDimSize(1),
4359 "input_scale", "input height")) ||
4360 failed(tryUpdateDimOrFailure(*this, IW, inputScaleShape.getDimSize(2),
4361 "input_scale", "input width")))
4362 return failure();
4363 multiplesOfIC = inputScaleShape.getDimSize(3);
4364 }
4365
4366 const ShapeAdaptor weightDataShape(getWeightData().getType());
4367 if (weightDataShape.hasRank()) {
4368 OC = weightDataShape.getDimSize(0);
4369 KH = weightDataShape.getDimSize(1);
4370 KW = weightDataShape.getDimSize(2);
4371 if (failed(tryUpdateDimOrFailure(*this, IC, weightDataShape.getDimSize(3),
4372 "weight_data", "input channels")))
4373 return failure();
4374 }
4375
4376 const ShapeAdaptor weightScaleShape(getWeightScale().getType());
4377 if (weightScaleShape.hasRank()) {
4378 if (failed(tryUpdateDimOrFailure(*this, OC, weightScaleShape.getDimSize(0),
4379 "weight_scale", "output channels")) ||
4380 failed(tryUpdateDimOrFailure(*this, KH, weightScaleShape.getDimSize(1),
4381 "weight_scale", "kernel height")) ||
4382 failed(tryUpdateDimOrFailure(*this, KW, weightScaleShape.getDimSize(2),
4383 "weight_scale", "kernel width")) ||
4384 failed(tryUpdateDimOrFailure(*this, multiplesOfIC,
4385 weightScaleShape.getDimSize(3),
4386 "weight_scale", "input channel blocks")))
4387 return failure();
4388 }
4389
4390 const uint32_t blockSize = BlockSizeAttr::getBlockSizeValue(getBlockSize());
4391 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
4392 return emitOpError("expect block size to be 32, got ") << blockSize;
4393 // Verify IC is a multiple of block size
4394 if (ShapedType::isStatic(IC) && IC % blockSize != 0)
4395 return emitOpError("expect IC to be a multiple of block size, got IC=")
4396 << IC << ", block_size=" << blockSize;
4397
4398 // Verify multiplesOfIC is IC / block size
4399 if (ShapedType::isStatic(IC) && ShapedType::isStatic(multiplesOfIC) &&
4400 multiplesOfIC != IC / blockSize)
4401 return emitOpError(
4402 "expect scale operands dimension 2 to equal IC/block_size (")
4403 << IC << "/" << blockSize << ")"
4404 << ", got " << multiplesOfIC;
4405
4406 // Verify pad/stride/dilation values
4407 SmallVector<int64_t> padValues;
4408 if (tosa::getConstShapeValues(getPad().getDefiningOp(), padValues)) {
4409 if (llvm::any_of(padValues, [](int64_t p) { return p < 0; }))
4410 return emitOpError("expect all padding values to be >= 0, got ")
4411 << padValues;
4412 }
4413
4414 SmallVector<int64_t> strideValues;
4415 if (tosa::getConstShapeValues(getStride().getDefiningOp(), strideValues)) {
4416 if (llvm::any_of(strideValues, [](int64_t s) { return s < 1; }))
4417 return emitOpError("expect all stride values to be >= 1, got ")
4418 << strideValues;
4419 }
4420
4421 SmallVector<int64_t> dilationValues;
4422 if (tosa::getConstShapeValues(getDilation().getDefiningOp(),
4423 dilationValues)) {
4424 if (llvm::any_of(dilationValues, [](int64_t d) { return d < 1; }))
4425 return emitOpError("expect all dilation values to be >= 1, got ")
4426 << dilationValues;
4427 }
4428
4429 // Verify output shape compatibility
4430 const ShapeAdaptor outputShape(getOutput().getType());
4431 if (!padValues.empty() && !strideValues.empty() && !dilationValues.empty() &&
4432 outputShape.hasRank()) {
4433 if (failed(verifyConvOutputSize(*this, IH, KH, outputShape.getDimSize(1),
4434 padValues[0], padValues[1], strideValues[0],
4435 dilationValues[0], "height", "y", "top",
4436 "bottom")) ||
4437 failed(verifyConvOutputSize(*this, IW, KW, outputShape.getDimSize(2),
4438 padValues[2], padValues[3], strideValues[1],
4439 dilationValues[1], "width", "x", "left",
4440 "right")))
4441 return failure();
4442 }
4443
4444 // Verify bias
4445 const ShapeAdaptor biasShape(getBias().getType());
4446 if (biasShape.hasRank() && outputShape.hasRank()) {
4447 const int64_t biasChannels = biasShape.getDimSize(0);
4448 const int64_t outputChannels =
4449 outputShape.getDimSize(outputShape.getRank() - 1);
4450 if (biasChannels == ShapedType::kDynamic ||
4451 outputChannels == ShapedType::kDynamic)
4452 // Skip following checks if biasChannels or outputChannels is dynamic dim
4453 return success();
4454
4455 if (biasChannels != outputChannels && biasChannels != 1)
4456 return emitOpError(
4457 "bias channels expected to be equal to output channels (")
4458 << outputChannels << ") or 1, got " << biasChannels;
4459 }
4460
4461 return success();
4462}
4463
4464LogicalResult Conv3DOp::inferReturnTypeComponents(
4465 MLIRContext *context, ::std::optional<Location> location,
4466 Conv3DOp::Adaptor adaptor,
4467 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4468 return inferConvReturnTypeComponents(adaptor, inferredReturnShapes);
4469}
4470
4471LogicalResult Conv3DOp::verify() {
4472 if (verifyConvOp(*this).failed() || verifyConvOpErrorIf(*this).failed())
4473 return failure();
4474 return success();
4475}
4476
4477LogicalResult AvgPool2dOp::inferReturnTypeComponents(
4478 MLIRContext *context, ::std::optional<Location> location,
4479 AvgPool2dOp::Adaptor adaptor,
4480 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4481 ShapeAdaptor inputShape(adaptor.getInput().getType());
4482 const Properties &prop = adaptor.getProperties();
4483 return poolingInferReturnTypes(inputShape, prop.kernel, prop.stride, prop.pad,
4484 inferredReturnShapes);
4485}
4486
4487LogicalResult AvgPool2dAdaptiveOp::inferReturnTypeComponents(
4488 MLIRContext *context, ::std::optional<Location> location,
4489 AvgPool2dAdaptiveOp::Adaptor adaptor,
4490 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4491 ShapeAdaptor inputShape(adaptor.getInput().getType());
4492
4493 llvm::SmallVector<int64_t> kernelValues;
4494 llvm::SmallVector<int64_t> strideValues;
4495 llvm::SmallVector<int64_t> padValues;
4496 if (tosa::getConstShapeValues(adaptor.getKernel().getDefiningOp(),
4497 kernelValues) &&
4498 tosa::getConstShapeValues(adaptor.getStride().getDefiningOp(),
4499 strideValues) &&
4500 tosa::getConstShapeValues(adaptor.getPad().getDefiningOp(), padValues)) {
4501 return poolingInferReturnTypes(inputShape, kernelValues, strideValues,
4502 padValues, inferredReturnShapes);
4503 }
4504
4505 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4506 if (inputShape.hasRank()) {
4507 // Keep N & C as pooling only changes H & W.
4508 outputShape[0] = inputShape.getDimSize(0);
4509 outputShape[3] = inputShape.getDimSize(3);
4510 }
4511
4512 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4513 return success();
4514}
4515
4516LogicalResult MaxPool2dOp::inferReturnTypeComponents(
4517 MLIRContext *context, ::std::optional<Location> location,
4518 MaxPool2dOp::Adaptor adaptor,
4519 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4520 ShapeAdaptor inputShape(adaptor.getInput().getType());
4521 const Properties &prop = adaptor.getProperties();
4522 return poolingInferReturnTypes(inputShape, prop.kernel, prop.stride, prop.pad,
4523 inferredReturnShapes);
4524}
4525
4526LogicalResult MaxPool2dAdaptiveOp::inferReturnTypeComponents(
4527 MLIRContext *context, ::std::optional<Location> location,
4528 MaxPool2dAdaptiveOp::Adaptor adaptor,
4529 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4530 ShapeAdaptor inputShape(adaptor.getInput().getType());
4531
4532 llvm::SmallVector<int64_t> kernelValues;
4533 llvm::SmallVector<int64_t> strideValues;
4534 llvm::SmallVector<int64_t> padValues;
4535 if (tosa::getConstShapeValues(adaptor.getKernel().getDefiningOp(),
4536 kernelValues) &&
4537 tosa::getConstShapeValues(adaptor.getStride().getDefiningOp(),
4538 strideValues) &&
4539 tosa::getConstShapeValues(adaptor.getPad().getDefiningOp(), padValues)) {
4540 return poolingInferReturnTypes(inputShape, kernelValues, strideValues,
4541 padValues, inferredReturnShapes);
4542 }
4543
4544 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4545 if (inputShape.hasRank()) {
4546 outputShape[0] = inputShape.getDimSize(0);
4547 outputShape[3] = inputShape.getDimSize(3);
4548 }
4549 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4550 return success();
4551}
4552
4553LogicalResult MaxPool2dOp::verify() {
4554 if (failed(verifySameElementTypes(*this, /* intype = */ getInput().getType(),
4555 /* outType = */ getOutput().getType())))
4556 return failure();
4557
4558 if (failed(verifyPoolingOp(*this)))
4559 return failure();
4560
4561 return success();
4562}
4563
4564LogicalResult MaxPool2dAdaptiveOp::verify() {
4565 if (failed(verifySameElementTypes(*this, /* intype = */ getInput().getType(),
4566 /* outType = */ getOutput().getType())))
4567 return failure();
4568
4569 AdaptivePoolingConstShapeValues values;
4571
4572 if (failed(verifyPoolingOpImpl(getOperation(), values.kernel, values.stride,
4573 values.pad, getInput(), getOutput())))
4574 return failure();
4575
4576 return success();
4577}
4578
4579LogicalResult DepthwiseConv2DOp::inferReturnTypeComponents(
4580 MLIRContext *context, ::std::optional<Location> location,
4581 DepthwiseConv2DOp::Adaptor adaptor,
4582 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4583 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4584
4585 int64_t inputWidth = ShapedType::kDynamic;
4586 int64_t inputHeight = ShapedType::kDynamic;
4587 int64_t inputChannels = ShapedType::kDynamic;
4588
4589 int64_t weightWidth = ShapedType::kDynamic;
4590 int64_t weightHeight = ShapedType::kDynamic;
4591 int64_t depthChannels = ShapedType::kDynamic;
4592
4593 // Input shape describes input width/height and batch.
4594 ShapeAdaptor inputShape(adaptor.getInput().getType());
4595 if (inputShape.hasRank()) {
4596 outputShape[0] = inputShape.getDimSize(0);
4597 inputHeight = inputShape.getDimSize(1);
4598 inputWidth = inputShape.getDimSize(2);
4599 inputChannels = inputShape.getDimSize(3);
4600 }
4601
4602 // Weight shapes describes the filter width/height and the output channels.
4603 ShapeAdaptor weightShape(adaptor.getWeight().getType());
4604 if (weightShape.hasRank()) {
4605 weightHeight = weightShape.getDimSize(0);
4606 weightWidth = weightShape.getDimSize(1);
4607 inputChannels = ShapedType::isDynamic(inputChannels)
4608 ? weightShape.getDimSize(2)
4609 : inputChannels;
4610 depthChannels = weightShape.getDimSize(3);
4611 }
4612
4613 // If both inputChannels and depthChannels are available we can determine
4614 // the output channels.
4615 if (ShapedType::isStatic(inputChannels) &&
4616 ShapedType::isStatic(depthChannels)) {
4617 outputShape[3] = inputChannels * depthChannels;
4618 }
4619
4620 // Bias shape can describe the output channels.
4621 ShapeAdaptor biasShape(adaptor.getBias().getType());
4622 if (biasShape.hasRank() && ShapedType::isDynamic(outputShape[3])) {
4623 int64_t bc = biasShape.getDimSize(0);
4624 if (bc != ShapedType::kDynamic && bc != 1)
4625 outputShape[3] = bc;
4626 }
4627
4628 llvm::ArrayRef<int64_t> dilation = adaptor.getDilation();
4629 llvm::ArrayRef<int64_t> padding = adaptor.getPad();
4630 llvm::ArrayRef<int64_t> stride = adaptor.getStride();
4631
4632 if (ShapedType::isStatic(inputHeight) && ShapedType::isStatic(weightHeight)) {
4633 int64_t inputSize = inputHeight + padding[0] + padding[1];
4634 int64_t filterSize = (weightHeight - 1) * dilation[0] + 1;
4635 int64_t unstridedResult = inputSize - filterSize + 1;
4636 outputShape[1] = (unstridedResult - 1) / stride[0] + 1;
4637 }
4638
4639 if (ShapedType::isStatic(inputWidth) && ShapedType::isStatic(weightWidth)) {
4640 int64_t inputSize = inputWidth + padding[2] + padding[3];
4641 int64_t filterSize = (weightWidth - 1) * dilation[1] + 1;
4642 int64_t unstridedResult = inputSize - filterSize + 1;
4643 outputShape[2] = (unstridedResult - 1) / stride[1] + 1;
4644 }
4645
4646 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4647 return success();
4648}
4649
4650LogicalResult DepthwiseConv2DOp::verify() {
4651 if (verifyConvOp(*this).failed() || verifyConvOpErrorIf(*this).failed())
4652 return failure();
4653 return success();
4654}
4655
4656LogicalResult TransposeConv2DOp::inferReturnTypeComponents(
4657 MLIRContext *context, ::std::optional<Location> location,
4658 TransposeConv2DOp::Adaptor adaptor,
4659 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4660 llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamic);
4661
4662 int64_t inputWidth = ShapedType::kDynamic;
4663 int64_t inputHeight = ShapedType::kDynamic;
4664 int64_t weightWidth = ShapedType::kDynamic;
4665 int64_t weightHeight = ShapedType::kDynamic;
4666
4667 // Input shape describes input width/height and batch.
4668 ShapeAdaptor inputShape(adaptor.getInput().getType());
4669 if (inputShape.hasRank()) {
4670 outputShape[0] = ShapedType::isDynamic(outputShape[0])
4671 ? inputShape.getDimSize(0)
4672 : outputShape[0];
4673 inputHeight = inputShape.getDimSize(1);
4674 inputWidth = inputShape.getDimSize(2);
4675 }
4676
4677 // Weight shapes describes the filter width/height and the output channels.
4678 ShapeAdaptor weightShape(adaptor.getWeight().getType());
4679 if (weightShape.hasRank()) {
4680 outputShape[3] = ShapedType::isDynamic(outputShape[3])
4681 ? weightShape.getDimSize(0)
4682 : outputShape[3];
4683 weightHeight = weightShape.getDimSize(1);
4684 weightWidth = weightShape.getDimSize(2);
4685 }
4686
4687 // Bias shape can describe the output channels.
4688 ShapeAdaptor biasShape(adaptor.getBias().getType());
4689 if (biasShape.hasRank() && ShapedType::isDynamic(outputShape[3])) {
4690 int64_t bc = biasShape.getDimSize(0);
4691 if (bc != ShapedType::kDynamic && bc != 1)
4692 outputShape[3] = bc;
4693 }
4694
4695 llvm::ArrayRef<int64_t> padding = adaptor.getOutPad();
4696 llvm::ArrayRef<int64_t> stride = adaptor.getStride();
4697
4698 if (ShapedType::isStatic(inputHeight) && ShapedType::isStatic(weightHeight)) {
4699 int64_t calculateSize =
4700 (inputHeight - 1) * stride[0] + padding[0] + padding[1] + weightHeight;
4701 outputShape[1] =
4702 ShapedType::isDynamic(outputShape[1]) ? calculateSize : outputShape[1];
4703 }
4704
4705 if (ShapedType::isStatic(inputWidth) && ShapedType::isStatic(weightWidth)) {
4706 int64_t calculateSize =
4707 (inputWidth - 1) * stride[1] + padding[2] + padding[3] + weightWidth;
4708 outputShape[2] =
4709 ShapedType::isDynamic(outputShape[2]) ? calculateSize : outputShape[2];
4710 }
4711
4712 inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
4713 return success();
4714}
4715
4716LogicalResult TransposeConv2DOp::verify() {
4717 if (verifyConvOp(*this).failed())
4718 return failure();
4719
4720 const llvm::ArrayRef<int64_t> strides = getStride();
4721 const int64_t strideY = strides[0];
4722 const int64_t strideX = strides[1];
4723
4724 if (strideY < 1 || strideX < 1)
4725 return emitOpError("expect all stride values to be >= 1, got [")
4726 << strides << "]";
4727
4728 const auto checkPadAgainstKernelDim =
4729 [this](int64_t padValue, int64_t kernelDimSize, llvm::StringRef padName,
4730 llvm::StringRef kernelDimName) -> LogicalResult {
4731 if (padValue <= -kernelDimSize)
4732 return emitOpError("expected ")
4733 << padName << " > -" << kernelDimName << ", but got: " << padName
4734 << "=" << padValue << " and " << kernelDimName << "="
4735 << kernelDimSize;
4736 return success();
4737 };
4738
4739 const llvm::ArrayRef<int64_t> padding = getOutPad();
4740 const int64_t outPadTop = padding[0];
4741 const int64_t outPadBottom = padding[1];
4742 const int64_t outPadLeft = padding[2];
4743 const int64_t outPadRight = padding[3];
4744
4745 const auto weightType =
4746 llvm::dyn_cast<RankedTensorType>(getWeight().getType());
4747
4748 if (weightType) {
4749 const int64_t kernelHeight = weightType.getDimSize(1);
4750 if (ShapedType::isStatic(kernelHeight)) {
4751 if (failed(checkPadAgainstKernelDim(outPadTop, kernelHeight,
4752 "out_pad_top", "KH")))
4753 return failure();
4754
4755 if (failed(checkPadAgainstKernelDim(outPadBottom, kernelHeight,
4756 "out_pad_bottom", "KH")))
4757 return failure();
4758 }
4759
4760 const int64_t kernelWidth = weightType.getDimSize(2);
4761 if (ShapedType::isStatic(kernelWidth)) {
4762 if (failed(checkPadAgainstKernelDim(outPadLeft, kernelWidth,
4763 "out_pad_left", "KW")))
4764 return failure();
4765
4766 if (failed(checkPadAgainstKernelDim(outPadRight, kernelWidth,
4767 "out_pad_right", "KW")))
4768 return failure();
4769 }
4770 }
4771
4772 // Rest of the checks depend on the output type being a RankedTensorType
4773 const auto outputType =
4774 llvm::dyn_cast<RankedTensorType>(getOutput().getType());
4775 if (!outputType)
4776 return success();
4777
4778 const auto inputType = llvm::dyn_cast<RankedTensorType>(getInput().getType());
4779 if (inputType && weightType) {
4780 const int64_t inputHeight = inputType.getDimSize(1);
4781 const int64_t kernelHeight = weightType.getDimSize(1);
4782 const int64_t outputHeight = outputType.getDimSize(1);
4783
4784 if (ShapedType::isStatic(inputHeight) &&
4785 ShapedType::isStatic(outputHeight)) {
4786 if (outputHeight !=
4787 (inputHeight - 1) * strideY + outPadTop + outPadBottom + kernelHeight)
4788 return emitOpError(
4789 "dimension mismatch: expected OH == (IH - 1) * stride_y "
4790 "+ out_pad_top + out_pad_bottom + KH, but got ")
4791 << outputHeight << " != (" << inputHeight << " - 1) * "
4792 << strideY << " + " << outPadTop << " + " << outPadBottom
4793 << " + " << kernelHeight;
4794 }
4795
4796 const int64_t inputWidth = inputType.getDimSize(2);
4797 const int64_t kernelWidth = weightType.getDimSize(2);
4798 const int64_t outputWidth = outputType.getDimSize(2);
4799
4800 if (ShapedType::isStatic(inputWidth) && ShapedType::isStatic(outputWidth)) {
4801 if (outputWidth !=
4802 (inputWidth - 1) * strideX + outPadLeft + outPadRight + kernelWidth)
4803 return emitOpError(
4804 "dimension mismatch: expected OW == (IW - 1) * stride_x "
4805 "+ out_pad_left + out_pad_right + KW, but got ")
4806 << outputWidth << " != (" << inputWidth << " - 1) * " << strideX
4807 << " + " << outPadLeft << " + " << outPadRight << " + "
4808 << kernelWidth;
4809 }
4810 }
4811
4812 const auto biasType = llvm::dyn_cast<RankedTensorType>(getBias().getType());
4813
4814 if (!biasType)
4815 return success();
4816
4817 const int64_t biasChannels = biasType.getDimSize(0);
4818
4819 // Skip further checks if bias is dynamic
4820 if (biasChannels == ShapedType::kDynamic)
4821 return success();
4822
4823 const int64_t outputChannels = outputType.getDimSize(3);
4824 if (!ShapedType::isDynamic(outputChannels) &&
4825 biasChannels != outputChannels && biasChannels != 1)
4826 return emitOpError(
4827 "bias channels expected to be equal to output channels (")
4828 << outputChannels << ") or 1, got " << biasChannels;
4829
4830 return success();
4831}
4832
4833LogicalResult RescaleOp::verify() {
4834 const auto inputType = llvm::cast<ShapedType>(getInput().getType());
4835 auto inputElementType =
4836 getStorageElementTypeOrSelf(inputType.getElementType());
4837 if (!mlir::isa<IntegerType>(inputElementType)) {
4838 emitOpError("expect input to have integer element type, got ")
4839 << inputElementType;
4840 return failure();
4841 }
4842
4843 const auto outputType = llvm::cast<ShapedType>(getOutput().getType());
4844 auto outputElementType =
4845 getStorageElementTypeOrSelf(outputType.getElementType());
4846 if (!mlir::isa<IntegerType>(outputElementType)) {
4847 emitOpError("expect output to have integer element type, got ")
4848 << outputElementType;
4849 return failure();
4850 }
4851
4852 if (verifyRescaleValueAndZpTypes(*this, getInput(), getInputZp(), "input")
4853 .failed())
4854 return failure();
4855
4856 if (verifyRescaleValueAndZpTypes(*this, getOutput(), getOutputZp(), "output")
4857 .failed())
4858 return failure();
4859
4860 const auto multiplierType = llvm::cast<ShapedType>(getMultiplier().getType());
4861 // multiplier element type must be i32 for scale32 = true
4862 if (getScale32() && !multiplierType.getElementType().isInteger(32)) {
4863 emitOpError("expect i32 element type for multiplier for scale32=true, got ")
4864 << multiplierType.getElementType();
4865 return failure();
4866 }
4867
4868 // multiplier element type must be i16 for scale32 = false
4869 if (!getScale32() && !multiplierType.getElementType().isInteger(16)) {
4870 emitOpError(
4871 "expect i16 element type for multiplier for scale32=false, got ")
4872 << multiplierType.getElementType();
4873 return failure();
4874 }
4875
4876 if (!inputType.hasRank())
4877 return success();
4878
4879 // multiplier/shift must have shape = {numChannels},
4880 // where numChannel is 1 if per_channel = false
4881 // otherwise numChannel is dimension in input shape's last axis
4882 int64_t numChannels = 1;
4883 if (getPerChannel()) {
4884 if (inputType.getRank() < 1) {
4885 emitOpError("requires input to be at least rank 1 when per_channel is "
4886 "true, but got rank ")
4887 << inputType.getRank();
4888 return failure();
4889 }
4890 numChannels = inputType.getDimSize(inputType.getRank() - 1);
4891 }
4892
4893 if (outputType.hasRank()) {
4895 getOperation(), outputType, inputType.getShape())))
4896 return failure();
4897 }
4898
4899 if (multiplierType.hasRank()) {
4900 ArrayRef<int64_t> multiplierShape = multiplierType.getShape();
4901 // multiplier input has rank 1 by dialect definition
4902 if (multiplierShape[0] != ShapedType::kDynamic &&
4903 multiplierShape[0] != numChannels) {
4904 emitOpError("expect shape of { ")
4905 << numChannels << " } for multiplier input, got { "
4906 << multiplierShape[0] << " }";
4907 return failure();
4908 }
4909 }
4910
4911 const auto shiftType = llvm::cast<ShapedType>(getShift().getType());
4912 if (shiftType.hasRank()) {
4913 ArrayRef<int64_t> shiftShape = shiftType.getShape();
4914 // shift input has rank 1 by dialect definition
4915 if (shiftShape[0] != ShapedType::kDynamic && shiftShape[0] != numChannels) {
4916 emitOpError("expect shape of { ")
4917 << numChannels << " } for shift input, got { " << shiftShape[0]
4918 << " }";
4919 return failure();
4920 }
4921 }
4922
4923 return success();
4924}
4925
4926LogicalResult RescaleOp::inferReturnTypeComponents(
4927 MLIRContext *context, ::std::optional<Location> location,
4928 RescaleOp::Adaptor adaptor,
4929 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4930 ShapeAdaptor inputShape(adaptor.getInput().getType());
4931 inferredReturnShapes.push_back(ShapedTypeComponents(inputShape));
4932 return success();
4933}
4934
4935LogicalResult CastOp::verify() {
4936 const ShapedType inputType = llvm::cast<ShapedType>(getInput().getType());
4937 const ShapedType outputType = llvm::cast<ShapedType>(getType());
4938 const Type inputElementType = inputType.getElementType();
4939 const Type outputElementType = outputType.getElementType();
4940
4941 const bool inputIsBlockScaled = llvm::isa<BlockScaledType>(inputElementType);
4942 const bool outputIsBlockScaled =
4943 llvm::isa<BlockScaledType>(outputElementType);
4944
4945 const bool isUnsigned = this->getInputUnsigned();
4946 const Type inputDataType = getStorageElementTypeOrSelf(inputType);
4947
4948 if (isUnsigned)
4949 if (!inputDataType.isInteger() || inputDataType.isInteger(1))
4950 return emitOpError()
4951 << "attribute input_unsigned requires integer type inputs. Got: "
4952 << inputDataType;
4953
4954 if (!inputIsBlockScaled && !outputIsBlockScaled)
4955 return success();
4956
4957 if (inputIsBlockScaled && outputIsBlockScaled)
4958 return emitOpError()
4959 << "requires exactly one of input or output to have block scaled "
4960 "element type";
4961
4962 const Type scalarElementType =
4963 inputIsBlockScaled ? outputElementType : inputElementType;
4964 if (!llvm::isa<FloatType>(scalarElementType))
4965 return emitOpError()
4966 << "requires non-block-scaled element type to be floating-point "
4967 "when casting to or from block scaled element type, got "
4968 << scalarElementType;
4969
4970 return success();
4971}
4972
4973LogicalResult CastFromBlockScaledOp::inferReturnTypeComponents(
4974 MLIRContext *context, ::std::optional<Location> location,
4975 CastFromBlockScaledOp::Adaptor adaptor,
4976 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
4977 const ShapeAdaptor inputShape(adaptor.getInputData().getType());
4978 inferredReturnShapes.push_back(ShapedTypeComponents(inputShape));
4979 return success();
4980}
4981
4982LogicalResult CastFromBlockScaledOp::verify() {
4983 const Type inputDataType = getInputData().getType();
4984 const Type outputDataType = getResult().getType();
4985 if (failed(verifyCompatibleShape(inputDataType, outputDataType)))
4986 return emitOpError() << "require compatible shapes for input_data ("
4987 << inputDataType << ") and " << "output_data ("
4988 << outputDataType << ")";
4989
4990 const ShapeAdaptor inputDataShape = ShapeAdaptor(inputDataType);
4991
4992 if (inputDataShape.hasRank()) {
4993 const unsigned int blockSize =
4994 BlockSizeAttr::getBlockSizeValue(getBlockSize());
4995 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
4996 return emitOpError("expect block size to be 32, got ") << blockSize;
4997 const int64_t inputDataLastDim =
4998 inputDataShape.getDimSize(inputDataShape.getRank() - 1);
4999 if (inputDataLastDim % blockSize != 0)
5000 return emitOpError() << "expect last dimension of input_data ("
5001 << inputDataLastDim
5002 << ") to be divisible by block_size (" << blockSize
5003 << ")";
5004
5005 const Type inputScaleType = getInputScale().getType();
5006 const ShapeAdaptor inputScaleShape = ShapeAdaptor(inputScaleType);
5007
5008 if (inputScaleShape.hasRank()) {
5009 SmallVector<int64_t> inputDataDims, inputScaleDims;
5010 inputDataShape.getDims(inputDataDims);
5011 inputScaleShape.getDims(inputScaleDims);
5012
5013 if (inputDataDims.size() != inputScaleDims.size() ||
5015 ArrayRef<int64_t>(inputDataDims).drop_back(1),
5016 ArrayRef<int64_t>(inputScaleDims).drop_back(1))))
5017 return emitOpError()
5018 << "require compatible shapes for input_data (" << inputDataType
5019 << ") and " << "input_scale (" << inputScaleType
5020 << ") except for the last dimension";
5021
5022 const SmallVector<int64_t, 2> dimsToCheck{inputDataLastDim / blockSize,
5023 inputScaleDims.back()};
5024 if (ShapedType::isStatic(inputDataLastDim) &&
5025 failed(verifyCompatibleDims(dimsToCheck)))
5026 return emitOpError()
5027 << "expect last dimension of input_scale ("
5028 << inputScaleDims.back()
5029 << ") to be equal to last dimension of input_data / block_size ("
5030 << inputDataDims.back() / blockSize << ")";
5031 }
5032 }
5033
5034 return success();
5035}
5036
5037LogicalResult CastToBlockScaledOp::inferReturnTypeComponents(
5038 MLIRContext *context, ::std::optional<Location> location,
5039 CastToBlockScaledOp::Adaptor adaptor,
5040 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
5041 const ShapeAdaptor inputShape(adaptor.getInputData().getType());
5042 inferredReturnShapes.push_back(ShapedTypeComponents(inputShape));
5043 if (!inputShape.hasRank())
5044 return success();
5045
5046 // Calculate output_scale shape if ranked input provided
5047 SmallVector<int64_t> outputScaleShape;
5048 inputShape.getDims(outputScaleShape);
5049 const int64_t lastDimLoc = inputShape.getRank() - 1;
5050 const int64_t lastDimSize = inputShape.getDimSize(lastDimLoc);
5051 if (ShapedType::isStatic(lastDimSize)) {
5052 const unsigned int blockSize =
5053 BlockSizeAttr::getBlockSizeValue(adaptor.getBlockSize());
5054 outputScaleShape[lastDimLoc] = lastDimSize / blockSize;
5055 }
5056 inferredReturnShapes.push_back(ShapedTypeComponents(outputScaleShape));
5057 return success();
5058}
5059
5060LogicalResult CastToBlockScaledOp::verify() {
5061 const Type inputDataType = getInputData().getType();
5062 const Type outputDataType = getResult(0).getType();
5063 if (failed(verifyCompatibleShape(inputDataType, outputDataType)))
5064 return emitOpError() << "require compatible shapes for input_data ("
5065 << inputDataType << ") and " << "output_data ("
5066 << outputDataType << ")";
5067
5068 const unsigned int blockSize =
5069 BlockSizeAttr::getBlockSizeValue(getBlockSize());
5070 if (blockSize != BlockSizeAttr::getBlockSizeValue(BlockSize::BLOCK_SIZE_32))
5071 return emitOpError("expect block size to be 32, got ") << blockSize;
5072 const ShapeAdaptor inputDataShape = ShapeAdaptor(inputDataType);
5073 if (inputDataShape.hasRank()) {
5074 const int64_t inputDataLastDim =
5075 inputDataShape.getDimSize(inputDataShape.getRank() - 1);
5076 if (ShapedType::isStatic(inputDataLastDim) &&
5077 inputDataLastDim % blockSize != 0)
5078 return emitOpError() << "expect last dimension of input_data ("
5079 << inputDataLastDim
5080 << ") to be divisible by block_size (" << blockSize
5081 << ")";
5082 }
5083
5084 const ShapeAdaptor outputDataShape = ShapeAdaptor(outputDataType);
5085 const Type outputScaleType = getResult(1).getType();
5086 const ShapeAdaptor outputScaleShape = ShapeAdaptor(outputScaleType);
5087 if (outputDataShape.hasRank() && outputScaleShape.hasRank()) {
5088 SmallVector<int64_t> outputDataDims, outputScaleDims;
5089 outputDataShape.getDims(outputDataDims);
5090 outputScaleShape.getDims(outputScaleDims);
5091
5092 if (outputDataDims.size() != outputScaleDims.size() ||
5094 ArrayRef<int64_t>(outputDataDims).drop_back(1),
5095 ArrayRef<int64_t>(outputScaleDims).drop_back(1))))
5096 return emitOpError() << "require compatible shapes for output_data ("
5097 << outputDataType << ") and " << "output_scale ("
5098 << outputScaleType
5099 << ") except for the last dimension";
5100
5101 const int64_t outputDataLastDim = outputDataDims.back();
5102 const SmallVector<int64_t, 2> dimsToCheck{outputDataLastDim / blockSize,
5103 outputScaleDims.back()};
5104 if (ShapedType::isStatic(outputDataLastDim) &&
5105 failed(verifyCompatibleDims(dimsToCheck)))
5106 return emitOpError()
5107 << "expect last dimension of output_scale ("
5108 << outputScaleDims.back()
5109 << ") to be equal to last dimension of output_data / block_size ("
5110 << outputDataDims.back() / blockSize << ")";
5111 }
5112
5113 return success();
5114}
5115
5116LogicalResult IfOp::inferReturnTypeComponents(
5117 MLIRContext *context, ::std::optional<Location> location,
5118 IfOp::Adaptor adaptor,
5119 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
5120 llvm::SmallVector<tosa::YieldOp> yieldOps;
5121 for (Region *region : adaptor.getRegions()) {
5122 for (auto &block : *region)
5123 if (auto returnOp = dyn_cast<tosa::YieldOp>(block.getTerminator()))
5124 yieldOps.push_back(returnOp);
5125 }
5126
5127 if (yieldOps.empty())
5128 return failure();
5129
5130 // Get the initial type information for the yield op.
5131 llvm::SmallVector<ValueKnowledge> resultKnowledge;
5132 resultKnowledge.reserve(yieldOps.front().getNumOperands());
5133 for (auto operand : yieldOps.front().getOperands()) {
5134 resultKnowledge.push_back(
5135 ValueKnowledge::getKnowledgeFromType(operand.getType()));
5136 }
5137
5138 for (auto yieldOp : yieldOps) {
5139 if (resultKnowledge.size() != yieldOp.getNumOperands())
5140 return failure();
5141
5142 for (const auto &it : llvm::enumerate(yieldOp.getOperands())) {
5143 int32_t index = it.index();
5144 auto meet = ValueKnowledge::meet(
5145 resultKnowledge[index],
5146 ValueKnowledge::getKnowledgeFromType(it.value().getType()));
5147 if (!meet)
5148 continue;
5149 resultKnowledge[index] = meet;
5150 }
5151 }
5152
5153 for (const ValueKnowledge &result : resultKnowledge) {
5154 inferredReturnShapes.push_back(result.getShapedTypeComponents());
5155 }
5156
5157 return success();
5158}
5159
5160LogicalResult WhileOp::inferReturnTypeComponents(
5161 MLIRContext *context, ::std::optional<Location> location,
5162 WhileOp::Adaptor adaptor,
5163 SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
5164 llvm::SmallVector<tosa::YieldOp> yieldOps;
5165 for (auto &block : adaptor.getBodyGraph())
5166 if (auto returnOp = dyn_cast<tosa::YieldOp>(block.getTerminator()))
5167 yieldOps.push_back(returnOp);
5168
5169 // TOSA's while must have a tosa.yield as its terminator. If not found this
5170 // tosa.while is invalid.
5171 if (yieldOps.empty())
5172 return failure();
5173
5174 // Get the initial type information from the operand types.
5175 llvm::SmallVector<ValueKnowledge> resultKnowledge;
5176 resultKnowledge.reserve(yieldOps.front().getNumOperands());
5177 for (auto operand : yieldOps.front().getOperands()) {
5178 resultKnowledge.push_back(
5179 ValueKnowledge::getKnowledgeFromType(operand.getType()));
5180 }
5181
5182 for (auto yieldOp : yieldOps) {
5183 if (resultKnowledge.size() != yieldOp.getNumOperands())
5184 return failure();
5185
5186 for (const auto &it : llvm::enumerate(yieldOp.getOperands())) {
5187 int32_t index = it.index();
5188 if (auto meet = ValueKnowledge::meet(
5189 resultKnowledge[index],
5190 ValueKnowledge::getKnowledgeFromType(it.value().getType()))) {
5191 resultKnowledge[index] = meet;
5192 }
5193 }
5194 }
5195
5196 for (const ValueKnowledge &result : resultKnowledge) {
5197 inferredReturnShapes.push_back(result.getShapedTypeComponents());
5198 }
5199
5200 return success();
5201}
5202
5204 Block::BlockArgListType blocksArgs,
5205 ValueRange initializers,
5206 StringRef prefix = "") {
5207 assert(blocksArgs.size() == initializers.size() &&
5208 "expected same length of arguments and initializers");
5209 if (initializers.empty())
5210 return;
5211
5212 parser << prefix << '(';
5213 llvm::interleaveComma(
5214 llvm::zip(blocksArgs, initializers), parser,
5215 [&](auto it) { parser << std::get<0>(it) << " = " << std::get<1>(it); });
5216 parser << ")";
5217}
5218
5219// parse and print of IfOp refer to the implementation of SCF dialect.
5220ParseResult IfOp::parse(OpAsmParser &parser, OperationState &result) {
5221 // Create the regions for 'then'.
5222 result.regions.reserve(2);
5223 Region *thenRegion = result.addRegion();
5224 Region *elseRegion = result.addRegion();
5225
5226 OpAsmParser::UnresolvedOperand cond;
5227
5228 if (parser.parseOperand(cond))
5229 return failure();
5230
5231 SmallVector<OpAsmParser::Argument, 4> regionArgs;
5232 SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
5233
5234 // Parse the optional block arguments
5235 OptionalParseResult listResult =
5236 parser.parseOptionalAssignmentList(regionArgs, operands);
5237 if (listResult.has_value() && failed(listResult.value()))
5238 return failure();
5239
5240 // Parse a colon.
5241 if (failed(parser.parseColon()))
5242 return parser.emitError(parser.getCurrentLocation(),
5243 "expected type for condition operand");
5244
5245 // Parse the type of the condition operand
5246 Type condType;
5247 if (failed(parser.parseType(condType)))
5248 return parser.emitError(parser.getCurrentLocation(),
5249 "expected type for condition operand");
5250
5251 // Resolve operand with provided type
5252 if (failed(parser.resolveOperand(cond, condType, result.operands)))
5253 return failure();
5254
5255 // Parse optional block arg types
5256 if (listResult.has_value()) {
5257 FunctionType functionType;
5258
5259 if (failed(parser.parseType(functionType)))
5260 return parser.emitError(parser.getCurrentLocation())
5261 << "expected list of types for block arguments "
5262 << "followed by arrow type and list of return types";
5263
5264 result.addTypes(functionType.getResults());
5265
5266 if (functionType.getNumInputs() != operands.size()) {
5267 return parser.emitError(parser.getCurrentLocation())
5268 << "expected as many input types as operands " << "(expected "
5269 << operands.size() << " got " << functionType.getNumInputs()
5270 << ")";
5271 }
5272
5273 // Resolve input operands.
5274 if (failed(parser.resolveOperands(operands, functionType.getInputs(),
5275 parser.getCurrentLocation(),
5276 result.operands)))
5277 return failure();
5278 } else {
5279 // Parse optional results type list.
5280 if (parser.parseOptionalArrowTypeList(result.types))
5281 return failure();
5282 }
5283
5284 // Parse the 'then' region.
5285 if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
5286 return failure();
5287
5288 // If we find an 'else' keyword then parse the 'else' region.
5289 if (!parser.parseOptionalKeyword("else")) {
5290 if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
5291 return failure();
5292 }
5293
5294 // Parse the optional attribute list.
5295 if (parser.parseOptionalAttrDict(result.attributes))
5296 return failure();
5297 return success();
5298}
5299
5300void IfOp::print(OpAsmPrinter &p) {
5301 p << " " << getCondition();
5302
5303 printInitializationList(p, getThenGraph().front().getArguments(),
5304 getInputList(), " ");
5305 p << " : ";
5306 p << getCondition().getType();
5307
5308 if (!getInputList().empty()) {
5309 p << " (";
5310 llvm::interleaveComma(getInputList().getTypes(), p);
5311 p << ")";
5312 }
5313 p.printArrowTypeList(getResultTypes());
5314 p << " ";
5315
5316 p.printRegion(getThenGraph());
5317
5318 // Print the 'else' regions if it exists and has a block.
5319 auto &elseRegion = getElseGraph();
5320 if (!elseRegion.empty()) {
5321 p << " else ";
5322 p.printRegion(elseRegion);
5323 }
5324
5325 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
5326}
5327
5328LogicalResult IfOp::verify() {
5329 if (errorIfTypeOrShapeMismatch(*this, getThenGraph().front().getArguments(),
5330 "'then_graph' arguments", getInputList(),
5331 "'input_list'")
5332 .failed())
5333 return failure();
5334
5335 if (errorIfTypeOrShapeMismatch(*this, getElseGraph().front().getArguments(),
5336 "'else_graph' arguments", getInputList(),
5337 "'input_list'")
5338 .failed())
5339 return failure();
5340
5341 // MLIR will verify the absence of the terminator for us if otherwise.
5342 if (getThenGraph().front().mightHaveTerminator()) {
5343 auto thenYield =
5344 dyn_cast<tosa::YieldOp>(getThenGraph().front().getTerminator());
5345 if (thenYield && errorIfTypeOrShapeMismatch(
5346 *this, thenYield.getInputs(), "'then_graph' results",
5347 getOutputList(), "'output_list'")
5348 .failed())
5349 return failure();
5350 }
5351
5352 // MLIR will verify the absence of the terminator for us if otherwise.
5353 if (getElseGraph().front().mightHaveTerminator()) {
5354 auto elseYield =
5355 dyn_cast<tosa::YieldOp>(getElseGraph().front().getTerminator());
5356 if (elseYield && errorIfTypeOrShapeMismatch(
5357 *this, elseYield.getInputs(), "'else_graph' results",
5358 getOutputList(), "'output_list'")
5359 .failed())
5360 return failure();
5361 }
5362
5363 auto condType = getCondition().getType();
5364 if (errorIfShapeNotSizeOne(*this, condType).failed())
5365 return emitOpError() << "'condition' must be a size 1 tensor, got "
5366 << condType;
5367
5368 return success();
5369}
5370
5371LogicalResult WhileOp::verify() {
5372 if (errorIfTypeOrShapeMismatch(*this, getInputList(), "'input_list'",
5373 getOutputList(), "'output_list'")
5374 .failed())
5375 return failure();
5376
5377 if (errorIfTypeOrShapeMismatch(*this, getCondGraph().front().getArguments(),
5378 "'cond_graph' arguments", getInputList(),
5379 "'input_list'")
5380 .failed())
5381 return failure();
5382
5383 if (errorIfTypeOrShapeMismatch(*this, getBodyGraph().front().getArguments(),
5384 "'body_graph' arguments", getInputList(),
5385 "'input_list'")
5386 .failed())
5387 return failure();
5388
5389 if (getBodyGraph().front().mightHaveTerminator()) {
5390 auto bodyYield =
5391 dyn_cast<tosa::YieldOp>(getBodyGraph().front().getTerminator());
5392 if (bodyYield && errorIfTypeOrShapeMismatch(*this, bodyYield.getInputs(),
5393 "'body_graph' results",
5394 getInputList(), "'input_list'")
5395 .failed())
5396 return failure();
5397 }
5398
5399 // Condition block output must be a single element tensor with a single bool
5400 // value.
5401 if (!getCondGraph().front().mightHaveTerminator())
5402 return success();
5403
5404 auto condYield =
5405 dyn_cast<tosa::YieldOp>(getCondGraph().front().getTerminator());
5406 if (!condYield)
5407 return success();
5408
5409 if (condYield.getInputs().size() != 1)
5410 return emitOpError() << "require 'cond_graph' only have one result";
5411
5412 auto condOutType = condYield.getInputs()[0].getType();
5413 if (errorIfShapeNotSizeOne(*this, condOutType).failed())
5414 return emitOpError() << "'cond_graph' result must be a size 1 tensor, got "
5415 << condOutType;
5416
5417 if (!getElementTypeOrSelf(condOutType).isInteger(1))
5418 return emitOpError() << "'cond_graph' result must be a boolean tensor, got "
5419 << condOutType;
5420
5421 return success();
5422}
5423
5424LogicalResult ReverseOp::verify() {
5425 TensorType inputType = getInput1().getType();
5426 int32_t reverseAxis = getAxis();
5427
5428 if (reverseAxis < 0)
5429 return emitOpError("expected non-negative reverse axis");
5430 if (inputType.hasRank()) {
5431 int64_t inputRank = inputType.getRank();
5432 // We allow for a special case where the input/output shape has rank 0 and
5433 // axis is also 0.
5434 if (reverseAxis >= inputRank && (reverseAxis != 0 || inputRank != 0))
5435 return emitOpError("expect input tensor rank (")
5436 << inputRank << ") to be larger than reverse axis (" << reverseAxis
5437 << ")";
5438 }
5439
5440 return success();
5441}
5442
5443LogicalResult tosa::SelectOp::verify() {
5444 // verify input2 and input3 have same element type as output
5445 if (verifySameElementTypes(*this, /* inType = */ getOnTrue().getType(),
5446 /* outType = */ getOutput().getType())
5447 .failed() ||
5448 verifySameElementTypes(*this, /* inType = */ getOnFalse().getType(),
5449 /* outType = */ getOutput().getType())
5450 .failed()) {
5451 return failure();
5452 }
5453 // verify input1 has element type of bool
5454 auto predicateType = llvm::dyn_cast<ShapedType>(getPred().getType());
5455 if (!predicateType) {
5456 return emitOpError("expect shaped tensor for input1, got ")
5457 << getInput1().getType();
5458 }
5459 auto predicateElementType = predicateType.getElementType();
5460 if (!predicateElementType.isInteger(1)) {
5461 return emitOpError("expect element type of bool for input1, got ")
5462 << predicateElementType;
5463 }
5464
5465 return success();
5466}
5467
5468LogicalResult tosa::VariableReadOp::verify() {
5469 if (verifyVariableOpErrorIf(*this, getOutput1().getType(), "'output1'")
5470 .failed())
5471 return failure();
5472
5473 return success();
5474}
5475
5476LogicalResult tosa::VariableWriteOp::verify() {
5477 if (verifyVariableOpErrorIf(*this, getInput1().getType(), "'input1'")
5478 .failed())
5479 return failure();
5480
5481 return success();
5482}
5483
5484// parse and print of WhileOp refer to the implementation of SCF dialect.
5485ParseResult WhileOp::parse(OpAsmParser &parser, OperationState &result) {
5486 SmallVector<OpAsmParser::Argument, 4> regionArgs;
5487 SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
5488 Region *cond = result.addRegion();
5489 Region *body = result.addRegion();
5490
5491 OptionalParseResult listResult =
5492 parser.parseOptionalAssignmentList(regionArgs, operands);
5493 if (listResult.has_value() && failed(listResult.value()))
5494 return failure();
5495
5496 FunctionType functionType;
5497 SMLoc typeLoc = parser.getCurrentLocation();
5498 if (failed(parser.parseColonType(functionType)))
5499 return failure();
5500
5501 result.addTypes(functionType.getResults());
5502
5503 if (functionType.getNumInputs() != operands.size()) {
5504 return parser.emitError(typeLoc)
5505 << "expected as many input types as operands " << "(expected "
5506 << operands.size() << " got " << functionType.getNumInputs() << ")";
5507 }
5508
5509 // Resolve input operands.
5510 if (failed(parser.resolveOperands(operands, functionType.getInputs(),
5511 parser.getCurrentLocation(),
5512 result.operands)))
5513 return failure();
5514
5515 // Propagate the types into the region arguments.
5516 for (size_t i = 0, e = regionArgs.size(); i != e; ++i)
5517 regionArgs[i].type = functionType.getInput(i);
5518
5519 return failure(parser.parseRegion(*cond, regionArgs) ||
5520 parser.parseKeyword("do") || parser.parseRegion(*body) ||
5521 parser.parseOptionalAttrDictWithKeyword(result.attributes));
5522}
5523
5524void WhileOp::print(OpAsmPrinter &parser) {
5525 printInitializationList(parser, getCondGraph().front().getArguments(),
5526 getInputList(), " ");
5527 parser << " : ";
5528 parser.printFunctionalType(getInputList().getTypes(),
5529 getResults().getTypes());
5530 parser << ' ';
5531 parser.printRegion(getCondGraph(), /*printEntryBlockArgs=*/false);
5532 parser << " do ";
5533 parser.printRegion(getBodyGraph());
5535 (*this)->getDiscardableAttrDictionary().getValue());
5536}
5537
5538// Create a rank-1 const tensor for zero point of the source tensor.
5539std::optional<Value> mlir::tosa::createZeroPointTensor(OpBuilder &builder,
5540 Location loc,
5541 Type srcElemType,
5542 int64_t zp) {
5543 srcElemType = getStorageElementTypeOrSelf(srcElemType);
5544 auto zpType = mlir::RankedTensorType::get({1}, srcElemType);
5545 if (llvm::isa<FloatType>(srcElemType)) {
5546 auto zpAttr = DenseElementsAttr::get(
5547 zpType, builder.getFloatAttr(srcElemType, static_cast<double>(zp)));
5548 return tosa::ConstOp::create(builder, loc, zpType, zpAttr);
5549 }
5550 if (llvm::isa<IntegerType>(srcElemType)) {
5551 auto zpAttr =
5552 DenseElementsAttr::get(zpType, builder.getIntegerAttr(srcElemType, zp));
5553 return tosa::ConstOp::create(builder, loc, zpType, zpAttr);
5554 }
5555 llvm::errs() << "zero point is not allowed for unsupported data types\n";
5556 return std::nullopt;
5557}
5558
5559//===----------------------------------------------------------------------===//
5560// TOSA Shape and Shape Operators Helper functions.
5561//===----------------------------------------------------------------------===//
5562
5564 return mlir::isa<tosa::shapeType>(t);
5565}
5566
5567LogicalResult
5568mlir::tosa::shapeType::verify(function_ref<InFlightDiagnostic()> emitError,
5569 int rank) {
5570 if (rank < 0)
5571 return emitError() << "invalid rank (must be >= 0): " << rank;
5572 return success();
5573}
5574
5576 for (auto v : op->getOperands()) {
5577 if (mlir::isa<::mlir::tosa::shapeType>(v.getType())) {
5578 Operation *definingOp = v.getDefiningOp();
5579 if (!definingOp || !definingOp->hasTrait<TosaShapeOperator>()) {
5580 return op->emitOpError("shape operand is not compile time resolvable");
5581 }
5582 }
5583 }
5584 return success();
5585}
5586
5587LogicalResult
5589 if (failed(OpTrait::impl::verifyAtLeastNOperands(op, 1)))
5590 return failure();
5591
5592 // delegate function that returns rank of shape type
5593 auto getRank = [](const Type type) {
5594 return mlir::cast<mlir::tosa::shapeType>(type).getRank();
5595 };
5596 auto operandTypes = op->getOperandTypes();
5597 auto resultTypes = op->getResultTypes();
5598
5599 auto rank = getRank(*op->getOperandTypes().begin());
5600 for (auto type : operandTypes) {
5601 if (getRank(type) != rank) {
5602 return op->emitOpError("operands don't have matching ranks");
5603 }
5604 }
5605 for (auto type : resultTypes) {
5606 if (getRank(type) != rank) {
5607 return op->emitOpError("result shape has different rank than operands");
5608 }
5609 }
5610 return success();
5611}
5612
5613//===----------------------------------------------------------------------===//
5614// TOSA Shape Operators verify functions.
5615//===----------------------------------------------------------------------===//
5616
5617LogicalResult tosa::ConstShapeOp::verify() {
5618 // check one dimensional rank
5619 auto valuesRank = getValues().getType().getRank();
5620 if (valuesRank != 1)
5621 return emitOpError("expect elements in attribute values with rank 1");
5622 // check that number of elements in values attr equal to rank of result shape
5623 auto count = getValues().getNumElements();
5624 auto rank = (cast<tosa::shapeType>(getResult().getType())).getRank();
5625 if (count != rank && (count != 1 || rank != 0)) {
5626 return emitOpError("expect number of elements in attribute values (")
5627 << count << ") to be equal to the rank (" << rank
5628 << ") for the result shape type";
5629 }
5630 return success();
5631}
5632
5633LogicalResult tosa::DimOp::verify() {
5634 const tosa::shapeType outShapeType =
5635 cast<tosa::shapeType>(getResult().getType());
5636 if (outShapeType.getRank() != 1)
5637 return emitOpError("expect output shape type to contain one element, got ")
5638 << outShapeType;
5639
5640 const ShapeAdaptor inputType(getInput1().getType());
5641 if (inputType.hasRank()) {
5642 const int64_t inputRank = inputType.getRank();
5643 const int64_t axis = getAxisAttr().getInt();
5644 if (axis < 0 || axis >= inputRank)
5645 return emitOpError("expect axis to be in the range [0, ")
5646 << inputRank << "), got " << axis;
5647 }
5648 return success();
5649}
5650
5651LogicalResult tosa::ConcatShapeOp::verify() {
5652 const tosa::shapeType outShapeType =
5653 cast<tosa::shapeType>(getResult().getType());
5654 const int64_t outputRank = outShapeType.getRank();
5655 const Operation::operand_range inputList = getInput();
5656
5657 if (inputList.size() == 0)
5658 return emitOpError("requires at least one input shape");
5659
5660 if (llvm::any_of(inputList, [](Value v) {
5661 return cast<tosa::shapeType>(v.getType()).getRank() == 0;
5662 }))
5663 return emitOpError("requires all inputs shapes have a rank greater than 0");
5664
5665 const int64_t inputsRank =
5666 llvm::accumulate(inputList, 0, [](int64_t acc, const Value &input) {
5667 const tosa::shapeType inShapeType =
5668 cast<tosa::shapeType>(input.getType());
5669 return acc + inShapeType.getRank();
5670 });
5671 if (outputRank != inputsRank)
5672 return emitOpError("requires output shape rank to be equal to the sum of "
5673 "the input shape ranks (")
5674 << inputsRank << "), got " << outputRank;
5675
5676 return success();
5677}
5678
5679LogicalResult tosa::SliceShapeOp::verify() {
5680 std::optional<int32_t> start;
5681 DenseIntElementsAttr startAttr;
5682 if (matchPattern(getStart(), m_Constant(&startAttr)))
5683 start = startAttr.getValues<int32_t>()[0];
5684 if (start && start.value() < 0)
5685 return emitOpError("expected non-negative start index, got ")
5686 << start.value();
5687
5688 std::optional<int32_t> size;
5689 DenseIntElementsAttr sizeAttr;
5690 if (matchPattern(getSize(), m_Constant(&sizeAttr)))
5691 size = sizeAttr.getValues<int32_t>()[0];
5692 if (size && size.value() <= 0)
5693 return emitOpError("expected positive size, got ") << size.value();
5694
5695 if (!size)
5696 return success();
5697
5698 const tosa::shapeType outShapeType =
5699 cast<tosa::shapeType>(getResult().getType());
5700 const int64_t outputRank = outShapeType.getRank();
5701 if (outputRank != size)
5702 return emitOpError(
5703 "expected output type size to be equal to size attribute, got ")
5704 << outputRank << " vs " << size.value();
5705
5706 if (!start)
5707 return success();
5708
5709 const tosa::shapeType inShapeType =
5710 cast<tosa::shapeType>(getInput().getType());
5711 const int64_t inputRank = inShapeType.getRank();
5712 const int64_t sliceSize = start.value() + size.value();
5713 if (sliceSize > inputRank)
5714 return emitOpError("expected start + size to be less than or equal to "
5715 "input shape rank (")
5716 << inputRank << "), got " << sliceSize;
5717
5718 return success();
5719}
5720
5721//===----------------------------------------------------------------------===//
5722// TOSA Attribute Definitions.
5723//===----------------------------------------------------------------------===//
5724
5725#define GET_ATTRDEF_CLASSES
5726#include "mlir/Dialect/Tosa/IR/TosaAttributes.cpp.inc"
5727
5728//===----------------------------------------------------------------------===//
5729// TOSA Type Definitions.
5730//===----------------------------------------------------------------------===//
5731#define GET_TYPEDEF_CLASSES
5732#include "mlir/Dialect/Tosa/IR/TosaOpsTypesBase.cpp.inc"
5733
5734//===----------------------------------------------------------------------===//
5735// TOSA Operator Definitions.
5736//===----------------------------------------------------------------------===//
5737
5738static ParseResult parseOptionalBoolClause(OpAsmParser &parser,
5739 StringRef keyword,
5740 BoolAttr &result) {
5741 if (failed(parser.parseOptionalKeyword(keyword)))
5742 return success();
5743 if (parser.parseLParen() || parser.parseAttribute(result) ||
5744 parser.parseRParen())
5745 return failure();
5746 return success();
5747}
5748
5749static void printOptionalBoolClause(OpAsmPrinter &printer, StringRef keyword,
5750 BoolAttr attr) {
5751 if (!attr)
5752 return;
5753 printer << keyword << '(';
5754 printer.printAttribute(attr);
5755 printer << ')';
5756}
5757
5758static ParseResult parseLocalBound(OpAsmParser &parser, BoolAttr &result) {
5759 return parseOptionalBoolClause(parser, "local_bound", result);
5760}
5761
5762static void printLocalBound(OpAsmPrinter &printer, Operation *, BoolAttr attr) {
5763 printOptionalBoolClause(printer, "local_bound", attr);
5764}
5765
5766static ParseResult parseInputUnsigned(OpAsmParser &parser, BoolAttr &result) {
5767 return parseOptionalBoolClause(parser, "input_unsigned", result);
5768}
5769
5771 BoolAttr attr) {
5772 printOptionalBoolClause(printer, "input_unsigned", attr);
5773}
5774
5775#define GET_OP_CLASSES
5776#include "mlir/Dialect/Tosa/IR/TosaOps.cpp.inc"
return success()
static void printInitializationList(OpAsmPrinter &p, Block::BlockArgListType blocksArgs, ValueRange initializers, StringRef prefix="")
Prints the initialization list in the form of <prefix>(inner = outer, inner2 = outer2,...
Definition SCF.cpp:502
true
Given two iterators into the same block, return "true" if a is before `b.
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
b getContext())
static Type getValueType(Attribute attr)
Definition SPIRVOps.cpp:835
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:229
static LogicalResult verifyMatMulShapes(T op, bool transposeB)
Definition TosaOps.cpp:2054
static ParseResult parseOptionalBoolClause(OpAsmParser &parser, StringRef keyword, BoolAttr &result)
Definition TosaOps.cpp:5738
static void printShapeToDiagnostic(InFlightDiagnostic &diag, ArrayRef< int64_t > shape)
Definition TosaOps.cpp:355
static void buildMatMulOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value a, Value b)
Definition TosaOps.cpp:1357
static LogicalResult verifySameElementTypes(Operation *op, Type aType, Type bType, StringRef aName="input", StringRef bName="output")
Definition TosaOps.cpp:985
static ParseResult parseLocalBound(OpAsmParser &parser, BoolAttr &result)
Definition TosaOps.cpp:5758
LogicalResult inferConvReturnTypeComponents(AdaptorT adaptor, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:4254
static int64_t getMatMulBatchDim(const ShapeAdaptor &shape, int64_t outputRank, int64_t axis)
Definition TosaOps.cpp:1913
static SmallVector< int64_t > convertToMlirShape(ArrayRef< int64_t > shape)
Definition TosaOps.cpp:137
static LogicalResult ReduceInferReturnTypes(ShapeAdaptor operandShape, Type inputType, IntegerAttr axis, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:3802
static void printScaleValues(AsmPrinter &printer, ArrayRef< Attribute > scaleValues, Type)
Definition TosaOps.cpp:546
static void buildAvgPool2dAdaptiveOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input, DenseI64ArrayAttr kernel, DenseI64ArrayAttr stride, DenseI64ArrayAttr pad, TypeAttr accType)
This builder mirrors avg_pool2d quant-info handling and materializes kernel/stride/pad as const_shape...
Definition TosaOps.cpp:1417
static LogicalResult verifyRescaleValueAndZpTypes(Operation *op, Value val, Value valZp, StringRef name)
Definition TosaOps.cpp:295
static void printOptionalBoolClause(OpAsmPrinter &printer, StringRef keyword, BoolAttr attr)
Definition TosaOps.cpp:5749
static LogicalResult errorIfShapeNotSizeOne(Operation *op, Type type)
Definition TosaOps.cpp:950
static void printLocalBound(OpAsmPrinter &printer, Operation *, BoolAttr attr)
Definition TosaOps.cpp:5762
LogicalResult argMaxMinVerify(T op)
Definition TosaOps.cpp:624
static LogicalResult verifyMatMulZeroPointType(T op, Value input, Value zp, StringRef inputName, StringRef zpName)
Definition TosaOps.cpp:2018
static ParseResult parseScaleValues(AsmParser &parser, SmallVector< Attribute > &scaleValues, Type scaleType)
Definition TosaOps.cpp:517
static ParseResult parseInputUnsigned(OpAsmParser &parser, BoolAttr &result)
Definition TosaOps.cpp:5766
#define REDUCE_SHAPE_INFER(OP)
Definition TosaOps.cpp:3827
static LogicalResult verifyConvOp(T op)
Definition TosaOps.cpp:655
static LogicalResult verifyAvgPoolCommonTypeAndZpChecks(T op)
Definition TosaOps.cpp:1125
static LogicalResult verifyVariableOpErrorIf(T op, Type type, StringRef name)
Definition TosaOps.cpp:959
static LogicalResult poolingInferReturnTypes(ShapeAdaptor inputShape, ArrayRef< int64_t > kernel, ArrayRef< int64_t > stride, ArrayRef< int64_t > pad, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:4017
static void buildPadOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input, Value paddings)
This builder is called on TOSA pad operator that needs to create its own OptionalAttr quantization_at...
Definition TosaOps.cpp:1504
static LogicalResult verifyPoolingOpImpl(Operation *op, ArrayRef< int64_t > kernel, ArrayRef< int64_t > strides, ArrayRef< int64_t > padding, Value input, Value output)
Definition TosaOps.cpp:1024
static std::optional< int64_t > idivCheck(const int64_t lhs, const int64_t rhs)
Definition TosaOps.cpp:278
static void buildVariableOp(OpBuilder &builder, OperationState &result, StringRef name, Type variableType, Attribute initialValue)
Definition TosaOps.cpp:1518
static void buildMatMulLikeOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value a, Value b)
Definition TosaOps.cpp:1332
LogicalResult verifyConvOutputSize(Operation *op, const int64_t inputSize, const int64_t kernelSize, const int64_t outputSize, const int64_t padBefore, const int64_t padAfter, const int64_t stride, const int64_t dilation, const llvm::StringRef dimName, const llvm::StringRef dimAxis, const llvm::StringRef padBeforeName, const llvm::StringRef padAfterName)
Definition TosaOps.cpp:384
static LogicalResult verifyReduceOp(T op)
Definition TosaOps.cpp:3852
#define NARY_SHAPE_INFER(OP)
Definition TosaOps.cpp:3920
#define ZERO_POINT_HELPER(OP, OPERAND_NAME, SIGN_EXTEND)
Definition TosaOps.cpp:3102
static void buildTransConvOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input, Value weight, Value bias, DenseI64ArrayAttr outpad, DenseI64ArrayAttr stride, TypeAttr accType)
Handles tosa.transpose_conv2d which has outpad and output shape attributes.
Definition TosaOps.cpp:1314
LogicalResult inferArgMaxMinReturnTypeComponents(MLIRContext *context, ::std::optional< Location > location, A adaptor, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:595
static void extractAdaptivePoolingConstShapeOperands(T op, AdaptivePoolingConstShapeValues &values)
Definition TosaOps.cpp:1183
static LogicalResult verifyConvOpErrorIf(T op)
Definition TosaOps.cpp:805
static FailureOr< int64_t > getZeroPoint(Value val, bool signExtend)
Definition TosaOps.cpp:3033
static constexpr bool IsSupportedAdaptivePoolConstShapeVerifyOp
Definition TosaOps.cpp:1176
LogicalResult tryUpdateDimOrFailure(Operation *op, int64_t &currDim, const int64_t newDim, const StringRef operandName, const StringRef dimName)
Definition TosaOps.cpp:340
static LogicalResult NAryInferReturnTypes(const ValueShapeRange &operands, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:3908
#define COMPATIBLE_RETURN_TYPES(OP)
Definition TosaOps.cpp:3818
static LogicalResult resolveBroadcastShape(const ValueShapeRange &operands, SmallVector< int64_t > &outShape)
Definition TosaOps.cpp:1562
static LogicalResult verifyMatMulQuantizedOperandsType(T op, Type aElementType, Type bElementType)
Definition TosaOps.cpp:1991
static LogicalResult verifyOutputShapeCompatibleWithExpected(Operation *op, ShapedType outputType, ArrayRef< int64_t > expectedShape, StringRef outputName="output")
Definition TosaOps.cpp:368
static void printInputUnsigned(OpAsmPrinter &printer, Operation *, BoolAttr attr)
Definition TosaOps.cpp:5770
static void buildNegateOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input)
This builder is called on single-parameter negate operator to construct input and output zero points ...
Definition TosaOps.cpp:1464
static void buildConvOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input, Value weight, Value bias, DenseI64ArrayAttr pad, DenseI64ArrayAttr stride, DenseI64ArrayAttr dilation, TypeAttr accType)
This builder is called on all convolution operators except TransposeConv, which has specialized outpu...
Definition TosaOps.cpp:1290
static SmallVector< int64_t > getMatMulBatchShape(const ShapeAdaptor &shape)
Definition TosaOps.cpp:2043
static void buildAvgPool2dOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value input, DenseArrayAttr kernel, DenseArrayAttr stride, DenseArrayAttr pad, TypeAttr accType)
Both the tosa.avg_pool2d and unary ops use the same UnaryOpQuantizationAttr but avg_pool operator has...
Definition TosaOps.cpp:1373
static LogicalResult errorIfTypeOrShapeMismatch(Operation *op, Type type1, StringRef name1, Type type2, StringRef name2)
Definition TosaOps.cpp:908
static LogicalResult inferMatMulReturnTypeComponents(const ShapeAdaptor &aShape, const ShapeAdaptor &bShape, bool transposeB, SmallVectorImpl< ShapedTypeComponents > &inferredReturnShapes)
Definition TosaOps.cpp:1949
static void buildMatMulTOpWithQuantInfo(OpBuilder &builder, OperationState &result, Type outputType, Value a, Value b)
Definition TosaOps.cpp:1363
static FailureOr< SmallVector< int64_t > > resolveMatMulOutputShape(const ShapeAdaptor &aShape, const ShapeAdaptor &bShape, int64_t outputRank, bool transposeB)
Definition TosaOps.cpp:1922
static FailureOr< int64_t > resolveBroadcastDim(const int64_t dim1, const int64_t dim2)
Definition TosaOps.cpp:1548
static LogicalResult verifyZeroPoint(T op, Value val, const int64_t &zp, const std::string &operand)
Definition TosaOps.cpp:3060
static LogicalResult verifyPoolingOp(T op)
Definition TosaOps.cpp:1119
static LogicalResult verifyDimIsPowerOfTwo(Operation *op, const int64_t dimSize, const llvm::StringRef dimName)
Definition TosaOps.cpp:1639
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
static void updateIfDynamic(int64_t &current, int64_t candidate)
Definition TosaOps.cpp:4056
void inferWeightShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &weightSpatial)
Definition TosaOps.cpp:4149
LogicalResult getSpatialParameters(SmallVector< int64_t > &padValues, SmallVector< int64_t > &strideValues, SmallVector< int64_t > &dilationValues)
Definition TosaOps.cpp:4178
void inferInputShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &inputSpatial)
Definition TosaOps.cpp:4123
ConvInferShapeAdaptor(Conv2DBlockScaledOp::Adaptor adaptor)
Definition TosaOps.cpp:4120
void inferInputShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &inputSpatial)
Definition TosaOps.cpp:4069
void inferWeightShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &weightSpatial)
Definition TosaOps.cpp:4084
ConvInferShapeAdaptor(Conv2DOp::Adaptor adaptor)
Definition TosaOps.cpp:4066
LogicalResult getSpatialParameters(SmallVector< int64_t > &padValues, SmallVector< int64_t > &strideValues, SmallVector< int64_t > &dilationValues)
Definition TosaOps.cpp:4102
void inferWeightShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &weightSpatial)
Definition TosaOps.cpp:4219
ConvInferShapeAdaptor(Conv3DOp::Adaptor adaptor)
Definition TosaOps.cpp:4199
void inferInputShape(SmallVectorImpl< int64_t > &outputShape, SmallVectorImpl< int64_t > &inputSpatial)
Definition TosaOps.cpp:4202
LogicalResult getSpatialParameters(SmallVector< int64_t > &padValues, SmallVector< int64_t > &strideValues, SmallVector< int64_t > &dilationValues)
Definition TosaOps.cpp:4239
This base class exposes generic asm parser hooks, usable across the various derived parsers.
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalEqual()=0
Parse a = token if present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseColon()=0
Parse a : token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
virtual ParseResult parseFloat(double &result)=0
Parse a floating point value from the stream.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
This base class exposes generic asm printer hooks, usable across the various derived printers.
virtual void printAttributeWithoutType(Attribute attr)
Print the given attribute without its type.
virtual void printAttribute(Attribute attr)
void printArrowTypeList(TypeRange &&types)
Attributes are known-constant values of operations.
Definition Attributes.h:25
MutableArrayRef< BlockArgument > BlockArgListType
Definition Block.h:110
Special case of IntegerAttr to represent boolean integers, i.e., signless i1 integers.
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
IntegerType getI32Type()
Definition Builders.cpp:71
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
DenseIntElementsAttr getIndexTensorAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:201
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.
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
An attribute that represents a reference to a dense integer vector or tensor object.
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
virtual InFlightDiagnostic emitError(const Twine &msg={}) const =0
Emit an error to the reader.
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Definition Builders.h:632
This class represents a diagnostic that is inflight and set to be reported.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual OptionalParseResult parseOptionalAssignmentList(SmallVectorImpl< Argument > &lhs, SmallVectorImpl< UnresolvedOperand > &rhs)=0
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDictWithKeyword(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary prefixed with 'attribute...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
void printFunctionalType(Operation *op)
Print the complete type of an operation in functional form.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
This class helps build Operations.
Definition Builders.h:210
This class indicates that op operates on tosa shape types.
Definition TosaOps.h:78
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
ResultRange result_range
Support result iteration.
Definition Operation.h:437
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
OperandRange operand_range
Definition Operation.h:398
operand_type_range getOperandTypes()
Definition Operation.h:424
result_type_range getResultTypes()
Definition Operation.h:455
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
ParseResult value() const
Access the internal ParseResult value.
bool has_value() const
Returns true if we contain a valid ParseResult value.
Type-safe wrapper around a void* for passing properties, including the properties structs of operatio...
This class provides an abstraction over the different types of ranges over Regions.
Definition Region.h:363
bool empty()
Definition Region.h:60
This diagnostic handler is a simple RAII class that registers and erases a diagnostic handler on a gi...
Adaptor class to abstract the differences between whether value is from a ShapedType or ShapedTypeCom...
bool isDynamicDim(int index) const
Returns whether the index'th dimension is dynamic.
int64_t getDimSize(int index) const
Returns the size of the index'th dimension.
int64_t getRank() const
Returns the rank of the shape.
bool hasStaticShape() const
Returns whether the shape is fully static.
int64_t getNumElements() const
Returns the number of elements in the shape.
void getDims(SmallVectorImpl< int64_t > &res) const
Populates the dimensions from shape referenced.
bool hasRank() const
Returns whether the shape has a rank.
ShapedTypeComponents that represents the components of a ShapedType.
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
Definition SymbolTable.h:25
Operation * lookup(StringRef name) const
Look up a symbol with the specified name, returning null if no such name exists.
Tensor types represent multi-dimensional arrays, and have two variants: RankedTensorType and Unranked...
ArrayRef< int64_t > getShape() const
Returns the shape of this tensor type.
bool hasRank() const
Returns if this type is ranked, i.e. it has a known number of dimensions.
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
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
Definition Types.cpp:66
bool isF32() const
Definition Types.cpp:40
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 isF16() const
Definition Types.cpp:38
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
bool isBF16() const
Definition Types.cpp:37
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
type_range getTypes() const
Range of values and shapes (corresponding effectively to Shapes dialect's ValueShape type concept).
ShapeAdaptor getShape(int index) const
Returns the shape of index'th operand.
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
LogicalResult verifyAtLeastNOperands(Operation *op, unsigned numOperands)
LogicalResult verifyTosaShapeOperatorWithSameRanks(Operation *op)
Definition TosaOps.cpp:5588
LogicalResult verifyTosaResolvableShapeOperands(Operation *op)
Definition TosaOps.cpp:5575
bool getBroadcastedShape(ArrayRef< int64_t > shape1, ArrayRef< int64_t > shape2, SmallVectorImpl< int64_t > &resultShape)
Returns true and sets resultShape to the broadcasted shape from the two given shapes if they are broa...
Definition Traits.cpp:59
LogicalResult convertFloatTypeFromAttribute(Type type, Attribute attr, llvm::SmallVectorImpl< char > &result)
Float type implementation of DenseElementTypeInterface::convertFromAttribute.
Attribute convertFloatTypeToAttribute(Type type, llvm::ArrayRef< char > rawData)
Float type implementation of DenseElementTypeInterface::convertToAttribute.
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
Definition Utils.cpp:18
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:744
SmallVector< unsigned > getBlockSize(AffineMap dimToLvl)
Given the dimToLvl map, returns the block sizes in a vector.
ConvOpQuantizationAttr buildConvOpQuantizationAttr(OpBuilder &builder, Value input, Value weight)
Method to build ConvOpQuantizationAttr, called from ConvOpQuantInfoBuilder/TransConvOpQuantInfoBuilde...
Type getStorageElementTypeOrSelf(Type type)
Definition TosaOps.cpp:284
RankedTensorType getVariableType(VariableOp variableOp)
Type buildConvOpResultTypeInfo(OpBuilder &builder, Type outputType, Value input, Value weight)
construct ConvOp output type with correct bitwidth based on input/weight width.
ParseResult parseVariableOpTypeOrInitialValue(OpAsmParser &parser, DenseElementsAttr &varShapeAttr, TypeAttr &typeAttr, Attribute &initialValueAttr)
Definition TosaOps.cpp:226
PadOpQuantizationAttr buildPadOpQuantizationAttr(OpBuilder &builder, Value input)
Builds PadOpQuantizationAttr, called from PadOpQuantInfoBuilder: inputZp: input zeropoint.
constexpr int64_t kInferableDimSize
Represents a dimension in the shape of a tensor that can be inferred based on the other provided dime...
Definition TosaOps.h:102
std::pair< Value, Value > createZPsAsConst(OpBuilder &builder, Value input, Value weight)
void printVariableOpTypeOrInitialValue(OpAsmPrinter &p, Operation *op, DenseElementsAttr varShapeAttr, TypeAttr typeAttr, Attribute initialValueAttr)
Definition TosaOps.cpp:251
FailureOr< T > getConstantScalarIntValue(Value val)
Value getTosaConstShape(ImplicitLocOpBuilder &builder, llvm::ArrayRef< int64_t > shape)
MatMulOpQuantizationAttr buildMatMulOpQuantizationAttr(OpBuilder &builder, Value a, Value b)
Builds MatMulOpQuantizationAttr, called from MatMulOpQuantInfoBuilder: aZp: input a zeropoint bZp: in...
unsigned getBitWidth(Type type)
Definition TosaOps.cpp:330
std::optional< Value > createZeroPointTensor(OpBuilder &builder, Location loc, Type srcElemType, int64_t zp=0)
Definition TosaOps.cpp:5539
bool isa_tosa_shape_type(mlir::Type t)
Definition TosaOps.cpp:5563
SmallVector< int64_t > convertFromMlirShape(ArrayRef< int64_t > shape)
UnaryOpQuantizationAttr buildUnaryOpQuantizationAttr(OpBuilder &builder, Value input, Type outputRawType)
Builds UnaryOpQuantizationAttr UnaryOpQuantInfoBuilder: inputZp: input zeropoint outputZp: output zer...
Type getStorageElementTypeFromQuantized(quant::QuantizedType quantizedType)
Value createPadConstTensor(OpBuilder &builder, Location loc, Value src, int32_t val=0)
Definition TosaOps.cpp:315
LogicalResult verifyBlockScaledTensorType(mlir::Type type, llvm::function_ref< mlir::InFlightDiagnostic()> emitError=nullptr, bool allowScaleValues=false)
Definition TosaOps.cpp:443
std::string getTosaTensorTypeErrorMessage(mlir::Type type)
Definition TosaOps.cpp:502
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
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
LogicalResult verifyCompatibleShapes(TypeRange types1, TypeRange types2)
Returns success if the given two arrays have the same number of elements and each pair wise entries h...
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
LogicalResult emitOptionalError(std::optional< Location > loc, Args &&...args)
Overloads of the above emission functions that take an optionally null location.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
SmallVector< SmallVector< OpFoldResult > > ReifiedRankedShapedTypeDims
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
LogicalResult verifyCompatibleDims(ArrayRef< int64_t > dims)
Dimensions are compatible if all non-dynamic dims are equal.
LogicalResult verifyRanksMatch(Operation *op, ShapedType lhs, ShapedType rhs, StringRef lhsName, StringRef rhsName)
Verify that two shaped types have matching ranks.
LogicalResult verifyCompatibleShape(ArrayRef< int64_t > shape1, ArrayRef< int64_t > shape2)
Returns success if the given two shapes are compatible.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
Definition Matchers.h:369
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
bool isPermutationVector(ArrayRef< int64_t > interchange)
Method to check if an interchange vector is a permutation.
This represents an operation in an abstracted form, suitable for use with the builder APIs.
static ValueKnowledge meet(const ValueKnowledge &lhs, const ValueKnowledge &rhs)
Definition ShapeUtils.h:136
static ValueKnowledge getKnowledgeFromType(Type type)
Definition ShapeUtils.h:45