Skip to content

TosaToLinAlg: fix tosa.cast legalization of FP->Int for non FP32 types. #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions mlir/lib/Conversion/TosaToLinalg/TosaToLinalg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -471,16 +471,33 @@ createLinalgBodyCalculationForElementwiseOp(Operation *op, ValueRange args,
}

if (arith::FPToSIOp::areCastCompatible(srcTy, dstTy)) {
auto intMin = rewriter.create<arith::ConstantOp>(
Value intMin = rewriter.create<arith::ConstantOp>(
loc, rewriter.getF32FloatAttr(
APInt::getSignedMinValue(dstTy.getIntOrFloatBitWidth())
.getSExtValue()));

auto intMax = rewriter.create<arith::ConstantOp>(
Value intMax = rewriter.create<arith::ConstantOp>(
loc, rewriter.getF32FloatAttr(
APInt::getSignedMaxValue(dstTy.getIntOrFloatBitWidth())
.getSExtValue()));

// Since F32 constants are created, we may still need to convert them to
// the correct type.
auto convertType = [&](Type ty, Value arg) {
auto argTy = arg.getType();
bool bitExtend =
argTy.getIntOrFloatBitWidth() < ty.getIntOrFloatBitWidth();
if (ty != argTy) {
if (!bitExtend)
arg = rewriter.create<arith::TruncFOp>(loc, ty, arg);
else
arg = rewriter.create<arith::ExtFOp>(loc, ty, arg);
}
return arg;
};
intMin = convertType(srcTy, intMin);
intMax = convertType(srcTy, intMax);

auto rounded = rewriter.create<math::RoundEvenOp>(loc, args[0]);

auto clamped = clampFloatHelper(loc, rounded, intMin, intMax, rewriter);
Expand Down
11 changes: 11 additions & 0 deletions mlir/test/Conversion/TosaToLinalg/tosa-to-linalg.mlir
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,17 @@ func.func @test_simple_f16(%arg0: tensor<1xf16>) -> () {
// CHECK: arith.extf
%0 = "tosa.cast"(%arg0) : (tensor<1xf16>) -> tensor<1xf32>

// CHECK: linalg.generic
// CHECK: %[[C_LOWEST:.+]] = arith.constant -2.14748365E+9
// CHECK: %[[C_MAX:.+]] = arith.constant 2.14748365E+9
// CHECK: arith.truncf %[[C_LOWEST]] : f32 to f16
// CHECK: arith.truncf %[[C_MAX]] : f32 to f16
// CHECK: math.roundeven
// CHECK: arith.minf
// CHECK: arith.maxf
// CHECK: arith.fptosi
%1 = "tosa.cast"(%arg0) : (tensor<1xf16>) -> tensor<1xi32>

return
}

Expand Down