1 //===-- lib/Evaluate/tools.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 "flang/Evaluate/tools.h"
10 #include "flang/Common/idioms.h"
11 #include "flang/Evaluate/characteristics.h"
12 #include "flang/Evaluate/traverse.h"
13 #include "flang/Parser/message.h"
14 #include "flang/Semantics/tools.h"
15 #include <algorithm>
16 #include <variant>
17 
18 using namespace Fortran::parser::literals;
19 
20 namespace Fortran::evaluate {
21 
22 // Can x*(a,b) be represented as (x*a,x*b)?  This code duplication
23 // of the subexpression "x" cannot (yet?) be reliably undone by
24 // common subexpression elimination in lowering, so it's disabled
25 // here for now to avoid the risk of potential duplication of
26 // expensive subexpressions (e.g., large array expressions, references
27 // to expensive functions) in generate code.
28 static constexpr bool allowOperandDuplication{false};
29 
30 std::optional<Expr<SomeType>> AsGenericExpr(DataRef &&ref) {
31   const Symbol &symbol{ref.GetLastSymbol()};
32   if (auto dyType{DynamicType::From(symbol)}) {
33     return TypedWrapper<Designator, DataRef>(*dyType, std::move(ref));
34   }
35   return std::nullopt;
36 }
37 
38 std::optional<Expr<SomeType>> AsGenericExpr(const Symbol &symbol) {
39   return AsGenericExpr(DataRef{symbol});
40 }
41 
42 Expr<SomeType> Parenthesize(Expr<SomeType> &&expr) {
43   return std::visit(
44       [&](auto &&x) {
45         using T = std::decay_t<decltype(x)>;
46         if constexpr (common::HasMember<T, TypelessExpression>) {
47           return expr; // no parentheses around typeless
48         } else if constexpr (std::is_same_v<T, Expr<SomeDerived>>) {
49           return AsGenericExpr(Parentheses<SomeDerived>{std::move(x)});
50         } else {
51           return std::visit(
52               [](auto &&y) {
53                 using T = ResultType<decltype(y)>;
54                 return AsGenericExpr(Parentheses<T>{std::move(y)});
55               },
56               std::move(x.u));
57         }
58       },
59       std::move(expr.u));
60 }
61 
62 std::optional<DataRef> ExtractDataRef(
63     const ActualArgument &arg, bool intoSubstring) {
64   if (const Expr<SomeType> *expr{arg.UnwrapExpr()}) {
65     return ExtractDataRef(*expr, intoSubstring);
66   } else {
67     return std::nullopt;
68   }
69 }
70 
71 std::optional<DataRef> ExtractSubstringBase(const Substring &substring) {
72   return std::visit(
73       common::visitors{
74           [&](const DataRef &x) -> std::optional<DataRef> { return x; },
75           [&](const StaticDataObject::Pointer &) -> std::optional<DataRef> {
76             return std::nullopt;
77           },
78       },
79       substring.parent());
80 }
81 
82 // IsVariable()
83 
84 auto IsVariableHelper::operator()(const Symbol &symbol) const -> Result {
85   const Symbol &root{GetAssociationRoot(symbol)};
86   return !IsNamedConstant(root) && root.has<semantics::ObjectEntityDetails>();
87 }
88 auto IsVariableHelper::operator()(const Component &x) const -> Result {
89   const Symbol &comp{x.GetLastSymbol()};
90   return (*this)(comp) && (IsPointer(comp) || (*this)(x.base()));
91 }
92 auto IsVariableHelper::operator()(const ArrayRef &x) const -> Result {
93   return (*this)(x.base());
94 }
95 auto IsVariableHelper::operator()(const Substring &x) const -> Result {
96   return (*this)(x.GetBaseObject());
97 }
98 auto IsVariableHelper::operator()(const ProcedureDesignator &x) const
99     -> Result {
100   if (const Symbol * symbol{x.GetSymbol()}) {
101     const Symbol *result{FindFunctionResult(*symbol)};
102     return result && IsPointer(*result) && !IsProcedurePointer(*result);
103   }
104   return false;
105 }
106 
107 // Conversions of COMPLEX component expressions to REAL.
108 ConvertRealOperandsResult ConvertRealOperands(
109     parser::ContextualMessages &messages, Expr<SomeType> &&x,
110     Expr<SomeType> &&y, int defaultRealKind) {
111   return std::visit(
112       common::visitors{
113           [&](Expr<SomeInteger> &&ix,
114               Expr<SomeInteger> &&iy) -> ConvertRealOperandsResult {
115             // Can happen in a CMPLX() constructor.  Per F'2018,
116             // both integer operands are converted to default REAL.
117             return {AsSameKindExprs<TypeCategory::Real>(
118                 ConvertToKind<TypeCategory::Real>(
119                     defaultRealKind, std::move(ix)),
120                 ConvertToKind<TypeCategory::Real>(
121                     defaultRealKind, std::move(iy)))};
122           },
123           [&](Expr<SomeInteger> &&ix,
124               Expr<SomeReal> &&ry) -> ConvertRealOperandsResult {
125             return {AsSameKindExprs<TypeCategory::Real>(
126                 ConvertTo(ry, std::move(ix)), std::move(ry))};
127           },
128           [&](Expr<SomeReal> &&rx,
129               Expr<SomeInteger> &&iy) -> ConvertRealOperandsResult {
130             return {AsSameKindExprs<TypeCategory::Real>(
131                 std::move(rx), ConvertTo(rx, std::move(iy)))};
132           },
133           [&](Expr<SomeReal> &&rx,
134               Expr<SomeReal> &&ry) -> ConvertRealOperandsResult {
135             return {AsSameKindExprs<TypeCategory::Real>(
136                 std::move(rx), std::move(ry))};
137           },
138           [&](Expr<SomeInteger> &&ix,
139               BOZLiteralConstant &&by) -> ConvertRealOperandsResult {
140             return {AsSameKindExprs<TypeCategory::Real>(
141                 ConvertToKind<TypeCategory::Real>(
142                     defaultRealKind, std::move(ix)),
143                 ConvertToKind<TypeCategory::Real>(
144                     defaultRealKind, std::move(by)))};
145           },
146           [&](BOZLiteralConstant &&bx,
147               Expr<SomeInteger> &&iy) -> ConvertRealOperandsResult {
148             return {AsSameKindExprs<TypeCategory::Real>(
149                 ConvertToKind<TypeCategory::Real>(
150                     defaultRealKind, std::move(bx)),
151                 ConvertToKind<TypeCategory::Real>(
152                     defaultRealKind, std::move(iy)))};
153           },
154           [&](Expr<SomeReal> &&rx,
155               BOZLiteralConstant &&by) -> ConvertRealOperandsResult {
156             return {AsSameKindExprs<TypeCategory::Real>(
157                 std::move(rx), ConvertTo(rx, std::move(by)))};
158           },
159           [&](BOZLiteralConstant &&bx,
160               Expr<SomeReal> &&ry) -> ConvertRealOperandsResult {
161             return {AsSameKindExprs<TypeCategory::Real>(
162                 ConvertTo(ry, std::move(bx)), std::move(ry))};
163           },
164           [&](auto &&, auto &&) -> ConvertRealOperandsResult { // C718
165             messages.Say("operands must be INTEGER or REAL"_err_en_US);
166             return std::nullopt;
167           },
168       },
169       std::move(x.u), std::move(y.u));
170 }
171 
172 // Helpers for NumericOperation and its subroutines below.
173 static std::optional<Expr<SomeType>> NoExpr() { return std::nullopt; }
174 
175 template <TypeCategory CAT>
176 std::optional<Expr<SomeType>> Package(Expr<SomeKind<CAT>> &&catExpr) {
177   return {AsGenericExpr(std::move(catExpr))};
178 }
179 template <TypeCategory CAT>
180 std::optional<Expr<SomeType>> Package(
181     std::optional<Expr<SomeKind<CAT>>> &&catExpr) {
182   if (catExpr) {
183     return {AsGenericExpr(std::move(*catExpr))};
184   }
185   return NoExpr();
186 }
187 
188 // Mixed REAL+INTEGER operations.  REAL**INTEGER is a special case that
189 // does not require conversion of the exponent expression.
190 template <template <typename> class OPR>
191 std::optional<Expr<SomeType>> MixedRealLeft(
192     Expr<SomeReal> &&rx, Expr<SomeInteger> &&iy) {
193   return Package(std::visit(
194       [&](auto &&rxk) -> Expr<SomeReal> {
195         using resultType = ResultType<decltype(rxk)>;
196         if constexpr (std::is_same_v<OPR<resultType>, Power<resultType>>) {
197           return AsCategoryExpr(
198               RealToIntPower<resultType>{std::move(rxk), std::move(iy)});
199         }
200         // G++ 8.1.0 emits bogus warnings about missing return statements if
201         // this statement is wrapped in an "else", as it should be.
202         return AsCategoryExpr(OPR<resultType>{
203             std::move(rxk), ConvertToType<resultType>(std::move(iy))});
204       },
205       std::move(rx.u)));
206 }
207 
208 std::optional<Expr<SomeComplex>> ConstructComplex(
209     parser::ContextualMessages &messages, Expr<SomeType> &&real,
210     Expr<SomeType> &&imaginary, int defaultRealKind) {
211   if (auto converted{ConvertRealOperands(
212           messages, std::move(real), std::move(imaginary), defaultRealKind)}) {
213     return {std::visit(
214         [](auto &&pair) {
215           return MakeComplex(std::move(pair[0]), std::move(pair[1]));
216         },
217         std::move(*converted))};
218   }
219   return std::nullopt;
220 }
221 
222 std::optional<Expr<SomeComplex>> ConstructComplex(
223     parser::ContextualMessages &messages, std::optional<Expr<SomeType>> &&real,
224     std::optional<Expr<SomeType>> &&imaginary, int defaultRealKind) {
225   if (auto parts{common::AllPresent(std::move(real), std::move(imaginary))}) {
226     return ConstructComplex(messages, std::get<0>(std::move(*parts)),
227         std::get<1>(std::move(*parts)), defaultRealKind);
228   }
229   return std::nullopt;
230 }
231 
232 Expr<SomeReal> GetComplexPart(const Expr<SomeComplex> &z, bool isImaginary) {
233   return std::visit(
234       [&](const auto &zk) {
235         static constexpr int kind{ResultType<decltype(zk)>::kind};
236         return AsCategoryExpr(ComplexComponent<kind>{isImaginary, zk});
237       },
238       z.u);
239 }
240 
241 // Convert REAL to COMPLEX of the same kind. Preserving the real operand kind
242 // and then applying complex operand promotion rules allows the result to have
243 // the highest precision of REAL and COMPLEX operands as required by Fortran
244 // 2018 10.9.1.3.
245 Expr<SomeComplex> PromoteRealToComplex(Expr<SomeReal> &&someX) {
246   return std::visit(
247       [](auto &&x) {
248         using RT = ResultType<decltype(x)>;
249         return AsCategoryExpr(ComplexConstructor<RT::kind>{
250             std::move(x), AsExpr(Constant<RT>{Scalar<RT>{}})});
251       },
252       std::move(someX.u));
253 }
254 
255 // Handle mixed COMPLEX+REAL (or INTEGER) operations in a better way
256 // than just converting the second operand to COMPLEX and performing the
257 // corresponding COMPLEX+COMPLEX operation.
258 template <template <typename> class OPR, TypeCategory RCAT>
259 std::optional<Expr<SomeType>> MixedComplexLeft(
260     parser::ContextualMessages &messages, Expr<SomeComplex> &&zx,
261     Expr<SomeKind<RCAT>> &&iry, [[maybe_unused]] int defaultRealKind) {
262   Expr<SomeReal> zr{GetComplexPart(zx, false)};
263   Expr<SomeReal> zi{GetComplexPart(zx, true)};
264   if constexpr (std::is_same_v<OPR<LargestReal>, Add<LargestReal>> ||
265       std::is_same_v<OPR<LargestReal>, Subtract<LargestReal>>) {
266     // (a,b) + x -> (a+x, b)
267     // (a,b) - x -> (a-x, b)
268     if (std::optional<Expr<SomeType>> rr{
269             NumericOperation<OPR>(messages, AsGenericExpr(std::move(zr)),
270                 AsGenericExpr(std::move(iry)), defaultRealKind)}) {
271       return Package(ConstructComplex(messages, std::move(*rr),
272           AsGenericExpr(std::move(zi)), defaultRealKind));
273     }
274   } else if constexpr (allowOperandDuplication &&
275       (std::is_same_v<OPR<LargestReal>, Multiply<LargestReal>> ||
276           std::is_same_v<OPR<LargestReal>, Divide<LargestReal>>)) {
277     // (a,b) * x -> (a*x, b*x)
278     // (a,b) / x -> (a/x, b/x)
279     auto copy{iry};
280     auto rr{NumericOperation<OPR>(messages, AsGenericExpr(std::move(zr)),
281         AsGenericExpr(std::move(iry)), defaultRealKind)};
282     auto ri{NumericOperation<OPR>(messages, AsGenericExpr(std::move(zi)),
283         AsGenericExpr(std::move(copy)), defaultRealKind)};
284     if (auto parts{common::AllPresent(std::move(rr), std::move(ri))}) {
285       return Package(ConstructComplex(messages, std::get<0>(std::move(*parts)),
286           std::get<1>(std::move(*parts)), defaultRealKind));
287     }
288   } else if constexpr (RCAT == TypeCategory::Integer &&
289       std::is_same_v<OPR<LargestReal>, Power<LargestReal>>) {
290     // COMPLEX**INTEGER is a special case that doesn't convert the exponent.
291     static_assert(RCAT == TypeCategory::Integer);
292     return Package(std::visit(
293         [&](auto &&zxk) {
294           using Ty = ResultType<decltype(zxk)>;
295           return AsCategoryExpr(
296               AsExpr(RealToIntPower<Ty>{std::move(zxk), std::move(iry)}));
297         },
298         std::move(zx.u)));
299   } else {
300     // (a,b) ** x -> (a,b) ** (x,0)
301     if constexpr (RCAT == TypeCategory::Integer) {
302       Expr<SomeComplex> zy{ConvertTo(zx, std::move(iry))};
303       return Package(PromoteAndCombine<OPR>(std::move(zx), std::move(zy)));
304     } else {
305       Expr<SomeComplex> zy{PromoteRealToComplex(std::move(iry))};
306       return Package(PromoteAndCombine<OPR>(std::move(zx), std::move(zy)));
307     }
308   }
309   return NoExpr();
310 }
311 
312 // Mixed COMPLEX operations with the COMPLEX operand on the right.
313 //  x + (a,b) -> (x+a, b)
314 //  x - (a,b) -> (x-a, -b)
315 //  x * (a,b) -> (x*a, x*b)
316 //  x / (a,b) -> (x,0) / (a,b)   (and **)
317 template <template <typename> class OPR, TypeCategory LCAT>
318 std::optional<Expr<SomeType>> MixedComplexRight(
319     parser::ContextualMessages &messages, Expr<SomeKind<LCAT>> &&irx,
320     Expr<SomeComplex> &&zy, [[maybe_unused]] int defaultRealKind) {
321   if constexpr (std::is_same_v<OPR<LargestReal>, Add<LargestReal>>) {
322     // x + (a,b) -> (a,b) + x -> (a+x, b)
323     return MixedComplexLeft<OPR, LCAT>(
324         messages, std::move(zy), std::move(irx), defaultRealKind);
325   } else if constexpr (allowOperandDuplication &&
326       std::is_same_v<OPR<LargestReal>, Multiply<LargestReal>>) {
327     // x * (a,b) -> (a,b) * x -> (a*x, b*x)
328     return MixedComplexLeft<OPR, LCAT>(
329         messages, std::move(zy), std::move(irx), defaultRealKind);
330   } else if constexpr (std::is_same_v<OPR<LargestReal>,
331                            Subtract<LargestReal>>) {
332     // x - (a,b) -> (x-a, -b)
333     Expr<SomeReal> zr{GetComplexPart(zy, false)};
334     Expr<SomeReal> zi{GetComplexPart(zy, true)};
335     if (std::optional<Expr<SomeType>> rr{
336             NumericOperation<Subtract>(messages, AsGenericExpr(std::move(irx)),
337                 AsGenericExpr(std::move(zr)), defaultRealKind)}) {
338       return Package(ConstructComplex(messages, std::move(*rr),
339           AsGenericExpr(-std::move(zi)), defaultRealKind));
340     }
341   } else {
342     // x / (a,b) -> (x,0) / (a,b)
343     if constexpr (LCAT == TypeCategory::Integer) {
344       Expr<SomeComplex> zx{ConvertTo(zy, std::move(irx))};
345       return Package(PromoteAndCombine<OPR>(std::move(zx), std::move(zy)));
346     } else {
347       Expr<SomeComplex> zx{PromoteRealToComplex(std::move(irx))};
348       return Package(PromoteAndCombine<OPR>(std::move(zx), std::move(zy)));
349     }
350   }
351   return NoExpr();
352 }
353 
354 // N.B. When a "typeless" BOZ literal constant appears as one (not both!) of
355 // the operands to a dyadic operation where one is permitted, it assumes the
356 // type and kind of the other operand.
357 template <template <typename> class OPR>
358 std::optional<Expr<SomeType>> NumericOperation(
359     parser::ContextualMessages &messages, Expr<SomeType> &&x,
360     Expr<SomeType> &&y, int defaultRealKind) {
361   return std::visit(
362       common::visitors{
363           [](Expr<SomeInteger> &&ix, Expr<SomeInteger> &&iy) {
364             return Package(PromoteAndCombine<OPR, TypeCategory::Integer>(
365                 std::move(ix), std::move(iy)));
366           },
367           [](Expr<SomeReal> &&rx, Expr<SomeReal> &&ry) {
368             return Package(PromoteAndCombine<OPR, TypeCategory::Real>(
369                 std::move(rx), std::move(ry)));
370           },
371           // Mixed REAL/INTEGER operations
372           [](Expr<SomeReal> &&rx, Expr<SomeInteger> &&iy) {
373             return MixedRealLeft<OPR>(std::move(rx), std::move(iy));
374           },
375           [](Expr<SomeInteger> &&ix, Expr<SomeReal> &&ry) {
376             return Package(std::visit(
377                 [&](auto &&ryk) -> Expr<SomeReal> {
378                   using resultType = ResultType<decltype(ryk)>;
379                   return AsCategoryExpr(
380                       OPR<resultType>{ConvertToType<resultType>(std::move(ix)),
381                           std::move(ryk)});
382                 },
383                 std::move(ry.u)));
384           },
385           // Homogeneous and mixed COMPLEX operations
386           [](Expr<SomeComplex> &&zx, Expr<SomeComplex> &&zy) {
387             return Package(PromoteAndCombine<OPR, TypeCategory::Complex>(
388                 std::move(zx), std::move(zy)));
389           },
390           [&](Expr<SomeComplex> &&zx, Expr<SomeInteger> &&iy) {
391             return MixedComplexLeft<OPR>(
392                 messages, std::move(zx), std::move(iy), defaultRealKind);
393           },
394           [&](Expr<SomeComplex> &&zx, Expr<SomeReal> &&ry) {
395             return MixedComplexLeft<OPR>(
396                 messages, std::move(zx), std::move(ry), defaultRealKind);
397           },
398           [&](Expr<SomeInteger> &&ix, Expr<SomeComplex> &&zy) {
399             return MixedComplexRight<OPR>(
400                 messages, std::move(ix), std::move(zy), defaultRealKind);
401           },
402           [&](Expr<SomeReal> &&rx, Expr<SomeComplex> &&zy) {
403             return MixedComplexRight<OPR>(
404                 messages, std::move(rx), std::move(zy), defaultRealKind);
405           },
406           // Operations with one typeless operand
407           [&](BOZLiteralConstant &&bx, Expr<SomeInteger> &&iy) {
408             return NumericOperation<OPR>(messages,
409                 AsGenericExpr(ConvertTo(iy, std::move(bx))), std::move(y),
410                 defaultRealKind);
411           },
412           [&](BOZLiteralConstant &&bx, Expr<SomeReal> &&ry) {
413             return NumericOperation<OPR>(messages,
414                 AsGenericExpr(ConvertTo(ry, std::move(bx))), std::move(y),
415                 defaultRealKind);
416           },
417           [&](Expr<SomeInteger> &&ix, BOZLiteralConstant &&by) {
418             return NumericOperation<OPR>(messages, std::move(x),
419                 AsGenericExpr(ConvertTo(ix, std::move(by))), defaultRealKind);
420           },
421           [&](Expr<SomeReal> &&rx, BOZLiteralConstant &&by) {
422             return NumericOperation<OPR>(messages, std::move(x),
423                 AsGenericExpr(ConvertTo(rx, std::move(by))), defaultRealKind);
424           },
425           // Default case
426           [&](auto &&, auto &&) {
427             // TODO: defined operator
428             messages.Say("non-numeric operands to numeric operation"_err_en_US);
429             return NoExpr();
430           },
431       },
432       std::move(x.u), std::move(y.u));
433 }
434 
435 template std::optional<Expr<SomeType>> NumericOperation<Power>(
436     parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
437     int defaultRealKind);
438 template std::optional<Expr<SomeType>> NumericOperation<Multiply>(
439     parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
440     int defaultRealKind);
441 template std::optional<Expr<SomeType>> NumericOperation<Divide>(
442     parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
443     int defaultRealKind);
444 template std::optional<Expr<SomeType>> NumericOperation<Add>(
445     parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
446     int defaultRealKind);
447 template std::optional<Expr<SomeType>> NumericOperation<Subtract>(
448     parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
449     int defaultRealKind);
450 
451 std::optional<Expr<SomeType>> Negation(
452     parser::ContextualMessages &messages, Expr<SomeType> &&x) {
453   return std::visit(
454       common::visitors{
455           [&](BOZLiteralConstant &&) {
456             messages.Say("BOZ literal cannot be negated"_err_en_US);
457             return NoExpr();
458           },
459           [&](NullPointer &&) {
460             messages.Say("NULL() cannot be negated"_err_en_US);
461             return NoExpr();
462           },
463           [&](ProcedureDesignator &&) {
464             messages.Say("Subroutine cannot be negated"_err_en_US);
465             return NoExpr();
466           },
467           [&](ProcedureRef &&) {
468             messages.Say("Pointer to subroutine cannot be negated"_err_en_US);
469             return NoExpr();
470           },
471           [&](Expr<SomeInteger> &&x) { return Package(-std::move(x)); },
472           [&](Expr<SomeReal> &&x) { return Package(-std::move(x)); },
473           [&](Expr<SomeComplex> &&x) { return Package(-std::move(x)); },
474           [&](Expr<SomeCharacter> &&) {
475             // TODO: defined operator
476             messages.Say("CHARACTER cannot be negated"_err_en_US);
477             return NoExpr();
478           },
479           [&](Expr<SomeLogical> &&) {
480             // TODO: defined operator
481             messages.Say("LOGICAL cannot be negated"_err_en_US);
482             return NoExpr();
483           },
484           [&](Expr<SomeDerived> &&) {
485             // TODO: defined operator
486             messages.Say("Operand cannot be negated"_err_en_US);
487             return NoExpr();
488           },
489       },
490       std::move(x.u));
491 }
492 
493 Expr<SomeLogical> LogicalNegation(Expr<SomeLogical> &&x) {
494   return std::visit(
495       [](auto &&xk) { return AsCategoryExpr(LogicalNegation(std::move(xk))); },
496       std::move(x.u));
497 }
498 
499 template <TypeCategory CAT>
500 Expr<LogicalResult> PromoteAndRelate(
501     RelationalOperator opr, Expr<SomeKind<CAT>> &&x, Expr<SomeKind<CAT>> &&y) {
502   return std::visit(
503       [=](auto &&xy) {
504         return PackageRelation(opr, std::move(xy[0]), std::move(xy[1]));
505       },
506       AsSameKindExprs(std::move(x), std::move(y)));
507 }
508 
509 std::optional<Expr<LogicalResult>> Relate(parser::ContextualMessages &messages,
510     RelationalOperator opr, Expr<SomeType> &&x, Expr<SomeType> &&y) {
511   return std::visit(
512       common::visitors{
513           [=](Expr<SomeInteger> &&ix,
514               Expr<SomeInteger> &&iy) -> std::optional<Expr<LogicalResult>> {
515             return PromoteAndRelate(opr, std::move(ix), std::move(iy));
516           },
517           [=](Expr<SomeReal> &&rx,
518               Expr<SomeReal> &&ry) -> std::optional<Expr<LogicalResult>> {
519             return PromoteAndRelate(opr, std::move(rx), std::move(ry));
520           },
521           [&](Expr<SomeReal> &&rx, Expr<SomeInteger> &&iy) {
522             return Relate(messages, opr, std::move(x),
523                 AsGenericExpr(ConvertTo(rx, std::move(iy))));
524           },
525           [&](Expr<SomeInteger> &&ix, Expr<SomeReal> &&ry) {
526             return Relate(messages, opr,
527                 AsGenericExpr(ConvertTo(ry, std::move(ix))), std::move(y));
528           },
529           [&](Expr<SomeComplex> &&zx,
530               Expr<SomeComplex> &&zy) -> std::optional<Expr<LogicalResult>> {
531             if (opr == RelationalOperator::EQ ||
532                 opr == RelationalOperator::NE) {
533               return PromoteAndRelate(opr, std::move(zx), std::move(zy));
534             } else {
535               messages.Say(
536                   "COMPLEX data may be compared only for equality"_err_en_US);
537               return std::nullopt;
538             }
539           },
540           [&](Expr<SomeComplex> &&zx, Expr<SomeInteger> &&iy) {
541             return Relate(messages, opr, std::move(x),
542                 AsGenericExpr(ConvertTo(zx, std::move(iy))));
543           },
544           [&](Expr<SomeComplex> &&zx, Expr<SomeReal> &&ry) {
545             return Relate(messages, opr, std::move(x),
546                 AsGenericExpr(ConvertTo(zx, std::move(ry))));
547           },
548           [&](Expr<SomeInteger> &&ix, Expr<SomeComplex> &&zy) {
549             return Relate(messages, opr,
550                 AsGenericExpr(ConvertTo(zy, std::move(ix))), std::move(y));
551           },
552           [&](Expr<SomeReal> &&rx, Expr<SomeComplex> &&zy) {
553             return Relate(messages, opr,
554                 AsGenericExpr(ConvertTo(zy, std::move(rx))), std::move(y));
555           },
556           [&](Expr<SomeCharacter> &&cx, Expr<SomeCharacter> &&cy) {
557             return std::visit(
558                 [&](auto &&cxk,
559                     auto &&cyk) -> std::optional<Expr<LogicalResult>> {
560                   using Ty = ResultType<decltype(cxk)>;
561                   if constexpr (std::is_same_v<Ty, ResultType<decltype(cyk)>>) {
562                     return PackageRelation(opr, std::move(cxk), std::move(cyk));
563                   } else {
564                     messages.Say(
565                         "CHARACTER operands do not have same KIND"_err_en_US);
566                     return std::nullopt;
567                   }
568                 },
569                 std::move(cx.u), std::move(cy.u));
570           },
571           // Default case
572           [&](auto &&, auto &&) {
573             DIE("invalid types for relational operator");
574             return std::optional<Expr<LogicalResult>>{};
575           },
576       },
577       std::move(x.u), std::move(y.u));
578 }
579 
580 Expr<SomeLogical> BinaryLogicalOperation(
581     LogicalOperator opr, Expr<SomeLogical> &&x, Expr<SomeLogical> &&y) {
582   CHECK(opr != LogicalOperator::Not);
583   return std::visit(
584       [=](auto &&xy) {
585         using Ty = ResultType<decltype(xy[0])>;
586         return Expr<SomeLogical>{BinaryLogicalOperation<Ty::kind>(
587             opr, std::move(xy[0]), std::move(xy[1]))};
588       },
589       AsSameKindExprs(std::move(x), std::move(y)));
590 }
591 
592 template <TypeCategory TO>
593 std::optional<Expr<SomeType>> ConvertToNumeric(int kind, Expr<SomeType> &&x) {
594   static_assert(common::IsNumericTypeCategory(TO));
595   return std::visit(
596       [=](auto &&cx) -> std::optional<Expr<SomeType>> {
597         using cxType = std::decay_t<decltype(cx)>;
598         if constexpr (!common::HasMember<cxType, TypelessExpression>) {
599           if constexpr (IsNumericTypeCategory(ResultType<cxType>::category)) {
600             return Expr<SomeType>{ConvertToKind<TO>(kind, std::move(cx))};
601           }
602         }
603         return std::nullopt;
604       },
605       std::move(x.u));
606 }
607 
608 std::optional<Expr<SomeType>> ConvertToType(
609     const DynamicType &type, Expr<SomeType> &&x) {
610   if (type.IsTypelessIntrinsicArgument()) {
611     return std::nullopt;
612   }
613   switch (type.category()) {
614   case TypeCategory::Integer:
615     if (auto *boz{std::get_if<BOZLiteralConstant>(&x.u)}) {
616       // Extension to C7109: allow BOZ literals to appear in integer contexts
617       // when the type is unambiguous.
618       return Expr<SomeType>{
619           ConvertToKind<TypeCategory::Integer>(type.kind(), std::move(*boz))};
620     }
621     return ConvertToNumeric<TypeCategory::Integer>(type.kind(), std::move(x));
622   case TypeCategory::Real:
623     if (auto *boz{std::get_if<BOZLiteralConstant>(&x.u)}) {
624       return Expr<SomeType>{
625           ConvertToKind<TypeCategory::Real>(type.kind(), std::move(*boz))};
626     }
627     return ConvertToNumeric<TypeCategory::Real>(type.kind(), std::move(x));
628   case TypeCategory::Complex:
629     return ConvertToNumeric<TypeCategory::Complex>(type.kind(), std::move(x));
630   case TypeCategory::Character:
631     if (auto *cx{UnwrapExpr<Expr<SomeCharacter>>(x)}) {
632       auto converted{
633           ConvertToKind<TypeCategory::Character>(type.kind(), std::move(*cx))};
634       if (auto length{type.GetCharLength()}) {
635         converted = std::visit(
636             [&](auto &&x) {
637               using Ty = std::decay_t<decltype(x)>;
638               using CharacterType = typename Ty::Result;
639               return Expr<SomeCharacter>{
640                   Expr<CharacterType>{SetLength<CharacterType::kind>{
641                       std::move(x), std::move(*length)}}};
642             },
643             std::move(converted.u));
644       }
645       return Expr<SomeType>{std::move(converted)};
646     }
647     break;
648   case TypeCategory::Logical:
649     if (auto *cx{UnwrapExpr<Expr<SomeLogical>>(x)}) {
650       return Expr<SomeType>{
651           ConvertToKind<TypeCategory::Logical>(type.kind(), std::move(*cx))};
652     }
653     break;
654   case TypeCategory::Derived:
655     if (auto fromType{x.GetType()}) {
656       if (type == *fromType) {
657         return std::move(x);
658       }
659     }
660     break;
661   }
662   return std::nullopt;
663 }
664 
665 std::optional<Expr<SomeType>> ConvertToType(
666     const DynamicType &to, std::optional<Expr<SomeType>> &&x) {
667   if (x) {
668     return ConvertToType(to, std::move(*x));
669   } else {
670     return std::nullopt;
671   }
672 }
673 
674 std::optional<Expr<SomeType>> ConvertToType(
675     const Symbol &symbol, Expr<SomeType> &&x) {
676   if (auto symType{DynamicType::From(symbol)}) {
677     return ConvertToType(*symType, std::move(x));
678   }
679   return std::nullopt;
680 }
681 
682 std::optional<Expr<SomeType>> ConvertToType(
683     const Symbol &to, std::optional<Expr<SomeType>> &&x) {
684   if (x) {
685     return ConvertToType(to, std::move(*x));
686   } else {
687     return std::nullopt;
688   }
689 }
690 
691 bool IsAssumedRank(const Symbol &original) {
692   if (const auto *assoc{original.detailsIf<semantics::AssocEntityDetails>()}) {
693     if (assoc->rank()) {
694       return false; // in SELECT RANK case
695     }
696   }
697   const Symbol &symbol{semantics::ResolveAssociations(original)};
698   if (const auto *details{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
699     return details->IsAssumedRank();
700   } else {
701     return false;
702   }
703 }
704 
705 bool IsAssumedRank(const ActualArgument &arg) {
706   if (const auto *expr{arg.UnwrapExpr()}) {
707     return IsAssumedRank(*expr);
708   } else {
709     const Symbol *assumedTypeDummy{arg.GetAssumedTypeDummy()};
710     CHECK(assumedTypeDummy);
711     return IsAssumedRank(*assumedTypeDummy);
712   }
713 }
714 
715 bool IsCoarray(const ActualArgument &arg) {
716   const auto *expr{arg.UnwrapExpr()};
717   return expr && IsCoarray(*expr);
718 }
719 
720 bool IsCoarray(const Symbol &symbol) {
721   return GetAssociationRoot(symbol).Corank() > 0;
722 }
723 
724 bool IsProcedure(const Expr<SomeType> &expr) {
725   return std::holds_alternative<ProcedureDesignator>(expr.u);
726 }
727 bool IsFunction(const Expr<SomeType> &expr) {
728   const auto *designator{std::get_if<ProcedureDesignator>(&expr.u)};
729   return designator && designator->GetType().has_value();
730 }
731 
732 bool IsProcedurePointerTarget(const Expr<SomeType> &expr) {
733   return std::visit(common::visitors{
734                         [](const NullPointer &) { return true; },
735                         [](const ProcedureDesignator &) { return true; },
736                         [](const ProcedureRef &) { return true; },
737                         [&](const auto &) {
738                           const Symbol *last{GetLastSymbol(expr)};
739                           return last && IsProcedurePointer(*last);
740                         },
741                     },
742       expr.u);
743 }
744 
745 template <typename A> inline const ProcedureRef *UnwrapProcedureRef(const A &) {
746   return nullptr;
747 }
748 
749 template <typename T>
750 inline const ProcedureRef *UnwrapProcedureRef(const FunctionRef<T> &func) {
751   return &func;
752 }
753 
754 template <typename T>
755 inline const ProcedureRef *UnwrapProcedureRef(const Expr<T> &expr) {
756   return std::visit(
757       [](const auto &x) { return UnwrapProcedureRef(x); }, expr.u);
758 }
759 
760 // IsObjectPointer()
761 bool IsObjectPointer(const Expr<SomeType> &expr, FoldingContext &context) {
762   if (IsNullPointer(expr)) {
763     return true;
764   } else if (IsProcedurePointerTarget(expr)) {
765     return false;
766   } else if (const auto *funcRef{UnwrapProcedureRef(expr)}) {
767     return IsVariable(*funcRef);
768   } else if (const Symbol * symbol{GetLastSymbol(expr)}) {
769     return IsPointer(symbol->GetUltimate());
770   } else {
771     return false;
772   }
773 }
774 
775 bool IsBareNullPointer(const Expr<SomeType> *expr) {
776   return expr && std::holds_alternative<NullPointer>(expr->u);
777 }
778 
779 // IsNullPointer()
780 struct IsNullPointerHelper {
781   template <typename A> bool operator()(const A &) const { return false; }
782   template <typename T> bool operator()(const FunctionRef<T> &call) const {
783     const auto *intrinsic{call.proc().GetSpecificIntrinsic()};
784     return intrinsic &&
785         intrinsic->characteristics.value().attrs.test(
786             characteristics::Procedure::Attr::NullPointer);
787   }
788   bool operator()(const NullPointer &) const { return true; }
789   template <typename T> bool operator()(const Parentheses<T> &x) const {
790     return (*this)(x.left());
791   }
792   template <typename T> bool operator()(const Expr<T> &x) const {
793     return std::visit(*this, x.u);
794   }
795 };
796 
797 bool IsNullPointer(const Expr<SomeType> &expr) {
798   return IsNullPointerHelper{}(expr);
799 }
800 
801 // GetSymbolVector()
802 auto GetSymbolVectorHelper::operator()(const Symbol &x) const -> Result {
803   if (const auto *details{x.detailsIf<semantics::AssocEntityDetails>()}) {
804     return (*this)(details->expr());
805   } else {
806     return {x.GetUltimate()};
807   }
808 }
809 auto GetSymbolVectorHelper::operator()(const Component &x) const -> Result {
810   Result result{(*this)(x.base())};
811   result.emplace_back(x.GetLastSymbol());
812   return result;
813 }
814 auto GetSymbolVectorHelper::operator()(const ArrayRef &x) const -> Result {
815   return GetSymbolVector(x.base());
816 }
817 auto GetSymbolVectorHelper::operator()(const CoarrayRef &x) const -> Result {
818   return x.base();
819 }
820 
821 const Symbol *GetLastTarget(const SymbolVector &symbols) {
822   auto end{std::crend(symbols)};
823   // N.B. Neither clang nor g++ recognizes "symbols.crbegin()" here.
824   auto iter{std::find_if(std::crbegin(symbols), end, [](const Symbol &x) {
825     return x.attrs().HasAny(
826         {semantics::Attr::POINTER, semantics::Attr::TARGET});
827   })};
828   return iter == end ? nullptr : &**iter;
829 }
830 
831 struct CollectSymbolsHelper
832     : public SetTraverse<CollectSymbolsHelper, semantics::UnorderedSymbolSet> {
833   using Base = SetTraverse<CollectSymbolsHelper, semantics::UnorderedSymbolSet>;
834   CollectSymbolsHelper() : Base{*this} {}
835   using Base::operator();
836   semantics::UnorderedSymbolSet operator()(const Symbol &symbol) const {
837     return {symbol};
838   }
839 };
840 template <typename A> semantics::UnorderedSymbolSet CollectSymbols(const A &x) {
841   return CollectSymbolsHelper{}(x);
842 }
843 template semantics::UnorderedSymbolSet CollectSymbols(const Expr<SomeType> &);
844 template semantics::UnorderedSymbolSet CollectSymbols(
845     const Expr<SomeInteger> &);
846 template semantics::UnorderedSymbolSet CollectSymbols(
847     const Expr<SubscriptInteger> &);
848 
849 // HasVectorSubscript()
850 struct HasVectorSubscriptHelper : public AnyTraverse<HasVectorSubscriptHelper> {
851   using Base = AnyTraverse<HasVectorSubscriptHelper>;
852   HasVectorSubscriptHelper() : Base{*this} {}
853   using Base::operator();
854   bool operator()(const Subscript &ss) const {
855     return !std::holds_alternative<Triplet>(ss.u) && ss.Rank() > 0;
856   }
857   bool operator()(const ProcedureRef &) const {
858     return false; // don't descend into function call arguments
859   }
860 };
861 
862 bool HasVectorSubscript(const Expr<SomeType> &expr) {
863   return HasVectorSubscriptHelper{}(expr);
864 }
865 
866 parser::Message *AttachDeclaration(
867     parser::Message &message, const Symbol &symbol) {
868   const Symbol *unhosted{&symbol};
869   while (
870       const auto *assoc{unhosted->detailsIf<semantics::HostAssocDetails>()}) {
871     unhosted = &assoc->symbol();
872   }
873   if (const auto *binding{
874           unhosted->detailsIf<semantics::ProcBindingDetails>()}) {
875     if (binding->symbol().name() != symbol.name()) {
876       message.Attach(binding->symbol().name(),
877           "Procedure '%s' of type '%s' is bound to '%s'"_en_US, symbol.name(),
878           symbol.owner().GetName().value(), binding->symbol().name());
879       return &message;
880     }
881     unhosted = &binding->symbol();
882   }
883   if (const auto *use{symbol.detailsIf<semantics::UseDetails>()}) {
884     message.Attach(use->location(),
885         "'%s' is USE-associated with '%s' in module '%s'"_en_US, symbol.name(),
886         unhosted->name(), GetUsedModule(*use).name());
887   } else {
888     message.Attach(
889         unhosted->name(), "Declaration of '%s'"_en_US, unhosted->name());
890   }
891   return &message;
892 }
893 
894 parser::Message *AttachDeclaration(
895     parser::Message *message, const Symbol &symbol) {
896   return message ? AttachDeclaration(*message, symbol) : nullptr;
897 }
898 
899 class FindImpureCallHelper
900     : public AnyTraverse<FindImpureCallHelper, std::optional<std::string>> {
901   using Result = std::optional<std::string>;
902   using Base = AnyTraverse<FindImpureCallHelper, Result>;
903 
904 public:
905   explicit FindImpureCallHelper(FoldingContext &c) : Base{*this}, context_{c} {}
906   using Base::operator();
907   Result operator()(const ProcedureRef &call) const {
908     if (auto chars{
909             characteristics::Procedure::Characterize(call.proc(), context_)}) {
910       if (chars->attrs.test(characteristics::Procedure::Attr::Pure)) {
911         return (*this)(call.arguments());
912       }
913     }
914     return call.proc().GetName();
915   }
916 
917 private:
918   FoldingContext &context_;
919 };
920 
921 std::optional<std::string> FindImpureCall(
922     FoldingContext &context, const Expr<SomeType> &expr) {
923   return FindImpureCallHelper{context}(expr);
924 }
925 std::optional<std::string> FindImpureCall(
926     FoldingContext &context, const ProcedureRef &proc) {
927   return FindImpureCallHelper{context}(proc);
928 }
929 
930 // Compare procedure characteristics for equality except that rhs may be
931 // Pure or Elemental when lhs is not.
932 static bool CharacteristicsMatch(const characteristics::Procedure &lhs,
933     const characteristics::Procedure &rhs) {
934   using Attr = characteristics::Procedure::Attr;
935   auto lhsAttrs{lhs.attrs};
936   lhsAttrs.set(
937       Attr::Pure, lhs.attrs.test(Attr::Pure) || rhs.attrs.test(Attr::Pure));
938   lhsAttrs.set(Attr::Elemental,
939       lhs.attrs.test(Attr::Elemental) || rhs.attrs.test(Attr::Elemental));
940   return lhsAttrs == rhs.attrs && lhs.functionResult == rhs.functionResult &&
941       lhs.dummyArguments == rhs.dummyArguments;
942 }
943 
944 // Common handling for procedure pointer compatibility of left- and right-hand
945 // sides.  Returns nullopt if they're compatible.  Otherwise, it returns a
946 // message that needs to be augmented by the names of the left and right sides
947 std::optional<parser::MessageFixedText> CheckProcCompatibility(bool isCall,
948     const std::optional<characteristics::Procedure> &lhsProcedure,
949     const characteristics::Procedure *rhsProcedure) {
950   std::optional<parser::MessageFixedText> msg;
951   if (!lhsProcedure) {
952     msg = "In assignment to object %s, the target '%s' is a procedure"
953           " designator"_err_en_US;
954   } else if (!rhsProcedure) {
955     msg = "In assignment to procedure %s, the characteristics of the target"
956           " procedure '%s' could not be determined"_err_en_US;
957   } else if (CharacteristicsMatch(*lhsProcedure, *rhsProcedure)) {
958     // OK
959   } else if (isCall) {
960     msg = "Procedure %s associated with result of reference to function '%s'"
961           " that is an incompatible procedure pointer"_err_en_US;
962   } else if (lhsProcedure->IsPure() && !rhsProcedure->IsPure()) {
963     msg = "PURE procedure %s may not be associated with non-PURE"
964           " procedure designator '%s'"_err_en_US;
965   } else if (lhsProcedure->IsFunction() && !rhsProcedure->IsFunction()) {
966     msg = "Function %s may not be associated with subroutine"
967           " designator '%s'"_err_en_US;
968   } else if (!lhsProcedure->IsFunction() && rhsProcedure->IsFunction()) {
969     msg = "Subroutine %s may not be associated with function"
970           " designator '%s'"_err_en_US;
971   } else if (lhsProcedure->HasExplicitInterface() &&
972       !rhsProcedure->HasExplicitInterface()) {
973     // Section 10.2.2.4, paragraph 3 prohibits associating a procedure pointer
974     // with an explicit interface with a procedure whose characteristics don't
975     // match.  That's the case if the target procedure has an implicit
976     // interface.  But this case is allowed by several other compilers as long
977     // as the explicit interface can be called via an implicit interface.
978     if (!lhsProcedure->CanBeCalledViaImplicitInterface()) {
979       msg = "Procedure %s with explicit interface that cannot be called via "
980             "an implicit interface cannot be associated with procedure "
981             "designator with an implicit interface"_err_en_US;
982     }
983   } else if (!lhsProcedure->HasExplicitInterface() &&
984       rhsProcedure->HasExplicitInterface()) {
985     // OK if the target can be called via an implicit interface
986     if (!rhsProcedure->CanBeCalledViaImplicitInterface()) {
987       msg = "Procedure %s with implicit interface may not be associated "
988             "with procedure designator '%s' with explicit interface that "
989             "cannot be called via an implicit interface"_err_en_US;
990     }
991   } else {
992     msg = "Procedure %s associated with incompatible procedure"
993           " designator '%s'"_err_en_US;
994   }
995   return msg;
996 }
997 
998 // GetLastPointerSymbol()
999 static const Symbol *GetLastPointerSymbol(const Symbol &symbol) {
1000   return IsPointer(GetAssociationRoot(symbol)) ? &symbol : nullptr;
1001 }
1002 static const Symbol *GetLastPointerSymbol(const SymbolRef &symbol) {
1003   return GetLastPointerSymbol(*symbol);
1004 }
1005 static const Symbol *GetLastPointerSymbol(const Component &x) {
1006   const Symbol &c{x.GetLastSymbol()};
1007   return IsPointer(c) ? &c : GetLastPointerSymbol(x.base());
1008 }
1009 static const Symbol *GetLastPointerSymbol(const NamedEntity &x) {
1010   const auto *c{x.UnwrapComponent()};
1011   return c ? GetLastPointerSymbol(*c) : GetLastPointerSymbol(x.GetLastSymbol());
1012 }
1013 static const Symbol *GetLastPointerSymbol(const ArrayRef &x) {
1014   return GetLastPointerSymbol(x.base());
1015 }
1016 static const Symbol *GetLastPointerSymbol(const CoarrayRef &x) {
1017   return nullptr;
1018 }
1019 const Symbol *GetLastPointerSymbol(const DataRef &x) {
1020   return std::visit([](const auto &y) { return GetLastPointerSymbol(y); }, x.u);
1021 }
1022 
1023 template <TypeCategory TO, TypeCategory FROM>
1024 static std::optional<Expr<SomeType>> DataConstantConversionHelper(
1025     FoldingContext &context, const DynamicType &toType,
1026     const Expr<SomeType> &expr) {
1027   DynamicType sizedType{FROM, toType.kind()};
1028   if (auto sized{
1029           Fold(context, ConvertToType(sizedType, Expr<SomeType>{expr}))}) {
1030     if (const auto *someExpr{UnwrapExpr<Expr<SomeKind<FROM>>>(*sized)}) {
1031       return std::visit(
1032           [](const auto &w) -> std::optional<Expr<SomeType>> {
1033             using FromType = typename std::decay_t<decltype(w)>::Result;
1034             static constexpr int kind{FromType::kind};
1035             if constexpr (IsValidKindOfIntrinsicType(TO, kind)) {
1036               if (const auto *fromConst{UnwrapExpr<Constant<FromType>>(w)}) {
1037                 using FromWordType = typename FromType::Scalar;
1038                 using LogicalType = value::Logical<FromWordType::bits>;
1039                 using ElementType =
1040                     std::conditional_t<TO == TypeCategory::Logical, LogicalType,
1041                         typename LogicalType::Word>;
1042                 std::vector<ElementType> values;
1043                 auto at{fromConst->lbounds()};
1044                 auto shape{fromConst->shape()};
1045                 for (auto n{GetSize(shape)}; n-- > 0;
1046                      fromConst->IncrementSubscripts(at)) {
1047                   auto elt{fromConst->At(at)};
1048                   if constexpr (TO == TypeCategory::Logical) {
1049                     values.emplace_back(std::move(elt));
1050                   } else {
1051                     values.emplace_back(elt.word());
1052                   }
1053                 }
1054                 return {AsGenericExpr(AsExpr(Constant<Type<TO, kind>>{
1055                     std::move(values), std::move(shape)}))};
1056               }
1057             }
1058             return std::nullopt;
1059           },
1060           someExpr->u);
1061     }
1062   }
1063   return std::nullopt;
1064 }
1065 
1066 std::optional<Expr<SomeType>> DataConstantConversionExtension(
1067     FoldingContext &context, const DynamicType &toType,
1068     const Expr<SomeType> &expr0) {
1069   Expr<SomeType> expr{Fold(context, Expr<SomeType>{expr0})};
1070   if (!IsActuallyConstant(expr)) {
1071     return std::nullopt;
1072   }
1073   if (auto fromType{expr.GetType()}) {
1074     if (toType.category() == TypeCategory::Logical &&
1075         fromType->category() == TypeCategory::Integer) {
1076       return DataConstantConversionHelper<TypeCategory::Logical,
1077           TypeCategory::Integer>(context, toType, expr);
1078     }
1079     if (toType.category() == TypeCategory::Integer &&
1080         fromType->category() == TypeCategory::Logical) {
1081       return DataConstantConversionHelper<TypeCategory::Integer,
1082           TypeCategory::Logical>(context, toType, expr);
1083     }
1084   }
1085   return std::nullopt;
1086 }
1087 
1088 bool IsAllocatableOrPointerObject(
1089     const Expr<SomeType> &expr, FoldingContext &context) {
1090   const semantics::Symbol *sym{UnwrapWholeSymbolOrComponentDataRef(expr)};
1091   return (sym && semantics::IsAllocatableOrPointer(*sym)) ||
1092       evaluate::IsObjectPointer(expr, context);
1093 }
1094 
1095 bool MayBePassedAsAbsentOptional(
1096     const Expr<SomeType> &expr, FoldingContext &context) {
1097   const semantics::Symbol *sym{UnwrapWholeSymbolOrComponentDataRef(expr)};
1098   // 15.5.2.12 1. is pretty clear that an unallocated allocatable/pointer actual
1099   // may be passed to a non-allocatable/non-pointer optional dummy. Note that
1100   // other compilers (like nag, nvfortran, ifort, gfortran and xlf) seems to
1101   // ignore this point in intrinsic contexts (e.g CMPLX argument).
1102   return (sym && semantics::IsOptional(*sym)) ||
1103       IsAllocatableOrPointerObject(expr, context);
1104 }
1105 
1106 } // namespace Fortran::evaluate
1107 
1108 namespace Fortran::semantics {
1109 
1110 const Symbol &ResolveAssociations(const Symbol &original) {
1111   const Symbol &symbol{original.GetUltimate()};
1112   if (const auto *details{symbol.detailsIf<AssocEntityDetails>()}) {
1113     if (const Symbol * nested{UnwrapWholeSymbolDataRef(details->expr())}) {
1114       return ResolveAssociations(*nested);
1115     }
1116   }
1117   return symbol;
1118 }
1119 
1120 // When a construct association maps to a variable, and that variable
1121 // is not an array with a vector-valued subscript, return the base
1122 // Symbol of that variable, else nullptr.  Descends into other construct
1123 // associations when one associations maps to another.
1124 static const Symbol *GetAssociatedVariable(const AssocEntityDetails &details) {
1125   if (const auto &expr{details.expr()}) {
1126     if (IsVariable(*expr) && !HasVectorSubscript(*expr)) {
1127       if (const Symbol * varSymbol{GetFirstSymbol(*expr)}) {
1128         return &GetAssociationRoot(*varSymbol);
1129       }
1130     }
1131   }
1132   return nullptr;
1133 }
1134 
1135 const Symbol &GetAssociationRoot(const Symbol &original) {
1136   const Symbol &symbol{ResolveAssociations(original)};
1137   if (const auto *details{symbol.detailsIf<AssocEntityDetails>()}) {
1138     if (const Symbol * root{GetAssociatedVariable(*details)}) {
1139       return *root;
1140     }
1141   }
1142   return symbol;
1143 }
1144 
1145 const Symbol *GetMainEntry(const Symbol *symbol) {
1146   if (symbol) {
1147     if (const auto *subpDetails{symbol->detailsIf<SubprogramDetails>()}) {
1148       if (const Scope * scope{subpDetails->entryScope()}) {
1149         if (const Symbol * main{scope->symbol()}) {
1150           return main;
1151         }
1152       }
1153     }
1154   }
1155   return symbol;
1156 }
1157 
1158 bool IsVariableName(const Symbol &original) {
1159   const Symbol &symbol{ResolveAssociations(original)};
1160   if (symbol.has<ObjectEntityDetails>()) {
1161     return !IsNamedConstant(symbol);
1162   } else if (const auto *assoc{symbol.detailsIf<AssocEntityDetails>()}) {
1163     const auto &expr{assoc->expr()};
1164     return expr && IsVariable(*expr) && !HasVectorSubscript(*expr);
1165   } else {
1166     return false;
1167   }
1168 }
1169 
1170 bool IsPureProcedure(const Symbol &original) {
1171   // An ENTRY is pure if its containing subprogram is
1172   const Symbol &symbol{DEREF(GetMainEntry(&original.GetUltimate()))};
1173   if (const auto *procDetails{symbol.detailsIf<ProcEntityDetails>()}) {
1174     if (const Symbol * procInterface{procDetails->interface().symbol()}) {
1175       // procedure component with a pure interface
1176       return IsPureProcedure(*procInterface);
1177     }
1178   } else if (const auto *details{symbol.detailsIf<ProcBindingDetails>()}) {
1179     return IsPureProcedure(details->symbol());
1180   } else if (!IsProcedure(symbol)) {
1181     return false;
1182   }
1183   if (IsStmtFunction(symbol)) {
1184     // Section 15.7(1) states that a statement function is PURE if it does not
1185     // reference an IMPURE procedure or a VOLATILE variable
1186     if (const auto &expr{symbol.get<SubprogramDetails>().stmtFunction()}) {
1187       for (const SymbolRef &ref : evaluate::CollectSymbols(*expr)) {
1188         if (IsFunction(*ref) && !IsPureProcedure(*ref)) {
1189           return false;
1190         }
1191         if (ref->GetUltimate().attrs().test(Attr::VOLATILE)) {
1192           return false;
1193         }
1194       }
1195     }
1196     return true; // statement function was not found to be impure
1197   }
1198   return symbol.attrs().test(Attr::PURE) ||
1199       (symbol.attrs().test(Attr::ELEMENTAL) &&
1200           !symbol.attrs().test(Attr::IMPURE));
1201 }
1202 
1203 bool IsPureProcedure(const Scope &scope) {
1204   const Symbol *symbol{scope.GetSymbol()};
1205   return symbol && IsPureProcedure(*symbol);
1206 }
1207 
1208 bool IsFunction(const Symbol &symbol) {
1209   const Symbol &ultimate{symbol.GetUltimate()};
1210   return ultimate.test(Symbol::Flag::Function) ||
1211       std::visit(common::visitors{
1212                      [](const SubprogramDetails &x) { return x.isFunction(); },
1213                      [](const ProcEntityDetails &x) {
1214                        const auto &ifc{x.interface()};
1215                        return ifc.type() ||
1216                            (ifc.symbol() && IsFunction(*ifc.symbol()));
1217                      },
1218                      [](const ProcBindingDetails &x) {
1219                        return IsFunction(x.symbol());
1220                      },
1221                      [](const auto &) { return false; },
1222                  },
1223           ultimate.details());
1224 }
1225 
1226 bool IsFunction(const Scope &scope) {
1227   const Symbol *symbol{scope.GetSymbol()};
1228   return symbol && IsFunction(*symbol);
1229 }
1230 
1231 bool IsProcedure(const Symbol &symbol) {
1232   return std::visit(common::visitors{
1233                         [](const SubprogramDetails &) { return true; },
1234                         [](const SubprogramNameDetails &) { return true; },
1235                         [](const ProcEntityDetails &) { return true; },
1236                         [](const GenericDetails &) { return true; },
1237                         [](const ProcBindingDetails &) { return true; },
1238                         [](const auto &) { return false; },
1239                     },
1240       symbol.GetUltimate().details());
1241 }
1242 
1243 bool IsProcedure(const Scope &scope) {
1244   const Symbol *symbol{scope.GetSymbol()};
1245   return symbol && IsProcedure(*symbol);
1246 }
1247 
1248 const Symbol *FindCommonBlockContaining(const Symbol &original) {
1249   const Symbol &root{GetAssociationRoot(original)};
1250   const auto *details{root.detailsIf<ObjectEntityDetails>()};
1251   return details ? details->commonBlock() : nullptr;
1252 }
1253 
1254 bool IsProcedurePointer(const Symbol &original) {
1255   const Symbol &symbol{GetAssociationRoot(original)};
1256   return symbol.has<ProcEntityDetails>() && IsPointer(symbol);
1257 }
1258 
1259 // 3.11 automatic data object
1260 bool IsAutomatic(const Symbol &original) {
1261   const Symbol &symbol{original.GetUltimate()};
1262   if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
1263     if (!object->isDummy() && !IsAllocatable(symbol) && !IsPointer(symbol)) {
1264       if (const DeclTypeSpec * type{symbol.GetType()}) {
1265         // If a type parameter value is not a constant expression, the
1266         // object is automatic.
1267         if (type->category() == DeclTypeSpec::Character) {
1268           if (const auto &length{
1269                   type->characterTypeSpec().length().GetExplicit()}) {
1270             if (!evaluate::IsConstantExpr(*length)) {
1271               return true;
1272             }
1273           }
1274         } else if (const DerivedTypeSpec * derived{type->AsDerived()}) {
1275           for (const auto &pair : derived->parameters()) {
1276             if (const auto &value{pair.second.GetExplicit()}) {
1277               if (!evaluate::IsConstantExpr(*value)) {
1278                 return true;
1279               }
1280             }
1281           }
1282         }
1283       }
1284       // If an array bound is not a constant expression, the object is
1285       // automatic.
1286       for (const ShapeSpec &dim : object->shape()) {
1287         if (const auto &lb{dim.lbound().GetExplicit()}) {
1288           if (!evaluate::IsConstantExpr(*lb)) {
1289             return true;
1290           }
1291         }
1292         if (const auto &ub{dim.ubound().GetExplicit()}) {
1293           if (!evaluate::IsConstantExpr(*ub)) {
1294             return true;
1295           }
1296         }
1297       }
1298     }
1299   }
1300   return false;
1301 }
1302 
1303 bool IsSaved(const Symbol &original) {
1304   const Symbol &symbol{GetAssociationRoot(original)};
1305   const Scope &scope{symbol.owner()};
1306   auto scopeKind{scope.kind()};
1307   if (symbol.has<AssocEntityDetails>()) {
1308     return false; // ASSOCIATE(non-variable)
1309   } else if (scopeKind == Scope::Kind::DerivedType) {
1310     return false; // this is a component
1311   } else if (symbol.attrs().test(Attr::SAVE)) {
1312     return true; // explicit SAVE attribute
1313   } else if (IsDummy(symbol) || IsFunctionResult(symbol) ||
1314       IsAutomatic(symbol) || IsNamedConstant(symbol)) {
1315     return false;
1316   } else if (scopeKind == Scope::Kind::Module ||
1317       (scopeKind == Scope::Kind::MainProgram &&
1318           (symbol.attrs().test(Attr::TARGET) || evaluate::IsCoarray(symbol)))) {
1319     // 8.5.16p4
1320     // In main programs, implied SAVE matters only for pointer
1321     // initialization targets and coarrays.
1322     // BLOCK DATA entities must all be in COMMON,
1323     // which was checked above.
1324     return true;
1325   } else if (scope.kind() == Scope::Kind::Subprogram &&
1326       scope.context().languageFeatures().IsEnabled(
1327           common::LanguageFeature::DefaultSave) &&
1328       !(scope.symbol() && scope.symbol()->attrs().test(Attr::RECURSIVE))) {
1329     // -fno-automatic/-save/-Msave option applies to objects in
1330     // executable subprograms unless they are explicitly RECURSIVE.
1331     return true;
1332   } else if (symbol.test(Symbol::Flag::InDataStmt)) {
1333     return true;
1334   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()};
1335              object && object->init()) {
1336     return true;
1337   } else if (IsProcedurePointer(symbol) &&
1338       symbol.get<ProcEntityDetails>().init()) {
1339     return true;
1340   } else if (scope.hasSAVE()) {
1341     return true; // bare SAVE statement
1342   } else if (const Symbol * block{FindCommonBlockContaining(symbol)};
1343              block && block->attrs().test(Attr::SAVE)) {
1344     return true; // in COMMON with SAVE
1345   } else {
1346     return false;
1347   }
1348 }
1349 
1350 bool IsDummy(const Symbol &symbol) {
1351   return std::visit(
1352       common::visitors{[](const EntityDetails &x) { return x.isDummy(); },
1353           [](const ObjectEntityDetails &x) { return x.isDummy(); },
1354           [](const ProcEntityDetails &x) { return x.isDummy(); },
1355           [](const SubprogramDetails &x) { return x.isDummy(); },
1356           [](const auto &) { return false; }},
1357       ResolveAssociations(symbol).details());
1358 }
1359 
1360 bool IsAssumedShape(const Symbol &symbol) {
1361   const Symbol &ultimate{ResolveAssociations(symbol)};
1362   const auto *object{ultimate.detailsIf<ObjectEntityDetails>()};
1363   return object && object->CanBeAssumedShape() &&
1364       !evaluate::IsAllocatableOrPointer(ultimate);
1365 }
1366 
1367 bool IsDeferredShape(const Symbol &symbol) {
1368   const Symbol &ultimate{ResolveAssociations(symbol)};
1369   const auto *object{ultimate.detailsIf<ObjectEntityDetails>()};
1370   return object && object->CanBeDeferredShape() &&
1371       evaluate::IsAllocatableOrPointer(ultimate);
1372 }
1373 
1374 bool IsFunctionResult(const Symbol &original) {
1375   const Symbol &symbol{GetAssociationRoot(original)};
1376   return (symbol.has<ObjectEntityDetails>() &&
1377              symbol.get<ObjectEntityDetails>().isFuncResult()) ||
1378       (symbol.has<ProcEntityDetails>() &&
1379           symbol.get<ProcEntityDetails>().isFuncResult());
1380 }
1381 
1382 bool IsKindTypeParameter(const Symbol &symbol) {
1383   const auto *param{symbol.GetUltimate().detailsIf<TypeParamDetails>()};
1384   return param && param->attr() == common::TypeParamAttr::Kind;
1385 }
1386 
1387 bool IsLenTypeParameter(const Symbol &symbol) {
1388   const auto *param{symbol.GetUltimate().detailsIf<TypeParamDetails>()};
1389   return param && param->attr() == common::TypeParamAttr::Len;
1390 }
1391 
1392 bool IsExtensibleType(const DerivedTypeSpec *derived) {
1393   return derived && !IsIsoCType(derived) &&
1394       !derived->typeSymbol().attrs().test(Attr::BIND_C) &&
1395       !derived->typeSymbol().get<DerivedTypeDetails>().sequence();
1396 }
1397 
1398 bool IsBuiltinDerivedType(const DerivedTypeSpec *derived, const char *name) {
1399   if (!derived) {
1400     return false;
1401   } else {
1402     const auto &symbol{derived->typeSymbol()};
1403     return &symbol.owner() == symbol.owner().context().GetBuiltinsScope() &&
1404         symbol.name() == "__builtin_"s + name;
1405   }
1406 }
1407 
1408 bool IsIsoCType(const DerivedTypeSpec *derived) {
1409   return IsBuiltinDerivedType(derived, "c_ptr") ||
1410       IsBuiltinDerivedType(derived, "c_funptr");
1411 }
1412 
1413 bool IsTeamType(const DerivedTypeSpec *derived) {
1414   return IsBuiltinDerivedType(derived, "team_type");
1415 }
1416 
1417 bool IsBadCoarrayType(const DerivedTypeSpec *derived) {
1418   return IsTeamType(derived) || IsIsoCType(derived);
1419 }
1420 
1421 bool IsEventTypeOrLockType(const DerivedTypeSpec *derivedTypeSpec) {
1422   return IsBuiltinDerivedType(derivedTypeSpec, "event_type") ||
1423       IsBuiltinDerivedType(derivedTypeSpec, "lock_type");
1424 }
1425 
1426 int CountLenParameters(const DerivedTypeSpec &type) {
1427   return std::count_if(type.parameters().begin(), type.parameters().end(),
1428       [](const auto &pair) { return pair.second.isLen(); });
1429 }
1430 
1431 int CountNonConstantLenParameters(const DerivedTypeSpec &type) {
1432   return std::count_if(
1433       type.parameters().begin(), type.parameters().end(), [](const auto &pair) {
1434         if (!pair.second.isLen()) {
1435           return false;
1436         } else if (const auto &expr{pair.second.GetExplicit()}) {
1437           return !IsConstantExpr(*expr);
1438         } else {
1439           return true;
1440         }
1441       });
1442 }
1443 
1444 // Are the type parameters of type1 compile-time compatible with the
1445 // corresponding kind type parameters of type2?  Return true if all constant
1446 // valued parameters are equal.
1447 // Used to check assignment statements and argument passing.  See 15.5.2.4(4)
1448 bool AreTypeParamCompatible(const semantics::DerivedTypeSpec &type1,
1449     const semantics::DerivedTypeSpec &type2) {
1450   for (const auto &[name, param1] : type1.parameters()) {
1451     if (semantics::MaybeIntExpr paramExpr1{param1.GetExplicit()}) {
1452       if (IsConstantExpr(*paramExpr1)) {
1453         const semantics::ParamValue *param2{type2.FindParameter(name)};
1454         if (param2) {
1455           if (semantics::MaybeIntExpr paramExpr2{param2->GetExplicit()}) {
1456             if (IsConstantExpr(*paramExpr2)) {
1457               if (ToInt64(*paramExpr1) != ToInt64(*paramExpr2)) {
1458                 return false;
1459               }
1460             }
1461           }
1462         }
1463       }
1464     }
1465   }
1466   return true;
1467 }
1468 
1469 const Symbol &GetUsedModule(const UseDetails &details) {
1470   return DEREF(details.symbol().owner().symbol());
1471 }
1472 
1473 static const Symbol *FindFunctionResult(
1474     const Symbol &original, UnorderedSymbolSet &seen) {
1475   const Symbol &root{GetAssociationRoot(original)};
1476   ;
1477   if (!seen.insert(root).second) {
1478     return nullptr; // don't loop
1479   }
1480   return std::visit(
1481       common::visitors{[](const SubprogramDetails &subp) {
1482                          return subp.isFunction() ? &subp.result() : nullptr;
1483                        },
1484           [&](const ProcEntityDetails &proc) {
1485             const Symbol *iface{proc.interface().symbol()};
1486             return iface ? FindFunctionResult(*iface, seen) : nullptr;
1487           },
1488           [&](const ProcBindingDetails &binding) {
1489             return FindFunctionResult(binding.symbol(), seen);
1490           },
1491           [](const auto &) -> const Symbol * { return nullptr; }},
1492       root.details());
1493 }
1494 
1495 const Symbol *FindFunctionResult(const Symbol &symbol) {
1496   UnorderedSymbolSet seen;
1497   return FindFunctionResult(symbol, seen);
1498 }
1499 
1500 // These are here in Evaluate/tools.cpp so that Evaluate can use
1501 // them; they cannot be defined in symbol.h due to the dependence
1502 // on Scope.
1503 
1504 bool SymbolSourcePositionCompare::operator()(
1505     const SymbolRef &x, const SymbolRef &y) const {
1506   return x->GetSemanticsContext().allCookedSources().Precedes(
1507       x->name(), y->name());
1508 }
1509 bool SymbolSourcePositionCompare::operator()(
1510     const MutableSymbolRef &x, const MutableSymbolRef &y) const {
1511   return x->GetSemanticsContext().allCookedSources().Precedes(
1512       x->name(), y->name());
1513 }
1514 
1515 SemanticsContext &Symbol::GetSemanticsContext() const {
1516   return DEREF(owner_).context();
1517 }
1518 
1519 } // namespace Fortran::semantics
1520