|
| 1 | +//===- FixTosaCastRounding.cpp - Fix tosa.cast rounding -------------------===// |
| 2 | +// |
| 3 | +// Part of the rocMLIR Project, under the Apache License v2.0 with LLVM |
| 4 | +// Exceptions. See https://llvm.org/LICENSE.txt for license information. |
| 5 | +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | +// |
| 7 | +// Copyright (c) 2026 Advanced Micro Devices Inc. |
| 8 | +// |
| 9 | +//===----------------------------------------------------------------------===// |
| 10 | +// |
| 11 | +// The upstream tosa-to-linalg pass inserts math.roundeven before arith.fptosi |
| 12 | +// when lowering tosa.cast from float to integer. This implements TOSA's |
| 13 | +// "round to nearest, ties to even" semantics. |
| 14 | +// |
| 15 | +// However, ONNX and PyTorch define float-to-int cast as truncation (round |
| 16 | +// towards zero), which is what arith.fptosi already does natively. Since |
| 17 | +// rocMLIR primarily serves ONNX/MIGraphX workloads, this pass removes the |
| 18 | +// math.roundeven ops to restore RTZ semantics without modifying the upstream |
| 19 | +// LLVM code. |
| 20 | +// |
| 21 | +//===----------------------------------------------------------------------===// |
| 22 | + |
| 23 | +#include "mlir/Conversion/FixTosaCastRounding/FixTosaCastRounding.h" |
| 24 | +#include "mlir/Dialect/Arith/IR/Arith.h" |
| 25 | +#include "mlir/Dialect/Func/IR/FuncOps.h" |
| 26 | +#include "mlir/Dialect/Linalg/IR/Linalg.h" |
| 27 | +#include "mlir/Dialect/Math/IR/Math.h" |
| 28 | +#include "mlir/IR/BuiltinTypes.h" |
| 29 | +#include "mlir/IR/Location.h" |
| 30 | +#include "mlir/IR/PatternMatch.h" |
| 31 | +#include "mlir/IR/TypeUtilities.h" |
| 32 | +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" |
| 33 | +#include "llvm/ADT/STLExtras.h" |
| 34 | + |
| 35 | +namespace mlir { |
| 36 | +#define GEN_PASS_DEF_FIXTOSACASTROUNDINGPASS |
| 37 | +#include "mlir/Conversion/RocMLIRPasses.h.inc" |
| 38 | +} // namespace mlir |
| 39 | + |
| 40 | +using namespace mlir; |
| 41 | + |
| 42 | +namespace { |
| 43 | + |
| 44 | +/// Returns true when `roundeven`'s result participates *exclusively* in the |
| 45 | +/// upstream tosa-to-linalg float-to-int cast chain. The chain has two parts: |
| 46 | +/// 1. Float clamp: optional `arith.minimumf`/`maximumf` on the rounded |
| 47 | +/// value, ending at `arith.fptosi`. |
| 48 | +/// 2. Integer saturation merge (i32 case): the rounded value also feeds |
| 49 | +/// `arith.cmpf` to produce an i1 mask, which feeds an `arith.select` |
| 50 | +/// that picks between an integer saturation constant and the |
| 51 | +/// `arith.fptosi` result. The merged i32 then flows to `linalg.yield`. |
| 52 | +/// |
| 53 | +/// We follow both branches and accept `linalg.yield` as a terminal. Removing |
| 54 | +/// the `math.roundeven` is safe even for the saturation comparison: at the |
| 55 | +/// i32 saturation boundary (|2^31|) every f32 value is already an integer |
| 56 | +/// (f32 ULP is >= 1 above 2^23), so `roundeven` is a no-op there and the |
| 57 | +/// `arith.cmpf` result is unchanged. |
| 58 | +/// |
| 59 | +/// This is intentionally strict: if any user of a value in the chain is not |
| 60 | +/// recognized, we return false (do not strip the `roundeven`) even when a |
| 61 | +/// sibling user does reach an `arith.fptosi`. This prevents miscompiles |
| 62 | +/// where the rounded value is also consumed by an unrelated op that depends |
| 63 | +/// on RNE semantics. |
| 64 | +static bool reachesFPToSI(math::RoundEvenOp op) { |
| 65 | + SmallVector<Value, 8> worklist(op->getResults()); |
| 66 | + bool foundFPToSI = false; |
| 67 | + while (!worklist.empty()) { |
| 68 | + Value v = worklist.pop_back_val(); |
| 69 | + for (Operation *user : v.getUsers()) { |
| 70 | + if (isa<arith::FPToSIOp>(user)) { |
| 71 | + foundFPToSI = true; |
| 72 | + continue; |
| 73 | + } |
| 74 | + if (isa<linalg::YieldOp>(user)) |
| 75 | + continue; |
| 76 | + if (isa<arith::MinimumFOp, arith::MaximumFOp, arith::CmpFOp, |
| 77 | + arith::SelectOp>(user)) { |
| 78 | + for (Value r : user->getResults()) |
| 79 | + worklist.push_back(r); |
| 80 | + continue; |
| 81 | + } |
| 82 | + return false; |
| 83 | + } |
| 84 | + } |
| 85 | + return foundFPToSI; |
| 86 | +} |
| 87 | + |
| 88 | +static bool hasRtzCastLocTag(Location loc) { |
| 89 | + if (auto fused = dyn_cast<FusedLoc>(loc)) |
| 90 | + if (auto meta = dyn_cast_or_null<StringAttr>(fused.getMetadata())) |
| 91 | + return meta.getValue() == rock::kRtzCastLocTag; |
| 92 | + return false; |
| 93 | +} |
| 94 | + |
| 95 | +/// True when this `math.roundeven` is part of an RTZ-tagged |
| 96 | +/// `migraphx.convert` lowering. The tag is set on the `tosa.cast` and ends |
| 97 | +/// up on the parent `linalg.generic`'s loc and on its output region block |
| 98 | +/// argument (the one carved out from the `tensor.empty()` that this cast |
| 99 | +/// writes into). Upstream `tosa-to-linalg` may assign the inner |
| 100 | +/// `math.roundeven` a different `Location`, so we don't rely on the op's |
| 101 | +/// own loc alone. |
| 102 | +/// |
| 103 | +/// We deliberately do NOT scan input block arguments: those inherit the |
| 104 | +/// loc of their incoming SSA value, and if that value comes from a |
| 105 | +/// previously-tagged cast the tag would propagate forward, causing this |
| 106 | +/// pass to wrongly strip an unrelated `math.roundeven` in a downstream |
| 107 | +/// generic. |
| 108 | +static bool isRtzTaggedCastLowering(math::RoundEvenOp op, |
| 109 | + linalg::GenericOp generic) { |
| 110 | + if (hasRtzCastLocTag(op->getLoc()) || hasRtzCastLocTag(generic.getLoc())) |
| 111 | + return true; |
| 112 | + return llvm::any_of(generic.getRegionOutputArgs(), [](BlockArgument arg) { |
| 113 | + return hasRtzCastLocTag(arg.getLoc()); |
| 114 | + }); |
| 115 | +} |
| 116 | + |
| 117 | +struct RemoveRoundEvenBeforeFPToSI |
| 118 | + : public OpRewritePattern<math::RoundEvenOp> { |
| 119 | + using OpRewritePattern::OpRewritePattern; |
| 120 | + |
| 121 | + LogicalResult matchAndRewrite(math::RoundEvenOp op, |
| 122 | + PatternRewriter &rewriter) const override { |
| 123 | + auto generic = op->getParentOfType<linalg::GenericOp>(); |
| 124 | + if (!generic) |
| 125 | + return failure(); |
| 126 | + |
| 127 | + // The RTZ-tagged cast lowering corresponds to a single tosa.cast and |
| 128 | + // therefore produces exactly one integer output from the generic. Use |
| 129 | + // getOutputs() rather than getResultTypes() so this still works in |
| 130 | + // buffer semantics (where there are no SSA results). |
| 131 | + // |
| 132 | + // Bail on multi-output generics (e.g. produced by linalg fusion) to |
| 133 | + // avoid stripping a math.roundeven that also feeds a sibling result -- |
| 134 | + // for instance an i1 yielded directly from arith.cmpf, which would |
| 135 | + // silently flip if we removed the rounding. |
| 136 | + // |
| 137 | + // Bail on i1 outputs as well: ONNX/PyTorch float-to-bool semantics is |
| 138 | + // "non-zero" rather than truncation, so removing roundeven would be |
| 139 | + // unsafe even if upstream tosa-to-linalg ever emitted it for an i1 |
| 140 | + // cast. Today MIGraphXToTosa does not tag float-to-i1 casts, but this |
| 141 | + // guard is defense-in-depth. |
| 142 | + ValueRange outs = generic.getOutputs(); |
| 143 | + if (outs.size() != 1) |
| 144 | + return failure(); |
| 145 | + Type outElemTy = getElementTypeOrSelf(outs[0].getType()); |
| 146 | + if (!isa<IntegerType>(outElemTy) || outElemTy.isInteger(1)) |
| 147 | + return failure(); |
| 148 | + |
| 149 | + if (!isRtzTaggedCastLowering(op, generic)) |
| 150 | + return failure(); |
| 151 | + |
| 152 | + if (!reachesFPToSI(op)) |
| 153 | + return failure(); |
| 154 | + |
| 155 | + rewriter.replaceOp(op, op.getOperand()); |
| 156 | + return success(); |
| 157 | + } |
| 158 | +}; |
| 159 | + |
| 160 | +struct FixTosaCastRoundingPass |
| 161 | + : public impl::FixTosaCastRoundingPassBase<FixTosaCastRoundingPass> { |
| 162 | + using FixTosaCastRoundingPassBase::FixTosaCastRoundingPassBase; |
| 163 | + |
| 164 | + void runOnOperation() override { |
| 165 | + RewritePatternSet patterns(&getContext()); |
| 166 | + patterns.add<RemoveRoundEvenBeforeFPToSI>(&getContext()); |
| 167 | + if (failed(applyPatternsGreedily(getOperation(), std::move(patterns)))) |
| 168 | + return signalPassFailure(); |
| 169 | + } |
| 170 | +}; |
| 171 | + |
| 172 | +} // namespace |
0 commit comments