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>
FoldTransformationalBessel(FunctionRef<T> && funcRef,FoldingContext & context)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>
FoldIntrinsicFunction(FoldingContext & context,FunctionRef<Type<TypeCategory::Real,KIND>> && funcRef)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   using Int4 = Type<TypeCategory::Integer, 4>;
53   ActualArguments &args{funcRef.arguments()};
54   auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
55   CHECK(intrinsic);
56   std::string name{intrinsic->name};
57   if (name == "acos" || name == "acosh" || name == "asin" || name == "asinh" ||
58       (name == "atan" && args.size() == 1) || name == "atanh" ||
59       name == "bessel_j0" || name == "bessel_j1" || name == "bessel_y0" ||
60       name == "bessel_y1" || name == "cos" || name == "cosh" || name == "erf" ||
61       name == "erfc" || name == "erfc_scaled" || name == "exp" ||
62       name == "gamma" || name == "log" || name == "log10" ||
63       name == "log_gamma" || name == "sin" || name == "sinh" || name == "tan" ||
64       name == "tanh") {
65     CHECK(args.size() == 1);
66     if (auto callable{GetHostRuntimeWrapper<T, T>(name)}) {
67       return FoldElementalIntrinsic<T, T>(
68           context, std::move(funcRef), *callable);
69     } else {
70       context.messages().Say(
71           "%s(real(kind=%d)) cannot be folded on host"_warn_en_US, name, KIND);
72     }
73   } else if (name == "amax0" || name == "amin0" || name == "amin1" ||
74       name == "amax1" || name == "dmin1" || name == "dmax1") {
75     return RewriteSpecificMINorMAX(context, std::move(funcRef));
76   } else if (name == "atan" || name == "atan2") {
77     std::string localName{name == "atan" ? "atan2" : name};
78     CHECK(args.size() == 2);
79     if (auto callable{GetHostRuntimeWrapper<T, T, T>(localName)}) {
80       return FoldElementalIntrinsic<T, T, T>(
81           context, std::move(funcRef), *callable);
82     } else {
83       context.messages().Say(
84           "%s(real(kind=%d), real(kind%d)) cannot be folded on host"_warn_en_US,
85           name, KIND, KIND);
86     }
87   } else if (name == "bessel_jn" || name == "bessel_yn") {
88     if (args.size() == 2) { // elemental
89       // runtime functions use int arg
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     if (auto *zExpr{UnwrapExpr<Expr<ComplexT>>(args[0])}) {
116       return Fold(context, Expr<T>{ComplexComponent{true, std::move(*zExpr)}});
117     }
118   } else if (name == "aint" || name == "anint") {
119     // ANINT rounds ties away from zero, not to even
120     common::RoundingMode mode{name == "aint"
121             ? common::RoundingMode::ToZero
122             : common::RoundingMode::TiesAwayFromZero};
123     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
124         ScalarFunc<T, T>([&name, &context, mode](
125                              const Scalar<T> &x) -> Scalar<T> {
126           ValueWithRealFlags<Scalar<T>> y{x.ToWholeNumber(mode)};
127           if (y.flags.test(RealFlag::Overflow)) {
128             context.messages().Say(
129                 "%s intrinsic folding overflow"_warn_en_US, name);
130           }
131           return y.value;
132         }));
133   } else if (name == "dim") {
134     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
135         ScalarFunc<T, T, T>(
136             [](const Scalar<T> &x, const Scalar<T> &y) -> Scalar<T> {
137               return x.DIM(y).value;
138             }));
139   } else if (name == "dprod") {
140     if (auto scalars{GetScalarConstantArguments<T, T>(context, args)}) {
141       return Fold(context,
142           Expr<T>{Multiply<T>{
143               Expr<T>{std::get<0>(*scalars)}, Expr<T>{std::get<1>(*scalars)}}});
144     }
145   } else if (name == "epsilon") {
146     return Expr<T>{Scalar<T>::EPSILON()};
147   } else if (name == "fraction") {
148     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
149         ScalarFunc<T, T>(
150             [](const Scalar<T> &x) -> Scalar<T> { return x.FRACTION(); }));
151   } else if (name == "huge") {
152     return Expr<T>{Scalar<T>::HUGE()};
153   } else if (name == "hypot") {
154     CHECK(args.size() == 2);
155     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
156         ScalarFunc<T, T, T>(
157             [](const Scalar<T> &x, const Scalar<T> &y) -> Scalar<T> {
158               return x.HYPOT(y).value;
159             }));
160   } else if (name == "max") {
161     return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater);
162   } else if (name == "maxval") {
163     return FoldMaxvalMinval<T>(context, std::move(funcRef),
164         RelationalOperator::GT, T::Scalar::HUGE().Negate());
165   } else if (name == "merge") {
166     return FoldMerge<T>(context, std::move(funcRef));
167   } else if (name == "min") {
168     return FoldMINorMAX(context, std::move(funcRef), Ordering::Less);
169   } else if (name == "minval") {
170     return FoldMaxvalMinval<T>(
171         context, std::move(funcRef), RelationalOperator::LT, T::Scalar::HUGE());
172   } else if (name == "mod") {
173     CHECK(args.size() == 2);
174     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
175         ScalarFunc<T, T, T>(
176             [&context](const Scalar<T> &x, const Scalar<T> &y) -> Scalar<T> {
177               auto result{x.MOD(y)};
178               if (result.flags.test(RealFlag::DivideByZero)) {
179                 context.messages().Say(
180                     "second argument to MOD must not be zero"_warn_en_US);
181               }
182               return result.value;
183             }));
184   } else if (name == "modulo") {
185     CHECK(args.size() == 2);
186     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
187         ScalarFunc<T, T, T>(
188             [&context](const Scalar<T> &x, const Scalar<T> &y) -> Scalar<T> {
189               auto result{x.MODULO(y)};
190               if (result.flags.test(RealFlag::DivideByZero)) {
191                 context.messages().Say(
192                     "second argument to MODULO must not be zero"_warn_en_US);
193               }
194               return result.value;
195             }));
196   } else if (name == "nearest") {
197     if (const auto *sExpr{UnwrapExpr<Expr<SomeReal>>(args[1])}) {
198       return common::visit(
199           [&](const auto &sVal) {
200             using TS = ResultType<decltype(sVal)>;
201             return FoldElementalIntrinsic<T, T, TS>(context, std::move(funcRef),
202                 ScalarFunc<T, T, TS>([&](const Scalar<T> &x,
203                                          const Scalar<TS> &s) -> Scalar<T> {
204                   if (s.IsZero()) {
205                     context.messages().Say(
206                         "NEAREST: S argument is zero"_warn_en_US);
207                   }
208                   auto result{x.NEAREST(!s.IsNegative())};
209                   if (result.flags.test(RealFlag::Overflow)) {
210                     context.messages().Say(
211                         "NEAREST intrinsic folding overflow"_warn_en_US);
212                   } else if (result.flags.test(RealFlag::InvalidArgument)) {
213                     context.messages().Say(
214                         "NEAREST intrinsic folding: bad argument"_warn_en_US);
215                   }
216                   return result.value;
217                 }));
218           },
219           sExpr->u);
220     }
221   } else if (name == "product") {
222     auto one{Scalar<T>::FromInteger(value::Integer<8>{1}).value};
223     return FoldProduct<T>(context, std::move(funcRef), one);
224   } else if (name == "real" || name == "dble") {
225     if (auto *expr{args[0].value().UnwrapExpr()}) {
226       return ToReal<KIND>(context, std::move(*expr));
227     }
228   } else if (name == "rrspacing") {
229     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
230         ScalarFunc<T, T>(
231             [](const Scalar<T> &x) -> Scalar<T> { return x.RRSPACING(); }));
232   } else if (name == "scale") {
233     if (const auto *byExpr{UnwrapExpr<Expr<SomeInteger>>(args[1])}) {
234       return common::visit(
235           [&](const auto &byVal) {
236             using TBY = ResultType<decltype(byVal)>;
237             return FoldElementalIntrinsic<T, T, TBY>(context,
238                 std::move(funcRef),
239                 ScalarFunc<T, T, TBY>(
240                     [&](const Scalar<T> &x, const Scalar<TBY> &y) -> Scalar<T> {
241                       ValueWithRealFlags<Scalar<T>> result{x.
242 // MSVC chokes on the keyword "template" here in a call to a
243 // member function template.
244 #ifndef _MSC_VER
245                                                            template
246 #endif
247                                                            SCALE(y)};
248                       if (result.flags.test(RealFlag::Overflow)) {
249                         context.messages().Say(
250                             "SCALE intrinsic folding overflow"_warn_en_US);
251                       }
252                       return result.value;
253                     }));
254           },
255           byExpr->u);
256     }
257   } else if (name == "set_exponent") {
258     return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
259         ScalarFunc<T, T, Int4>(
260             [&](const Scalar<T> &x, const Scalar<Int4> &i) -> Scalar<T> {
261               return x.SET_EXPONENT(i.ToInt64());
262             }));
263   } else if (name == "sign") {
264     return FoldElementalIntrinsic<T, T, T>(
265         context, std::move(funcRef), &Scalar<T>::SIGN);
266   } else if (name == "spacing") {
267     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
268         ScalarFunc<T, T>(
269             [](const Scalar<T> &x) -> Scalar<T> { return x.SPACING(); }));
270   } else if (name == "sqrt") {
271     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
272         ScalarFunc<T, T>(
273             [](const Scalar<T> &x) -> Scalar<T> { return x.SQRT().value; }));
274   } else if (name == "sum") {
275     return FoldSum<T>(context, std::move(funcRef));
276   } else if (name == "tiny") {
277     return Expr<T>{Scalar<T>::TINY()};
278   } else if (name == "__builtin_ieee_next_after") {
279     if (const auto *yExpr{UnwrapExpr<Expr<SomeReal>>(args[1])}) {
280       return common::visit(
281           [&](const auto &yVal) {
282             using TY = ResultType<decltype(yVal)>;
283             return FoldElementalIntrinsic<T, T, TY>(context, std::move(funcRef),
284                 ScalarFunc<T, T, TY>([&](const Scalar<T> &x,
285                                          const Scalar<TY> &y) -> Scalar<T> {
286                   bool upward{true};
287                   switch (x.Compare(Scalar<T>::Convert(y).value)) {
288                   case Relation::Unordered:
289                     context.messages().Say(
290                         "IEEE_NEXT_AFTER intrinsic folding: bad argument"_warn_en_US);
291                     return x;
292                   case Relation::Equal:
293                     return x;
294                   case Relation::Less:
295                     upward = true;
296                     break;
297                   case Relation::Greater:
298                     upward = false;
299                     break;
300                   }
301                   auto result{x.NEAREST(upward)};
302                   if (result.flags.test(RealFlag::Overflow)) {
303                     context.messages().Say(
304                         "IEEE_NEXT_AFTER intrinsic folding overflow"_warn_en_US);
305                   }
306                   return result.value;
307                 }));
308           },
309           yExpr->u);
310     }
311   } else if (name == "__builtin_ieee_next_up" ||
312       name == "__builtin_ieee_next_down") {
313     bool upward{name == "__builtin_ieee_next_up"};
314     const char *iName{upward ? "IEEE_NEXT_UP" : "IEEE_NEXT_DOWN"};
315     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
316         ScalarFunc<T, T>([&](const Scalar<T> &x) -> Scalar<T> {
317           auto result{x.NEAREST(upward)};
318           if (result.flags.test(RealFlag::Overflow)) {
319             context.messages().Say(
320                 "%s intrinsic folding overflow"_warn_en_US, iName);
321           } else if (result.flags.test(RealFlag::InvalidArgument)) {
322             context.messages().Say(
323                 "%s intrinsic folding: bad argument"_warn_en_US, iName);
324           }
325           return result.value;
326         }));
327   }
328   // TODO: dot_product, matmul, norm2
329   return Expr<T>{std::move(funcRef)};
330 }
331 
332 #ifdef _MSC_VER // disable bogus warning about missing definitions
333 #pragma warning(disable : 4661)
334 #endif
335 FOR_EACH_REAL_KIND(template class ExpressionBase, )
336 template class ExpressionBase<SomeReal>;
337 } // namespace Fortran::evaluate
338