Debian Codegraph @

flang/lib/Evaluate/fold-implementation.h

raw
1 //===-- lib/Evaluate/fold-implementation.h --------------------------------===//
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 #ifndef FORTRAN_EVALUATE_FOLD_IMPLEMENTATION_H_
10 #define FORTRAN_EVALUATE_FOLD_IMPLEMENTATION_H_
11
12 #include "character.h"
13 #include "host.h"
14 #include "int-power.h"
15 #include "flang/Common/indirection.h"
16 #include "flang/Common/template.h"
17 #include "flang/Common/unwrap.h"
18 #include "flang/Evaluate/characteristics.h"
19 #include "flang/Evaluate/common.h"
20 #include "flang/Evaluate/constant.h"
21 #include "flang/Evaluate/expression.h"
22 #include "flang/Evaluate/fold.h"
23 #include "flang/Evaluate/formatting.h"
24 #include "flang/Evaluate/intrinsics-library.h"
25 #include "flang/Evaluate/intrinsics.h"
26 #include "flang/Evaluate/shape.h"
27 #include "flang/Evaluate/tools.h"
28 #include "flang/Evaluate/traverse.h"
29 #include "flang/Evaluate/type.h"
30 #include "flang/Parser/message.h"
31 #include "flang/Semantics/scope.h"
32 #include "flang/Semantics/symbol.h"
33 #include "flang/Semantics/tools.h"
34 #include <algorithm>
35 #include <cmath>
36 #include <complex>
37 #include <cstdio>
38 #include <optional>
39 #include <type_traits>
40 #include <variant>
41
42 // Some environments, viz. glibc 2.17 and *BSD, allow the macro HUGE
43 // to leak out of <math.h>.
44 #undef HUGE
45
46 namespace Fortran::evaluate {
47
48 // Don't use Kahan extended precision summation any more when folding
49 // transformational intrinsic functions other than SUM, since it is
50 // not used in the runtime implementations of those functions and we
51 // want results to match.
52 static constexpr bool useKahanSummation{false};
53
54 // Utilities
55 template <typename T> class Folder {
56 public:
57 explicit Folder(FoldingContext &c) : context_{c} {}
58 std::optional<Constant<T>> GetNamedConstant(const Symbol &);
59 std::optional<Constant<T>> ApplySubscripts(const Constant<T> &array,
60 const std::vector<Constant<SubscriptInteger>> &subscripts);
61 std::optional<Constant<T>> ApplyComponent(Constant<SomeDerived> &&,
62 const Symbol &component,
63 const std::vector<Constant<SubscriptInteger>> * = nullptr);
64 std::optional<Constant<T>> GetConstantComponent(
65 Component &, const std::vector<Constant<SubscriptInteger>> * = nullptr);
66 std::optional<Constant<T>> Folding(ArrayRef &);
67 std::optional<Constant<T>> Folding(DataRef &);
68 Expr<T> Folding(Designator<T> &&);
69 Constant<T> *Folding(std::optional<ActualArgument> &);
70
71 Expr<T> CSHIFT(FunctionRef<T> &&);
72 Expr<T> EOSHIFT(FunctionRef<T> &&);
73 Expr<T> MERGE(FunctionRef<T> &&);
74 Expr<T> PACK(FunctionRef<T> &&);
75 Expr<T> RESHAPE(FunctionRef<T> &&);
76 Expr<T> SPREAD(FunctionRef<T> &&);
77 Expr<T> TRANSPOSE(FunctionRef<T> &&);
78 Expr<T> UNPACK(FunctionRef<T> &&);
79
80 Expr<T> TRANSFER(FunctionRef<T> &&);
81
82 private:
83 FoldingContext &context_;
84 };
85
86 std::optional<Constant<SubscriptInteger>> GetConstantSubscript(
87 FoldingContext &, Subscript &, const NamedEntity &, int dim);
88
89 // Helper to use host runtime on scalars for folding.
90 template <typename TR, typename... TA>
91 std::optional<std::function<Scalar<TR>(FoldingContext &, Scalar<TA>...)>>
92 GetHostRuntimeWrapper(const std::string &name) {
93 std::vector<DynamicType> argTypes{TA{}.GetType()...};
94 if (auto hostWrapper{GetHostRuntimeWrapper(name, TR{}.GetType(), argTypes)}) {
95 return [hostWrapper](
96 FoldingContext &context, Scalar<TA>... args) -> Scalar<TR> {
97 std::vector<Expr<SomeType>> genericArgs{
98 AsGenericExpr(Constant<TA>{args})...};
99 return GetScalarConstantValue<TR>(
100 (*hostWrapper)(context, std::move(genericArgs)))
101 .value();
102 };
103 }
104 return std::nullopt;
105 }
106
107 // FoldOperation() rewrites expression tree nodes.
108 // If there is any possibility that the rewritten node will
109 // not have the same representation type, the result of
110 // FoldOperation() will be packaged in an Expr<> of the same
111 // specific type.
112
113 // no-op base case
114 template <typename A>
115 common::IfNoLvalue<Expr<ResultType<A>>, A> FoldOperation(
116 FoldingContext &, A &&x) {
117 static_assert(!std::is_same_v<A, Expr<ResultType<A>>>,
118 "call Fold() instead for Expr<>");
119 return Expr<ResultType<A>>{std::move(x)};
120 }
121
122 Component FoldOperation(FoldingContext &, Component &&);
123 NamedEntity FoldOperation(FoldingContext &, NamedEntity &&);
124 Triplet FoldOperation(FoldingContext &, Triplet &&);
125 Subscript FoldOperation(FoldingContext &, Subscript &&);
126 ArrayRef FoldOperation(FoldingContext &, ArrayRef &&);
127 CoarrayRef FoldOperation(FoldingContext &, CoarrayRef &&);
128 DataRef FoldOperation(FoldingContext &, DataRef &&);
129 Substring FoldOperation(FoldingContext &, Substring &&);
130 ComplexPart FoldOperation(FoldingContext &, ComplexPart &&);
131 template <typename T>
132 Expr<T> FoldOperation(FoldingContext &, FunctionRef<T> &&);
133 template <typename T>
134 Expr<T> FoldOperation(FoldingContext &context, Designator<T> &&designator) {
135 return Folder<T>{context}.Folding(std::move(designator));
136 }
137 Expr<TypeParamInquiry::Result> FoldOperation(
138 FoldingContext &, TypeParamInquiry &&);
139 Expr<ImpliedDoIndex::Result> FoldOperation(
140 FoldingContext &context, ImpliedDoIndex &&);
141 template <typename T>
142 Expr<T> FoldOperation(FoldingContext &, ArrayConstructor<T> &&);
143 Expr<SomeDerived> FoldOperation(FoldingContext &, StructureConstructor &&);
144
145 template <typename T>
146 std::optional<Constant<T>> Folder<T>::GetNamedConstant(const Symbol &symbol0) {
147 const Symbol &symbol{ResolveAssociations(symbol0)};
148 if (IsNamedConstant(symbol)) {
149 if (const auto *object{
150 symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
151 if (const auto *constant{UnwrapConstantValue<T>(object->init())}) {
152 return *constant;
153 }
154 }
155 }
156 return std::nullopt;
157 }
158
159 template <typename T>
160 std::optional<Constant<T>> Folder<T>::Folding(ArrayRef &aRef) {
161 std::vector<Constant<SubscriptInteger>> subscripts;
162 int dim{0};
163 for (Subscript &ss : aRef.subscript()) {
164 if (auto constant{GetConstantSubscript(context_, ss, aRef.base(), dim++)}) {
165 subscripts.emplace_back(std::move(*constant));
166 } else {
167 return std::nullopt;
168 }
169 }
170 if (Component * component{aRef.base().UnwrapComponent()}) {
171 return GetConstantComponent(*component, &subscripts);
172 } else if (std::optional<Constant<T>> array{
173 GetNamedConstant(aRef.base().GetLastSymbol())}) {
174 return ApplySubscripts(*array, subscripts);
175 } else {
176 return std::nullopt;
177 }
178 }
179
180 template <typename T>
181 std::optional<Constant<T>> Folder<T>::Folding(DataRef &ref) {
182 return common::visit(
183 common::visitors{
184 [this](SymbolRef &sym) { return GetNamedConstant(*sym); },
185 [this](Component &comp) {
186 comp = FoldOperation(context_, std::move(comp));
187 return GetConstantComponent(comp);
188 },
189 [this](ArrayRef &aRef) {
190 aRef = FoldOperation(context_, std::move(aRef));
191 return Folding(aRef);
192 },
193 [](CoarrayRef &) { return std::optional<Constant<T>>{}; },
194 },
195 ref.u);
196 }
197
198 // TODO: This would be more natural as a member function of Constant<T>.
199 template <typename T>
200 std::optional<Constant<T>> Folder<T>::ApplySubscripts(const Constant<T> &array,
201 const std::vector<Constant<SubscriptInteger>> &subscripts) {
202 const auto &shape{array.shape()};
203 const auto &lbounds{array.lbounds()};
204 int rank{GetRank(shape)};
205 CHECK(rank == static_cast<int>(subscripts.size()));
206 std::size_t elements{1};
207 ConstantSubscripts resultShape;
208 ConstantSubscripts ssLB;
209 for (const auto &ss : subscripts) {
210 if (ss.Rank() == 1) {
211 resultShape.push_back(static_cast<ConstantSubscript>(ss.size()));
212 elements *= ss.size();
213 ssLB.push_back(ss.lbounds().front());
214 } else if (ss.Rank() > 1) {
215 return std::nullopt; // error recovery
216 }
217 }
218 ConstantSubscripts ssAt(rank, 0), at(rank, 0), tmp(1, 0);
219 std::vector<Scalar<T>> values;
220 while (elements-- > 0) {
221 bool increment{true};
222 int k{0};
223 for (int j{0}; j < rank; ++j) {
224 if (subscripts[j].Rank() == 0) {
225 at[j] = subscripts[j].GetScalarValue().value().ToInt64();
226 } else {
227 CHECK(k < GetRank(resultShape));
228 tmp[0] = ssLB.at(k) + ssAt.at(k);
229 at[j] = subscripts[j].At(tmp).ToInt64();
230 if (increment) {
231 if (++ssAt[k] == resultShape[k]) {
232 ssAt[k] = 0;
233 } else {
234 increment = false;
235 }
236 }
237 ++k;
238 }
239 if (at[j] < lbounds[j] || at[j] >= lbounds[j] + shape[j]) {
240 context_.messages().Say(
241 "Subscript value (%jd) is out of range on dimension %d in reference to a constant array value"_err_en_US,
242 at[j], j + 1);
243 return std::nullopt;
244 }
245 }
246 values.emplace_back(array.At(at));
247 CHECK(!increment || elements == 0);
248 CHECK(k == GetRank(resultShape));
249 }
250 if constexpr (T::category == TypeCategory::Character) {
251 return Constant<T>{array.LEN(), std::move(values), std::move(resultShape)};
252 } else if constexpr (std::is_same_v<T, SomeDerived>) {
253 return Constant<T>{array.result().derivedTypeSpec(), std::move(values),
254 std::move(resultShape)};
255 } else {
256 return Constant<T>{std::move(values), std::move(resultShape)};
257 }
258 }
259
260 template <typename T>
261 std::optional<Constant<T>> Folder<T>::ApplyComponent(
262 Constant<SomeDerived> &&structures, const Symbol &component,
263 const std::vector<Constant<SubscriptInteger>> *subscripts) {
264 if (auto scalar{structures.GetScalarValue()}) {
265 if (std::optional<Expr<SomeType>> expr{scalar->Find(component)}) {
266 if (const Constant<T> *value{UnwrapConstantValue<T>(*expr)}) {
267 if (subscripts) {
268 return ApplySubscripts(*value, *subscripts);
269 } else {
270 return *value;
271 }
272 }
273 }
274 } else {
275 // A(:)%scalar_component & A(:)%array_component(subscripts)
276 std::unique_ptr<ArrayConstructor<T>> array;
277 if (structures.empty()) {
278 return std::nullopt;
279 }
280 ConstantSubscripts at{structures.lbounds()};
281 do {
282 StructureConstructor scalar{structures.At(at)};
283 if (std::optional<Expr<SomeType>> expr{scalar.Find(component)}) {
284 if (const Constant<T> *value{UnwrapConstantValue<T>(expr.value())}) {
285 if (!array.get()) {
286 // This technique ensures that character length or derived type
287 // information is propagated to the array constructor.
288 auto *typedExpr{UnwrapExpr<Expr<T>>(expr.value())};
289 CHECK(typedExpr);
290 array = std::make_unique<ArrayConstructor<T>>(*typedExpr);
291 }
292 if (subscripts) {
293 if (auto element{ApplySubscripts(*value, *subscripts)}) {
294 CHECK(element->Rank() == 0);
295 array->Push(Expr<T>{std::move(*element)});
296 } else {
297 return std::nullopt;
298 }
299 } else {
300 CHECK(value->Rank() == 0);
301 array->Push(Expr<T>{*value});
302 }
303 } else {
304 return std::nullopt;
305 }
306 }
307 } while (structures.IncrementSubscripts(at));
308 // Fold the ArrayConstructor<> into a Constant<>.
309 CHECK(array);
310 Expr<T> result{Fold(context_, Expr<T>{std::move(*array)})};
311 if (auto *constant{UnwrapConstantValue<T>(result)}) {
312 return constant->Reshape(common::Clone(structures.shape()));
313 }
314 }
315 return std::nullopt;
316 }
317
318 template <typename T>
319 std::optional<Constant<T>> Folder<T>::GetConstantComponent(Component &component,
320 const std::vector<Constant<SubscriptInteger>> *subscripts) {
321 if (std::optional<Constant<SomeDerived>> structures{common::visit(
322 common::visitors{
323 [&](const Symbol &symbol) {
324 return Folder<SomeDerived>{context_}.GetNamedConstant(symbol);
325 },
326 [&](ArrayRef &aRef) {
327 return Folder<SomeDerived>{context_}.Folding(aRef);
328 },
329 [&](Component &base) {
330 return Folder<SomeDerived>{context_}.GetConstantComponent(base);
331 },
332 [&](CoarrayRef &) {
333 return std::optional<Constant<SomeDerived>>{};
334 },
335 },
336 component.base().u)}) {
337 return ApplyComponent(
338 std::move(*structures), component.GetLastSymbol(), subscripts);
339 } else {
340 return std::nullopt;
341 }
342 }
343
344 template <typename T> Expr<T> Folder<T>::Folding(Designator<T> &&designator) {
345 if constexpr (T::category == TypeCategory::Character) {
346 if (auto *substring{common::Unwrap<Substring>(designator.u)}) {
347 if (std::optional<Expr<SomeCharacter>> folded{
348 substring->Fold(context_)}) {
349 if (const auto *specific{std::get_if<Expr<T>>(&folded->u)}) {
350 return std::move(*specific);
351 }
352 }
353 // We used to fold zero-length substrings into zero-length
354 // constants here, but that led to problems in variable
355 // definition contexts.
356 }
357 } else if constexpr (T::category == TypeCategory::Real) {
358 if (auto *zPart{std::get_if<ComplexPart>(&designator.u)}) {
359 *zPart = FoldOperation(context_, std::move(*zPart));
360 using ComplexT = Type<TypeCategory::Complex, T::kind>;
361 if (auto zConst{Folder<ComplexT>{context_}.Folding(zPart->complex())}) {
362 return Fold(context_,
363 Expr<T>{ComplexComponent<T::kind>{
364 zPart->part() == ComplexPart::Part::IM,
365 Expr<ComplexT>{std::move(*zConst)}}});
366 } else {
367 return Expr<T>{Designator<T>{std::move(*zPart)}};
368 }
369 }
370 }
371 return common::visit(
372 common::visitors{
373 [&](SymbolRef &&symbol) {
374 if (auto constant{GetNamedConstant(*symbol)}) {
375 return Expr<T>{std::move(*constant)};
376 }
377 return Expr<T>{std::move(designator)};
378 },
379 [&](ArrayRef &&aRef) {
380 aRef = FoldOperation(context_, std::move(aRef));
381 if (auto c{Folding(aRef)}) {
382 return Expr<T>{std::move(*c)};
383 } else {
384 return Expr<T>{Designator<T>{std::move(aRef)}};
385 }
386 },
387 [&](Component &&component) {
388 component = FoldOperation(context_, std::move(component));
389 if (auto c{GetConstantComponent(component)}) {
390 return Expr<T>{std::move(*c)};
391 } else {
392 return Expr<T>{Designator<T>{std::move(component)}};
393 }
394 },
395 [&](auto &&x) {
396 return Expr<T>{
397 Designator<T>{FoldOperation(context_, std::move(x))}};
398 },
399 },
400 std::move(designator.u));
401 }
402
403 // Apply type conversion and re-folding if necessary.
404 // This is where BOZ arguments are converted.
405 template <typename T>
406 Constant<T> *Folder<T>::Folding(std::optional<ActualArgument> &arg) {
407 if (auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
408 if constexpr (T::category != TypeCategory::Derived) {
409 if (!UnwrapExpr<Expr<T>>(*expr)) {
410 if (auto converted{ConvertToType(T::GetType(), std::move(*expr))}) {
411 *expr = Fold(context_, std::move(*converted));
412 }
413 }
414 }
415 return UnwrapConstantValue<T>(*expr);
416 }
417 return nullptr;
418 }
419
420 template <typename... A, std::size_t... I>
421 std::optional<std::tuple<const Constant<A> *...>> GetConstantArgumentsHelper(
422 FoldingContext &context, ActualArguments &arguments,
423 std::index_sequence<I...>) {
424 static_assert(sizeof...(A) > 0);
425 std::tuple<const Constant<A> *...> args{
426 Folder<A>{context}.Folding(arguments.at(I))...};
427 if ((... && (std::get<I>(args)))) {
428 return args;
429 } else {
430 return std::nullopt;
431 }
432 }
433
434 template <typename... A>
435 std::optional<std::tuple<const Constant<A> *...>> GetConstantArguments(
436 FoldingContext &context, ActualArguments &args) {
437 return GetConstantArgumentsHelper<A...>(
438 context, args, std::index_sequence_for<A...>{});
439 }
440
441 template <typename... A, std::size_t... I>
442 std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArgumentsHelper(
443 FoldingContext &context, ActualArguments &args, std::index_sequence<I...>) {
444 if (auto constArgs{GetConstantArguments<A...>(context, args)}) {
445 return std::tuple<Scalar<A>...>{
446 std::get<I>(*constArgs)->GetScalarValue().value()...};
447 } else {
448 return std::nullopt;
449 }
450 }
451
452 template <typename... A>
453 std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArguments(
454 FoldingContext &context, ActualArguments &args) {
455 return GetScalarConstantArgumentsHelper<A...>(
456 context, args, std::index_sequence_for<A...>{});
457 }
458
459 // helpers to fold intrinsic function references
460 // Define callable types used in a common utility that
461 // takes care of array and cast/conversion aspects for elemental intrinsics
462
463 template <typename TR, typename... TArgs>
464 using ScalarFunc = std::function<Scalar<TR>(const Scalar<TArgs> &...)>;
465 template <typename TR, typename... TArgs>
466 using ScalarFuncWithContext =
467 std::function<Scalar<TR>(FoldingContext &, const Scalar<TArgs> &...)>;
468
469 template <template <typename, typename...> typename WrapperType, typename TR,
470 typename... TA, std::size_t... I>
471 Expr<TR> FoldElementalIntrinsicHelper(FoldingContext &context,
472 FunctionRef<TR> &&funcRef, WrapperType<TR, TA...> func,
473 std::index_sequence<I...>) {
474 if (std::optional<std::tuple<const Constant<TA> *...>> args{
475 GetConstantArguments<TA...>(context, funcRef.arguments())}) {
476 // Compute the shape of the result based on shapes of arguments
477 ConstantSubscripts shape;
478 int rank{0};
479 const ConstantSubscripts *shapes[]{&std::get<I>(*args)->shape()...};
480 const int ranks[]{std::get<I>(*args)->Rank()...};
481 for (unsigned int i{0}; i < sizeof...(TA); ++i) {
482 if (ranks[i] > 0) {
483 if (rank == 0) {
484 rank = ranks[i];
485 shape = *shapes[i];
486 } else {
487 if (shape != *shapes[i]) {
488 // TODO: Rank compatibility was already checked but it seems to be
489 // the first place where the actual shapes are checked to be the
490 // same. Shouldn't this be checked elsewhere so that this is also
491 // checked for non constexpr call to elemental intrinsics function?
492 context.messages().Say(
493 "Arguments in elemental intrinsic function are not conformable"_err_en_US);
494 return Expr<TR>{std::move(funcRef)};
495 }
496 }
497 }
498 }
499 CHECK(rank == GetRank(shape));
500 // Compute all the scalar values of the results
501 std::vector<Scalar<TR>> results;
502 std::optional<uint64_t> n{TotalElementCount(shape)};
503 if (!n) {
504 context.messages().Say(
505 "Too many elements in elemental intrinsic function result"_err_en_US);
506 return Expr<TR>{std::move(funcRef)};
507 }
508 if (*n > 0) {
509 ConstantBounds bounds{shape};
510 ConstantSubscripts resultIndex(rank, 1);
511 ConstantSubscripts argIndex[]{std::get<I>(*args)->lbounds()...};
512 do {
513 if constexpr (std::is_same_v<WrapperType<TR, TA...>,
514 ScalarFuncWithContext<TR, TA...>>) {
515 results.emplace_back(
516 func(context, std::get<I>(*args)->At(argIndex[I])...));
517 } else if constexpr (std::is_same_v<WrapperType<TR, TA...>,
518 ScalarFunc<TR, TA...>>) {
519 results.emplace_back(func(std::get<I>(*args)->At(argIndex[I])...));
520 }
521 (std::get<I>(*args)->IncrementSubscripts(argIndex[I]), ...);
522 } while (bounds.IncrementSubscripts(resultIndex));
523 }
524 // Build and return constant result
525 if constexpr (TR::category == TypeCategory::Character) {
526 auto len{static_cast<ConstantSubscript>(
527 results.empty() ? 0 : results[0].length())};
528 return Expr<TR>{Constant<TR>{len, std::move(results), std::move(shape)}};
529 } else if constexpr (TR::category == TypeCategory::Derived) {
530 if (!results.empty()) {
531 return Expr<TR>{rank == 0
532 ? Constant<TR>{results.front()}
533 : Constant<TR>{results.front().derivedTypeSpec(),
534 std::move(results), std::move(shape)}};
535 }
536 } else {
537 return Expr<TR>{Constant<TR>{std::move(results), std::move(shape)}};
538 }
539 }
540 return Expr<TR>{std::move(funcRef)};
541 }
542
543 template <typename TR, typename... TA>
544 Expr<TR> FoldElementalIntrinsic(FoldingContext &context,
545 FunctionRef<TR> &&funcRef, ScalarFunc<TR, TA...> func) {
546 return FoldElementalIntrinsicHelper<ScalarFunc, TR, TA...>(
547 context, std::move(funcRef), func, std::index_sequence_for<TA...>{});
548 }
549 template <typename TR, typename... TA>
550 Expr<TR> FoldElementalIntrinsic(FoldingContext &context,
551 FunctionRef<TR> &&funcRef, ScalarFuncWithContext<TR, TA...> func) {
552 return FoldElementalIntrinsicHelper<ScalarFuncWithContext, TR, TA...>(
553 context, std::move(funcRef), func, std::index_sequence_for<TA...>{});
554 }
555
556 std::optional<std::int64_t> GetInt64ArgOr(
557 const std::optional<ActualArgument> &, std::int64_t defaultValue);
558
559 template <typename A, typename B>
560 std::optional<std::vector<A>> GetIntegerVector(const B &x) {
561 static_assert(std::is_integral_v<A>);
562 if (const auto *someInteger{UnwrapExpr<Expr<SomeInteger>>(x)}) {
563 return common::visit(
564 [](const auto &typedExpr) -> std::optional<std::vector<A>> {
565 using T = ResultType<decltype(typedExpr)>;
566 if (const auto *constant{UnwrapConstantValue<T>(typedExpr)}) {
567 if (constant->Rank() == 1) {
568 std::vector<A> result;
569 for (const auto &value : constant->values()) {
570 result.push_back(static_cast<A>(value.ToInt64()));
571 }
572 return result;
573 }
574 }
575 return std::nullopt;
576 },
577 someInteger->u);
578 }
579 return std::nullopt;
580 }
581
582 // Transform an intrinsic function reference that contains user errors
583 // into an intrinsic with the same characteristic but the "invalid" name.
584 // This to prevent generating warnings over and over if the expression
585 // gets re-folded.
586 template <typename T> Expr<T> MakeInvalidIntrinsic(FunctionRef<T> &&funcRef) {
587 SpecificIntrinsic invalid{std::get<SpecificIntrinsic>(funcRef.proc().u)};
588 invalid.name = IntrinsicProcTable::InvalidName;
589 return Expr<T>{FunctionRef<T>{ProcedureDesignator{std::move(invalid)},
590 ActualArguments{std::move(funcRef.arguments())}}};
591 }
592
593 template <typename T> Expr<T> Folder<T>::CSHIFT(FunctionRef<T> &&funcRef) {
594 auto args{funcRef.arguments()};
595 CHECK(args.size() == 3);
596 const auto *array{UnwrapConstantValue<T>(args[0])};
597 const auto *shiftExpr{UnwrapExpr<Expr<SomeInteger>>(args[1])};
598 auto dim{GetInt64ArgOr(args[2], 1)};
599 if (!array || !shiftExpr || !dim) {
600 return Expr<T>{std::move(funcRef)};
601 }
602 auto convertedShift{Fold(context_,
603 ConvertToType<SubscriptInteger>(Expr<SomeInteger>{*shiftExpr}))};
604 const auto *shift{UnwrapConstantValue<SubscriptInteger>(convertedShift)};
605 if (!shift) {
606 return Expr<T>{std::move(funcRef)};
607 }
608 // Arguments are constant
609 if (*dim < 1 || *dim > array->Rank()) {
610 context_.messages().Say("Invalid 'dim=' argument (%jd) in CSHIFT"_err_en_US,
611 static_cast<std::intmax_t>(*dim));
612 } else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
613 // message already emitted from intrinsic look-up
614 } else {
615 int rank{array->Rank()};
616 int zbDim{static_cast<int>(*dim) - 1};
617 bool ok{true};
618 if (shift->Rank() > 0) {
619 int k{0};
620 for (int j{0}; j < rank; ++j) {
621 if (j != zbDim) {
622 if (array->shape()[j] != shift->shape()[k]) {
623 context_.messages().Say(
624 "Invalid 'shift=' argument in CSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
625 k + 1, static_cast<std::intmax_t>(shift->shape()[k]),
626 static_cast<std::intmax_t>(array->shape()[j]));
627 ok = false;
628 }
629 ++k;
630 }
631 }
632 }
633 if (ok) {
634 std::vector<Scalar<T>> resultElements;
635 ConstantSubscripts arrayLB{array->lbounds()};
636 ConstantSubscripts arrayAt{arrayLB};
637 ConstantSubscript &dimIndex{arrayAt[zbDim]};
638 ConstantSubscript dimLB{dimIndex}; // initial value
639 ConstantSubscript dimExtent{array->shape()[zbDim]};
640 ConstantSubscripts shiftLB{shift->lbounds()};
641 for (auto n{GetSize(array->shape())}; n > 0; --n) {
642 ConstantSubscript origDimIndex{dimIndex};
643 ConstantSubscripts shiftAt;
644 if (shift->Rank() > 0) {
645 int k{0};
646 for (int j{0}; j < rank; ++j) {
647 if (j != zbDim) {
648 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
649 }
650 }
651 }
652 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
653 dimIndex = dimLB + ((dimIndex - dimLB + shiftCount) % dimExtent);
654 if (dimIndex < dimLB) {
655 dimIndex += dimExtent;
656 } else if (dimIndex >= dimLB + dimExtent) {
657 dimIndex -= dimExtent;
658 }
659 resultElements.push_back(array->At(arrayAt));
660 dimIndex = origDimIndex;
661 array->IncrementSubscripts(arrayAt);
662 }
663 return Expr<T>{PackageConstant<T>(
664 std::move(resultElements), *array, array->shape())};
665 }
666 }
667 // Invalid, prevent re-folding
668 return MakeInvalidIntrinsic(std::move(funcRef));
669 }
670
671 template <typename T> Expr<T> Folder<T>::EOSHIFT(FunctionRef<T> &&funcRef) {
672 auto args{funcRef.arguments()};
673 CHECK(args.size() == 4);
674 const auto *array{UnwrapConstantValue<T>(args[0])};
675 const auto *shiftExpr{UnwrapExpr<Expr<SomeInteger>>(args[1])};
676 auto dim{GetInt64ArgOr(args[3], 1)};
677 if (!array || !shiftExpr || !dim) {
678 return Expr<T>{std::move(funcRef)};
679 }
680 // Apply type conversions to the shift= and boundary= arguments.
681 auto convertedShift{Fold(context_,
682 ConvertToType<SubscriptInteger>(Expr<SomeInteger>{*shiftExpr}))};
683 const auto *shift{UnwrapConstantValue<SubscriptInteger>(convertedShift)};
684 if (!shift) {
685 return Expr<T>{std::move(funcRef)};
686 }
687 const Constant<T> *boundary{nullptr};
688 std::optional<Expr<SomeType>> convertedBoundary;
689 if (const auto *boundaryExpr{UnwrapExpr<Expr<SomeType>>(args[2])}) {
690 convertedBoundary = Fold(context_,
691 ConvertToType(array->GetType(), Expr<SomeType>{*boundaryExpr}));
692 boundary = UnwrapExpr<Constant<T>>(convertedBoundary);
693 if (!boundary) {
694 return Expr<T>{std::move(funcRef)};
695 }
696 }
697 // Arguments are constant
698 if (*dim < 1 || *dim > array->Rank()) {
699 context_.messages().Say(
700 "Invalid 'dim=' argument (%jd) in EOSHIFT"_err_en_US,
701 static_cast<std::intmax_t>(*dim));
702 } else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
703 // message already emitted from intrinsic look-up
704 } else if (boundary && boundary->Rank() > 0 &&
705 boundary->Rank() != array->Rank() - 1) {
706 // ditto
707 } else {
708 int rank{array->Rank()};
709 int zbDim{static_cast<int>(*dim) - 1};
710 bool ok{true};
711 if (shift->Rank() > 0) {
712 int k{0};
713 for (int j{0}; j < rank; ++j) {
714 if (j != zbDim) {
715 if (array->shape()[j] != shift->shape()[k]) {
716 context_.messages().Say(
717 "Invalid 'shift=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
718 k + 1, static_cast<std::intmax_t>(shift->shape()[k]),
719 static_cast<std::intmax_t>(array->shape()[j]));
720 ok = false;
721 }
722 ++k;
723 }
724 }
725 }
726 if (boundary && boundary->Rank() > 0) {
727 int k{0};
728 for (int j{0}; j < rank; ++j) {
729 if (j != zbDim) {
730 if (array->shape()[j] != boundary->shape()[k]) {
731 context_.messages().Say(
732 "Invalid 'boundary=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
733 k + 1, static_cast<std::intmax_t>(boundary->shape()[k]),
734 static_cast<std::intmax_t>(array->shape()[j]));
735 ok = false;
736 }
737 ++k;
738 }
739 }
740 }
741 if (ok) {
742 std::vector<Scalar<T>> resultElements;
743 ConstantSubscripts arrayLB{array->lbounds()};
744 ConstantSubscripts arrayAt{arrayLB};
745 ConstantSubscript &dimIndex{arrayAt[zbDim]};
746 ConstantSubscript dimLB{dimIndex}; // initial value
747 ConstantSubscript dimExtent{array->shape()[zbDim]};
748 ConstantSubscripts shiftLB{shift->lbounds()};
749 ConstantSubscripts boundaryLB;
750 if (boundary) {
751 boundaryLB = boundary->lbounds();
752 }
753 for (auto n{GetSize(array->shape())}; n > 0; --n) {
754 ConstantSubscript origDimIndex{dimIndex};
755 ConstantSubscripts shiftAt;
756 if (shift->Rank() > 0) {
757 int k{0};
758 for (int j{0}; j < rank; ++j) {
759 if (j != zbDim) {
760 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
761 }
762 }
763 }
764 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
765 dimIndex += shiftCount;
766 if (dimIndex >= dimLB && dimIndex < dimLB + dimExtent) {
767 resultElements.push_back(array->At(arrayAt));
768 } else if (boundary) {
769 ConstantSubscripts boundaryAt;
770 if (boundary->Rank() > 0) {
771 for (int j{0}; j < rank; ++j) {
772 int k{0};
773 if (j != zbDim) {
774 boundaryAt.emplace_back(
775 boundaryLB[k++] + arrayAt[j] - arrayLB[j]);
776 }
777 }
778 }
779 resultElements.push_back(boundary->At(boundaryAt));
780 } else if constexpr (T::category == TypeCategory::Integer ||
781 T::category == TypeCategory::Real ||
782 T::category == TypeCategory::Complex ||
783 T::category == TypeCategory::Logical) {
784 resultElements.emplace_back();
785 } else if constexpr (T::category == TypeCategory::Character) {
786 auto len{static_cast<std::size_t>(array->LEN())};
787 typename Scalar<T>::value_type space{' '};
788 resultElements.emplace_back(len, space);
789 } else {
790 DIE("no derived type boundary");
791 }
792 dimIndex = origDimIndex;
793 array->IncrementSubscripts(arrayAt);
794 }
795 return Expr<T>{PackageConstant<T>(
796 std::move(resultElements), *array, array->shape())};
797 }
798 }
799 // Invalid, prevent re-folding
800 return MakeInvalidIntrinsic(std::move(funcRef));
801 }
802
803 template <typename T> Expr<T> Folder<T>::MERGE(FunctionRef<T> &&funcRef) {
804 return FoldElementalIntrinsic<T, T, T, LogicalResult>(context_,
805 std::move(funcRef),
806 ScalarFunc<T, T, T, LogicalResult>(
807 [](const Scalar<T> &ifTrue, const Scalar<T> &ifFalse,
808 const Scalar<LogicalResult> &predicate) -> Scalar<T> {
809 return predicate.IsTrue() ? ifTrue : ifFalse;
810 }));
811 }
812
813 template <typename T> Expr<T> Folder<T>::PACK(FunctionRef<T> &&funcRef) {
814 auto args{funcRef.arguments()};
815 CHECK(args.size() == 3);
816 const auto *array{UnwrapConstantValue<T>(args[0])};
817 const auto *vector{UnwrapConstantValue<T>(args[2])};
818 auto convertedMask{Fold(context_,
819 ConvertToType<LogicalResult>(
820 Expr<SomeLogical>{DEREF(UnwrapExpr<Expr<SomeLogical>>(args[1]))}))};
821 const auto *mask{UnwrapConstantValue<LogicalResult>(convertedMask)};
822 if (!array || !mask || (args[2] && !vector)) {
823 return Expr<T>{std::move(funcRef)};
824 }
825 // Arguments are constant.
826 ConstantSubscript arrayElements{GetSize(array->shape())};
827 ConstantSubscript truths{0};
828 ConstantSubscripts maskAt{mask->lbounds()};
829 if (mask->Rank() == 0) {
830 if (mask->At(maskAt).IsTrue()) {
831 truths = arrayElements;
832 }
833 } else if (array->shape() != mask->shape()) {
834 // Error already emitted from intrinsic processing
835 return MakeInvalidIntrinsic(std::move(funcRef));
836 } else {
837 for (ConstantSubscript j{0}; j < arrayElements;
838 ++j, mask->IncrementSubscripts(maskAt)) {
839 if (mask->At(maskAt).IsTrue()) {
840 ++truths;
841 }
842 }
843 }
844 std::vector<Scalar<T>> resultElements;
845 ConstantSubscripts arrayAt{array->lbounds()};
846 ConstantSubscript resultSize{truths};
847 if (vector) {
848 resultSize = vector->shape().at(0);
849 if (resultSize < truths) {
850 context_.messages().Say(
851 "Invalid 'vector=' argument in PACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
852 static_cast<std::intmax_t>(truths),
853 static_cast<std::intmax_t>(resultSize));
854 return MakeInvalidIntrinsic(std::move(funcRef));
855 }
856 }
857 for (ConstantSubscript j{0}; j < truths;) {
858 if (mask->At(maskAt).IsTrue()) {
859 resultElements.push_back(array->At(arrayAt));
860 ++j;
861 }
862 array->IncrementSubscripts(arrayAt);
863 mask->IncrementSubscripts(maskAt);
864 }
865 if (vector) {
866 ConstantSubscripts vectorAt{vector->lbounds()};
867 vectorAt.at(0) += truths;
868 for (ConstantSubscript j{truths}; j < resultSize; ++j) {
869 resultElements.push_back(vector->At(vectorAt));
870 ++vectorAt[0];
871 }
872 }
873 return Expr<T>{PackageConstant<T>(std::move(resultElements), *array,
874 ConstantSubscripts{static_cast<ConstantSubscript>(resultSize)})};
875 }
876
877 template <typename T> Expr<T> Folder<T>::RESHAPE(FunctionRef<T> &&funcRef) {
878 auto args{funcRef.arguments()};
879 CHECK(args.size() == 4);
880 const auto *source{UnwrapConstantValue<T>(args[0])};
881 const auto *pad{UnwrapConstantValue<T>(args[2])};
882 std::optional<std::vector<ConstantSubscript>> shape{
883 GetIntegerVector<ConstantSubscript>(args[1])};
884 std::optional<std::vector<int>> order{GetIntegerVector<int>(args[3])};
885 if (!source || !shape || (args[2] && !pad) || (args[3] && !order)) {
886 return Expr<T>{std::move(funcRef)}; // Non-constant arguments
887 } else if (shape.value().size() > common::maxRank) {
888 context_.messages().Say(
889 "Size of 'shape=' argument must not be greater than %d"_err_en_US,
890 common::maxRank);
891 } else if (HasNegativeExtent(shape.value())) {
892 context_.messages().Say(
893 "'shape=' argument must not have a negative extent"_err_en_US);
894 } else {
895 std::optional<uint64_t> optResultElement{TotalElementCount(shape.value())};
896 if (!optResultElement) {
897 context_.messages().Say(
898 "'shape=' argument has too many elements"_err_en_US);
899 } else {
900 int rank{GetRank(shape.value())};
901 uint64_t resultElements{*optResultElement};
902 std::optional<std::vector<int>> dimOrder;
903 if (order) {
904 dimOrder = ValidateDimensionOrder(rank, *order);
905 }
906 std::vector<int> *dimOrderPtr{dimOrder ? &dimOrder.value() : nullptr};
907 if (order && !dimOrder) {
908 context_.messages().Say(
909 "Invalid 'order=' argument in RESHAPE"_err_en_US);
910 } else if (resultElements > source->size() && (!pad || pad->empty())) {
911 context_.messages().Say(
912 "Too few elements in 'source=' argument and 'pad=' "
913 "argument is not present or has null size"_err_en_US);
914 } else {
915 Constant<T> result{!source->empty() || !pad
916 ? source->Reshape(std::move(shape.value()))
917 : pad->Reshape(std::move(shape.value()))};
918 ConstantSubscripts subscripts{result.lbounds()};
919 auto copied{result.CopyFrom(*source,
920 std::min(static_cast<uint64_t>(source->size()), resultElements),
921 subscripts, dimOrderPtr)};
922 if (copied < resultElements) {
923 CHECK(pad);
924 copied += result.CopyFrom(
925 *pad, resultElements - copied, subscripts, dimOrderPtr);
926 }
927 CHECK(copied == resultElements);
928 return Expr<T>{std::move(result)};
929 }
930 }
931 }
932 // Invalid, prevent re-folding
933 return MakeInvalidIntrinsic(std::move(funcRef));
934 }
935
936 template <typename T> Expr<T> Folder<T>::SPREAD(FunctionRef<T> &&funcRef) {
937 auto args{funcRef.arguments()};
938 CHECK(args.size() == 3);
939 const Constant<T> *source{UnwrapConstantValue<T>(args[0])};
940 auto dim{ToInt64(args[1])};
941 auto ncopies{ToInt64(args[2])};
942 if (!source || !dim) {
943 return Expr<T>{std::move(funcRef)};
944 }
945 int sourceRank{source->Rank()};
946 if (sourceRank >= common::maxRank) {
947 context_.messages().Say(
948 "SOURCE= argument to SPREAD has rank %d but must have rank less than %d"_err_en_US,
949 sourceRank, common::maxRank);
950 } else if (*dim < 1 || *dim > sourceRank + 1) {
951 context_.messages().Say(
952 "DIM=%d argument to SPREAD must be between 1 and %d"_err_en_US, *dim,
953 sourceRank + 1);
954 } else if (!ncopies) {
955 return Expr<T>{std::move(funcRef)};
956 } else {
957 if (*ncopies < 0) {
958 ncopies = 0;
959 }
960 // TODO: Consider moving this implementation (after the user error
961 // checks), along with other transformational intrinsics, into
962 // constant.h (or a new header) so that the transformationals
963 // are available for all Constant<>s without needing to be packaged
964 // as references to intrinsic functions for folding.
965 ConstantSubscripts shape{source->shape()};
966 shape.insert(shape.begin() + *dim - 1, *ncopies);
967 Constant<T> spread{source->Reshape(std::move(shape))};
968 std::optional<uint64_t> n{TotalElementCount(spread.shape())};
969 if (!n) {
970 context_.messages().Say("Too many elements in SPREAD result"_err_en_US);
971 } else {
972 std::vector<int> dimOrder;
973 for (int j{0}; j < sourceRank; ++j) {
974 dimOrder.push_back(j < *dim - 1 ? j : j + 1);
975 }
976 dimOrder.push_back(*dim - 1);
977 ConstantSubscripts at{spread.lbounds()}; // all 1
978 spread.CopyFrom(*source, *n, at, &dimOrder);
979 return Expr<T>{std::move(spread)};
980 }
981 }
982 // Invalid, prevent re-folding
983 return MakeInvalidIntrinsic(std::move(funcRef));
984 }
985
986 template <typename T> Expr<T> Folder<T>::TRANSPOSE(FunctionRef<T> &&funcRef) {
987 auto args{funcRef.arguments()};
988 CHECK(args.size() == 1);
989 const auto *matrix{UnwrapConstantValue<T>(args[0])};
990 if (!matrix) {
991 return Expr<T>{std::move(funcRef)};
992 }
993 // Argument is constant. Traverse its elements in transposed order.
994 std::vector<Scalar<T>> resultElements;
995 ConstantSubscripts at(2);
996 for (ConstantSubscript j{0}; j < matrix->shape()[0]; ++j) {
997 at[0] = matrix->lbounds()[0] + j;
998 for (ConstantSubscript k{0}; k < matrix->shape()[1]; ++k) {
999 at[1] = matrix->lbounds()[1] + k;
1000 resultElements.push_back(matrix->At(at));
1001 }
1002 }
1003 at = matrix->shape();
1004 std::swap(at[0], at[1]);
1005 return Expr<T>{PackageConstant<T>(std::move(resultElements), *matrix, at)};
1006 }
1007
1008 template <typename T> Expr<T> Folder<T>::UNPACK(FunctionRef<T> &&funcRef) {
1009 auto args{funcRef.arguments()};
1010 CHECK(args.size() == 3);
1011 const auto *vector{UnwrapConstantValue<T>(args[0])};
1012 auto convertedMask{Fold(context_,
1013 ConvertToType<LogicalResult>(
1014 Expr<SomeLogical>{DEREF(UnwrapExpr<Expr<SomeLogical>>(args[1]))}))};
1015 const auto *mask{UnwrapConstantValue<LogicalResult>(convertedMask)};
1016 const auto *field{UnwrapConstantValue<T>(args[2])};
1017 if (!vector || !mask || !field) {
1018 return Expr<T>{std::move(funcRef)};
1019 }
1020 // Arguments are constant.
1021 if (field->Rank() > 0 && field->shape() != mask->shape()) {
1022 // Error already emitted from intrinsic processing
1023 return MakeInvalidIntrinsic(std::move(funcRef));
1024 }
1025 ConstantSubscript maskElements{GetSize(mask->shape())};
1026 ConstantSubscript truths{0};
1027 ConstantSubscripts maskAt{mask->lbounds()};
1028 for (ConstantSubscript j{0}; j < maskElements;
1029 ++j, mask->IncrementSubscripts(maskAt)) {
1030 if (mask->At(maskAt).IsTrue()) {
1031 ++truths;
1032 }
1033 }
1034 if (truths > GetSize(vector->shape())) {
1035 context_.messages().Say(
1036 "Invalid 'vector=' argument in UNPACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
1037 static_cast<std::intmax_t>(truths),
1038 static_cast<std::intmax_t>(GetSize(vector->shape())));
1039 return MakeInvalidIntrinsic(std::move(funcRef));
1040 }
1041 std::vector<Scalar<T>> resultElements;
1042 ConstantSubscripts vectorAt{vector->lbounds()};
1043 ConstantSubscripts fieldAt{field->lbounds()};
1044 for (ConstantSubscript j{0}; j < maskElements; ++j) {
1045 if (mask->At(maskAt).IsTrue()) {
1046 resultElements.push_back(vector->At(vectorAt));
1047 vector->IncrementSubscripts(vectorAt);
1048 } else {
1049 resultElements.push_back(field->At(fieldAt));
1050 }
1051 mask->IncrementSubscripts(maskAt);
1052 field->IncrementSubscripts(fieldAt);
1053 }
1054 return Expr<T>{
1055 PackageConstant<T>(std::move(resultElements), *vector, mask->shape())};
1056 }
1057
1058 std::optional<Expr<SomeType>> FoldTransfer(
1059 FoldingContext &, const ActualArguments &);
1060
1061 template <typename T> Expr<T> Folder<T>::TRANSFER(FunctionRef<T> &&funcRef) {
1062 if (auto folded{FoldTransfer(context_, funcRef.arguments())}) {
1063 return DEREF(UnwrapExpr<Expr<T>>(*folded));
1064 } else {
1065 return Expr<T>{std::move(funcRef)};
1066 }
1067 }
1068
1069 template <typename T>
1070 Expr<T> FoldMINorMAX(
1071 FoldingContext &context, FunctionRef<T> &&funcRef, Ordering order) {
1072 static_assert(T::category == TypeCategory::Integer ||
1073 T::category == TypeCategory::Real ||
1074 T::category == TypeCategory::Character);
1075 std::vector<Constant<T> *> constantArgs;
1076 // Call Folding on all arguments, even if some are not constant,
1077 // to make operand promotion explicit.
1078 for (auto &arg : funcRef.arguments()) {
1079 if (auto *cst{Folder<T>{context}.Folding(arg)}) {
1080 constantArgs.push_back(cst);
1081 }
1082 }
1083 if (constantArgs.size() != funcRef.arguments().size()) {
1084 return Expr<T>(std::move(funcRef));
1085 }
1086 CHECK(!constantArgs.empty());
1087 Expr<T> result{std::move(*constantArgs[0])};
1088 for (std::size_t i{1}; i < constantArgs.size(); ++i) {
1089 Extremum<T> extremum{order, result, Expr<T>{std::move(*constantArgs[i])}};
1090 result = FoldOperation(context, std::move(extremum));
1091 }
1092 return result;
1093 }
1094
1095 // For AMAX0, AMIN0, AMAX1, AMIN1, DMAX1, DMIN1, MAX0, MIN0, MAX1, and MIN1
1096 // a special care has to be taken to insert the conversion on the result
1097 // of the MIN/MAX. This is made slightly more complex by the extension
1098 // supported by f18 that arguments may have different kinds. This implies
1099 // that the created MIN/MAX result type cannot be deduced from the standard but
1100 // has to be deduced from the arguments.
1101 // e.g. AMAX0(int8, int4) is rewritten to REAL(MAX(int8, INT(int4, 8)))).
1102 template <typename T>
1103 Expr<T> RewriteSpecificMINorMAX(
1104 FoldingContext &context, FunctionRef<T> &&funcRef) {
1105 ActualArguments &args{funcRef.arguments()};
1106 auto &intrinsic{DEREF(std::get_if<SpecificIntrinsic>(&funcRef.proc().u))};
1107 // Rewrite MAX1(args) to INT(MAX(args)) and fold. Same logic for MIN1.
1108 // Find result type for max/min based on the arguments.
1109 std::optional<DynamicType> resultType;
1110 ActualArgument *resultTypeArg{nullptr};
1111 for (auto j{args.size()}; j-- > 0;) {
1112 if (args[j]) {
1113 DynamicType type{args[j]->GetType().value()};
1114 // Handle mixed real/integer arguments: all the previous arguments were
1115 // integers and this one is real. The type of the MAX/MIN result will
1116 // be the one of the real argument.
1117 if (!resultType ||
1118 (type.category() == resultType->category() &&
1119 type.kind() > resultType->kind()) ||
1120 resultType->category() == TypeCategory::Integer) {
1121 resultType = type;
1122 resultTypeArg = &*args[j];
1123 }
1124 }
1125 }
1126 if (!resultType) { // error recovery
1127 return Expr<T>{std::move(funcRef)};
1128 }
1129 intrinsic.name =
1130 intrinsic.name.find("max") != std::string::npos ? "max"s : "min"s;
1131 intrinsic.characteristics.value().functionResult.value().SetType(*resultType);
1132 auto insertConversion{[&](const auto &x) -> Expr<T> {
1133 using TR = ResultType<decltype(x)>;
1134 FunctionRef<TR> maxRef{
1135 ProcedureDesignator{funcRef.proc()}, ActualArguments{args}};
1136 return Fold(context, ConvertToType<T>(AsCategoryExpr(std::move(maxRef))));
1137 }};
1138 if (auto *sx{UnwrapExpr<Expr<SomeReal>>(*resultTypeArg)}) {
1139 return common::visit(insertConversion, sx->u);
1140 } else if (auto *sx{UnwrapExpr<Expr<SomeInteger>>(*resultTypeArg)}) {
1141 return common::visit(insertConversion, sx->u);
1142 } else {
1143 return Expr<T>{std::move(funcRef)}; // error recovery
1144 }
1145 }
1146
1147 // FoldIntrinsicFunction()
1148 template <int KIND>
1149 Expr<Type<TypeCategory::Integer, KIND>> FoldIntrinsicFunction(
1150 FoldingContext &context, FunctionRef<Type<TypeCategory::Integer, KIND>> &&);
1151 template <int KIND>
1152 Expr<Type<TypeCategory::Real, KIND>> FoldIntrinsicFunction(
1153 FoldingContext &context, FunctionRef<Type<TypeCategory::Real, KIND>> &&);
1154 template <int KIND>
1155 Expr<Type<TypeCategory::Complex, KIND>> FoldIntrinsicFunction(
1156 FoldingContext &context, FunctionRef<Type<TypeCategory::Complex, KIND>> &&);
1157 template <int KIND>
1158 Expr<Type<TypeCategory::Logical, KIND>> FoldIntrinsicFunction(
1159 FoldingContext &context, FunctionRef<Type<TypeCategory::Logical, KIND>> &&);
1160
1161 template <typename T>
1162 Expr<T> FoldOperation(FoldingContext &context, FunctionRef<T> &&funcRef) {
1163 ActualArguments &args{funcRef.arguments()};
1164 const auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
1165 if (!intrinsic || intrinsic->name != "kind") {
1166 // Don't fold the argument to KIND(); it might be a TypeParamInquiry
1167 // with a forced result type that doesn't match the parameter.
1168 for (std::optional<ActualArgument> &arg : args) {
1169 if (auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
1170 *expr = Fold(context, std::move(*expr));
1171 }
1172 }
1173 }
1174 if (intrinsic) {
1175 const std::string name{intrinsic->name};
1176 if (name == "cshift") {
1177 return Folder<T>{context}.CSHIFT(std::move(funcRef));
1178 } else if (name == "eoshift") {
1179 return Folder<T>{context}.EOSHIFT(std::move(funcRef));
1180 } else if (name == "merge") {
1181 return Folder<T>{context}.MERGE(std::move(funcRef));
1182 } else if (name == "pack") {
1183 return Folder<T>{context}.PACK(std::move(funcRef));
1184 } else if (name == "reshape") {
1185 return Folder<T>{context}.RESHAPE(std::move(funcRef));
1186 } else if (name == "spread") {
1187 return Folder<T>{context}.SPREAD(std::move(funcRef));
1188 } else if (name == "transfer") {
1189 return Folder<T>{context}.TRANSFER(std::move(funcRef));
1190 } else if (name == "transpose") {
1191 return Folder<T>{context}.TRANSPOSE(std::move(funcRef));
1192 } else if (name == "unpack") {
1193 return Folder<T>{context}.UNPACK(std::move(funcRef));
1194 }
1195 // TODO: extends_type_of, same_type_as
1196 if constexpr (!std::is_same_v<T, SomeDerived>) {
1197 return FoldIntrinsicFunction(context, std::move(funcRef));
1198 }
1199 }
1200 return Expr<T>{std::move(funcRef)};
1201 }
1202
1203 Expr<ImpliedDoIndex::Result> FoldOperation(FoldingContext &, ImpliedDoIndex &&);
1204
1205 // Array constructor folding
1206 template <typename T> class ArrayConstructorFolder {
1207 public:
1208 explicit ArrayConstructorFolder(FoldingContext &c) : context_{c} {}
1209
1210 Expr<T> FoldArray(ArrayConstructor<T> &&array) {
1211 // Calls FoldArray(const ArrayConstructorValues<T> &) below
1212 if (FoldArray(array)) {
1213 auto n{static_cast<ConstantSubscript>(elements_.size())};
1214 if constexpr (std::is_same_v<T, SomeDerived>) {
1215 return Expr<T>{Constant<T>{array.GetType().GetDerivedTypeSpec(),
1216 std::move(elements_), ConstantSubscripts{n}}};
1217 } else if constexpr (T::category == TypeCategory::Character) {
1218 if (const auto *len{array.LEN()}) {
1219 auto length{Fold(context_, common::Clone(*len))};
1220 if (std::optional<ConstantSubscript> lengthValue{ToInt64(length)}) {
1221 return Expr<T>{Constant<T>{
1222 *lengthValue, std::move(elements_), ConstantSubscripts{n}}};
1223 }
1224 }
1225 } else {
1226 return Expr<T>{
1227 Constant<T>{std::move(elements_), ConstantSubscripts{n}}};
1228 }
1229 }
1230 return Expr<T>{std::move(array)};
1231 }
1232
1233 private:
1234 bool FoldArray(const Expr<T> &expr) {
1235 Expr<T> folded{Fold(context_, common::Clone(expr))};
1236 if (const auto *c{UnwrapConstantValue<T>(folded)}) {
1237 // Copy elements in Fortran array element order
1238 if (!c->empty()) {
1239 ConstantSubscripts index{c->lbounds()};
1240 do {
1241 elements_.emplace_back(c->At(index));
1242 } while (c->IncrementSubscripts(index));
1243 }
1244 return true;
1245 } else {
1246 return false;
1247 }
1248 }
1249 bool FoldArray(const common::CopyableIndirection<Expr<T>> &expr) {
1250 return FoldArray(expr.value());
1251 }
1252 bool FoldArray(const ImpliedDo<T> &iDo) {
1253 Expr<SubscriptInteger> lower{
1254 Fold(context_, Expr<SubscriptInteger>{iDo.lower()})};
1255 Expr<SubscriptInteger> upper{
1256 Fold(context_, Expr<SubscriptInteger>{iDo.upper()})};
1257 Expr<SubscriptInteger> stride{
1258 Fold(context_, Expr<SubscriptInteger>{iDo.stride()})};
1259 std::optional<ConstantSubscript> start{ToInt64(lower)}, end{ToInt64(upper)},
1260 step{ToInt64(stride)};
1261 if (start && end && step && *step != 0) {
1262 bool result{true};
1263 ConstantSubscript &j{context_.StartImpliedDo(iDo.name(), *start)};
1264 if (*step > 0) {
1265 for (; j <= *end; j += *step) {
1266 result &= FoldArray(iDo.values());
1267 }
1268 } else {
1269 for (; j >= *end; j += *step) {
1270 result &= FoldArray(iDo.values());
1271 }
1272 }
1273 context_.EndImpliedDo(iDo.name());
1274 return result;
1275 } else {
1276 return false;
1277 }
1278 }
1279 bool FoldArray(const ArrayConstructorValue<T> &x) {
1280 return common::visit([&](const auto &y) { return FoldArray(y); }, x.u);
1281 }
1282 bool FoldArray(const ArrayConstructorValues<T> &xs) {
1283 for (const auto &x : xs) {
1284 if (!FoldArray(x)) {
1285 return false;
1286 }
1287 }
1288 return true;
1289 }
1290
1291 FoldingContext &context_;
1292 std::vector<Scalar<T>> elements_;
1293 };
1294
1295 template <typename T>
1296 Expr<T> FoldOperation(FoldingContext &context, ArrayConstructor<T> &&array) {
1297 return ArrayConstructorFolder<T>{context}.FoldArray(std::move(array));
1298 }
1299
1300 // Array operation elemental application: When all operands to an operation
1301 // are constant arrays, array constructors without any implied DO loops,
1302 // &/or expanded scalars, pull the operation "into" the array result by
1303 // applying it in an elementwise fashion. For example, [A,1]+[B,2]
1304 // is rewritten into [A+B,1+2] and then partially folded to [A+B,3].
1305
1306 // If possible, restructures an array expression into an array constructor
1307 // that comprises a "flat" ArrayConstructorValues with no implied DO loops.
1308 template <typename T>
1309 bool ArrayConstructorIsFlat(const ArrayConstructorValues<T> &values) {
1310 for (const ArrayConstructorValue<T> &x : values) {
1311 if (!std::holds_alternative<Expr<T>>(x.u)) {
1312 return false;
1313 }
1314 }
1315 return true;
1316 }
1317
1318 template <typename T>
1319 std::optional<Expr<T>> AsFlatArrayConstructor(const Expr<T> &expr) {
1320 if (const auto *c{UnwrapConstantValue<T>(expr)}) {
1321 ArrayConstructor<T> result{expr};
1322 if (!c->empty()) {
1323 ConstantSubscripts at{c->lbounds()};
1324 do {
1325 result.Push(Expr<T>{Constant<T>{c->At(at)}});
1326 } while (c->IncrementSubscripts(at));
1327 }
1328 return std::make_optional<Expr<T>>(std::move(result));
1329 } else if (const auto *a{UnwrapExpr<ArrayConstructor<T>>(expr)}) {
1330 if (ArrayConstructorIsFlat(*a)) {
1331 return std::make_optional<Expr<T>>(expr);
1332 }
1333 } else if (const auto *p{UnwrapExpr<Parentheses<T>>(expr)}) {
1334 return AsFlatArrayConstructor(Expr<T>{p->left()});
1335 }
1336 return std::nullopt;
1337 }
1338
1339 template <TypeCategory CAT>
1340 std::enable_if_t<CAT != TypeCategory::Derived,
1341 std::optional<Expr<SomeKind<CAT>>>>
1342 AsFlatArrayConstructor(const Expr<SomeKind<CAT>> &expr) {
1343 return common::visit(
1344 [&](const auto &kindExpr) -> std::optional<Expr<SomeKind<CAT>>> {
1345 if (auto flattened{AsFlatArrayConstructor(kindExpr)}) {
1346 return Expr<SomeKind<CAT>>{std::move(*flattened)};
1347 } else {
1348 return std::nullopt;
1349 }
1350 },
1351 expr.u);
1352 }
1353
1354 // FromArrayConstructor is a subroutine for MapOperation() below.
1355 // Given a flat ArrayConstructor<T> and a shape, it wraps the array
1356 // into an Expr<T>, folds it, and returns the resulting wrapped
1357 // array constructor or constant array value.
1358 template <typename T>
1359 std::optional<Expr<T>> FromArrayConstructor(
1360 FoldingContext &context, ArrayConstructor<T> &&values, const Shape &shape) {
1361 if (auto constShape{AsConstantExtents(context, shape)}) {
1362 Expr<T> result{Fold(context, Expr<T>{std::move(values)})};
1363 if (auto *constant{UnwrapConstantValue<T>(result)}) {
1364 // Elements and shape are both constant.
1365 return Expr<T>{constant->Reshape(std::move(*constShape))};
1366 }
1367 if (constShape->size() == 1) {
1368 if (auto elements{GetShape(context, result)}) {
1369 if (auto constElements{AsConstantExtents(context, *elements)}) {
1370 if (constElements->size() == 1 &&
1371 constElements->at(0) == constShape->at(0)) {
1372 // Elements are not constant, but array constructor has
1373 // the right known shape and can be simply returned as is.
1374 return std::move(result);
1375 }
1376 }
1377 }
1378 }
1379 }
1380 return std::nullopt;
1381 }
1382
1383 // MapOperation is a utility for various specializations of ApplyElementwise()
1384 // that follow. Given one or two flat ArrayConstructor<OPERAND> (wrapped in an
1385 // Expr<OPERAND>) for some specific operand type(s), apply a given function f
1386 // to each of their corresponding elements to produce a flat
1387 // ArrayConstructor<RESULT> (wrapped in an Expr<RESULT>).
1388 // Preserves shape.
1389
1390 // Unary case
1391 template <typename RESULT, typename OPERAND>
1392 std::optional<Expr<RESULT>> MapOperation(FoldingContext &context,
1393 std::function<Expr<RESULT>(Expr<OPERAND> &&)> &&f, const Shape &shape,
1394 [[maybe_unused]] std::optional<Expr<SubscriptInteger>> &&length,
1395 Expr<OPERAND> &&values) {
1396 ArrayConstructor<RESULT> result{values};
1397 if constexpr (common::HasMember<OPERAND, AllIntrinsicCategoryTypes>) {
1398 common::visit(
1399 [&](auto &&kindExpr) {
1400 using kindType = ResultType<decltype(kindExpr)>;
1401 auto &aConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1402 for (auto &acValue : aConst) {
1403 auto &scalar{std::get<Expr<kindType>>(acValue.u)};
1404 result.Push(Fold(context, f(Expr<OPERAND>{std::move(scalar)})));
1405 }
1406 },
1407 std::move(values.u));
1408 } else {
1409 auto &aConst{std::get<ArrayConstructor<OPERAND>>(values.u)};
1410 for (auto &acValue : aConst) {
1411 auto &scalar{std::get<Expr<OPERAND>>(acValue.u)};
1412 result.Push(Fold(context, f(std::move(scalar))));
1413 }
1414 }
1415 if constexpr (RESULT::category == TypeCategory::Character) {
1416 if (length) {
1417 result.set_LEN(std::move(*length));
1418 }
1419 }
1420 return FromArrayConstructor(context, std::move(result), shape);
1421 }
1422
1423 template <typename RESULT, typename A>
1424 ArrayConstructor<RESULT> ArrayConstructorFromMold(
1425 const A &prototype, std::optional<Expr<SubscriptInteger>> &&length) {
1426 ArrayConstructor<RESULT> result{prototype};
1427 if constexpr (RESULT::category == TypeCategory::Character) {
1428 if (length) {
1429 result.set_LEN(std::move(*length));
1430 }
1431 }
1432 return result;
1433 }
1434
1435 template <typename LEFT, typename RIGHT>
1436 bool ShapesMatch(FoldingContext &context,
1437 const ArrayConstructor<LEFT> &leftArrConst,
1438 const ArrayConstructor<RIGHT> &rightArrConst) {
1439 auto rightIter{rightArrConst.begin()};
1440 for (auto &leftValue : leftArrConst) {
1441 CHECK(rightIter != rightArrConst.end());
1442 auto &leftExpr{std::get<Expr<LEFT>>(leftValue.u)};
1443 auto &rightExpr{std::get<Expr<RIGHT>>(rightIter->u)};
1444 if (leftExpr.Rank() != rightExpr.Rank()) {
1445 return false;
1446 }
1447 std::optional<Shape> leftShape{GetShape(context, leftExpr)};
1448 std::optional<Shape> rightShape{GetShape(context, rightExpr)};
1449 if (!leftShape || !rightShape || *leftShape != *rightShape) {
1450 return false;
1451 }
1452 ++rightIter;
1453 }
1454 return true;
1455 }
1456
1457 // array * array case
1458 template <typename RESULT, typename LEFT, typename RIGHT>
1459 auto MapOperation(FoldingContext &context,
1460 std::function<Expr<RESULT>(Expr<LEFT> &&, Expr<RIGHT> &&)> &&f,
1461 const Shape &shape, std::optional<Expr<SubscriptInteger>> &&length,
1462 Expr<LEFT> &&leftValues, Expr<RIGHT> &&rightValues)
1463 -> std::optional<Expr<RESULT>> {
1464 auto result{ArrayConstructorFromMold<RESULT>(leftValues, std::move(length))};
1465 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1466 if constexpr (common::HasMember<RIGHT, AllIntrinsicCategoryTypes>) {
1467 bool mapped{common::visit(
1468 [&](auto &&kindExpr) -> bool {
1469 using kindType = ResultType<decltype(kindExpr)>;
1470
1471 auto &rightArrConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1472 if (!ShapesMatch(context, leftArrConst, rightArrConst)) {
1473 return false;
1474 }
1475 auto rightIter{rightArrConst.begin()};
1476 for (auto &leftValue : leftArrConst) {
1477 CHECK(rightIter != rightArrConst.end());
1478 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1479 auto &rightScalar{std::get<Expr<kindType>>(rightIter->u)};
1480 result.Push(Fold(context,
1481 f(std::move(leftScalar), Expr<RIGHT>{std::move(rightScalar)})));
1482 ++rightIter;
1483 }
1484 return true;
1485 },
1486 std::move(rightValues.u))};
1487 if (!mapped) {
1488 return std::nullopt;
1489 }
1490 } else {
1491 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1492 if (!ShapesMatch(context, leftArrConst, rightArrConst)) {
1493 return std::nullopt;
1494 }
1495 auto rightIter{rightArrConst.begin()};
1496 for (auto &leftValue : leftArrConst) {
1497 CHECK(rightIter != rightArrConst.end());
1498 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1499 auto &rightScalar{std::get<Expr<RIGHT>>(rightIter->u)};
1500 result.Push(
1501 Fold(context, f(std::move(leftScalar), std::move(rightScalar))));
1502 ++rightIter;
1503 }
1504 }
1505 return FromArrayConstructor(context, std::move(result), shape);
1506 }
1507
1508 // array * scalar case
1509 template <typename RESULT, typename LEFT, typename RIGHT>
1510 auto MapOperation(FoldingContext &context,
1511 std::function<Expr<RESULT>(Expr<LEFT> &&, Expr<RIGHT> &&)> &&f,
1512 const Shape &shape, std::optional<Expr<SubscriptInteger>> &&length,
1513 Expr<LEFT> &&leftValues, const Expr<RIGHT> &rightScalar)
1514 -> std::optional<Expr<RESULT>> {
1515 auto result{ArrayConstructorFromMold<RESULT>(leftValues, std::move(length))};
1516 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1517 for (auto &leftValue : leftArrConst) {
1518 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1519 result.Push(
1520 Fold(context, f(std::move(leftScalar), Expr<RIGHT>{rightScalar})));
1521 }
1522 return FromArrayConstructor(context, std::move(result), shape);
1523 }
1524
1525 // scalar * array case
1526 template <typename RESULT, typename LEFT, typename RIGHT>
1527 auto MapOperation(FoldingContext &context,
1528 std::function<Expr<RESULT>(Expr<LEFT> &&, Expr<RIGHT> &&)> &&f,
1529 const Shape &shape, std::optional<Expr<SubscriptInteger>> &&length,
1530 const Expr<LEFT> &leftScalar, Expr<RIGHT> &&rightValues)
1531 -> std::optional<Expr<RESULT>> {
1532 auto result{ArrayConstructorFromMold<RESULT>(leftScalar, std::move(length))};
1533 if constexpr (common::HasMember<RIGHT, AllIntrinsicCategoryTypes>) {
1534 common::visit(
1535 [&](auto &&kindExpr) {
1536 using kindType = ResultType<decltype(kindExpr)>;
1537 auto &rightArrConst{std::get<ArrayConstructor<kindType>>(kindExpr.u)};
1538 for (auto &rightValue : rightArrConst) {
1539 auto &rightScalar{std::get<Expr<kindType>>(rightValue.u)};
1540 result.Push(Fold(context,
1541 f(Expr<LEFT>{leftScalar},
1542 Expr<RIGHT>{std::move(rightScalar)})));
1543 }
1544 },
1545 std::move(rightValues.u));
1546 } else {
1547 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1548 for (auto &rightValue : rightArrConst) {
1549 auto &rightScalar{std::get<Expr<RIGHT>>(rightValue.u)};
1550 result.Push(
1551 Fold(context, f(Expr<LEFT>{leftScalar}, std::move(rightScalar))));
1552 }
1553 }
1554 return FromArrayConstructor(context, std::move(result), shape);
1555 }
1556
1557 template <typename DERIVED, typename RESULT, typename... OPD>
1558 std::optional<Expr<SubscriptInteger>> ComputeResultLength(
1559 Operation<DERIVED, RESULT, OPD...> &operation) {
1560 if constexpr (RESULT::category == TypeCategory::Character) {
1561 return Expr<RESULT>{operation.derived()}.LEN();
1562 }
1563 return std::nullopt;
1564 }
1565
1566 // ApplyElementwise() recursively folds the operand expression(s) of an
1567 // operation, then attempts to apply the operation to the (corresponding)
1568 // scalar element(s) of those operands. Returns std::nullopt for scalars
1569 // or unlinearizable operands.
1570 template <typename DERIVED, typename RESULT, typename OPERAND>
1571 auto ApplyElementwise(FoldingContext &context,
1572 Operation<DERIVED, RESULT, OPERAND> &operation,
1573 std::function<Expr<RESULT>(Expr<OPERAND> &&)> &&f)
1574 -> std::optional<Expr<RESULT>> {
1575 auto &expr{operation.left()};
1576 expr = Fold(context, std::move(expr));
1577 if (expr.Rank() > 0) {
1578 if (std::optional<Shape> shape{GetShape(context, expr)}) {
1579 if (auto values{AsFlatArrayConstructor(expr)}) {
1580 return MapOperation(context, std::move(f), *shape,
1581 ComputeResultLength(operation), std::move(*values));
1582 }
1583 }
1584 }
1585 return std::nullopt;
1586 }
1587
1588 template <typename DERIVED, typename RESULT, typename OPERAND>
1589 auto ApplyElementwise(
1590 FoldingContext &context, Operation<DERIVED, RESULT, OPERAND> &operation)
1591 -> std::optional<Expr<RESULT>> {
1592 return ApplyElementwise(context, operation,
1593 std::function<Expr<RESULT>(Expr<OPERAND> &&)>{
1594 [](Expr<OPERAND> &&operand) {
1595 return Expr<RESULT>{DERIVED{std::move(operand)}};
1596 }});
1597 }
1598
1599 template <typename DERIVED, typename RESULT, typename LEFT, typename RIGHT>
1600 auto ApplyElementwise(FoldingContext &context,
1601 Operation<DERIVED, RESULT, LEFT, RIGHT> &operation,
1602 std::function<Expr<RESULT>(Expr<LEFT> &&, Expr<RIGHT> &&)> &&f)
1603 -> std::optional<Expr<RESULT>> {
1604 auto resultLength{ComputeResultLength(operation)};
1605 auto &leftExpr{operation.left()};
1606 leftExpr = Fold(context, std::move(leftExpr));
1607 auto &rightExpr{operation.right()};
1608 rightExpr = Fold(context, std::move(rightExpr));
1609 if (leftExpr.Rank() > 0) {
1610 if (std::optional<Shape> leftShape{GetShape(context, leftExpr)}) {
1611 if (auto left{AsFlatArrayConstructor(leftExpr)}) {
1612 if (rightExpr.Rank() > 0) {
1613 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1614 if (auto right{AsFlatArrayConstructor(rightExpr)}) {
1615 if (CheckConformance(context.messages(), *leftShape, *rightShape,
1616 CheckConformanceFlags::EitherScalarExpandable)
1617 .value_or(false /*fail if not known now to conform*/)) {
1618 return MapOperation(context, std::move(f), *leftShape,
1619 std::move(resultLength), std::move(*left),
1620 std::move(*right));
1621 } else {
1622 return std::nullopt;
1623 }
1624 return MapOperation(context, std::move(f), *leftShape,
1625 std::move(resultLength), std::move(*left), std::move(*right));
1626 }
1627 }
1628 } else if (IsExpandableScalar(rightExpr, context, *leftShape)) {
1629 return MapOperation(context, std::move(f), *leftShape,
1630 std::move(resultLength), std::move(*left), rightExpr);
1631 }
1632 }
1633 }
1634 } else if (rightExpr.Rank() > 0) {
1635 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1636 if (IsExpandableScalar(leftExpr, context, *rightShape)) {
1637 if (auto right{AsFlatArrayConstructor(rightExpr)}) {
1638 return MapOperation(context, std::move(f), *rightShape,
1639 std::move(resultLength), leftExpr, std::move(*right));
1640 }
1641 }
1642 }
1643 }
1644 return std::nullopt;
1645 }
1646
1647 template <typename DERIVED, typename RESULT, typename LEFT, typename RIGHT>
1648 auto ApplyElementwise(
1649 FoldingContext &context, Operation<DERIVED, RESULT, LEFT, RIGHT> &operation)
1650 -> std::optional<Expr<RESULT>> {
1651 return ApplyElementwise(context, operation,
1652 std::function<Expr<RESULT>(Expr<LEFT> &&, Expr<RIGHT> &&)>{
1653 [](Expr<LEFT> &&left, Expr<RIGHT> &&right) {
1654 return Expr<RESULT>{DERIVED{std::move(left), std::move(right)}};
1655 }});
1656 }
1657
1658 // Unary operations
1659
1660 template <typename TO, typename FROM>
1661 common::IfNoLvalue<std::optional<TO>, FROM> ConvertString(FROM &&s) {
1662 if constexpr (std::is_same_v<TO, FROM>) {
1663 return std::make_optional<TO>(std::move(s));
1664 } else {
1665 // Fortran character conversion is well defined between distinct kinds
1666 // only when the actual characters are valid 7-bit ASCII.
1667 TO str;
1668 for (auto iter{s.cbegin()}; iter != s.cend(); ++iter) {
1669 if (static_cast<std::uint64_t>(*iter) > 127) {
1670 return std::nullopt;
1671 }
1672 str.push_back(*iter);
1673 }
1674 return std::make_optional<TO>(std::move(str));
1675 }
1676 }
1677
1678 template <typename TO, TypeCategory FROMCAT>
1679 Expr<TO> FoldOperation(
1680 FoldingContext &context, Convert<TO, FROMCAT> &&convert) {
1681 if (auto array{ApplyElementwise(context, convert)}) {
1682 return *array;
1683 }
1684 struct {
1685 FoldingContext &context;
1686 Convert<TO, FROMCAT> &convert;
1687 } msvcWorkaround{context, convert};
1688 return common::visit(
1689 [&msvcWorkaround](auto &kindExpr) -> Expr<TO> {
1690 using Operand = ResultType<decltype(kindExpr)>;
1691 // This variable is a workaround for msvc which emits an error when
1692 // using the FROMCAT template parameter below.
1693 TypeCategory constexpr FromCat{FROMCAT};
1694 static_assert(FromCat == Operand::category);
1695 auto &convert{msvcWorkaround.convert};
1696 if (auto value{GetScalarConstantValue<Operand>(kindExpr)}) {
1697 FoldingContext &ctx{msvcWorkaround.context};
1698 if constexpr (TO::category == TypeCategory::Integer) {
1699 if constexpr (FromCat == TypeCategory::Integer) {
1700 auto converted{Scalar<TO>::ConvertSigned(*value)};
1701 if (converted.overflow &&
1702 msvcWorkaround.context.languageFeatures().ShouldWarn(
1703 common::UsageWarning::FoldingException)) {
1704 ctx.messages().Say(
1705 "INTEGER(%d) to INTEGER(%d) conversion overflowed"_warn_en_US,
1706 Operand::kind, TO::kind);
1707 }
1708 return ScalarConstantToExpr(std::move(converted.value));
1709 } else if constexpr (FromCat == TypeCategory::Real) {
1710 auto converted{value->template ToInteger<Scalar<TO>>()};
1711 if (msvcWorkaround.context.languageFeatures().ShouldWarn(
1712 common::UsageWarning::FoldingException)) {
1713 if (converted.flags.test(RealFlag::InvalidArgument)) {
1714 ctx.messages().Say(
1715 "REAL(%d) to INTEGER(%d) conversion: invalid argument"_warn_en_US,
1716 Operand::kind, TO::kind);
1717 } else if (converted.flags.test(RealFlag::Overflow)) {
1718 ctx.messages().Say(
1719 "REAL(%d) to INTEGER(%d) conversion overflowed"_warn_en_US,
1720 Operand::kind, TO::kind);
1721 }
1722 }
1723 return ScalarConstantToExpr(std::move(converted.value));
1724 }
1725 } else if constexpr (TO::category == TypeCategory::Real) {
1726 if constexpr (FromCat == TypeCategory::Integer) {
1727 auto converted{Scalar<TO>::FromInteger(*value)};
1728 if (!converted.flags.empty()) {
1729 char buffer[64];
1730 std::snprintf(buffer, sizeof buffer,
1731 "INTEGER(%d) to REAL(%d) conversion", Operand::kind,
1732 TO::kind);
1733 RealFlagWarnings(ctx, converted.flags, buffer);
1734 }
1735 return ScalarConstantToExpr(std::move(converted.value));
1736 } else if constexpr (FromCat == TypeCategory::Real) {
1737 auto converted{Scalar<TO>::Convert(*value)};
1738 char buffer[64];
1739 if (!converted.flags.empty()) {
1740 std::snprintf(buffer, sizeof buffer,
1741 "REAL(%d) to REAL(%d) conversion", Operand::kind, TO::kind);
1742 RealFlagWarnings(ctx, converted.flags, buffer);
1743 }
1744 if (ctx.targetCharacteristics().areSubnormalsFlushedToZero()) {
1745 converted.value = converted.value.FlushSubnormalToZero();
1746 }
1747 return ScalarConstantToExpr(std::move(converted.value));
1748 }
1749 } else if constexpr (TO::category == TypeCategory::Complex) {
1750 if constexpr (FromCat == TypeCategory::Complex) {
1751 return FoldOperation(ctx,
1752 ComplexConstructor<TO::kind>{
1753 AsExpr(Convert<typename TO::Part>{AsCategoryExpr(
1754 Constant<typename Operand::Part>{value->REAL()})}),
1755 AsExpr(Convert<typename TO::Part>{AsCategoryExpr(
1756 Constant<typename Operand::Part>{value->AIMAG()})})});
1757 }
1758 } else if constexpr (TO::category == TypeCategory::Character &&
1759 FromCat == TypeCategory::Character) {
1760 if (auto converted{ConvertString<Scalar<TO>>(std::move(*value))}) {
1761 return ScalarConstantToExpr(std::move(*converted));
1762 }
1763 } else if constexpr (TO::category == TypeCategory::Logical &&
1764 FromCat == TypeCategory::Logical) {
1765 return Expr<TO>{value->IsTrue()};
1766 }
1767 } else if constexpr (TO::category == FromCat &&
1768 FromCat != TypeCategory::Character) {
1769 // Conversion of non-constant in same type category
1770 if constexpr (std::is_same_v<Operand, TO>) {
1771 return std::move(kindExpr); // remove needless conversion
1772 } else if constexpr (TO::category == TypeCategory::Logical ||
1773 TO::category == TypeCategory::Integer) {
1774 if (auto *innerConv{
1775 std::get_if<Convert<Operand, TO::category>>(&kindExpr.u)}) {
1776 // Conversion of conversion of same category & kind
1777 if (auto *x{std::get_if<Expr<TO>>(&innerConv->left().u)}) {
1778 if constexpr (TO::category == TypeCategory::Logical ||
1779 TO::kind <= Operand::kind) {
1780 return std::move(*x); // no-op Logical or Integer
1781 // widening/narrowing conversion pair
1782 } else if constexpr (std::is_same_v<TO,
1783 DescriptorInquiry::Result>) {
1784 if (std::holds_alternative<DescriptorInquiry>(x->u) ||
1785 std::holds_alternative<TypeParamInquiry>(x->u)) {
1786 // int(int(size(...),kind=k),kind=8) -> size(...)
1787 return std::move(*x);
1788 }
1789 }
1790 }
1791 }
1792 }
1793 }
1794 return Expr<TO>{std::move(convert)};
1795 },
1796 convert.left().u);
1797 }
1798
1799 template <typename T>
1800 Expr<T> FoldOperation(FoldingContext &context, Parentheses<T> &&x) {
1801 auto &operand{x.left()};
1802 operand = Fold(context, std::move(operand));
1803 if (auto value{GetScalarConstantValue<T>(operand)}) {
1804 // Preserve parentheses, even around constants.
1805 return Expr<T>{Parentheses<T>{Expr<T>{Constant<T>{*value}}}};
1806 } else if (std::holds_alternative<Parentheses<T>>(operand.u)) {
1807 // ((x)) -> (x)
1808 return std::move(operand);
1809 } else {
1810 return Expr<T>{Parentheses<T>{std::move(operand)}};
1811 }
1812 }
1813
1814 template <typename T>
1815 Expr<T> FoldOperation(FoldingContext &context, Negate<T> &&x) {
1816 if (auto array{ApplyElementwise(context, x)}) {
1817 return *array;
1818 }
1819 auto &operand{x.left()};
1820 if (auto *nn{std::get_if<Negate<T>>(&x.left().u)}) {
1821 // -(-x) -> (x)
1822 if (IsVariable(nn->left())) {
1823 return FoldOperation(context, Parentheses<T>{std::move(nn->left())});
1824 } else {
1825 return std::move(nn->left());
1826 }
1827 } else if (auto value{GetScalarConstantValue<T>(operand)}) {
1828 if constexpr (T::category == TypeCategory::Integer) {
1829 auto negated{value->Negate()};
1830 if (negated.overflow &&
1831 context.languageFeatures().ShouldWarn(
1832 common::UsageWarning::FoldingException)) {
1833 context.messages().Say(
1834 "INTEGER(%d) negation overflowed"_warn_en_US, T::kind);
1835 }
1836 return Expr<T>{Constant<T>{std::move(negated.value)}};
1837 } else {
1838 // REAL & COMPLEX negation: no exceptions possible
1839 return Expr<T>{Constant<T>{value->Negate()}};
1840 }
1841 }
1842 return Expr<T>{std::move(x)};
1843 }
1844
1845 // Binary (dyadic) operations
1846
1847 template <typename LEFT, typename RIGHT>
1848 std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
1849 const Expr<LEFT> &x, const Expr<RIGHT> &y) {
1850 if (auto xvalue{GetScalarConstantValue<LEFT>(x)}) {
1851 if (auto yvalue{GetScalarConstantValue<RIGHT>(y)}) {
1852 return {std::make_pair(*xvalue, *yvalue)};
1853 }
1854 }
1855 return std::nullopt;
1856 }
1857
1858 template <typename DERIVED, typename RESULT, typename LEFT, typename RIGHT>
1859 std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
1860 const Operation<DERIVED, RESULT, LEFT, RIGHT> &operation) {
1861 return OperandsAreConstants(operation.left(), operation.right());
1862 }
1863
1864 template <typename T>
1865 Expr<T> FoldOperation(FoldingContext &context, Add<T> &&x) {
1866 if (auto array{ApplyElementwise(context, x)}) {
1867 return *array;
1868 }
1869 if (auto folded{OperandsAreConstants(x)}) {
1870 if constexpr (T::category == TypeCategory::Integer) {
1871 auto sum{folded->first.AddSigned(folded->second)};
1872 if (sum.overflow &&
1873 context.languageFeatures().ShouldWarn(
1874 common::UsageWarning::FoldingException)) {
1875 context.messages().Say(
1876 "INTEGER(%d) addition overflowed"_warn_en_US, T::kind);
1877 }
1878 return Expr<T>{Constant<T>{sum.value}};
1879 } else {
1880 auto sum{folded->first.Add(
1881 folded->second, context.targetCharacteristics().roundingMode())};
1882 RealFlagWarnings(context, sum.flags, "addition");
1883 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
1884 sum.value = sum.value.FlushSubnormalToZero();
1885 }
1886 return Expr<T>{Constant<T>{sum.value}};
1887 }
1888 }
1889 return Expr<T>{std::move(x)};
1890 }
1891
1892 template <typename T>
1893 Expr<T> FoldOperation(FoldingContext &context, Subtract<T> &&x) {
1894 if (auto array{ApplyElementwise(context, x)}) {
1895 return *array;
1896 }
1897 if (auto folded{OperandsAreConstants(x)}) {
1898 if constexpr (T::category == TypeCategory::Integer) {
1899 auto difference{folded->first.SubtractSigned(folded->second)};
1900 if (difference.overflow &&
1901 context.languageFeatures().ShouldWarn(
1902 common::UsageWarning::FoldingException)) {
1903 context.messages().Say(
1904 "INTEGER(%d) subtraction overflowed"_warn_en_US, T::kind);
1905 }
1906 return Expr<T>{Constant<T>{difference.value}};
1907 } else {
1908 auto difference{folded->first.Subtract(
1909 folded->second, context.targetCharacteristics().roundingMode())};
1910 RealFlagWarnings(context, difference.flags, "subtraction");
1911 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
1912 difference.value = difference.value.FlushSubnormalToZero();
1913 }
1914 return Expr<T>{Constant<T>{difference.value}};
1915 }
1916 }
1917 return Expr<T>{std::move(x)};
1918 }
1919
1920 template <typename T>
1921 Expr<T> FoldOperation(FoldingContext &context, Multiply<T> &&x) {
1922 if (auto array{ApplyElementwise(context, x)}) {
1923 return *array;
1924 }
1925 if (auto folded{OperandsAreConstants(x)}) {
1926 if constexpr (T::category == TypeCategory::Integer) {
1927 auto product{folded->first.MultiplySigned(folded->second)};
1928 if (product.SignedMultiplicationOverflowed() &&
1929 context.languageFeatures().ShouldWarn(
1930 common::UsageWarning::FoldingException)) {
1931 context.messages().Say(
1932 "INTEGER(%d) multiplication overflowed"_warn_en_US, T::kind);
1933 }
1934 return Expr<T>{Constant<T>{product.lower}};
1935 } else {
1936 auto product{folded->first.Multiply(
1937 folded->second, context.targetCharacteristics().roundingMode())};
1938 RealFlagWarnings(context, product.flags, "multiplication");
1939 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
1940 product.value = product.value.FlushSubnormalToZero();
1941 }
1942 return Expr<T>{Constant<T>{product.value}};
1943 }
1944 } else if constexpr (T::category == TypeCategory::Integer) {
1945 if (auto c{GetScalarConstantValue<T>(x.right())}) {
1946 x.right() = std::move(x.left());
1947 x.left() = Expr<T>{std::move(*c)};
1948 }
1949 if (auto c{GetScalarConstantValue<T>(x.left())}) {
1950 if (c->IsZero() && x.right().Rank() == 0) {
1951 return std::move(x.left());
1952 } else if (c->CompareSigned(Scalar<T>{1}) == Ordering::Equal) {
1953 if (IsVariable(x.right())) {
1954 return FoldOperation(context, Parentheses<T>{std::move(x.right())});
1955 } else {
1956 return std::move(x.right());
1957 }
1958 } else if (c->CompareSigned(Scalar<T>{-1}) == Ordering::Equal) {
1959 return FoldOperation(context, Negate<T>{std::move(x.right())});
1960 }
1961 }
1962 }
1963 return Expr<T>{std::move(x)};
1964 }
1965
1966 template <typename T>
1967 Expr<T> FoldOperation(FoldingContext &context, Divide<T> &&x) {
1968 if (auto array{ApplyElementwise(context, x)}) {
1969 return *array;
1970 }
1971 if (auto folded{OperandsAreConstants(x)}) {
1972 if constexpr (T::category == TypeCategory::Integer) {
1973 auto quotAndRem{folded->first.DivideSigned(folded->second)};
1974 if (quotAndRem.divisionByZero) {
1975 if (context.languageFeatures().ShouldWarn(
1976 common::UsageWarning::FoldingException)) {
1977 context.messages().Say(
1978 "INTEGER(%d) division by zero"_warn_en_US, T::kind);
1979 }
1980 return Expr<T>{std::move(x)};
1981 }
1982 if (quotAndRem.overflow &&
1983 context.languageFeatures().ShouldWarn(
1984 common::UsageWarning::FoldingException)) {
1985 context.messages().Say(
1986 "INTEGER(%d) division overflowed"_warn_en_US, T::kind);
1987 }
1988 return Expr<T>{Constant<T>{quotAndRem.quotient}};
1989 } else {
1990 auto quotient{folded->first.Divide(
1991 folded->second, context.targetCharacteristics().roundingMode())};
1992 // Don't warn about -1./0., 0./0., or 1./0. from a module file
1993 // they are interpreted as canonical Fortran representations of -Inf,
1994 // NaN, and Inf respectively.
1995 bool isCanonicalNaNOrInf{false};
1996 if constexpr (T::category == TypeCategory::Real) {
1997 if (folded->second.IsZero() && context.moduleFileName().has_value()) {
1998 using IntType = typename T::Scalar::Word;
1999 auto intNumerator{folded->first.template ToInteger<IntType>()};
2000 isCanonicalNaNOrInf = intNumerator.flags == RealFlags{} &&
2001 intNumerator.value >= IntType{-1} &&
2002 intNumerator.value <= IntType{1};
2003 }
2004 }
2005 if (!isCanonicalNaNOrInf) {
2006 RealFlagWarnings(context, quotient.flags, "division");
2007 }
2008 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2009 quotient.value = quotient.value.FlushSubnormalToZero();
2010 }
2011 return Expr<T>{Constant<T>{quotient.value}};
2012 }
2013 }
2014 return Expr<T>{std::move(x)};
2015 }
2016
2017 template <typename T>
2018 Expr<T> FoldOperation(FoldingContext &context, Power<T> &&x) {
2019 if (auto array{ApplyElementwise(context, x)}) {
2020 return *array;
2021 }
2022 if (auto folded{OperandsAreConstants(x)}) {
2023 if constexpr (T::category == TypeCategory::Integer) {
2024 auto power{folded->first.Power(folded->second)};
2025 if (context.languageFeatures().ShouldWarn(
2026 common::UsageWarning::FoldingException)) {
2027 if (power.divisionByZero) {
2028 context.messages().Say(
2029 "INTEGER(%d) zero to negative power"_warn_en_US, T::kind);
2030 } else if (power.overflow) {
2031 context.messages().Say(
2032 "INTEGER(%d) power overflowed"_warn_en_US, T::kind);
2033 } else if (power.zeroToZero) {
2034 context.messages().Say(
2035 "INTEGER(%d) 0**0 is not defined"_warn_en_US, T::kind);
2036 }
2037 }
2038 return Expr<T>{Constant<T>{power.power}};
2039 } else {
2040 if (auto callable{GetHostRuntimeWrapper<T, T, T>("pow")}) {
2041 return Expr<T>{
2042 Constant<T>{(*callable)(context, folded->first, folded->second)}};
2043 } else if (context.languageFeatures().ShouldWarn(
2044 common::UsageWarning::FoldingFailure)) {
2045 context.messages().Say(
2046 "Power for %s cannot be folded on host"_warn_en_US,
2047 T{}.AsFortran());
2048 }
2049 }
2050 }
2051 return Expr<T>{std::move(x)};
2052 }
2053
2054 template <typename T>
2055 Expr<T> FoldOperation(FoldingContext &context, RealToIntPower<T> &&x) {
2056 if (auto array{ApplyElementwise(context, x)}) {
2057 return *array;
2058 }
2059 return common::visit(
2060 [&](auto &y) -> Expr<T> {
2061 if (auto folded{OperandsAreConstants(x.left(), y)}) {
2062 auto power{evaluate::IntPower(folded->first, folded->second)};
2063 RealFlagWarnings(context, power.flags, "power with INTEGER exponent");
2064 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2065 power.value = power.value.FlushSubnormalToZero();
2066 }
2067 return Expr<T>{Constant<T>{power.value}};
2068 } else {
2069 return Expr<T>{std::move(x)};
2070 }
2071 },
2072 x.right().u);
2073 }
2074
2075 template <typename T>
2076 Expr<T> FoldOperation(FoldingContext &context, Extremum<T> &&x) {
2077 if (auto array{ApplyElementwise(context, x,
2078 std::function<Expr<T>(Expr<T> &&, Expr<T> &&)>{[=](Expr<T> &&l,
2079 Expr<T> &&r) {
2080 return Expr<T>{Extremum<T>{x.ordering, std::move(l), std::move(r)}};
2081 }})}) {
2082 return *array;
2083 }
2084 if (auto folded{OperandsAreConstants(x)}) {
2085 if constexpr (T::category == TypeCategory::Integer) {
2086 if (folded->first.CompareSigned(folded->second) == x.ordering) {
2087 return Expr<T>{Constant<T>{folded->first}};
2088 }
2089 } else if constexpr (T::category == TypeCategory::Real) {
2090 if (folded->first.IsNotANumber() ||
2091 (folded->first.Compare(folded->second) == Relation::Less) ==
2092 (x.ordering == Ordering::Less)) {
2093 return Expr<T>{Constant<T>{folded->first}};
2094 }
2095 } else {
2096 static_assert(T::category == TypeCategory::Character);
2097 // Result of MIN and MAX on character has the length of
2098 // the longest argument.
2099 auto maxLen{std::max(folded->first.length(), folded->second.length())};
2100 bool isFirst{x.ordering == Compare(folded->first, folded->second)};
2101 auto res{isFirst ? std::move(folded->first) : std::move(folded->second)};
2102 res = res.length() == maxLen
2103 ? std::move(res)
2104 : CharacterUtils<T::kind>::Resize(res, maxLen);
2105 return Expr<T>{Constant<T>{std::move(res)}};
2106 }
2107 return Expr<T>{Constant<T>{folded->second}};
2108 }
2109 return Expr<T>{std::move(x)};
2110 }
2111
2112 template <int KIND>
2113 Expr<Type<TypeCategory::Real, KIND>> ToReal(
2114 FoldingContext &context, Expr<SomeType> &&expr) {
2115 using Result = Type<TypeCategory::Real, KIND>;
2116 std::optional<Expr<Result>> result;
2117 common::visit(
2118 [&](auto &&x) {
2119 using From = std::decay_t<decltype(x)>;
2120 if constexpr (std::is_same_v<From, BOZLiteralConstant>) {
2121 // Move the bits without any integer->real conversion
2122 From original{x};
2123 result = ConvertToType<Result>(std::move(x));
2124 const auto *constant{UnwrapExpr<Constant<Result>>(*result)};
2125 CHECK(constant);
2126 Scalar<Result> real{constant->GetScalarValue().value()};
2127 From converted{From::ConvertUnsigned(real.RawBits()).value};
2128 if (original != converted &&
2129 context.languageFeatures().ShouldWarn(
2130 common::UsageWarning::FoldingValueChecks)) { // C1601
2131 context.messages().Say(
2132 "Nonzero bits truncated from BOZ literal constant in REAL intrinsic"_warn_en_US);
2133 }
2134 } else if constexpr (IsNumericCategoryExpr<From>()) {
2135 result = Fold(context, ConvertToType<Result>(std::move(x)));
2136 } else {
2137 common::die("ToReal: bad argument expression");
2138 }
2139 },
2140 std::move(expr.u));
2141 return result.value();
2142 }
2143
2144 // REAL(z) and AIMAG(z)
2145 template <int KIND>
2146 Expr<Type<TypeCategory::Real, KIND>> FoldOperation(
2147 FoldingContext &context, ComplexComponent<KIND> &&x) {
2148 using Operand = Type<TypeCategory::Complex, KIND>;
2149 using Result = Type<TypeCategory::Real, KIND>;
2150 if (auto array{ApplyElementwise(context, x,
2151 std::function<Expr<Result>(Expr<Operand> &&)>{
2152 [=](Expr<Operand> &&operand) {
2153 return Expr<Result>{ComplexComponent<KIND>{
2154 x.isImaginaryPart, std::move(operand)}};
2155 }})}) {
2156 return *array;
2157 }
2158 auto &operand{x.left()};
2159 if (auto value{GetScalarConstantValue<Operand>(operand)}) {
2160 if (x.isImaginaryPart) {
2161 return Expr<Result>{Constant<Result>{value->AIMAG()}};
2162 } else {
2163 return Expr<Result>{Constant<Result>{value->REAL()}};
2164 }
2165 }
2166 return Expr<Result>{std::move(x)};
2167 }
2168
2169 template <typename T>
2170 Expr<T> ExpressionBase<T>::Rewrite(FoldingContext &context, Expr<T> &&expr) {
2171 return common::visit(
2172 [&](auto &&x) -> Expr<T> {
2173 if constexpr (IsSpecificIntrinsicType<T>) {
2174 return FoldOperation(context, std::move(x));
2175 } else if constexpr (std::is_same_v<T, SomeDerived>) {
2176 return FoldOperation(context, std::move(x));
2177 } else if constexpr (common::HasMember<decltype(x),
2178 TypelessExpression>) {
2179 return std::move(expr);
2180 } else {
2181 return Expr<T>{Fold(context, std::move(x))};
2182 }
2183 },
2184 std::move(expr.u));
2185 }
2186
2187 FOR_EACH_TYPE_AND_KIND(extern template class ExpressionBase, )
2188 } // namespace Fortran::evaluate
2189 #endif // FORTRAN_EVALUATE_FOLD_IMPLEMENTATION_H_