Debian Codegraph @

flang/lib/Evaluate/fold-logical.cpp

raw
1 //===-- lib/Evaluate/fold-logical.cpp -------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "fold-implementation.h"
10 #include "fold-matmul.h"
11 #include "fold-reduction.h"
12 #include "flang/Evaluate/check-expression.h"
13 #include "flang/Runtime/magic-numbers.h"
14
15 namespace Fortran::evaluate {
16
17 template <typename T>
18 static std::optional<Expr<SomeType>> ZeroExtend(const Constant<T> &c) {
19 std::vector<Scalar<LargestInt>> exts;
20 for (const auto &v : c.values()) {
21 exts.push_back(Scalar<LargestInt>::ConvertUnsigned(v).value);
22 }
23 return AsGenericExpr(
24 Constant<LargestInt>(std::move(exts), ConstantSubscripts(c.shape())));
25 }
26
27 // for ALL, ANY & PARITY
28 template <typename T>
29 static Expr<T> FoldAllAnyParity(FoldingContext &context, FunctionRef<T> &&ref,
30 Scalar<T> (Scalar<T>::*operation)(const Scalar<T> &) const,
31 Scalar<T> identity) {
32 static_assert(T::category == TypeCategory::Logical);
33 std::optional<int> dim;
34 if (std::optional<ArrayAndMask<T>> arrayAndMask{
35 ProcessReductionArgs<T>(context, ref.arguments(), dim,
36 /*ARRAY(MASK)=*/0, /*DIM=*/1)}) {
37 OperationAccumulator accumulator{arrayAndMask->array, operation};
38 return Expr<T>{DoReduction<T>(
39 arrayAndMask->array, arrayAndMask->mask, dim, identity, accumulator)};
40 }
41 return Expr<T>{std::move(ref)};
42 }
43
44 // OUT_OF_RANGE(x,mold[,round]) references are entirely rewritten here into
45 // expressions, which are then folded into constants when 'x' and 'round'
46 // are constant. It is guaranteed that 'x' is evaluated at most once.
47
48 template <int X_RKIND, int MOLD_IKIND>
49 Expr<SomeReal> RealToIntBoundHelper(bool round, bool negate) {
50 using RType = Type<TypeCategory::Real, X_RKIND>;
51 using RealType = Scalar<RType>;
52 using IntType = Scalar<Type<TypeCategory::Integer, MOLD_IKIND>>;
53 RealType result{}; // 0.
54 common::RoundingMode roundingMode{round
55 ? common::RoundingMode::TiesAwayFromZero
56 : common::RoundingMode::ToZero};
57 // Add decreasing powers of two to the result to find the largest magnitude
58 // value that can be converted to the integer type without overflow.
59 RealType at{RealType::FromInteger(IntType{negate ? -1 : 1}).value};
60 bool decrement{true};
61 while (!at.template ToInteger<IntType>(roundingMode)
62 .flags.test(RealFlag::Overflow)) {
63 auto tmp{at.SCALE(IntType{1})};
64 if (tmp.flags.test(RealFlag::Overflow)) {
65 decrement = false;
66 break;
67 }
68 at = tmp.value;
69 }
70 while (true) {
71 if (decrement) {
72 at = at.SCALE(IntType{-1}).value;
73 } else {
74 decrement = true;
75 }
76 auto tmp{at.Add(result)};
77 if (tmp.flags.test(RealFlag::Inexact)) {
78 break;
79 } else if (!tmp.value.template ToInteger<IntType>(roundingMode)
80 .flags.test(RealFlag::Overflow)) {
81 result = tmp.value;
82 }
83 }
84 return AsCategoryExpr(Constant<RType>{std::move(result)});
85 }
86
87 static Expr<SomeReal> RealToIntBound(
88 int xRKind, int moldIKind, bool round, bool negate) {
89 switch (xRKind) {
90 #define ICASES(RK) \
91 switch (moldIKind) { \
92 case 1: \
93 return RealToIntBoundHelper<RK, 1>(round, negate); \
94 break; \
95 case 2: \
96 return RealToIntBoundHelper<RK, 2>(round, negate); \
97 break; \
98 case 4: \
99 return RealToIntBoundHelper<RK, 4>(round, negate); \
100 break; \
101 case 8: \
102 return RealToIntBoundHelper<RK, 8>(round, negate); \
103 break; \
104 case 16: \
105 return RealToIntBoundHelper<RK, 16>(round, negate); \
106 break; \
107 } \
108 break
109 case 2:
110 ICASES(2);
111 break;
112 case 3:
113 ICASES(3);
114 break;
115 case 4:
116 ICASES(4);
117 break;
118 case 8:
119 ICASES(8);
120 break;
121 case 10:
122 ICASES(10);
123 break;
124 case 16:
125 ICASES(16);
126 break;
127 }
128 DIE("RealToIntBound: no case");
129 #undef ICASES
130 }
131
132 class RealToIntLimitHelper {
133 public:
134 using Result = std::optional<Expr<SomeReal>>;
135 using Types = RealTypes;
136 RealToIntLimitHelper(
137 FoldingContext &context, Expr<SomeReal> &&hi, Expr<SomeReal> &lo)
138 : context_{context}, hi_{std::move(hi)}, lo_{lo} {}
139 template <typename T> Result Test() {
140 if (UnwrapExpr<Expr<T>>(hi_)) {
141 bool promote{T::kind < 16};
142 Result constResult;
143 if (auto hiV{GetScalarConstantValue<T>(hi_)}) {
144 auto loV{GetScalarConstantValue<T>(lo_)};
145 CHECK(loV.has_value());
146 auto diff{hiV->Subtract(*loV, Rounding{common::RoundingMode::ToZero})};
147 promote = promote &&
148 (diff.flags.test(RealFlag::Overflow) ||
149 diff.flags.test(RealFlag::Inexact));
150 constResult = AsCategoryExpr(Constant<T>{std::move(diff.value)});
151 }
152 if (promote) {
153 constexpr int nextKind{T::kind < 4 ? 4 : T::kind == 4 ? 8 : 16};
154 using T2 = Type<TypeCategory::Real, nextKind>;
155 hi_ = Expr<SomeReal>{Fold(context_, ConvertToType<T2>(std::move(hi_)))};
156 lo_ = Expr<SomeReal>{Fold(context_, ConvertToType<T2>(std::move(lo_)))};
157 if (constResult) {
158 // Use promoted constants on next iteration of SearchTypes
159 return std::nullopt;
160 }
161 }
162 if (constResult) {
163 return constResult;
164 } else {
165 return AsCategoryExpr(std::move(hi_) - Expr<SomeReal>{lo_});
166 }
167 } else {
168 return std::nullopt;
169 }
170 }
171
172 private:
173 FoldingContext &context_;
174 Expr<SomeReal> hi_;
175 Expr<SomeReal> &lo_;
176 };
177
178 static std::optional<Expr<SomeReal>> RealToIntLimit(
179 FoldingContext &context, Expr<SomeReal> &&hi, Expr<SomeReal> &lo) {
180 return common::SearchTypes(RealToIntLimitHelper{context, std::move(hi), lo});
181 }
182
183 // RealToRealBounds() returns a pair (HUGE(x),REAL(HUGE(mold),KIND(x)))
184 // when REAL(HUGE(x),KIND(mold)) overflows, and std::nullopt otherwise.
185 template <int X_RKIND, int MOLD_RKIND>
186 std::optional<std::pair<Expr<SomeReal>, Expr<SomeReal>>>
187 RealToRealBoundsHelper() {
188 using RType = Type<TypeCategory::Real, X_RKIND>;
189 using RealType = Scalar<RType>;
190 using MoldRealType = Scalar<Type<TypeCategory::Real, MOLD_RKIND>>;
191 if (!MoldRealType::Convert(RealType::HUGE()).flags.test(RealFlag::Overflow)) {
192 return std::nullopt;
193 } else {
194 return std::make_pair(AsCategoryExpr(Constant<RType>{
195 RealType::Convert(MoldRealType::HUGE()).value}),
196 AsCategoryExpr(Constant<RType>{RealType::HUGE()}));
197 }
198 }
199
200 static std::optional<std::pair<Expr<SomeReal>, Expr<SomeReal>>>
201 RealToRealBounds(int xRKind, int moldRKind) {
202 switch (xRKind) {
203 #define RCASES(RK) \
204 switch (moldRKind) { \
205 case 2: \
206 return RealToRealBoundsHelper<RK, 2>(); \
207 break; \
208 case 3: \
209 return RealToRealBoundsHelper<RK, 3>(); \
210 break; \
211 case 4: \
212 return RealToRealBoundsHelper<RK, 4>(); \
213 break; \
214 case 8: \
215 return RealToRealBoundsHelper<RK, 8>(); \
216 break; \
217 case 10: \
218 return RealToRealBoundsHelper<RK, 10>(); \
219 break; \
220 case 16: \
221 return RealToRealBoundsHelper<RK, 16>(); \
222 break; \
223 } \
224 break
225 case 2:
226 RCASES(2);
227 break;
228 case 3:
229 RCASES(3);
230 break;
231 case 4:
232 RCASES(4);
233 break;
234 case 8:
235 RCASES(8);
236 break;
237 case 10:
238 RCASES(10);
239 break;
240 case 16:
241 RCASES(16);
242 break;
243 }
244 DIE("RealToRealBounds: no case");
245 #undef RCASES
246 }
247
248 template <int X_IKIND, int MOLD_RKIND>
249 std::optional<Expr<SomeInteger>> IntToRealBoundHelper(bool negate) {
250 using IType = Type<TypeCategory::Integer, X_IKIND>;
251 using IntType = Scalar<IType>;
252 using RealType = Scalar<Type<TypeCategory::Real, MOLD_RKIND>>;
253 IntType result{}; // 0
254 while (true) {
255 std::optional<IntType> next;
256 for (int bit{0}; bit < IntType::bits; ++bit) {
257 IntType power{IntType{}.IBSET(bit)};
258 if (power.IsNegative()) {
259 if (!negate) {
260 break;
261 }
262 } else if (negate) {
263 power = power.Negate().value;
264 }
265 auto tmp{power.AddSigned(result)};
266 if (tmp.overflow ||
267 RealType::FromInteger(tmp.value).flags.test(RealFlag::Overflow)) {
268 break;
269 }
270 next = tmp.value;
271 }
272 if (next) {
273 CHECK(result.CompareSigned(*next) != Ordering::Equal);
274 result = *next;
275 } else {
276 break;
277 }
278 }
279 if (result.CompareSigned(IntType::HUGE()) == Ordering::Equal) {
280 return std::nullopt;
281 } else {
282 return AsCategoryExpr(Constant<IType>{std::move(result)});
283 }
284 }
285
286 static std::optional<Expr<SomeInteger>> IntToRealBound(
287 int xIKind, int moldRKind, bool negate) {
288 switch (xIKind) {
289 #define RCASES(IK) \
290 switch (moldRKind) { \
291 case 2: \
292 return IntToRealBoundHelper<IK, 2>(negate); \
293 break; \
294 case 3: \
295 return IntToRealBoundHelper<IK, 3>(negate); \
296 break; \
297 case 4: \
298 return IntToRealBoundHelper<IK, 4>(negate); \
299 break; \
300 case 8: \
301 return IntToRealBoundHelper<IK, 8>(negate); \
302 break; \
303 case 10: \
304 return IntToRealBoundHelper<IK, 10>(negate); \
305 break; \
306 case 16: \
307 return IntToRealBoundHelper<IK, 16>(negate); \
308 break; \
309 } \
310 break
311 case 1:
312 RCASES(1);
313 break;
314 case 2:
315 RCASES(2);
316 break;
317 case 4:
318 RCASES(4);
319 break;
320 case 8:
321 RCASES(8);
322 break;
323 case 16:
324 RCASES(16);
325 break;
326 }
327 DIE("IntToRealBound: no case");
328 #undef RCASES
329 }
330
331 template <int X_IKIND, int MOLD_IKIND>
332 std::optional<Expr<SomeInteger>> IntToIntBoundHelper() {
333 if constexpr (X_IKIND <= MOLD_IKIND) {
334 return std::nullopt;
335 } else {
336 using XIType = Type<TypeCategory::Integer, X_IKIND>;
337 using IntegerType = Scalar<XIType>;
338 using MoldIType = Type<TypeCategory::Integer, MOLD_IKIND>;
339 using MoldIntegerType = Scalar<MoldIType>;
340 return AsCategoryExpr(Constant<XIType>{
341 IntegerType::ConvertSigned(MoldIntegerType::HUGE()).value});
342 }
343 }
344
345 static std::optional<Expr<SomeInteger>> IntToIntBound(
346 int xIKind, int moldIKind) {
347 switch (xIKind) {
348 #define ICASES(IK) \
349 switch (moldIKind) { \
350 case 1: \
351 return IntToIntBoundHelper<IK, 1>(); \
352 break; \
353 case 2: \
354 return IntToIntBoundHelper<IK, 2>(); \
355 break; \
356 case 4: \
357 return IntToIntBoundHelper<IK, 4>(); \
358 break; \
359 case 8: \
360 return IntToIntBoundHelper<IK, 8>(); \
361 break; \
362 case 16: \
363 return IntToIntBoundHelper<IK, 16>(); \
364 break; \
365 } \
366 break
367 case 1:
368 ICASES(1);
369 break;
370 case 2:
371 ICASES(2);
372 break;
373 case 4:
374 ICASES(4);
375 break;
376 case 8:
377 ICASES(8);
378 break;
379 case 16:
380 ICASES(16);
381 break;
382 }
383 DIE("IntToIntBound: no case");
384 #undef ICASES
385 }
386
387 // ApplyIntrinsic() constructs the typed expression representation
388 // for a specific intrinsic function reference.
389 // TODO: maybe move into tools.h?
390 class IntrinsicCallHelper {
391 public:
392 explicit IntrinsicCallHelper(SpecificCall &&call) : call_{call} {
393 CHECK(proc_.IsFunction());
394 typeAndShape_ = proc_.functionResult->GetTypeAndShape();
395 CHECK(typeAndShape_ != nullptr);
396 }
397 using Result = std::optional<Expr<SomeType>>;
398 using Types = LengthlessIntrinsicTypes;
399 template <typename T> Result Test() {
400 if (T::category == typeAndShape_->type().category() &&
401 T::kind == typeAndShape_->type().kind()) {
402 return AsGenericExpr(FunctionRef<T>{
403 ProcedureDesignator{std::move(call_.specificIntrinsic)},
404 std::move(call_.arguments)});
405 } else {
406 return std::nullopt;
407 }
408 }
409
410 private:
411 SpecificCall call_;
412 const characteristics::Procedure &proc_{
413 call_.specificIntrinsic.characteristics.value()};
414 const characteristics::TypeAndShape *typeAndShape_{nullptr};
415 };
416
417 static Expr<SomeType> ApplyIntrinsic(
418 FoldingContext &context, const std::string &func, ActualArguments &&args) {
419 auto found{
420 context.intrinsics().Probe(CallCharacteristics{func}, args, context)};
421 CHECK(found.has_value());
422 auto result{common::SearchTypes(IntrinsicCallHelper{std::move(*found)})};
423 CHECK(result.has_value());
424 return *result;
425 }
426
427 static Expr<LogicalResult> CompareUnsigned(FoldingContext &context,
428 const char *intrin, Expr<SomeType> &&x, Expr<SomeType> &&y) {
429 Expr<SomeType> result{ApplyIntrinsic(context, intrin,
430 ActualArguments{
431 ActualArgument{std::move(x)}, ActualArgument{std::move(y)}})};
432 return DEREF(UnwrapExpr<Expr<LogicalResult>>(result));
433 }
434
435 // Determines the right kind of INTEGER to hold the bits of a REAL type.
436 static Expr<SomeType> IntTransferMold(
437 const TargetCharacteristics &target, DynamicType realType, bool asVector) {
438 CHECK(realType.category() == TypeCategory::Real);
439 int rKind{realType.kind()};
440 int iKind{std::max<int>(target.GetAlignment(TypeCategory::Real, rKind),
441 target.GetByteSize(TypeCategory::Real, rKind))};
442 CHECK(target.CanSupportType(TypeCategory::Integer, iKind));
443 DynamicType iType{TypeCategory::Integer, iKind};
444 ConstantSubscripts shape;
445 if (asVector) {
446 shape = ConstantSubscripts{1};
447 }
448 Constant<SubscriptInteger> value{
449 std::vector<Scalar<SubscriptInteger>>{0}, std::move(shape)};
450 auto expr{ConvertToType(iType, AsGenericExpr(std::move(value)))};
451 CHECK(expr.has_value());
452 return std::move(*expr);
453 }
454
455 static Expr<SomeType> GetRealBits(FoldingContext &context, Expr<SomeReal> &&x) {
456 auto xType{x.GetType()};
457 CHECK(xType.has_value());
458 bool asVector{x.Rank() > 0};
459 return ApplyIntrinsic(context, "transfer",
460 ActualArguments{ActualArgument{AsGenericExpr(std::move(x))},
461 ActualArgument{IntTransferMold(
462 context.targetCharacteristics(), *xType, asVector)}});
463 }
464
465 template <int KIND>
466 static Expr<Type<TypeCategory::Logical, KIND>> RewriteOutOfRange(
467 FoldingContext &context,
468 FunctionRef<Type<TypeCategory::Logical, KIND>> &&funcRef) {
469 using ResultType = Type<TypeCategory::Logical, KIND>;
470 ActualArguments &args{funcRef.arguments()};
471 // Fold x= and round= unconditionally
472 if (auto *x{UnwrapExpr<Expr<SomeType>>(args[0])}) {
473 *args[0] = Fold(context, std::move(*x));
474 }
475 if (args.size() >= 3) {
476 if (auto *round{UnwrapExpr<Expr<SomeType>>(args[2])}) {
477 *args[2] = Fold(context, std::move(*round));
478 }
479 }
480 if (auto *x{UnwrapExpr<Expr<SomeType>>(args[0])}) {
481 x = UnwrapExpr<Expr<SomeType>>(args[0]);
482 CHECK(x != nullptr);
483 if (const auto *mold{UnwrapExpr<Expr<SomeType>>(args[1])}) {
484 DynamicType xType{x->GetType().value()};
485 std::optional<Expr<LogicalResult>> result;
486 bool alwaysFalse{false};
487 if (auto *iXExpr{UnwrapExpr<Expr<SomeInteger>>(*x)}) {
488 int iXKind{iXExpr->GetType().value().kind()};
489 if (auto *iMoldExpr{UnwrapExpr<Expr<SomeInteger>>(*mold)}) {
490 // INTEGER -> INTEGER
491 int iMoldKind{iMoldExpr->GetType().value().kind()};
492 if (auto hi{IntToIntBound(iXKind, iMoldKind)}) {
493 // 'hi' is INT(HUGE(mold), KIND(x))
494 // OUT_OF_RANGE(x,mold) = (x + (hi + 1)) .UGT. (2*hi + 1)
495 auto one{DEREF(UnwrapExpr<Expr<SomeInteger>>(ConvertToType(
496 xType, AsGenericExpr(Constant<SubscriptInteger>{1}))))};
497 auto lhs{std::move(*iXExpr) +
498 (Expr<SomeInteger>{*hi} + Expr<SomeInteger>{one})};
499 auto two{DEREF(UnwrapExpr<Expr<SomeInteger>>(ConvertToType(
500 xType, AsGenericExpr(Constant<SubscriptInteger>{2}))))};
501 auto rhs{std::move(two) * std::move(*hi) + std::move(one)};
502 result = CompareUnsigned(context, "bgt",
503 Expr<SomeType>{std::move(lhs)}, Expr<SomeType>{std::move(rhs)});
504 } else {
505 alwaysFalse = true;
506 }
507 } else if (auto *rMoldExpr{UnwrapExpr<Expr<SomeReal>>(*mold)}) {
508 // INTEGER -> REAL
509 int rMoldKind{rMoldExpr->GetType().value().kind()};
510 if (auto hi{IntToRealBound(iXKind, rMoldKind, /*negate=*/false)}) {
511 // OUT_OF_RANGE(x,mold) = (x - lo) .UGT. (hi - lo)
512 auto lo{IntToRealBound(iXKind, rMoldKind, /*negate=*/true)};
513 CHECK(lo.has_value());
514 auto lhs{std::move(*iXExpr) - Expr<SomeInteger>{*lo}};
515 auto rhs{std::move(*hi) - std::move(*lo)};
516 result = CompareUnsigned(context, "bgt",
517 Expr<SomeType>{std::move(lhs)}, Expr<SomeType>{std::move(rhs)});
518 } else {
519 alwaysFalse = true;
520 }
521 }
522 } else if (auto *rXExpr{UnwrapExpr<Expr<SomeReal>>(*x)}) {
523 int rXKind{rXExpr->GetType().value().kind()};
524 if (auto *iMoldExpr{UnwrapExpr<Expr<SomeInteger>>(*mold)}) {
525 // REAL -> INTEGER
526 int iMoldKind{iMoldExpr->GetType().value().kind()};
527 auto hi{RealToIntBound(rXKind, iMoldKind, false, false)};
528 auto lo{RealToIntBound(rXKind, iMoldKind, false, true)};
529 if (args.size() >= 3) {
530 // Bounds depend on round= value
531 if (auto *round{UnwrapExpr<Expr<SomeType>>(args[2])}) {
532 if (const Symbol * whole{UnwrapWholeSymbolDataRef(*round)};
533 whole && semantics::IsOptional(whole->GetUltimate()) &&
534 context.languageFeatures().ShouldWarn(
535 common::UsageWarning::OptionalMustBePresent)) {
536 if (auto source{args[2]->sourceLocation()}) {
537 context.messages().Say(*source,
538 "ROUND= argument to OUT_OF_RANGE() is an optional dummy argument that must be present at execution"_warn_en_US);
539 }
540 }
541 auto rlo{RealToIntBound(rXKind, iMoldKind, true, true)};
542 auto rhi{RealToIntBound(rXKind, iMoldKind, true, false)};
543 auto mlo{Fold(context,
544 ApplyIntrinsic(context, "merge",
545 ActualArguments{
546 ActualArgument{Expr<SomeType>{std::move(rlo)}},
547 ActualArgument{Expr<SomeType>{std::move(lo)}},
548 ActualArgument{Expr<SomeType>{*round}}}))};
549 auto mhi{Fold(context,
550 ApplyIntrinsic(context, "merge",
551 ActualArguments{
552 ActualArgument{Expr<SomeType>{std::move(rhi)}},
553 ActualArgument{Expr<SomeType>{std::move(hi)}},
554 ActualArgument{std::move(*round)}}))};
555 lo = std::move(DEREF(UnwrapExpr<Expr<SomeReal>>(mlo)));
556 hi = std::move(DEREF(UnwrapExpr<Expr<SomeReal>>(mhi)));
557 }
558 }
559 // OUT_OF_RANGE(x,mold[,round]) =
560 // TRANSFER(x - lo, int) .UGT. TRANSFER(hi - lo, int)
561 hi = Fold(context, std::move(hi));
562 lo = Fold(context, std::move(lo));
563 if (auto rhs{RealToIntLimit(context, std::move(hi), lo)}) {
564 Expr<SomeReal> lhs{std::move(*rXExpr) - std::move(lo)};
565 result = CompareUnsigned(context, "bgt",
566 GetRealBits(context, std::move(lhs)),
567 GetRealBits(context, std::move(*rhs)));
568 }
569 } else if (auto *rMoldExpr{UnwrapExpr<Expr<SomeReal>>(*mold)}) {
570 // REAL -> REAL
571 // Only finite arguments with ABS(x) > HUGE(mold) are .TRUE.
572 // OUT_OF_RANGE(x,mold) =
573 // TRANSFER(ABS(x) - HUGE(mold), int) - 1 .ULT.
574 // TRANSFER(HUGE(mold), int)
575 // Note that OUT_OF_RANGE(+/-Inf or NaN,mold) =
576 // TRANSFER(+Inf or Nan, int) - 1 .ULT. TRANSFER(HUGE(mold), int)
577 int rMoldKind{rMoldExpr->GetType().value().kind()};
578 if (auto bounds{RealToRealBounds(rXKind, rMoldKind)}) {
579 auto &[moldHuge, xHuge]{*bounds};
580 Expr<SomeType> abs{ApplyIntrinsic(context, "abs",
581 ActualArguments{
582 ActualArgument{Expr<SomeType>{std::move(*rXExpr)}}})};
583 auto &absR{DEREF(UnwrapExpr<Expr<SomeReal>>(abs))};
584 Expr<SomeType> diffBits{
585 GetRealBits(context, std::move(absR) - std::move(moldHuge))};
586 auto &diffBitsI{DEREF(UnwrapExpr<Expr<SomeInteger>>(diffBits))};
587 Expr<SomeType> decr{std::move(diffBitsI) -
588 Expr<SomeInteger>{Expr<SubscriptInteger>{1}}};
589 result = CompareUnsigned(context, "blt", std::move(decr),
590 GetRealBits(context, std::move(xHuge)));
591 } else {
592 alwaysFalse = true;
593 }
594 }
595 }
596 if (alwaysFalse) {
597 // xType can never overflow moldType, so
598 // OUT_OF_RANGE(x) = (x /= 0) .AND. .FALSE.
599 // which has the same shape as x.
600 Expr<LogicalResult> scalarFalse{
601 Constant<LogicalResult>{Scalar<LogicalResult>{false}}};
602 if (x->Rank() > 0) {
603 if (auto nez{Relate(context.messages(), RelationalOperator::NE,
604 std::move(*x),
605 AsGenericExpr(Constant<SubscriptInteger>{0}))}) {
606 result = Expr<LogicalResult>{LogicalOperation<LogicalResult::kind>{
607 LogicalOperator::And, std::move(*nez), std::move(scalarFalse)}};
608 }
609 } else {
610 result = std::move(scalarFalse);
611 }
612 }
613 if (result) {
614 auto restorer{context.messages().DiscardMessages()};
615 return Fold(
616 context, AsExpr(ConvertToType<ResultType>(std::move(*result))));
617 }
618 }
619 }
620 return AsExpr(std::move(funcRef));
621 }
622
623 static std::optional<common::RoundingMode> GetRoundingMode(
624 const std::optional<ActualArgument> &arg) {
625 if (arg) {
626 if (const auto *cst{UnwrapExpr<Constant<SomeDerived>>(*arg)}) {
627 if (auto constr{cst->GetScalarValue()}) {
628 if (StructureConstructorValues & values{constr->values()};
629 values.size() == 1) {
630 const Expr<SomeType> &value{values.begin()->second.value()};
631 if (auto code{ToInt64(value)}) {
632 return static_cast<common::RoundingMode>(*code);
633 }
634 }
635 }
636 }
637 }
638 return std::nullopt;
639 }
640
641 template <int KIND>
642 Expr<Type<TypeCategory::Logical, KIND>> FoldIntrinsicFunction(
643 FoldingContext &context,
644 FunctionRef<Type<TypeCategory::Logical, KIND>> &&funcRef) {
645 using T = Type<TypeCategory::Logical, KIND>;
646 ActualArguments &args{funcRef.arguments()};
647 auto *intrinsic{std::get_if<SpecificIntrinsic>(&funcRef.proc().u)};
648 CHECK(intrinsic);
649 std::string name{intrinsic->name};
650 using SameInt = Type<TypeCategory::Integer, KIND>;
651 if (name == "all") {
652 return FoldAllAnyParity(
653 context, std::move(funcRef), &Scalar<T>::AND, Scalar<T>{true});
654 } else if (name == "any") {
655 return FoldAllAnyParity(
656 context, std::move(funcRef), &Scalar<T>::OR, Scalar<T>{false});
657 } else if (name == "associated") {
658 bool gotConstant{true};
659 const Expr<SomeType> *firstArgExpr{args[0]->UnwrapExpr()};
660 if (!firstArgExpr || !IsNullPointer(*firstArgExpr)) {
661 gotConstant = false;
662 } else if (args[1]) { // There's a second argument
663 const Expr<SomeType> *secondArgExpr{args[1]->UnwrapExpr()};
664 if (!secondArgExpr || !IsNullPointer(*secondArgExpr)) {
665 gotConstant = false;
666 }
667 }
668 return gotConstant ? Expr<T>{false} : Expr<T>{std::move(funcRef)};
669 } else if (name == "bge" || name == "bgt" || name == "ble" || name == "blt") {
670 static_assert(std::is_same_v<Scalar<LargestInt>, BOZLiteralConstant>);
671
672 // The arguments to these intrinsics can be of different types. In that
673 // case, the shorter of the two would need to be zero-extended to match
674 // the size of the other. If at least one of the operands is not a constant,
675 // the zero-extending will be done during lowering. Otherwise, the folding
676 // must be done here.
677 std::optional<Expr<SomeType>> constArgs[2];
678 for (int i{0}; i <= 1; i++) {
679 if (BOZLiteralConstant * x{UnwrapExpr<BOZLiteralConstant>(args[i])}) {
680 constArgs[i] = AsGenericExpr(Constant<LargestInt>{std::move(*x)});
681 } else if (auto *x{UnwrapExpr<Expr<SomeInteger>>(args[i])}) {
682 common::visit(
683 [&](const auto &ix) {
684 using IntT = typename std::decay_t<decltype(ix)>::Result;
685 if (auto *c{UnwrapConstantValue<IntT>(ix)}) {
686 constArgs[i] = ZeroExtend(*c);
687 }
688 },
689 x->u);
690 }
691 }
692
693 if (constArgs[0] && constArgs[1]) {
694 auto fptr{&Scalar<LargestInt>::BGE};
695 if (name == "bge") { // done in fptr declaration
696 } else if (name == "bgt") {
697 fptr = &Scalar<LargestInt>::BGT;
698 } else if (name == "ble") {
699 fptr = &Scalar<LargestInt>::BLE;
700 } else if (name == "blt") {
701 fptr = &Scalar<LargestInt>::BLT;
702 } else {
703 common::die("missing case to fold intrinsic function %s", name.c_str());
704 }
705
706 for (int i{0}; i <= 1; i++) {
707 *args[i] = std::move(constArgs[i].value());
708 }
709
710 return FoldElementalIntrinsic<T, LargestInt, LargestInt>(context,
711 std::move(funcRef),
712 ScalarFunc<T, LargestInt, LargestInt>(
713 [&fptr](
714 const Scalar<LargestInt> &i, const Scalar<LargestInt> &j) {
715 return Scalar<T>{std::invoke(fptr, i, j)};
716 }));
717 } else {
718 return Expr<T>{std::move(funcRef)};
719 }
720 } else if (name == "btest") {
721 if (const auto *ix{UnwrapExpr<Expr<SomeInteger>>(args[0])}) {
722 return common::visit(
723 [&](const auto &x) {
724 using IT = ResultType<decltype(x)>;
725 return FoldElementalIntrinsic<T, IT, SameInt>(context,
726 std::move(funcRef),
727 ScalarFunc<T, IT, SameInt>(
728 [&](const Scalar<IT> &x, const Scalar<SameInt> &pos) {
729 auto posVal{pos.ToInt64()};
730 if (posVal < 0 || posVal >= x.bits) {
731 context.messages().Say(
732 "POS=%jd out of range for BTEST"_err_en_US,
733 static_cast<std::intmax_t>(posVal));
734 }
735 return Scalar<T>{x.BTEST(posVal)};
736 }));
737 },
738 ix->u);
739 }
740 } else if (name == "dot_product") {
741 return FoldDotProduct<T>(context, std::move(funcRef));
742 } else if (name == "extends_type_of") {
743 // Type extension testing with EXTENDS_TYPE_OF() ignores any type
744 // parameters. Returns a constant truth value when the result is known now.
745 if (args[0] && args[1]) {
746 auto t0{args[0]->GetType()};
747 auto t1{args[1]->GetType()};
748 if (t0 && t1) {
749 if (auto result{t0->ExtendsTypeOf(*t1)}) {
750 return Expr<T>{*result};
751 }
752 }
753 }
754 } else if (name == "isnan" || name == "__builtin_ieee_is_nan") {
755 // Only replace the type of the function if we can do the fold
756 if (args[0] && args[0]->UnwrapExpr() &&
757 IsActuallyConstant(*args[0]->UnwrapExpr())) {
758 auto restorer{context.messages().DiscardMessages()};
759 using DefaultReal = Type<TypeCategory::Real, 4>;
760 return FoldElementalIntrinsic<T, DefaultReal>(context, std::move(funcRef),
761 ScalarFunc<T, DefaultReal>([](const Scalar<DefaultReal> &x) {
762 return Scalar<T>{x.IsNotANumber()};
763 }));
764 }
765 } else if (name == "__builtin_ieee_is_negative") {
766 auto restorer{context.messages().DiscardMessages()};
767 using DefaultReal = Type<TypeCategory::Real, 4>;
768 if (args[0] && args[0]->UnwrapExpr() &&
769 IsActuallyConstant(*args[0]->UnwrapExpr())) {
770 return FoldElementalIntrinsic<T, DefaultReal>(context, std::move(funcRef),
771 ScalarFunc<T, DefaultReal>([](const Scalar<DefaultReal> &x) {
772 return Scalar<T>{x.IsNegative()};
773 }));
774 }
775 } else if (name == "__builtin_ieee_is_normal") {
776 auto restorer{context.messages().DiscardMessages()};
777 using DefaultReal = Type<TypeCategory::Real, 4>;
778 if (args[0] && args[0]->UnwrapExpr() &&
779 IsActuallyConstant(*args[0]->UnwrapExpr())) {
780 return FoldElementalIntrinsic<T, DefaultReal>(context, std::move(funcRef),
781 ScalarFunc<T, DefaultReal>([](const Scalar<DefaultReal> &x) {
782 return Scalar<T>{x.IsNormal()};
783 }));
784 }
785 } else if (name == "is_contiguous") {
786 if (args.at(0)) {
787 if (auto *expr{args[0]->UnwrapExpr()}) {
788 if (auto contiguous{IsContiguous(*expr, context)}) {
789 return Expr<T>{*contiguous};
790 }
791 } else if (auto *assumedType{args[0]->GetAssumedTypeDummy()}) {
792 if (auto contiguous{IsContiguous(*assumedType, context)}) {
793 return Expr<T>{*contiguous};
794 }
795 }
796 }
797 } else if (name == "is_iostat_end") {
798 if (args[0] && args[0]->UnwrapExpr() &&
799 IsActuallyConstant(*args[0]->UnwrapExpr())) {
800 using Int64 = Type<TypeCategory::Integer, 8>;
801 return FoldElementalIntrinsic<T, Int64>(context, std::move(funcRef),
802 ScalarFunc<T, Int64>([](const Scalar<Int64> &x) {
803 return Scalar<T>{x.ToInt64() == FORTRAN_RUNTIME_IOSTAT_END};
804 }));
805 }
806 } else if (name == "is_iostat_eor") {
807 if (args[0] && args[0]->UnwrapExpr() &&
808 IsActuallyConstant(*args[0]->UnwrapExpr())) {
809 using Int64 = Type<TypeCategory::Integer, 8>;
810 return FoldElementalIntrinsic<T, Int64>(context, std::move(funcRef),
811 ScalarFunc<T, Int64>([](const Scalar<Int64> &x) {
812 return Scalar<T>{x.ToInt64() == FORTRAN_RUNTIME_IOSTAT_EOR};
813 }));
814 }
815 } else if (name == "lge" || name == "lgt" || name == "lle" || name == "llt") {
816 // Rewrite LGE/LGT/LLE/LLT into ASCII character relations
817 auto *cx0{UnwrapExpr<Expr<SomeCharacter>>(args[0])};
818 auto *cx1{UnwrapExpr<Expr<SomeCharacter>>(args[1])};
819 if (cx0 && cx1) {
820 return Fold(context,
821 ConvertToType<T>(
822 PackageRelation(name == "lge" ? RelationalOperator::GE
823 : name == "lgt" ? RelationalOperator::GT
824 : name == "lle" ? RelationalOperator::LE
825 : RelationalOperator::LT,
826 ConvertToType<Ascii>(std::move(*cx0)),
827 ConvertToType<Ascii>(std::move(*cx1)))));
828 }
829 } else if (name == "logical") {
830 if (auto *expr{UnwrapExpr<Expr<SomeLogical>>(args[0])}) {
831 return Fold(context, ConvertToType<T>(std::move(*expr)));
832 }
833 } else if (name == "matmul") {
834 return FoldMatmul(context, std::move(funcRef));
835 } else if (name == "out_of_range") {
836 return RewriteOutOfRange<KIND>(context, std::move(funcRef));
837 } else if (name == "parity") {
838 return FoldAllAnyParity(
839 context, std::move(funcRef), &Scalar<T>::NEQV, Scalar<T>{false});
840 } else if (name == "same_type_as") {
841 // Type equality testing with SAME_TYPE_AS() ignores any type parameters.
842 // Returns a constant truth value when the result is known now.
843 if (args[0] && args[1]) {
844 auto t0{args[0]->GetType()};
845 auto t1{args[1]->GetType()};
846 if (t0 && t1) {
847 if (auto result{t0->SameTypeAs(*t1)}) {
848 return Expr<T>{*result};
849 }
850 }
851 }
852 } else if (name == "__builtin_ieee_support_datatype") {
853 return Expr<T>{true};
854 } else if (name == "__builtin_ieee_support_denormal") {
855 return Expr<T>{context.targetCharacteristics().ieeeFeatures().test(
856 IeeeFeature::Denormal)};
857 } else if (name == "__builtin_ieee_support_divide") {
858 return Expr<T>{context.targetCharacteristics().ieeeFeatures().test(
859 IeeeFeature::Divide)};
860 } else if (name == "__builtin_ieee_support_flag") {
861 return Expr<T>{context.targetCharacteristics().ieeeFeatures().test(
862 IeeeFeature::Flags)};
863 } else if (name == "__builtin_ieee_support_halting") {
864 return Expr<T>{context.targetCharacteristics().ieeeFeatures().test(
865 IeeeFeature::Halting)};
866 } else if (name == "__builtin_ieee_support_inf") {
867 return Expr<T>{
868 context.targetCharacteristics().ieeeFeatures().test(IeeeFeature::Inf)};
869 } else if (name == "__builtin_ieee_support_io") {
870 return Expr<T>{
871 context.targetCharacteristics().ieeeFeatures().test(IeeeFeature::Io)};
872 } else if (name == "__builtin_ieee_support_nan") {
873 return Expr<T>{
874 context.targetCharacteristics().ieeeFeatures().test(IeeeFeature::NaN)};
875 } else if (name == "__builtin_ieee_support_rounding") {
876 if (context.targetCharacteristics().ieeeFeatures().test(
877 IeeeFeature::Rounding)) {
878 if (auto mode{GetRoundingMode(args[0])}) {
879 return Expr<T>{mode != common::RoundingMode::TiesAwayFromZero};
880 }
881 }
882 } else if (name == "__builtin_ieee_support_sqrt") {
883 return Expr<T>{
884 context.targetCharacteristics().ieeeFeatures().test(IeeeFeature::Sqrt)};
885 } else if (name == "__builtin_ieee_support_standard") {
886 return Expr<T>{context.targetCharacteristics().ieeeFeatures().test(
887 IeeeFeature::Standard)};
888 } else if (name == "__builtin_ieee_support_subnormal") {
889 return Expr<T>{context.targetCharacteristics().ieeeFeatures().test(
890 IeeeFeature::Subnormal)};
891 } else if (name == "__builtin_ieee_support_underflow_control") {
892 return Expr<T>{context.targetCharacteristics().ieeeFeatures().test(
893 IeeeFeature::UnderflowControl)};
894 }
895 return Expr<T>{std::move(funcRef)};
896 }
897
898 template <typename T>
899 Expr<LogicalResult> FoldOperation(
900 FoldingContext &context, Relational<T> &&relation) {
901 if (auto array{ApplyElementwise(context, relation,
902 std::function<Expr<LogicalResult>(Expr<T> &&, Expr<T> &&)>{
903 [=](Expr<T> &&x, Expr<T> &&y) {
904 return Expr<LogicalResult>{Relational<SomeType>{
905 Relational<T>{relation.opr, std::move(x), std::move(y)}}};
906 }})}) {
907 return *array;
908 }
909 if (auto folded{OperandsAreConstants(relation)}) {
910 bool result{};
911 if constexpr (T::category == TypeCategory::Integer) {
912 result =
913 Satisfies(relation.opr, folded->first.CompareSigned(folded->second));
914 } else if constexpr (T::category == TypeCategory::Real) {
915 result = Satisfies(relation.opr, folded->first.Compare(folded->second));
916 } else if constexpr (T::category == TypeCategory::Complex) {
917 result = (relation.opr == RelationalOperator::EQ) ==
918 folded->first.Equals(folded->second);
919 } else if constexpr (T::category == TypeCategory::Character) {
920 result = Satisfies(relation.opr, Compare(folded->first, folded->second));
921 } else {
922 static_assert(T::category != TypeCategory::Logical);
923 }
924 return Expr<LogicalResult>{Constant<LogicalResult>{result}};
925 }
926 return Expr<LogicalResult>{Relational<SomeType>{std::move(relation)}};
927 }
928
929 Expr<LogicalResult> FoldOperation(
930 FoldingContext &context, Relational<SomeType> &&relation) {
931 return common::visit(
932 [&](auto &&x) {
933 return Expr<LogicalResult>{FoldOperation(context, std::move(x))};
934 },
935 std::move(relation.u));
936 }
937
938 template <int KIND>
939 Expr<Type<TypeCategory::Logical, KIND>> FoldOperation(
940 FoldingContext &context, Not<KIND> &&x) {
941 if (auto array{ApplyElementwise(context, x)}) {
942 return *array;
943 }
944 using Ty = Type<TypeCategory::Logical, KIND>;
945 auto &operand{x.left()};
946 if (auto value{GetScalarConstantValue<Ty>(operand)}) {
947 return Expr<Ty>{Constant<Ty>{!value->IsTrue()}};
948 }
949 return Expr<Ty>{x};
950 }
951
952 template <int KIND>
953 Expr<Type<TypeCategory::Logical, KIND>> FoldOperation(
954 FoldingContext &context, LogicalOperation<KIND> &&operation) {
955 using LOGICAL = Type<TypeCategory::Logical, KIND>;
956 if (auto array{ApplyElementwise(context, operation,
957 std::function<Expr<LOGICAL>(Expr<LOGICAL> &&, Expr<LOGICAL> &&)>{
958 [=](Expr<LOGICAL> &&x, Expr<LOGICAL> &&y) {
959 return Expr<LOGICAL>{LogicalOperation<KIND>{
960 operation.logicalOperator, std::move(x), std::move(y)}};
961 }})}) {
962 return *array;
963 }
964 if (auto folded{OperandsAreConstants(operation)}) {
965 bool xt{folded->first.IsTrue()}, yt{folded->second.IsTrue()}, result{};
966 switch (operation.logicalOperator) {
967 case LogicalOperator::And:
968 result = xt && yt;
969 break;
970 case LogicalOperator::Or:
971 result = xt || yt;
972 break;
973 case LogicalOperator::Eqv:
974 result = xt == yt;
975 break;
976 case LogicalOperator::Neqv:
977 result = xt != yt;
978 break;
979 case LogicalOperator::Not:
980 DIE("not a binary operator");
981 }
982 return Expr<LOGICAL>{Constant<LOGICAL>{result}};
983 }
984 return Expr<LOGICAL>{std::move(operation)};
985 }
986
987 #ifdef _MSC_VER // disable bogus warning about missing definitions
988 #pragma warning(disable : 4661)
989 #endif
990 FOR_EACH_LOGICAL_KIND(template class ExpressionBase, )
991 template class ExpressionBase<SomeLogical>;
992 } // namespace Fortran::evaluate