1 //===-- lib/Evaluate/fold-integer.cpp -------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "fold-implementation.h"
10 #include "fold-reduction.h"
11 #include "flang/Evaluate/check-expression.h"
12 
13 namespace Fortran::evaluate {
14 
15 // Class to retrieve the constant lower bound of an expression which is an
16 // array that devolves to a type of Constant<T>
17 class GetConstantArrayLboundHelper {
18 public:
19   GetConstantArrayLboundHelper(ConstantSubscript dim) : dim_{dim} {}
20 
21   template <typename T> ConstantSubscript GetLbound(const T &) {
22     // The method is needed for template expansion, but we should never get
23     // here in practice.
24     CHECK(false);
25     return 0;
26   }
27 
28   template <typename T> ConstantSubscript GetLbound(const Constant<T> &x) {
29     // Return the lower bound
30     return x.lbounds()[dim_];
31   }
32 
33   template <typename T> ConstantSubscript GetLbound(const Parentheses<T> &x) {
34     // Strip off the parentheses
35     return GetLbound(x.left());
36   }
37 
38   template <typename T> ConstantSubscript GetLbound(const Expr<T> &x) {
39     // recurse through Expr<T>'a until we hit a constant
40     return std::visit([&](const auto &inner) { return GetLbound(inner); },
41         //      [&](const auto &) { return 0; },
42         x.u);
43   }
44 
45 private:
46   ConstantSubscript dim_;
47 };
48 
49 template <int KIND>
50 Expr<Type<TypeCategory::Integer, KIND>> LBOUND(FoldingContext &context,
51     FunctionRef<Type<TypeCategory::Integer, KIND>> &&funcRef) {
52   using T = Type<TypeCategory::Integer, KIND>;
53   ActualArguments &args{funcRef.arguments()};
54   if (const auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) {
55     if (int rank{array->Rank()}; rank > 0) {
56       std::optional<int> dim;
57       if (funcRef.Rank() == 0) {
58         // Optional DIM= argument is present: result is scalar.
59         if (auto dim64{GetInt64Arg(args[1])}) {
60           if (*dim64 < 1 || *dim64 > rank) {
61             context.messages().Say("DIM=%jd dimension is out of range for "
62                                    "rank-%d array"_err_en_US,
63                 *dim64, rank);
64             return MakeInvalidIntrinsic<T>(std::move(funcRef));
65           } else {
66             dim = *dim64 - 1; // 1-based to 0-based
67           }
68         } else {
69           // DIM= is present but not constant
70           return Expr<T>{std::move(funcRef)};
71         }
72       }
73       bool lowerBoundsAreOne{true};
74       if (auto named{ExtractNamedEntity(*array)}) {
75         const Symbol &symbol{named->GetLastSymbol()};
76         if (symbol.Rank() == rank) {
77           lowerBoundsAreOne = false;
78           if (dim) {
79             return Fold(context,
80                 ConvertToType<T>(GetLowerBound(context, *named, *dim)));
81           } else if (auto extents{
82                          AsExtentArrayExpr(GetLowerBounds(context, *named))}) {
83             return Fold(context,
84                 ConvertToType<T>(Expr<ExtentType>{std::move(*extents)}));
85           }
86         } else {
87           lowerBoundsAreOne = symbol.Rank() == 0; // LBOUND(array%component)
88         }
89       }
90       if (IsActuallyConstant(*array)) {
91         return Expr<T>{GetConstantArrayLboundHelper{*dim}.GetLbound(*array)};
92       }
93       if (lowerBoundsAreOne) {
94         if (dim) {
95           return Expr<T>{1};
96         } else {
97           std::vector<Scalar<T>> ones(rank, Scalar<T>{1});
98           return Expr<T>{
99               Constant<T>{std::move(ones), ConstantSubscripts{rank}}};
100         }
101       }
102     }
103   }
104   return Expr<T>{std::move(funcRef)};
105 }
106 
107 template <int KIND>
108 Expr<Type<TypeCategory::Integer, KIND>> UBOUND(FoldingContext &context,
109     FunctionRef<Type<TypeCategory::Integer, KIND>> &&funcRef) {
110   using T = Type<TypeCategory::Integer, KIND>;
111   ActualArguments &args{funcRef.arguments()};
112   if (auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) {
113     if (int rank{array->Rank()}; rank > 0) {
114       std::optional<int> dim;
115       if (funcRef.Rank() == 0) {
116         // Optional DIM= argument is present: result is scalar.
117         if (auto dim64{GetInt64Arg(args[1])}) {
118           if (*dim64 < 1 || *dim64 > rank) {
119             context.messages().Say("DIM=%jd dimension is out of range for "
120                                    "rank-%d array"_err_en_US,
121                 *dim64, rank);
122             return MakeInvalidIntrinsic<T>(std::move(funcRef));
123           } else {
124             dim = *dim64 - 1; // 1-based to 0-based
125           }
126         } else {
127           // DIM= is present but not constant
128           return Expr<T>{std::move(funcRef)};
129         }
130       }
131       bool takeBoundsFromShape{true};
132       if (auto named{ExtractNamedEntity(*array)}) {
133         const Symbol &symbol{named->GetLastSymbol()};
134         if (symbol.Rank() == rank) {
135           takeBoundsFromShape = false;
136           if (dim) {
137             if (semantics::IsAssumedSizeArray(symbol) && *dim == rank - 1) {
138               context.messages().Say("DIM=%jd dimension is out of range for "
139                                      "rank-%d assumed-size array"_err_en_US,
140                   rank, rank);
141               return MakeInvalidIntrinsic<T>(std::move(funcRef));
142             } else if (auto ub{GetUpperBound(context, *named, *dim)}) {
143               return Fold(context, ConvertToType<T>(std::move(*ub)));
144             }
145           } else {
146             Shape ubounds{GetUpperBounds(context, *named)};
147             if (semantics::IsAssumedSizeArray(symbol)) {
148               CHECK(!ubounds.back());
149               ubounds.back() = ExtentExpr{-1};
150             }
151             if (auto extents{AsExtentArrayExpr(ubounds)}) {
152               return Fold(context,
153                   ConvertToType<T>(Expr<ExtentType>{std::move(*extents)}));
154             }
155           }
156         } else {
157           takeBoundsFromShape = symbol.Rank() == 0; // UBOUND(array%component)
158         }
159       }
160       if (takeBoundsFromShape) {
161         if (auto shape{GetContextFreeShape(context, *array)}) {
162           if (dim) {
163             if (auto &dimSize{shape->at(*dim)}) {
164               return Fold(context,
165                   ConvertToType<T>(Expr<ExtentType>{std::move(*dimSize)}));
166             }
167           } else if (auto shapeExpr{AsExtentArrayExpr(*shape)}) {
168             return Fold(context, ConvertToType<T>(std::move(*shapeExpr)));
169           }
170         }
171       }
172     }
173   }
174   return Expr<T>{std::move(funcRef)};
175 }
176 
177 // COUNT()
178 template <typename T>
179 static Expr<T> FoldCount(FoldingContext &context, FunctionRef<T> &&ref) {
180   static_assert(T::category == TypeCategory::Integer);
181   ActualArguments &arg{ref.arguments()};
182   if (const Constant<LogicalResult> *mask{arg.empty()
183               ? nullptr
184               : Folder<LogicalResult>{context}.Folding(arg[0])}) {
185     std::optional<int> dim;
186     if (CheckReductionDIM(dim, context, arg, 1, mask->Rank())) {
187       auto accumulator{[&](Scalar<T> &element, const ConstantSubscripts &at) {
188         if (mask->At(at).IsTrue()) {
189           element = element.AddSigned(Scalar<T>{1}).value;
190         }
191       }};
192       return Expr<T>{DoReduction<T>(*mask, dim, Scalar<T>{}, accumulator)};
193     }
194   }
195   return Expr<T>{std::move(ref)};
196 }
197 
198 // FINDLOC(), MAXLOC(), & MINLOC()
199 enum class WhichLocation { Findloc, Maxloc, Minloc };
200 template <WhichLocation WHICH> class LocationHelper {
201 public:
202   LocationHelper(
203       DynamicType &&type, ActualArguments &arg, FoldingContext &context)
204       : type_{type}, arg_{arg}, context_{context} {}
205   using Result = std::optional<Constant<SubscriptInteger>>;
206   using Types = std::conditional_t<WHICH == WhichLocation::Findloc,
207       AllIntrinsicTypes, RelationalTypes>;
208 
209   template <typename T> Result Test() const {
210     if (T::category != type_.category() || T::kind != type_.kind()) {
211       return std::nullopt;
212     }
213     CHECK(arg_.size() == (WHICH == WhichLocation::Findloc ? 6 : 5));
214     Folder<T> folder{context_};
215     Constant<T> *array{folder.Folding(arg_[0])};
216     if (!array) {
217       return std::nullopt;
218     }
219     std::optional<Constant<T>> value;
220     if constexpr (WHICH == WhichLocation::Findloc) {
221       if (const Constant<T> *p{folder.Folding(arg_[1])}) {
222         value.emplace(*p);
223       } else {
224         return std::nullopt;
225       }
226     }
227     std::optional<int> dim;
228     Constant<LogicalResult> *mask{
229         GetReductionMASK(arg_[maskArg], array->shape(), context_)};
230     if ((!mask && arg_[maskArg]) ||
231         !CheckReductionDIM(dim, context_, arg_, dimArg, array->Rank())) {
232       return std::nullopt;
233     }
234     bool back{false};
235     if (arg_[backArg]) {
236       const auto *backConst{
237           Folder<LogicalResult>{context_}.Folding(arg_[backArg])};
238       if (backConst) {
239         back = backConst->GetScalarValue().value().IsTrue();
240       } else {
241         return std::nullopt;
242       }
243     }
244     const RelationalOperator relation{WHICH == WhichLocation::Findloc
245             ? RelationalOperator::EQ
246             : WHICH == WhichLocation::Maxloc
247             ? (back ? RelationalOperator::GE : RelationalOperator::GT)
248             : back ? RelationalOperator::LE
249                    : RelationalOperator::LT};
250     // Use lower bounds of 1 exclusively.
251     array->SetLowerBoundsToOne();
252     ConstantSubscripts at{array->lbounds()}, maskAt, resultIndices, resultShape;
253     if (mask) {
254       mask->SetLowerBoundsToOne();
255       maskAt = mask->lbounds();
256     }
257     if (dim) { // DIM=
258       if (*dim < 1 || *dim > array->Rank()) {
259         context_.messages().Say("DIM=%d is out of range"_err_en_US, *dim);
260         return std::nullopt;
261       }
262       int zbDim{*dim - 1};
263       resultShape = array->shape();
264       resultShape.erase(
265           resultShape.begin() + zbDim); // scalar if array is vector
266       ConstantSubscript dimLength{array->shape()[zbDim]};
267       ConstantSubscript n{GetSize(resultShape)};
268       for (ConstantSubscript j{0}; j < n; ++j) {
269         ConstantSubscript hit{0};
270         if constexpr (WHICH == WhichLocation::Maxloc ||
271             WHICH == WhichLocation::Minloc) {
272           value.reset();
273         }
274         for (ConstantSubscript k{0}; k < dimLength;
275              ++k, ++at[zbDim], mask && ++maskAt[zbDim]) {
276           if ((!mask || mask->At(maskAt).IsTrue()) &&
277               IsHit(array->At(at), value, relation)) {
278             hit = at[zbDim];
279             if constexpr (WHICH == WhichLocation::Findloc) {
280               if (!back) {
281                 break;
282               }
283             }
284           }
285         }
286         resultIndices.emplace_back(hit);
287         at[zbDim] = dimLength;
288         array->IncrementSubscripts(at);
289         at[zbDim] = 1;
290         if (mask) {
291           maskAt[zbDim] = mask->lbounds()[zbDim] + dimLength - 1;
292           mask->IncrementSubscripts(maskAt);
293           maskAt[zbDim] = mask->lbounds()[zbDim];
294         }
295       }
296     } else { // no DIM=
297       resultShape = ConstantSubscripts{array->Rank()}; // always a vector
298       ConstantSubscript n{GetSize(array->shape())};
299       resultIndices = ConstantSubscripts(array->Rank(), 0);
300       for (ConstantSubscript j{0}; j < n; ++j, array->IncrementSubscripts(at),
301            mask && mask->IncrementSubscripts(maskAt)) {
302         if ((!mask || mask->At(maskAt).IsTrue()) &&
303             IsHit(array->At(at), value, relation)) {
304           resultIndices = at;
305           if constexpr (WHICH == WhichLocation::Findloc) {
306             if (!back) {
307               break;
308             }
309           }
310         }
311       }
312     }
313     std::vector<Scalar<SubscriptInteger>> resultElements;
314     for (ConstantSubscript j : resultIndices) {
315       resultElements.emplace_back(j);
316     }
317     return Constant<SubscriptInteger>{
318         std::move(resultElements), std::move(resultShape)};
319   }
320 
321 private:
322   template <typename T>
323   bool IsHit(typename Constant<T>::Element element,
324       std::optional<Constant<T>> &value,
325       [[maybe_unused]] RelationalOperator relation) const {
326     std::optional<Expr<LogicalResult>> cmp;
327     bool result{true};
328     if (value) {
329       if constexpr (T::category == TypeCategory::Logical) {
330         // array(at) .EQV. value?
331         static_assert(WHICH == WhichLocation::Findloc);
332         cmp.emplace(
333             ConvertToType<LogicalResult>(Expr<T>{LogicalOperation<T::kind>{
334                 LogicalOperator::Eqv, Expr<T>{Constant<T>{std::move(element)}},
335                 Expr<T>{Constant<T>{*value}}}}));
336       } else { // compare array(at) to value
337         cmp.emplace(
338             PackageRelation(relation, Expr<T>{Constant<T>{std::move(element)}},
339                 Expr<T>{Constant<T>{*value}}));
340       }
341       Expr<LogicalResult> folded{Fold(context_, std::move(*cmp))};
342       result = GetScalarConstantValue<LogicalResult>(folded).value().IsTrue();
343     } else {
344       // first unmasked element for MAXLOC/MINLOC - always take it
345     }
346     if constexpr (WHICH == WhichLocation::Maxloc ||
347         WHICH == WhichLocation::Minloc) {
348       if (result) {
349         value.emplace(std::move(element));
350       }
351     }
352     return result;
353   }
354 
355   static constexpr int dimArg{WHICH == WhichLocation::Findloc ? 2 : 1};
356   static constexpr int maskArg{dimArg + 1};
357   static constexpr int backArg{maskArg + 2};
358 
359   DynamicType type_;
360   ActualArguments &arg_;
361   FoldingContext &context_;
362 };
363 
364 template <WhichLocation which>
365 static std::optional<Constant<SubscriptInteger>> FoldLocationCall(
366     ActualArguments &arg, FoldingContext &context) {
367   if (arg[0]) {
368     if (auto type{arg[0]->GetType()}) {
369       return common::SearchTypes(
370           LocationHelper<which>{std::move(*type), arg, context});
371     }
372   }
373   return std::nullopt;
374 }
375 
376 template <WhichLocation which, typename T>
377 static Expr<T> FoldLocation(FoldingContext &context, FunctionRef<T> &&ref) {
378   static_assert(T::category == TypeCategory::Integer);
379   if (std::optional<Constant<SubscriptInteger>> found{
380           FoldLocationCall<which>(ref.arguments(), context)}) {
381     return Expr<T>{Fold(
382         context, ConvertToType<T>(Expr<SubscriptInteger>{std::move(*found)}))};
383   } else {
384     return Expr<T>{std::move(ref)};
385   }
386 }
387 
388 // for IALL, IANY, & IPARITY
389 template <typename T>
390 static Expr<T> FoldBitReduction(FoldingContext &context, FunctionRef<T> &&ref,
391     Scalar<T> (Scalar<T>::*operation)(const Scalar<T> &) const,
392     Scalar<T> identity) {
393   static_assert(T::category == TypeCategory::Integer);
394   std::optional<int> dim;
395   if (std::optional<Constant<T>> array{
396           ProcessReductionArgs<T>(context, ref.arguments(), dim, identity,
397               /*ARRAY=*/0, /*DIM=*/1, /*MASK=*/2)}) {
398     auto accumulator{[&](Scalar<T> &element, const ConstantSubscripts &at) {
399       element = (element.*operation)(array->At(at));
400     }};
401     return Expr<T>{DoReduction<T>(*array, dim, identity, accumulator)};
402   }
403   return Expr<T>{std::move(ref)};
404 }
405 
406 template <int KIND>
407 Expr<Type<TypeCategory::Integer, KIND>> FoldIntrinsicFunction(
408     FoldingContext &context,
409     FunctionRef<Type<TypeCategory::Integer, KIND>> &&funcRef) {
410   using T = Type<TypeCategory::Integer, KIND>;
411   using Int4 = Type<TypeCategory::Integer, 4>;
412   ActualArguments &args{funcRef.arguments()};
413   auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
414   CHECK(intrinsic);
415   std::string name{intrinsic->name};
416   if (name == "abs") { // incl. babs, iiabs, jiaabs, & kiabs
417     return FoldElementalIntrinsic<T, T>(context, std::move(funcRef),
418         ScalarFunc<T, T>([&context](const Scalar<T> &i) -> Scalar<T> {
419           typename Scalar<T>::ValueWithOverflow j{i.ABS()};
420           if (j.overflow) {
421             context.messages().Say(
422                 "abs(integer(kind=%d)) folding overflowed"_en_US, KIND);
423           }
424           return j.value;
425         }));
426   } else if (name == "bit_size") {
427     return Expr<T>{Scalar<T>::bits};
428   } else if (name == "ceiling" || name == "floor" || name == "nint") {
429     if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
430       // NINT rounds ties away from zero, not to even
431       common::RoundingMode mode{name == "ceiling" ? common::RoundingMode::Up
432               : name == "floor"                   ? common::RoundingMode::Down
433                                 : common::RoundingMode::TiesAwayFromZero};
434       return std::visit(
435           [&](const auto &kx) {
436             using TR = ResultType<decltype(kx)>;
437             return FoldElementalIntrinsic<T, TR>(context, std::move(funcRef),
438                 ScalarFunc<T, TR>([&](const Scalar<TR> &x) {
439                   auto y{x.template ToInteger<Scalar<T>>(mode)};
440                   if (y.flags.test(RealFlag::Overflow)) {
441                     context.messages().Say(
442                         "%s intrinsic folding overflow"_en_US, name);
443                   }
444                   return y.value;
445                 }));
446           },
447           cx->u);
448     }
449   } else if (name == "count") {
450     return FoldCount<T>(context, std::move(funcRef));
451   } else if (name == "digits") {
452     if (const auto *cx{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
453       return Expr<T>{std::visit(
454           [](const auto &kx) {
455             return Scalar<ResultType<decltype(kx)>>::DIGITS;
456           },
457           cx->u)};
458     } else if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
459       return Expr<T>{std::visit(
460           [](const auto &kx) {
461             return Scalar<ResultType<decltype(kx)>>::DIGITS;
462           },
463           cx->u)};
464     } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
465       return Expr<T>{std::visit(
466           [](const auto &kx) {
467             return Scalar<typename ResultType<decltype(kx)>::Part>::DIGITS;
468           },
469           cx->u)};
470     }
471   } else if (name == "dim") {
472     return FoldElementalIntrinsic<T, T, T>(
473         context, std::move(funcRef), &Scalar<T>::DIM);
474   } else if (name == "dshiftl" || name == "dshiftr") {
475     const auto fptr{
476         name == "dshiftl" ? &Scalar<T>::DSHIFTL : &Scalar<T>::DSHIFTR};
477     // Third argument can be of any kind. However, it must be smaller or equal
478     // than BIT_SIZE. It can be converted to Int4 to simplify.
479     return FoldElementalIntrinsic<T, T, T, Int4>(context, std::move(funcRef),
480         ScalarFunc<T, T, T, Int4>(
481             [&fptr](const Scalar<T> &i, const Scalar<T> &j,
482                 const Scalar<Int4> &shift) -> Scalar<T> {
483               return std::invoke(fptr, i, j, static_cast<int>(shift.ToInt64()));
484             }));
485   } else if (name == "exponent") {
486     if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
487       return std::visit(
488           [&funcRef, &context](const auto &x) -> Expr<T> {
489             using TR = typename std::decay_t<decltype(x)>::Result;
490             return FoldElementalIntrinsic<T, TR>(context, std::move(funcRef),
491                 &Scalar<TR>::template EXPONENT<Scalar<T>>);
492           },
493           sx->u);
494     } else {
495       DIE("exponent argument must be real");
496     }
497   } else if (name == "findloc") {
498     return FoldLocation<WhichLocation::Findloc, T>(context, std::move(funcRef));
499   } else if (name == "huge") {
500     return Expr<T>{Scalar<T>::HUGE()};
501   } else if (name == "iachar" || name == "ichar") {
502     auto *someChar{UnwrapExpr<Expr<SomeCharacter>>(args[0])};
503     CHECK(someChar);
504     if (auto len{ToInt64(someChar->LEN())}) {
505       if (len.value() != 1) {
506         // Do not die, this was not checked before
507         context.messages().Say(
508             "Character in intrinsic function %s must have length one"_en_US,
509             name);
510       } else {
511         return std::visit(
512             [&funcRef, &context](const auto &str) -> Expr<T> {
513               using Char = typename std::decay_t<decltype(str)>::Result;
514               return FoldElementalIntrinsic<T, Char>(context,
515                   std::move(funcRef),
516                   ScalarFunc<T, Char>([](const Scalar<Char> &c) {
517                     return Scalar<T>{CharacterUtils<Char::kind>::ICHAR(c)};
518                   }));
519             },
520             someChar->u);
521       }
522     }
523   } else if (name == "iand" || name == "ior" || name == "ieor") {
524     auto fptr{&Scalar<T>::IAND};
525     if (name == "iand") { // done in fptr declaration
526     } else if (name == "ior") {
527       fptr = &Scalar<T>::IOR;
528     } else if (name == "ieor") {
529       fptr = &Scalar<T>::IEOR;
530     } else {
531       common::die("missing case to fold intrinsic function %s", name.c_str());
532     }
533     return FoldElementalIntrinsic<T, T, T>(
534         context, std::move(funcRef), ScalarFunc<T, T, T>(fptr));
535   } else if (name == "iall") {
536     return FoldBitReduction(
537         context, std::move(funcRef), &Scalar<T>::IAND, Scalar<T>{}.NOT());
538   } else if (name == "iany") {
539     return FoldBitReduction(
540         context, std::move(funcRef), &Scalar<T>::IOR, Scalar<T>{});
541   } else if (name == "ibclr" || name == "ibset") {
542     // Second argument can be of any kind. However, it must be smaller
543     // than BIT_SIZE. It can be converted to Int4 to simplify.
544     auto fptr{&Scalar<T>::IBCLR};
545     if (name == "ibclr") { // done in fptr definition
546     } else if (name == "ibset") {
547       fptr = &Scalar<T>::IBSET;
548     } else {
549       common::die("missing case to fold intrinsic function %s", name.c_str());
550     }
551     return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
552         ScalarFunc<T, T, Int4>([&](const Scalar<T> &i,
553                                    const Scalar<Int4> &pos) -> Scalar<T> {
554           auto posVal{static_cast<int>(pos.ToInt64())};
555           if (posVal < 0) {
556             context.messages().Say(
557                 "bit position for %s (%d) is negative"_err_en_US, name, posVal);
558           } else if (posVal >= i.bits) {
559             context.messages().Say(
560                 "bit position for %s (%d) is not less than %d"_err_en_US, name,
561                 posVal, i.bits);
562           }
563           return std::invoke(fptr, i, posVal);
564         }));
565   } else if (name == "index" || name == "scan" || name == "verify") {
566     if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
567       return std::visit(
568           [&](const auto &kch) -> Expr<T> {
569             using TC = typename std::decay_t<decltype(kch)>::Result;
570             if (UnwrapExpr<Expr<SomeLogical>>(args[2])) { // BACK=
571               return FoldElementalIntrinsic<T, TC, TC, LogicalResult>(context,
572                   std::move(funcRef),
573                   ScalarFunc<T, TC, TC, LogicalResult>{
574                       [&name](const Scalar<TC> &str, const Scalar<TC> &other,
575                           const Scalar<LogicalResult> &back) -> Scalar<T> {
576                         return name == "index"
577                             ? CharacterUtils<TC::kind>::INDEX(
578                                   str, other, back.IsTrue())
579                             : name == "scan" ? CharacterUtils<TC::kind>::SCAN(
580                                                    str, other, back.IsTrue())
581                                              : CharacterUtils<TC::kind>::VERIFY(
582                                                    str, other, back.IsTrue());
583                       }});
584             } else {
585               return FoldElementalIntrinsic<T, TC, TC>(context,
586                   std::move(funcRef),
587                   ScalarFunc<T, TC, TC>{
588                       [&name](const Scalar<TC> &str,
589                           const Scalar<TC> &other) -> Scalar<T> {
590                         return name == "index"
591                             ? CharacterUtils<TC::kind>::INDEX(str, other)
592                             : name == "scan"
593                             ? CharacterUtils<TC::kind>::SCAN(str, other)
594                             : CharacterUtils<TC::kind>::VERIFY(str, other);
595                       }});
596             }
597           },
598           charExpr->u);
599     } else {
600       DIE("first argument must be CHARACTER");
601     }
602   } else if (name == "int") {
603     if (auto *expr{UnwrapExpr<Expr<SomeType>>(args[0])}) {
604       return std::visit(
605           [&](auto &&x) -> Expr<T> {
606             using From = std::decay_t<decltype(x)>;
607             if constexpr (std::is_same_v<From, BOZLiteralConstant> ||
608                 IsNumericCategoryExpr<From>()) {
609               return Fold(context, ConvertToType<T>(std::move(x)));
610             }
611             DIE("int() argument type not valid");
612           },
613           std::move(expr->u));
614     }
615   } else if (name == "int_ptr_kind") {
616     return Expr<T>{8};
617   } else if (name == "kind") {
618     if constexpr (common::HasMember<T, IntegerTypes>) {
619       return Expr<T>{args[0].value().GetType()->kind()};
620     } else {
621       DIE("kind() result not integral");
622     }
623   } else if (name == "iparity") {
624     return FoldBitReduction(
625         context, std::move(funcRef), &Scalar<T>::IEOR, Scalar<T>{});
626   } else if (name == "ishft") {
627     return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
628         ScalarFunc<T, T, Int4>([&](const Scalar<T> &i,
629                                    const Scalar<Int4> &pos) -> Scalar<T> {
630           auto posVal{static_cast<int>(pos.ToInt64())};
631           if (posVal < -i.bits) {
632             context.messages().Say(
633                 "SHIFT=%d count for ishft is less than %d"_err_en_US, posVal,
634                 -i.bits);
635           } else if (posVal > i.bits) {
636             context.messages().Say(
637                 "SHIFT=%d count for ishft is greater than %d"_err_en_US, posVal,
638                 i.bits);
639           }
640           return i.ISHFT(posVal);
641         }));
642   } else if (name == "lbound") {
643     return LBOUND(context, std::move(funcRef));
644   } else if (name == "leadz" || name == "trailz" || name == "poppar" ||
645       name == "popcnt") {
646     if (auto *sn{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
647       return std::visit(
648           [&funcRef, &context, &name](const auto &n) -> Expr<T> {
649             using TI = typename std::decay_t<decltype(n)>::Result;
650             if (name == "poppar") {
651               return FoldElementalIntrinsic<T, TI>(context, std::move(funcRef),
652                   ScalarFunc<T, TI>([](const Scalar<TI> &i) -> Scalar<T> {
653                     return Scalar<T>{i.POPPAR() ? 1 : 0};
654                   }));
655             }
656             auto fptr{&Scalar<TI>::LEADZ};
657             if (name == "leadz") { // done in fptr definition
658             } else if (name == "trailz") {
659               fptr = &Scalar<TI>::TRAILZ;
660             } else if (name == "popcnt") {
661               fptr = &Scalar<TI>::POPCNT;
662             } else {
663               common::die(
664                   "missing case to fold intrinsic function %s", name.c_str());
665             }
666             return FoldElementalIntrinsic<T, TI>(context, std::move(funcRef),
667                 ScalarFunc<T, TI>([&fptr](const Scalar<TI> &i) -> Scalar<T> {
668                   return Scalar<T>{std::invoke(fptr, i)};
669                 }));
670           },
671           sn->u);
672     } else {
673       DIE("leadz argument must be integer");
674     }
675   } else if (name == "len") {
676     if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
677       return std::visit(
678           [&](auto &kx) {
679             if (auto len{kx.LEN()}) {
680               if (IsScopeInvariantExpr(*len)) {
681                 return Fold(context, ConvertToType<T>(*std::move(len)));
682               } else {
683                 return Expr<T>{std::move(funcRef)};
684               }
685             } else {
686               return Expr<T>{std::move(funcRef)};
687             }
688           },
689           charExpr->u);
690     } else {
691       DIE("len() argument must be of character type");
692     }
693   } else if (name == "len_trim") {
694     if (auto *charExpr{UnwrapExpr<Expr<SomeCharacter>>(args[0])}) {
695       return std::visit(
696           [&](const auto &kch) -> Expr<T> {
697             using TC = typename std::decay_t<decltype(kch)>::Result;
698             return FoldElementalIntrinsic<T, TC>(context, std::move(funcRef),
699                 ScalarFunc<T, TC>{[](const Scalar<TC> &str) -> Scalar<T> {
700                   return CharacterUtils<TC::kind>::LEN_TRIM(str);
701                 }});
702           },
703           charExpr->u);
704     } else {
705       DIE("len_trim() argument must be of character type");
706     }
707   } else if (name == "maskl" || name == "maskr") {
708     // Argument can be of any kind but value has to be smaller than BIT_SIZE.
709     // It can be safely converted to Int4 to simplify.
710     const auto fptr{name == "maskl" ? &Scalar<T>::MASKL : &Scalar<T>::MASKR};
711     return FoldElementalIntrinsic<T, Int4>(context, std::move(funcRef),
712         ScalarFunc<T, Int4>([&fptr](const Scalar<Int4> &places) -> Scalar<T> {
713           return fptr(static_cast<int>(places.ToInt64()));
714         }));
715   } else if (name == "max") {
716     return FoldMINorMAX(context, std::move(funcRef), Ordering::Greater);
717   } else if (name == "max0" || name == "max1") {
718     return RewriteSpecificMINorMAX(context, std::move(funcRef));
719   } else if (name == "maxexponent") {
720     if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
721       return std::visit(
722           [](const auto &x) {
723             using TR = typename std::decay_t<decltype(x)>::Result;
724             return Expr<T>{Scalar<TR>::MAXEXPONENT};
725           },
726           sx->u);
727     }
728   } else if (name == "maxloc") {
729     return FoldLocation<WhichLocation::Maxloc, T>(context, std::move(funcRef));
730   } else if (name == "maxval") {
731     return FoldMaxvalMinval<T>(context, std::move(funcRef),
732         RelationalOperator::GT, T::Scalar::Least());
733   } else if (name == "merge") {
734     return FoldMerge<T>(context, std::move(funcRef));
735   } else if (name == "merge_bits") {
736     return FoldElementalIntrinsic<T, T, T, T>(
737         context, std::move(funcRef), &Scalar<T>::MERGE_BITS);
738   } else if (name == "min") {
739     return FoldMINorMAX(context, std::move(funcRef), Ordering::Less);
740   } else if (name == "min0" || name == "min1") {
741     return RewriteSpecificMINorMAX(context, std::move(funcRef));
742   } else if (name == "minexponent") {
743     if (auto *sx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
744       return std::visit(
745           [](const auto &x) {
746             using TR = typename std::decay_t<decltype(x)>::Result;
747             return Expr<T>{Scalar<TR>::MINEXPONENT};
748           },
749           sx->u);
750     }
751   } else if (name == "minloc") {
752     return FoldLocation<WhichLocation::Minloc, T>(context, std::move(funcRef));
753   } else if (name == "minval") {
754     return FoldMaxvalMinval<T>(
755         context, std::move(funcRef), RelationalOperator::LT, T::Scalar::HUGE());
756   } else if (name == "mod") {
757     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
758         ScalarFuncWithContext<T, T, T>(
759             [](FoldingContext &context, const Scalar<T> &x,
760                 const Scalar<T> &y) -> Scalar<T> {
761               auto quotRem{x.DivideSigned(y)};
762               if (quotRem.divisionByZero) {
763                 context.messages().Say("mod() by zero"_en_US);
764               } else if (quotRem.overflow) {
765                 context.messages().Say("mod() folding overflowed"_en_US);
766               }
767               return quotRem.remainder;
768             }));
769   } else if (name == "modulo") {
770     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
771         ScalarFuncWithContext<T, T, T>(
772             [](FoldingContext &context, const Scalar<T> &x,
773                 const Scalar<T> &y) -> Scalar<T> {
774               auto result{x.MODULO(y)};
775               if (result.overflow) {
776                 context.messages().Say("modulo() folding overflowed"_en_US);
777               }
778               return result.value;
779             }));
780   } else if (name == "not") {
781     return FoldElementalIntrinsic<T, T>(
782         context, std::move(funcRef), &Scalar<T>::NOT);
783   } else if (name == "precision") {
784     if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
785       return Expr<T>{std::visit(
786           [](const auto &kx) {
787             return Scalar<ResultType<decltype(kx)>>::PRECISION;
788           },
789           cx->u)};
790     } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
791       return Expr<T>{std::visit(
792           [](const auto &kx) {
793             return Scalar<typename ResultType<decltype(kx)>::Part>::PRECISION;
794           },
795           cx->u)};
796     }
797   } else if (name == "product") {
798     return FoldProduct<T>(context, std::move(funcRef), Scalar<T>{1});
799   } else if (name == "radix") {
800     return Expr<T>{2};
801   } else if (name == "range") {
802     if (const auto *cx{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
803       return Expr<T>{std::visit(
804           [](const auto &kx) {
805             return Scalar<ResultType<decltype(kx)>>::RANGE;
806           },
807           cx->u)};
808     } else if (const auto *cx{UnwrapExpr<Expr<SomeReal>>(args[0])}) {
809       return Expr<T>{std::visit(
810           [](const auto &kx) {
811             return Scalar<ResultType<decltype(kx)>>::RANGE;
812           },
813           cx->u)};
814     } else if (const auto *cx{UnwrapExpr<Expr<SomeComplex>>(args[0])}) {
815       return Expr<T>{std::visit(
816           [](const auto &kx) {
817             return Scalar<typename ResultType<decltype(kx)>::Part>::RANGE;
818           },
819           cx->u)};
820     }
821   } else if (name == "rank") {
822     if (const auto *array{UnwrapExpr<Expr<SomeType>>(args[0])}) {
823       if (auto named{ExtractNamedEntity(*array)}) {
824         const Symbol &symbol{named->GetLastSymbol()};
825         if (IsAssumedRank(symbol)) {
826           // DescriptorInquiry can only be placed in expression of kind
827           // DescriptorInquiry::Result::kind.
828           return ConvertToType<T>(Expr<
829               Type<TypeCategory::Integer, DescriptorInquiry::Result::kind>>{
830               DescriptorInquiry{*named, DescriptorInquiry::Field::Rank}});
831         }
832       }
833       return Expr<T>{args[0].value().Rank()};
834     }
835     return Expr<T>{args[0].value().Rank()};
836   } else if (name == "selected_char_kind") {
837     if (const auto *chCon{UnwrapExpr<Constant<TypeOf<std::string>>>(args[0])}) {
838       if (std::optional<std::string> value{chCon->GetScalarValue()}) {
839         int defaultKind{
840             context.defaults().GetDefaultKind(TypeCategory::Character)};
841         return Expr<T>{SelectedCharKind(*value, defaultKind)};
842       }
843     }
844   } else if (name == "selected_int_kind") {
845     if (auto p{GetInt64Arg(args[0])}) {
846       return Expr<T>{SelectedIntKind(*p)};
847     }
848   } else if (name == "selected_real_kind" ||
849       name == "__builtin_ieee_selected_real_kind") {
850     if (auto p{GetInt64ArgOr(args[0], 0)}) {
851       if (auto r{GetInt64ArgOr(args[1], 0)}) {
852         if (auto radix{GetInt64ArgOr(args[2], 2)}) {
853           return Expr<T>{SelectedRealKind(*p, *r, *radix)};
854         }
855       }
856     }
857   } else if (name == "shape") {
858     if (auto shape{GetContextFreeShape(context, args[0])}) {
859       if (auto shapeExpr{AsExtentArrayExpr(*shape)}) {
860         return Fold(context, ConvertToType<T>(std::move(*shapeExpr)));
861       }
862     }
863   } else if (name == "shifta" || name == "shiftr" || name == "shiftl") {
864     // Second argument can be of any kind. However, it must be smaller or
865     // equal than BIT_SIZE. It can be converted to Int4 to simplify.
866     auto fptr{&Scalar<T>::SHIFTA};
867     if (name == "shifta") { // done in fptr definition
868     } else if (name == "shiftr") {
869       fptr = &Scalar<T>::SHIFTR;
870     } else if (name == "shiftl") {
871       fptr = &Scalar<T>::SHIFTL;
872     } else {
873       common::die("missing case to fold intrinsic function %s", name.c_str());
874     }
875     return FoldElementalIntrinsic<T, T, Int4>(context, std::move(funcRef),
876         ScalarFunc<T, T, Int4>([&](const Scalar<T> &i,
877                                    const Scalar<Int4> &pos) -> Scalar<T> {
878           auto posVal{static_cast<int>(pos.ToInt64())};
879           if (posVal < 0) {
880             context.messages().Say(
881                 "SHIFT=%d count for %s is negative"_err_en_US, posVal, name);
882           } else if (posVal > i.bits) {
883             context.messages().Say(
884                 "SHIFT=%d count for %s is greater than %d"_err_en_US, posVal,
885                 name, i.bits);
886           }
887           return std::invoke(fptr, i, posVal);
888         }));
889   } else if (name == "sign") {
890     return FoldElementalIntrinsic<T, T, T>(context, std::move(funcRef),
891         ScalarFunc<T, T, T>(
892             [&context](const Scalar<T> &j, const Scalar<T> &k) -> Scalar<T> {
893               typename Scalar<T>::ValueWithOverflow result{j.SIGN(k)};
894               if (result.overflow) {
895                 context.messages().Say(
896                     "sign(integer(kind=%d)) folding overflowed"_en_US, KIND);
897               }
898               return result.value;
899             }));
900   } else if (name == "size") {
901     if (auto shape{GetContextFreeShape(context, args[0])}) {
902       if (auto &dimArg{args[1]}) { // DIM= is present, get one extent
903         if (auto dim{GetInt64Arg(args[1])}) {
904           int rank{GetRank(*shape)};
905           if (*dim >= 1 && *dim <= rank) {
906             const Symbol *symbol{UnwrapWholeSymbolDataRef(args[0])};
907             if (symbol && IsAssumedSizeArray(*symbol) && *dim == rank) {
908               context.messages().Say(
909                   "size(array,dim=%jd) of last dimension is not available for rank-%d assumed-size array dummy argument"_err_en_US,
910                   *dim, rank);
911               return MakeInvalidIntrinsic<T>(std::move(funcRef));
912             } else if (auto &extent{shape->at(*dim - 1)}) {
913               return Fold(context, ConvertToType<T>(std::move(*extent)));
914             }
915           } else {
916             context.messages().Say(
917                 "size(array,dim=%jd) dimension is out of range for rank-%d array"_en_US,
918                 *dim, rank);
919           }
920         }
921       } else if (auto extents{common::AllElementsPresent(std::move(*shape))}) {
922         // DIM= is absent; compute PRODUCT(SHAPE())
923         ExtentExpr product{1};
924         for (auto &&extent : std::move(*extents)) {
925           product = std::move(product) * std::move(extent);
926         }
927         return Expr<T>{ConvertToType<T>(Fold(context, std::move(product)))};
928       }
929     }
930   } else if (name == "sizeof") { // in bytes; extension
931     if (auto info{
932             characteristics::TypeAndShape::Characterize(args[0], context)}) {
933       if (auto bytes{info->MeasureSizeInBytes(context)}) {
934         return Expr<T>{Fold(context, ConvertToType<T>(std::move(*bytes)))};
935       }
936     }
937   } else if (name == "storage_size") { // in bits
938     if (auto info{
939             characteristics::TypeAndShape::Characterize(args[0], context)}) {
940       if (auto bytes{info->MeasureElementSizeInBytes(context, true)}) {
941         return Expr<T>{
942             Fold(context, Expr<T>{8} * ConvertToType<T>(std::move(*bytes)))};
943       }
944     }
945   } else if (name == "sum") {
946     return FoldSum<T>(context, std::move(funcRef));
947   } else if (name == "ubound") {
948     return UBOUND(context, std::move(funcRef));
949   }
950   // TODO: dot_product, ibits, ishftc, matmul, sign, transfer
951   return Expr<T>{std::move(funcRef)};
952 }
953 
954 // Substitutes a bare type parameter reference with its value if it has one now
955 // in an instantiation.  Bare LEN type parameters are substituted only when
956 // the known value is constant.
957 Expr<TypeParamInquiry::Result> FoldOperation(
958     FoldingContext &context, TypeParamInquiry &&inquiry) {
959   std::optional<NamedEntity> base{inquiry.base()};
960   parser::CharBlock parameterName{inquiry.parameter().name()};
961   if (base) {
962     // Handling "designator%typeParam".  Get the value of the type parameter
963     // from the instantiation of the base
964     if (const semantics::DeclTypeSpec *
965         declType{base->GetLastSymbol().GetType()}) {
966       if (const semantics::ParamValue *
967           paramValue{
968               declType->derivedTypeSpec().FindParameter(parameterName)}) {
969         const semantics::MaybeIntExpr &paramExpr{paramValue->GetExplicit()};
970         if (paramExpr && IsConstantExpr(*paramExpr)) {
971           Expr<SomeInteger> intExpr{*paramExpr};
972           return Fold(context,
973               ConvertToType<TypeParamInquiry::Result>(std::move(intExpr)));
974         }
975       }
976     }
977   } else {
978     // A "bare" type parameter: replace with its value, if that's now known
979     // in a current derived type instantiation, for KIND type parameters.
980     if (const auto *pdt{context.pdtInstance()}) {
981       bool isLen{false};
982       if (const semantics::Scope * scope{context.pdtInstance()->scope()}) {
983         auto iter{scope->find(parameterName)};
984         if (iter != scope->end()) {
985           const Symbol &symbol{*iter->second};
986           const auto *details{symbol.detailsIf<semantics::TypeParamDetails>()};
987           if (details) {
988             isLen = details->attr() == common::TypeParamAttr::Len;
989             const semantics::MaybeIntExpr &initExpr{details->init()};
990             if (initExpr && IsConstantExpr(*initExpr) &&
991                 (!isLen || ToInt64(*initExpr))) {
992               Expr<SomeInteger> expr{*initExpr};
993               return Fold(context,
994                   ConvertToType<TypeParamInquiry::Result>(std::move(expr)));
995             }
996           }
997         }
998       }
999       if (const auto *value{pdt->FindParameter(parameterName)}) {
1000         if (value->isExplicit()) {
1001           auto folded{Fold(context,
1002               AsExpr(ConvertToType<TypeParamInquiry::Result>(
1003                   Expr<SomeInteger>{value->GetExplicit().value()})))};
1004           if (!isLen || ToInt64(folded)) {
1005             return folded;
1006           }
1007         }
1008       }
1009     }
1010   }
1011   return AsExpr(std::move(inquiry));
1012 }
1013 
1014 std::optional<std::int64_t> ToInt64(const Expr<SomeInteger> &expr) {
1015   return std::visit(
1016       [](const auto &kindExpr) { return ToInt64(kindExpr); }, expr.u);
1017 }
1018 
1019 std::optional<std::int64_t> ToInt64(const Expr<SomeType> &expr) {
1020   if (const auto *intExpr{UnwrapExpr<Expr<SomeInteger>>(expr)}) {
1021     return ToInt64(*intExpr);
1022   } else {
1023     return std::nullopt;
1024   }
1025 }
1026 
1027 #ifdef _MSC_VER // disable bogus warning about missing definitions
1028 #pragma warning(disable : 4661)
1029 #endif
1030 FOR_EACH_INTEGER_KIND(template class ExpressionBase, )
1031 template class ExpressionBase<SomeInteger>;
1032 } // namespace Fortran::evaluate
1033