MLIR 24.0.0git
ComplexToStandard.cpp
Go to the documentation of this file.
1//===- ComplexToStandard.cpp - conversion from Complex to Standard 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
10
17#include <type_traits>
18
19namespace mlir {
20#define GEN_PASS_DEF_CONVERTCOMPLEXTOSTANDARDPASS
21#include "mlir/Conversion/Passes.h.inc"
22} // namespace mlir
23
24using namespace mlir;
25
26namespace {
27
28enum class AbsFn { abs, sqrt, rsqrt };
29
30// Returns the absolute value, its square root or its reciprocal square root.
31Value computeAbs(Value real, Value imag, arith::FastMathFlags fmf,
32 ImplicitLocOpBuilder &b, AbsFn fn = AbsFn::abs) {
33 Value one = arith::ConstantOp::create(b, real.getType(),
34 b.getFloatAttr(real.getType(), 1.0));
35
36 Value absReal = math::AbsFOp::create(b, real, fmf);
37 Value absImag = math::AbsFOp::create(b, imag, fmf);
38
39 Value max = arith::MaximumFOp::create(b, absReal, absImag, fmf);
40 Value min = arith::MinimumFOp::create(b, absReal, absImag, fmf);
41
42 // The lowering below requires NaNs and infinities to work correctly.
43 arith::FastMathFlags fmfWithNaNInf = arith::bitEnumClear(
44 fmf, arith::FastMathFlags::nnan | arith::FastMathFlags::ninf);
45 Value ratio = arith::DivFOp::create(b, min, max, fmfWithNaNInf);
46 Value ratioSq = arith::MulFOp::create(b, ratio, ratio, fmfWithNaNInf);
47 Value ratioSqPlusOne = arith::AddFOp::create(b, ratioSq, one, fmfWithNaNInf);
49
50 if (fn == AbsFn::rsqrt) {
51 ratioSqPlusOne = math::RsqrtOp::create(b, ratioSqPlusOne, fmfWithNaNInf);
52 min = math::RsqrtOp::create(b, min, fmfWithNaNInf);
53 max = math::RsqrtOp::create(b, max, fmfWithNaNInf);
54 }
55
56 if (fn == AbsFn::sqrt) {
57 Value quarter = arith::ConstantOp::create(
58 b, real.getType(), b.getFloatAttr(real.getType(), 0.25));
59 // sqrt(sqrt(a*b)) would avoid the pow, but will overflow more easily.
60 Value sqrt = math::SqrtOp::create(b, max, fmfWithNaNInf);
61 Value p025 =
62 math::PowFOp::create(b, ratioSqPlusOne, quarter, fmfWithNaNInf);
63 result = arith::MulFOp::create(b, sqrt, p025, fmfWithNaNInf);
64 } else {
65 Value sqrt = math::SqrtOp::create(b, ratioSqPlusOne, fmfWithNaNInf);
66 result = arith::MulFOp::create(b, max, sqrt, fmfWithNaNInf);
67 }
68
69 Value isNaN = arith::CmpFOp::create(b, arith::CmpFPredicate::UNO, result,
70 result, fmfWithNaNInf);
71 return arith::SelectOp::create(b, isNaN, min, result);
72}
73
74struct AbsOpConversion : public OpConversionPattern<complex::AbsOp> {
75 using OpConversionPattern<complex::AbsOp>::OpConversionPattern;
76
77 LogicalResult
78 matchAndRewrite(complex::AbsOp op, OpAdaptor adaptor,
79 ConversionPatternRewriter &rewriter) const override {
80 ImplicitLocOpBuilder b(op.getLoc(), rewriter);
81
82 arith::FastMathFlags fmf = op.getFastMathFlagsAttr().getValue();
83
84 Value real = complex::ReOp::create(b, adaptor.getComplex());
85 Value imag = complex::ImOp::create(b, adaptor.getComplex());
86 rewriter.replaceOp(op, computeAbs(real, imag, fmf, b));
87
88 return success();
89 }
90};
91
92// atan2(y,x) = -i * log((x + i * y)/sqrt(x**2+y**2))
93struct Atan2OpConversion : public OpConversionPattern<complex::Atan2Op> {
94 using OpConversionPattern<complex::Atan2Op>::OpConversionPattern;
95
96 LogicalResult
97 matchAndRewrite(complex::Atan2Op op, OpAdaptor adaptor,
98 ConversionPatternRewriter &rewriter) const override {
99 mlir::ImplicitLocOpBuilder b(op.getLoc(), rewriter);
100
101 auto type = cast<ComplexType>(op.getType());
102 Type elementType = type.getElementType();
103 arith::FastMathFlagsAttr fmf = op.getFastMathFlagsAttr();
104
105 Value lhs = adaptor.getLhs();
106 Value rhs = adaptor.getRhs();
107
108 Value rhsSquared = complex::MulOp::create(b, type, rhs, rhs, fmf);
109 Value lhsSquared = complex::MulOp::create(b, type, lhs, lhs, fmf);
110 Value rhsSquaredPlusLhsSquared =
111 complex::AddOp::create(b, type, rhsSquared, lhsSquared, fmf);
112 Value sqrtOfRhsSquaredPlusLhsSquared =
113 complex::SqrtOp::create(b, type, rhsSquaredPlusLhsSquared, fmf);
114
115 Value zero =
116 arith::ConstantOp::create(b, elementType, b.getZeroAttr(elementType));
117 Value one = arith::ConstantOp::create(b, elementType,
118 b.getFloatAttr(elementType, 1));
119 Value i = complex::CreateOp::create(b, type, zero, one);
120 Value iTimesLhs = complex::MulOp::create(b, i, lhs, fmf);
121 Value rhsPlusILhs = complex::AddOp::create(b, rhs, iTimesLhs, fmf);
122
123 Value divResult = complex::DivOp::create(
124 b, rhsPlusILhs, sqrtOfRhsSquaredPlusLhsSquared, fmf);
125 Value logResult = complex::LogOp::create(b, divResult, fmf);
126
127 Value negativeOne = arith::ConstantOp::create(
128 b, elementType, b.getFloatAttr(elementType, -1));
129 Value negativeI = complex::CreateOp::create(b, type, zero, negativeOne);
130
131 rewriter.replaceOpWithNewOp<complex::MulOp>(op, negativeI, logResult, fmf);
132 return success();
133 }
134};
135
136template <typename ComparisonOp, arith::CmpFPredicate p>
137struct ComparisonOpConversion : public OpConversionPattern<ComparisonOp> {
138 using OpConversionPattern<ComparisonOp>::OpConversionPattern;
139 using ResultCombiner =
140 std::conditional_t<std::is_same<ComparisonOp, complex::EqualOp>::value,
141 arith::AndIOp, arith::OrIOp>;
142
143 LogicalResult
144 matchAndRewrite(ComparisonOp op, typename ComparisonOp::Adaptor adaptor,
145 ConversionPatternRewriter &rewriter) const override {
146 auto loc = op.getLoc();
147 auto type = cast<ComplexType>(adaptor.getLhs().getType()).getElementType();
148
149 Value realLhs =
150 complex::ReOp::create(rewriter, loc, type, adaptor.getLhs());
151 Value imagLhs =
152 complex::ImOp::create(rewriter, loc, type, adaptor.getLhs());
153 Value realRhs =
154 complex::ReOp::create(rewriter, loc, type, adaptor.getRhs());
155 Value imagRhs =
156 complex::ImOp::create(rewriter, loc, type, adaptor.getRhs());
157 Value realComparison =
158 arith::CmpFOp::create(rewriter, loc, p, realLhs, realRhs);
159 Value imagComparison =
160 arith::CmpFOp::create(rewriter, loc, p, imagLhs, imagRhs);
161
162 rewriter.replaceOpWithNewOp<ResultCombiner>(op, realComparison,
163 imagComparison);
164 return success();
165 }
166};
167
168// Default conversion which applies the BinaryStandardOp separately on the real
169// and imaginary parts. Can for example be used for complex::AddOp and
170// complex::SubOp.
171template <typename BinaryComplexOp, typename BinaryStandardOp>
172struct BinaryComplexOpConversion : public OpConversionPattern<BinaryComplexOp> {
173 using OpConversionPattern<BinaryComplexOp>::OpConversionPattern;
174
175 LogicalResult
176 matchAndRewrite(BinaryComplexOp op, typename BinaryComplexOp::Adaptor adaptor,
177 ConversionPatternRewriter &rewriter) const override {
178 auto type = cast<ComplexType>(adaptor.getLhs().getType());
179 auto elementType = cast<FloatType>(type.getElementType());
180 mlir::ImplicitLocOpBuilder b(op.getLoc(), rewriter);
181 arith::FastMathFlagsAttr fmf = op.getFastMathFlagsAttr();
182
183 Value realLhs = complex::ReOp::create(b, elementType, adaptor.getLhs());
184 Value realRhs = complex::ReOp::create(b, elementType, adaptor.getRhs());
185 Value resultReal = BinaryStandardOp::create(b, elementType, realLhs,
186 realRhs, fmf.getValue());
187 Value imagLhs = complex::ImOp::create(b, elementType, adaptor.getLhs());
188 Value imagRhs = complex::ImOp::create(b, elementType, adaptor.getRhs());
189 Value resultImag = BinaryStandardOp::create(b, elementType, imagLhs,
190 imagRhs, fmf.getValue());
191 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, resultReal,
192 resultImag);
193 return success();
194 }
195};
196
197template <typename TrigonometricOp>
198struct TrigonometricOpConversion : public OpConversionPattern<TrigonometricOp> {
199 using OpAdaptor = typename OpConversionPattern<TrigonometricOp>::OpAdaptor;
200
201 using OpConversionPattern<TrigonometricOp>::OpConversionPattern;
202
203 LogicalResult
204 matchAndRewrite(TrigonometricOp op, OpAdaptor adaptor,
205 ConversionPatternRewriter &rewriter) const override {
206 auto loc = op.getLoc();
207 auto type = cast<ComplexType>(adaptor.getComplex().getType());
208 auto elementType = cast<FloatType>(type.getElementType());
209 arith::FastMathFlagsAttr fmf = op.getFastMathFlagsAttr();
210
211 Value real =
212 complex::ReOp::create(rewriter, loc, elementType, adaptor.getComplex());
213 Value imag =
214 complex::ImOp::create(rewriter, loc, elementType, adaptor.getComplex());
215
216 // Trigonometric ops use a set of common building blocks to convert to real
217 // ops. Here we create these building blocks and call into an op-specific
218 // implementation in the subclass to combine them.
219 Value half = arith::ConstantOp::create(
220 rewriter, loc, elementType, rewriter.getFloatAttr(elementType, 0.5));
221 Value exp = math::ExpOp::create(rewriter, loc, imag, fmf);
222 Value scaledExp = arith::MulFOp::create(rewriter, loc, half, exp, fmf);
223 Value reciprocalExp = arith::DivFOp::create(rewriter, loc, half, exp, fmf);
224 Value sin = math::SinOp::create(rewriter, loc, real, fmf);
225 Value cos = math::CosOp::create(rewriter, loc, real, fmf);
226
227 auto resultPair =
228 combine(loc, scaledExp, reciprocalExp, sin, cos, rewriter, fmf);
229
230 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, resultPair.first,
231 resultPair.second);
232 return success();
233 }
234
235 virtual std::pair<Value, Value>
236 combine(Location loc, Value scaledExp, Value reciprocalExp, Value sin,
237 Value cos, ConversionPatternRewriter &rewriter,
238 arith::FastMathFlagsAttr fmf) const = 0;
239};
240
241struct CosOpConversion : public TrigonometricOpConversion<complex::CosOp> {
242 using TrigonometricOpConversion<complex::CosOp>::TrigonometricOpConversion;
243
244 std::pair<Value, Value> combine(Location loc, Value scaledExp,
245 Value reciprocalExp, Value sin, Value cos,
246 ConversionPatternRewriter &rewriter,
247 arith::FastMathFlagsAttr fmf) const override {
248 // Complex cosine is defined as;
249 // cos(x + iy) = 0.5 * (exp(i(x + iy)) + exp(-i(x + iy)))
250 // Plugging in:
251 // exp(i(x+iy)) = exp(-y + ix) = exp(-y)(cos(x) + i sin(x))
252 // exp(-i(x+iy)) = exp(y + i(-x)) = exp(y)(cos(x) + i (-sin(x)))
253 // and defining t := exp(y)
254 // We get:
255 // Re(cos(x + iy)) = (0.5/t + 0.5*t) * cos x
256 // Im(cos(x + iy)) = (0.5/t - 0.5*t) * sin x
257 Value sum =
258 arith::AddFOp::create(rewriter, loc, reciprocalExp, scaledExp, fmf);
259 Value resultReal = arith::MulFOp::create(rewriter, loc, sum, cos, fmf);
260 Value diff =
261 arith::SubFOp::create(rewriter, loc, reciprocalExp, scaledExp, fmf);
262 Value resultImag = arith::MulFOp::create(rewriter, loc, diff, sin, fmf);
263 return {resultReal, resultImag};
264 }
265};
266
267struct DivOpConversion : public OpConversionPattern<complex::DivOp> {
268 DivOpConversion(MLIRContext *context, complex::ComplexRangeFlags target)
269 : OpConversionPattern<complex::DivOp>(context), complexRange(target) {}
270
271 using OpConversionPattern<complex::DivOp>::OpConversionPattern;
272
273 LogicalResult
274 matchAndRewrite(complex::DivOp op, OpAdaptor adaptor,
275 ConversionPatternRewriter &rewriter) const override {
276 auto loc = op.getLoc();
277 auto type = cast<ComplexType>(adaptor.getLhs().getType());
278 auto elementType = cast<FloatType>(type.getElementType());
279 arith::FastMathFlagsAttr fmf = op.getFastMathFlagsAttr();
280
281 Value lhsReal =
282 complex::ReOp::create(rewriter, loc, elementType, adaptor.getLhs());
283 Value lhsImag =
284 complex::ImOp::create(rewriter, loc, elementType, adaptor.getLhs());
285 Value rhsReal =
286 complex::ReOp::create(rewriter, loc, elementType, adaptor.getRhs());
287 Value rhsImag =
288 complex::ImOp::create(rewriter, loc, elementType, adaptor.getRhs());
289
290 Value resultReal, resultImag;
291
292 if (complexRange == complex::ComplexRangeFlags::basic ||
293 complexRange == complex::ComplexRangeFlags::none) {
295 rewriter, loc, lhsReal, lhsImag, rhsReal, rhsImag, fmf, &resultReal,
296 &resultImag);
297 } else if (complexRange == complex::ComplexRangeFlags::improved) {
299 rewriter, loc, lhsReal, lhsImag, rhsReal, rhsImag, fmf, &resultReal,
300 &resultImag);
301 }
302
303 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, resultReal,
304 resultImag);
305
306 return success();
307 }
308
309private:
310 complex::ComplexRangeFlags complexRange;
311};
312
313struct ExpOpConversion : public OpConversionPattern<complex::ExpOp> {
314 using OpConversionPattern<complex::ExpOp>::OpConversionPattern;
315
316 // exp(x+I*y) = exp(x)*(cos(y)+I*sin(y))
317 // Handle special cases as StableHLO implementation does:
318 // 1. When y == +-0, set imag(exp(z)) = y
319 // 2. When exp(x) == inf, use exp(x/2)*(cos(y)+I*sin(y))*exp(x/2)
320 // Handle non-finite inputs according to C99 annex G:
321 // 3. When x == -inf and y is non-finite, return 0 + I*0.
322 // 4. When x == +inf and y is non-finite, return inf + I*NaN.
323 LogicalResult
324 matchAndRewrite(complex::ExpOp op, OpAdaptor adaptor,
325 ConversionPatternRewriter &rewriter) const override {
326 auto loc = op.getLoc();
327 auto type = cast<ComplexType>(adaptor.getComplex().getType());
328 auto ET = cast<FloatType>(type.getElementType());
329 arith::FastMathFlags fmf = op.getFastMathFlagsAttr().getValue();
330 const auto &floatSemantics = ET.getFloatSemantics();
331 ImplicitLocOpBuilder b(loc, rewriter);
332
333 Value x = complex::ReOp::create(b, ET, adaptor.getComplex());
334 Value y = complex::ImOp::create(b, ET, adaptor.getComplex());
335 Value zero = arith::ConstantOp::create(b, ET, b.getZeroAttr(ET));
336 Value half = arith::ConstantOp::create(b, ET, b.getFloatAttr(ET, 0.5));
337 Value inf = arith::ConstantOp::create(
338 b, ET, b.getFloatAttr(ET, APFloat::getInf(floatSemantics)));
339
340 // Intermediate exp may overflow.
341 arith::FastMathFlags fmfWithInf =
342 arith::bitEnumClear(fmf, arith::FastMathFlags::ninf);
343 Value exp = math::ExpOp::create(b, x, fmfWithInf);
344 Value xHalf = arith::MulFOp::create(b, x, half, fmf);
345 Value expHalf = math::ExpOp::create(b, xHalf, fmf);
346 Value cos = math::CosOp::create(b, y, fmf);
347 Value sin = math::SinOp::create(b, y, fmf);
348
349 Value expIsInf = arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, exp,
350 inf, fmfWithInf);
351 Value yIsZero =
352 arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, y, zero);
353
354 // Real path: select between exp(x)*cos(y) and exp(x/2)*cos(y)*exp(x/2)
355 Value realNormal = arith::MulFOp::create(b, exp, cos, fmf);
356 Value expHalfCos = arith::MulFOp::create(b, expHalf, cos, fmf);
357 Value realOverflow = arith::MulFOp::create(b, expHalfCos, expHalf, fmf);
358 Value resultReal =
359 arith::SelectOp::create(b, expIsInf, realOverflow, realNormal);
360
361 // Imaginary part: if y == +-0 return +-0 else select between exp(x)*sin(y)
362 // and exp(x/2)*sin(y)*exp(x/2)
363 Value imagNormal = arith::MulFOp::create(b, exp, sin, fmf);
364 Value expHalfSin = arith::MulFOp::create(b, expHalf, sin, fmf);
365 Value imagOverflow = arith::MulFOp::create(b, expHalfSin, expHalf, fmf);
366 Value imagNonZero =
367 arith::SelectOp::create(b, expIsInf, imagOverflow, imagNormal);
368 Value resultImag = arith::SelectOp::create(b, yIsZero, y, imagNonZero);
369
370 // When x is +-inf and y is +-inf or NaN, exp(x) * cos(y) is inf * NaN or
371 // 0 * NaN. C99 Annex G gives exp(-inf + I*y) = +-0 +- 0*I and
372 // exp(+inf + I*y) = +-inf + NaN*I for these y.
373 if (!arith::bitEnumContainsAll(fmf, arith::FastMathFlags::ninf)) {
374 Value absX = math::AbsFOp::create(b, x);
375 Value absY = math::AbsFOp::create(b, y);
376 Value yIsNotFinite =
377 arith::CmpFOp::create(b, arith::CmpFPredicate::UGE, absY, inf);
378 Value xIsInf =
379 arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, absX, inf);
380 Value xIsNeg =
381 arith::CmpFOp::create(b, arith::CmpFPredicate::OLT, x, zero);
382 Value useExpX = arith::AndIOp::create(b, xIsInf, yIsNotFinite);
383 Value useZeroImag = arith::AndIOp::create(b, useExpX, xIsNeg);
384 resultReal = arith::SelectOp::create(b, useExpX, exp, resultReal);
385 resultImag = arith::SelectOp::create(b, useZeroImag, zero, resultImag);
386 }
387
388 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, resultReal,
389 resultImag);
390 return success();
391 }
392};
393
394Value evaluatePolynomial(ImplicitLocOpBuilder &b, Value arg,
395 ArrayRef<double> coefficients,
396 arith::FastMathFlagsAttr fmf) {
397 auto argType = mlir::cast<FloatType>(arg.getType());
398 Value poly =
399 arith::ConstantOp::create(b, b.getFloatAttr(argType, coefficients[0]));
400 for (unsigned i = 1; i < coefficients.size(); ++i) {
401 poly = math::FmaOp::create(
402 b, poly, arg,
403 arith::ConstantOp::create(b, b.getFloatAttr(argType, coefficients[i])),
404 fmf);
405 }
406 return poly;
407}
408
409struct Expm1OpConversion : public OpConversionPattern<complex::Expm1Op> {
410 using OpConversionPattern<complex::Expm1Op>::OpConversionPattern;
411
412 // e^(a+bi)-1 = (e^a*cos(b)-1)+e^a*sin(b)i
413 // [handle inaccuracies when a and/or b are small]
414 // = ((e^a - 1) * cos(b) + cos(b) - 1) + e^a*sin(b)i
415 // = (expm1(a) * cos(b) + cosm1(b)) + e^a*sin(b)i
416 LogicalResult
417 matchAndRewrite(complex::Expm1Op op, OpAdaptor adaptor,
418 ConversionPatternRewriter &rewriter) const override {
419 auto type = op.getType();
420 auto elemType = mlir::cast<FloatType>(type.getElementType());
421
422 arith::FastMathFlagsAttr fmf = op.getFastMathFlagsAttr();
423 ImplicitLocOpBuilder b(op.getLoc(), rewriter);
424 Value real = complex::ReOp::create(b, adaptor.getComplex());
425 Value imag = complex::ImOp::create(b, adaptor.getComplex());
426
427 Value zero = arith::ConstantOp::create(b, b.getFloatAttr(elemType, 0.0));
428 Value one = arith::ConstantOp::create(b, b.getFloatAttr(elemType, 1.0));
429
430 Value expm1Real = math::ExpM1Op::create(b, real, fmf);
431 Value expReal = arith::AddFOp::create(b, expm1Real, one, fmf);
432
433 Value sinImag = math::SinOp::create(b, imag, fmf);
434 Value cosm1Imag = emitCosm1(imag, fmf, b);
435 Value cosImag = arith::AddFOp::create(b, cosm1Imag, one, fmf);
436
437 Value realResult = arith::AddFOp::create(
438 b, arith::MulFOp::create(b, expm1Real, cosImag, fmf), cosm1Imag, fmf);
439
440 Value imagIsZero = arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, imag,
441 zero, fmf.getValue());
442 Value imagResult = arith::SelectOp::create(
443 b, imagIsZero, zero, arith::MulFOp::create(b, expReal, sinImag, fmf));
444
445 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, realResult,
446 imagResult);
447 return success();
448 }
449
450private:
451 Value emitCosm1(Value arg, arith::FastMathFlagsAttr fmf,
452 ImplicitLocOpBuilder &b) const {
453 auto argType = mlir::cast<FloatType>(arg.getType());
454 auto negHalf = arith::ConstantOp::create(b, b.getFloatAttr(argType, -0.5));
455 auto one = arith::ConstantOp::create(b, b.getFloatAttr(argType, 1.0));
456
457 // Algorithm copied from cephes cosm1.
458 SmallVector<double, 7> kCoeffs{
459 4.7377507964246204691685E-14, -1.1470284843425359765671E-11,
460 2.0876754287081521758361E-9, -2.7557319214999787979814E-7,
461 2.4801587301570552304991E-5, -1.3888888888888872993737E-3,
462 4.1666666666666666609054E-2,
463 };
464 Value cos = math::CosOp::create(b, arg, fmf);
465 Value forLargeArg = arith::SubFOp::create(b, cos, one, fmf);
466
467 Value argPow2 = arith::MulFOp::create(b, arg, arg, fmf);
468 Value argPow4 = arith::MulFOp::create(b, argPow2, argPow2, fmf);
469 Value poly = evaluatePolynomial(b, argPow2, kCoeffs, fmf);
470
471 auto forSmallArg =
472 arith::AddFOp::create(b, arith::MulFOp::create(b, argPow4, poly, fmf),
473 arith::MulFOp::create(b, negHalf, argPow2, fmf));
474
475 // (pi/4)^2 is approximately 0.61685
476 Value piOver4Pow2 =
477 arith::ConstantOp::create(b, b.getFloatAttr(argType, 0.61685));
478 Value cond = arith::CmpFOp::create(b, arith::CmpFPredicate::OGE, argPow2,
479 piOver4Pow2, fmf.getValue());
480 return arith::SelectOp::create(b, cond, forLargeArg, forSmallArg);
481 }
482};
483
484struct LogOpConversion : public OpConversionPattern<complex::LogOp> {
485 using OpConversionPattern<complex::LogOp>::OpConversionPattern;
486
487 LogicalResult
488 matchAndRewrite(complex::LogOp op, OpAdaptor adaptor,
489 ConversionPatternRewriter &rewriter) const override {
490 auto type = cast<ComplexType>(adaptor.getComplex().getType());
491 auto elementType = cast<FloatType>(type.getElementType());
492 arith::FastMathFlagsAttr fmf = op.getFastMathFlagsAttr();
493 mlir::ImplicitLocOpBuilder b(op.getLoc(), rewriter);
494
495 Value abs = complex::AbsOp::create(b, elementType, adaptor.getComplex(),
496 fmf.getValue());
497 Value resultReal = math::LogOp::create(b, elementType, abs, fmf.getValue());
498 Value real = complex::ReOp::create(b, elementType, adaptor.getComplex());
499 Value imag = complex::ImOp::create(b, elementType, adaptor.getComplex());
500 Value resultImag =
501 math::Atan2Op::create(b, elementType, imag, real, fmf.getValue());
502 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, resultReal,
503 resultImag);
504 return success();
505 }
506};
507
508struct Log1pOpConversion : public OpConversionPattern<complex::Log1pOp> {
509 using OpConversionPattern<complex::Log1pOp>::OpConversionPattern;
510
511 LogicalResult
512 matchAndRewrite(complex::Log1pOp op, OpAdaptor adaptor,
513 ConversionPatternRewriter &rewriter) const override {
514 auto type = cast<ComplexType>(adaptor.getComplex().getType());
515 auto elementType = cast<FloatType>(type.getElementType());
516 arith::FastMathFlags fmf = op.getFastMathFlagsAttr().getValue();
517 mlir::ImplicitLocOpBuilder b(op.getLoc(), rewriter);
518
519 Value real = complex::ReOp::create(b, adaptor.getComplex());
520 Value imag = complex::ImOp::create(b, adaptor.getComplex());
521
522 Value half = arith::ConstantOp::create(b, elementType,
523 b.getFloatAttr(elementType, 0.5));
524 Value one = arith::ConstantOp::create(b, elementType,
525 b.getFloatAttr(elementType, 1));
526 Value realPlusOne = arith::AddFOp::create(b, real, one, fmf);
527 Value absRealPlusOne = math::AbsFOp::create(b, realPlusOne, fmf);
528 Value absImag = math::AbsFOp::create(b, imag, fmf);
529
530 Value maxAbs = arith::MaximumFOp::create(b, absRealPlusOne, absImag, fmf);
531 Value minAbs = arith::MinimumFOp::create(b, absRealPlusOne, absImag, fmf);
532
533 Value useReal = arith::CmpFOp::create(b, arith::CmpFPredicate::OGT,
534 realPlusOne, absImag, fmf);
535 Value maxMinusOne = arith::SubFOp::create(b, maxAbs, one, fmf);
536 Value maxAbsOfRealPlusOneAndImagMinusOne =
537 arith::SelectOp::create(b, useReal, real, maxMinusOne);
538 arith::FastMathFlags fmfWithNaNInf = arith::bitEnumClear(
539 fmf, arith::FastMathFlags::nnan | arith::FastMathFlags::ninf);
540 Value minMaxRatio = arith::DivFOp::create(b, minAbs, maxAbs, fmfWithNaNInf);
541 Value logOfMaxAbsOfRealPlusOneAndImag =
542 math::Log1pOp::create(b, maxAbsOfRealPlusOneAndImagMinusOne, fmf);
543 Value logOfSqrtPart = math::Log1pOp::create(
544 b, arith::MulFOp::create(b, minMaxRatio, minMaxRatio, fmfWithNaNInf),
545 fmfWithNaNInf);
546 Value r = arith::AddFOp::create(
547 b, arith::MulFOp::create(b, half, logOfSqrtPart, fmfWithNaNInf),
548 logOfMaxAbsOfRealPlusOneAndImag, fmfWithNaNInf);
549 Value resultReal = arith::SelectOp::create(
550 b,
551 arith::CmpFOp::create(b, arith::CmpFPredicate::UNO, r, r,
552 fmfWithNaNInf),
553 minAbs, r);
554 Value resultImag = math::Atan2Op::create(b, imag, realPlusOne, fmf);
555 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, resultReal,
556 resultImag);
557 return success();
558 }
559};
560
561struct MulOpConversion : public OpConversionPattern<complex::MulOp> {
562 using OpConversionPattern<complex::MulOp>::OpConversionPattern;
563
564 LogicalResult
565 matchAndRewrite(complex::MulOp op, OpAdaptor adaptor,
566 ConversionPatternRewriter &rewriter) const override {
567 mlir::ImplicitLocOpBuilder b(op.getLoc(), rewriter);
568 auto type = cast<ComplexType>(adaptor.getLhs().getType());
569 auto elementType = cast<FloatType>(type.getElementType());
570 arith::FastMathFlagsAttr fmf = op.getFastMathFlagsAttr();
571 auto fmfValue = fmf.getValue();
572 Value lhsReal = complex::ReOp::create(b, elementType, adaptor.getLhs());
573 Value lhsImag = complex::ImOp::create(b, elementType, adaptor.getLhs());
574 Value rhsReal = complex::ReOp::create(b, elementType, adaptor.getRhs());
575 Value rhsImag = complex::ImOp::create(b, elementType, adaptor.getRhs());
576 Value real;
577 Value imag;
578 if (arith::bitEnumContainsAll(fmfValue, arith::FastMathFlags::contract)) {
579 Value lhsImagTimesRhsImag =
580 arith::MulFOp::create(b, lhsImag, rhsImag, fmfValue);
581 Value negLhsImagTimesRhsImag =
582 arith::NegFOp::create(b, lhsImagTimesRhsImag, fmfValue);
583 real = math::FmaOp::create(b, lhsReal, rhsReal, negLhsImagTimesRhsImag,
584 fmfValue);
585
586 Value lhsImagTimesRhsReal =
587 arith::MulFOp::create(b, lhsImag, rhsReal, fmfValue);
588 imag = math::FmaOp::create(b, lhsReal, rhsImag, lhsImagTimesRhsReal,
589 fmfValue);
590 } else {
591 Value lhsRealTimesRhsReal =
592 arith::MulFOp::create(b, lhsReal, rhsReal, fmfValue);
593 Value lhsImagTimesRhsImag =
594 arith::MulFOp::create(b, lhsImag, rhsImag, fmfValue);
595 Value lhsImagTimesRhsReal =
596 arith::MulFOp::create(b, lhsImag, rhsReal, fmfValue);
597 Value lhsRealTimesRhsImag =
598 arith::MulFOp::create(b, lhsReal, rhsImag, fmfValue);
599
600 real = arith::SubFOp::create(b, lhsRealTimesRhsReal, lhsImagTimesRhsImag,
601 fmfValue);
602 imag = arith::AddFOp::create(b, lhsImagTimesRhsReal, lhsRealTimesRhsImag,
603 fmfValue);
604 }
605 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, real, imag);
606 return success();
607 }
608};
609
610struct NegOpConversion : public OpConversionPattern<complex::NegOp> {
611 using OpConversionPattern<complex::NegOp>::OpConversionPattern;
612
613 LogicalResult
614 matchAndRewrite(complex::NegOp op, OpAdaptor adaptor,
615 ConversionPatternRewriter &rewriter) const override {
616 auto loc = op.getLoc();
617 auto type = cast<ComplexType>(adaptor.getComplex().getType());
618 auto elementType = cast<FloatType>(type.getElementType());
619 arith::FastMathFlags fmf = op.getFastMathFlagsAttr().getValue();
620
621 Value real =
622 complex::ReOp::create(rewriter, loc, elementType, adaptor.getComplex());
623 Value imag =
624 complex::ImOp::create(rewriter, loc, elementType, adaptor.getComplex());
625 Value negReal = arith::NegFOp::create(rewriter, loc, real, fmf);
626 Value negImag = arith::NegFOp::create(rewriter, loc, imag, fmf);
627 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, negReal, negImag);
628 return success();
629 }
630};
631
632struct SinOpConversion : public TrigonometricOpConversion<complex::SinOp> {
633 using TrigonometricOpConversion<complex::SinOp>::TrigonometricOpConversion;
634
635 std::pair<Value, Value> combine(Location loc, Value scaledExp,
636 Value reciprocalExp, Value sin, Value cos,
637 ConversionPatternRewriter &rewriter,
638 arith::FastMathFlagsAttr fmf) const override {
639 // Complex sine is defined as;
640 // sin(x + iy) = -0.5i * (exp(i(x + iy)) - exp(-i(x + iy)))
641 // Plugging in:
642 // exp(i(x+iy)) = exp(-y + ix) = exp(-y)(cos(x) + i sin(x))
643 // exp(-i(x+iy)) = exp(y + i(-x)) = exp(y)(cos(x) + i (-sin(x)))
644 // and defining t := exp(y)
645 // We get:
646 // Re(sin(x + iy)) = (0.5*t + 0.5/t) * sin x
647 // Im(sin(x + iy)) = (0.5*t - 0.5/t) * cos x
648 Value sum =
649 arith::AddFOp::create(rewriter, loc, scaledExp, reciprocalExp, fmf);
650 Value resultReal = arith::MulFOp::create(rewriter, loc, sum, sin, fmf);
651 Value diff =
652 arith::SubFOp::create(rewriter, loc, scaledExp, reciprocalExp, fmf);
653 Value resultImag = arith::MulFOp::create(rewriter, loc, diff, cos, fmf);
654 return {resultReal, resultImag};
655 }
656};
657
658// The algorithm is listed in https://dl.acm.org/doi/pdf/10.1145/363717.363780.
659struct SqrtOpConversion : public OpConversionPattern<complex::SqrtOp> {
660 using OpConversionPattern<complex::SqrtOp>::OpConversionPattern;
661
662 LogicalResult
663 matchAndRewrite(complex::SqrtOp op, OpAdaptor adaptor,
664 ConversionPatternRewriter &rewriter) const override {
665 ImplicitLocOpBuilder b(op.getLoc(), rewriter);
666
667 auto type = cast<ComplexType>(op.getType());
668 auto elementType = cast<FloatType>(type.getElementType());
669 arith::FastMathFlags fmf = op.getFastMathFlagsAttr().getValue();
670
671 auto cst = [&](APFloat v) {
672 return arith::ConstantOp::create(b, elementType,
673 b.getFloatAttr(elementType, v));
674 };
675 const auto &floatSemantics = elementType.getFloatSemantics();
676 Value zero = cst(APFloat::getZero(floatSemantics));
677 Value half = arith::ConstantOp::create(b, elementType,
678 b.getFloatAttr(elementType, 0.5));
679
680 Value real = complex::ReOp::create(b, elementType, adaptor.getComplex());
681 Value imag = complex::ImOp::create(b, elementType, adaptor.getComplex());
682 Value absSqrt = computeAbs(real, imag, fmf, b, AbsFn::sqrt);
683 Value argArg = math::Atan2Op::create(b, imag, real, fmf);
684 Value sqrtArg = arith::MulFOp::create(b, argArg, half, fmf);
685 Value cos = math::CosOp::create(b, sqrtArg, fmf);
686 Value sin = math::SinOp::create(b, sqrtArg, fmf);
687 // sin(atan2(0, inf)) = 0, sqrt(abs(inf)) = inf, but we can't multiply
688 // 0 * inf.
689 Value sinIsZero =
690 arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, sin, zero, fmf);
691
692 Value resultReal = arith::MulFOp::create(b, absSqrt, cos, fmf);
693 Value resultImag = arith::SelectOp::create(
694 b, sinIsZero, zero, arith::MulFOp::create(b, absSqrt, sin, fmf));
695 if (!arith::bitEnumContainsAll(fmf, arith::FastMathFlags::nnan |
696 arith::FastMathFlags::ninf)) {
697 Value inf = cst(APFloat::getInf(floatSemantics));
698 Value negInf = cst(APFloat::getInf(floatSemantics, true));
699 Value nan = cst(APFloat::getNaN(floatSemantics));
700 Value absImag = math::AbsFOp::create(b, elementType, imag, fmf);
701
702 Value absImagIsInf = arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ,
703 absImag, inf, fmf);
704 Value absImagIsNotInf = arith::CmpFOp::create(
705 b, arith::CmpFPredicate::ONE, absImag, inf, fmf);
706 Value realIsInf =
707 arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, real, inf, fmf);
708 Value realIsNegInf = arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ,
709 real, negInf, fmf);
710
711 resultReal = arith::SelectOp::create(
712 b, arith::AndIOp::create(b, realIsNegInf, absImagIsNotInf), zero,
713 resultReal);
714 resultReal = arith::SelectOp::create(
715 b, arith::OrIOp::create(b, absImagIsInf, realIsInf), inf, resultReal);
716
717 Value imagSignInf = math::CopySignOp::create(b, inf, imag, fmf);
718 resultImag = arith::SelectOp::create(
719 b,
720 arith::CmpFOp::create(b, arith::CmpFPredicate::UNO, absSqrt, absSqrt),
721 nan, resultImag);
722 resultImag = arith::SelectOp::create(
723 b, arith::OrIOp::create(b, absImagIsInf, realIsNegInf), imagSignInf,
724 resultImag);
725 }
726
727 Value resultIsZero =
728 arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, absSqrt, zero, fmf);
729 resultReal = arith::SelectOp::create(b, resultIsZero, zero, resultReal);
730 resultImag = arith::SelectOp::create(b, resultIsZero, zero, resultImag);
731
732 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, resultReal,
733 resultImag);
734 return success();
735 }
736};
737
738struct SignOpConversion : public OpConversionPattern<complex::SignOp> {
739 using OpConversionPattern<complex::SignOp>::OpConversionPattern;
740
741 LogicalResult
742 matchAndRewrite(complex::SignOp op, OpAdaptor adaptor,
743 ConversionPatternRewriter &rewriter) const override {
744 auto type = cast<ComplexType>(adaptor.getComplex().getType());
745 auto elementType = cast<FloatType>(type.getElementType());
746 mlir::ImplicitLocOpBuilder b(op.getLoc(), rewriter);
747 arith::FastMathFlagsAttr fmf = op.getFastMathFlagsAttr();
748
749 Value real = complex::ReOp::create(b, elementType, adaptor.getComplex());
750 Value imag = complex::ImOp::create(b, elementType, adaptor.getComplex());
751 Value zero =
752 arith::ConstantOp::create(b, elementType, b.getZeroAttr(elementType));
753 Value realIsZero =
754 arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, real, zero);
755 Value imagIsZero =
756 arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, imag, zero);
757 Value isZero = arith::AndIOp::create(b, realIsZero, imagIsZero);
758 auto abs =
759 complex::AbsOp::create(b, elementType, adaptor.getComplex(), fmf);
760 Value realSign = arith::DivFOp::create(b, real, abs, fmf);
761 Value imagSign = arith::DivFOp::create(b, imag, abs, fmf);
762 Value sign = complex::CreateOp::create(b, type, realSign, imagSign);
763 rewriter.replaceOpWithNewOp<arith::SelectOp>(op, isZero,
764 adaptor.getComplex(), sign);
765 return success();
766 }
767};
768
769template <typename Op>
770struct TanTanhOpConversion : public OpConversionPattern<Op> {
771 using OpConversionPattern<Op>::OpConversionPattern;
772
773 LogicalResult
774 matchAndRewrite(Op op, typename Op::Adaptor adaptor,
775 ConversionPatternRewriter &rewriter) const override {
776 ImplicitLocOpBuilder b(op.getLoc(), rewriter);
777 auto loc = op.getLoc();
778 auto type = cast<ComplexType>(adaptor.getComplex().getType());
779 auto elementType = cast<FloatType>(type.getElementType());
780 arith::FastMathFlags fmf = op.getFastMathFlagsAttr().getValue();
781 const auto &floatSemantics = elementType.getFloatSemantics();
782
783 Value real =
784 complex::ReOp::create(b, loc, elementType, adaptor.getComplex());
785 Value imag =
786 complex::ImOp::create(b, loc, elementType, adaptor.getComplex());
787
788 if constexpr (std::is_same_v<Op, complex::TanOp>) {
789 // tan(x+yi) = -i*tanh(-y + xi)
790 std::swap(real, imag);
791 real = arith::NegFOp::create(b, real, fmf);
792 }
793
794 auto cst = [&](APFloat v) {
795 return arith::ConstantOp::create(b, elementType,
796 b.getFloatAttr(elementType, v));
797 };
798 Value inf = cst(APFloat::getInf(floatSemantics));
799 Value four = arith::ConstantOp::create(b, elementType,
800 b.getFloatAttr(elementType, 4.0));
801 // Intermediate sums and expm1s may overflow.
802 arith::FastMathFlags fmfWithInf =
803 arith::bitEnumClear(fmf, arith::FastMathFlags::ninf);
804 Value twoReal = arith::AddFOp::create(b, real, real, fmfWithInf);
805 Value negTwoReal = arith::NegFOp::create(b, twoReal, fmfWithInf);
806 Value expTwoRealMinusOne = math::ExpM1Op::create(b, twoReal, fmfWithInf);
807 Value expNegTwoRealMinusOne =
808 math::ExpM1Op::create(b, negTwoReal, fmfWithInf);
809 Value realNum = arith::SubFOp::create(b, expTwoRealMinusOne,
810 expNegTwoRealMinusOne, fmf);
811 Value expProduct = arith::MulFOp::create(b, expTwoRealMinusOne,
812 expNegTwoRealMinusOne, fmfWithInf);
813 Value expSumMinusTwo = arith::NegFOp::create(b, expProduct, fmfWithInf);
814
815 Value cosImag = math::CosOp::create(b, imag, fmf);
816 Value cosImagSq = arith::MulFOp::create(b, cosImag, cosImag, fmf);
817 Value twoCosTwoImagPlusOne = arith::MulFOp::create(b, cosImagSq, four, fmf);
818 Value sinImag = math::SinOp::create(b, imag, fmf);
819
820 Value imagNum = arith::MulFOp::create(
821 b, four, arith::MulFOp::create(b, cosImag, sinImag, fmf), fmf);
822
823 Value denom = arith::AddFOp::create(b, expSumMinusTwo, twoCosTwoImagPlusOne,
824 fmfWithInf);
825
826 Value isInf = arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ,
827 expSumMinusTwo, inf, fmfWithInf);
828 Value negOne = arith::ConstantOp::create(b, elementType,
829 b.getFloatAttr(elementType, -1.0));
830 Value realLimit = math::CopySignOp::create(b, negOne, real, fmf);
831
832 Value resultReal = arith::SelectOp::create(
833 b, isInf, realLimit, arith::DivFOp::create(b, realNum, denom, fmf));
834 Value resultImag = arith::DivFOp::create(b, imagNum, denom, fmfWithInf);
835
836 if (!arith::bitEnumContainsAll(fmf, arith::FastMathFlags::nnan |
837 arith::FastMathFlags::ninf)) {
838 Value zero = arith::ConstantOp::create(b, elementType,
839 b.getFloatAttr(elementType, 0.0));
840 Value nan = cst(APFloat::getNaN(floatSemantics));
841 bool noInfs = arith::bitEnumContainsAll(fmf, arith::FastMathFlags::ninf);
842 Value imagIsNotFinite;
843 if (noInfs) {
844 imagIsNotFinite =
845 arith::CmpFOp::create(b, arith::CmpFPredicate::UNO, imag, imag);
846 } else {
847 Value absImag = math::AbsFOp::create(b, imag, fmf);
848 imagIsNotFinite =
849 arith::CmpFOp::create(b, arith::CmpFPredicate::UGE, absImag, inf);
850 }
851 Value imagIsZero =
852 arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, imag, zero);
853
854 Value resultRealIsNaN = imagIsNotFinite;
855 Value resultImagIsZero = imagIsZero;
856 if (!noInfs) {
857 Value absReal = math::AbsFOp::create(b, real, fmf);
858 Value absRealIsInf =
859 arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, absReal, inf);
860 Value absRealIsNotInf = arith::XOrIOp::create(
861 b, absRealIsInf,
862 arith::ConstantIntOp::create(b, true, /*width=*/1));
863 resultRealIsNaN =
864 arith::AndIOp::create(b, imagIsNotFinite, absRealIsNotInf);
865 resultImagIsZero = arith::OrIOp::create(
866 b, imagIsZero,
867 arith::AndIOp::create(b, absRealIsInf, imagIsNotFinite));
868 }
869
870 resultReal = arith::SelectOp::create(b, resultRealIsNaN, nan, resultReal);
871 resultImag =
872 arith::SelectOp::create(b, resultImagIsZero, zero, resultImag);
873 }
874
875 if constexpr (std::is_same_v<Op, complex::TanOp>) {
876 // tan(x+yi) = -i*tanh(-y + xi)
877 std::swap(resultReal, resultImag);
878 resultImag = arith::NegFOp::create(b, resultImag, fmf);
879 }
880
881 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, resultReal,
882 resultImag);
883 return success();
884 }
885};
886
887struct ConjOpConversion : public OpConversionPattern<complex::ConjOp> {
888 using OpConversionPattern<complex::ConjOp>::OpConversionPattern;
889
890 LogicalResult
891 matchAndRewrite(complex::ConjOp op, OpAdaptor adaptor,
892 ConversionPatternRewriter &rewriter) const override {
893 auto loc = op.getLoc();
894 auto type = cast<ComplexType>(adaptor.getComplex().getType());
895 auto elementType = cast<FloatType>(type.getElementType());
896 arith::FastMathFlags fmf = op.getFastMathFlagsAttr().getValue();
897 Value real =
898 complex::ReOp::create(rewriter, loc, elementType, adaptor.getComplex());
899 Value imag =
900 complex::ImOp::create(rewriter, loc, elementType, adaptor.getComplex());
901 Value negImag =
902 arith::NegFOp::create(rewriter, loc, elementType, imag, fmf);
903
904 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, real, negImag);
905
906 return success();
907 }
908};
909
910/// Converts lhs^y = (a+bi)^(c+di) to
911/// (a*a+b*b)^(0.5c) * exp(-d*atan2(b,a)) * (cos(q) + i*sin(q)),
912/// where q = c*atan2(b,a)+0.5d*ln(a*a+b*b)
913static Value powOpConversionImpl(mlir::ImplicitLocOpBuilder &builder,
914 ComplexType type, Value lhs, Value c, Value d,
915 arith::FastMathFlags fmf) {
916 auto elementType = cast<FloatType>(type.getElementType());
917
918 Value a = complex::ReOp::create(builder, lhs);
919 Value b = complex::ImOp::create(builder, lhs);
920
921 Value abs = complex::AbsOp::create(builder, lhs, fmf);
922 Value absToC = math::PowFOp::create(builder, abs, c, fmf);
923
924 Value negD = arith::NegFOp::create(builder, d, fmf);
925 Value argLhs = math::Atan2Op::create(builder, b, a, fmf);
926 Value negDArgLhs = arith::MulFOp::create(builder, negD, argLhs, fmf);
927 Value expNegDArgLhs = math::ExpOp::create(builder, negDArgLhs, fmf);
928
929 Value coeff = arith::MulFOp::create(builder, absToC, expNegDArgLhs, fmf);
930 Value lnAbs = math::LogOp::create(builder, abs, fmf);
931 Value cArgLhs = arith::MulFOp::create(builder, c, argLhs, fmf);
932 Value dLnAbs = arith::MulFOp::create(builder, d, lnAbs, fmf);
933 Value q = arith::AddFOp::create(builder, cArgLhs, dLnAbs, fmf);
934 Value cosQ = math::CosOp::create(builder, q, fmf);
935 Value sinQ = math::SinOp::create(builder, q, fmf);
936
937 Value inf = arith::ConstantOp::create(
938 builder, elementType,
939 builder.getFloatAttr(elementType,
940 APFloat::getInf(elementType.getFloatSemantics())));
941 Value zero = arith::ConstantOp::create(
942 builder, elementType, builder.getFloatAttr(elementType, 0.0));
943 Value one = arith::ConstantOp::create(builder, elementType,
944 builder.getFloatAttr(elementType, 1.0));
945 Value complexOne = complex::CreateOp::create(builder, type, one, zero);
946 Value complexZero = complex::CreateOp::create(builder, type, zero, zero);
947 Value complexInf = complex::CreateOp::create(builder, type, inf, zero);
948
949 // Case 0:
950 // d^c is 0 if d is 0 and c > 0. 0^0 is defined to be 1.0, see
951 // Branch Cuts for Complex Elementary Functions or Much Ado About
952 // Nothing's Sign Bit, W. Kahan, Section 10.
953 Value absEqZero =
954 arith::CmpFOp::create(builder, arith::CmpFPredicate::OEQ, abs, zero, fmf);
955 Value dEqZero =
956 arith::CmpFOp::create(builder, arith::CmpFPredicate::OEQ, d, zero, fmf);
957 Value cEqZero =
958 arith::CmpFOp::create(builder, arith::CmpFPredicate::OEQ, c, zero, fmf);
959 Value bEqZero =
960 arith::CmpFOp::create(builder, arith::CmpFPredicate::OEQ, b, zero, fmf);
961
962 Value zeroLeC =
963 arith::CmpFOp::create(builder, arith::CmpFPredicate::OLE, zero, c, fmf);
964 Value coeffCosQ = arith::MulFOp::create(builder, coeff, cosQ, fmf);
965 Value coeffSinQ = arith::MulFOp::create(builder, coeff, sinQ, fmf);
966 Value complexOneOrZero =
967 arith::SelectOp::create(builder, cEqZero, complexOne, complexZero);
968 Value coeffCosSin =
969 complex::CreateOp::create(builder, type, coeffCosQ, coeffSinQ);
970 Value cutoff0 = arith::SelectOp::create(
971 builder,
972 arith::AndIOp::create(
973 builder, arith::AndIOp::create(builder, absEqZero, dEqZero), zeroLeC),
974 complexOneOrZero, coeffCosSin);
975
976 // Case 1:
977 // x^0 is defined to be 1 for any x, see
978 // Branch Cuts for Complex Elementary Functions or Much Ado About
979 // Nothing's Sign Bit, W. Kahan, Section 10.
980 Value rhsEqZero = arith::AndIOp::create(builder, cEqZero, dEqZero);
981 Value cutoff1 =
982 arith::SelectOp::create(builder, rhsEqZero, complexOne, cutoff0);
983
984 // Case 2:
985 // 1^(c + d*i) = 1 + 0*i
986 Value lhsEqOne = arith::AndIOp::create(
987 builder,
988 arith::CmpFOp::create(builder, arith::CmpFPredicate::OEQ, a, one, fmf),
989 bEqZero);
990 Value cutoff2 =
991 arith::SelectOp::create(builder, lhsEqOne, complexOne, cutoff1);
992
993 // Case 3:
994 // inf^(c + 0*i) = inf + 0*i, c > 0
995 Value lhsEqInf = arith::AndIOp::create(
996 builder,
997 arith::CmpFOp::create(builder, arith::CmpFPredicate::OEQ, a, inf, fmf),
998 bEqZero);
999 Value rhsGt0 = arith::AndIOp::create(
1000 builder, dEqZero,
1001 arith::CmpFOp::create(builder, arith::CmpFPredicate::OGT, c, zero, fmf));
1002 Value cutoff3 = arith::SelectOp::create(
1003 builder, arith::AndIOp::create(builder, lhsEqInf, rhsGt0), complexInf,
1004 cutoff2);
1005
1006 // Case 4:
1007 // inf^(c + 0*i) = 0 + 0*i, c < 0
1008 Value rhsLt0 = arith::AndIOp::create(
1009 builder, dEqZero,
1010 arith::CmpFOp::create(builder, arith::CmpFPredicate::OLT, c, zero, fmf));
1011 Value cutoff4 = arith::SelectOp::create(
1012 builder, arith::AndIOp::create(builder, lhsEqInf, rhsLt0), complexZero,
1013 cutoff3);
1014
1015 return cutoff4;
1016}
1017
1018struct PowiOpConversion : public OpConversionPattern<complex::PowiOp> {
1019 using OpConversionPattern<complex::PowiOp>::OpConversionPattern;
1020
1021 LogicalResult
1022 matchAndRewrite(complex::PowiOp op, OpAdaptor adaptor,
1023 ConversionPatternRewriter &rewriter) const override {
1024 ImplicitLocOpBuilder builder(op.getLoc(), rewriter);
1025 auto type = cast<ComplexType>(op.getType());
1026 auto elementType = cast<FloatType>(type.getElementType());
1027
1028 Value floatExponent =
1029 arith::SIToFPOp::create(builder, elementType, adaptor.getRhs());
1030 Value zero = arith::ConstantOp::create(
1031 builder, elementType, builder.getFloatAttr(elementType, 0.0));
1032 Value complexExponent =
1033 complex::CreateOp::create(builder, type, floatExponent, zero);
1034
1035 auto pow = complex::PowOp::create(builder, type, adaptor.getLhs(),
1036 complexExponent, op.getFastmathAttr());
1037 rewriter.replaceOp(op, pow.getResult());
1038 return success();
1039 }
1040};
1041
1042struct PowOpConversion : public OpConversionPattern<complex::PowOp> {
1043 using OpConversionPattern<complex::PowOp>::OpConversionPattern;
1044
1045 LogicalResult
1046 matchAndRewrite(complex::PowOp op, OpAdaptor adaptor,
1047 ConversionPatternRewriter &rewriter) const override {
1048 mlir::ImplicitLocOpBuilder builder(op.getLoc(), rewriter);
1049 auto type = cast<ComplexType>(adaptor.getLhs().getType());
1050 auto elementType = cast<FloatType>(type.getElementType());
1051
1052 Value c = complex::ReOp::create(builder, elementType, adaptor.getRhs());
1053 Value d = complex::ImOp::create(builder, elementType, adaptor.getRhs());
1054
1055 rewriter.replaceOp(op, {powOpConversionImpl(builder, type, adaptor.getLhs(),
1056 c, d, op.getFastmath())});
1057 return success();
1058 }
1059};
1060
1061struct RsqrtOpConversion : public OpConversionPattern<complex::RsqrtOp> {
1062 using OpConversionPattern<complex::RsqrtOp>::OpConversionPattern;
1063
1064 LogicalResult
1065 matchAndRewrite(complex::RsqrtOp op, OpAdaptor adaptor,
1066 ConversionPatternRewriter &rewriter) const override {
1067 mlir::ImplicitLocOpBuilder b(op.getLoc(), rewriter);
1068 auto type = cast<ComplexType>(adaptor.getComplex().getType());
1069 auto elementType = cast<FloatType>(type.getElementType());
1070
1071 arith::FastMathFlags fmf = op.getFastMathFlagsAttr().getValue();
1072
1073 auto cst = [&](APFloat v) {
1074 return arith::ConstantOp::create(b, elementType,
1075 b.getFloatAttr(elementType, v));
1076 };
1077 const auto &floatSemantics = elementType.getFloatSemantics();
1078 Value zero = cst(APFloat::getZero(floatSemantics));
1079 Value inf = cst(APFloat::getInf(floatSemantics));
1080 Value negHalf = arith::ConstantOp::create(
1081 b, elementType, b.getFloatAttr(elementType, -0.5));
1082 Value nan = cst(APFloat::getNaN(floatSemantics));
1083
1084 Value real = complex::ReOp::create(b, elementType, adaptor.getComplex());
1085 Value imag = complex::ImOp::create(b, elementType, adaptor.getComplex());
1086 Value absRsqrt = computeAbs(real, imag, fmf, b, AbsFn::rsqrt);
1087 Value argArg = math::Atan2Op::create(b, imag, real, fmf);
1088 Value rsqrtArg = arith::MulFOp::create(b, argArg, negHalf, fmf);
1089 Value cos = math::CosOp::create(b, rsqrtArg, fmf);
1090 Value sin = math::SinOp::create(b, rsqrtArg, fmf);
1091
1092 Value resultReal = arith::MulFOp::create(b, absRsqrt, cos, fmf);
1093 Value resultImag = arith::MulFOp::create(b, absRsqrt, sin, fmf);
1094
1095 if (!arith::bitEnumContainsAll(fmf, arith::FastMathFlags::nnan |
1096 arith::FastMathFlags::ninf)) {
1097 Value realSignedZero = math::CopySignOp::create(b, zero, real, fmf);
1098 Value imagSignedZero = math::CopySignOp::create(b, zero, imag, fmf);
1099 Value negImagSignedZero = arith::NegFOp::create(b, imagSignedZero, fmf);
1100
1101 Value absReal = math::AbsFOp::create(b, real, fmf);
1102 Value absImag = math::AbsFOp::create(b, imag, fmf);
1103
1104 Value absImagIsInf = arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ,
1105 absImag, inf, fmf);
1106 Value realIsNan =
1107 arith::CmpFOp::create(b, arith::CmpFPredicate::UNO, real, real, fmf);
1108 Value realIsInf = arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ,
1109 absReal, inf, fmf);
1110 Value inIsNanInf = arith::AndIOp::create(b, absImagIsInf, realIsNan);
1111
1112 Value resultIsZero = arith::OrIOp::create(b, inIsNanInf, realIsInf);
1113
1114 resultReal =
1115 arith::SelectOp::create(b, resultIsZero, realSignedZero, resultReal);
1116 resultImag = arith::SelectOp::create(b, resultIsZero, negImagSignedZero,
1117 resultImag);
1118 }
1119
1120 Value isRealZero =
1121 arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, real, zero, fmf);
1122 Value isImagZero =
1123 arith::CmpFOp::create(b, arith::CmpFPredicate::OEQ, imag, zero, fmf);
1124 Value isZero = arith::AndIOp::create(b, isRealZero, isImagZero);
1125
1126 resultReal = arith::SelectOp::create(b, isZero, inf, resultReal);
1127 resultImag = arith::SelectOp::create(b, isZero, nan, resultImag);
1128
1129 rewriter.replaceOpWithNewOp<complex::CreateOp>(op, type, resultReal,
1130 resultImag);
1131 return success();
1132 }
1133};
1134
1135struct AngleOpConversion : public OpConversionPattern<complex::AngleOp> {
1136 using OpConversionPattern<complex::AngleOp>::OpConversionPattern;
1137
1138 LogicalResult
1139 matchAndRewrite(complex::AngleOp op, OpAdaptor adaptor,
1140 ConversionPatternRewriter &rewriter) const override {
1141 auto loc = op.getLoc();
1142 auto type = op.getType();
1143 arith::FastMathFlagsAttr fmf = op.getFastMathFlagsAttr();
1144
1145 Value real =
1146 complex::ReOp::create(rewriter, loc, type, adaptor.getComplex());
1147 Value imag =
1148 complex::ImOp::create(rewriter, loc, type, adaptor.getComplex());
1149
1150 rewriter.replaceOpWithNewOp<math::Atan2Op>(op, imag, real, fmf);
1151
1152 return success();
1153 }
1154};
1155
1156} // namespace
1157
1159 RewritePatternSet &patterns, complex::ComplexRangeFlags complexRange) {
1160 // clang-format off
1161 patterns.add<
1162 AbsOpConversion,
1163 AngleOpConversion,
1164 Atan2OpConversion,
1165 BinaryComplexOpConversion<complex::AddOp, arith::AddFOp>,
1166 BinaryComplexOpConversion<complex::SubOp, arith::SubFOp>,
1167 ComparisonOpConversion<complex::EqualOp, arith::CmpFPredicate::OEQ>,
1168 ComparisonOpConversion<complex::NotEqualOp, arith::CmpFPredicate::UNE>,
1169 ConjOpConversion,
1170 CosOpConversion,
1171 ExpOpConversion,
1172 Expm1OpConversion,
1173 Log1pOpConversion,
1174 LogOpConversion,
1175 MulOpConversion,
1176 NegOpConversion,
1177 SignOpConversion,
1178 SinOpConversion,
1179 SqrtOpConversion,
1180 TanTanhOpConversion<complex::TanOp>,
1181 TanTanhOpConversion<complex::TanhOp>,
1182 PowiOpConversion,
1183 PowOpConversion,
1184 RsqrtOpConversion
1185 >(patterns.getContext());
1186
1187 patterns.add<DivOpConversion>(patterns.getContext(), complexRange);
1188
1189 // clang-format on
1190}
1191
1192namespace {
1193struct ConvertComplexToStandardPass
1195 ConvertComplexToStandardPass> {
1196 using Base::Base;
1197
1198 void runOnOperation() override;
1199};
1200
1201void ConvertComplexToStandardPass::runOnOperation() {
1202 // Convert to the Standard dialect using the converter defined above.
1203 RewritePatternSet patterns(&getContext());
1204 populateComplexToStandardConversionPatterns(patterns, complexRange);
1205
1206 ConversionTarget target(getContext());
1207 target.addLegalDialect<arith::ArithDialect, math::MathDialect>();
1208 target.addLegalOp<complex::CreateOp, complex::ImOp, complex::ReOp>();
1209 if (failed(
1210 applyPartialConversion(getOperation(), target, std::move(patterns))))
1211 signalPassFailure();
1212}
1213} // namespace
return success()
lhs
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
b getContext())
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
Definition Builders.h:632
Location getLoc()
The source location the operation was defined or derived from.
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
static ConstantIntOp create(OpBuilder &builder, Location location, int64_t value, unsigned width)
Definition ArithOps.cpp:335
NestedPattern Op(FilterFunctionType filter=defaultFilterFunction)
void convertDivToStandardUsingAlgebraic(ConversionPatternRewriter &rewriter, Location loc, Value lhsRe, Value lhsIm, Value rhsRe, Value rhsIm, arith::FastMathFlagsAttr fmf, Value *resultRe, Value *resultIm)
convert a complex division to the arith/math dialects using algebraic method
void convertDivToStandardUsingRangeReduction(ConversionPatternRewriter &rewriter, Location loc, Value lhsRe, Value lhsIm, Value rhsRe, Value rhsIm, arith::FastMathFlagsAttr fmf, Value *resultRe, Value *resultIm)
convert a complex division to the arith/math dialects using Smith's method
Fraction abs(const Fraction &f)
Definition Fraction.h:107
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
OwningOpRef< spirv::ModuleOp > combine(ArrayRef< spirv::ModuleOp > inputModules, OpBuilder &combinedModuleBuilder, SymbolRenameListener symRenameListener)
Combines a list of SPIR-V inputModules into one.
Include the generated interface declarations.
constexpr T real(const NonFloatComplex< T > &x)
Definition Complex.h:255
void populateComplexToStandardConversionPatterns(RewritePatternSet &patterns, mlir::complex::ComplexRangeFlags complexRange=mlir::complex::ComplexRangeFlags::improved)
Populate the given list with patterns that convert from Complex to Standard.
constexpr T imag(const NonFloatComplex< T > &x)
Definition Complex.h:260