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 
11 namespace Fortran::evaluate {
12 
13 template <int KIND>
14 Expr<Type<TypeCategory::Real, KIND>> FoldIntrinsicFunction(
15     FoldingContext &context,
16     FunctionRef<Type<TypeCategory::Real, KIND>> &&funcRef) {
17   using T = Type<TypeCategory::Real, KIND>;
18   using ComplexT = Type<TypeCategory::Complex, KIND>;
19   ActualArguments &args{funcRef.arguments()};
20   auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
21   CHECK(intrinsic);
22   std::string name{intrinsic->name};
23   if (name == "acos" || name == "acosh" || name == "asin" || name == "asinh" ||
24       (name == "atan" && args.size() == 1) || name == "atanh" ||
25       name == "bessel_j0" || name == "bessel_j1" || name == "bessel_y0" ||
26       name == "bessel_y1" || name == "cos" || name == "cosh" || name == "erf" ||
27       name == "erfc" || name == "erfc_scaled" || name == "exp" ||
28       name == "gamma" || name == "log" || name == "log10" ||
29       name == "log_gamma" || name == "sin" || name == "sinh" ||
30       name == "sqrt" || name == "tan" || name == "tanh") {
31     CHECK(args.size() == 1);
32     if (auto callable{context.hostIntrinsicsLibrary()
33                           .GetHostProcedureWrapper<Scalar, T, T>(name)}) {
34       return FoldElementalIntrinsic<T, T>(
35           context, std::move(funcRef), *callable);
36     } else {
37       context.messages().Say(
38           "%s(real(kind=%d)) cannot be folded on host"_en_US, name, KIND);
39     }
40   } else if (name == "atan" || name == "atan2" || name == "hypot" ||
41       name == "mod") {
42     std::string localName{name == "atan2" ? "atan" : name};
43     CHECK(args.size() == 2);
44     if (auto callable{
45             context.hostIntrinsicsLibrary()
46                 .GetHostProcedureWrapper<Scalar, T, T, T>(localName)}) {
47       return FoldElementalIntrinsic<T, T, T>(
48           context, std::move(funcRef), *callable);
49     } else {
50       context.messages().Say(
51           "%s(real(kind=%d), real(kind%d)) cannot be folded on host"_en_US,
52           name, KIND, KIND);
53     }
54   } else if (name == "bessel_jn" || name == "bessel_yn") {
55     if (args.size() == 2) { // elemental
56       // runtime functions use int arg
57       using Int4 = Type<TypeCategory::Integer, 4>;
58       if (auto callable{
59               context.hostIntrinsicsLibrary()
60                   .GetHostProcedureWrapper<Scalar, T, Int4, T>(name)}) {
61         return FoldElementalIntrinsic<T, Int4, T>(
62             context, std::move(funcRef), *callable);
63       } else {
64         context.messages().Say(
65             "%s(integer(kind=4), real(kind=%d)) cannot be folded on host"_en_US,
66             name, KIND);
67       }
68     }
69   } else if (name == "abs") {
70     // Argument can be complex or real
71     if (auto *x{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
72       return FoldElementalIntrinsic<T, T>(
73           context, std::move(funcRef), &Scalar<T>::ABS);
74     } else if (auto *z{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
75       if (auto callable{
76               context.hostIntrinsicsLibrary()
77                   .GetHostProcedureWrapper<Scalar, T, ComplexT>("abs")}) {
78         return FoldElementalIntrinsic<T, ComplexT>(
79             context, std::move(funcRef), *callable);
80       } else {
81         context.messages().Say(
82             "abs(complex(kind=%d)) cannot be folded on host"_en_US, KIND);
83       }
84     } else {
85       common::die(" unexpected argument type inside abs");
86     }
87   } else if (name == "aimag") {
88     return FoldElementalIntrinsic<T, ComplexT>(
89         context, std::move(funcRef), &Scalar<ComplexT>::AIMAG);
90   } else if (name == "aint" || name == "anint") {
91     // ANINT rounds ties away from zero, not to even
92     common::RoundingMode mode{name == "aint"
93             ? common::RoundingMode::ToZero
94             : common::RoundingMode::TiesAwayFromZero};
95     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
96         ScalarFunc<T, T>([&name, &context, mode](
97                              const Scalar<T> &x) -> Scalar<T> {
98           ValueWithRealFlags<Scalar<T>> y{x.ToWholeNumber(mode)};
99           if (y.flags.test(RealFlag::Overflow)) {
100             context.messages().Say("%s intrinsic folding overflow"_en_US, name);
101           }
102           return y.value;
103         }));
104   } else if (name == "dprod") {
105     if (auto scalars{GetScalarConstantArguments<T, T>(context, args)}) {
106       return Fold(context,
107           Expr<T>{Multiply<T>{
108               Expr<T>{std::get<0>(*scalars)}, Expr<T>{std::get<1>(*scalars)}}});
109     }
110   } else if (name == "epsilon") {
111     return Expr<T>{Scalar<T>::EPSILON()};
112   } else if (name == "huge") {
113     return Expr<T>{Scalar<T>::HUGE()};
114   } else if (name == "max") {
115     return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater);
116   } else if (name == "merge") {
117     return FoldMerge<T>(context, std::move(funcRef));
118   } else if (name == "min") {
119     return FoldMINorMAX(context, std::move(funcRef), Ordering::Less);
120   } else if (name == "real") {
121     if (auto *expr{args[0].value().UnwrapExpr()}) {
122       return ToReal<KIND>(context, std::move(*expr));
123     }
124   } else if (name == "sign") {
125     return FoldElementalIntrinsic<T, T, T>(
126         context, std::move(funcRef), &Scalar<T>::SIGN);
127   } else if (name == "tiny") {
128     return Expr<T>{Scalar<T>::TINY()};
129   }
130   // TODO: cshift, dim, dot_product, eoshift, fraction, matmul,
131   // maxval, minval, modulo, nearest, norm2, pack, product,
132   // reduce, rrspacing, scale, set_exponent, spacing, spread,
133   // sum, transfer, transpose, unpack, bessel_jn (transformational) and
134   // bessel_yn (transformational)
135   return Expr<T>{std::move(funcRef)};
136 }
137 
138 template <int KIND>
139 Expr<Type<TypeCategory::Real, KIND>> FoldOperation(
140     FoldingContext &context, ComplexComponent<KIND> &&x) {
141   using Operand = Type<TypeCategory::Complex, KIND>;
142   using Result = Type<TypeCategory::Real, KIND>;
143   if (auto array{ApplyElementwise(context, x,
144           std::function<Expr<Result>(Expr<Operand> &&)>{
145               [=](Expr<Operand> &&operand) {
146                 return Expr<Result>{ComplexComponent<KIND>{
147                     x.isImaginaryPart, std::move(operand)}};
148               }})}) {
149     return *array;
150   }
151   using Part = Type<TypeCategory::Real, KIND>;
152   auto &operand{x.left()};
153   if (auto value{GetScalarConstantValue<Operand>(operand)}) {
154     if (x.isImaginaryPart) {
155       return Expr<Part>{Constant<Part>{value->AIMAG()}};
156     } else {
157       return Expr<Part>{Constant<Part>{value->REAL()}};
158     }
159   }
160   return Expr<Part>{std::move(x)};
161 }
162 
163 FOR_EACH_REAL_KIND(template class ExpressionBase, )
164 template class ExpressionBase<SomeReal>;
165 } // namespace Fortran::evaluate
166