xref: /llvm-project/flang/lib/Evaluate/fold-logical.cpp (revision 4ca111d4cb4c0b425268c86b54fb19c4be2e88dd)
1 //===-- lib/Evaluate/fold-logical.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 #include "flang/Evaluate/check-expression.h"
12 
13 namespace Fortran::evaluate {
14 
15 // for ALL & ANY
16 template <typename T>
17 static Expr<T> FoldAllAny(FoldingContext &context, FunctionRef<T> &&ref,
18     Scalar<T> (Scalar<T>::*operation)(const Scalar<T> &) const,
19     Scalar<T> identity) {
20   static_assert(T::category == TypeCategory::Logical);
21   using Element = Scalar<T>;
22   std::optional<int> dim;
23   if (std::optional<Constant<T>> array{
24           ProcessReductionArgs<T>(context, ref.arguments(), dim, identity,
25               /*ARRAY(MASK)=*/0, /*DIM=*/1)}) {
26     auto accumulator{[&](Element &element, const ConstantSubscripts &at) {
27       element = (element.*operation)(array->At(at));
28     }};
29     return Expr<T>{DoReduction<T>(*array, dim, identity, accumulator)};
30   }
31   return Expr<T>{std::move(ref)};
32 }
33 
34 template <int KIND>
35 Expr<Type<TypeCategory::Logical, KIND>> FoldIntrinsicFunction(
36     FoldingContext &context,
37     FunctionRef<Type<TypeCategory::Logical, KIND>> &&funcRef) {
38   using T = Type<TypeCategory::Logical, KIND>;
39   ActualArguments &args{funcRef.arguments()};
40   auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
41   CHECK(intrinsic);
42   std::string name{intrinsic->name};
43   using SameInt = Type<TypeCategory::Integer, KIND>;
44   if (name == "all") {
45     return FoldAllAny(
46         context, std::move(funcRef), &Scalar<T>::AND, Scalar<T>{true});
47   } else if (name == "any") {
48     return FoldAllAny(
49         context, std::move(funcRef), &Scalar<T>::OR, Scalar<T>{false});
50   } else if (name == "associated") {
51     bool gotConstant{true};
52     const Expr<SomeType> *firstArgExpr{args[0]->UnwrapExpr()};
53     if (!firstArgExpr || !IsNullPointer(*firstArgExpr)) {
54       gotConstant = false;
55     } else if (args[1]) { // There's a second argument
56       const Expr<SomeType> *secondArgExpr{args[1]->UnwrapExpr()};
57       if (!secondArgExpr || !IsNullPointer(*secondArgExpr)) {
58         gotConstant = false;
59       }
60     }
61     return gotConstant ? Expr<T>{false} : Expr<T>{std::move(funcRef)};
62   } else if (name == "bge" || name == "bgt" || name == "ble" || name == "blt") {
63     static_assert(std::is_same_v<Scalar<LargestInt>, BOZLiteralConstant>);
64     // Arguments do not have to be of the same integer type. Convert all
65     // arguments to the biggest integer type before comparing them to
66     // simplify.
67     for (int i{0}; i <= 1; ++i) {
68       if (auto *x{UnwrapExpr<Expr<SomeInteger>>(args[i])}) {
69         *args[i] = AsGenericExpr(
70             Fold(context, ConvertToType<LargestInt>(std::move(*x))));
71       } else if (auto *x{UnwrapExpr<BOZLiteralConstant>(args[i])}) {
72         *args[i] = AsGenericExpr(Constant<LargestInt>{std::move(*x)});
73       }
74     }
75     auto fptr{&Scalar<LargestInt>::BGE};
76     if (name == "bge") { // done in fptr declaration
77     } else if (name == "bgt") {
78       fptr = &Scalar<LargestInt>::BGT;
79     } else if (name == "ble") {
80       fptr = &Scalar<LargestInt>::BLE;
81     } else if (name == "blt") {
82       fptr = &Scalar<LargestInt>::BLT;
83     } else {
84       common::die("missing case to fold intrinsic function %s", name.c_str());
85     }
86     return FoldElementalIntrinsic<T, LargestInt, LargestInt>(context,
87         std::move(funcRef),
88         ScalarFunc<T, LargestInt, LargestInt>(
89             [&fptr](const Scalar<LargestInt> &i, const Scalar<LargestInt> &j) {
90               return Scalar<T>{std::invoke(fptr, i, j)};
91             }));
92   } else if (name == "btest") {
93     if (const auto *ix{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
94       return std::visit(
95           [&](const auto &x) {
96             using IT = ResultType<decltype(x)>;
97             return FoldElementalIntrinsic<T, IT, SameInt>(context,
98                 std::move(funcRef),
99                 ScalarFunc<T, IT, SameInt>(
100                     [&](const Scalar<IT> &x, const Scalar<SameInt> &pos) {
101                       auto posVal{pos.ToInt64()};
102                       if (posVal < 0 || posVal >= x.bits) {
103                         context.messages().Say(
104                             "POS=%jd out of range for BTEST"_err_en_US,
105                             static_cast<std::intmax_t>(posVal));
106                       }
107                       return Scalar<T>{x.BTEST(posVal)};
108                     }));
109           },
110           ix->u);
111     }
112   } else if (name == "isnan" || name == "__builtin_ieee_is_nan") {
113     // A warning about an invalid argument is discarded from converting
114     // the argument of isnan() / IEEE_IS_NAN().
115     auto restorer{context.messages().DiscardMessages()};
116     using DefaultReal = Type<TypeCategory::Real, 4>;
117     return FoldElementalIntrinsic<T, DefaultReal>(context, std::move(funcRef),
118         ScalarFunc<T, DefaultReal>([](const Scalar<DefaultReal> &x) {
119           return Scalar<T>{x.IsNotANumber()};
120         }));
121   } else if (name == "__builtin_ieee_is_negative") {
122     auto restorer{context.messages().DiscardMessages()};
123     using DefaultReal = Type<TypeCategory::Real, 4>;
124     return FoldElementalIntrinsic<T, DefaultReal>(context, std::move(funcRef),
125         ScalarFunc<T, DefaultReal>([](const Scalar<DefaultReal> &x) {
126           return Scalar<T>{x.IsNegative()};
127         }));
128   } else if (name == "__builtin_ieee_is_normal") {
129     auto restorer{context.messages().DiscardMessages()};
130     using DefaultReal = Type<TypeCategory::Real, 4>;
131     return FoldElementalIntrinsic<T, DefaultReal>(context, std::move(funcRef),
132         ScalarFunc<T, DefaultReal>([](const Scalar<DefaultReal> &x) {
133           return Scalar<T>{x.IsNormal()};
134         }));
135   } else if (name == "is_contiguous") {
136     if (args.at(0)) {
137       if (auto *expr{args[0]->UnwrapExpr()}) {
138         if (IsSimplyContiguous(*expr, context)) {
139           return Expr<T>{true};
140         }
141       }
142     }
143   } else if (name == "lge" || name == "lgt" || name == "lle" || name == "llt") {
144     // Rewrite LGE/LGT/LLE/LLT into ASCII character relations
145     auto *cx0{UnwrapExpr<Expr<SomeCharacter>>(args[0])};
146     auto *cx1{UnwrapExpr<Expr<SomeCharacter>>(args[1])};
147     if (cx0 && cx1) {
148       return Fold(context,
149           ConvertToType<T>(
150               PackageRelation(name == "lge" ? RelationalOperator::GE
151                       : name == "lgt"       ? RelationalOperator::GT
152                       : name == "lle"       ? RelationalOperator::LE
153                                             : RelationalOperator::LT,
154                   ConvertToType<Ascii>(std::move(*cx0)),
155                   ConvertToType<Ascii>(std::move(*cx1)))));
156     }
157   } else if (name == "logical") {
158     if (auto *expr{UnwrapExpr<Expr<SomeLogical>>(args[0])}) {
159       return Fold(context, ConvertToType<T>(std::move(*expr)));
160     }
161   } else if (name == "merge") {
162     return FoldMerge<T>(context, std::move(funcRef));
163   } else if (name == "__builtin_ieee_support_datatype" ||
164       name == "__builtin_ieee_support_denormal" ||
165       name == "__builtin_ieee_support_divide" ||
166       name == "__builtin_ieee_support_divide" ||
167       name == "__builtin_ieee_support_inf" ||
168       name == "__builtin_ieee_support_io" ||
169       name == "__builtin_ieee_support_nan" ||
170       name == "__builtin_ieee_support_sqrt" ||
171       name == "__builtin_ieee_support_standard" ||
172       name == "__builtin_ieee_support_subnormal" ||
173       name == "__builtin_ieee_support_underflow_control") {
174     return Expr<T>{true};
175   }
176   // TODO: dot_product, is_iostat_end,
177   // is_iostat_eor, logical, matmul, out_of_range,
178   // parity, transfer
179   return Expr<T>{std::move(funcRef)};
180 }
181 
182 template <typename T>
183 Expr<LogicalResult> FoldOperation(
184     FoldingContext &context, Relational<T> &&relation) {
185   if (auto array{ApplyElementwise(context, relation,
186           std::function<Expr<LogicalResult>(Expr<T> &&, Expr<T> &&)>{
187               [=](Expr<T> &&x, Expr<T> &&y) {
188                 return Expr<LogicalResult>{Relational<SomeType>{
189                     Relational<T>{relation.opr, std::move(x), std::move(y)}}};
190               }})}) {
191     return *array;
192   }
193   if (auto folded{OperandsAreConstants(relation)}) {
194     bool result{};
195     if constexpr (T::category == TypeCategory::Integer) {
196       result =
197           Satisfies(relation.opr, folded->first.CompareSigned(folded->second));
198     } else if constexpr (T::category == TypeCategory::Real) {
199       result = Satisfies(relation.opr, folded->first.Compare(folded->second));
200     } else if constexpr (T::category == TypeCategory::Complex) {
201       result = (relation.opr == RelationalOperator::EQ) ==
202           folded->first.Equals(folded->second);
203     } else if constexpr (T::category == TypeCategory::Character) {
204       result = Satisfies(relation.opr, Compare(folded->first, folded->second));
205     } else {
206       static_assert(T::category != TypeCategory::Logical);
207     }
208     return Expr<LogicalResult>{Constant<LogicalResult>{result}};
209   }
210   return Expr<LogicalResult>{Relational<SomeType>{std::move(relation)}};
211 }
212 
213 Expr<LogicalResult> FoldOperation(
214     FoldingContext &context, Relational<SomeType> &&relation) {
215   return std::visit(
216       [&](auto &&x) {
217         return Expr<LogicalResult>{FoldOperation(context, std::move(x))};
218       },
219       std::move(relation.u));
220 }
221 
222 template <int KIND>
223 Expr<Type<TypeCategory::Logical, KIND>> FoldOperation(
224     FoldingContext &context, Not<KIND> &&x) {
225   if (auto array{ApplyElementwise(context, x)}) {
226     return *array;
227   }
228   using Ty = Type<TypeCategory::Logical, KIND>;
229   auto &operand{x.left()};
230   if (auto value{GetScalarConstantValue<Ty>(operand)}) {
231     return Expr<Ty>{Constant<Ty>{!value->IsTrue()}};
232   }
233   return Expr<Ty>{x};
234 }
235 
236 template <int KIND>
237 Expr<Type<TypeCategory::Logical, KIND>> FoldOperation(
238     FoldingContext &context, LogicalOperation<KIND> &&operation) {
239   using LOGICAL = Type<TypeCategory::Logical, KIND>;
240   if (auto array{ApplyElementwise(context, operation,
241           std::function<Expr<LOGICAL>(Expr<LOGICAL> &&, Expr<LOGICAL> &&)>{
242               [=](Expr<LOGICAL> &&x, Expr<LOGICAL> &&y) {
243                 return Expr<LOGICAL>{LogicalOperation<KIND>{
244                     operation.logicalOperator, std::move(x), std::move(y)}};
245               }})}) {
246     return *array;
247   }
248   if (auto folded{OperandsAreConstants(operation)}) {
249     bool xt{folded->first.IsTrue()}, yt{folded->second.IsTrue()}, result{};
250     switch (operation.logicalOperator) {
251     case LogicalOperator::And:
252       result = xt && yt;
253       break;
254     case LogicalOperator::Or:
255       result = xt || yt;
256       break;
257     case LogicalOperator::Eqv:
258       result = xt == yt;
259       break;
260     case LogicalOperator::Neqv:
261       result = xt != yt;
262       break;
263     case LogicalOperator::Not:
264       DIE("not a binary operator");
265     }
266     return Expr<LOGICAL>{Constant<LOGICAL>{result}};
267   }
268   return Expr<LOGICAL>{std::move(operation)};
269 }
270 
271 #ifdef _MSC_VER // disable bogus warning about missing definitions
272 #pragma warning(disable : 4661)
273 #endif
274 FOR_EACH_LOGICAL_KIND(template class ExpressionBase, )
275 template class ExpressionBase<SomeLogical>;
276 } // namespace Fortran::evaluate
277