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