|
| 1 | +//===- TosaFoldConstantCast.cpp -------------------------------------------===// |
| 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 | +// Fold TOSA cast operation on constant data |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +#include "mlir/Dialect/Tosa/IR/TosaOps.h" |
| 14 | +#include "mlir/Dialect/Tosa/Transforms/Passes.h" |
| 15 | +#include "mlir/Dialect/Tosa/Transforms/TosaFoldCommon.h" |
| 16 | +#include "mlir/IR/Matchers.h" |
| 17 | +#include "mlir/Pass/Pass.h" |
| 18 | +#include <llvm/ADT/APFloat.h> |
| 19 | +#include <llvm/ADT/APInt.h> |
| 20 | +#include <llvm/ADT/APSInt.h> |
| 21 | +#include <mlir/IR/BuiltinTypes.h> |
| 22 | +#include <mlir/IR/MLIRContext.h> |
| 23 | +#include <mlir/Support/LogicalResult.h> |
| 24 | + |
| 25 | +using namespace mlir; |
| 26 | +using namespace mlir::tosa; |
| 27 | + |
| 28 | +namespace { |
| 29 | + |
| 30 | +struct TosaFoldConstantCast : public OpRewritePattern<CastOp> { |
| 31 | + |
| 32 | + using OpRewritePattern::OpRewritePattern; |
| 33 | + |
| 34 | + static APFloat convertIntToFloat(const APInt &toConvert, |
| 35 | + FloatType targetType) { |
| 36 | + APFloat res(targetType.getFloatSemantics()); |
| 37 | + res.convertFromAPInt(toConvert, true /* isSigned */, tosaRoundingMode); |
| 38 | + return res; |
| 39 | + } |
| 40 | + |
| 41 | + static APFloat convertFloatToFloat(const APFloat &toConvert, |
| 42 | + FloatType targetType) { |
| 43 | + APFloat res(toConvert); |
| 44 | + bool didLosePrecision; |
| 45 | + res.convert(targetType.getFloatSemantics(), tosaRoundingMode, |
| 46 | + &didLosePrecision); |
| 47 | + return res; |
| 48 | + } |
| 49 | + |
| 50 | + static APInt convertFloatToInt(const APFloat &toConvert, |
| 51 | + IntegerType targetType) { |
| 52 | + auto targetWidth = targetType.getIntOrFloatBitWidth(); |
| 53 | + // Converting NaN to an integer results in an unpredictable value. Pick 0. |
| 54 | + if (toConvert.isNaN()) { |
| 55 | + return APInt::getZero(targetWidth); |
| 56 | + } |
| 57 | + |
| 58 | + // Make sure to properly translate booleans |
| 59 | + if (targetWidth == 1) { |
| 60 | + return toConvert.isZero() ? APInt::getZero(1) : APInt::getAllOnes(1); |
| 61 | + } |
| 62 | + |
| 63 | + // Use the built-in functionality of APFloats to convert to integers. |
| 64 | + // The result of this conversion should be an integer which might still be |
| 65 | + // outside of the target integer range. |
| 66 | + auto floatSize = APFloat::getSizeInBits(toConvert.getSemantics()); |
| 67 | + APSInt converted(std::max(floatSize, targetWidth), targetType.isUnsigned()); |
| 68 | + bool ignored = false; |
| 69 | + toConvert.convertToInteger(converted, APFloat::rmNearestTiesToEven, |
| 70 | + &ignored); |
| 71 | + // Clip to allowed range. |
| 72 | + if (targetWidth < floatSize) { |
| 73 | + if (targetType.isUnsigned()) { |
| 74 | + return converted.truncUSat(targetWidth); |
| 75 | + } |
| 76 | + return converted.truncSSat(targetWidth); |
| 77 | + } |
| 78 | + return converted; |
| 79 | + } |
| 80 | + |
| 81 | + static APInt convertIntToInt(const APInt &toConvert, IntegerType targetType) { |
| 82 | + // Make sure to properly translate booleans |
| 83 | + if (targetType.getWidth() == 1) { |
| 84 | + return toConvert.isZero() ? APInt::getZero(1) : APInt::getAllOnes(1); |
| 85 | + } |
| 86 | + if (targetType.isUnsigned()) { |
| 87 | + return toConvert.zextOrTrunc(targetType.getIntOrFloatBitWidth()); |
| 88 | + } |
| 89 | + return toConvert.sextOrTrunc(targetType.getIntOrFloatBitWidth()); |
| 90 | + } |
| 91 | + |
| 92 | + static void warnAboutNaNToIntCast(DenseElementsAttr elements, CastOp location, |
| 93 | + PatternRewriter &rewriter) { |
| 94 | + // This is only relevant if the input values are float |
| 95 | + if (!isa<FloatType>(elements.getElementType())) { |
| 96 | + return; |
| 97 | + } |
| 98 | + // Check if it is an float to integer conversion |
| 99 | + auto resultType = location.getOutput().getType(); |
| 100 | + if (!isa<IntegerType>(cast<TensorType>(resultType).getElementType())) { |
| 101 | + return; |
| 102 | + } |
| 103 | + |
| 104 | + // Report encountered NaNs |
| 105 | + auto checkNan = [](const APFloat &val) { return val.isNaN(); }; |
| 106 | + if (any_of(elements.getValues<APFloat>(), checkNan)) { |
| 107 | + location->emitWarning( |
| 108 | + "Float tensor is casted to integer and it contains NaN values. The " |
| 109 | + "cast results in an unspecified value."); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + LogicalResult matchAndRewrite(CastOp tosaCast, |
| 114 | + PatternRewriter &rewriter) const override { |
| 115 | + auto inputTensor = tosaCast.getInput(); |
| 116 | + |
| 117 | + // If the input tensor is not constant, we cannot fold it. |
| 118 | + if (failed(notifyIfNoTosaDenseConstantTensor(inputTensor, tosaCast, |
| 119 | + rewriter))) { |
| 120 | + return failure(); |
| 121 | + } |
| 122 | + |
| 123 | + auto fromType = inputTensor.getType().getElementType(); |
| 124 | + auto toType = tosaCast.getOutput().getType().getElementType(); |
| 125 | + |
| 126 | + DenseElementsAttr elements; |
| 127 | + matchPattern(inputTensor, m_Constant(&elements)); |
| 128 | + |
| 129 | + // Issue a warning if we convert float -> int and NaNs are present; the |
| 130 | + // result value is unspecified in that case |
| 131 | + warnAboutNaNToIntCast(elements, tosaCast, rewriter); |
| 132 | + |
| 133 | + // Only fold splat tensors and those used only once to avoid duplicating |
| 134 | + // them. |
| 135 | + if (!inputTensor.hasOneUse() && !isa<SplatElementsAttr>(elements)) { |
| 136 | + return rewriter.notifyMatchFailure(tosaCast, |
| 137 | + "Currently, casts will only be folded " |
| 138 | + "if its input only has a single user"); |
| 139 | + } |
| 140 | + |
| 141 | + // Report a match failure for unexpected types |
| 142 | + if (!toType.isIntOrFloat() || !fromType.isIntOrFloat()) { |
| 143 | + return rewriter.notifyMatchFailure( |
| 144 | + tosaCast, "Only casts from/to int/float are supported."); |
| 145 | + } |
| 146 | + |
| 147 | + auto isUnsigned = [](Type toCheck) { |
| 148 | + return isa<IntegerType>(toCheck) && |
| 149 | + cast<IntegerType>(toCheck).isUnsigned(); |
| 150 | + }; |
| 151 | + auto typesToCheck = {toType, fromType}; |
| 152 | + if (llvm::any_of(typesToCheck, isUnsigned)) { |
| 153 | + // TOSA casts currently don't support unsigned integers. |
| 154 | + // To support them by here, one could use APSInt instead of APInts, |
| 155 | + // however, this causes trouble with `getValues` which does not support |
| 156 | + // APSInts currently. |
| 157 | + return rewriter.notifyMatchFailure( |
| 158 | + tosaCast, "Cast folding from/to unsigned integers is not supported."); |
| 159 | + } |
| 160 | + |
| 161 | + DenseElementsAttr res; |
| 162 | + if (auto intOutTy = dyn_cast<IntegerType>(toType)) { |
| 163 | + if (isa<FloatType>(fromType)) { |
| 164 | + res = applyElementWise<APFloat, APInt, IntegerType>( |
| 165 | + elements, &convertFloatToInt, intOutTy); |
| 166 | + } else { |
| 167 | + assert(isa<IntegerType>(fromType)); |
| 168 | + res = applyElementWise<APInt, APInt, IntegerType>( |
| 169 | + elements, &convertIntToInt, intOutTy); |
| 170 | + } |
| 171 | + } else { |
| 172 | + assert(isa<FloatType>(toType)); |
| 173 | + auto floatOutTy = cast<FloatType>(toType); |
| 174 | + if (isa<FloatType>(fromType)) { |
| 175 | + res = applyElementWise<APFloat, APFloat, FloatType>( |
| 176 | + elements, &convertFloatToFloat, floatOutTy); |
| 177 | + } else { |
| 178 | + assert(isa<IntegerType>(fromType)); |
| 179 | + res = applyElementWise<APInt, APFloat, FloatType>( |
| 180 | + elements, &convertIntToFloat, floatOutTy); |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + rewriter.replaceOpWithNewOp<ConstOp>(tosaCast, res.getType(), res); |
| 185 | + return success(); |
| 186 | + } |
| 187 | +}; |
| 188 | + |
| 189 | +struct TosaFoldConstantFloatCasts : TosaFoldConstantCast { |
| 190 | + |
| 191 | + TosaFoldConstantFloatCasts(MLIRContext *ctx) : TosaFoldConstantCast(ctx) {} |
| 192 | + |
| 193 | + LogicalResult matchAndRewrite(CastOp tosaCast, |
| 194 | + PatternRewriter &rewriter) const override { |
| 195 | + if (isa<IntegerType>(tosaCast.getInput().getType().getElementType())) { |
| 196 | + return rewriter.notifyMatchFailure( |
| 197 | + tosaCast, "Folding casts from int is currently disabled."); |
| 198 | + } |
| 199 | + |
| 200 | + return TosaFoldConstantCast::matchAndRewrite(tosaCast, rewriter); |
| 201 | + } |
| 202 | +}; |
| 203 | + |
| 204 | +} // namespace |
| 205 | + |
| 206 | +void mlir::tosa::populateTosaFoldConstantCastPatterns( |
| 207 | + MLIRContext *ctx, RewritePatternSet &patterns, bool enableIntCastFolding) { |
| 208 | + if (enableIntCastFolding) { |
| 209 | + patterns.add<TosaFoldConstantCast>(ctx); |
| 210 | + } else { |
| 211 | + patterns.add<TosaFoldConstantFloatCasts>(ctx); |
| 212 | + } |
| 213 | +} |
0 commit comments