1 //===- TosaToArith.cpp - Lowering Tosa to Arith Dialect -------------===//
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 // These rewriters lower from the Tosa to the Arith dialect.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Conversion/TosaToArith/TosaToArith.h"
14 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
15 #include "mlir/Dialect/Tosa/IR/TosaOps.h"
16 #include "mlir/IR/PatternMatch.h"
17 #include "mlir/IR/TypeUtilities.h"
18 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
19 
20 using namespace mlir;
21 using namespace tosa;
22 
23 namespace {
24 
25 class ConstOpConverter : public OpRewritePattern<tosa::ConstOp> {
26 public:
27   using OpRewritePattern<tosa::ConstOp>::OpRewritePattern;
28 
matchAndRewrite(tosa::ConstOp op,PatternRewriter & rewriter) const29   LogicalResult matchAndRewrite(tosa::ConstOp op,
30                                 PatternRewriter &rewriter) const final {
31     rewriter.replaceOpWithNewOp<arith::ConstantOp>(op, op.getValue());
32     return success();
33   }
34 };
35 
matchContainerType(Type element,Type container)36 Type matchContainerType(Type element, Type container) {
37   if (auto shapedTy = container.dyn_cast<ShapedType>())
38     return shapedTy.clone(element);
39 
40   return element;
41 }
42 
getConstantAttr(Type type,int64_t value,PatternRewriter & rewriter)43 Attribute getConstantAttr(Type type, int64_t value, PatternRewriter &rewriter) {
44   if (auto shapedTy = type.dyn_cast<ShapedType>()) {
45     Type eTy = shapedTy.getElementType();
46     APInt valueInt(eTy.getIntOrFloatBitWidth(), value);
47     return DenseIntElementsAttr::get(shapedTy, valueInt);
48   }
49 
50   return rewriter.getIntegerAttr(type, value);
51 }
52 
getConstantValue(Location loc,Type type,int64_t value,PatternRewriter & rewriter)53 Value getConstantValue(Location loc, Type type, int64_t value,
54                        PatternRewriter &rewriter) {
55   return rewriter.create<arith::ConstantOp>(
56       loc, getConstantAttr(type, value, rewriter));
57 }
58 
59 // This converts the TOSA ApplyScale operator to a set of arithmetic ops,
60 // using 64-bit operations to perform the necessary multiply, bias, and shift.
61 class ApplyScaleGenericOpConverter
62     : public OpRewritePattern<tosa::ApplyScaleOp> {
63 public:
64   using OpRewritePattern<tosa::ApplyScaleOp>::OpRewritePattern;
65 
matchAndRewrite(tosa::ApplyScaleOp op,PatternRewriter & rewriter) const66   LogicalResult matchAndRewrite(tosa::ApplyScaleOp op,
67                                 PatternRewriter &rewriter) const final {
68     Location loc = op.getLoc();
69     Value value = op.getValue();
70     Value multiplier32 = op.getMultiplier();
71 
72     Type resultTy = op.getType();
73     Type valueTy = value.getType();
74     Type i32Ty = matchContainerType(rewriter.getI32Type(), resultTy);
75     Type i64Ty = matchContainerType(rewriter.getI64Type(), resultTy);
76 
77     Value zero = getConstantValue(loc, valueTy, 0, rewriter);
78     Value one64 = getConstantValue(loc, i64Ty, 1, rewriter);
79     Value thirtyOne32 = getConstantValue(loc, i32Ty, 31, rewriter);
80 
81     Value shift32 = rewriter.create<arith::ExtUIOp>(loc, i32Ty, op.getShift());
82 
83     // Compute the multiplication in 64-bits then select the high / low parts.
84     Value value64 = rewriter.create<arith::ExtSIOp>(loc, i64Ty, value);
85     Value multiplier64 =
86         rewriter.create<arith::ExtSIOp>(loc, i64Ty, multiplier32);
87     Value multiply64 =
88         rewriter.create<arith::MulIOp>(loc, value64, multiplier64);
89 
90     // Apply normal rounding.
91     Value shift64 = rewriter.create<arith::ExtUIOp>(loc, i64Ty, shift32);
92     Value round = rewriter.create<arith::ShLIOp>(loc, one64, shift64);
93     round = rewriter.create<arith::ShRUIOp>(loc, round, one64);
94     multiply64 = rewriter.create<arith::AddIOp>(loc, multiply64, round);
95 
96     // Apply double rounding if necessary.
97     if (op.getDoubleRound()) {
98       int64_t roundInt = 1 << 30;
99       Value roundUp = getConstantValue(loc, i64Ty, roundInt, rewriter);
100       Value roundDown = getConstantValue(loc, i64Ty, -roundInt, rewriter);
101       Value positive = rewriter.create<arith::CmpIOp>(
102           loc, arith::CmpIPredicate::sge, value, zero);
103       Value dir =
104           rewriter.create<arith::SelectOp>(loc, positive, roundUp, roundDown);
105       Value val = rewriter.create<arith::AddIOp>(loc, dir, multiply64);
106       Value valid = rewriter.create<arith::CmpIOp>(
107           loc, arith::CmpIPredicate::sgt, shift32, thirtyOne32);
108       multiply64 =
109           rewriter.create<arith::SelectOp>(loc, valid, val, multiply64);
110     }
111 
112     Value result64 = rewriter.create<arith::ShRSIOp>(loc, multiply64, shift64);
113     Value result32 = rewriter.create<arith::TruncIOp>(loc, i32Ty, result64);
114 
115     rewriter.replaceOp(op, result32);
116     return success();
117   }
118 };
119 
120 class ApplyScale32BitOpConverter : public OpRewritePattern<tosa::ApplyScaleOp> {
121 public:
122   using OpRewritePattern<tosa::ApplyScaleOp>::OpRewritePattern;
123 
matchAndRewrite(tosa::ApplyScaleOp op,PatternRewriter & rewriter) const124   LogicalResult matchAndRewrite(tosa::ApplyScaleOp op,
125                                 PatternRewriter &rewriter) const final {
126     Location loc = op.getLoc();
127 
128     Type resultTy = op.getType();
129     Type i32Ty = matchContainerType(rewriter.getI32Type(), resultTy);
130     Type i64Ty = matchContainerType(rewriter.getI64Type(), resultTy);
131 
132     Value value = op.getValue();
133     if (getElementTypeOrSelf(value.getType()).getIntOrFloatBitWidth() > 32) {
134       return failure();
135     }
136 
137     Value value32 = op.getValue();
138     Value multiplier32 = op.getMultiplier();
139     Value shift32 = rewriter.create<arith::ExtUIOp>(loc, i32Ty, op.getShift());
140 
141     // Constants used during the scaling operation.
142     Value zero32 = getConstantValue(loc, i32Ty, 0, rewriter);
143     Value one32 = getConstantValue(loc, i32Ty, 1, rewriter);
144     Value two32 = getConstantValue(loc, i32Ty, 2, rewriter);
145     Value thirty32 = getConstantValue(loc, i32Ty, 30, rewriter);
146     Value thirtyTwo32 = getConstantValue(loc, i32Ty, 32, rewriter);
147     Value thirtyTwo64 = getConstantValue(loc, i64Ty, 32, rewriter);
148 
149     // Compute the multiplication in 64-bits then select the high / low parts.
150     Value value64 = rewriter.create<arith::ExtSIOp>(loc, i64Ty, value32);
151     Value multiplier64 =
152         rewriter.create<arith::ExtSIOp>(loc, i64Ty, multiplier32);
153     Value multiply64 =
154         rewriter.create<arith::MulIOp>(loc, value64, multiplier64);
155 
156     // Grab out the high/low of the computation
157     Value high64 =
158         rewriter.create<arith::ShRUIOp>(loc, multiply64, thirtyTwo64);
159     Value high32 = rewriter.create<arith::TruncIOp>(loc, i32Ty, high64);
160     Value low32 = rewriter.create<arith::MulIOp>(loc, value32, multiplier32);
161 
162     // Determine the direction and amount to shift the high bits.
163     Value shiftOver32 = rewriter.create<arith::CmpIOp>(
164         loc, arith::CmpIPredicate::sge, shift32, thirtyTwo32);
165     Value roundHighBits = rewriter.create<arith::CmpIOp>(
166         loc, arith::CmpIPredicate::sgt, shift32, thirtyTwo32);
167 
168     Value shiftHighL =
169         rewriter.create<arith::SubIOp>(loc, thirtyTwo32, shift32);
170     Value shiftHighR =
171         rewriter.create<arith::SubIOp>(loc, shift32, thirtyTwo32);
172 
173     shiftHighL =
174         rewriter.create<arith::SelectOp>(loc, shiftOver32, zero32, shiftHighL);
175     shiftHighR =
176         rewriter.create<arith::SelectOp>(loc, shiftOver32, shiftHighR, zero32);
177 
178     // Conditionally perform our double round.
179     if (op.getDoubleRound()) {
180       Value negOne32 = getConstantValue(loc, i32Ty, -1, rewriter);
181       Value valuePositive = rewriter.create<arith::CmpIOp>(
182           loc, arith::CmpIPredicate::sge, value32, zero32);
183 
184       Value roundDir =
185           rewriter.create<arith::SelectOp>(loc, valuePositive, one32, negOne32);
186       roundDir =
187           rewriter.create<arith::SelectOp>(loc, shiftOver32, roundDir, zero32);
188 
189       Value shiftLow = rewriter.create<arith::ShRUIOp>(loc, low32, thirty32);
190       Value rounded = rewriter.create<arith::AddIOp>(loc, shiftLow, roundDir);
191       Value carry = rewriter.create<arith::ShRSIOp>(loc, rounded, two32);
192 
193       Value shiftRound =
194           rewriter.create<arith::ShLIOp>(loc, roundDir, thirty32);
195 
196       low32 = rewriter.create<arith::AddIOp>(loc, low32, shiftRound);
197       high32 = rewriter.create<arith::AddIOp>(loc, high32, carry);
198     }
199 
200     // Conditionally apply rounding in the low bits.
201     {
202       Value shiftSubOne = rewriter.create<arith::SubIOp>(loc, shift32, one32);
203       Value roundBit = rewriter.create<arith::ShLIOp>(loc, one32, shiftSubOne);
204       roundBit = rewriter.create<arith::SelectOp>(loc, roundHighBits, zero32,
205                                                   roundBit);
206 
207       Value newLow32 = rewriter.create<arith::AddIOp>(loc, low32, roundBit);
208       Value wasRounded = rewriter.create<arith::CmpIOp>(
209           loc, arith::CmpIPredicate::ugt, low32, newLow32);
210       low32 = newLow32;
211 
212       Value rounded32 = rewriter.create<arith::ExtUIOp>(loc, i32Ty, wasRounded);
213       high32 = rewriter.create<arith::AddIOp>(loc, high32, rounded32);
214     }
215 
216     // Conditionally apply rounding in the high bits.
217     {
218       Value shiftSubOne =
219           rewriter.create<arith::SubIOp>(loc, shiftHighR, one32);
220       Value roundBit = rewriter.create<arith::ShLIOp>(loc, one32, shiftSubOne);
221       roundBit = rewriter.create<arith::SelectOp>(loc, roundHighBits, roundBit,
222                                                   zero32);
223       high32 = rewriter.create<arith::AddIOp>(loc, high32, roundBit);
224     }
225 
226     // Combine the correct high/low bits into the final rescale result.
227     high32 = rewriter.create<arith::ShLIOp>(loc, high32, shiftHighL);
228     high32 = rewriter.create<arith::ShRSIOp>(loc, high32, shiftHighR);
229     low32 = rewriter.create<arith::ShRUIOp>(loc, low32, shift32);
230     low32 = rewriter.create<arith::SelectOp>(loc, shiftOver32, zero32, low32);
231 
232     // Apply the rounding behavior and shift to the final alignment.
233     Value result = rewriter.create<arith::AddIOp>(loc, low32, high32);
234 
235     // Truncate if necessary.
236     if (!getElementTypeOrSelf(resultTy).isInteger(32)) {
237       result = rewriter.create<arith::TruncIOp>(loc, resultTy, result);
238     }
239 
240     rewriter.replaceOp(op, result);
241     return success();
242   }
243 };
244 
245 } // namespace
246 
populateTosaToArithConversionPatterns(RewritePatternSet * patterns)247 void mlir::tosa::populateTosaToArithConversionPatterns(
248     RewritePatternSet *patterns) {
249   patterns->add<ConstOpConverter>(patterns->getContext());
250 }
251 
populateTosaRescaleToArithConversionPatterns(RewritePatternSet * patterns,bool include32Bit)252 void mlir::tosa::populateTosaRescaleToArithConversionPatterns(
253     RewritePatternSet *patterns, bool include32Bit) {
254   patterns->add<ApplyScaleGenericOpConverter>(patterns->getContext(), 100);
255   if (include32Bit) {
256     patterns->add<ApplyScale32BitOpConverter>(patterns->getContext(), 200);
257   }
258 }
259