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 with an implicit interface
975     msg = "Procedure %s with explicit interface may not be associated with"
976           " procedure designator '%s' with implicit interface"_err_en_US;
977   } else if (!lhsProcedure->HasExplicitInterface() &&
978       rhsProcedure->HasExplicitInterface()) {
979     if (!rhsProcedure->CanBeCalledViaImplicitInterface()) {
980       msg = "Procedure %s with implicit interface may not be associated "
981             "with procedure designator '%s' with explicit interface that "
982             "cannot be called via an implicit interface"_err_en_US;
983     }
984   } else {
985     msg = "Procedure %s associated with incompatible procedure"
986           " designator '%s'"_err_en_US;
987   }
988   return msg;
989 }
990 
991 // GetLastPointerSymbol()
992 static const Symbol *GetLastPointerSymbol(const Symbol &symbol) {
993   return IsPointer(GetAssociationRoot(symbol)) ? &symbol : nullptr;
994 }
995 static const Symbol *GetLastPointerSymbol(const SymbolRef &symbol) {
996   return GetLastPointerSymbol(*symbol);
997 }
998 static const Symbol *GetLastPointerSymbol(const Component &x) {
999   const Symbol &c{x.GetLastSymbol()};
1000   return IsPointer(c) ? &c : GetLastPointerSymbol(x.base());
1001 }
1002 static const Symbol *GetLastPointerSymbol(const NamedEntity &x) {
1003   const auto *c{x.UnwrapComponent()};
1004   return c ? GetLastPointerSymbol(*c) : GetLastPointerSymbol(x.GetLastSymbol());
1005 }
1006 static const Symbol *GetLastPointerSymbol(const ArrayRef &x) {
1007   return GetLastPointerSymbol(x.base());
1008 }
1009 static const Symbol *GetLastPointerSymbol(const CoarrayRef &x) {
1010   return nullptr;
1011 }
1012 const Symbol *GetLastPointerSymbol(const DataRef &x) {
1013   return std::visit([](const auto &y) { return GetLastPointerSymbol(y); }, x.u);
1014 }
1015 
1016 template <TypeCategory TO, TypeCategory FROM>
1017 static std::optional<Expr<SomeType>> DataConstantConversionHelper(
1018     FoldingContext &context, const DynamicType &toType,
1019     const Expr<SomeType> &expr) {
1020   DynamicType sizedType{FROM, toType.kind()};
1021   if (auto sized{
1022           Fold(context, ConvertToType(sizedType, Expr<SomeType>{expr}))}) {
1023     if (const auto *someExpr{UnwrapExpr<Expr<SomeKind<FROM>>>(*sized)}) {
1024       return std::visit(
1025           [](const auto &w) -> std::optional<Expr<SomeType>> {
1026             using FromType = typename std::decay_t<decltype(w)>::Result;
1027             static constexpr int kind{FromType::kind};
1028             if constexpr (IsValidKindOfIntrinsicType(TO, kind)) {
1029               if (const auto *fromConst{UnwrapExpr<Constant<FromType>>(w)}) {
1030                 using FromWordType = typename FromType::Scalar;
1031                 using LogicalType = value::Logical<FromWordType::bits>;
1032                 using ElementType =
1033                     std::conditional_t<TO == TypeCategory::Logical, LogicalType,
1034                         typename LogicalType::Word>;
1035                 std::vector<ElementType> values;
1036                 auto at{fromConst->lbounds()};
1037                 auto shape{fromConst->shape()};
1038                 for (auto n{GetSize(shape)}; n-- > 0;
1039                      fromConst->IncrementSubscripts(at)) {
1040                   auto elt{fromConst->At(at)};
1041                   if constexpr (TO == TypeCategory::Logical) {
1042                     values.emplace_back(std::move(elt));
1043                   } else {
1044                     values.emplace_back(elt.word());
1045                   }
1046                 }
1047                 return {AsGenericExpr(AsExpr(Constant<Type<TO, kind>>{
1048                     std::move(values), std::move(shape)}))};
1049               }
1050             }
1051             return std::nullopt;
1052           },
1053           someExpr->u);
1054     }
1055   }
1056   return std::nullopt;
1057 }
1058 
1059 std::optional<Expr<SomeType>> DataConstantConversionExtension(
1060     FoldingContext &context, const DynamicType &toType,
1061     const Expr<SomeType> &expr0) {
1062   Expr<SomeType> expr{Fold(context, Expr<SomeType>{expr0})};
1063   if (!IsActuallyConstant(expr)) {
1064     return std::nullopt;
1065   }
1066   if (auto fromType{expr.GetType()}) {
1067     if (toType.category() == TypeCategory::Logical &&
1068         fromType->category() == TypeCategory::Integer) {
1069       return DataConstantConversionHelper<TypeCategory::Logical,
1070           TypeCategory::Integer>(context, toType, expr);
1071     }
1072     if (toType.category() == TypeCategory::Integer &&
1073         fromType->category() == TypeCategory::Logical) {
1074       return DataConstantConversionHelper<TypeCategory::Integer,
1075           TypeCategory::Logical>(context, toType, expr);
1076     }
1077   }
1078   return std::nullopt;
1079 }
1080 
1081 } // namespace Fortran::evaluate
1082 
1083 namespace Fortran::semantics {
1084 
1085 const Symbol &ResolveAssociations(const Symbol &original) {
1086   const Symbol &symbol{original.GetUltimate()};
1087   if (const auto *details{symbol.detailsIf<AssocEntityDetails>()}) {
1088     if (const Symbol * nested{UnwrapWholeSymbolDataRef(details->expr())}) {
1089       return ResolveAssociations(*nested);
1090     }
1091   }
1092   return symbol;
1093 }
1094 
1095 // When a construct association maps to a variable, and that variable
1096 // is not an array with a vector-valued subscript, return the base
1097 // Symbol of that variable, else nullptr.  Descends into other construct
1098 // associations when one associations maps to another.
1099 static const Symbol *GetAssociatedVariable(const AssocEntityDetails &details) {
1100   if (const auto &expr{details.expr()}) {
1101     if (IsVariable(*expr) && !HasVectorSubscript(*expr)) {
1102       if (const Symbol * varSymbol{GetFirstSymbol(*expr)}) {
1103         return &GetAssociationRoot(*varSymbol);
1104       }
1105     }
1106   }
1107   return nullptr;
1108 }
1109 
1110 const Symbol &GetAssociationRoot(const Symbol &original) {
1111   const Symbol &symbol{ResolveAssociations(original)};
1112   if (const auto *details{symbol.detailsIf<AssocEntityDetails>()}) {
1113     if (const Symbol * root{GetAssociatedVariable(*details)}) {
1114       return *root;
1115     }
1116   }
1117   return symbol;
1118 }
1119 
1120 const Symbol *GetMainEntry(const Symbol *symbol) {
1121   if (symbol) {
1122     if (const auto *subpDetails{symbol->detailsIf<SubprogramDetails>()}) {
1123       if (const Scope * scope{subpDetails->entryScope()}) {
1124         if (const Symbol * main{scope->symbol()}) {
1125           return main;
1126         }
1127       }
1128     }
1129   }
1130   return symbol;
1131 }
1132 
1133 bool IsVariableName(const Symbol &original) {
1134   const Symbol &symbol{ResolveAssociations(original)};
1135   if (symbol.has<ObjectEntityDetails>()) {
1136     return !IsNamedConstant(symbol);
1137   } else if (const auto *assoc{symbol.detailsIf<AssocEntityDetails>()}) {
1138     const auto &expr{assoc->expr()};
1139     return expr && IsVariable(*expr) && !HasVectorSubscript(*expr);
1140   } else {
1141     return false;
1142   }
1143 }
1144 
1145 bool IsPureProcedure(const Symbol &original) {
1146   // An ENTRY is pure if its containing subprogram is
1147   const Symbol &symbol{DEREF(GetMainEntry(&original.GetUltimate()))};
1148   if (const auto *procDetails{symbol.detailsIf<ProcEntityDetails>()}) {
1149     if (const Symbol * procInterface{procDetails->interface().symbol()}) {
1150       // procedure component with a pure interface
1151       return IsPureProcedure(*procInterface);
1152     }
1153   } else if (const auto *details{symbol.detailsIf<ProcBindingDetails>()}) {
1154     return IsPureProcedure(details->symbol());
1155   } else if (!IsProcedure(symbol)) {
1156     return false;
1157   }
1158   if (IsStmtFunction(symbol)) {
1159     // Section 15.7(1) states that a statement function is PURE if it does not
1160     // reference an IMPURE procedure or a VOLATILE variable
1161     if (const auto &expr{symbol.get<SubprogramDetails>().stmtFunction()}) {
1162       for (const SymbolRef &ref : evaluate::CollectSymbols(*expr)) {
1163         if (IsFunction(*ref) && !IsPureProcedure(*ref)) {
1164           return false;
1165         }
1166         if (ref->GetUltimate().attrs().test(Attr::VOLATILE)) {
1167           return false;
1168         }
1169       }
1170     }
1171     return true; // statement function was not found to be impure
1172   }
1173   return symbol.attrs().test(Attr::PURE) ||
1174       (symbol.attrs().test(Attr::ELEMENTAL) &&
1175           !symbol.attrs().test(Attr::IMPURE));
1176 }
1177 
1178 bool IsPureProcedure(const Scope &scope) {
1179   const Symbol *symbol{scope.GetSymbol()};
1180   return symbol && IsPureProcedure(*symbol);
1181 }
1182 
1183 bool IsFunction(const Symbol &symbol) {
1184   return std::visit(
1185       common::visitors{
1186           [](const SubprogramDetails &x) { return x.isFunction(); },
1187           [&](const SubprogramNameDetails &) {
1188             return symbol.test(Symbol::Flag::Function);
1189           },
1190           [](const ProcEntityDetails &x) {
1191             const auto &ifc{x.interface()};
1192             return ifc.type() || (ifc.symbol() && IsFunction(*ifc.symbol()));
1193           },
1194           [](const ProcBindingDetails &x) { return IsFunction(x.symbol()); },
1195           [](const auto &) { return false; },
1196       },
1197       symbol.GetUltimate().details());
1198 }
1199 
1200 bool IsFunction(const Scope &scope) {
1201   const Symbol *symbol{scope.GetSymbol()};
1202   return symbol && IsFunction(*symbol);
1203 }
1204 
1205 bool IsProcedure(const Symbol &symbol) {
1206   return std::visit(common::visitors{
1207                         [](const SubprogramDetails &) { return true; },
1208                         [](const SubprogramNameDetails &) { return true; },
1209                         [](const ProcEntityDetails &) { return true; },
1210                         [](const GenericDetails &) { return true; },
1211                         [](const ProcBindingDetails &) { return true; },
1212                         [](const auto &) { return false; },
1213                     },
1214       symbol.GetUltimate().details());
1215 }
1216 
1217 bool IsProcedure(const Scope &scope) {
1218   const Symbol *symbol{scope.GetSymbol()};
1219   return symbol && IsProcedure(*symbol);
1220 }
1221 
1222 const Symbol *FindCommonBlockContaining(const Symbol &original) {
1223   const Symbol &root{GetAssociationRoot(original)};
1224   const auto *details{root.detailsIf<ObjectEntityDetails>()};
1225   return details ? details->commonBlock() : nullptr;
1226 }
1227 
1228 bool IsProcedurePointer(const Symbol &original) {
1229   const Symbol &symbol{GetAssociationRoot(original)};
1230   return symbol.has<ProcEntityDetails>() && IsPointer(symbol);
1231 }
1232 
1233 // 3.11 automatic data object
1234 bool IsAutomatic(const Symbol &original) {
1235   const Symbol &symbol{original.GetUltimate()};
1236   if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
1237     if (!object->isDummy() && !IsAllocatable(symbol) && !IsPointer(symbol)) {
1238       if (const DeclTypeSpec * type{symbol.GetType()}) {
1239         // If a type parameter value is not a constant expression, the
1240         // object is automatic.
1241         if (type->category() == DeclTypeSpec::Character) {
1242           if (const auto &length{
1243                   type->characterTypeSpec().length().GetExplicit()}) {
1244             if (!evaluate::IsConstantExpr(*length)) {
1245               return true;
1246             }
1247           }
1248         } else if (const DerivedTypeSpec * derived{type->AsDerived()}) {
1249           for (const auto &pair : derived->parameters()) {
1250             if (const auto &value{pair.second.GetExplicit()}) {
1251               if (!evaluate::IsConstantExpr(*value)) {
1252                 return true;
1253               }
1254             }
1255           }
1256         }
1257       }
1258       // If an array bound is not a constant expression, the object is
1259       // automatic.
1260       for (const ShapeSpec &dim : object->shape()) {
1261         if (const auto &lb{dim.lbound().GetExplicit()}) {
1262           if (!evaluate::IsConstantExpr(*lb)) {
1263             return true;
1264           }
1265         }
1266         if (const auto &ub{dim.ubound().GetExplicit()}) {
1267           if (!evaluate::IsConstantExpr(*ub)) {
1268             return true;
1269           }
1270         }
1271       }
1272     }
1273   }
1274   return false;
1275 }
1276 
1277 bool IsSaved(const Symbol &original) {
1278   const Symbol &symbol{GetAssociationRoot(original)};
1279   const Scope &scope{symbol.owner()};
1280   auto scopeKind{scope.kind()};
1281   if (symbol.has<AssocEntityDetails>()) {
1282     return false; // ASSOCIATE(non-variable)
1283   } else if (scopeKind == Scope::Kind::DerivedType) {
1284     return false; // this is a component
1285   } else if (symbol.attrs().test(Attr::SAVE)) {
1286     return true; // explicit SAVE attribute
1287   } else if (IsDummy(symbol) || IsFunctionResult(symbol) ||
1288       IsAutomatic(symbol) || IsNamedConstant(symbol)) {
1289     return false;
1290   } else if (scopeKind == Scope::Kind::Module ||
1291       (scopeKind == Scope::Kind::MainProgram &&
1292           (symbol.attrs().test(Attr::TARGET) || evaluate::IsCoarray(symbol)))) {
1293     // 8.5.16p4
1294     // In main programs, implied SAVE matters only for pointer
1295     // initialization targets and coarrays.
1296     // BLOCK DATA entities must all be in COMMON,
1297     // which was checked above.
1298     return true;
1299   } else if (scope.kind() == Scope::Kind::Subprogram &&
1300       scope.context().languageFeatures().IsEnabled(
1301           common::LanguageFeature::DefaultSave) &&
1302       !(scope.symbol() && scope.symbol()->attrs().test(Attr::RECURSIVE))) {
1303     // -fno-automatic/-save/-Msave option applies to objects in
1304     // executable subprograms unless they are explicitly RECURSIVE.
1305     return true;
1306   } else if (symbol.test(Symbol::Flag::InDataStmt)) {
1307     return true;
1308   } else if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()};
1309              object && object->init()) {
1310     return true;
1311   } else if (IsProcedurePointer(symbol) &&
1312       symbol.get<ProcEntityDetails>().init()) {
1313     return true;
1314   } else if (scope.hasSAVE()) {
1315     return true; // bare SAVE statement
1316   } else if (const Symbol * block{FindCommonBlockContaining(symbol)};
1317              block && block->attrs().test(Attr::SAVE)) {
1318     return true; // in COMMON with SAVE
1319   } else {
1320     return false;
1321   }
1322 }
1323 
1324 bool IsDummy(const Symbol &symbol) {
1325   return std::visit(
1326       common::visitors{[](const EntityDetails &x) { return x.isDummy(); },
1327           [](const ObjectEntityDetails &x) { return x.isDummy(); },
1328           [](const ProcEntityDetails &x) { return x.isDummy(); },
1329           [](const SubprogramDetails &x) { return x.isDummy(); },
1330           [](const auto &) { return false; }},
1331       ResolveAssociations(symbol).details());
1332 }
1333 
1334 bool IsAssumedShape(const Symbol &symbol) {
1335   const Symbol &ultimate{ResolveAssociations(symbol)};
1336   const auto *object{ultimate.detailsIf<ObjectEntityDetails>()};
1337   return object && object->CanBeAssumedShape() &&
1338       !evaluate::IsAllocatableOrPointer(ultimate);
1339 }
1340 
1341 bool IsDeferredShape(const Symbol &symbol) {
1342   const Symbol &ultimate{ResolveAssociations(symbol)};
1343   const auto *object{ultimate.detailsIf<ObjectEntityDetails>()};
1344   return object && object->CanBeDeferredShape() &&
1345       evaluate::IsAllocatableOrPointer(ultimate);
1346 }
1347 
1348 bool IsFunctionResult(const Symbol &original) {
1349   const Symbol &symbol{GetAssociationRoot(original)};
1350   return (symbol.has<ObjectEntityDetails>() &&
1351              symbol.get<ObjectEntityDetails>().isFuncResult()) ||
1352       (symbol.has<ProcEntityDetails>() &&
1353           symbol.get<ProcEntityDetails>().isFuncResult());
1354 }
1355 
1356 bool IsKindTypeParameter(const Symbol &symbol) {
1357   const auto *param{symbol.GetUltimate().detailsIf<TypeParamDetails>()};
1358   return param && param->attr() == common::TypeParamAttr::Kind;
1359 }
1360 
1361 bool IsLenTypeParameter(const Symbol &symbol) {
1362   const auto *param{symbol.GetUltimate().detailsIf<TypeParamDetails>()};
1363   return param && param->attr() == common::TypeParamAttr::Len;
1364 }
1365 
1366 bool IsExtensibleType(const DerivedTypeSpec *derived) {
1367   return derived && !IsIsoCType(derived) &&
1368       !derived->typeSymbol().attrs().test(Attr::BIND_C) &&
1369       !derived->typeSymbol().get<DerivedTypeDetails>().sequence();
1370 }
1371 
1372 bool IsBuiltinDerivedType(const DerivedTypeSpec *derived, const char *name) {
1373   if (!derived) {
1374     return false;
1375   } else {
1376     const auto &symbol{derived->typeSymbol()};
1377     return &symbol.owner() == symbol.owner().context().GetBuiltinsScope() &&
1378         symbol.name() == "__builtin_"s + name;
1379   }
1380 }
1381 
1382 bool IsIsoCType(const DerivedTypeSpec *derived) {
1383   return IsBuiltinDerivedType(derived, "c_ptr") ||
1384       IsBuiltinDerivedType(derived, "c_funptr");
1385 }
1386 
1387 bool IsTeamType(const DerivedTypeSpec *derived) {
1388   return IsBuiltinDerivedType(derived, "team_type");
1389 }
1390 
1391 bool IsBadCoarrayType(const DerivedTypeSpec *derived) {
1392   return IsTeamType(derived) || IsIsoCType(derived);
1393 }
1394 
1395 bool IsEventTypeOrLockType(const DerivedTypeSpec *derivedTypeSpec) {
1396   return IsBuiltinDerivedType(derivedTypeSpec, "event_type") ||
1397       IsBuiltinDerivedType(derivedTypeSpec, "lock_type");
1398 }
1399 
1400 int CountLenParameters(const DerivedTypeSpec &type) {
1401   return std::count_if(type.parameters().begin(), type.parameters().end(),
1402       [](const auto &pair) { return pair.second.isLen(); });
1403 }
1404 
1405 int CountNonConstantLenParameters(const DerivedTypeSpec &type) {
1406   return std::count_if(
1407       type.parameters().begin(), type.parameters().end(), [](const auto &pair) {
1408         if (!pair.second.isLen()) {
1409           return false;
1410         } else if (const auto &expr{pair.second.GetExplicit()}) {
1411           return !IsConstantExpr(*expr);
1412         } else {
1413           return true;
1414         }
1415       });
1416 }
1417 
1418 // Are the type parameters of type1 compile-time compatible with the
1419 // corresponding kind type parameters of type2?  Return true if all constant
1420 // valued parameters are equal.
1421 // Used to check assignment statements and argument passing.  See 15.5.2.4(4)
1422 bool AreTypeParamCompatible(const semantics::DerivedTypeSpec &type1,
1423     const semantics::DerivedTypeSpec &type2) {
1424   for (const auto &[name, param1] : type1.parameters()) {
1425     if (semantics::MaybeIntExpr paramExpr1{param1.GetExplicit()}) {
1426       if (IsConstantExpr(*paramExpr1)) {
1427         const semantics::ParamValue *param2{type2.FindParameter(name)};
1428         if (param2) {
1429           if (semantics::MaybeIntExpr paramExpr2{param2->GetExplicit()}) {
1430             if (IsConstantExpr(*paramExpr2)) {
1431               if (ToInt64(*paramExpr1) != ToInt64(*paramExpr2)) {
1432                 return false;
1433               }
1434             }
1435           }
1436         }
1437       }
1438     }
1439   }
1440   return true;
1441 }
1442 
1443 const Symbol &GetUsedModule(const UseDetails &details) {
1444   return DEREF(details.symbol().owner().symbol());
1445 }
1446 
1447 static const Symbol *FindFunctionResult(
1448     const Symbol &original, UnorderedSymbolSet &seen) {
1449   const Symbol &root{GetAssociationRoot(original)};
1450   ;
1451   if (!seen.insert(root).second) {
1452     return nullptr; // don't loop
1453   }
1454   return std::visit(
1455       common::visitors{[](const SubprogramDetails &subp) {
1456                          return subp.isFunction() ? &subp.result() : nullptr;
1457                        },
1458           [&](const ProcEntityDetails &proc) {
1459             const Symbol *iface{proc.interface().symbol()};
1460             return iface ? FindFunctionResult(*iface, seen) : nullptr;
1461           },
1462           [&](const ProcBindingDetails &binding) {
1463             return FindFunctionResult(binding.symbol(), seen);
1464           },
1465           [](const auto &) -> const Symbol * { return nullptr; }},
1466       root.details());
1467 }
1468 
1469 const Symbol *FindFunctionResult(const Symbol &symbol) {
1470   UnorderedSymbolSet seen;
1471   return FindFunctionResult(symbol, seen);
1472 }
1473 
1474 // These are here in Evaluate/tools.cpp so that Evaluate can use
1475 // them; they cannot be defined in symbol.h due to the dependence
1476 // on Scope.
1477 
1478 bool SymbolSourcePositionCompare::operator()(
1479     const SymbolRef &x, const SymbolRef &y) const {
1480   return x->GetSemanticsContext().allCookedSources().Precedes(
1481       x->name(), y->name());
1482 }
1483 bool SymbolSourcePositionCompare::operator()(
1484     const MutableSymbolRef &x, const MutableSymbolRef &y) const {
1485   return x->GetSemanticsContext().allCookedSources().Precedes(
1486       x->name(), y->name());
1487 }
1488 
1489 SemanticsContext &Symbol::GetSemanticsContext() const {
1490   return DEREF(owner_).context();
1491 }
1492 
1493 } // namespace Fortran::semantics
1494