xref: /llvm-project/flang/lib/Evaluate/fold-logical.cpp (revision 27899112c69836cb1e7bbb58df2f3471a882292c)
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 "flang/Evaluate/check-expression.h"
11 
12 namespace Fortran::evaluate {
13 
14 template <int KIND>
15 Expr<Type<TypeCategory::Logical, KIND>> FoldIntrinsicFunction(
16     FoldingContext &context,
17     FunctionRef<Type<TypeCategory::Logical, KIND>> &&funcRef) {
18   using T = Type<TypeCategory::Logical, 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 == "all") {
24     if (!args[1]) { // TODO: ALL(x,DIM=d)
25       if (const auto *constant{UnwrapConstantValue<T>(args[0])}) {
26         bool result{true};
27         for (const auto &element : constant->values()) {
28           if (!element.IsTrue()) {
29             result = false;
30             break;
31           }
32         }
33         return Expr<T>{result};
34       }
35     }
36   } else if (name == "any") {
37     if (!args[1]) { // TODO: ANY(x,DIM=d)
38       if (const auto *constant{UnwrapConstantValue<T>(args[0])}) {
39         bool result{false};
40         for (const auto &element : constant->values()) {
41           if (element.IsTrue()) {
42             result = true;
43             break;
44           }
45         }
46         return Expr<T>{result};
47       }
48     }
49   } else if (name == "associated") {
50     bool gotConstant{true};
51     const Expr<SomeType> *firstArgExpr{args[0]->UnwrapExpr()};
52     if (!firstArgExpr || !IsNullPointer(*firstArgExpr)) {
53       gotConstant = false;
54     } else if (args[1]) { // There's a second argument
55       const Expr<SomeType> *secondArgExpr{args[1]->UnwrapExpr()};
56       if (!secondArgExpr || !IsNullPointer(*secondArgExpr)) {
57         gotConstant = false;
58       }
59     }
60     return gotConstant ? Expr<T>{false} : Expr<T>{std::move(funcRef)};
61   } else if (name == "bge" || name == "bgt" || name == "ble" || name == "blt") {
62     using LargestInt = Type<TypeCategory::Integer, 16>;
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 == "isnan") {
93     // A warning about an invalid argument is discarded from converting
94     // the argument of isnan().
95     auto restorer{context.messages().DiscardMessages()};
96     using DefaultReal = Type<TypeCategory::Real, 4>;
97     return FoldElementalIntrinsic<T, DefaultReal>(context, std::move(funcRef),
98         ScalarFunc<T, DefaultReal>([](const Scalar<DefaultReal> &x) {
99           return Scalar<T>{x.IsNotANumber()};
100         }));
101   } else if (name == "is_contiguous") {
102     if (args.at(0)) {
103       if (auto *expr{args[0]->UnwrapExpr()}) {
104         if (IsSimplyContiguous(*expr, context)) {
105           return Expr<T>{true};
106         }
107       }
108     }
109   } else if (name == "logical") {
110     if (auto *expr{UnwrapExpr<Expr<SomeLogical>>(args[0])}) {
111       return Fold(context, ConvertToType<T>(std::move(*expr)));
112     }
113   } else if (name == "merge") {
114     return FoldMerge<T>(context, std::move(funcRef));
115   } else if (name == "__builtin_ieee_support_datatype" ||
116       name == "__builtin_ieee_support_denormal" ||
117       name == "__builtin_ieee_support_divide" ||
118       name == "__builtin_ieee_support_divide" ||
119       name == "__builtin_ieee_support_inf" ||
120       name == "__builtin_ieee_support_io" ||
121       name == "__builtin_ieee_support_nan" ||
122       name == "__builtin_ieee_support_sqrt" ||
123       name == "__builtin_ieee_support_standard" ||
124       name == "__builtin_ieee_support_subnormal" ||
125       name == "__builtin_ieee_support_underflow_control") {
126     return Expr<T>{true};
127   }
128   // TODO: btest, cshift, dot_product, eoshift, is_iostat_end,
129   // is_iostat_eor, lge, lgt, lle, llt, logical, matmul, out_of_range,
130   // pack, parity, reduce, spread, transfer, transpose, unpack,
131   // extends_type_of, same_type_as
132   return Expr<T>{std::move(funcRef)};
133 }
134 
135 template <typename T>
136 Expr<LogicalResult> FoldOperation(
137     FoldingContext &context, Relational<T> &&relation) {
138   if (auto array{ApplyElementwise(context, relation,
139           std::function<Expr<LogicalResult>(Expr<T> &&, Expr<T> &&)>{
140               [=](Expr<T> &&x, Expr<T> &&y) {
141                 return Expr<LogicalResult>{Relational<SomeType>{
142                     Relational<T>{relation.opr, std::move(x), std::move(y)}}};
143               }})}) {
144     return *array;
145   }
146   if (auto folded{OperandsAreConstants(relation)}) {
147     bool result{};
148     if constexpr (T::category == TypeCategory::Integer) {
149       result =
150           Satisfies(relation.opr, folded->first.CompareSigned(folded->second));
151     } else if constexpr (T::category == TypeCategory::Real) {
152       result = Satisfies(relation.opr, folded->first.Compare(folded->second));
153     } else if constexpr (T::category == TypeCategory::Complex) {
154       result = (relation.opr == RelationalOperator::EQ) ==
155           folded->first.Equals(folded->second);
156     } else if constexpr (T::category == TypeCategory::Character) {
157       result = Satisfies(relation.opr, Compare(folded->first, folded->second));
158     } else {
159       static_assert(T::category != TypeCategory::Logical);
160     }
161     return Expr<LogicalResult>{Constant<LogicalResult>{result}};
162   }
163   return Expr<LogicalResult>{Relational<SomeType>{std::move(relation)}};
164 }
165 
166 Expr<LogicalResult> FoldOperation(
167     FoldingContext &context, Relational<SomeType> &&relation) {
168   return std::visit(
169       [&](auto &&x) {
170         return Expr<LogicalResult>{FoldOperation(context, std::move(x))};
171       },
172       std::move(relation.u));
173 }
174 
175 template <int KIND>
176 Expr<Type<TypeCategory::Logical, KIND>> FoldOperation(
177     FoldingContext &context, Not<KIND> &&x) {
178   if (auto array{ApplyElementwise(context, x)}) {
179     return *array;
180   }
181   using Ty = Type<TypeCategory::Logical, KIND>;
182   auto &operand{x.left()};
183   if (auto value{GetScalarConstantValue<Ty>(operand)}) {
184     return Expr<Ty>{Constant<Ty>{!value->IsTrue()}};
185   }
186   return Expr<Ty>{x};
187 }
188 
189 template <int KIND>
190 Expr<Type<TypeCategory::Logical, KIND>> FoldOperation(
191     FoldingContext &context, LogicalOperation<KIND> &&operation) {
192   using LOGICAL = Type<TypeCategory::Logical, KIND>;
193   if (auto array{ApplyElementwise(context, operation,
194           std::function<Expr<LOGICAL>(Expr<LOGICAL> &&, Expr<LOGICAL> &&)>{
195               [=](Expr<LOGICAL> &&x, Expr<LOGICAL> &&y) {
196                 return Expr<LOGICAL>{LogicalOperation<KIND>{
197                     operation.logicalOperator, std::move(x), std::move(y)}};
198               }})}) {
199     return *array;
200   }
201   if (auto folded{OperandsAreConstants(operation)}) {
202     bool xt{folded->first.IsTrue()}, yt{folded->second.IsTrue()}, result{};
203     switch (operation.logicalOperator) {
204     case LogicalOperator::And:
205       result = xt && yt;
206       break;
207     case LogicalOperator::Or:
208       result = xt || yt;
209       break;
210     case LogicalOperator::Eqv:
211       result = xt == yt;
212       break;
213     case LogicalOperator::Neqv:
214       result = xt != yt;
215       break;
216     case LogicalOperator::Not:
217       DIE("not a binary operator");
218     }
219     return Expr<LOGICAL>{Constant<LOGICAL>{result}};
220   }
221   return Expr<LOGICAL>{std::move(operation)};
222 }
223 
224 FOR_EACH_LOGICAL_KIND(template class ExpressionBase, )
225 template class ExpressionBase<SomeLogical>;
226 } // namespace Fortran::evaluate
227