1 //===- ExpandOps.cpp - Pass to legalize Arithmetic ops for LLVM lowering --===//
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 #include "PassDetail.h"
10 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
11 #include "mlir/Dialect/Arithmetic/Transforms/Passes.h"
12 #include "mlir/Dialect/StandardOps/IR/Ops.h"
13 #include "mlir/IR/TypeUtilities.h"
14 #include "mlir/Transforms/DialectConversion.h"
15 
16 using namespace mlir;
17 
18 /// Create an integer or index constant.
19 static Value createConst(Location loc, Type type, int value,
20                          PatternRewriter &rewriter) {
21   return rewriter.create<arith::ConstantOp>(
22       loc, rewriter.getIntegerAttr(type, value));
23 }
24 
25 namespace {
26 
27 /// Expands CeilDivUIOp (n, m) into
28 ///  n == 0 ? 0 : ((n-1) / m) + 1
29 struct CeilDivUIOpConverter : public OpRewritePattern<arith::CeilDivUIOp> {
30   using OpRewritePattern::OpRewritePattern;
31   LogicalResult matchAndRewrite(arith::CeilDivUIOp op,
32                                 PatternRewriter &rewriter) const final {
33     Location loc = op.getLoc();
34     Value a = op.getLhs();
35     Value b = op.getRhs();
36     Value zero = createConst(loc, a.getType(), 0, rewriter);
37     Value compare =
38         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq, a, zero);
39     Value one = createConst(loc, a.getType(), 1, rewriter);
40     Value minusOne = rewriter.create<arith::SubIOp>(loc, a, one);
41     Value quotient = rewriter.create<arith::DivUIOp>(loc, minusOne, b);
42     Value plusOne = rewriter.create<arith::AddIOp>(loc, quotient, one);
43     rewriter.replaceOpWithNewOp<SelectOp>(op, compare, zero, plusOne);
44     return success();
45   }
46 };
47 
48 /// Expands CeilDivSIOp (n, m) into
49 ///   1) x = (m > 0) ? -1 : 1
50 ///   2) (n*m>0) ? ((n+x) / m) + 1 : - (-n / m)
51 struct CeilDivSIOpConverter : public OpRewritePattern<arith::CeilDivSIOp> {
52   using OpRewritePattern::OpRewritePattern;
53   LogicalResult matchAndRewrite(arith::CeilDivSIOp op,
54                                 PatternRewriter &rewriter) const final {
55     Location loc = op.getLoc();
56     Type type = op.getType();
57     Value a = op.getLhs();
58     Value b = op.getRhs();
59     Value plusOne = createConst(loc, type, 1, rewriter);
60     Value zero = createConst(loc, type, 0, rewriter);
61     Value minusOne = createConst(loc, type, -1, rewriter);
62     // Compute x = (b>0) ? -1 : 1.
63     Value compare =
64         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::sgt, b, zero);
65     Value x = rewriter.create<SelectOp>(loc, compare, minusOne, plusOne);
66     // Compute positive res: 1 + ((x+a)/b).
67     Value xPlusA = rewriter.create<arith::AddIOp>(loc, x, a);
68     Value xPlusADivB = rewriter.create<arith::DivSIOp>(loc, xPlusA, b);
69     Value posRes = rewriter.create<arith::AddIOp>(loc, plusOne, xPlusADivB);
70     // Compute negative res: - ((-a)/b).
71     Value minusA = rewriter.create<arith::SubIOp>(loc, zero, a);
72     Value minusADivB = rewriter.create<arith::DivSIOp>(loc, minusA, b);
73     Value negRes = rewriter.create<arith::SubIOp>(loc, zero, minusADivB);
74     // Result is (a*b>0) ? pos result : neg result.
75     // Note, we want to avoid using a*b because of possible overflow.
76     // The case that matters are a>0, a==0, a<0, b>0 and b<0. We do
77     // not particuliarly care if a*b<0 is true or false when b is zero
78     // as this will result in an illegal divide. So `a*b<0` can be reformulated
79     // as `(a<0 && b<0) || (a>0 && b>0)' or `(a<0 && b<0) || (a>0 && b>=0)'.
80     // We pick the first expression here.
81     Value aNeg =
82         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt, a, zero);
83     Value aPos =
84         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::sgt, a, zero);
85     Value bNeg =
86         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt, b, zero);
87     Value bPos =
88         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::sgt, b, zero);
89     Value firstTerm = rewriter.create<arith::AndIOp>(loc, aNeg, bNeg);
90     Value secondTerm = rewriter.create<arith::AndIOp>(loc, aPos, bPos);
91     Value compareRes =
92         rewriter.create<arith::OrIOp>(loc, firstTerm, secondTerm);
93     // Perform substitution and return success.
94     rewriter.replaceOpWithNewOp<SelectOp>(op, compareRes, posRes, negRes);
95     return success();
96   }
97 };
98 
99 /// Expands FloorDivSIOp (n, m) into
100 ///   1)  x = (m<0) ? 1 : -1
101 ///   2)  return (n*m<0) ? - ((-n+x) / m) -1 : n / m
102 struct FloorDivSIOpConverter : public OpRewritePattern<arith::FloorDivSIOp> {
103   using OpRewritePattern::OpRewritePattern;
104   LogicalResult matchAndRewrite(arith::FloorDivSIOp op,
105                                 PatternRewriter &rewriter) const final {
106     Location loc = op.getLoc();
107     Type type = op.getType();
108     Value a = op.getLhs();
109     Value b = op.getRhs();
110     Value plusOne = createConst(loc, type, 1, rewriter);
111     Value zero = createConst(loc, type, 0, rewriter);
112     Value minusOne = createConst(loc, type, -1, rewriter);
113     // Compute x = (b<0) ? 1 : -1.
114     Value compare =
115         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt, b, zero);
116     Value x = rewriter.create<SelectOp>(loc, compare, plusOne, minusOne);
117     // Compute negative res: -1 - ((x-a)/b).
118     Value xMinusA = rewriter.create<arith::SubIOp>(loc, x, a);
119     Value xMinusADivB = rewriter.create<arith::DivSIOp>(loc, xMinusA, b);
120     Value negRes = rewriter.create<arith::SubIOp>(loc, minusOne, xMinusADivB);
121     // Compute positive res: a/b.
122     Value posRes = rewriter.create<arith::DivSIOp>(loc, a, b);
123     // Result is (a*b<0) ? negative result : positive result.
124     // Note, we want to avoid using a*b because of possible overflow.
125     // The case that matters are a>0, a==0, a<0, b>0 and b<0. We do
126     // not particuliarly care if a*b<0 is true or false when b is zero
127     // as this will result in an illegal divide. So `a*b<0` can be reformulated
128     // as `(a>0 && b<0) || (a>0 && b<0)' or `(a>0 && b<0) || (a>0 && b<=0)'.
129     // We pick the first expression here.
130     Value aNeg =
131         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt, a, zero);
132     Value aPos =
133         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::sgt, a, zero);
134     Value bNeg =
135         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt, b, zero);
136     Value bPos =
137         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::sgt, b, zero);
138     Value firstTerm = rewriter.create<arith::AndIOp>(loc, aNeg, bPos);
139     Value secondTerm = rewriter.create<arith::AndIOp>(loc, aPos, bNeg);
140     Value compareRes =
141         rewriter.create<arith::OrIOp>(loc, firstTerm, secondTerm);
142     // Perform substitution and return success.
143     rewriter.replaceOpWithNewOp<SelectOp>(op, compareRes, negRes, posRes);
144     return success();
145   }
146 };
147 
148 template <typename OpTy, arith::CmpFPredicate pred>
149 struct MaxMinFOpConverter : public OpRewritePattern<OpTy> {
150 public:
151   using OpRewritePattern<OpTy>::OpRewritePattern;
152 
153   LogicalResult matchAndRewrite(OpTy op,
154                                 PatternRewriter &rewriter) const final {
155     Value lhs = op.getLhs();
156     Value rhs = op.getRhs();
157 
158     Location loc = op.getLoc();
159     // If any operand is NaN, 'cmp' will be true (and 'select' returns 'lhs').
160     static_assert(pred == arith::CmpFPredicate::UGT ||
161                   pred == arith::CmpFPredicate::ULT);
162     Value cmp = rewriter.create<arith::CmpFOp>(loc, pred, lhs, rhs);
163     Value select = rewriter.create<SelectOp>(loc, cmp, lhs, rhs);
164 
165     // Handle the case where rhs is NaN: 'isNaN(rhs) ? rhs : select'.
166     Value isNaN = rewriter.create<arith::CmpFOp>(loc, arith::CmpFPredicate::UNO,
167                                                  rhs, rhs);
168     rewriter.replaceOpWithNewOp<SelectOp>(op, isNaN, rhs, select);
169     return success();
170   }
171 };
172 
173 template <typename OpTy, arith::CmpIPredicate pred>
174 struct MaxMinIOpConverter : public OpRewritePattern<OpTy> {
175 public:
176   using OpRewritePattern<OpTy>::OpRewritePattern;
177   LogicalResult matchAndRewrite(OpTy op,
178                                 PatternRewriter &rewriter) const final {
179     Value lhs = op.getLhs();
180     Value rhs = op.getRhs();
181 
182     Location loc = op.getLoc();
183     Value cmp = rewriter.create<arith::CmpIOp>(loc, pred, lhs, rhs);
184     rewriter.replaceOpWithNewOp<SelectOp>(op, cmp, lhs, rhs);
185     return success();
186   }
187 };
188 
189 struct ArithmeticExpandOpsPass
190     : public ArithmeticExpandOpsBase<ArithmeticExpandOpsPass> {
191   void runOnFunction() override {
192     RewritePatternSet patterns(&getContext());
193     ConversionTarget target(getContext());
194 
195     arith::populateArithmeticExpandOpsPatterns(patterns);
196 
197     target.addLegalDialect<arith::ArithmeticDialect, StandardOpsDialect>();
198     // clang-format off
199     target.addIllegalOp<
200       arith::CeilDivSIOp,
201       arith::CeilDivUIOp,
202       arith::FloorDivSIOp,
203       arith::MaxFOp,
204       arith::MaxSIOp,
205       arith::MaxUIOp,
206       arith::MinFOp,
207       arith::MinSIOp,
208       arith::MinUIOp
209     >();
210     // clang-format on
211     if (failed(
212             applyPartialConversion(getFunction(), target, std::move(patterns))))
213       signalPassFailure();
214   }
215 };
216 
217 } // namespace
218 
219 void mlir::arith::populateArithmeticExpandOpsPatterns(
220     RewritePatternSet &patterns) {
221   // clang-format off
222   patterns.add<
223     CeilDivSIOpConverter,
224     CeilDivUIOpConverter,
225     FloorDivSIOpConverter,
226     MaxMinFOpConverter<MaxFOp, arith::CmpFPredicate::UGT>,
227     MaxMinFOpConverter<MinFOp, arith::CmpFPredicate::ULT>,
228     MaxMinIOpConverter<MaxSIOp, arith::CmpIPredicate::sgt>,
229     MaxMinIOpConverter<MaxUIOp, arith::CmpIPredicate::ugt>,
230     MaxMinIOpConverter<MinSIOp, arith::CmpIPredicate::slt>,
231     MaxMinIOpConverter<MinUIOp, arith::CmpIPredicate::ult>
232    >(patterns.getContext());
233   // clang-format on
234 }
235 
236 std::unique_ptr<Pass> mlir::arith::createArithmeticExpandOpsPass() {
237   return std::make_unique<ArithmeticExpandOpsPass>();
238 }
239