1 //===-- lib/Evaluate/fold-real.cpp ----------------------------------------===//
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 "fold-implementation.h"
10 #include "fold-reduction.h"
11 
12 namespace Fortran::evaluate {
13 
14 template <typename T>
15 static Expr<T> FoldTransformationalBessel(
16     FunctionRef<T> &&funcRef, FoldingContext &context) {
17   CHECK(funcRef.arguments().size() == 3);
18   /// Bessel runtime functions use `int` integer arguments. Convert integer
19   /// arguments to Int4, any overflow error will be reported during the
20   /// conversion folding.
21   using Int4 = Type<TypeCategory::Integer, 4>;
22   if (auto args{
23           GetConstantArguments<Int4, Int4, T>(context, funcRef.arguments())}) {
24     const std::string &name{std::get<SpecificIntrinsic>(funcRef.proc().u).name};
25     if (auto elementalBessel{GetHostRuntimeWrapper<T, Int4, T>(name)}) {
26       std::vector<Scalar<T>> results;
27       int n1{static_cast<int>(
28           std::get<0>(*args)->GetScalarValue().value().ToInt64())};
29       int n2{static_cast<int>(
30           std::get<1>(*args)->GetScalarValue().value().ToInt64())};
31       Scalar<T> x{std::get<2>(*args)->GetScalarValue().value()};
32       for (int i{n1}; i <= n2; ++i) {
33         results.emplace_back((*elementalBessel)(context, Scalar<Int4>{i}, x));
34       }
35       return Expr<T>{Constant<T>{
36           std::move(results), ConstantSubscripts{std::max(n2 - n1 + 1, 0)}}};
37     } else {
38       context.messages().Say(
39           "%s(integer(kind=4), real(kind=%d)) cannot be folded on host"_warn_en_US,
40           name, T::kind);
41     }
42   }
43   return Expr<T>{std::move(funcRef)};
44 }
45 
46 template <int KIND>
47 Expr<Type<TypeCategory::Real, KIND>> FoldIntrinsicFunction(
48     FoldingContext &context,
49     FunctionRef<Type<TypeCategory::Real, KIND>> &&funcRef) {
50   using T = Type<TypeCategory::Real, KIND>;
51   using ComplexT = Type<TypeCategory::Complex, KIND>;
52   ActualArguments &args{funcRef.arguments()};
53   auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
54   CHECK(intrinsic);
55   std::string name{intrinsic->name};
56   if (name == "acos" || name == "acosh" || name == "asin" || name == "asinh" ||
57       (name == "atan" && args.size() == 1) || name == "atanh" ||
58       name == "bessel_j0" || name == "bessel_j1" || name == "bessel_y0" ||
59       name == "bessel_y1" || name == "cos" || name == "cosh" || name == "erf" ||
60       name == "erfc" || name == "erfc_scaled" || name == "exp" ||
61       name == "gamma" || name == "log" || name == "log10" ||
62       name == "log_gamma" || name == "sin" || name == "sinh" || name == "tan" ||
63       name == "tanh") {
64     CHECK(args.size() == 1);
65     if (auto callable{GetHostRuntimeWrapper<T, T>(name)}) {
66       return FoldElementalIntrinsic<T, T>(
67           context, std::move(funcRef), *callable);
68     } else {
69       context.messages().Say(
70           "%s(real(kind=%d)) cannot be folded on host"_warn_en_US, name, KIND);
71     }
72   } else if (name == "amax0" || name == "amin0" || name == "amin1" ||
73       name == "amax1" || name == "dmin1" || name == "dmax1") {
74     return RewriteSpecificMINorMAX(context, std::move(funcRef));
75   } else if (name == "atan" || name == "atan2" || name == "mod") {
76     std::string localName{name == "atan" ? "atan2" : name};
77     CHECK(args.size() == 2);
78     if (auto callable{GetHostRuntimeWrapper<T, T, T>(localName)}) {
79       return FoldElementalIntrinsic<T, T, T>(
80           context, std::move(funcRef), *callable);
81     } else {
82       context.messages().Say(
83           "%s(real(kind=%d), real(kind%d)) cannot be folded on host"_warn_en_US,
84           name, KIND, KIND);
85     }
86   } else if (name == "bessel_jn" || name == "bessel_yn") {
87     if (args.size() == 2) { // elemental
88       // runtime functions use int arg
89       using Int4 = Type<TypeCategory::Integer, 4>;
90       if (auto callable{GetHostRuntimeWrapper<T, Int4, T>(name)}) {
91         return FoldElementalIntrinsic<T, Int4, T>(
92             context, std::move(funcRef), *callable);
93       } else {
94         context.messages().Say(
95             "%s(integer(kind=4), real(kind=%d)) cannot be folded on host"_warn_en_US,
96             name, KIND);
97       }
98     } else {
99       return FoldTransformationalBessel<T>(std::move(funcRef), context);
100     }
101   } else if (name == "abs") { // incl. zabs & cdabs
102     // Argument can be complex or real
103     if (auto *x{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
104       return FoldElementalIntrinsic<T, T>(
105           context, std::move(funcRef), &Scalar<T>::ABS);
106     } else if (auto *z{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
107       return FoldElementalIntrinsic<T, ComplexT>(context, std::move(funcRef),
108           ScalarFunc<T, ComplexT>([](const Scalar<ComplexT> &z) -> Scalar<T> {
109             return z.ABS().value;
110           }));
111     } else {
112       common::die(" unexpected argument type inside abs");
113     }
114   } else if (name == "aimag") {
115     return FoldElementalIntrinsic<T, ComplexT>(
116         context, std::move(funcRef), &Scalar<ComplexT>::AIMAG);
117   } else if (name == "aint" || name == "anint") {
118     // ANINT rounds ties away from zero, not to even
119     common::RoundingMode mode{name == "aint"
120             ? common::RoundingMode::ToZero
121             : common::RoundingMode::TiesAwayFromZero};
122     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
123         ScalarFunc<T, T>([&name, &context, mode](
124                              const Scalar<T> &x) -> Scalar<T> {
125           ValueWithRealFlags<Scalar<T>> y{x.ToWholeNumber(mode)};
126           if (y.flags.test(RealFlag::Overflow)) {
127             context.messages().Say(
128                 "%s intrinsic folding overflow"_warn_en_US, name);
129           }
130           return y.value;
131         }));
132   } else if (name == "dprod") {
133     if (auto scalars{GetScalarConstantArguments<T, T>(context, args)}) {
134       return Fold(context,
135           Expr<T>{Multiply<T>{
136               Expr<T>{std::get<0>(*scalars)}, Expr<T>{std::get<1>(*scalars)}}});
137     }
138   } else if (name == "epsilon") {
139     return Expr<T>{Scalar<T>::EPSILON()};
140   } else if (name == "huge") {
141     return Expr<T>{Scalar<T>::HUGE()};
142   } else if (name == "hypot") {
143     CHECK(args.size() == 2);
144     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
145         ScalarFunc<T, T, T>(
146             [](const Scalar<T> &x, const Scalar<T> &y) -> Scalar<T> {
147               return x.HYPOT(y).value;
148             }));
149   } else if (name == "max") {
150     return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater);
151   } else if (name == "maxval") {
152     return FoldMaxvalMinval<T>(context, std::move(funcRef),
153         RelationalOperator::GT, T::Scalar::HUGE().Negate());
154   } else if (name == "merge") {
155     return FoldMerge<T>(context, std::move(funcRef));
156   } else if (name == "nearest") {
157     if (const auto *sExpr{UnwrapExpr<Expr<SomeReal>>(args[1])}) {
158       return common::visit(
159           [&](const auto &sVal) {
160             using TS = ResultType<decltype(sVal)>;
161             return FoldElementalIntrinsic<T, T, TS>(context, std::move(funcRef),
162                 ScalarFunc<T, T, TS>([&](const Scalar<T> &x,
163                                          const Scalar<TS> &s) -> Scalar<T> {
164                   if (s.IsZero()) {
165                     context.messages().Say(
166                         "NEAREST: S argument is zero"_warn_en_US);
167                   }
168                   auto result{x.NEAREST(!s.IsNegative())};
169                   if (result.flags.test(RealFlag::Overflow)) {
170                     context.messages().Say(
171                         "NEAREST intrinsic folding overflow"_warn_en_US);
172                   } else if (result.flags.test(RealFlag::InvalidArgument)) {
173                     context.messages().Say(
174                         "NEAREST intrinsic folding: bad argument"_warn_en_US);
175                   }
176                   return result.value;
177                 }));
178           },
179           sExpr->u);
180     }
181   } else if (name == "min") {
182     return FoldMINorMAX(context, std::move(funcRef), Ordering::Less);
183   } else if (name == "minval") {
184     return FoldMaxvalMinval<T>(
185         context, std::move(funcRef), RelationalOperator::LT, T::Scalar::HUGE());
186   } else if (name == "product") {
187     auto one{Scalar<T>::FromInteger(value::Integer<8>{1}).value};
188     return FoldProduct<T>(context, std::move(funcRef), one);
189   } else if (name == "real" || name == "dble") {
190     if (auto *expr{args[0].value().UnwrapExpr()}) {
191       return ToReal<KIND>(context, std::move(*expr));
192     }
193   } else if (name == "scale") {
194     if (const auto *byExpr{UnwrapExpr<Expr<SomeInteger>>(args[1])}) {
195       return common::visit(
196           [&](const auto &byVal) {
197             using TBY = ResultType<decltype(byVal)>;
198             return FoldElementalIntrinsic<T, T, TBY>(context,
199                 std::move(funcRef),
200                 ScalarFunc<T, T, TBY>(
201                     [&](const Scalar<T> &x, const Scalar<TBY> &y) -> Scalar<T> {
202                       ValueWithRealFlags<Scalar<T>> result{x.
203 // MSVC chokes on the keyword "template" here in a call to a
204 // member function template.
205 #ifndef _MSC_VER
206                                                            template
207 #endif
208                                                            SCALE(y)};
209                       if (result.flags.test(RealFlag::Overflow)) {
210                         context.messages().Say(
211                             "SCALE intrinsic folding overflow"_warn_en_US);
212                       }
213                       return result.value;
214                     }));
215           },
216           byExpr->u);
217     }
218   } else if (name == "sign") {
219     return FoldElementalIntrinsic<T, T, T>(
220         context, std::move(funcRef), &Scalar<T>::SIGN);
221   } else if (name == "sqrt") {
222     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
223         ScalarFunc<T, T>(
224             [](const Scalar<T> &x) -> Scalar<T> { return x.SQRT().value; }));
225   } else if (name == "sum") {
226     return FoldSum<T>(context, std::move(funcRef));
227   } else if (name == "tiny") {
228     return Expr<T>{Scalar<T>::TINY()};
229   } else if (name == "__builtin_ieee_next_after") {
230     if (const auto *yExpr{UnwrapExpr<Expr<SomeReal>>(args[1])}) {
231       return common::visit(
232           [&](const auto &yVal) {
233             using TY = ResultType<decltype(yVal)>;
234             return FoldElementalIntrinsic<T, T, TY>(context, std::move(funcRef),
235                 ScalarFunc<T, T, TY>([&](const Scalar<T> &x,
236                                          const Scalar<TY> &y) -> Scalar<T> {
237                   bool upward{true};
238                   switch (x.Compare(Scalar<T>::Convert(y).value)) {
239                   case Relation::Unordered:
240                     context.messages().Say(
241                         "IEEE_NEXT_AFTER intrinsic folding: bad argument"_warn_en_US);
242                     return x;
243                   case Relation::Equal:
244                     return x;
245                   case Relation::Less:
246                     upward = true;
247                     break;
248                   case Relation::Greater:
249                     upward = false;
250                     break;
251                   }
252                   auto result{x.NEAREST(upward)};
253                   if (result.flags.test(RealFlag::Overflow)) {
254                     context.messages().Say(
255                         "IEEE_NEXT_AFTER intrinsic folding overflow"_warn_en_US);
256                   }
257                   return result.value;
258                 }));
259           },
260           yExpr->u);
261     }
262   } else if (name == "__builtin_ieee_next_up" ||
263       name == "__builtin_ieee_next_down") {
264     bool upward{name == "__builtin_ieee_next_up"};
265     const char *iName{upward ? "IEEE_NEXT_UP" : "IEEE_NEXT_DOWN"};
266     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
267         ScalarFunc<T, T>([&](const Scalar<T> &x) -> Scalar<T> {
268           auto result{x.NEAREST(upward)};
269           if (result.flags.test(RealFlag::Overflow)) {
270             context.messages().Say(
271                 "%s intrinsic folding overflow"_warn_en_US, iName);
272           } else if (result.flags.test(RealFlag::InvalidArgument)) {
273             context.messages().Say(
274                 "%s intrinsic folding: bad argument"_warn_en_US, iName);
275           }
276           return result.value;
277         }));
278   }
279   // TODO: dim, dot_product, fraction, matmul,
280   // modulo, norm2, rrspacing,
281   // set_exponent, spacing, transfer,
282   return Expr<T>{std::move(funcRef)};
283 }
284 
285 template <int KIND>
286 Expr<Type<TypeCategory::Real, KIND>> FoldOperation(
287     FoldingContext &context, ComplexComponent<KIND> &&x) {
288   using Operand = Type<TypeCategory::Complex, KIND>;
289   using Result = Type<TypeCategory::Real, KIND>;
290   if (auto array{ApplyElementwise(context, x,
291           std::function<Expr<Result>(Expr<Operand> &&)>{
292               [=](Expr<Operand> &&operand) {
293                 return Expr<Result>{ComplexComponent<KIND>{
294                     x.isImaginaryPart, std::move(operand)}};
295               }})}) {
296     return *array;
297   }
298   using Part = Type<TypeCategory::Real, KIND>;
299   auto &operand{x.left()};
300   if (auto value{GetScalarConstantValue<Operand>(operand)}) {
301     if (x.isImaginaryPart) {
302       return Expr<Part>{Constant<Part>{value->AIMAG()}};
303     } else {
304       return Expr<Part>{Constant<Part>{value->REAL()}};
305     }
306   }
307   return Expr<Part>{std::move(x)};
308 }
309 
310 #ifdef _MSC_VER // disable bogus warning about missing definitions
311 #pragma warning(disable : 4661)
312 #endif
313 FOR_EACH_REAL_KIND(template class ExpressionBase, )
314 template class ExpressionBase<SomeReal>;
315 } // namespace Fortran::evaluate
316