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://developer.mlplatform.org/w/tosa/
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "mlir/Dialect/Tosa/IR/TosaOps.h"
16 #include "mlir/Dialect/Quant/QuantOps.h"
17 #include "mlir/Dialect/Tensor/IR/Tensor.h"
18 #include "mlir/Dialect/Tosa/Utils/QuantUtils.h"
19 #include "mlir/Dialect/Tosa/Utils/ShapeUtils.h"
20 #include "mlir/IR/BuiltinTypes.h"
21 #include "mlir/IR/Matchers.h"
22 #include "mlir/IR/PatternMatch.h"
23 #include "mlir/Transforms/FoldUtils.h"
24 #include "mlir/Transforms/InliningUtils.h"
25 #include "mlir/Transforms/RegionUtils.h"
26 #include "llvm/ADT/DenseMap.h"
27 
28 using namespace mlir;
29 using namespace mlir::tosa;
30 
31 #include "mlir/Dialect/Tosa/IR/TosaOpsDialect.cpp.inc"
32 
33 //===----------------------------------------------------------------------===//
34 // Tosa dialect structs and interface includes.
35 //===----------------------------------------------------------------------===//
36 #include "mlir/Dialect/Tosa/IR/TosaInterfaces.cpp.inc"
37 #include "mlir/Dialect/Tosa/IR/TosaStructs.cpp.inc"
38 
39 namespace {
40 //===----------------------------------------------------------------------===//
41 // Dialect Function Inliner Interface.
42 //===----------------------------------------------------------------------===//
43 struct TosaInlinerInterface : public DialectInlinerInterface {
44   using DialectInlinerInterface::DialectInlinerInterface;
45 
46   //===--------------------------------------------------------------------===//
47   // Analysis Hooks.
48   //===--------------------------------------------------------------------===//
49 
50   /// All operations can be inlined by default.
51   bool isLegalToInline(Operation *op, Region *region, bool wouldBeCloned,
52                        BlockAndValueMapping &map) const final {
53     return true;
54   }
55 
56   /// All regions with If and While parent operators can be inlined.
57   bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
58                        BlockAndValueMapping &map) const final {
59     return (isa<tosa::IfOp>(dest->getParentOp()) ||
60             isa<tosa::WhileOp>(dest->getParentOp()));
61   }
62 };
63 } // namespace
64 
65 //===----------------------------------------------------------------------===//
66 // TOSA control flow support.
67 //===----------------------------------------------------------------------===//
68 
69 /// Returns the while loop body.
70 Region &tosa::WhileOp::getLoopBody() { return body(); }
71 
72 //===----------------------------------------------------------------------===//
73 // Tosa dialect initialization.
74 //===----------------------------------------------------------------------===//
75 
76 void TosaDialect::initialize() {
77   addOperations<
78 #define GET_OP_LIST
79 #include "mlir/Dialect/Tosa/IR/TosaOps.cpp.inc"
80       >();
81   addInterfaces<TosaInlinerInterface>();
82 }
83 
84 Operation *TosaDialect::materializeConstant(OpBuilder &builder, Attribute value,
85                                             Type type, Location loc) {
86   // Tosa dialect constants only support ElementsAttr unlike standard dialect
87   // constant which supports all attributes.
88   if (value.isa<ElementsAttr>())
89     return builder.create<tosa::ConstOp>(loc, type, value.cast<ElementsAttr>());
90   return nullptr;
91 }
92 
93 //===----------------------------------------------------------------------===//
94 // Operator Canonicalizers.
95 //===----------------------------------------------------------------------===//
96 
97 struct ConcatOptimization : public OpRewritePattern<tosa::ConcatOp> {
98   using OpRewritePattern<tosa::ConcatOp>::OpRewritePattern;
99 
100   LogicalResult matchAndRewrite(tosa::ConcatOp op,
101                                 PatternRewriter &rewriter) const override {
102     if (op.input1().size() != 1)
103       return failure();
104     if (op.input1().front().getType() != op.getType()) {
105       rewriter
106           .replaceOpWithNewOp<tensor::CastOp>(op, op.getType(),
107                                               op.input1().front())
108           .getResult();
109       return success();
110     }
111 
112     rewriter.replaceOp(op, op.input1().front());
113     return success();
114   }
115 };
116 
117 void ConcatOp::getCanonicalizationPatterns(RewritePatternSet &results,
118                                            MLIRContext *context) {
119   results.add<ConcatOptimization>(context);
120 }
121 
122 struct ReshapeReshapeOptimization : public OpRewritePattern<tosa::ReshapeOp> {
123   using OpRewritePattern<tosa::ReshapeOp>::OpRewritePattern;
124 
125   LogicalResult matchAndRewrite(tosa::ReshapeOp op,
126                                 PatternRewriter &rewriter) const override {
127     Value input = op.input1();
128     Operation *definingOp = input.getDefiningOp();
129     if (!definingOp)
130       return failure();
131 
132     if (tosa::ReshapeOp reshapeOp = dyn_cast<tosa::ReshapeOp>(definingOp)) {
133       rewriter.replaceOpWithNewOp<tosa::ReshapeOp>(
134           op, op.getType(), reshapeOp.input1(), op.new_shape());
135       return success();
136     }
137 
138     return failure();
139   }
140 };
141 
142 struct ReshapeConstOptimization : public OpRewritePattern<tosa::ReshapeOp> {
143   using OpRewritePattern<tosa::ReshapeOp>::OpRewritePattern;
144 
145   LogicalResult matchAndRewrite(tosa::ReshapeOp op,
146                                 PatternRewriter &rewriter) const override {
147     Value input = op.input1();
148     ArrayAttr newShape = op.new_shape();
149 
150     // Check if input is constant
151     DenseElementsAttr inputAttr;
152     if (!matchPattern(input, m_Constant(&inputAttr)))
153       return failure();
154 
155     // Check if has >1 consumer and is not splat
156     if (!input.hasOneUse() && !inputAttr.isSplat())
157       return failure();
158 
159     // Grab the new shape
160     SmallVector<int64_t> newShapeValues = llvm::to_vector<6>(
161         llvm::map_range(newShape.getValue(), [](const Attribute &val) {
162           return val.cast<IntegerAttr>().getValue().getSExtValue();
163         }));
164 
165     // Build new const op with correct output shape
166     ShapedType inputShape = input.getType().cast<ShapedType>();
167     DenseElementsAttr outputAttr =
168         inputAttr.reshape(inputShape.clone(newShapeValues));
169     rewriter.replaceOpWithNewOp<tosa::ConstOp>(op, outputAttr.getType(),
170                                                outputAttr);
171     return success();
172   }
173 };
174 
175 void ReshapeOp::getCanonicalizationPatterns(RewritePatternSet &results,
176                                             MLIRContext *context) {
177   results.add<ReshapeReshapeOptimization>(context);
178   results.add<ReshapeConstOptimization>(context);
179 }
180 
181 LogicalResult SelectOp::canonicalize(SelectOp op, PatternRewriter &rewriter) {
182   auto notOp = op.pred().getDefiningOp<tosa::LogicalNotOp>();
183   if (!notOp)
184     return failure();
185   rewriter.updateRootInPlace(op, [&]() {
186     op.getOperation()->setOperands(
187         {notOp.input1(), op.on_false(), op.on_true()});
188   });
189   return success();
190 }
191 
192 struct ConstantTransposeOptimization
193     : public OpRewritePattern<tosa::TransposeOp> {
194   using OpRewritePattern::OpRewritePattern;
195 
196   LogicalResult matchAndRewrite(tosa::TransposeOp op,
197                                 PatternRewriter &rewriter) const override {
198     auto outputType = op.getType().cast<ShapedType>();
199     ArrayRef<int64_t> outputShape = outputType.getShape();
200     // TOSA supports quantized types.
201     if (!outputType.getElementType().isIntOrIndexOrFloat())
202       return failure();
203 
204     DenseElementsAttr inputValues;
205     if (!matchPattern(op.input1(), m_Constant(&inputValues)))
206       return failure();
207     // Make sure the input is a constant that has a single user.
208     if (!llvm::hasSingleElement(op.input1().getDefiningOp()->getUsers()))
209       return failure();
210 
211     DenseIntElementsAttr permAttr;
212     if (!matchPattern(op.perms(), m_Constant(&permAttr)))
213       return failure();
214     auto permValues = llvm::to_vector<6>(llvm::map_range(
215         // TOSA allows both 32- and 64-bit integer tensors here.
216         permAttr.getValues<APInt>(),
217         [](const APInt &val) { return val.getZExtValue(); }));
218 
219     auto inputType = op.input1().getType().cast<ShapedType>();
220     ArrayRef<int64_t> inputShape = inputType.getShape();
221     int64_t numElements = inputType.getNumElements();
222 
223     SmallVector<Attribute, 4> outputValues;
224     outputValues.resize(numElements);
225 
226     // Transpose the input constant. Because we don't know its rank in advance,
227     // we need to loop over the range [0, element count) and delinearize the
228     // index.
229     auto attrValues = inputValues.getValues<Attribute>();
230     for (int srcLinearIndex = 0; srcLinearIndex < numElements;
231          ++srcLinearIndex) {
232       SmallVector<uint64_t, 6> srcIndices(inputType.getRank(), 0);
233       int totalCount = srcLinearIndex;
234       for (int dim = inputType.getRank() - 1; dim >= 0; --dim) {
235         srcIndices[dim] = totalCount % inputShape[dim];
236         totalCount /= inputShape[dim];
237       }
238 
239       SmallVector<uint64_t, 6> dstIndices(outputType.getRank(), 0);
240       for (int dim = outputType.getRank() - 1; dim >= 0; --dim)
241         dstIndices[dim] = srcIndices[permValues[dim]];
242 
243       uint64_t dstLinearIndex = dstIndices.front();
244       for (int dim = 1; dim < outputType.getRank(); ++dim)
245         dstLinearIndex = dstLinearIndex * outputShape[dim] + dstIndices[dim];
246 
247       outputValues[dstLinearIndex] = attrValues[srcIndices];
248     }
249 
250     rewriter.replaceOpWithNewOp<tosa::ConstOp>(
251         op, outputType, DenseElementsAttr::get(outputType, outputValues));
252     return success();
253   }
254 };
255 
256 struct NoOpOptimization : public OpRewritePattern<tosa::TransposeOp> {
257   using OpRewritePattern::OpRewritePattern;
258 
259   LogicalResult matchAndRewrite(tosa::TransposeOp op,
260                                 PatternRewriter &rewriter) const override {
261     auto perm = op.perms();
262 
263     DenseIntElementsAttr permAttr;
264     if (!matchPattern(perm, m_Constant(&permAttr))) {
265       return failure();
266     }
267 
268     SmallVector<int64_t> permValues = llvm::to_vector<6>(
269         llvm::map_range(permAttr.getValues<APInt>(),
270                         [](const APInt &val) { return val.getSExtValue(); }));
271 
272     for (int i = 0, s = permValues.size(); i < s; i++) {
273       if (i != permValues[i]) {
274         return failure();
275       }
276     }
277 
278     rewriter.replaceOp(op, op.input1());
279     return success();
280   }
281 };
282 
283 void TransposeOp::getCanonicalizationPatterns(RewritePatternSet &results,
284                                               MLIRContext *context) {
285   results.add<ConstantTransposeOptimization>(context);
286   results.add<NoOpOptimization>(context);
287 }
288 
289 struct AddZeroOptimization : public OpRewritePattern<tosa::AddOp> {
290   using OpRewritePattern::OpRewritePattern;
291 
292   LogicalResult matchAndRewrite(tosa::AddOp op,
293                                 PatternRewriter &rewriter) const override {
294     auto input1 = op.input1();
295     auto input2 = op.input2();
296 
297     DenseElementsAttr input1Attr;
298     if (matchPattern(input1, m_Constant(&input1Attr)) && input1Attr.isSplat() &&
299         input2.getType() == op.getType()) {
300       if (input1Attr.getType().getElementType().isa<IntegerType>() &&
301           input1Attr.getSplatValue<APInt>().isZero()) {
302         rewriter.replaceOp(op, op.input2());
303         return success();
304       }
305     }
306 
307     DenseElementsAttr input2Attr;
308     if (matchPattern(input2, m_Constant(&input2Attr)) && input2Attr.isSplat() &&
309         input1.getType() == op.getType()) {
310       if (input2Attr.getType().getElementType().isa<IntegerType>() &&
311           input2Attr.getSplatValue<APInt>().isZero()) {
312         rewriter.replaceOp(op, op.input1());
313         return success();
314       }
315     }
316 
317     return failure();
318   }
319 };
320 
321 void AddOp::getCanonicalizationPatterns(RewritePatternSet &results,
322                                         MLIRContext *context) {
323   results.add<AddZeroOptimization>(context);
324 }
325 
326 struct MulOneOptimization : public OpRewritePattern<tosa::MulOp> {
327   using OpRewritePattern::OpRewritePattern;
328 
329   LogicalResult matchAndRewrite(tosa::MulOp op,
330                                 PatternRewriter &rewriter) const override {
331     auto input1 = op.input1();
332     auto input2 = op.input2();
333 
334     DenseElementsAttr input1Attr;
335     if (matchPattern(input1, m_Constant(&input1Attr)) && input1Attr.isSplat() &&
336         input2.getType() == op.getType()) {
337       if (input1Attr.getType().getElementType().isa<FloatType>() &&
338           input1Attr.getSplatValue<APFloat>().isExactlyValue(1)) {
339         rewriter.replaceOp(op, op.input2());
340         return success();
341       }
342 
343       if (input1Attr.getType().getElementType().isa<IntegerType>() &&
344           matchPattern(input1, m_One())) {
345         rewriter.replaceOp(op, op.input2());
346         return success();
347       }
348     }
349 
350     DenseElementsAttr input2Attr;
351     if (matchPattern(input2, m_Constant(&input2Attr)) && input2Attr.isSplat() &&
352         input1.getType() == op.getType()) {
353       if (input2Attr.getType().getElementType().isa<FloatType>() &&
354           input2Attr.getSplatValue<APFloat>().isExactlyValue(1)) {
355         rewriter.replaceOp(op, op.input1());
356         return success();
357       }
358 
359       if (input2Attr.getType().getElementType().isa<IntegerType>() &&
360           matchPattern(input2, m_One())) {
361         rewriter.replaceOp(op, op.input1());
362         return success();
363       }
364     }
365 
366     return failure();
367   }
368 };
369 
370 void MulOp::getCanonicalizationPatterns(RewritePatternSet &results,
371                                         MLIRContext *context) {
372   results.add<MulOneOptimization>(context);
373 }
374 
375 struct MaterializePadValue : public OpRewritePattern<tosa::PadOp> {
376   using OpRewritePattern::OpRewritePattern;
377 
378   LogicalResult matchAndRewrite(tosa::PadOp op,
379                                 PatternRewriter &rewriter) const override {
380     if (op.pad_const())
381       return failure();
382 
383     auto input = op.input1();
384     auto padding = op.padding();
385 
386     ShapedType inputTy = input.getType().cast<ShapedType>();
387     Type elementTy = inputTy.getElementType();
388 
389     Attribute constantAttr;
390     if (elementTy.isa<FloatType>())
391       constantAttr = rewriter.getFloatAttr(elementTy, 0.0);
392     else if (elementTy.isa<IntegerType>() && !op.quantization_info())
393       constantAttr = rewriter.getIntegerAttr(elementTy, 0);
394     else if (elementTy.isa<IntegerType>() && op.quantization_info()) {
395       auto value = op.quantization_info().getValue().input_zp().getValue();
396       constantAttr = rewriter.getIntegerAttr(elementTy, value.getZExtValue());
397     }
398 
399     if (!constantAttr) {
400       return rewriter.notifyMatchFailure(
401           op,
402           "tosa.pad to linalg lowering encountered an unknown element type");
403     }
404 
405     auto denseAttr = DenseElementsAttr::get(
406         RankedTensorType::get({}, elementTy), constantAttr);
407     auto constantVal = rewriter.create<tosa::ConstOp>(
408         op.getLoc(), denseAttr.getType(), denseAttr);
409 
410     rewriter.replaceOpWithNewOp<tosa::PadOp>(
411         op, op.getType(), ValueRange{input, padding, constantVal},
412         op->getAttrs());
413     return success();
414   }
415 };
416 
417 void PadOp::getCanonicalizationPatterns(RewritePatternSet &results,
418                                         MLIRContext *context) {
419   results.add<MaterializePadValue>(context);
420 }
421 
422 struct MaxPool2dIsNoOp : public OpRewritePattern<tosa::MaxPool2dOp> {
423   using OpRewritePattern::OpRewritePattern;
424 
425   LogicalResult matchAndRewrite(tosa::MaxPool2dOp op,
426                                 PatternRewriter &rewriter) const override {
427     Value input = op.input();
428     Value output = op.output();
429     ShapedType inputType = input.getType().cast<ShapedType>();
430     ShapedType outputType = output.getType().cast<ShapedType>();
431 
432     if (!inputType.hasStaticShape() || !outputType.hasStaticShape()) {
433       return failure();
434     }
435 
436     // If the output and input shapes are 1x1, then this is a no op.
437     ArrayRef<int64_t> outputShape = outputType.getShape();
438     if (outputShape[1] != 1 || outputShape[2] != 1) {
439       return failure();
440     }
441 
442     ArrayRef<int64_t> inputShape = inputType.getShape();
443     if (inputShape[1] != 1 || inputShape[2] != 1) {
444       return failure();
445     }
446 
447     rewriter.replaceOp(op, input);
448     return success();
449   }
450 };
451 
452 void MaxPool2dOp::getCanonicalizationPatterns(RewritePatternSet &results,
453                                               MLIRContext *context) {
454   results.add<MaxPool2dIsNoOp>(context);
455 }
456 
457 struct ClampIsNoOp : public OpRewritePattern<tosa::ClampOp> {
458   using OpRewritePattern::OpRewritePattern;
459 
460   LogicalResult matchAndRewrite(tosa::ClampOp op,
461                                 PatternRewriter &rewriter) const override {
462     Value input = op.input();
463     auto inputType = op.input().getType().template dyn_cast<RankedTensorType>();
464     auto inputElementType = inputType.getElementType();
465 
466     if (!inputType.hasStaticShape()) {
467       return failure();
468     }
469 
470     if (inputElementType.isF32()) {
471       auto minClamp = op.min_fp();
472       auto maxClamp = op.max_fp();
473       bool isMin = (minClamp.isLargest() || minClamp.isInfinity()) &&
474                    minClamp.isNegative();
475       bool isMax = (maxClamp.isLargest() || maxClamp.isInfinity()) &&
476                    !maxClamp.isNegative();
477 
478       if (isMin && isMax) {
479         rewriter.replaceOp(op, input);
480         return success();
481       }
482       return failure();
483     }
484 
485     if (inputElementType.isUnsignedInteger()) {
486       int64_t minClamp = op.min_int();
487       int64_t maxClamp = op.max_int();
488 
489       int64_t intMin =
490           APInt::getMinValue(inputElementType.getIntOrFloatBitWidth())
491               .getZExtValue();
492       int64_t intMax =
493           APInt::getMaxValue(inputElementType.getIntOrFloatBitWidth())
494               .getZExtValue();
495 
496       if (minClamp <= intMin && maxClamp >= intMax) {
497         rewriter.replaceOp(op, input);
498         return success();
499       }
500       return failure();
501     }
502 
503     if (inputElementType.isa<IntegerType>()) {
504       int64_t minClamp = op.min_int();
505       int64_t maxClamp = op.max_int();
506 
507       int64_t intMin =
508           APInt::getSignedMinValue(inputElementType.getIntOrFloatBitWidth())
509               .getSExtValue();
510       int64_t intMax =
511           APInt::getSignedMaxValue(inputElementType.getIntOrFloatBitWidth())
512               .getSExtValue();
513 
514       if (minClamp <= intMin && maxClamp >= intMax) {
515         rewriter.replaceOp(op, input);
516         return success();
517       }
518       return failure();
519     }
520 
521     return failure();
522   }
523 };
524 
525 struct ClampClampOptimization : public OpRewritePattern<tosa::ClampOp> {
526   using OpRewritePattern<tosa::ClampOp>::OpRewritePattern;
527 
528   LogicalResult matchAndRewrite(tosa::ClampOp op,
529                                 PatternRewriter &rewriter) const override {
530     Value input = op.input();
531 
532     Operation *definingOp = input.getDefiningOp();
533     if (!definingOp)
534       return failure();
535 
536     if (tosa::ClampOp clampOp = dyn_cast<tosa::ClampOp>(definingOp)) {
537       auto minFp = std::max(op.min_fp(), clampOp.min_fp()).convertToFloat();
538       auto maxFp = std::min(op.max_fp(), clampOp.max_fp()).convertToFloat();
539 
540       auto minInt = std::max(op.min_int(), clampOp.min_int());
541       auto maxInt = std::min(op.max_int(), clampOp.max_int());
542 
543       rewriter.replaceOpWithNewOp<tosa::ClampOp>(
544           op, op.getType(), clampOp.input(), rewriter.getI64IntegerAttr(minInt),
545           rewriter.getI64IntegerAttr(maxInt), rewriter.getF32FloatAttr(minFp),
546           rewriter.getF32FloatAttr(maxFp));
547       return success();
548     }
549 
550     return failure();
551   }
552 };
553 
554 void ClampOp::getCanonicalizationPatterns(RewritePatternSet &results,
555                                           MLIRContext *context) {
556   results.add<ClampIsNoOp>(context);
557   results.add<ClampClampOptimization>(context);
558 }
559 
560 //===----------------------------------------------------------------------===//
561 // Operator Folders.
562 //===----------------------------------------------------------------------===//
563 
564 OpFoldResult CastOp::fold(ArrayRef<Attribute> operands) {
565   if (input().getType() == getType())
566     return input();
567   return {};
568 }
569 
570 OpFoldResult ConstOp::fold(ArrayRef<Attribute> operands) {
571   assert(operands.empty() && "constant has no operands");
572   return valueAttr();
573 }
574 
575 #define REDUCE_FOLDER(OP)                                                      \
576   OpFoldResult OP::fold(ArrayRef<Attribute> operands) {                        \
577     ShapedType inputTy = input().getType().cast<ShapedType>();                 \
578     if (!inputTy.hasRank())                                                    \
579       return {};                                                               \
580     if (inputTy.getDimSize(axis()) == 1)                                       \
581       return input();                                                          \
582     return {};                                                                 \
583   }
584 
585 REDUCE_FOLDER(ReduceAllOp)
586 REDUCE_FOLDER(ReduceAnyOp)
587 REDUCE_FOLDER(ReduceMaxOp)
588 REDUCE_FOLDER(ReduceMinOp)
589 REDUCE_FOLDER(ReduceProdOp)
590 REDUCE_FOLDER(ReduceSumOp)
591 #undef REDUCE_FOLDER
592 
593 OpFoldResult ReshapeOp::fold(ArrayRef<Attribute> operands) {
594   auto inputTy = input1().getType().dyn_cast<RankedTensorType>();
595   auto outputTy = getType().dyn_cast<RankedTensorType>();
596 
597   if (!inputTy || !outputTy || inputTy != outputTy)
598     return {};
599   return input1();
600 }
601 
602 OpFoldResult PadOp::fold(ArrayRef<Attribute> operands) {
603   // If the pad is all zeros we can fold this operation away.
604   if (operands[1]) {
605     auto densePad = operands[1].cast<DenseElementsAttr>();
606     if (densePad.isSplat() && densePad.getSplatValue<APInt>().isZero()) {
607       return input1();
608     }
609   }
610 
611   return {};
612 }
613 
614 OpFoldResult SliceOp::fold(ArrayRef<Attribute> operands) {
615   auto inputTy = input().getType().dyn_cast<RankedTensorType>();
616   auto outputTy = getType().dyn_cast<RankedTensorType>();
617 
618   if (!inputTy || !outputTy || inputTy != outputTy)
619     return {};
620   if (inputTy.hasStaticShape())
621     return input();
622 
623   return {};
624 }
625 
626 OpFoldResult tosa::SelectOp::fold(ArrayRef<Attribute> operands) {
627   if (on_true() == on_false())
628     return on_true();
629 
630   auto predicate = operands[0].dyn_cast_or_null<DenseIntElementsAttr>();
631   if (!predicate)
632     return {};
633 
634   if (!predicate.isSplat())
635     return {};
636   return predicate.getSplatValue<APInt>().getBoolValue() ? on_true()
637                                                          : on_false();
638 }
639 
640 OpFoldResult TileOp::fold(ArrayRef<Attribute> operands) {
641   bool allOnes = true;
642   for (Attribute val : multiples().getValue()) {
643     allOnes = allOnes && val.cast<IntegerAttr>().getValue().getSExtValue() == 1;
644   }
645 
646   if (allOnes && input1().getType() == getType())
647     return input1();
648   return {};
649 }
650 
651 OpFoldResult TransposeOp::fold(ArrayRef<Attribute> operands) {
652   if (!operands[1])
653     return {};
654 
655   // Transposing splat values just means reshaping.
656   if (auto input = operands[0].dyn_cast_or_null<DenseElementsAttr>()) {
657     if (input.isSplat())
658       return input.reshape(getType().cast<ShapedType>());
659   }
660 
661   auto perms = llvm::to_vector<6>(llvm::map_range(
662       operands[1].cast<DenseIntElementsAttr>().getValues<APInt>(),
663       [](const APInt &val) { return val.getSExtValue(); }));
664 
665   if (llvm::equal(llvm::seq<int64_t>(0, perms.size()), perms) &&
666       input1().getType() == getType())
667     return input1();
668   return {};
669 }
670 
671 //===----------------------------------------------------------------------===//
672 // TOSA Operator Verifiers.
673 //===----------------------------------------------------------------------===//
674 
675 template <typename T>
676 static LogicalResult verifyConvOp(T op) {
677   // All TOSA conv ops have an input() and weight().
678   auto inputType = op.input().getType().template dyn_cast<RankedTensorType>();
679   auto weightType = op.weight().getType().template dyn_cast<RankedTensorType>();
680 
681   // Must be ranked tensor types
682   if (!inputType) {
683     op.emitOpError("expect a ranked tensor for input, got ") << op.input();
684     return failure();
685   }
686   if (!weightType) {
687     op.emitOpError("expect a ranked tensor for weight, got ") << op.weight();
688     return failure();
689   }
690 
691   auto inputEType = inputType.getElementType();
692   auto weightEType = weightType.getElementType();
693 
694   bool inputIsQuant = !inputEType.template isa<FloatType>();
695   bool weightIsQuant = !weightEType.template isa<FloatType>();
696 
697   // Either both must be quantized or both unquantized.
698   if (inputIsQuant != weightIsQuant) {
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   // Quantized type must have constructed the quantizationattr, and unquantized
706   // types should not have a quantizationattr.
707   if ((inputIsQuant && !op.quantization_info()) ||
708       (!inputIsQuant && op.quantization_info())) {
709     op.emitOpError("quantizationattr is required for quantized type, and not "
710                    "allowed for float type");
711     return failure();
712   }
713 
714   return success();
715 }
716 
717 LogicalResult tosa::AvgPool2dOp::verify() {
718   auto inputETy = input().getType().cast<ShapedType>().getElementType();
719   auto resultETy = getType().cast<ShapedType>().getElementType();
720 
721   if (auto quantType = inputETy.dyn_cast<mlir::quant::UniformQuantizedType>())
722     inputETy = quantType.getStorageType();
723 
724   if (auto quantType = resultETy.dyn_cast<mlir::quant::UniformQuantizedType>())
725     resultETy = quantType.getStorageType();
726 
727   if (inputETy.isF32() && resultETy.isF32())
728     return success();
729   if (inputETy.isInteger(8) && resultETy.isInteger(8))
730     return success();
731   if (inputETy.isInteger(16) && resultETy.isInteger(16))
732     return success();
733 
734   return emitOpError("input/output element types are incompatible.");
735 }
736 
737 //===----------------------------------------------------------------------===//
738 // TOSA Operator Quantization Builders.
739 //===----------------------------------------------------------------------===//
740 
741 /// This builder is called on all convolution operators except TransposeConv,
742 /// which has specialized output shape semantics. The builder also defines the
743 /// bitwidth of the output given the bit width of the input & weight content.
744 static void buildConvOpWithQuantInfo(OpBuilder &builder, OperationState &result,
745                                      Type outputType, Value input, Value weight,
746                                      Value bias, ArrayAttr pad,
747                                      ArrayAttr stride, ArrayAttr dilation) {
748 
749   result.addOperands({input, weight, bias});
750   result.addAttribute("pad", pad);
751   result.addAttribute("stride", stride);
752   result.addAttribute("dilation", dilation);
753 
754   auto quantAttr = buildConvOpQuantizationAttr(builder, input, weight);
755   if (quantAttr) {
756     result.addAttribute("quantization_info", quantAttr);
757     result.addTypes(
758         buildConvOpResultTypeInfo(builder, outputType, input, weight));
759   } else {
760     result.addTypes(outputType);
761   }
762 }
763 
764 /// Handles tosa.transpose_conv2d which has outpad and output shape attributes.
765 static void
766 buildTransConvOpWithQuantInfo(OpBuilder &builder, OperationState &result,
767                               Type outputType, Value input, Value weight,
768                               Value bias, ArrayAttr outpad, ArrayAttr stride,
769                               ArrayAttr dilation, ArrayAttr outputShape) {
770   result.addOperands({input, weight, bias});
771   result.addAttribute("out_pad", outpad);
772   result.addAttribute("stride", stride);
773   result.addAttribute("dilation", dilation);
774   result.addAttribute("out_shape", outputShape);
775   auto quantAttr = ::buildConvOpQuantizationAttr(builder, input, weight);
776 
777   if (quantAttr) {
778     result.addAttribute("quantization_info", quantAttr);
779     result.addTypes(
780         buildConvOpResultTypeInfo(builder, outputType, input, weight));
781   } else {
782     result.addTypes(outputType);
783   }
784 }
785 
786 /// The tosa.fully_connected op has its own builder as it does not have
787 /// strides/dilation/padding.
788 static void buildFCOpWithQuantInfo(OpBuilder &builder, OperationState &result,
789                                    Type outputType, Value input, Value weight,
790                                    Value bias) {
791 
792   result.addOperands({input, weight, bias});
793   auto quantAttr = ::buildConvOpQuantizationAttr(builder, input, weight);
794   if (quantAttr) {
795     result.addAttribute("quantization_info", quantAttr);
796     result.addTypes(
797         buildConvOpResultTypeInfo(builder, outputType, input, weight));
798   } else {
799     result.addTypes(outputType);
800   }
801 }
802 
803 /// The tosa.matmul op is also intended to be generated where a fully_connected
804 /// op must be constructed where the weight is not a constant. In this case,
805 /// the fully_connected op must be expressed using matmul.
806 /// TODO: Add link to the leglization document explaining this.
807 static void buildMatMulOpWithQuantInfo(OpBuilder &builder,
808                                        OperationState &result, Type outputType,
809                                        Value a, Value b) {
810   result.addOperands({a, b});
811   auto quantAttr = ::buildMatMulOpQuantizationAttr(builder, a, b);
812 
813   if (quantAttr) {
814     result.addAttribute("quantization_info", quantAttr);
815 
816     auto inputType = a.getType().dyn_cast<ShapedType>();
817     assert(inputType && "Input must be a shaped tensor type!");
818 
819     auto inputQType = inputType.getElementType()
820                           .dyn_cast<mlir::quant::UniformQuantizedType>();
821     assert(inputQType && "Tensor must have quantized datatype!");
822 
823     unsigned inputBits = inputQType.getStorageTypeIntegralWidth();
824 
825     auto outputShapedType = outputType.dyn_cast<ShapedType>();
826     assert(outputShapedType && "Output must be a shaped type");
827 
828     IntegerType accElementType;
829     if (inputBits == 16)
830       accElementType = builder.getIntegerType(48);
831     else
832       accElementType = builder.getI32Type();
833     auto accType = outputShapedType.clone(accElementType);
834     result.addTypes(accType);
835   } else {
836     result.addTypes(outputType);
837   }
838 }
839 
840 /// Both the tosa.avg_pool2d and unary ops use the same UnaruOpQuantizationAttr
841 /// but avg_pool operator has its own builder as it has additional parameters
842 /// not part of the unary ops.
843 static void buildAvgPool2dOpWithQuantInfo(OpBuilder &builder,
844                                           OperationState &result,
845                                           Type outputType, Value input,
846                                           ArrayAttr kernel, ArrayAttr stride,
847                                           ArrayAttr pad) {
848   result.addOperands(input);
849   result.addAttribute("kernel", kernel);
850   result.addAttribute("stride", stride);
851   result.addAttribute("pad", pad);
852   auto quantAttr = buildUnaryOpQuantizationAttr(builder, input, outputType);
853   if (quantAttr)
854     result.addAttribute("quantization_info", quantAttr);
855   result.types.push_back(outputType);
856 }
857 
858 /// This builder is called on single-parameter unary operators that have scale
859 /// relationship between their input and output, expressed by the
860 /// UnaryOpQuantizationAttr.
861 static void buildUnaryOpWithQuantInfo(OpBuilder &builder,
862                                       OperationState &result, Type outputType,
863                                       Value input) {
864   result.addOperands(input);
865   auto quantAttr = buildUnaryOpQuantizationAttr(builder, input, outputType);
866   if (quantAttr)
867     result.addAttribute("quantization_info", quantAttr);
868   result.types.push_back(outputType);
869 }
870 
871 /// This builder is called on TOSA pad operator that needs to create its own
872 /// OptionalAttr quantization_attr parameter to scale the padding values
873 /// correctly. No pad_const is interpreted as zero-padding.
874 static void buildPadOpWithQuantInfo(OpBuilder &builder, OperationState &result,
875                                     Type outputType, Value input,
876                                     Value paddings) {
877   result.addOperands({input, paddings});
878   auto quantAttr = buildPadOpQuantizationAttr(builder, input);
879   if (quantAttr)
880     result.addAttribute("quantization_info", quantAttr);
881   result.types.push_back(outputType);
882 }
883 
884 /// This builder is called on TOSA pad operator when an explicit pad_const
885 /// value is passed in. It also optionally constructs quantization_attr.
886 static void buildExplicitValuePadOpWithQuantInfo(OpBuilder &builder,
887                                                  OperationState &result,
888                                                  Type outputType, Value input,
889                                                  Value paddings,
890                                                  Value padConst) {
891   result.addOperands({input, paddings, padConst});
892   auto quantAttr = buildPadOpQuantizationAttr(builder, input);
893   if (quantAttr)
894     result.addAttribute("quantization_info", quantAttr);
895   result.types.push_back(outputType);
896 }
897 
898 //===----------------------------------------------------------------------===//
899 // TOSA Operator Return Type Inference.
900 //===----------------------------------------------------------------------===//
901 
902 static void getI64Values(ArrayAttr arrayAttr, SmallVector<int64_t> &values) {
903   for (auto it : arrayAttr) {
904     values.push_back(it.cast<IntegerAttr>().getValue().getSExtValue());
905   }
906 }
907 
908 static void getF64Values(ArrayAttr arrayAttr, SmallVector<double> &values) {
909   for (auto it : arrayAttr) {
910     values.push_back(it.cast<FloatAttr>().getValueAsDouble());
911   }
912 }
913 
914 LogicalResult tosa::ArgMaxOp::inferReturnTypeComponents(
915     MLIRContext *context, ::llvm::Optional<Location> location,
916     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
917     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
918   ShapeAdaptor inputShape = operands.getShape(0);
919   IntegerAttr axis = attributes.get("axis").cast<IntegerAttr>();
920   int32_t axisVal = axis.getValue().getSExtValue();
921 
922   if (!inputShape.hasRank()) {
923     inferredReturnShapes.push_back(ShapedTypeComponents());
924     return success();
925   }
926 
927   SmallVector<int64_t> outShape;
928   outShape.reserve(inputShape.getRank() - 1);
929   for (int i = 0, s = inputShape.getRank(); i < s; i++) {
930     if (i == axisVal)
931       continue;
932     outShape.push_back(inputShape.getDimSize(i));
933   }
934 
935   inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
936   return success();
937 }
938 
939 LogicalResult tosa::ConcatOp::inferReturnTypeComponents(
940     MLIRContext *context, ::llvm::Optional<Location> location,
941     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
942     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
943   // Infer all dimension sizes by reducing based on inputs.
944   int32_t axis =
945       attributes.get("axis").cast<IntegerAttr>().getValue().getSExtValue();
946   llvm::SmallVector<int64_t> outputShape;
947   bool hasRankedInput = false;
948   for (auto operand : operands) {
949     ShapeAdaptor operandShape = operands.getShape(operand);
950     if (!operandShape.hasRank())
951       continue;
952 
953     // Copy the Operand's rank.
954     if (!hasRankedInput)
955       outputShape.resize(operandShape.getRank(), ShapedType::kDynamicSize);
956 
957     // Copy shapes until the dim is non-dynamic.
958     for (int i = 0, s = operandShape.getRank(); i < s; i++) {
959       if (i == axis || operandShape.isDynamicDim(i))
960         continue;
961       if (outputShape[i] == ShapedType::kDynamicSize)
962         outputShape[i] = operandShape.getDimSize(i);
963       if (outputShape[i] != operandShape.getDimSize(i))
964         return failure();
965     }
966 
967     hasRankedInput = true;
968   }
969 
970   if (!hasRankedInput) {
971     inferredReturnShapes.push_back(ShapedTypeComponents());
972     return success();
973   }
974 
975   // Determine the dimension size along the concatenation axis.
976   int concatDimSize = 0;
977   for (auto operand : operands) {
978     ShapeAdaptor operandShape = operands.getShape(operand);
979 
980     // We need to know the length of the concatenation axis of all inputs to
981     // determine the dimension size of the output shape.
982     if (!operandShape.hasRank() || operandShape.isDynamicDim(axis)) {
983       concatDimSize = ShapedType::kDynamicSize;
984       break;
985     }
986 
987     concatDimSize += operandShape.getDimSize(axis);
988   }
989 
990   outputShape[axis] = concatDimSize;
991 
992   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
993   return success();
994 }
995 
996 LogicalResult tosa::FullyConnectedOp::inferReturnTypeComponents(
997     MLIRContext *context, ::llvm::Optional<Location> location,
998     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
999     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1000   ShapeAdaptor inputShape = operands.getShape(0);
1001   ShapeAdaptor weightShape = operands.getShape(1);
1002   ShapeAdaptor biasShape = operands.getShape(2);
1003 
1004   // All shapes are dynamic.
1005   SmallVector<int64_t> outShape;
1006   outShape.resize(2, ShapedType::kDynamicSize);
1007 
1008   if (inputShape.hasRank()) {
1009     outShape[0] = inputShape.getDimSize(0);
1010   }
1011 
1012   if (weightShape.hasRank()) {
1013     outShape[1] = weightShape.getDimSize(0);
1014   }
1015 
1016   if (biasShape.hasRank()) {
1017     outShape[1] = outShape[1] == ShapedType::kDynamicSize
1018                       ? biasShape.getDimSize(0)
1019                       : outShape[1];
1020   }
1021 
1022   inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
1023   return success();
1024 }
1025 
1026 LogicalResult FullyConnectedOp::verify() { return verifyConvOp(*this); }
1027 
1028 LogicalResult tosa::MatMulOp::inferReturnTypeComponents(
1029     MLIRContext *context, ::llvm::Optional<Location> location,
1030     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1031     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1032   ShapeAdaptor lhsShape = operands.getShape(0);
1033   ShapeAdaptor rhsShape = operands.getShape(1);
1034 
1035   // All shapes are dynamic.
1036   SmallVector<int64_t> outShape;
1037   outShape.resize(3, ShapedType::kDynamicSize);
1038 
1039   if (lhsShape.hasRank()) {
1040     outShape[0] = lhsShape.getDimSize(0);
1041     outShape[1] = lhsShape.getDimSize(1);
1042   }
1043 
1044   if (rhsShape.hasRank()) {
1045     outShape[0] = outShape[0] == ShapedType::kDynamicSize
1046                       ? rhsShape.getDimSize(0)
1047                       : outShape[0];
1048     outShape[2] = rhsShape.getDimSize(2);
1049   }
1050 
1051   inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
1052   return success();
1053 }
1054 
1055 LogicalResult tosa::PadOp::inferReturnTypeComponents(
1056     MLIRContext *context, ::llvm::Optional<Location> location,
1057     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1058     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1059   ShapeAdaptor inputShape = operands.getShape(0);
1060   ShapeAdaptor paddingShape = operands.getShape(1);
1061   SmallVector<int64_t> outputShape;
1062 
1063   // If both inputs have unknown shape, we cannot determine the shape of the
1064   // output.
1065   if (!inputShape.hasRank() && !paddingShape.hasRank()) {
1066     inferredReturnShapes.push_back(ShapedTypeComponents());
1067     return success();
1068   }
1069 
1070   // If the input rank is unknown we can info the output rank using the padding
1071   // shape's first dim.
1072   if (!inputShape.hasRank()) {
1073     if (paddingShape.isDynamicDim(0)) {
1074       inferredReturnShapes.push_back(ShapedTypeComponents());
1075       return success();
1076     }
1077 
1078     outputShape.resize(paddingShape.getDimSize(0), ShapedType::kDynamicSize);
1079     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1080     return success();
1081   }
1082 
1083   DenseIntElementsAttr paddings;
1084   // If the paddings value is not a constant, all dimensions must be dynamic.
1085   if (!matchPattern(operands[1], m_Constant(&paddings))) {
1086     outputShape.resize(inputShape.getRank(), ShapedType::kDynamicSize);
1087     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1088     return success();
1089   }
1090 
1091   SmallVector<int64_t> paddingValues;
1092   for (auto val : paddings) {
1093     paddingValues.push_back(val.getSExtValue());
1094   }
1095 
1096   outputShape.reserve(inputShape.getRank());
1097   for (int i = 0, s = inputShape.getRank(); i < s; i++) {
1098     if (inputShape.isDynamicDim(i)) {
1099       outputShape.push_back(ShapedType::kDynamicSize);
1100       continue;
1101     }
1102 
1103     outputShape.push_back(inputShape.getDimSize(i) + paddingValues[i * 2] +
1104                           paddingValues[i * 2 + 1]);
1105   }
1106 
1107   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1108   return success();
1109 }
1110 
1111 LogicalResult tosa::SliceOp::inferReturnTypeComponents(
1112     MLIRContext *context, ::llvm::Optional<Location> location,
1113     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1114     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1115   ArrayAttr sizes = SliceOpAdaptor(operands, attributes).size();
1116   SmallVector<int64_t> outputShape;
1117   outputShape.reserve(sizes.size());
1118   for (auto val : sizes) {
1119     outputShape.push_back(val.cast<IntegerAttr>().getValue().getSExtValue());
1120   }
1121 
1122   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1123   return success();
1124 }
1125 
1126 LogicalResult tosa::TableOp::inferReturnTypeComponents(
1127     MLIRContext *context, ::llvm::Optional<Location> location,
1128     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1129     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1130   ShapeAdaptor inputShape = operands.getShape(0);
1131 
1132   if (!inputShape.hasRank()) {
1133     inferredReturnShapes.push_back(ShapedTypeComponents());
1134     return success();
1135   }
1136 
1137   inferredReturnShapes.resize(1);
1138   inputShape.getDims(inferredReturnShapes[0]);
1139   return success();
1140 }
1141 
1142 LogicalResult tosa::TileOp::inferReturnTypeComponents(
1143     MLIRContext *context, ::llvm::Optional<Location> location,
1144     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1145     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1146   TileOpAdaptor adaptor(operands, attributes);
1147   ArrayAttr multiples = adaptor.multiples();
1148   ShapeAdaptor inputShape = operands.getShape(0);
1149   SmallVector<int64_t> outputShape;
1150   if (!inputShape.hasRank()) {
1151     outputShape.resize(multiples.size(), ShapedType::kDynamicSize);
1152     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1153     return success();
1154   }
1155 
1156   // We need the multiple values to determine the output shape.
1157   SmallVector<int64_t> multipleValues;
1158   multipleValues.reserve(multiples.size());
1159   for (auto val : multiples) {
1160     multipleValues.push_back(val.cast<IntegerAttr>().getValue().getSExtValue());
1161   }
1162 
1163   // Any non dynamic dimension can be multiplied to a known size.
1164   outputShape.reserve(multiples.size());
1165   for (int i = 0, s = inputShape.getRank(); i < s; i++) {
1166     int dim = inputShape.getDimSize(i);
1167     if (dim != ShapedType::kDynamicSize)
1168       dim *= multipleValues[i];
1169     outputShape.push_back(dim);
1170   }
1171 
1172   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1173   return success();
1174 }
1175 
1176 LogicalResult tosa::ReshapeOp::inferReturnTypeComponents(
1177     MLIRContext *context, ::llvm::Optional<Location> location,
1178     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1179     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1180   ReshapeOpAdaptor adaptor(operands, attributes);
1181   ShapeAdaptor inputShape = operands.getShape(0);
1182 
1183   ArrayAttr newShape = adaptor.new_shape();
1184   llvm::SmallVector<int64_t> newShapeValue;
1185   getI64Values(newShape, newShapeValue);
1186 
1187   // We cannot infer from the total number of elements so we must take the
1188   // shape attribute as exact.
1189   if (!inputShape.hasRank() || !inputShape.hasStaticShape()) {
1190     inferredReturnShapes.push_back(ShapedTypeComponents(newShapeValue));
1191     return success();
1192   }
1193 
1194   // Determine the number of elements covered by the slice of all static
1195   // dimensions. This allows us to infer the length of the remaining dynamic
1196   // dimension.
1197   int64_t numElements = inputShape.getNumElements();
1198   int64_t staticMul = 1;
1199   for (auto val : newShapeValue) {
1200     if (val != ShapedType::kDynamicSize) {
1201       staticMul *= val;
1202     }
1203   }
1204 
1205   // Determine the length of the dynamic dimension.
1206   for (auto &val : newShapeValue) {
1207     if (val == ShapedType::kDynamicSize)
1208       val = numElements / staticMul;
1209   }
1210 
1211   inferredReturnShapes.push_back(ShapedTypeComponents(newShapeValue));
1212   return success();
1213 }
1214 
1215 LogicalResult tosa::TransposeOp::inferReturnTypeComponents(
1216     MLIRContext *context, ::llvm::Optional<Location> location,
1217     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1218     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1219   ShapeAdaptor inputShape = operands.getShape(0);
1220   ShapeAdaptor permsShape = operands.getShape(1);
1221 
1222   // If input rank and permutation length is unknown, the output rank is
1223   // unknown.
1224   if (!inputShape.hasRank() || !permsShape.hasRank() ||
1225       permsShape.isDynamicDim(0)) {
1226     inferredReturnShapes.push_back(ShapedTypeComponents());
1227     return success();
1228   }
1229 
1230   // This would imply the number of permutations does not match the rank of the
1231   // input which is illegal.
1232   if (permsShape.getDimSize(0) != inputShape.getRank()) {
1233     return failure();
1234   }
1235 
1236   // Without the input dims we cannot determine the output dim sizes but we
1237   // can determine the output rank.
1238   SmallVector<int64_t> outputShape;
1239   if (!inputShape.hasRank()) {
1240     outputShape.resize(permsShape.getDimSize(0), ShapedType::kDynamicSize);
1241     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1242     return success();
1243   }
1244 
1245   // Rank-0 means no permutations matter.
1246   if (inputShape.getRank() == 0) {
1247     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1248     return success();
1249   }
1250 
1251   // Check whether the input dimensions are all the same.
1252   bool allTheSame = true;
1253   for (int i = 1, s = inputShape.getRank(); i < s; i++) {
1254     if (inputShape.getDimSize(0) != inputShape.getDimSize(i)) {
1255       allTheSame = false;
1256       break;
1257     }
1258   }
1259 
1260   // If all of the input dimensions are the same we don't care about the
1261   // permutation.
1262   if (allTheSame) {
1263     outputShape.resize(inputShape.getRank(), inputShape.getDimSize(0));
1264     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1265     return success();
1266   }
1267 
1268   outputShape.resize(inputShape.getRank(), ShapedType::kDynamicSize);
1269   // If the permuations are a constant we can directly determine the output
1270   // shape.
1271   if (ShapeAdaptor permShape = operands.getValueAsShape(1)) {
1272     outputShape.reserve(inputShape.getRank());
1273     for (int i = 0, s = inputShape.getRank(); i < s; i++) {
1274       outputShape[i] = inputShape.getDimSize(permShape.getDimSize(i));
1275     }
1276   }
1277 
1278   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1279   return success();
1280 }
1281 
1282 LogicalResult tosa::GatherOp::inferReturnTypeComponents(
1283     MLIRContext *context, ::llvm::Optional<Location> location,
1284     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1285     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1286   llvm::SmallVector<int64_t> outputShape;
1287   outputShape.resize(3, ShapedType::kDynamicSize);
1288 
1289   ShapeAdaptor valuesShape = operands.getShape(0);
1290   if (valuesShape.hasRank()) {
1291     outputShape[0] = valuesShape.getDimSize(0);
1292     outputShape[2] = valuesShape.getDimSize(2);
1293   }
1294 
1295   ShapeAdaptor indicesShape = operands.getShape(1);
1296   if (indicesShape.hasRank()) {
1297     if (outputShape[0] == ShapedType::kDynamicSize)
1298       outputShape[0] = indicesShape.getDimSize(0);
1299     if (outputShape[1] == ShapedType::kDynamicSize)
1300       outputShape[1] = indicesShape.getDimSize(1);
1301   }
1302 
1303   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1304   return success();
1305 }
1306 
1307 LogicalResult tosa::ResizeOp::inferReturnTypeComponents(
1308     MLIRContext *context, ::llvm::Optional<Location> location,
1309     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1310     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1311   ResizeOpAdaptor adaptor(operands, attributes);
1312   llvm::SmallVector<int64_t, 4> outputShape;
1313   outputShape.resize(4, ShapedType::kDynamicSize);
1314 
1315   int32_t inHeight = ShapedType::kDynamicSize;
1316   int32_t inWidth = ShapedType::kDynamicSize;
1317 
1318   ShapeAdaptor inputShape = operands.getShape(adaptor.input());
1319   if (inputShape.hasRank()) {
1320     outputShape[0] = inputShape.getDimSize(0);
1321     outputShape[3] = inputShape.getDimSize(3);
1322 
1323     inHeight = inputShape.getDimSize(1);
1324     inWidth = inputShape.getDimSize(2);
1325   }
1326 
1327   int32_t shift = adaptor.shift();
1328   llvm::SmallVector<int64_t> newShape;
1329   getI64Values(adaptor.output_size(), newShape);
1330   outputShape[1] = newShape[0];
1331   outputShape[2] = newShape[1];
1332 
1333   llvm::SmallVector<int64_t> strideInt;
1334   llvm::SmallVector<int64_t> offsetInt;
1335   llvm::SmallVector<double> strideFp;
1336   llvm::SmallVector<double> offsetFp;
1337   getI64Values(adaptor.offset(), offsetInt);
1338   getF64Values(adaptor.offset_fp(), offsetFp);
1339   getI64Values(adaptor.stride(), strideInt);
1340   getF64Values(adaptor.stride_fp(), strideFp);
1341 
1342   // If we have a 0 zero in integers we know that the resize indexing needs to
1343   // be performed in floating point. Use the floating point varient to compute
1344   // the resize shape.
1345   bool fpMode = strideInt[0] == 0;
1346 
1347   // We can compute the output shape if attribute specifies unknown dimensions
1348   // based on the offset and stride. If we perfectly line up to the last index
1349   // we need to round up the size to include it.
1350   if (outputShape[1] == ShapedType::kDynamicSize && inHeight >= 0 && fpMode) {
1351     float sizeFp = (inHeight - offsetFp[0] - 1) / strideFp[0];
1352     float round = std::floor(sizeFp) == sizeFp ? 1 : 0;
1353     outputShape[1] = std::ceil(sizeFp) + round;
1354   }
1355 
1356   if (outputShape[2] == ShapedType::kDynamicSize && inWidth >= 0 && fpMode) {
1357     float sizeFp = (inWidth - offsetFp[1] - 1) / strideFp[1];
1358     float round = std::floor(sizeFp) == sizeFp ? 1 : 0;
1359     outputShape[2] = std::ceil(sizeFp) + round;
1360   }
1361 
1362   if (outputShape[1] == ShapedType::kDynamicSize && inHeight >= 0 && !fpMode) {
1363     int64_t size = (inHeight - 1);
1364     size = ((size << shift) - offsetInt[0]) / strideInt[0];
1365     outputShape[1] = size + 1;
1366   }
1367 
1368   if (outputShape[2] == ShapedType::kDynamicSize && inWidth >= 0 && !fpMode) {
1369     int64_t size = (inWidth - 1);
1370     size = ((size << shift) - offsetInt[1]) / strideInt[1];
1371     outputShape[2] = size + 1;
1372   }
1373 
1374   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1375   return success();
1376 }
1377 
1378 LogicalResult tosa::ScatterOp::inferReturnTypeComponents(
1379     MLIRContext *context, ::llvm::Optional<Location> location,
1380     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1381     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1382   llvm::SmallVector<int64_t> outputShape;
1383   outputShape.resize(3, ShapedType::kDynamicSize);
1384 
1385   ShapeAdaptor valuesInShape = operands.getShape(0);
1386   if (valuesInShape.hasRank()) {
1387     outputShape[0] = valuesInShape.getDimSize(0);
1388     outputShape[1] = valuesInShape.getDimSize(1);
1389     outputShape[2] = valuesInShape.getDimSize(2);
1390   }
1391 
1392   ShapeAdaptor indicesShape = operands.getShape(1);
1393   if (indicesShape.hasRank()) {
1394     if (outputShape[0] == ShapedType::kDynamicSize)
1395       outputShape[0] = indicesShape.getDimSize(0);
1396   }
1397 
1398   ShapeAdaptor inputShape = operands.getShape(2);
1399   if (inputShape.hasRank()) {
1400     if (outputShape[0] == ShapedType::kDynamicSize)
1401       outputShape[0] = inputShape.getDimSize(0);
1402     if (outputShape[2] == ShapedType::kDynamicSize)
1403       outputShape[2] = inputShape.getDimSize(2);
1404   }
1405 
1406   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1407   return success();
1408 }
1409 
1410 static LogicalResult ReduceInferReturnTypes(
1411     ShapeAdaptor operandShape, IntegerAttr axis,
1412     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1413   if (!operandShape.hasRank()) {
1414     inferredReturnShapes.push_back(ShapedTypeComponents());
1415     return success();
1416   }
1417 
1418   SmallVector<int64_t> outputShape;
1419   operandShape.getDims(outputShape);
1420   int64_t axisVal = axis.getValue().getSExtValue();
1421   outputShape[axisVal] = 1;
1422   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1423   return success();
1424 }
1425 
1426 #define REDUCE_SHAPE_INFER(OP)                                                 \
1427   LogicalResult OP::inferReturnTypeComponents(                                 \
1428       MLIRContext *context, ::llvm::Optional<Location> location,               \
1429       ValueShapeRange operands, DictionaryAttr attributes,                     \
1430       RegionRange regions,                                                     \
1431       SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {           \
1432     return ReduceInferReturnTypes(operands.getShape(0),                        \
1433                                   attributes.get("axis").cast<IntegerAttr>(),  \
1434                                   inferredReturnShapes);                       \
1435   }
1436 
1437 REDUCE_SHAPE_INFER(tosa::ReduceAllOp)
1438 REDUCE_SHAPE_INFER(tosa::ReduceAnyOp)
1439 REDUCE_SHAPE_INFER(tosa::ReduceMaxOp)
1440 REDUCE_SHAPE_INFER(tosa::ReduceMinOp)
1441 REDUCE_SHAPE_INFER(tosa::ReduceProdOp)
1442 REDUCE_SHAPE_INFER(tosa::ReduceSumOp)
1443 #undef REDUCE_SHAPE_INFER
1444 
1445 static LogicalResult resolveBroadcastShape(const ValueShapeRange &operands,
1446                                            SmallVector<int64_t> &outShape) {
1447   int64_t outRank = 0;
1448   for (int i = 0, e = operands.size(); i != e; ++i) {
1449     auto shape = operands.getShape(i);
1450     if (!shape.hasRank()) {
1451       return failure();
1452     }
1453     outRank = std::max<int64_t>(outRank, shape.getRank());
1454   }
1455 
1456   outShape.resize(outRank, 1);
1457 
1458   for (int i = 0, e = operands.size(); i != e; ++i) {
1459     auto shape = operands.getShape(i);
1460     auto rankDiff = outShape.size() - shape.getRank();
1461 
1462     for (size_t i = 0, e = shape.getRank(); i < e; ++i) {
1463       auto dim1 = outShape[i + rankDiff];
1464       auto dim2 = shape.getDimSize(i);
1465       auto resolvedDim = dim1;
1466 
1467       if (dim1 == 1) {
1468         resolvedDim = dim2;
1469       } else if (dim2 == 1) {
1470         resolvedDim = dim1;
1471       } else if (dim1 != dim2) {
1472         return failure();
1473       }
1474       outShape[i + rankDiff] = resolvedDim;
1475     }
1476   }
1477 
1478   return success();
1479 }
1480 
1481 static LogicalResult NAryInferReturnTypes(
1482     const ValueShapeRange &operands,
1483     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1484   llvm::SmallVector<int64_t> outShape;
1485   if (resolveBroadcastShape(operands, outShape).failed()) {
1486     inferredReturnShapes.push_back(ShapedTypeComponents());
1487   } else {
1488     inferredReturnShapes.push_back(ShapedTypeComponents(outShape));
1489   }
1490   return success();
1491 }
1492 
1493 #define NARY_SHAPE_INFER(OP)                                                   \
1494   LogicalResult OP::inferReturnTypeComponents(                                 \
1495       MLIRContext *context, ::llvm::Optional<Location> location,               \
1496       ValueShapeRange operands, DictionaryAttr attributes,                     \
1497       RegionRange regions,                                                     \
1498       SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {           \
1499     return NAryInferReturnTypes(operands, inferredReturnShapes);               \
1500   }
1501 
1502 NARY_SHAPE_INFER(tosa::AbsOp)
1503 NARY_SHAPE_INFER(tosa::AddOp)
1504 NARY_SHAPE_INFER(tosa::ArithmeticRightShiftOp)
1505 NARY_SHAPE_INFER(tosa::BitwiseAndOp)
1506 NARY_SHAPE_INFER(tosa::BitwiseOrOp)
1507 NARY_SHAPE_INFER(tosa::BitwiseXorOp)
1508 NARY_SHAPE_INFER(tosa::BitwiseNotOp)
1509 NARY_SHAPE_INFER(tosa::CastOp)
1510 NARY_SHAPE_INFER(tosa::CeilOp)
1511 NARY_SHAPE_INFER(tosa::ClampOp)
1512 NARY_SHAPE_INFER(tosa::ClzOp)
1513 NARY_SHAPE_INFER(tosa::DivOp)
1514 NARY_SHAPE_INFER(tosa::EqualOp)
1515 NARY_SHAPE_INFER(tosa::ExpOp)
1516 NARY_SHAPE_INFER(tosa::FloorOp)
1517 NARY_SHAPE_INFER(tosa::GreaterEqualOp)
1518 NARY_SHAPE_INFER(tosa::GreaterOp)
1519 NARY_SHAPE_INFER(tosa::IdentityOp)
1520 NARY_SHAPE_INFER(tosa::LogOp)
1521 NARY_SHAPE_INFER(tosa::LogicalAndOp)
1522 NARY_SHAPE_INFER(tosa::LogicalLeftShiftOp)
1523 NARY_SHAPE_INFER(tosa::LogicalNotOp)
1524 NARY_SHAPE_INFER(tosa::LogicalOrOp)
1525 NARY_SHAPE_INFER(tosa::LogicalRightShiftOp)
1526 NARY_SHAPE_INFER(tosa::LogicalXorOp)
1527 NARY_SHAPE_INFER(tosa::MaximumOp)
1528 NARY_SHAPE_INFER(tosa::MinimumOp)
1529 NARY_SHAPE_INFER(tosa::MulOp)
1530 NARY_SHAPE_INFER(tosa::NegateOp)
1531 NARY_SHAPE_INFER(tosa::PowOp)
1532 NARY_SHAPE_INFER(tosa::ReciprocalOp)
1533 NARY_SHAPE_INFER(tosa::ReluNOp)
1534 NARY_SHAPE_INFER(tosa::RescaleOp)
1535 NARY_SHAPE_INFER(tosa::ReverseOp)
1536 NARY_SHAPE_INFER(tosa::RsqrtOp)
1537 NARY_SHAPE_INFER(tosa::SelectOp)
1538 NARY_SHAPE_INFER(tosa::SubOp)
1539 NARY_SHAPE_INFER(tosa::TanhOp)
1540 NARY_SHAPE_INFER(tosa::SigmoidOp)
1541 #undef PRED_SHAPE_INFER
1542 
1543 static LogicalResult poolingInferReturnTypes(
1544     const ValueShapeRange &operands, DictionaryAttr attributes,
1545     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1546   ShapeAdaptor inputShape = operands.getShape(0);
1547   llvm::SmallVector<int64_t> outputShape;
1548   outputShape.resize(4, -1);
1549 
1550   // We only know the rank if the input type is unranked.
1551   if (!inputShape) {
1552     inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1553     return success();
1554   }
1555 
1556   // Batch and number of channels are identical for pooling layer.
1557   outputShape[0] = inputShape.getDimSize(0);
1558   outputShape[3] = inputShape.getDimSize(3);
1559 
1560   int32_t height = inputShape.getDimSize(1);
1561   int32_t width = inputShape.getDimSize(2);
1562 
1563   llvm::SmallVector<int64_t> kernel;
1564   llvm::SmallVector<int64_t> stride;
1565   llvm::SmallVector<int64_t> pad;
1566 
1567   getI64Values(attributes.get("kernel").cast<ArrayAttr>(), kernel);
1568   getI64Values(attributes.get("stride").cast<ArrayAttr>(), stride);
1569   getI64Values(attributes.get("pad").cast<ArrayAttr>(), pad);
1570 
1571   if (height != -1) {
1572     int32_t padded = height + pad[0] + pad[1] - kernel[0];
1573     outputShape[1] = padded / stride[0] + 1;
1574   }
1575 
1576   if (width != -1) {
1577     int32_t padded = width + pad[2] + pad[3] - kernel[1];
1578     outputShape[2] = padded / stride[1] + 1;
1579   }
1580 
1581   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1582   return success();
1583 }
1584 
1585 LogicalResult Conv2DOp::inferReturnTypeComponents(
1586     MLIRContext *context, ::llvm::Optional<Location> location,
1587     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1588     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1589   llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamicSize);
1590   Conv2DOp::Adaptor adaptor(operands.getValues(), attributes);
1591 
1592   int32_t inputWidth = ShapedType::kDynamicSize;
1593   int32_t inputHeight = ShapedType::kDynamicSize;
1594   int32_t weightWidth = ShapedType::kDynamicSize;
1595   int32_t weightHeight = ShapedType::kDynamicSize;
1596 
1597   // Input shape describes input width/height and batch.
1598 
1599   ShapeAdaptor inputShape = operands.getShape(adaptor.input());
1600   if (inputShape.hasRank()) {
1601     outputShape[0] = inputShape.getDimSize(0);
1602     inputHeight = inputShape.getDimSize(1);
1603     inputWidth = inputShape.getDimSize(2);
1604   }
1605 
1606   // Weight shapes describes the filter width/height and the output channels.
1607   ShapeAdaptor weightShape = operands.getShape(adaptor.weight());
1608   if (weightShape.hasRank()) {
1609     outputShape[3] = weightShape.getDimSize(0);
1610     weightHeight = weightShape.getDimSize(1);
1611     weightWidth = weightShape.getDimSize(2);
1612   }
1613 
1614   // Bias shape can describe the output channels.
1615   ShapeAdaptor biasShape = operands.getShape(adaptor.bias());
1616   if (biasShape.hasRank()) {
1617     outputShape[3] = ShapedType::isDynamic(outputShape[3])
1618                          ? biasShape.getDimSize(0)
1619                          : outputShape[3];
1620   }
1621 
1622   llvm::SmallVector<int64_t> dilation;
1623   llvm::SmallVector<int64_t> padding;
1624   llvm::SmallVector<int64_t> stride;
1625 
1626   getI64Values(adaptor.dilation(), dilation);
1627   getI64Values(adaptor.pad(), padding);
1628   getI64Values(adaptor.stride(), stride);
1629 
1630   if (!ShapedType::isDynamic(inputHeight) &&
1631       !ShapedType::isDynamic(weightHeight)) {
1632     int32_t inputSize = inputHeight + padding[0] + padding[1];
1633     int32_t filterSize = (weightHeight - 1) * dilation[0] + 1;
1634     int32_t unstridedResult = inputSize - filterSize + 1;
1635     outputShape[1] = (unstridedResult - 1) / stride[0] + 1;
1636   }
1637 
1638   if (!ShapedType::isDynamic(inputWidth) &&
1639       !ShapedType::isDynamic(weightWidth)) {
1640     int32_t inputSize = inputWidth + padding[2] + padding[3];
1641     int32_t filterSize = (weightWidth - 1) * dilation[1] + 1;
1642     int32_t unstridedResult = inputSize - filterSize + 1;
1643     outputShape[2] = (unstridedResult - 1) / stride[1] + 1;
1644   }
1645 
1646   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1647   return success();
1648 }
1649 
1650 LogicalResult Conv2DOp::verify() { return verifyConvOp(*this); }
1651 
1652 LogicalResult Conv3DOp::inferReturnTypeComponents(
1653     MLIRContext *context, ::llvm::Optional<Location> location,
1654     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1655     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1656   llvm::SmallVector<int64_t> outputShape(5, ShapedType::kDynamicSize);
1657   Conv2DOp::Adaptor adaptor(operands.getValues(), attributes);
1658 
1659   int32_t inputWidth = ShapedType::kDynamicSize;
1660   int32_t inputHeight = ShapedType::kDynamicSize;
1661   int32_t inputDepth = ShapedType::kDynamicSize;
1662 
1663   int32_t weightWidth = ShapedType::kDynamicSize;
1664   int32_t weightHeight = ShapedType::kDynamicSize;
1665   int32_t weightDepth = ShapedType::kDynamicSize;
1666 
1667   // Input shape describes input width/height and batch.
1668   ShapeAdaptor inputShape = operands.getShape(adaptor.input());
1669   if (inputShape.hasRank()) {
1670     outputShape[0] = inputShape.getDimSize(0);
1671     inputHeight = inputShape.getDimSize(1);
1672     inputWidth = inputShape.getDimSize(2);
1673     inputDepth = inputShape.getDimSize(3);
1674   }
1675 
1676   // Weight shapes describes the filter width/height and the output channels.
1677   ShapeAdaptor weightShape = operands.getShape(adaptor.weight());
1678   if (weightShape.hasRank()) {
1679     outputShape[4] = weightShape.getDimSize(0);
1680     weightHeight = weightShape.getDimSize(1);
1681     weightWidth = weightShape.getDimSize(2);
1682     weightDepth = weightShape.getDimSize(3);
1683   }
1684 
1685   // Bias shape can describe the output channels.
1686   ShapeAdaptor biasShape = operands.getShape(adaptor.bias());
1687   if (biasShape.hasRank()) {
1688     outputShape[4] =
1689         (outputShape[4] == -1) ? biasShape.getDimSize(0) : outputShape[4];
1690   }
1691 
1692   llvm::SmallVector<int64_t> dilation;
1693   llvm::SmallVector<int64_t> padding;
1694   llvm::SmallVector<int64_t> stride;
1695 
1696   getI64Values(adaptor.dilation(), dilation);
1697   getI64Values(adaptor.pad(), padding);
1698   getI64Values(adaptor.stride(), stride);
1699 
1700   if (!ShapedType::isDynamic(inputHeight) &&
1701       !ShapedType::isDynamic(weightHeight)) {
1702     int32_t inputSize = inputHeight + padding[0] + padding[1];
1703     int32_t filterSize = (weightHeight - 1) * dilation[0] + 1;
1704     int32_t unstridedResult = inputSize - filterSize + 1;
1705     outputShape[1] = (unstridedResult - 1) / stride[0] + 1;
1706   }
1707 
1708   if (!ShapedType::isDynamic(inputWidth) &&
1709       !ShapedType::isDynamic(weightWidth)) {
1710     int32_t inputSize = inputWidth + padding[2] + padding[3];
1711     int32_t filterSize = (weightWidth - 1) * dilation[1] + 1;
1712     int32_t unstridedResult = inputSize - filterSize + 1;
1713     outputShape[2] = (unstridedResult - 1) / stride[1] + 1;
1714   }
1715 
1716   if (!ShapedType::isDynamic(inputDepth) &&
1717       !ShapedType::isDynamic(weightDepth)) {
1718     int32_t inputSize = inputDepth + padding[4] + padding[5];
1719     int32_t filterSize = (weightDepth - 1) * dilation[2] + 1;
1720     int32_t unstridedResult = inputSize - filterSize + 1;
1721     outputShape[3] = (unstridedResult - 1) / stride[2] + 1;
1722   }
1723 
1724   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1725   return success();
1726 }
1727 
1728 LogicalResult Conv3DOp::verify() { return verifyConvOp(*this); }
1729 
1730 LogicalResult AvgPool2dOp::inferReturnTypeComponents(
1731     MLIRContext *context, ::llvm::Optional<Location> location,
1732     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1733     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1734   return poolingInferReturnTypes(operands, attributes, inferredReturnShapes);
1735 }
1736 
1737 LogicalResult MaxPool2dOp::inferReturnTypeComponents(
1738     MLIRContext *context, ::llvm::Optional<Location> location,
1739     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1740     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1741   return poolingInferReturnTypes(operands, attributes, inferredReturnShapes);
1742 }
1743 
1744 LogicalResult DepthwiseConv2DOp::inferReturnTypeComponents(
1745     MLIRContext *context, ::llvm::Optional<Location> location,
1746     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1747     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1748   llvm::SmallVector<int64_t> outputShape(4, ShapedType::kDynamicSize);
1749   DepthwiseConv2DOp::Adaptor adaptor(operands.getValues(), attributes);
1750 
1751   int32_t inputWidth = ShapedType::kDynamicSize;
1752   int32_t inputHeight = ShapedType::kDynamicSize;
1753   int32_t inputChannels = ShapedType::kDynamicSize;
1754 
1755   int32_t weightWidth = ShapedType::kDynamicSize;
1756   int32_t weightHeight = ShapedType::kDynamicSize;
1757   int32_t depthChannels = ShapedType::kDynamicSize;
1758 
1759   // Input shape describes input width/height and batch.
1760   ShapeAdaptor inputShape = operands.getShape(adaptor.input());
1761   if (inputShape.hasRank()) {
1762     outputShape[0] = inputShape.getDimSize(0);
1763     inputHeight = inputShape.getDimSize(1);
1764     inputWidth = inputShape.getDimSize(2);
1765     inputChannels = inputShape.getDimSize(3);
1766   }
1767 
1768   // Weight shapes describes the filter width/height and the output channels.
1769   ShapeAdaptor weightShape = operands.getShape(adaptor.weight());
1770   if (weightShape.hasRank()) {
1771     weightHeight = weightShape.getDimSize(0);
1772     weightWidth = weightShape.getDimSize(1);
1773     inputChannels = ShapedType::isDynamic(inputChannels)
1774                         ? weightShape.getDimSize(2)
1775                         : inputChannels;
1776     depthChannels = weightShape.getDimSize(3);
1777   }
1778 
1779   // If both inputChannels and depthChannels are available we can determine
1780   // the output channels.
1781   if (!ShapedType::isDynamic(inputChannels) &&
1782       !ShapedType::isDynamic(depthChannels)) {
1783     outputShape[3] = inputChannels * depthChannels;
1784   }
1785 
1786   // Bias shape can describe the output channels.
1787   ShapeAdaptor biasShape = operands.getShape(adaptor.bias());
1788   if (biasShape.hasRank()) {
1789     outputShape[3] = ShapedType::isDynamic(outputShape[3])
1790                          ? biasShape.getDimSize(0)
1791                          : outputShape[3];
1792   }
1793 
1794   llvm::SmallVector<int64_t> dilation;
1795   llvm::SmallVector<int64_t> padding;
1796   llvm::SmallVector<int64_t> stride;
1797 
1798   getI64Values(adaptor.dilation(), dilation);
1799   getI64Values(adaptor.pad(), padding);
1800   getI64Values(adaptor.stride(), stride);
1801 
1802   if (!ShapedType::isDynamic(inputHeight) &&
1803       !ShapedType::isDynamic(weightHeight)) {
1804     int32_t inputSize = inputHeight + padding[0] + padding[1];
1805     int32_t filterSize = (weightHeight - 1) * dilation[0] + 1;
1806     int32_t unstridedResult = inputSize - filterSize + 1;
1807     outputShape[1] = (unstridedResult - 1) / stride[0] + 1;
1808   }
1809 
1810   if (!ShapedType::isDynamic(inputWidth) &&
1811       !ShapedType::isDynamic(weightWidth)) {
1812     int32_t inputSize = inputWidth + padding[2] + padding[3];
1813     int32_t filterSize = (weightWidth - 1) * dilation[1] + 1;
1814     int32_t unstridedResult = inputSize - filterSize + 1;
1815     outputShape[2] = (unstridedResult - 1) / stride[1] + 1;
1816   }
1817 
1818   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1819   return success();
1820 }
1821 
1822 LogicalResult DepthwiseConv2DOp::verify() { return verifyConvOp(*this); }
1823 
1824 LogicalResult TransposeConv2DOp::inferReturnTypeComponents(
1825     MLIRContext *context, ::llvm::Optional<Location> location,
1826     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1827     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1828   TransposeConv2DOp::Adaptor adaptor(operands.getValues(), attributes);
1829   llvm::SmallVector<int64_t> outputShape;
1830   getI64Values(adaptor.out_shape(), outputShape);
1831 
1832   int32_t inputWidth = ShapedType::kDynamicSize;
1833   int32_t inputHeight = ShapedType::kDynamicSize;
1834   int32_t weightWidth = ShapedType::kDynamicSize;
1835   int32_t weightHeight = ShapedType::kDynamicSize;
1836 
1837   // Input shape describes input width/height and batch.
1838   ShapeAdaptor inputShape = operands.getShape(adaptor.input());
1839   if (inputShape.hasRank()) {
1840     outputShape[0] = ShapedType::isDynamic(outputShape[0])
1841                          ? inputShape.getDimSize(0)
1842                          : outputShape[0];
1843     inputHeight = inputShape.getDimSize(1);
1844     inputWidth = inputShape.getDimSize(2);
1845   }
1846 
1847   // Weight shapes describes the filter width/height and the output channels.
1848   ShapeAdaptor weightShape = operands.getShape(adaptor.filter());
1849   if (weightShape.hasRank()) {
1850     outputShape[3] = ShapedType::isDynamic(outputShape[3])
1851                          ? weightShape.getDimSize(0)
1852                          : outputShape[3];
1853     weightHeight = weightShape.getDimSize(1);
1854     weightWidth = weightShape.getDimSize(2);
1855   }
1856 
1857   // Bias shape can describe the output channels.
1858   ShapeAdaptor biasShape = operands.getShape(adaptor.input());
1859   if (biasShape.hasRank()) {
1860     outputShape[3] = ShapedType::isDynamic(outputShape[3])
1861                          ? biasShape.getDimSize(0)
1862                          : outputShape[3];
1863   }
1864 
1865   llvm::SmallVector<int64_t> dilation;
1866   llvm::SmallVector<int64_t> padding;
1867   llvm::SmallVector<int64_t> stride;
1868 
1869   getI64Values(adaptor.dilation(), dilation);
1870   getI64Values(adaptor.out_pad(), padding);
1871   getI64Values(adaptor.stride(), stride);
1872 
1873   if (!ShapedType::isDynamic(inputHeight) &&
1874       !ShapedType::isDynamic(weightHeight)) {
1875     int32_t dilated = (weightHeight - 1) * dilation[0] + 1;
1876     int32_t calculateSize =
1877         (inputHeight - 1) * stride[0] - padding[0] + dilated;
1878     outputShape[1] = outputShape[1] == -1 ? calculateSize : outputShape[1];
1879   }
1880 
1881   if (!ShapedType::isDynamic(inputWidth) &&
1882       !ShapedType::isDynamic(weightWidth)) {
1883     int32_t dilated = (weightWidth - 1) * dilation[1] + 1;
1884     int32_t calculateSize = (inputWidth - 1) * stride[1] - padding[1] + dilated;
1885     outputShape[2] = outputShape[2] == -1 ? calculateSize : outputShape[2];
1886   }
1887 
1888   inferredReturnShapes.push_back(ShapedTypeComponents(outputShape));
1889   return success();
1890 }
1891 
1892 LogicalResult IfOp::inferReturnTypeComponents(
1893     MLIRContext *context, ::llvm::Optional<Location> location,
1894     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1895     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1896   llvm::SmallVector<tosa::YieldOp> yieldOps;
1897   for (Region *region : regions) {
1898     for (auto &block : *region)
1899       if (auto returnOp = dyn_cast<tosa::YieldOp>(block.getTerminator()))
1900         yieldOps.push_back(returnOp);
1901   }
1902 
1903   if (yieldOps.empty())
1904     return failure();
1905 
1906   // Get the initial type information for the yield op.
1907   llvm::SmallVector<ValueKnowledge> resultKnowledge;
1908   resultKnowledge.reserve(yieldOps.front().getNumOperands());
1909   for (auto operand : yieldOps.front().getOperands()) {
1910     resultKnowledge.push_back(
1911         ValueKnowledge::getKnowledgeFromType(operand.getType()));
1912   }
1913 
1914   for (auto yieldOp : yieldOps) {
1915     if (resultKnowledge.size() != yieldOp.getNumOperands())
1916       return failure();
1917 
1918     for (const auto &it : llvm::enumerate(yieldOp.getOperands())) {
1919       int32_t index = it.index();
1920       auto meet = ValueKnowledge::meet(
1921           resultKnowledge[index],
1922           ValueKnowledge::getKnowledgeFromType(it.value().getType()));
1923       if (!meet)
1924         continue;
1925       resultKnowledge[index] = meet;
1926     }
1927   }
1928 
1929   for (const ValueKnowledge &result : resultKnowledge) {
1930     inferredReturnShapes.push_back(result.getShapedTypeComponents());
1931   }
1932 
1933   return success();
1934 }
1935 
1936 LogicalResult WhileOp::inferReturnTypeComponents(
1937     MLIRContext *context, ::llvm::Optional<Location> location,
1938     ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions,
1939     SmallVectorImpl<ShapedTypeComponents> &inferredReturnShapes) {
1940   llvm::SmallVector<tosa::YieldOp> yieldOps;
1941   for (auto &block : *regions[1])
1942     if (auto returnOp = dyn_cast<tosa::YieldOp>(block.getTerminator()))
1943       yieldOps.push_back(returnOp);
1944 
1945   // TOSA's while must have a tosa.yield as its terminator. If not found this
1946   // tosa.while is invalid.
1947   if (yieldOps.empty())
1948     return failure();
1949 
1950   // Get the initial type information from the operand types.
1951   llvm::SmallVector<ValueKnowledge> resultKnowledge;
1952   resultKnowledge.reserve(yieldOps.front().getNumOperands());
1953   for (auto operand : yieldOps.front().getOperands()) {
1954     resultKnowledge.push_back(
1955         ValueKnowledge::getKnowledgeFromType(operand.getType()));
1956   }
1957 
1958   for (auto yieldOp : yieldOps) {
1959     if (resultKnowledge.size() != yieldOp.getNumOperands())
1960       return failure();
1961 
1962     for (const auto &it : llvm::enumerate(yieldOp.getOperands())) {
1963       int32_t index = it.index();
1964       if (auto meet = ValueKnowledge::meet(
1965               resultKnowledge[index],
1966               ValueKnowledge::getKnowledgeFromType(it.value().getType()))) {
1967         resultKnowledge[index] = meet;
1968       }
1969     }
1970   }
1971 
1972   for (const ValueKnowledge &result : resultKnowledge) {
1973     inferredReturnShapes.push_back(result.getShapedTypeComponents());
1974   }
1975 
1976   return success();
1977 }
1978 
1979 //===----------------------------------------------------------------------===//
1980 // TOSA Operator Definitions.
1981 //===----------------------------------------------------------------------===//
1982 
1983 #define GET_OP_CLASSES
1984 #include "mlir/Dialect/Tosa/IR/TosaOps.cpp.inc"
1985