9#ifndef FORTRAN_EVALUATE_FOLD_IMPLEMENTATION_H_
10#define FORTRAN_EVALUATE_FOLD_IMPLEMENTATION_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/check-expression.h"
20#include "flang/Evaluate/common.h"
21#include "flang/Evaluate/constant.h"
22#include "flang/Evaluate/expression.h"
23#include "flang/Evaluate/fold.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"
51static constexpr bool useKahanSummation{
false};
54template <
typename T>
class Folder {
56 explicit Folder(
int kind,
FoldingContext &c,
bool forOptionalArgument =
false)
57 : kind_{kind}, context_{c}, forOptionalArgument_{forOptionalArgument} {}
58 template <
typename U = T,
60 std::enable_if_t<std::is_same_v<U, Type<TypeCategory::Derived>>>>
61 explicit Folder(
FoldingContext &c,
bool forOptionalArgument =
false)
62 : Folder(0, c, forOptionalArgument) {}
64 std::optional<Constant<T>> GetNamedConstant(
const Symbol &);
65 std::optional<Constant<T>> ApplySubscripts(
const Constant<T> &array,
67 std::optional<Constant<T>> ApplyComponent(
70 std::optional<Constant<T>> GetConstantComponent(
72 std::optional<Constant<T>> Folding(
ArrayRef &);
73 std::optional<Constant<T>> Folding(
DataRef &);
75 Constant<T> *Folding(std::optional<ActualArgument> &);
91 bool forOptionalArgument_{
false};
94std::optional<Constant<SubscriptInteger>> GetConstantSubscript(
97template <
typename TR,
typename... TA, std::size_t... I>
98std::optional<std::function<Scalar<TR>(
FoldingContext &, Scalar<TA>...)>>
99GetHostRuntimeWrapperHelper(
int resultKind,
100 std::array<
int,
sizeof...(TA)> argKinds,
const std::string &name,
101 std::index_sequence<I...>) {
102 std::vector<DynamicType> argTypes{
DynamicType{TA::category, argKinds[I]}...};
103 if (
auto hostWrapper{GetHostRuntimeWrapper(
104 name, DynamicType{TR::category, resultKind}, argTypes)}) {
105 return [hostWrapper, resultKind, argKinds](
107 std::vector<Expr<SomeType>> genericArgs{
109 return GetScalarConstantValue<TR>(
110 resultKind, (*hostWrapper)(context, std::move(genericArgs)))
118template <
typename TR,
typename... TA>
119static std::optional<std::function<Scalar<TR>(
FoldingContext &, Scalar<TA>...)>>
120GetHostRuntimeWrapper(
int resultKind, std::array<
int,
sizeof...(TA)> argKinds,
121 const std::string &name) {
122 return GetHostRuntimeWrapperHelper<TR, TA...>(
123 resultKind, argKinds, name, std::index_sequence_for<TA...>{});
134common::IfNoLvalue<Expr<ResultType<A>>, A> FoldOperation(
136 static_assert(!std::is_same_v<A, Expr<ResultType<A>>>,
137 "call Fold() instead for Expr<>");
160 const int kind{designator.kind()};
161 return Folder<T>{kind, context}.Folding(std::move(designator));
177std::optional<Constant<T>> Folder<T>::GetNamedConstant(
const Symbol &symbol0) {
178 const Symbol &symbol{ResolveAssociations(symbol0)};
179 if (IsNamedConstant(symbol)) {
180 if (
const auto *
object{
181 symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
182 if (
const auto *constant{UnwrapConstantValue<T>(kind_, object->init())}) {
191std::optional<Constant<T>> Folder<T>::Folding(
ArrayRef &aRef) {
192 std::vector<Constant<SubscriptInteger>> subscripts;
195 if (
auto constant{GetConstantSubscript(context_, ss, aRef.base(), dim++)}) {
196 subscripts.emplace_back(std::move(*constant));
201 if (
Component * component{aRef.base().UnwrapComponent()}) {
202 return GetConstantComponent(*component, &subscripts);
204 GetNamedConstant(aRef.base().GetLastSymbol())}) {
205 return ApplySubscripts(*array, subscripts);
212std::optional<Constant<T>> Folder<T>::Folding(
DataRef &ref) {
213 return common::visit(
215 [
this](SymbolRef &sym) {
return GetNamedConstant(*sym); },
217 comp = FoldOperation(context_, std::move(comp));
218 return GetConstantComponent(comp);
221 aRef = FoldOperation(context_, std::move(aRef));
222 return Folding(aRef);
224 [](
CoarrayRef &) {
return std::optional<Constant<T>>{}; },
231std::optional<Constant<T>> Folder<T>::ApplySubscripts(
const Constant<T> &array,
233 const int kind{array.kind()};
234 const auto &shape{array.shape()};
235 const auto &lbounds{array.lbounds()};
236 int rank{GetRank(shape)};
237 CHECK(rank ==
static_cast<int>(subscripts.size()));
238 std::size_t elements{1};
239 ConstantSubscripts resultShape;
240 ConstantSubscripts ssLB;
241 for (
const auto &ss : subscripts) {
242 if (ss.Rank() == 1) {
243 resultShape.push_back(
static_cast<ConstantSubscript
>(ss.size()));
244 elements *= ss.size();
245 ssLB.push_back(ss.lbounds().front());
246 }
else if (ss.Rank() > 1) {
250 ConstantSubscripts ssAt(rank, 0), at(rank, 0), tmp(1, 0);
251 std::vector<Scalar<T>> values;
252 while (elements-- > 0) {
253 bool increment{
true};
255 for (
int j{0}; j < rank; ++j) {
256 if (subscripts[j].Rank() == 0) {
257 at[j] = subscripts[j].GetScalarValue().value().ToInt64();
259 CHECK(k < GetRank(resultShape));
260 tmp[0] = ssLB.at(k) + ssAt.at(k);
261 at[j] = subscripts[j].At(tmp).ToInt64();
263 if (++ssAt[k] == resultShape[k]) {
271 if (at[j] < lbounds[j] || at[j] >= lbounds[j] + shape[j]) {
272 context_.messages().Say(
273 "Subscript value (%jd) is out of range on dimension %d in reference to a constant array value"_err_en_US,
278 values.emplace_back(array.At(at));
279 CHECK(!increment || elements == 0);
280 CHECK(k == GetRank(resultShape));
282 if constexpr (T::category == TypeCategory::Character) {
284 kind, array.LEN(), std::move(values), std::move(resultShape)};
285 }
else if constexpr (std::is_same_v<T, Type<TypeCategory::Derived>>) {
287 return Constant<T>{array.result().derivedTypeSpec(), std::move(values),
288 std::move(resultShape)};
290 return Constant<T>{kind, std::move(values), std::move(resultShape)};
295std::optional<Constant<T>> Folder<T>::ApplyComponent(
298 if (
auto scalar{structures.GetScalarValue()}) {
299 if (std::optional<
Expr<SomeType>> expr{scalar->Find(component)}) {
300 if (
const Constant<T> *value{UnwrapConstantValue<T>(kind_, *expr)}) {
302 return ApplySubscripts(*value, *subscripts);
310 std::unique_ptr<ArrayConstructor<T>> array;
311 if (structures.empty()) {
314 ConstantSubscripts at{structures.lbounds()};
319 UnwrapConstantValue<T>(kind_, expr.value())}) {
323 auto *typedExpr{UnwrapExpr<Expr<T>>(kind_, expr.value())};
325 array = std::make_unique<ArrayConstructor<T>>(kind_, *typedExpr);
326 if constexpr (T::category == TypeCategory::Character) {
327 array->set_LEN(MakeSubscriptIntExpr(value->LEN()));
331 if (
auto element{ApplySubscripts(*value, *subscripts)}) {
332 CHECK(element->Rank() == 0);
333 array->Push(
Expr<T>{std::move(*element)});
338 CHECK(value->Rank() == 0);
345 }
while (structures.IncrementSubscripts(at));
349 if (
auto *constant{UnwrapConstantValue<T>(kind_, result)}) {
350 return constant->Reshape(common::Clone(structures.shape()));
357std::optional<Constant<T>> Folder<T>::GetConstantComponent(
Component &component,
362 [&](
const Symbol &symbol) {
364 .GetNamedConstant(symbol);
372 .GetConstantComponent(base);
375 return std::optional<
379 component.base().u)}) {
380 return ApplyComponent(
381 std::move(*structures), component.GetLastSymbol(), subscripts);
388 const int kind{designator.kind()};
389 if constexpr (T::category == TypeCategory::Character) {
390 if (
auto *substring{common::Unwrap<Substring>(designator.u)}) {
392 substring->Fold(context_)};
393 folded && folded->kind() == kind) {
394 return std::move(*folded);
400 }
else if constexpr (T::category == TypeCategory::Real) {
401 if (
auto *zPart{std::get_if<ComplexPart>(&designator.u)}) {
402 *zPart = FoldOperation(context_, std::move(*zPart));
406 return Fold(context_,
414 return common::visit(
416 [&](SymbolRef &&symbol) {
417 if (
auto constant{GetNamedConstant(*symbol)}) {
418 return Expr<T>{std::move(*constant)};
420 return Expr<T>{std::move(designator)};
423 aRef = FoldOperation(context_, std::move(aRef));
424 if (
auto c{Folding(aRef)}) {
431 component = FoldOperation(context_, std::move(component));
432 if (
auto c{GetConstantComponent(component)}) {
438 [&, kind](
auto &&x) {
443 std::move(designator.u));
449Constant<T> *Folder<T>::Folding(std::optional<ActualArgument> &arg) {
450 if (
auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
451 *expr = Fold(context_, std::move(*expr));
452 if constexpr (T::category != TypeCategory::Derived) {
453 if (!UnwrapExpr<
Expr<T>>(kind_, *expr)) {
455 var{forOptionalArgument_
456 ? UnwrapWholeSymbolOrComponentDataRef(*expr)
458 var && (IsOptional(*var) || IsAllocatableOrObjectPointer(var))) {
460 }
else if (
auto converted{ConvertToType(
461 DynamicType{T::category, kind_}, std::move(*expr))}) {
462 *expr = Fold(context_, std::move(*converted));
466 return UnwrapConstantValue<T>(kind_, *expr);
471template <
typename... A, std::size_t... I>
472std::optional<std::tuple<const Constant<A> *...>> GetConstantArgumentsHelper(
473 const std::array<
int,
sizeof...(A)> &kinds,
FoldingContext &context,
474 ActualArguments &arguments,
bool hasOptionalArgument,
475 std::index_sequence<I...>) {
476 static_assert(
sizeof...(A) > 0);
477 std::tuple<const Constant<A> *...> args{
478 Folder<A>{kinds[I], context, hasOptionalArgument}.Folding(
479 arguments.at(I))...};
480 if ((... && (std::get<I>(args)))) {
487template <
typename... A>
488std::optional<std::tuple<const Constant<A> *...>> GetConstantArguments(
489 const std::array<
int,
sizeof...(A)> &kinds,
FoldingContext &context,
490 ActualArguments &args,
bool hasOptionalArgument) {
491 return GetConstantArgumentsHelper<A...>(kinds, context, args,
492 hasOptionalArgument, std::index_sequence_for<A...>{});
495template <
typename... A, std::size_t... I>
496std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArgumentsHelper(
497 const std::array<
int,
sizeof...(A)> &kinds,
FoldingContext &context,
498 ActualArguments &args,
bool hasOptionalArgument,
499 std::index_sequence<I...>) {
500 if (
auto constArgs{GetConstantArguments<A...>(
501 kinds, context, args, hasOptionalArgument)}) {
502 return std::tuple<Scalar<A>...>{
503 std::get<I>(*constArgs)->GetScalarValue().value()...};
509template <
typename... A>
510std::optional<std::tuple<Scalar<A>...>> GetScalarConstantArguments(
511 const std::array<
int,
sizeof...(A)> &kinds,
FoldingContext &context,
512 ActualArguments &args,
bool hasOptionalArgument) {
513 return GetScalarConstantArgumentsHelper<A...>(kinds, context, args,
514 hasOptionalArgument, std::index_sequence_for<A...>{});
521template <
typename TR,
typename... TArgs>
522using ScalarFunc = std::function<Scalar<TR>(
const Scalar<TArgs> &...)>;
523template <
typename TR,
typename... TArgs>
524using ScalarFuncWithContext =
525 std::function<Scalar<TR>(
FoldingContext &,
const Scalar<TArgs> &...)>;
527template <
template <
typename,
typename...>
typename WrapperType,
typename TR,
528 typename... TA, std::size_t... I>
529Expr<TR> FoldElementalIntrinsicHelper(
int resultKind,
530 const std::array<
int,
sizeof...(TA)> &argKinds,
FoldingContext &context,
532 bool hasOptionalArgument, std::index_sequence<I...>) {
533 CHECK(funcRef.kind() == resultKind);
534 if (std::optional<std::tuple<
const Constant<TA> *...>> args{
535 GetConstantArguments<TA...>({argKinds[I]...}, context,
536 funcRef.arguments(), hasOptionalArgument)}) {
538 ConstantSubscripts shape;
540 const ConstantSubscripts *shapes[]{&std::get<I>(*args)->shape()...};
541 const int ranks[]{std::get<I>(*args)->Rank()...};
542 for (
unsigned int i{0}; i <
sizeof...(TA); ++i) {
548 if (shape != *shapes[i]) {
553 context.messages().Say(
554 "Arguments in elemental intrinsic function are not conformable"_err_en_US);
555 return Expr<TR>{std::move(funcRef)};
560 CHECK(rank == GetRank(shape));
562 std::vector<Scalar<TR>> results;
563 std::optional<uint64_t> n{TotalElementCount(shape)};
565 context.messages().Say(
566 "Too many elements in elemental intrinsic function result"_err_en_US);
567 return Expr<TR>{std::move(funcRef)};
571 ConstantSubscripts resultIndex(rank, 1);
572 ConstantSubscripts argIndex[]{std::get<I>(*args)->lbounds()...};
574 if constexpr (std::is_same_v<WrapperType<TR, TA...>,
575 ScalarFuncWithContext<TR, TA...>>) {
576 results.emplace_back(
577 func(context, std::get<I>(*args)->At(argIndex[I])...));
578 }
else if constexpr (std::is_same_v<WrapperType<TR, TA...>,
579 ScalarFunc<TR, TA...>>) {
580 results.emplace_back(func(std::get<I>(*args)->At(argIndex[I])...));
582 (std::get<I>(*args)->IncrementSubscripts(argIndex[I]), ...);
583 }
while (bounds.IncrementSubscripts(resultIndex));
586 if constexpr (TR::category == TypeCategory::Character) {
587 auto len{
static_cast<ConstantSubscript
>(
588 results.empty() ? 0 : results[0].length())};
590 Constant<TR>{resultKind, len, std::move(results), std::move(shape)}};
591 }
else if constexpr (TR::category == TypeCategory::Derived) {
592 if (!results.empty()) {
596 std::move(results), std::move(shape)}};
600 Constant<TR>{resultKind, std::move(results), std::move(shape)}};
603 return Expr<TR>{std::move(funcRef)};
606template <
typename TR,
typename... TA>
607Expr<TR> FoldElementalIntrinsic(
int resultKind,
608 const std::array<
int,
sizeof...(TA)> &argKinds,
FoldingContext &context,
610 bool hasOptionalArgument =
false) {
611 return FoldElementalIntrinsicHelper<ScalarFunc, TR, TA...>(resultKind,
612 argKinds, context, std::move(funcRef), func, hasOptionalArgument,
613 std::index_sequence_for<TA...>{});
615template <
typename TR,
typename... TA>
616Expr<TR> FoldElementalIntrinsic(
int resultKind,
617 const std::array<
int,
sizeof...(TA)> &argKinds,
FoldingContext &context,
619 bool hasOptionalArgument =
false) {
620 return FoldElementalIntrinsicHelper<ScalarFuncWithContext, TR, TA...>(
621 resultKind, argKinds, context, std::move(funcRef), func,
622 hasOptionalArgument, std::index_sequence_for<TA...>{});
625std::optional<std::int64_t> GetInt64ArgOr(
626 const std::optional<ActualArgument> &, std::int64_t defaultValue);
628template <
typename A,
typename B>
629std::optional<std::vector<A>> GetIntegerVector(
const B &x) {
630 static_assert(common::is_integral_v<A>);
631 if (
const auto *someInteger{
632 UnwrapExpr<Expr<Type<TypeCategory::Integer>>>(x)}) {
633 if (
const auto *constant{
634 UnwrapConstantValue<Type<TypeCategory::Integer>>(*someInteger)}) {
635 if (constant->Rank() == 1) {
636 std::vector<A> result;
637 for (
const auto &value : constant->values()) {
638 result.push_back(
static_cast<A
>(value.ToInt64()));
652 const int kind{funcRef.kind()};
654 invalid.name = IntrinsicProcTable::InvalidName;
656 ActualArguments{std::move(funcRef.arguments())}}};
660 const int kind{funcRef.kind()};
661 auto args{funcRef.arguments()};
662 CHECK(args.size() == 3);
663 const auto *array{UnwrapConstantValue<T>(kind, args[0])};
664 const auto *shiftExpr{UnwrapExpr<Expr<Type<TypeCategory::Integer>>>(args[1])};
665 auto dim{GetInt64ArgOr(args[2], 1)};
666 if (!array || !shiftExpr || !dim) {
667 return Expr<T>{std::move(funcRef)};
669 auto convertedShift{Fold(context_,
670 ConvertToType<SubscriptInteger>(SubscriptIntegerKind,
672 const auto *shift{UnwrapConstantValue<SubscriptInteger>(
673 SubscriptIntegerKind, convertedShift)};
675 return Expr<T>{std::move(funcRef)};
678 if (*dim < 1 || *dim > array->Rank()) {
679 context_.messages().Say(
"Invalid 'dim=' argument (%jd) in CSHIFT"_err_en_US,
680 static_cast<std::intmax_t
>(*dim));
681 }
else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
684 int rank{array->Rank()};
685 int zbDim{
static_cast<int>(*dim) - 1};
687 if (shift->Rank() > 0) {
689 for (
int j{0}; j < rank; ++j) {
691 if (array->shape()[j] != shift->shape()[k]) {
692 context_.messages().Say(
693 "Invalid 'shift=' argument in CSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
694 k + 1,
static_cast<std::intmax_t
>(shift->shape()[k]),
695 static_cast<std::intmax_t
>(array->shape()[j]));
703 std::vector<Scalar<T>> resultElements;
704 ConstantSubscripts arrayLB{array->lbounds()};
705 ConstantSubscripts arrayAt{arrayLB};
706 ConstantSubscript &dimIndex{arrayAt[zbDim]};
707 ConstantSubscript dimLB{dimIndex};
708 ConstantSubscript dimExtent{array->shape()[zbDim]};
709 ConstantSubscripts shiftLB{shift->lbounds()};
710 for (
auto n{GetSize(array->shape())}; n > 0; --n) {
711 ConstantSubscript origDimIndex{dimIndex};
712 ConstantSubscripts shiftAt;
713 if (shift->Rank() > 0) {
715 for (
int j{0}; j < rank; ++j) {
717 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
721 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
722 dimIndex = dimLB + ((dimIndex - dimLB + shiftCount) % dimExtent);
723 if (dimIndex < dimLB) {
724 dimIndex += dimExtent;
725 }
else if (dimIndex >= dimLB + dimExtent) {
726 dimIndex -= dimExtent;
728 resultElements.push_back(array->At(arrayAt));
729 dimIndex = origDimIndex;
730 array->IncrementSubscripts(arrayAt);
732 return Expr<T>{PackageConstant<T>(
733 kind, std::move(resultElements), *array, array->shape())};
737 return MakeInvalidIntrinsic(std::move(funcRef));
741 const int kind{funcRef.kind()};
742 auto args{funcRef.arguments()};
743 CHECK(args.size() == 4);
744 const auto *array{UnwrapConstantValue<T>(kind, args[0])};
745 const auto *shiftExpr{UnwrapExpr<Expr<Type<TypeCategory::Integer>>>(args[1])};
746 auto dim{GetInt64ArgOr(args[3], 1)};
747 if (!array || !shiftExpr || !dim) {
748 return Expr<T>{std::move(funcRef)};
751 auto convertedShift{Fold(context_,
752 ConvertToType<SubscriptInteger>(SubscriptIntegerKind,
754 const auto *shift{UnwrapConstantValue<SubscriptInteger>(
755 SubscriptIntegerKind, convertedShift)};
757 return Expr<T>{std::move(funcRef)};
760 std::optional<Expr<SomeType>> convertedBoundary;
761 if (
const auto *boundaryExpr{UnwrapExpr<Expr<SomeType>>(args[2])}) {
762 convertedBoundary = Fold(context_,
764 boundary = UnwrapExpr<Constant<T>>(kind, convertedBoundary);
766 return Expr<T>{std::move(funcRef)};
770 if (*dim < 1 || *dim > array->Rank()) {
771 context_.messages().Say(
772 "Invalid 'dim=' argument (%jd) in EOSHIFT"_err_en_US,
773 static_cast<std::intmax_t
>(*dim));
774 }
else if (shift->Rank() > 0 && shift->Rank() != array->Rank() - 1) {
776 }
else if (boundary && boundary->Rank() > 0 &&
777 boundary->Rank() != array->Rank() - 1) {
780 int rank{array->Rank()};
781 int zbDim{
static_cast<int>(*dim) - 1};
783 if (shift->Rank() > 0) {
785 for (
int j{0}; j < rank; ++j) {
787 if (array->shape()[j] != shift->shape()[k]) {
788 context_.messages().Say(
789 "Invalid 'shift=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
790 k + 1,
static_cast<std::intmax_t
>(shift->shape()[k]),
791 static_cast<std::intmax_t
>(array->shape()[j]));
798 if (boundary && boundary->Rank() > 0) {
800 for (
int j{0}; j < rank; ++j) {
802 if (array->shape()[j] != boundary->shape()[k]) {
803 context_.messages().Say(
804 "Invalid 'boundary=' argument in EOSHIFT: extent on dimension %d is %jd but must be %jd"_err_en_US,
805 k + 1,
static_cast<std::intmax_t
>(boundary->shape()[k]),
806 static_cast<std::intmax_t
>(array->shape()[j]));
814 std::vector<Scalar<T>> resultElements;
815 ConstantSubscripts arrayLB{array->lbounds()};
816 ConstantSubscripts arrayAt{arrayLB};
817 ConstantSubscript &dimIndex{arrayAt[zbDim]};
818 ConstantSubscript dimLB{dimIndex};
819 ConstantSubscript dimExtent{array->shape()[zbDim]};
820 ConstantSubscripts shiftLB{shift->lbounds()};
821 ConstantSubscripts boundaryLB;
823 boundaryLB = boundary->lbounds();
825 for (
auto n{GetSize(array->shape())}; n > 0; --n) {
826 ConstantSubscript origDimIndex{dimIndex};
827 ConstantSubscripts shiftAt;
828 if (shift->Rank() > 0) {
830 for (
int j{0}; j < rank; ++j) {
832 shiftAt.emplace_back(shiftLB[k++] + arrayAt[j] - arrayLB[j]);
836 ConstantSubscript shiftCount{shift->At(shiftAt).ToInt64()};
837 dimIndex += shiftCount;
838 if (dimIndex >= dimLB && dimIndex < dimLB + dimExtent) {
839 resultElements.push_back(array->At(arrayAt));
840 }
else if (boundary) {
841 ConstantSubscripts boundaryAt;
842 if (boundary->Rank() > 0) {
843 for (
int j{0}; j < rank; ++j) {
846 boundaryAt.emplace_back(
847 boundaryLB[k++] + arrayAt[j] - arrayLB[j]);
851 resultElements.push_back(boundary->At(boundaryAt));
852 }
else if constexpr (T::category == TypeCategory::Integer ||
853 T::category == TypeCategory::Unsigned ||
854 T::category == TypeCategory::Real ||
855 T::category == TypeCategory::Complex ||
856 T::category == TypeCategory::Logical) {
857 resultElements.emplace_back(Scalar<T>::Zero(kind));
858 }
else if constexpr (T::category == TypeCategory::Character) {
859 auto len{
static_cast<std::size_t
>(array->LEN())};
860 resultElements.emplace_back(kind, len,
' ');
862 DIE(
"no derived type boundary");
864 dimIndex = origDimIndex;
865 array->IncrementSubscripts(arrayAt);
867 return Expr<T>{PackageConstant<T>(
868 kind, std::move(resultElements), *array, array->shape())};
872 return MakeInvalidIntrinsic(std::move(funcRef));
876 const int kind{funcRef.kind()};
877 return FoldElementalIntrinsic<T, T, T, LogicalResult>(kind,
878 {kind, kind, LogicalResultKind}, context_, std::move(funcRef),
879 ScalarFunc<T, T, T, LogicalResult>(
880 [](
const Scalar<T> &ifTrue,
const Scalar<T> &ifFalse,
881 const Scalar<LogicalResult> &predicate) -> Scalar<T> {
882 return predicate.IsTrue() ? ifTrue : ifFalse;
887 const int kind{funcRef.kind()};
888 auto args{funcRef.arguments()};
889 CHECK(args.size() == 3);
890 const auto *array{UnwrapConstantValue<T>(kind, args[0])};
891 const auto *vector{UnwrapConstantValue<T>(kind, args[2])};
892 auto convertedMask{Fold(context_,
893 ConvertToType<LogicalResult>(LogicalResultKind,
897 UnwrapConstantValue<LogicalResult>(LogicalResultKind, convertedMask)};
898 if (!array || !mask || (args[2] && !vector)) {
899 return Expr<T>{std::move(funcRef)};
902 ConstantSubscript arrayElements{GetSize(array->shape())};
903 ConstantSubscript truths{0};
904 ConstantSubscripts maskAt{mask->lbounds()};
905 if (mask->Rank() == 0) {
906 if (mask->At(maskAt).IsTrue()) {
907 truths = arrayElements;
909 }
else if (array->shape() != mask->shape()) {
911 return MakeInvalidIntrinsic(std::move(funcRef));
913 for (ConstantSubscript j{0}; j < arrayElements;
914 ++j, mask->IncrementSubscripts(maskAt)) {
915 if (mask->At(maskAt).IsTrue()) {
920 std::vector<Scalar<T>> resultElements;
921 ConstantSubscripts arrayAt{array->lbounds()};
922 ConstantSubscript resultSize{truths};
924 resultSize = vector->shape().at(0);
925 if (resultSize < truths) {
926 context_.messages().Say(
927 "Invalid 'vector=' argument in PACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
928 static_cast<std::intmax_t
>(truths),
929 static_cast<std::intmax_t
>(resultSize));
930 return MakeInvalidIntrinsic(std::move(funcRef));
933 for (ConstantSubscript j{0}; j < truths;) {
934 if (mask->At(maskAt).IsTrue()) {
935 resultElements.push_back(array->At(arrayAt));
938 array->IncrementSubscripts(arrayAt);
939 mask->IncrementSubscripts(maskAt);
942 ConstantSubscripts vectorAt{vector->lbounds()};
943 vectorAt.at(0) += truths;
944 for (ConstantSubscript j{truths}; j < resultSize; ++j) {
945 resultElements.push_back(vector->At(vectorAt));
949 return Expr<T>{PackageConstant<T>(kind, std::move(resultElements), *array,
950 ConstantSubscripts{
static_cast<ConstantSubscript
>(resultSize)})};
954 auto args{funcRef.arguments()};
955 CHECK(args.size() == 4);
956 const auto *source{UnwrapConstantValue<T>(funcRef.kind(), args[0])};
957 const auto *pad{UnwrapConstantValue<T>(funcRef.kind(), args[2])};
958 std::optional<std::vector<ConstantSubscript>> shape{
959 GetIntegerVector<ConstantSubscript>(args[1])};
960 std::optional<std::vector<int>> order{GetIntegerVector<int>(args[3])};
961 std::optional<uint64_t> optResultElement;
962 std::optional<std::vector<int>> dimOrder;
965 if (shape->size() > common::maxRank) {
966 context_.messages().Say(
967 "Size of 'shape=' argument (%zd) must not be greater than %d"_err_en_US,
968 shape->size(), common::maxRank);
970 }
else if (HasNegativeExtent(*shape)) {
971 context_.messages().Say(
972 "'shape=' argument (%s) must not have a negative extent"_err_en_US,
973 DEREF(args[1]->UnwrapExpr()).AsFortran());
976 optResultElement = TotalElementCount(*shape);
977 if (!optResultElement) {
978 context_.messages().Say(
979 "'shape=' argument (%s) specifies an array with too many elements"_err_en_US,
980 DEREF(args[1]->UnwrapExpr()).AsFortran());
985 dimOrder = ValidateDimensionOrder(GetRank(*shape), *order);
987 context_.messages().Say(
988 "Invalid 'order=' argument (%s) in RESHAPE"_err_en_US,
989 DEREF(args[3]->UnwrapExpr()).AsFortran());
996 }
else if (!source || !shape || (args[2] && !pad) || (args[3] && !order)) {
997 return Expr<T>{std::move(funcRef)};
999 uint64_t resultElements{*optResultElement};
1000 std::vector<int> *dimOrderPtr{dimOrder ? &dimOrder.value() :
nullptr};
1001 if (resultElements > source->size() && (!pad || pad->empty())) {
1002 context_.messages().Say(
1003 "Too few elements in 'source=' argument and 'pad=' "
1004 "argument is not present or has null size"_err_en_US);
1008 ? source->Reshape(std::move(shape.value()))
1009 : pad->Reshape(std::move(shape.value()))};
1010 ConstantSubscripts subscripts{result.lbounds()};
1011 auto copied{result.CopyFrom(*source,
1012 std::min(
static_cast<uint64_t
>(source->size()), resultElements),
1013 subscripts, dimOrderPtr)};
1014 if (copied < resultElements) {
1016 copied += result.CopyFrom(
1017 *pad, resultElements - copied, subscripts, dimOrderPtr);
1019 CHECK(copied == resultElements);
1020 return Expr<T>{std::move(result)};
1024 return MakeInvalidIntrinsic(std::move(funcRef));
1028 auto args{funcRef.arguments()};
1029 CHECK(args.size() == 3);
1030 const Constant<T> *source{UnwrapConstantValue<T>(funcRef.kind(), args[0])};
1031 auto dim{ToInt64(args[1])};
1032 auto ncopies{ToInt64(args[2])};
1033 if (!source || !dim) {
1034 return Expr<T>{std::move(funcRef)};
1036 int sourceRank{source->Rank()};
1037 if (sourceRank >= common::maxRank) {
1038 context_.messages().Say(
1039 "SOURCE= argument to SPREAD has rank %d but must have rank less than %d"_err_en_US,
1040 sourceRank, common::maxRank);
1041 }
else if (*dim < 1 || *dim > sourceRank + 1) {
1042 context_.messages().Say(
1043 "DIM=%d argument to SPREAD must be between 1 and %d"_err_en_US, *dim,
1045 }
else if (!ncopies) {
1046 return Expr<T>{std::move(funcRef)};
1056 ConstantSubscripts shape{source->shape()};
1057 shape.insert(shape.begin() + *dim - 1, *ncopies);
1058 Constant<T> spread{source->Reshape(std::move(shape))};
1059 std::optional<uint64_t> n{TotalElementCount(spread.shape())};
1061 context_.messages().Say(
"Too many elements in SPREAD result"_err_en_US);
1063 std::vector<int> dimOrder;
1064 for (
int j{0}; j < sourceRank; ++j) {
1065 dimOrder.push_back(j < *dim - 1 ? j : j + 1);
1067 dimOrder.push_back(*dim - 1);
1068 ConstantSubscripts at{spread.lbounds()};
1069 spread.CopyFrom(*source, *n, at, &dimOrder);
1070 return Expr<T>{std::move(spread)};
1074 return MakeInvalidIntrinsic(std::move(funcRef));
1078 const int kind{funcRef.kind()};
1079 auto args{funcRef.arguments()};
1080 CHECK(args.size() == 1);
1081 const auto *matrix{UnwrapConstantValue<T>(kind, args[0])};
1083 return Expr<T>{std::move(funcRef)};
1086 std::vector<Scalar<T>> resultElements;
1087 ConstantSubscripts at(2);
1088 for (ConstantSubscript j{0}; j < matrix->shape()[0]; ++j) {
1089 at[0] = matrix->lbounds()[0] + j;
1090 for (ConstantSubscript k{0}; k < matrix->shape()[1]; ++k) {
1091 at[1] = matrix->lbounds()[1] + k;
1092 resultElements.push_back(matrix->At(at));
1095 at = matrix->shape();
1096 std::swap(at[0], at[1]);
1098 PackageConstant<T>(kind, std::move(resultElements), *matrix, at)};
1102 const int kind{funcRef.kind()};
1103 auto args{funcRef.arguments()};
1104 CHECK(args.size() == 3);
1105 const auto *vector{UnwrapConstantValue<T>(kind, args[0])};
1106 auto convertedMask{Fold(context_,
1107 ConvertToType<LogicalResult>(LogicalResultKind,
1111 UnwrapConstantValue<LogicalResult>(LogicalResultKind, convertedMask)};
1112 const auto *field{UnwrapConstantValue<T>(kind, args[2])};
1113 if (!vector || !mask || !field) {
1114 return Expr<T>{std::move(funcRef)};
1117 if (field->Rank() > 0 && field->shape() != mask->shape()) {
1119 return MakeInvalidIntrinsic(std::move(funcRef));
1121 ConstantSubscript maskElements{GetSize(mask->shape())};
1122 ConstantSubscript truths{0};
1123 ConstantSubscripts maskAt{mask->lbounds()};
1124 for (ConstantSubscript j{0}; j < maskElements;
1125 ++j, mask->IncrementSubscripts(maskAt)) {
1126 if (mask->At(maskAt).IsTrue()) {
1130 if (truths > GetSize(vector->shape())) {
1131 context_.messages().Say(
1132 "Invalid 'vector=' argument in UNPACK: the 'mask=' argument has %jd true elements, but the vector has only %jd elements"_err_en_US,
1133 static_cast<std::intmax_t
>(truths),
1134 static_cast<std::intmax_t
>(GetSize(vector->shape())));
1135 return MakeInvalidIntrinsic(std::move(funcRef));
1137 std::vector<Scalar<T>> resultElements;
1138 ConstantSubscripts vectorAt{vector->lbounds()};
1139 ConstantSubscripts fieldAt{field->lbounds()};
1140 for (ConstantSubscript j{0}; j < maskElements; ++j) {
1141 if (mask->At(maskAt).IsTrue()) {
1142 resultElements.push_back(vector->At(vectorAt));
1143 vector->IncrementSubscripts(vectorAt);
1145 resultElements.push_back(field->At(fieldAt));
1147 mask->IncrementSubscripts(maskAt);
1148 field->IncrementSubscripts(fieldAt);
1150 return Expr<T>{PackageConstant<T>(
1151 kind, std::move(resultElements), *vector, mask->shape())};
1154std::optional<Expr<SomeType>> FoldTransfer(
1158 if (
auto folded{FoldTransfer(context_, funcRef.arguments())}) {
1159 return DEREF(UnwrapExpr<
Expr<T>>(funcRef.kind(), *folded));
1161 return Expr<T>{std::move(funcRef)};
1167template <
typename T>
1170 const int kind{funcRef.kind()};
1171 static_assert(T::category == TypeCategory::Integer ||
1172 T::category == TypeCategory::Unsigned ||
1173 T::category == TypeCategory::Real ||
1174 T::category == TypeCategory::Character);
1197 auto &args{funcRef.arguments()};
1198 std::size_t nargs{args.size()};
1199 bool allArgsConstant{
true};
1200 bool extremumAnyway{nargs == 2 && T::category != TypeCategory::Character};
1204 if (!folder.Folding(args[0])) {
1205 allArgsConstant =
false;
1207 if (!folder.Folding(args[1])) {
1208 allArgsConstant =
false;
1214 for (std::size_t i{2}; i < nargs; ++i) {
1216 if (!folder.Folding(args[i])) {
1217 allArgsConstant =
false;
1225 if (allArgsConstant || extremumAnyway) {
1228 if (
const auto *resultp{UnwrapExpr<Expr<T>>(kind, args[0])}) {
1230 for (std::size_t i{1}; i < nargs; ++i) {
1231 if (
const auto *tExpr{UnwrapExpr<Expr<T>>(kind, args[i])}) {
1232 result = FoldOperation(
1233 context,
Extremum<T>{order, std::move(result), *tExpr});
1236 return Expr<T>{std::move(funcRef)};
1244 return Expr<T>{std::move(funcRef)};
1254template <
typename T>
1255Expr<T> RewriteSpecificMINorMAX(
1257 int kind{funcRef.kind()};
1258 ActualArguments &args{funcRef.arguments()};
1259 auto &intrinsic{DEREF(std::get_if<SpecificIntrinsic>(&funcRef.proc().u))};
1262 std::optional<DynamicType> resultType;
1264 for (
auto j{args.size()}; j-- > 0;) {
1271 (type.category() == resultType->category() &&
1272 type.kind() > resultType->kind()) ||
1273 resultType->category() == TypeCategory::Integer) {
1275 resultTypeArg = &*args[j];
1280 return Expr<T>{std::move(funcRef)};
1283 intrinsic.name.find(
"max") != std::string::npos ?
"max"s :
"min"s;
1284 intrinsic.characteristics.value().functionResult.value().SetType(*resultType);
1285 auto insertConversion{[&](
const auto &x) ->
Expr<T> {
1286 using TR = ResultType<
decltype(x)>;
1287 const int rKind{x.kind()};
1291 context, ConvertToType<T>(kind, AsCategoryExpr(std::move(maxRef))));
1293 if (
auto *sx{UnwrapExpr<Expr<Type<TypeCategory::Real>>>(*resultTypeArg)}) {
1294 return insertConversion(*sx);
1295 }
else if (
auto *sx{UnwrapExpr<Expr<Type<TypeCategory::Integer>>>(
1297 return insertConversion(*sx);
1299 return Expr<T>{std::move(funcRef)};
1331template <
typename T>
1333 const int kind{funcRef.kind()};
1334 ActualArguments &args{funcRef.arguments()};
1335 const auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
1336 if (!intrinsic || intrinsic->name !=
"kind") {
1339 for (std::optional<ActualArgument> &arg : args) {
1340 if (arg && arg->GetConditionalArg()) {
1341 FoldConditionalArg(context, arg);
1342 }
else if (
auto *expr{UnwrapExpr<Expr<SomeType>>(arg)}) {
1343 if (!intrinsic && IsNamedConstantDesignator(*expr)) {
1353 *expr = Fold(context, std::move(*expr));
1378 std::optional<FunctionRef<T>> viaRepresentative;
1379 for (std::size_t j{0}; j < args.size(); ++j) {
1380 if (args[j] && args[j]->isConditionalArg()) {
1382 DEREF(args[j]->GetConditionalArg())};
1386 if (condArg.HasNilConsequent() ||
1387 !IsTypeOnlyInquiryArg(*intrinsic, j)) {
1388 return Expr<T>{std::move(funcRef)};
1390 if (!viaRepresentative) {
1391 viaRepresentative.emplace(funcRef);
1394 *viaRepresentative->arguments()[j] =
1395 common::Clone(DEREF(condArg.FirstNonNilConsequent()));
1398 if (viaRepresentative) {
1399 Expr<T> folded{FoldOperation(context, std::move(*viaRepresentative))};
1403 return std::holds_alternative<Constant<T>>(folded.u)
1405 :
Expr<T>{std::move(funcRef)};
1407 const std::string name{intrinsic->name};
1408 if (name ==
"cshift") {
1409 return Folder<T>{kind, context}.CSHIFT(std::move(funcRef));
1410 }
else if (name ==
"eoshift") {
1411 return Folder<T>{kind, context}.EOSHIFT(std::move(funcRef));
1412 }
else if (name ==
"merge") {
1413 return Folder<T>{kind, context}.MERGE(std::move(funcRef));
1414 }
else if (name ==
"pack") {
1415 return Folder<T>{kind, context}.PACK(std::move(funcRef));
1416 }
else if (name ==
"reshape") {
1417 return Folder<T>{kind, context}.RESHAPE(std::move(funcRef));
1418 }
else if (name ==
"spread") {
1419 return Folder<T>{kind, context}.SPREAD(std::move(funcRef));
1420 }
else if (name ==
"transfer") {
1421 return Folder<T>{kind, context}.TRANSFER(std::move(funcRef));
1422 }
else if (name ==
"transpose") {
1423 return Folder<T>{kind, context}.TRANSPOSE(std::move(funcRef));
1424 }
else if (name ==
"unpack") {
1425 return Folder<T>{kind, context}.UNPACK(std::move(funcRef));
1428 if constexpr (std::is_same_v<T, Type<TypeCategory::Derived>>) {
1431 if (name ==
"huge") {
1433 if (args.size() >= 1 && args[0]) {
1435 UnwrapExpr<Expr<Type<TypeCategory::Derived>>>(args[0])}) {
1436 return std::move(*expr);
1439 }
else if (name ==
"next" || name ==
"previous") {
1440 return FoldEnumerationNextOrPrevious(
1441 context, std::move(funcRef), name ==
"next");
1444 return FoldIntrinsicFunction(context, std::move(funcRef));
1447 return Expr<T>{std::move(funcRef)};
1451template <
typename T>
class ArrayConstructorFolder {
1454 : context_{c}, resultInfo_{kind} {}
1457 const int kind{array.kind()};
1458 if constexpr (T::category == TypeCategory::Character) {
1459 if (
const auto *len{array.LEN()}) {
1460 charLength_ = ToInt64(Fold(context_, common::Clone(*len)));
1461 knownCharLength_ = charLength_.has_value();
1465 if (FoldArray(array)) {
1466 auto n{
static_cast<ConstantSubscript
>(elements_.size())};
1467 if constexpr (std::is_same_v<T, Type<TypeCategory::Derived>>) {
1470 std::move(elements_), ConstantSubscripts{n}}};
1471 }
else if constexpr (T::category == TypeCategory::Character) {
1474 kind, *charLength_, std::move(elements_), ConstantSubscripts{n}}};
1477 CHECK(resultInfo_.kind() == kind);
1479 kind, std::move(elements_), ConstantSubscripts{n}, resultInfo_}};
1482 return Expr<T>{std::move(array)};
1486 bool FoldArray(
const Expr<T> &expr) {
1487 const int kind{expr.kind()};
1488 Expr<T> folded{Fold(context_, common::Clone(expr))};
1489 if (
const auto *c{UnwrapConstantValue<T>(kind, folded)}) {
1492 ConstantSubscripts index{c->lbounds()};
1494 elements_.emplace_back(c->At(index));
1495 }
while (c->IncrementSubscripts(index));
1497 if constexpr (T::category == TypeCategory::Character) {
1498 if (!knownCharLength_) {
1499 charLength_ = std::max(c->LEN(), charLength_.value_or(-1));
1501 }
else if constexpr (T::category == TypeCategory::Real ||
1502 T::category == TypeCategory::Complex) {
1503 if (c->result().isFromInexactLiteralConversion()) {
1504 resultInfo_.set_isFromInexactLiteralConversion();
1512 bool FoldArray(
const common::CopyableIndirection<
Expr<T>> &expr) {
1513 return FoldArray(expr.value());
1522 std::optional<ConstantSubscript> start{ToInt64(
lower)}, end{ToInt64(upper)},
1523 step{ToInt64(stride)};
1524 if (start && end && step && *step != 0) {
1526 ConstantSubscript &j{context_.StartImpliedDo(iDo.name(), *start)};
1528 for (; j <= *end; j += *step) {
1529 result &= FoldArray(iDo.values());
1532 for (; j >= *end; j += *step) {
1533 result &= FoldArray(iDo.values());
1536 context_.EndImpliedDo(iDo.name());
1543 return common::visit([&](
const auto &y) {
return FoldArray(y); }, x.u);
1546 for (
const auto &x : xs) {
1547 if (!FoldArray(x)) {
1555 std::vector<Scalar<T>> elements_;
1556 std::optional<ConstantSubscript> charLength_;
1557 bool knownCharLength_{
false};
1558 typename Constant<T>::Result resultInfo_;
1561template <
typename T>
1563 const int kind{array.kind()};
1564 return ArrayConstructorFolder<T>{kind, context}.FoldArray(std::move(array));
1575template <
typename T>
1578 if (!std::holds_alternative<
Expr<T>>(x.u)) {
1585template <
typename T>
1586std::optional<Expr<T>> AsFlatArrayConstructor(
const Expr<T> &expr) {
1587 const int kind{expr.kind()};
1588 if (
const auto *c{UnwrapConstantValue<T>(kind, expr)}) {
1591 ConstantSubscripts at{c->lbounds()};
1593 result.Push(MakeConstantExpr<T>(kind, c->At(at)));
1594 }
while (c->IncrementSubscripts(at));
1596 return std::make_optional<Expr<T>>(std::move(result));
1597 }
else if (
const auto *a{UnwrapExpr<ArrayConstructor<T>>(expr)}) {
1598 if (ArrayConstructorIsFlat(*a)) {
1599 return std::make_optional<Expr<T>>(expr);
1601 }
else if (
const auto *p{UnwrapExpr<Parentheses<T>>(expr)}) {
1602 return AsFlatArrayConstructor(
Expr<T>{p->left()});
1604 return std::nullopt;
1611template <
typename T>
1612std::optional<Expr<T>> FromArrayConstructor(
1614 const int kind{values.kind()};
1615 if (
auto constShape{AsConstantExtents(context, shape)};
1616 constShape && !HasNegativeExtent(*constShape)) {
1618 if (
auto *constant{UnwrapConstantValue<T>(kind, result)}) {
1620 return Expr<T>{constant->Reshape(std::move(*constShape))};
1622 if (constShape->size() == 1) {
1623 if (
auto elements{GetShape(context, result)}) {
1624 if (
auto constElements{AsConstantExtents(context, *elements)}) {
1625 if (constElements->size() == 1 &&
1626 constElements->at(0) == constShape->at(0)) {
1629 return std::move(result);
1635 return std::nullopt;
1646template <
typename RESULT,
typename OPERAND>
1647std::optional<Expr<RESULT>> MapOperation(
int kind,
FoldingContext &context,
1652 auto &aConst{std::get<ArrayConstructor<OPERAND>>(values.u)};
1653 for (
auto &acValue : aConst) {
1654 auto &scalar{std::get<Expr<OPERAND>>(acValue.u)};
1655 result.Push(Fold(context, f(std::move(scalar))));
1657 if constexpr (RESULT::category == TypeCategory::Character) {
1659 result.set_LEN(std::move(*length));
1662 return FromArrayConstructor(context, std::move(result), shape);
1665template <
typename RESULT,
typename A>
1669 if constexpr (RESULT::category == TypeCategory::Character) {
1671 result.set_LEN(std::move(*length));
1677template <
typename LEFT,
typename RIGHT>
1681 auto rightIter{rightArrConst.begin()};
1682 for (
auto &leftValue : leftArrConst) {
1683 CHECK(rightIter != rightArrConst.end());
1684 auto &leftExpr{std::get<Expr<LEFT>>(leftValue.u)};
1685 auto &rightExpr{std::get<Expr<RIGHT>>(rightIter->u)};
1686 if (leftExpr.Rank() != rightExpr.Rank()) {
1689 std::optional<Shape> leftShape{GetShape(context, leftExpr)};
1690 std::optional<Shape> rightShape{GetShape(context, rightExpr)};
1691 if (!leftShape || !rightShape || *leftShape != *rightShape) {
1700template <
typename RESULT,
typename LEFT,
typename RIGHT>
1705 -> std::optional<Expr<RESULT>> {
1707 ArrayConstructorFromMold<RESULT>(kind, leftValues, std::move(length))};
1708 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1709 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1710 if (!ShapesMatch(context, leftArrConst, rightArrConst)) {
1711 return std::nullopt;
1713 auto rightIter{rightArrConst.begin()};
1714 for (
auto &leftValue : leftArrConst) {
1715 CHECK(rightIter != rightArrConst.end());
1716 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1717 auto &rightScalar{std::get<Expr<RIGHT>>(rightIter->u)};
1719 Fold(context, f(std::move(leftScalar), std::move(rightScalar))));
1722 return FromArrayConstructor(context, std::move(result), shape);
1726template <
typename RESULT,
typename LEFT,
typename RIGHT>
1731 -> std::optional<Expr<RESULT>> {
1733 ArrayConstructorFromMold<RESULT>(kind, leftValues, std::move(length))};
1734 auto &leftArrConst{std::get<ArrayConstructor<LEFT>>(leftValues.u)};
1735 for (
auto &leftValue : leftArrConst) {
1736 auto &leftScalar{std::get<Expr<LEFT>>(leftValue.u)};
1738 Fold(context, f(std::move(leftScalar),
Expr<RIGHT>{rightScalar})));
1740 return FromArrayConstructor(context, std::move(result), shape);
1744template <
typename RESULT,
typename LEFT,
typename RIGHT>
1749 -> std::optional<Expr<RESULT>> {
1751 ArrayConstructorFromMold<RESULT>(kind, leftScalar, std::move(length))};
1752 auto &rightArrConst{std::get<ArrayConstructor<RIGHT>>(rightValues.u)};
1753 for (
auto &rightValue : rightArrConst) {
1754 auto &rightScalar{std::get<Expr<RIGHT>>(rightValue.u)};
1756 Fold(context, f(
Expr<LEFT>{leftScalar}, std::move(rightScalar))));
1758 return FromArrayConstructor(context, std::move(result), shape);
1761template <
typename DERIVED,
typename RESULT,
typename... OPD>
1762std::optional<Expr<SubscriptInteger>> ComputeResultLength(
1764 if constexpr (RESULT::category == TypeCategory::Character) {
1767 return std::nullopt;
1774template <
typename DERIVED,
typename RESULT,
typename OPERAND>
1778 -> std::optional<Expr<RESULT>> {
1779 const int kind{operation.kind()};
1780 auto &expr{operation.left()};
1781 expr = Fold(context, std::move(expr));
1782 if (expr.Rank() > 0) {
1783 if (std::optional<Shape> shape{GetShape(context, expr)}) {
1784 if (
auto values{AsFlatArrayConstructor(expr)}) {
1785 return MapOperation(kind, context, std::move(f), *shape,
1786 ComputeResultLength(operation), std::move(*values));
1790 return std::nullopt;
1793template <
typename DERIVED,
typename RESULT,
typename OPERAND>
1794auto ApplyElementwise(
1796 -> std::optional<Expr<RESULT>> {
1797 const int kind{operation.kind()};
1798 return ApplyElementwise(context, operation,
1801 return Expr<RESULT>{DERIVED{kind, std::move(operand)}};
1805template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
1809 -> std::optional<Expr<RESULT>> {
1810 const int kind{operation.kind()};
1811 auto resultLength{ComputeResultLength(operation)};
1812 auto &leftExpr{operation.left()};
1813 auto &rightExpr{operation.right()};
1814 if (leftExpr.Rank() != rightExpr.Rank() && leftExpr.Rank() != 0 &&
1815 rightExpr.Rank() != 0) {
1816 return std::nullopt;
1818 leftExpr = Fold(context, std::move(leftExpr));
1819 rightExpr = Fold(context, std::move(rightExpr));
1820 if (leftExpr.Rank() > 0) {
1821 if (std::optional<Shape> leftShape{GetShape(context, leftExpr)}) {
1822 if (
auto left{AsFlatArrayConstructor(leftExpr)}) {
1823 if (rightExpr.Rank() > 0) {
1824 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1825 if (
auto right{AsFlatArrayConstructor(rightExpr)}) {
1826 if (CheckConformance(context.messages(), *leftShape, *rightShape,
1827 CheckConformanceFlags::EitherScalarExpandable)
1828 .value_or(
false )) {
1829 return MapOperation(kind, context, std::move(f), *leftShape,
1830 std::move(resultLength), std::move(*left),
1833 return std::nullopt;
1835 return MapOperation(kind, context, std::move(f), *leftShape,
1836 std::move(resultLength), std::move(*left), std::move(*right));
1839 }
else if (IsExpandableScalar(rightExpr, context, *leftShape)) {
1840 return MapOperation(kind, context, std::move(f), *leftShape,
1841 std::move(resultLength), std::move(*left), rightExpr);
1845 }
else if (rightExpr.Rank() > 0) {
1846 if (std::optional<Shape> rightShape{GetShape(context, rightExpr)}) {
1847 if (IsExpandableScalar(leftExpr, context, *rightShape)) {
1848 if (
auto right{AsFlatArrayConstructor(rightExpr)}) {
1849 return MapOperation(kind, context, std::move(f), *rightShape,
1850 std::move(resultLength), leftExpr, std::move(*right));
1855 return std::nullopt;
1858template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
1859auto ApplyElementwise(
1861 -> std::optional<Expr<RESULT>> {
1862 const int kind{operation.kind()};
1863 return ApplyElementwise(context, operation,
1867 DERIVED{kind, std::move(left), std::move(right)}};
1873template <
typename TO,
typename FROM>
1874common::IfNoLvalue<std::optional<TO>, FROM> ConvertString(
1875 int toKind, FROM &&s) {
1876 const int fromKind{s.kind()};
1877 if (std::is_same_v<TO, FROM> && toKind == fromKind) {
1878 return std::make_optional<TO>(std::move(s));
1880 return s.ToAscii(toKind);
1884template <
typename TO, TypeCategory FROMCAT>
1887 const int toKind{convert.kind()};
1888 if (
auto array{ApplyElementwise(context, convert)}) {
1892 auto &operand{convert.left()};
1893 const int operandKind{operand.kind()};
1896 TypeCategory
constexpr FromCat{FROMCAT};
1897 if (
auto value{GetScalarConstantValue<Operand>(operand)}) {
1899 const int fromKind{value->kind()};
1900 if constexpr (TO::category == TypeCategory::Integer) {
1901 if constexpr (FromCat == TypeCategory::Integer) {
1902 auto converted{Scalar<TO>::ConvertSigned(toKind, *value)};
1903 if (converted.overflow) {
1904 ctx.Warn(common::UsageWarning::FoldingException,
1905 "conversion of %s_%d to INTEGER(%d) overflowed; result is %s"_warn_en_US,
1906 value->SignedDecimal(), fromKind, toKind,
1907 converted.value.SignedDecimal());
1909 return MakeConstantExpr<TO>(toKind, std::move(converted.value));
1910 }
else if constexpr (FromCat == TypeCategory::Unsigned) {
1911 auto converted{Scalar<TO>::ConvertUnsigned(toKind, *value)};
1912 if ((converted.overflow || converted.value.IsNegative())) {
1913 ctx.Warn(common::UsageWarning::FoldingException,
1914 "conversion of %s_U%d to INTEGER(%d) overflowed; result is %s"_warn_en_US,
1915 value->UnsignedDecimal(), fromKind, toKind,
1916 converted.value.SignedDecimal());
1918 return MakeConstantExpr<TO>(toKind, std::move(converted.value));
1919 }
else if constexpr (FromCat == TypeCategory::Real) {
1920 auto converted{value->ToInteger(
1921 common::RoundingMode::ToZero, Scalar<TO>::bits(toKind))};
1922 if (converted.flags.test(RealFlag::InvalidArgument)) {
1923 ctx.Warn(common::UsageWarning::FoldingException,
1924 "REAL(%d) to INTEGER(%d) conversion: invalid argument"_warn_en_US,
1926 }
else if (converted.flags.test(RealFlag::Overflow)) {
1927 ctx.Warn(common::UsageWarning::FoldingException,
1928 "REAL(%d) to INTEGER(%d) conversion overflowed"_warn_en_US,
1931 return MakeConstantExpr<TO>(toKind, std::move(converted.value));
1933 }
else if constexpr (TO::category == TypeCategory::Unsigned) {
1934 if constexpr (FromCat == TypeCategory::Integer ||
1935 FromCat == TypeCategory::Unsigned) {
1936 return MakeConstantExpr<TO>(
1937 toKind, Scalar<TO>::ConvertUnsigned(toKind, *value).value);
1938 }
else if constexpr (FromCat == TypeCategory::Real) {
1939 return MakeConstantExpr<TO>(toKind,
1942 common::RoundingMode::ToZero, Scalar<TO>::bits(toKind))
1945 }
else if constexpr (TO::category == TypeCategory::Real) {
1946 if constexpr (FromCat == TypeCategory::Integer ||
1947 FromCat == TypeCategory::Unsigned) {
1948 auto converted{Scalar<TO>::FromInteger(
1949 toKind, *value, FromCat == TypeCategory::Unsigned)};
1950 if (!converted.flags.empty()) {
1952 std::snprintf(buffer,
sizeof buffer,
1953 "INTEGER(%d) to REAL(%d) conversion", fromKind, toKind);
1954 ctx.RealFlagWarnings(converted.flags, buffer);
1956 return MakeConstantExpr<TO>(toKind, std::move(converted.value));
1957 }
else if constexpr (FromCat == TypeCategory::Real) {
1958 auto converted{Scalar<TO>::Convert(toKind, *value)};
1960 if (!converted.flags.empty()) {
1961 std::snprintf(buffer,
sizeof buffer,
1962 "REAL(%d) to REAL(%d) conversion", fromKind, toKind);
1963 ctx.RealFlagWarnings(converted.flags, buffer);
1965 if (ctx.targetCharacteristics().areSubnormalsFlushedToZero()) {
1966 converted.value = converted.value.FlushSubnormalToZero();
1968 return MakeConstantExpr<TO>(toKind, std::move(converted.value));
1970 }
else if constexpr (TO::category == TypeCategory::Complex) {
1971 if constexpr (FromCat == TypeCategory::Complex) {
1972 auto real{value->REAL()};
1973 auto imag{value->AIMAG()};
1974 return FoldOperation(ctx,
1979 real.kind(), real})))),
1983 imag.kind(), imag}))))});
1985 }
else if constexpr (TO::category == TypeCategory::Character &&
1986 FromCat == TypeCategory::Character) {
1988 ConvertString<Scalar<TO>>(toKind, std::move(*value))}) {
1989 return ScalarConstantToExpr(std::move(*converted));
1991 }
else if constexpr (TO::category == TypeCategory::Logical &&
1992 FromCat == TypeCategory::Logical) {
1993 return MakeConstantExpr<TO>(toKind, value->IsTrue());
1995 }
else if constexpr (TO::category == FromCat &&
1996 FromCat != TypeCategory::Character) {
1998 if (Operand::category == TO::category && toKind == operandKind) {
1999 return std::move(operand);
2000 }
else if constexpr (TO::category == TypeCategory::Logical ||
2001 TO::category == TypeCategory::Integer) {
2002 if (
auto *innerConv{
2003 std::get_if<Convert<Operand, TO::category>>(&operand.u)}) {
2005 if (
auto *x{&innerConv->left()}; x->kind() == toKind) {
2006 if (TO::category == TypeCategory::Logical || toKind <= operandKind) {
2007 return std::move(*x);
2009 }
else if constexpr (std::is_same_v<TO, DescriptorInquiry::Result>) {
2010 if (toKind == DescriptorInquiry::kind()) {
2011 if (std::holds_alternative<DescriptorInquiry>(x->u) ||
2012 std::holds_alternative<TypeParamInquiry>(x->u)) {
2014 return std::move(*x);
2022 return Expr<TO>{std::move(convert)};
2025template <
typename T>
2027 const int kind{x.kind()};
2028 auto &operand{x.left()};
2029 operand = Fold(context, std::move(operand));
2030 if (
auto value{GetScalarConstantValue<T>(kind, operand)}) {
2035 return std::move(operand);
2041template <
typename T>
2043 const int kind{x.kind()};
2044 if (
auto array{ApplyElementwise(context, x)}) {
2047 auto &operand{x.left()};
2048 if (
auto *nn{std::get_if<Negate<T>>(&x.left().u)}; nn && nn->kind() == kind) {
2050 if (IsVariable(nn->left())) {
2051 return FoldOperation(context,
Parentheses<T>{std::move(nn->left())});
2053 return std::move(nn->left());
2055 }
else if (
auto value{GetScalarConstantValue<T>(kind, operand)}) {
2056 if constexpr (T::category == TypeCategory::Integer) {
2057 auto negated{value->Negate()};
2058 if (negated.overflow) {
2059 context.Warn(common::UsageWarning::FoldingException,
2060 "INTEGER(%d) negation overflowed"_warn_en_US, kind);
2063 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2075template <
typename LEFT,
typename RIGHT>
2076std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
2078 if (
auto xvalue{GetScalarConstantValue<LEFT>(x)}) {
2079 if (
auto yvalue{GetScalarConstantValue<RIGHT>(y)}) {
2080 return {std::make_pair(*xvalue, *yvalue)};
2083 return std::nullopt;
2086template <
typename DERIVED,
typename RESULT,
typename LEFT,
typename RIGHT>
2087std::optional<std::pair<Scalar<LEFT>, Scalar<RIGHT>>> OperandsAreConstants(
2089 return OperandsAreConstants(operation.left(), operation.right());
2092template <
typename T>
2094 const int kind{x.kind()};
2095 if (
auto array{ApplyElementwise(context, x)}) {
2098 if (
auto folded{OperandsAreConstants(x)}) {
2099 if constexpr (T::category == TypeCategory::Integer) {
2100 auto sum{folded->first.AddSigned(folded->second)};
2102 context.Warn(common::UsageWarning::FoldingException,
2103 "INTEGER(%d) addition overflowed"_warn_en_US, kind);
2106 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2108 Constant<T>{kind, folded->first.AddUnsigned(folded->second).value}};
2110 auto sum{folded->first.Add(
2111 folded->second, context.targetCharacteristics().roundingMode())};
2112 context.RealFlagWarnings(sum.flags,
"addition");
2113 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2114 sum.value = sum.value.FlushSubnormalToZero();
2118 }
else if constexpr (T::category == TypeCategory::Integer ||
2119 T::category == TypeCategory::Unsigned) {
2120 if (
auto c{GetScalarConstantValue<T>(kind, x.right())}) {
2121 if (c->IsZero() && x.left().Rank() == 0) {
2122 if (IsVariable(x.left())) {
2123 return FoldOperation(context,
Parentheses<T>{std::move(x.left())});
2125 return std::move(x.left());
2128 }
else if (
auto c{GetScalarConstantValue<T>(kind, x.left())}) {
2129 if (c->IsZero() && x.right().Rank() == 0) {
2130 if (IsVariable(x.right())) {
2131 return FoldOperation(context,
Parentheses<T>{std::move(x.right())});
2133 return std::move(x.right());
2141template <
typename T>
2143 const int kind{x.kind()};
2144 if (
auto array{ApplyElementwise(context, x)}) {
2147 if (
auto folded{OperandsAreConstants(x)}) {
2148 if constexpr (T::category == TypeCategory::Integer) {
2149 auto difference{folded->first.SubtractSigned(folded->second)};
2150 if (difference.overflow) {
2151 context.Warn(common::UsageWarning::FoldingException,
2152 "INTEGER(%d) subtraction overflowed"_warn_en_US, kind);
2155 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2157 kind, folded->first.SubtractSigned(folded->second).value}};
2159 auto difference{folded->first.Subtract(
2160 folded->second, context.targetCharacteristics().roundingMode())};
2161 context.RealFlagWarnings(difference.flags,
"subtraction");
2162 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2163 difference.value = difference.value.FlushSubnormalToZero();
2167 }
else if constexpr (T::category == TypeCategory::Integer ||
2168 T::category == TypeCategory::Unsigned) {
2169 if (
auto c{GetScalarConstantValue<T>(kind, x.right())}) {
2170 if (c->IsZero() && x.left().Rank() == 0) {
2171 if (IsVariable(x.left())) {
2172 return FoldOperation(context,
Parentheses<T>{std::move(x.left())});
2174 return std::move(x.left());
2182template <
typename T>
2184 const int kind{x.kind()};
2185 if (
auto array{ApplyElementwise(context, x)}) {
2188 if (
auto folded{OperandsAreConstants(x)}) {
2189 if constexpr (T::category == TypeCategory::Integer) {
2190 auto product{folded->first.MultiplySigned(folded->second)};
2191 if (product.SignedMultiplicationOverflowed()) {
2192 context.Warn(common::UsageWarning::FoldingException,
2193 "INTEGER(%d) multiplication overflowed"_warn_en_US, kind);
2196 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2198 kind, folded->first.MultiplyUnsigned(folded->second).lower}};
2200 auto product{folded->first.Multiply(
2201 folded->second, context.targetCharacteristics().roundingMode())};
2202 context.RealFlagWarnings(product.flags,
"multiplication");
2203 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2204 product.value = product.value.FlushSubnormalToZero();
2208 }
else if constexpr (T::category == TypeCategory::Integer) {
2209 if (
auto c{GetScalarConstantValue<T>(kind, x.right())}) {
2210 x.right() = std::move(x.left());
2211 x.left() = MakeConstantExpr<T>(kind, *c);
2213 if (
auto c{GetScalarConstantValue<T>(kind, x.left())}) {
2214 if (c->IsZero() && x.right().Rank() == 0) {
2215 return std::move(x.left());
2218 if (IsVariable(x.right())) {
2219 return FoldOperation(context,
Parentheses<T>{std::move(x.right())});
2221 return std::move(x.right());
2225 return FoldOperation(context,
Negate<T>{std::move(x.right())});
2232template <
typename T>
2234 const int kind{x.kind()};
2235 if (
auto array{ApplyElementwise(context, x)}) {
2238 if (
auto folded{OperandsAreConstants(x)}) {
2239 if constexpr (T::category == TypeCategory::Integer) {
2240 auto quotAndRem{folded->first.DivideSigned(folded->second)};
2241 if (quotAndRem.divisionByZero) {
2242 context.Warn(common::UsageWarning::FoldingException,
2243 "INTEGER(%d) division by zero"_warn_en_US, kind);
2246 if (quotAndRem.overflow) {
2247 context.Warn(common::UsageWarning::FoldingException,
2248 "INTEGER(%d) division overflowed"_warn_en_US, kind);
2251 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2252 auto quotAndRem{folded->first.DivideUnsigned(folded->second)};
2253 if (quotAndRem.divisionByZero) {
2254 context.Warn(common::UsageWarning::FoldingException,
2255 "UNSIGNED(%d) division by zero"_warn_en_US, kind);
2260 auto quotient{folded->first.Divide(
2261 folded->second, context.targetCharacteristics().roundingMode())};
2265 bool isCanonicalNaNOrInf{
false};
2266 if constexpr (T::category == TypeCategory::Real) {
2267 if (folded->second.IsZero() && context.moduleFileName().has_value()) {
2268 using IntType =
typename T::Scalar::Word;
2269 auto intNumerator{folded->first.ToInteger()};
2270 const int intKind{intNumerator.value.kind()};
2271 isCanonicalNaNOrInf = intNumerator.flags == RealFlags{} &&
2272 intNumerator.value >= IntType{intKind, -1} &&
2273 intNumerator.value <= IntType{intKind, 1};
2276 if (!isCanonicalNaNOrInf) {
2277 context.RealFlagWarnings(quotient.flags,
"division");
2279 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2280 quotient.value = quotient.value.FlushSubnormalToZero();
2288template <
typename T>
2290 const int kind{x.kind()};
2291 if (
auto array{ApplyElementwise(context, x)}) {
2294 if (
auto folded{OperandsAreConstants(x)}) {
2295 if constexpr (T::category == TypeCategory::Integer) {
2296 auto power{folded->first.Power(folded->second)};
2297 if (power.divisionByZero) {
2298 context.Warn(common::UsageWarning::FoldingException,
2299 "INTEGER(%d) zero to negative power"_warn_en_US, kind);
2300 }
else if (power.overflow) {
2301 context.Warn(common::UsageWarning::FoldingException,
2302 "INTEGER(%d) power overflowed"_warn_en_US, kind);
2303 }
else if (power.zeroToZero) {
2304 context.Warn(common::UsageWarning::FoldingException,
2305 "INTEGER(%d) 0**0 is not defined"_warn_en_US, kind);
2309 if (folded->first.IsZero()) {
2310 if (folded->second.IsZero()) {
2311 context.Warn(common::UsageWarning::FoldingException,
2312 "REAL/COMPLEX 0**0 is not defined"_warn_en_US);
2317 }
else if (
auto callable{GetHostRuntimeWrapper<T, T, T>(
2318 kind, {kind, kind},
"pow")}) {
2320 kind, (*callable)(context, folded->first, folded->second)}};
2322 context.Warn(common::UsageWarning::FoldingFailure,
2323 "Power for %s cannot be folded on host"_warn_en_US,
2331template <
typename T>
2333 const int kind{x.kind()};
2334 if (
auto array{ApplyElementwise(context, x)}) {
2337 if (
auto folded{OperandsAreConstants(x.left(), x.right())}) {
2339 if constexpr (T::category == TypeCategory::Complex) {
2344 using DoubleComplex = Scalar<Type<TypeCategory::Complex>>;
2345 using DoublePart = DoubleComplex::Part;
2346 using SinglePart =
typename Scalar<T>::Part;
2348 DoubleComplex wideBase{
2349 DoublePart::Convert(8, folded->first.REAL()).value,
2350 DoublePart::Convert(8, folded->first.AIMAG()).value};
2351 auto wide{evaluate::IntPower(wideBase, folded->second)};
2352 power.flags = wide.flags;
2353 power.value = Scalar<T>{SinglePart::Convert(kind, wide.value.REAL())
2354 .AccumulateFlags(power.flags),
2355 SinglePart::Convert(kind, wide.value.AIMAG())
2356 .AccumulateFlags(power.flags)};
2358 power = evaluate::IntPower(folded->first, folded->second);
2361 power = evaluate::IntPower(folded->first, folded->second);
2363 context.RealFlagWarnings(power.flags,
"power with INTEGER exponent");
2364 if (context.targetCharacteristics().areSubnormalsFlushedToZero()) {
2365 power.value = power.value.FlushSubnormalToZero();
2372template <
typename T>
2374 x.condition() = Fold(context, std::move(x.condition()));
2376 if (
auto cst{GetScalarConstantValue<LogicalResult>(
2377 LogicalResultKind, x.condition())}) {
2378 return cst->IsTrue() ? Fold(context, std::move(x.thenValue()))
2379 : Fold(context, std::move(x.elseValue()));
2384template <
typename T>
2386 const int kind{x.kind()};
2387 if (
auto array{ApplyElementwise(context, x,
2391 Extremum<T>{ordering, std::move(l), std::move(r)}};
2395 if (
auto folded{OperandsAreConstants(x)}) {
2396 if constexpr (T::category == TypeCategory::Integer) {
2397 if (folded->first.CompareSigned(folded->second) == x.ordering) {
2400 }
else if constexpr (T::category == TypeCategory::Unsigned) {
2401 if (folded->first.CompareUnsigned(folded->second) == x.ordering) {
2404 }
else if constexpr (T::category == TypeCategory::Real) {
2405 if (folded->first.IsNotANumber() ||
2406 (folded->first.Compare(folded->second) == Relation::Less) ==
2407 (x.ordering == Ordering::Less)) {
2411 static_assert(T::category == TypeCategory::Character);
2414 auto maxLen{std::max(folded->first.length(), folded->second.length())};
2415 bool isFirst{x.ordering == Compare(folded->first, folded->second)};
2416 auto res{isFirst ? std::move(folded->first) : std::move(folded->second)};
2417 res = res.length() == maxLen ? std::move(res)
2418 : CharacterUtils::Resize(res, maxLen);
2433 if constexpr (T::category == TypeCategory::Integer ||
2434 T::category == TypeCategory::Unsigned) {
2435 auto absorbs{[&](
const Expr<T> &operand,
const Expr<T> &nested) {
2436 const auto *c{std::get_if<Constant<T>>(&operand.u)};
2437 const auto *inner{std::get_if<Extremum<T>>(&nested.u)};
2438 if (!c || !inner || inner->ordering != x.ordering) {
2441 auto isSameConstant{[&](
const Expr<T> &y) {
2442 const auto *ic{std::get_if<Constant<T>>(&y.u)};
2443 return ic && *ic == *c;
2445 return isSameConstant(inner->left()) || isSameConstant(inner->right());
2447 if (absorbs(x.left(), x.right())) {
2448 return Expr<T>{std::move(x.right())};
2449 }
else if (absorbs(x.right(), x.left())) {
2450 return Expr<T>{std::move(x.left())};
2459template <
typename T>
2461 return common::visit(
2463 if constexpr (IsSpecificIntrinsicType<T>) {
2464 return FoldOperation(context, std::move(x));
2465 }
else if constexpr (std::is_same_v<T, Type<TypeCategory::Derived>>) {
2466 return FoldOperation(context, std::move(x));
2467 }
else if constexpr (common::HasMember<
decltype(x),
2468 TypelessExpression>) {
2469 return std::move(expr);
2471 return Expr<T>{Fold(context, std::move(x))};
Definition expression.h:512
Definition expression.h:540
Definition variable.h:209
Definition variable.h:247
Definition variable.h:362
Definition expression.h:415
Definition constant.h:181
Definition variable.h:386
Definition expression.h:64
Definition fold-implementation.h:54
Definition expression.h:478
Definition variable.h:101
Definition expression.h:114
Definition variable.h:488
Definition expression.h:853
Definition variable.h:309
Definition variable.h:165
Definition variable.h:136
Definition integer-value.h:35
Definition ParserActions.h:24
Definition expression.h:309
Definition expression.h:506
Definition expression.h:275
Definition expression.h:373
Definition expression.h:218
Definition variable.h:293
Definition expression.h:330
Definition expression.h:354
Definition expression.h:464
Definition expression.h:323
Definition expression.h:263
Definition expression.h:237
Definition expression.h:337
Definition expression.h:346
Definition variable.h:196
Definition expression.h:316