FLANG
tools.h
1//===-- include/flang/Evaluate/tools.h --------------------------*- C++ -*-===//
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#ifndef FORTRAN_EVALUATE_TOOLS_H_
10#define FORTRAN_EVALUATE_TOOLS_H_
11
12#include "traverse.h"
13#include "flang/Common/enum-set.h"
14#include "flang/Common/idioms.h"
15#include "flang/Common/template.h"
16#include "flang/Common/unwrap.h"
17#include "flang/Evaluate/constant.h"
18#include "flang/Evaluate/expression.h"
19#include "flang/Evaluate/shape.h"
20#include "flang/Evaluate/type.h"
21#include "flang/Parser/message.h"
22#include "flang/Semantics/attr.h"
23#include "flang/Semantics/scope.h"
24#include "flang/Semantics/symbol.h"
25#include <algorithm>
26#include <array>
27#include <optional>
28#include <set>
29#include <type_traits>
30#include <utility>
31
32namespace Fortran::evaluate {
33
34// Some expression predicates and extractors.
35
36// Predicate: true when an expression is a variable reference, not an
37// operation. Be advised: a call to a function that returns an object
38// pointer is a "variable" in Fortran (it can be the left-hand side of
39// an assignment).
40struct IsVariableHelper
41 : public AnyTraverse<IsVariableHelper, std::optional<bool>> {
42 using Result = std::optional<bool>; // effectively tri-state
43 using Base = AnyTraverse<IsVariableHelper, Result>;
44 IsVariableHelper() : Base{*this} {}
45 using Base::operator();
46 Result operator()(const StaticDataObject &) const { return false; }
47 Result operator()(const Symbol &) const;
48 Result operator()(const Component &) const;
49 Result operator()(const ArrayRef &) const;
50 Result operator()(const Substring &) const;
51 Result operator()(const CoarrayRef &) const { return true; }
52 Result operator()(const ComplexPart &) const { return true; }
53 Result operator()(const ProcedureDesignator &) const;
54 template <typename T> Result operator()(const ConditionalExpr<T> &) const {
55 return false;
56 }
57 template <typename T> Result operator()(const Expr<T> &x) const {
58 if constexpr (std::is_same_v<T, SomeType>) {
59 if (std::holds_alternative<ProcedureDesignator>(x.u) ||
60 std::holds_alternative<ProcedureRef>(x.u)) {
61 return false; // procedure pointer
62 } else {
63 return (*this)(x.u);
64 }
65 } else {
66 // Expression with a specific type
67 if (std::holds_alternative<Designator<T>>(x.u) ||
68 std::holds_alternative<FunctionRef<T>>(x.u)) {
69 if (auto known{(*this)(x.u)}) {
70 return known;
71 }
72 }
73 return false;
74 }
75 }
76};
77
78template <typename A> bool IsVariable(const A &x) {
79 if (auto known{IsVariableHelper{}(x)}) {
80 return *known;
81 } else {
82 return false;
83 }
84}
85
86// Finds the corank of an entity, possibly packaged in various ways.
87// Unlike rank, only data references have corank > 0.
88int GetCorank(const ActualArgument &);
89static inline int GetCorank(const Symbol &symbol) { return symbol.Corank(); }
90template <typename A> int GetCorank(const A &) { return 0; }
91template <typename T> int GetCorank(const Designator<T> &designator) {
92 return designator.Corank();
93}
94template <typename T> int GetCorank(const Expr<T> &expr) {
95 return common::visit([](const auto &x) { return GetCorank(x); }, expr.u);
96}
97template <typename A> int GetCorank(const std::optional<A> &x) {
98 return x ? GetCorank(*x) : 0;
99}
100template <typename A> int GetCorank(const A *x) {
101 return x ? GetCorank(*x) : 0;
102}
103
104// Predicate: true when an expression is a coarray (corank > 0)
105template <typename A> bool IsCoarray(const A &x) { return GetCorank(x) > 0; }
106
107// Generalizing packagers: these take operations and expressions of more
108// specific types and wrap them in Expr<> containers of more abstract types.
109
110template <typename A> common::IfNoLvalue<Expr<ResultType<A>>, A> AsExpr(A &&x) {
111 return Expr<ResultType<A>>{std::move(x)};
112}
113
114template <typename T, typename U = typename Relational<T>::Result>
115Expr<U> AsExpr(Relational<T> &&x) {
116 // The variant in Expr<Type<TypeCategory::Logical>> only contains
117 // Relational<SomeType>, not other Relational<T>s. Wrap the Relational<T>
118 // in Relational<SomeType> before creating Expr<>.
119 return Expr<U>(Relational<SomeType>{std::move(x)});
120}
121
122template <typename T> Expr<T> AsExpr(Expr<T> &&x) {
123 static_assert(IsSpecificIntrinsicType<T>);
124 return std::move(x);
125}
126
127template <TypeCategory CATEGORY>
128Expr<Type<CATEGORY>> AsCategoryExpr(Expr<Type<CATEGORY>> &&x) {
129 return std::move(x);
130}
131
132template <typename A>
133common::IfNoLvalue<Expr<SomeType>, A> AsGenericExpr(A &&x) {
134 if constexpr (common::HasMember<A, TypelessExpression>) {
135 return Expr<SomeType>{std::move(x)};
136 } else {
137 return Expr<SomeType>{AsCategoryExpr(std::move(x))};
138 }
139}
140
141inline Expr<SomeType> AsGenericExpr(Expr<SomeType> &&x) { return std::move(x); }
142
143// These overloads wrap DataRefs and simple whole variables up into
144// generic expressions if they have a known type.
145std::optional<Expr<SomeType>> AsGenericExpr(DataRef &&);
146std::optional<Expr<SomeType>> AsGenericExpr(const Symbol &);
147
148// Propagate std::optional from input to output.
149template <typename A>
150std::optional<Expr<SomeType>> AsGenericExpr(std::optional<A> &&x) {
151 if (x) {
152 return AsGenericExpr(std::move(*x));
153 } else {
154 return std::nullopt;
155 }
156}
157
158template <typename A>
159common::IfNoLvalue<Expr<Type<ResultType<A>::category>>, A> AsCategoryExpr(
160 A &&x) {
161 return AsExpr(std::move(x));
162}
163
164Expr<SomeType> Parenthesize(Expr<SomeType> &&);
165
166template <typename A> constexpr bool IsNumericCategoryExpr() {
167 if constexpr (common::HasMember<A, TypelessExpression>) {
168 return false;
169 } else {
170 return common::HasMember<ResultType<A>, NumericTypes>;
171 }
172}
173
174// Specializing extractor. If an Expr wraps some type of object, perhaps
175// in several layers, return a pointer to it; otherwise null. Also works
176// with expressions contained in ActualArgument.
177template <typename A, typename B>
178auto UnwrapExpr(B &x) -> common::Constify<A, B> * {
179 using Ty = std::decay_t<B>;
180 if constexpr (std::is_same_v<A, Ty>) {
181 return &x;
182 } else if constexpr (std::is_same_v<Ty, ActualArgument>) {
183 if (auto *expr{x.UnwrapExpr()}) {
184 return UnwrapExpr<A>(*expr);
185 }
186 } else if constexpr (std::is_same_v<Ty, Expr<SomeType>>) {
187 return common::visit([](auto &x) { return UnwrapExpr<A>(x); }, x.u);
188 } else if constexpr (!common::HasMember<A, TypelessExpression>) {
189 if constexpr (std::is_same_v<Ty, Expr<ResultType<A>>>) {
190 return common::visit([](auto &x) { return UnwrapExpr<A>(x); }, x.u);
191 }
192 }
193 return nullptr;
194}
195
196template <typename A, typename B>
197const A *UnwrapExpr(const std::optional<B> &x) {
198 if (x) {
199 return UnwrapExpr<A>(*x);
200 } else {
201 return nullptr;
202 }
203}
204
205template <typename A, typename B> A *UnwrapExpr(std::optional<B> &x) {
206 if (x) {
207 return UnwrapExpr<A>(*x);
208 } else {
209 return nullptr;
210 }
211}
212
213template <typename A, typename B> const A *UnwrapExpr(const B *x) {
214 if (x) {
215 return UnwrapExpr<A>(*x);
216 } else {
217 return nullptr;
218 }
219}
220
221template <typename A, typename B> A *UnwrapExpr(B *x) {
222 if (x) {
223 return UnwrapExpr<A>(*x);
224 } else {
225 return nullptr;
226 }
227}
228
231template <typename A, typename B> auto UnwrapExpr(int kind, B &x) {
232 auto *result{UnwrapExpr<A>(x)};
233 if (result && result->kind() != kind) {
234 result = nullptr;
235 }
236 return result;
237}
238
239// A variant of UnwrapExpr above that also skips through (parentheses)
240// and conversions of kinds within a category. Useful for extracting LEN
241// type parameter inquiries, at least.
242template <typename A, typename B>
243auto UnwrapConvertedExpr(B &x) -> common::Constify<A, B> * {
244 using Ty = std::decay_t<B>;
245 if constexpr (std::is_same_v<A, Ty>) {
246 return &x;
247 } else if constexpr (std::is_same_v<Ty, ActualArgument>) {
248 if (auto *expr{x.UnwrapExpr()}) {
249 return UnwrapConvertedExpr<A>(*expr);
250 }
251 } else if constexpr (std::is_same_v<Ty, Expr<SomeType>>) {
252 return common::visit(
253 [](auto &x) { return UnwrapConvertedExpr<A>(x); }, x.u);
254 } else {
255 using DesiredResult = ResultType<A>;
256 if constexpr (std::is_same_v<Ty, Expr<DesiredResult>>) {
257 return common::visit(
258 [](auto &x) { return UnwrapConvertedExpr<A>(x); }, x.u);
259 } else {
260 using ThisResult = ResultType<B>;
261 if constexpr (std::is_same_v<Ty, Expr<ThisResult>>) {
262 return common::visit(
263 [](auto &x) { return UnwrapConvertedExpr<A>(x); }, x.u);
264 } else if constexpr (std::is_same_v<Ty, Parentheses<ThisResult>> ||
265 std::is_same_v<Ty, Convert<ThisResult, DesiredResult::category>>) {
266 return common::visit(
267 [](auto &x) { return UnwrapConvertedExpr<A>(x); }, x.left().u);
268 }
269 }
270 }
271 return nullptr;
272}
273
274// UnwrapProcedureRef() returns a pointer to a ProcedureRef when the whole
275// expression is a reference to a procedure.
276template <typename A> inline const ProcedureRef *UnwrapProcedureRef(const A &) {
277 return nullptr;
278}
279
280inline const ProcedureRef *UnwrapProcedureRef(const ProcedureRef &proc) {
281 // Reference to subroutine or to a function that returns
282 // an object pointer or procedure pointer
283 return &proc;
284}
285
286template <typename T>
287inline const ProcedureRef *UnwrapProcedureRef(const FunctionRef<T> &func) {
288 return &func; // reference to a function returning a non-pointer
289}
290
291template <typename T>
292inline const ProcedureRef *UnwrapProcedureRef(const Expr<T> &expr) {
293 return common::visit(
294 [](const auto &x) { return UnwrapProcedureRef(x); }, expr.u);
295}
296
297// When an expression is a "bare" LEN= derived type parameter inquiry,
298// possibly wrapped in integer kind conversions &/or parentheses, return
299// a pointer to the Symbol with TypeParamDetails.
300template <typename A> const Symbol *ExtractBareLenParameter(const A &expr) {
301 if (const auto *typeParam{
302 UnwrapConvertedExpr<evaluate::TypeParamInquiry>(expr)}) {
303 if (!typeParam->base()) {
304 const Symbol &symbol{typeParam->parameter()};
305 if (const auto *tpd{symbol.detailsIf<semantics::TypeParamDetails>()}) {
306 if (tpd->attr() == common::TypeParamAttr::Len) {
307 return &symbol;
308 }
309 }
310 }
311 }
312 return nullptr;
313}
314
315// If an expression simply wraps a DataRef, extract and return it.
316// The Boolean arguments control the handling of Substring and ComplexPart
317// references: when true (not default), it extracts the base DataRef
318// of a substring or complex part.
319template <typename A>
320common::IfNoLvalue<std::optional<DataRef>, A> ExtractDataRef(
321 const A &x, bool intoSubstring, bool intoComplexPart) {
322 if constexpr (common::HasMember<decltype(x), decltype(DataRef::u)>) {
323 return DataRef{x};
324 } else {
325 return std::nullopt; // default base case
326 }
327}
328
329std::optional<DataRef> ExtractSubstringBase(const Substring &);
330
331inline std::optional<DataRef> ExtractDataRef(const Substring &x,
332 bool intoSubstring = false, bool intoComplexPart = false) {
333 if (intoSubstring) {
334 return ExtractSubstringBase(x);
335 } else {
336 return std::nullopt;
337 }
338}
339inline std::optional<DataRef> ExtractDataRef(const ComplexPart &x,
340 bool intoSubstring = false, bool intoComplexPart = false) {
341 if (intoComplexPart) {
342 return x.complex();
343 } else {
344 return std::nullopt;
345 }
346}
347template <typename T>
348std::optional<DataRef> ExtractDataRef(const Designator<T> &d,
349 bool intoSubstring = false, bool intoComplexPart = false) {
350 return common::visit(
351 [=](const auto &x) -> std::optional<DataRef> {
352 return ExtractDataRef(x, intoSubstring, intoComplexPart);
353 },
354 d.u);
355}
356template <typename T>
357std::optional<DataRef> ExtractDataRef(const Expr<T> &expr,
358 bool intoSubstring = false, bool intoComplexPart = false) {
359 return common::visit(
360 [=](const auto &x) {
361 return ExtractDataRef(x, intoSubstring, intoComplexPart);
362 },
363 expr.u);
364}
365template <typename A>
366std::optional<DataRef> ExtractDataRef(const std::optional<A> &x,
367 bool intoSubstring = false, bool intoComplexPart = false) {
368 if (x) {
369 return ExtractDataRef(*x, intoSubstring, intoComplexPart);
370 } else {
371 return std::nullopt;
372 }
373}
374template <typename A>
375std::optional<DataRef> ExtractDataRef(
376 A *p, bool intoSubstring = false, bool intoComplexPart = false) {
377 if (p) {
378 return ExtractDataRef(std::as_const(*p), intoSubstring, intoComplexPart);
379 } else {
380 return std::nullopt;
381 }
382}
383std::optional<DataRef> ExtractDataRef(const ActualArgument &,
384 bool intoSubstring = false, bool intoComplexPart = false);
385
386// Predicate: is an expression is an array element reference?
387template <typename T>
388const Symbol *IsArrayElement(const Expr<T> &expr, bool intoSubstring = true,
389 bool skipComponents = false) {
390 if (auto dataRef{ExtractDataRef(expr, intoSubstring)}) {
391 for (const DataRef *ref{&*dataRef}; ref;) {
392 if (const Component * component{std::get_if<Component>(&ref->u)}) {
393 ref = skipComponents ? &component->base() : nullptr;
394 } else if (const auto *coarrayRef{std::get_if<CoarrayRef>(&ref->u)}) {
395 ref = &coarrayRef->base();
396 } else if (const auto *arrayRef{std::get_if<ArrayRef>(&ref->u)}) {
397 return &arrayRef->GetLastSymbol();
398 } else {
399 break;
400 }
401 }
402 }
403 return nullptr;
404}
405
406template <typename T>
407bool isStructureComponent(const Fortran::evaluate::Expr<T> &expr) {
408 if (auto dataRef{ExtractDataRef(expr, /*intoSubstring=*/false)}) {
409 const Fortran::evaluate::DataRef *ref{&*dataRef};
410 return std::holds_alternative<Fortran::evaluate::Component>(ref->u);
411 }
412
413 return false;
414}
415
416template <typename A>
417std::optional<NamedEntity> ExtractNamedEntity(const A &x) {
418 if (auto dataRef{ExtractDataRef(x)}) {
419 return common::visit(
420 common::visitors{
421 [](SymbolRef &&symbol) -> std::optional<NamedEntity> {
422 return NamedEntity{symbol};
423 },
424 [](Component &&component) -> std::optional<NamedEntity> {
425 return NamedEntity{std::move(component)};
426 },
427 [](auto &&) { return std::optional<NamedEntity>{}; },
428 },
429 std::move(dataRef->u));
430 } else {
431 return std::nullopt;
432 }
433}
434
436 template <typename A> std::optional<CoarrayRef> operator()(const A &) const {
437 return std::nullopt;
438 }
439 std::optional<CoarrayRef> operator()(const CoarrayRef &x) const { return x; }
440 template <typename A>
441 std::optional<CoarrayRef> operator()(const Expr<A> &expr) const {
442 return common::visit(*this, expr.u);
443 }
444 std::optional<CoarrayRef> operator()(const DataRef &dataRef) const {
445 return common::visit(*this, dataRef.u);
446 }
447 std::optional<CoarrayRef> operator()(const NamedEntity &named) const {
448 if (const Component * component{named.UnwrapComponent()}) {
449 return (*this)(*component);
450 } else {
451 return std::nullopt;
452 }
453 }
454 std::optional<CoarrayRef> operator()(const ProcedureDesignator &des) const {
455 if (const auto *component{
456 std::get_if<common::CopyableIndirection<Component>>(&des.u)}) {
457 return (*this)(component->value());
458 } else {
459 return std::nullopt;
460 }
461 }
462 std::optional<CoarrayRef> operator()(const Component &component) const {
463 return (*this)(component.base());
464 }
465 std::optional<CoarrayRef> operator()(const ArrayRef &arrayRef) const {
466 return (*this)(arrayRef.base());
467 }
468};
469
470static inline std::optional<CoarrayRef> ExtractCoarrayRef(const DataRef &x) {
472}
473
474template <typename A> std::optional<CoarrayRef> ExtractCoarrayRef(const A &x) {
475 if (auto dataRef{ExtractDataRef(x, true)}) {
476 return ExtractCoarrayRef(*dataRef);
477 } else {
479 }
480}
481
482template <typename TARGET> struct ExtractFromExprDesignatorHelper {
483 template <typename T> static std::optional<TARGET> visit(T &&) {
484 return std::nullopt;
485 }
486
487 static std::optional<TARGET> visit(const TARGET &t) { return t; }
488
489 template <typename T>
490 static std::optional<TARGET> visit(const Designator<T> &e) {
491 return common::visit([](auto &&s) { return visit(s); }, e.u);
492 }
493
494 template <typename T> static std::optional<TARGET> visit(const Expr<T> &e) {
495 return common::visit([](auto &&s) { return visit(s); }, e.u);
496 }
497};
498
499template <typename A> std::optional<Substring> ExtractSubstring(const A &x) {
500 return ExtractFromExprDesignatorHelper<Substring>::visit(x);
501}
502
503template <typename A>
504std::optional<ComplexPart> ExtractComplexPart(const A &x) {
505 return ExtractFromExprDesignatorHelper<ComplexPart>::visit(x);
506}
507
508// If an expression is simply a whole symbol data designator,
509// extract and return that symbol, else null.
510const Symbol *UnwrapWholeSymbolDataRef(const DataRef &);
511const Symbol *UnwrapWholeSymbolDataRef(const std::optional<DataRef> &);
512template <typename A> const Symbol *UnwrapWholeSymbolDataRef(const A &x) {
513 return UnwrapWholeSymbolDataRef(ExtractDataRef(x));
514}
515
516// If an expression is a whole symbol or a whole component desginator,
517// extract and return that symbol, else null.
518const Symbol *UnwrapWholeSymbolOrComponentDataRef(const DataRef &);
519const Symbol *UnwrapWholeSymbolOrComponentDataRef(
520 const std::optional<DataRef> &);
521template <typename A>
522const Symbol *UnwrapWholeSymbolOrComponentDataRef(const A &x) {
523 return UnwrapWholeSymbolOrComponentDataRef(ExtractDataRef(x));
524}
525
526// If an expression is a whole symbol or a whole component designator,
527// potentially followed by an image selector, extract and return that symbol,
528// else null.
529const Symbol *UnwrapWholeSymbolOrComponentOrCoarrayRef(const DataRef &);
530const Symbol *UnwrapWholeSymbolOrComponentOrCoarrayRef(
531 const std::optional<DataRef> &);
532template <typename A>
533const Symbol *UnwrapWholeSymbolOrComponentOrCoarrayRef(const A &x) {
534 return UnwrapWholeSymbolOrComponentOrCoarrayRef(ExtractDataRef(x));
535}
536
537// GetFirstSymbol(A%B%C[I]%D) -> A
538template <typename A> const Symbol *GetFirstSymbol(const A &x) {
539 if (auto dataRef{ExtractDataRef(x, true)}) {
540 return &dataRef->GetFirstSymbol();
541 } else {
542 return nullptr;
543 }
544}
545
546// GetLastPointerSymbol(A%PTR1%B%PTR2%C) -> PTR2
547const Symbol *GetLastPointerSymbol(const evaluate::DataRef &);
548
549// Creation of conversion expressions can be done to either a known
550// specific intrinsic type with ConvertToType<T>(x) or by converting
551// one arbitrary expression to the type of another with ConvertTo(to, from).
552
553template <typename TO, TypeCategory FROMCAT>
554Expr<TO> ConvertToType(int toKind, Expr<Type<FROMCAT>> &&x) {
555 static_assert(IsSpecificIntrinsicType<TO>);
556 if constexpr (FROMCAT == TO::category) {
557 if (x.kind() == toKind) {
558 return std::move(x);
559 } else {
560 return Expr<TO>{Convert<TO, FROMCAT>{toKind, std::move(x)}};
561 }
562 } else if constexpr (TO::category == TypeCategory::Complex) {
563 using Part = typename TO::Part;
565 ConvertToType<Part>(toKind, std::move(x)), MakeZeroExpr<Part>(toKind)}};
566 } else if constexpr (FROMCAT == TypeCategory::Complex) {
567 // Extract and convert the real component of a complex value
568 using Part = typename Type<FROMCAT>::Part;
569 return ConvertToType<TO, TypeCategory::Real>(
570 toKind, Expr<Part>{ComplexComponent{false, std::move(x)}});
571 } else {
572 return Expr<TO>{Convert<TO, FROMCAT>{toKind, std::move(x)}};
573 }
574}
575
576template <typename TO>
577Expr<TO> ConvertToType(int toKind, BOZLiteralConstant &&x) {
578 static_assert(IsSpecificIntrinsicType<TO>);
579 if constexpr (TO::category == TypeCategory::Integer ||
580 TO::category == TypeCategory::Unsigned) {
581 return MakeConstantExpr<TO>(
582 toKind, Scalar<TO>::ConvertUnsigned(toKind, std::move(x)).value);
583 } else {
584 static_assert(TO::category == TypeCategory::Real);
585 using Word = value::IntegerValue;
586 return MakeConstantExpr<TO>(toKind,
587 Scalar<TO>{toKind, Word::ConvertUnsigned(toKind, std::move(x)).value});
588 }
589}
590
591template <typename T> bool IsBOZLiteral(const Expr<T> &expr) {
592 return std::holds_alternative<BOZLiteralConstant>(expr.u);
593}
594
595// Conversions to dynamic types
596std::optional<Expr<SomeType>> ConvertToType(
597 const DynamicType &, Expr<SomeType> &&);
598std::optional<Expr<SomeType>> ConvertToType(
599 const DynamicType &, std::optional<Expr<SomeType>> &&);
600std::optional<Expr<SomeType>> ConvertToType(const Symbol &, Expr<SomeType> &&);
601std::optional<Expr<SomeType>> ConvertToType(
602 const Symbol &, std::optional<Expr<SomeType>> &&);
603
604// Conversions to the type of another expression
605template <TypeCategory TC, typename FROM>
606common::IfNoLvalue<Expr<Type<TC>>, FROM> ConvertTo(
607 const Expr<Type<TC>> &to, FROM &&x) {
608 return ConvertToType<Type<TC>>(to.kind(), std::move(x));
609}
610
611template <typename FROM>
612common::IfNoLvalue<Expr<SomeType>, FROM> ConvertTo(
613 const Expr<SomeType> &to, FROM &&from) {
614 return common::visit(
615 [&](const auto &toCatExpr) {
616 return AsGenericExpr(ConvertTo(toCatExpr, std::move(from)));
617 },
618 to.u);
619}
620
621// Convert an expression of some known category to a dynamically chosen
622// kind of some category (usually but not necessarily distinct).
623template <TypeCategory TOCAT, typename VALUE>
624common::IfNoLvalue<Expr<Type<TOCAT>>, VALUE> ConvertToKind(
625 int kind, VALUE &&x) {
626 CHECK(common::IsValidKindOfIntrinsicType(TOCAT, kind));
627 return AsCategoryExpr(ConvertToType<Type<TOCAT>>(kind, std::move(x)));
628}
629
630// Given a type category CAT, SameKindExprs<CAT, N> contains an array of
631// expressions in that category. Callers ensure that their runtime kinds match.
632template <typename A, int N = 2> using SameExprs = std::array<Expr<A>, N>;
633template <int N = 2> struct SameKindExprsHelper {
634 template <typename A> using SameExprs = std::array<Expr<A>, N>;
635};
636template <TypeCategory CAT, int N = 2>
637using SameKindExprs =
638 common::MapTemplate<SameKindExprsHelper<N>::template SameExprs,
639 CategoryTypes<CAT>>;
640
641// Given references to two expressions of arbitrary kind in the same type
642// category, convert one to the kind of the other when it has the smaller kind,
643// then return them in a type-safe package.
644template <TypeCategory CAT>
645SameKindExprs<CAT, 2> AsSameKindExprs(
646 Expr<Type<CAT>> &&x, Expr<Type<CAT>> &&y) {
647 int xKind{x.kind()};
648 int yKind{y.kind()};
649 if (xKind == yKind) {
650 return {SameExprs<Type<CAT>>{std::move(x), std::move(y)}};
651 } else if (xKind < yKind) {
652 return {SameExprs<Type<CAT>>{ConvertTo(y, std::move(x)), std::move(y)}};
653 } else {
654 // Must be computed before x is moved into the first array element.
655 auto converted{ConvertTo(x, std::move(y))};
656 return {SameExprs<Type<CAT>>{std::move(x), std::move(converted)}};
657 }
658}
659
660// Ensure that both operands of an intrinsic REAL operation (or CMPLX()
661// constructor) are INTEGER or REAL, then convert them as necessary to the
662// same kind of REAL.
663using ConvertRealOperandsResult =
664 std::optional<SameKindExprs<TypeCategory::Real, 2>>;
665ConvertRealOperandsResult ConvertRealOperands(parser::ContextualMessages &,
666 Expr<SomeType> &&, Expr<SomeType> &&, int defaultRealKind);
667
668// Per F'2018 R718, if both components are INTEGER, they are both converted
669// to default REAL and the result is default COMPLEX. Otherwise, the
670// kind of the result is the kind of most precise REAL component, and the other
671// component is converted if necessary to its type.
672std::optional<Expr<Type<TypeCategory::Complex>>> ConstructComplex(
673 parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
674 int defaultRealKind);
675std::optional<Expr<Type<TypeCategory::Complex>>> ConstructComplex(
676 parser::ContextualMessages &, std::optional<Expr<SomeType>> &&,
677 std::optional<Expr<SomeType>> &&, int defaultRealKind);
678
679template <typename A> Expr<TypeOf<A>> ScalarConstantToExpr(const A &x) {
680 using Ty = TypeOf<A>;
681 const int kind{x.kind()};
682 static_assert(
683 std::is_same_v<Scalar<Ty>, std::decay_t<A>>, "TypeOf<> is broken");
684 return MakeConstantExpr<Ty>(kind, x);
685}
686
687// Combine two expressions of the same specific numeric type with an operation
688// to produce a new expression.
689template <template <typename> class OPR, typename SPECIFIC>
691 static_assert(IsSpecificIntrinsicType<SPECIFIC>);
692 CHECK(x.kind() == y.kind());
693 return AsExpr(OPR<SPECIFIC>{x.kind(), std::move(x), std::move(y)});
694}
695
696// Given two expressions of arbitrary kind in the same intrinsic type
697// category, convert one of them if necessary to the larger kind of the
698// other, then combine the resulting homogenized operands with a given
699// operation, returning a new expression in the same type category.
700template <template <typename> class OPR, TypeCategory CAT>
701Expr<Type<CAT>> PromoteAndCombine(Expr<Type<CAT>> &&x, Expr<Type<CAT>> &&y) {
702 return common::visit(
703 [](auto &&xy) {
704 using Ty = ResultType<decltype(xy[0])>;
705 return AsCategoryExpr(
706 Combine<OPR, Ty>(std::move(xy[0]), std::move(xy[1])));
707 },
708 AsSameKindExprs(std::move(x), std::move(y)));
709}
710
711// Given two expressions of arbitrary type, try to combine them with a
712// binary numeric operation (e.g., Add), possibly with data type conversion of
713// one of the operands to the type of the other. Handles special cases with
714// typeless literal operands and with REAL/COMPLEX exponentiation to INTEGER
715// powers.
716template <template <typename> class OPR>
717std::optional<Expr<SomeType>> NumericOperation(parser::ContextualMessages &,
718 Expr<SomeType> &&, Expr<SomeType> &&, int defaultRealKind);
719
720extern template std::optional<Expr<SomeType>> NumericOperation<Power>(
721 parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
722 int defaultRealKind);
723extern template std::optional<Expr<SomeType>> NumericOperation<Multiply>(
724 parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
725 int defaultRealKind);
726extern template std::optional<Expr<SomeType>> NumericOperation<Divide>(
727 parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
728 int defaultRealKind);
729extern template std::optional<Expr<SomeType>> NumericOperation<Add>(
730 parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
731 int defaultRealKind);
732extern template std::optional<Expr<SomeType>> NumericOperation<Subtract>(
733 parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
734 int defaultRealKind);
735
736std::optional<Expr<SomeType>> Negation(
737 parser::ContextualMessages &, Expr<SomeType> &&);
738
739// Given two expressions of arbitrary type, try to combine them with a
740// relational operator (e.g., .LT.), possibly with data type conversion.
741std::optional<Expr<LogicalResult>> Relate(parser::ContextualMessages &,
742 RelationalOperator, Expr<SomeType> &&, Expr<SomeType> &&);
743
744// Create a relational operation between two identically-typed operands
745// and wrap it up in an Expr<LogicalResult>.
746template <typename T>
747Expr<LogicalResult> PackageRelation(
748 RelationalOperator opr, Expr<T> &&x, Expr<T> &&y) {
749 static_assert(IsSpecificIntrinsicType<T>);
750 return Expr<LogicalResult>{
751 Relational<SomeType>{Relational<T>{opr, std::move(x), std::move(y)}}};
752}
753
754inline Expr<Type<TypeCategory::Logical>> LogicalNegation(
756 const int kind{x.kind()};
757 return AsExpr(Not{kind, std::move(x)});
758}
759
760Expr<Type<TypeCategory::Logical>> BinaryLogicalOperation(LogicalOperator,
762
763// Convenience functions and operator overloadings for expression construction.
764// These interfaces are defined only for those situations that can never
765// emit any message. Use the more general templates (above) in other
766// situations.
767
768template <TypeCategory C> Expr<Type<C>> operator-(Expr<Type<C>> &&x) {
769 return AsExpr(Negate<Type<C>>{std::move(x)});
770}
771
772template <TypeCategory CAT>
773Expr<Type<CAT>> operator+(Expr<Type<CAT>> &&x, Expr<Type<CAT>> &&y) {
774 return PromoteAndCombine<Add, CAT>(std::move(x), std::move(y));
775}
776
777template <TypeCategory CAT>
778Expr<Type<CAT>> operator-(Expr<Type<CAT>> &&x, Expr<Type<CAT>> &&y) {
779 return PromoteAndCombine<Subtract, CAT>(std::move(x), std::move(y));
780}
781
782template <TypeCategory CAT>
783Expr<Type<CAT>> operator*(Expr<Type<CAT>> &&x, Expr<Type<CAT>> &&y) {
784 return PromoteAndCombine<Multiply, CAT>(std::move(x), std::move(y));
785}
786
787template <TypeCategory CAT>
788Expr<Type<CAT>> operator/(Expr<Type<CAT>> &&x, Expr<Type<CAT>> &&y) {
789 return PromoteAndCombine<Divide, CAT>(std::move(x), std::move(y));
790}
791
792// TypedWrapper() wraps a object in an explicitly typed representation
793// (e.g., Designator<> or FunctionRef<>) that has been instantiated on
794// a dynamically chosen Fortran type.
795template <TypeCategory CATEGORY, template <typename> typename WRAPPER,
796 typename WRAPPED>
797common::IfNoLvalue<std::optional<Expr<SomeType>>, WRAPPED> WrapperHelper(
798 int kind, WRAPPED &&x) {
799 if (!common::IsValidKindOfIntrinsicType(CATEGORY, kind)) {
800 return std::nullopt;
801 }
802 return AsGenericExpr(WRAPPER<Type<CATEGORY>>{kind, std::move(x)});
803}
804
805template <template <typename> typename WRAPPER, typename WRAPPED>
806common::IfNoLvalue<std::optional<Expr<SomeType>>, WRAPPED> TypedWrapper(
807 const DynamicType &dyType, WRAPPED &&x) {
808 switch (dyType.category()) {
809 SWITCH_COVERS_ALL_CASES
810 case TypeCategory::Integer:
811 return WrapperHelper<TypeCategory::Integer, WRAPPER, WRAPPED>(
812 dyType.kind(), std::move(x));
813 case TypeCategory::Unsigned:
814 return WrapperHelper<TypeCategory::Unsigned, WRAPPER, WRAPPED>(
815 dyType.kind(), std::move(x));
816 case TypeCategory::Real:
817 return WrapperHelper<TypeCategory::Real, WRAPPER, WRAPPED>(
818 dyType.kind(), std::move(x));
819 case TypeCategory::Complex:
820 return WrapperHelper<TypeCategory::Complex, WRAPPER, WRAPPED>(
821 dyType.kind(), std::move(x));
822 case TypeCategory::Character:
823 return WrapperHelper<TypeCategory::Character, WRAPPER, WRAPPED>(
824 dyType.kind(), std::move(x));
825 case TypeCategory::Logical:
826 return WrapperHelper<TypeCategory::Logical, WRAPPER, WRAPPED>(
827 dyType.kind(), std::move(x));
828 case TypeCategory::Derived:
829 return AsGenericExpr(Expr<Type<TypeCategory::Derived>>{
830 WRAPPER<Type<TypeCategory::Derived>>{/*kind=*/0, std::move(x)}});
831 }
832}
833
834// GetLastSymbol() returns the rightmost symbol in an object or procedure
835// designator (which has perhaps been wrapped in an Expr<>), or a null pointer
836// when none is found. It will return an ASSOCIATE construct entity's symbol
837// rather than descending into its expression.
838struct GetLastSymbolHelper
839 : public AnyTraverse<GetLastSymbolHelper, std::optional<const Symbol *>> {
840 using Result = std::optional<const Symbol *>;
841 using Base = AnyTraverse<GetLastSymbolHelper, Result>;
842 GetLastSymbolHelper() : Base{*this} {}
843 using Base::operator();
844 Result operator()(const Symbol &x) const { return &x; }
845 Result operator()(const Component &x) const { return &x.GetLastSymbol(); }
846 Result operator()(const NamedEntity &x) const { return &x.GetLastSymbol(); }
847 Result operator()(const ProcedureDesignator &x) const {
848 return x.GetSymbol();
849 }
850 template <typename T> Result operator()(const Expr<T> &x) const {
851 if constexpr (!std::is_same_v<T, SomeType>) {
852 if (const auto *designator{std::get_if<Designator<T>>(&x.u)}) {
853 if (auto known{(*this)(*designator)}) {
854 return known;
855 }
856 }
857 return nullptr;
858 } else {
859 return (*this)(x.u);
860 }
861 }
862};
863
864template <typename A> const Symbol *GetLastSymbol(const A &x) {
865 if (auto known{GetLastSymbolHelper{}(x)}) {
866 return *known;
867 } else {
868 return nullptr;
869 }
870}
871
872// For everyday variables: if GetLastSymbol() succeeds on the argument, return
873// its set of attributes, otherwise the empty set. Also works on variables that
874// are pointer results of functions.
875template <typename A> semantics::Attrs GetAttrs(const A &x) {
876 if (const Symbol * symbol{GetLastSymbol(x)}) {
877 return symbol->attrs();
878 } else {
879 return {};
880 }
881}
882
883template <> semantics::Attrs GetAttrs<Expr<SomeType>>(const Expr<SomeType> &x);
884
885template <typename A> semantics::Attrs GetAttrs(const std::optional<A> &x) {
886 if (x) {
887 return GetAttrs(*x);
888 } else {
889 return {};
890 }
891}
892
893// GetBaseObject()
894template <typename A> std::optional<BaseObject> GetBaseObject(const A &) {
895 return std::nullopt;
896}
897template <typename T>
898std::optional<BaseObject> GetBaseObject(const Designator<T> &x) {
899 return x.GetBaseObject();
900}
901template <typename T>
902std::optional<BaseObject> GetBaseObject(const Expr<T> &x) {
903 return common::visit([](const auto &y) { return GetBaseObject(y); }, x.u);
904}
905template <typename A>
906std::optional<BaseObject> GetBaseObject(const std::optional<A> &x) {
907 if (x) {
908 return GetBaseObject(*x);
909 } else {
910 return std::nullopt;
911 }
912}
913
914// Like IsAllocatableOrPointer, but accepts pointer function results as being
915// pointers too.
916bool IsAllocatableOrPointerObject(const Expr<SomeType> &);
917
918bool IsAllocatableDesignator(const Expr<SomeType> &);
919
920// Procedure and pointer detection predicates
921bool IsProcedureDesignator(const Expr<SomeType> &);
922bool IsFunctionDesignator(const Expr<SomeType> &);
923bool IsPointer(const Expr<SomeType> &);
924bool IsProcedurePointer(const Expr<SomeType> &);
925bool IsProcedure(const Expr<SomeType> &);
926bool IsProcedurePointerTarget(const Expr<SomeType> &);
927bool IsBareNullPointer(const Expr<SomeType> *); // NULL() w/o MOLD= or type
928bool IsNullObjectPointer(const Expr<SomeType> *); // NULL() or NULL(objptr)
929bool IsNullProcedurePointer(const Expr<SomeType> *); // NULL() or NULL(procptr)
930bool IsNullPointer(const Expr<SomeType> *); // NULL() or NULL(pointer)
931bool IsNullAllocatable(const Expr<SomeType> *); // NULL(allocatable)
932bool IsNullPointerOrAllocatable(const Expr<SomeType> *); // NULL of any form
933bool IsObjectPointer(const Expr<SomeType> &);
934
935// Can Expr be passed as absent to an optional dummy argument.
936// See 15.5.2.12 point 1 for more details.
937bool MayBePassedAsAbsentOptional(const Expr<SomeType> &);
938
939// Extracts the chain of symbols from a designator, which has perhaps been
940// wrapped in an Expr<>, removing all of the (co)subscripts. The
941// base object will be the first symbol in the result vector.
942struct GetSymbolVectorHelper
943 : public Traverse<GetSymbolVectorHelper, SymbolVector> {
944 using Result = SymbolVector;
945 using Base = Traverse<GetSymbolVectorHelper, Result>;
946 using Base::operator();
947 GetSymbolVectorHelper() : Base{*this} {}
948 Result Default() { return {}; }
949 Result Combine(Result &&a, Result &&b) {
950 a.insert(a.end(), b.begin(), b.end());
951 return std::move(a);
952 }
953 Result operator()(const Symbol &) const;
954 Result operator()(const Component &) const;
955 Result operator()(const ArrayRef &) const;
956 Result operator()(const CoarrayRef &) const;
957};
958template <typename A> SymbolVector GetSymbolVector(const A &x) {
959 return GetSymbolVectorHelper{}(x);
960}
961
962// The selector of an associate name when it is a variable that is not a
963// pointer returned by a function, else nullptr.
964const Expr<SomeType> *GetVariableSelector(const Symbol &);
965
966// GetLastTarget() returns the rightmost symbol in an object designator's
967// SymbolVector that has the POINTER or TARGET attribute, or a null pointer
968// when none is found.
969const Symbol *GetLastTarget(const SymbolVector &);
970
971// Collects all of the Symbols in an expression
972template <typename A> semantics::UnorderedSymbolSet CollectSymbols(const A &);
973extern template semantics::UnorderedSymbolSet CollectSymbols(
974 const Expr<SomeType> &);
975extern template semantics::UnorderedSymbolSet CollectSymbols(
976 const Expr<SubscriptInteger> &);
977extern template semantics::UnorderedSymbolSet CollectSymbols(
978 const ProcedureDesignator &);
979extern template semantics::UnorderedSymbolSet CollectSymbols(
980 const Assignment &);
981
982// Collects the originating arrays named by the ubound()/lbound() provenance of
983// the RankOneBoundElements in an expression. Traverse() visits only an
984// element's base, so CollectSymbols() never sees these; the module file writer
985// needs them so that a bound serialized as ubound(a,dim) also declares 'a'.
986// This is deliberately not part of Traverse(): an element's value depends only
987// on its base, and visiting the originating array there would make an element
988// whose array is an INTENT(OUT) or INTENT(INOUT) dummy fail
989// IsScopeInvariantExpr() and block folding that is valid today.
990template <typename A>
991semantics::UnorderedSymbolSet CollectRankOneBoundProvenanceSymbols(const A &);
992extern template semantics::UnorderedSymbolSet
993CollectRankOneBoundProvenanceSymbols(const Expr<SomeType> &);
994extern template semantics::UnorderedSymbolSet
995CollectRankOneBoundProvenanceSymbols(const Expr<SubscriptInteger> &);
996
997// Collects Symbols of interest for the CUDA data transfer in an expression
998template <typename A>
999semantics::UnorderedSymbolSet CollectCudaSymbols(const A &);
1000extern template semantics::UnorderedSymbolSet CollectCudaSymbols(
1001 const Expr<SomeType> &);
1002extern template semantics::UnorderedSymbolSet CollectCudaSymbols(
1003 const Expr<SubscriptInteger> &);
1004
1005// Predicate: does a variable contain a vector-valued subscript (not a triplet)?
1006bool HasVectorSubscript(const Expr<SomeType> &);
1007bool HasVectorSubscript(const ActualArgument &);
1008
1009// Predicate: is an expression a section of an array?
1010bool IsArraySection(const Expr<SomeType> &expr);
1011
1012// Predicate: does an expression contain constant?
1013bool HasConstant(const Expr<SomeType> &);
1014
1015// Predicate: Does an expression contain a component
1016bool HasStructureComponent(const Expr<SomeType> &expr);
1017
1018// Predicate: does an expression contain a procedure reference?
1019bool HasProcedureRef(const Expr<SomeType> &expr);
1020
1021// Predicate: does an expression contain a VOLATILE or ASYNCHRONOUS symbol?
1022bool HasVolatileOrAsynchronousSymbol(const Expr<SomeType> &expr);
1023
1024// Can a scalar real or complex RHS expression in an assignment be rewritten
1025// as a split sum expression tree?
1026bool CanBuildSplitSumExpressionTree(
1027 FoldingContext &, const Expr<SomeType> &lhs, const Expr<SomeType> &rhs);
1028
1029// Try to rewrite eligible scalar real or complex sums within an expression as
1030// split sum expression trees.
1031std::optional<Expr<SomeType>> TryBuildSplitSumExpressionTrees(
1032 const Expr<SomeType> &expr);
1033
1034// Utilities for attaching the location of the declaration of a symbol
1035// of interest to a message. Handles the case of USE association gracefully.
1036parser::Message *AttachDeclaration(parser::Message &, const Symbol &);
1037parser::Message *AttachDeclaration(parser::Message *, const Symbol &);
1038template <typename MESSAGES, typename... A>
1039parser::Message *SayWithDeclaration(
1040 MESSAGES &messages, const Symbol &symbol, A &&...x) {
1041 return AttachDeclaration(messages.Say(std::forward<A>(x)...), symbol);
1042}
1043template <typename... A>
1044parser::Message *WarnWithDeclaration(FoldingContext context,
1045 const Symbol &symbol, common::LanguageFeature feature, A &&...x) {
1046 return AttachDeclaration(
1047 context.Warn(feature, std::forward<A>(x)...), symbol);
1048}
1049template <typename... A>
1050parser::Message *WarnWithDeclaration(FoldingContext &context,
1051 const Symbol &symbol, common::UsageWarning warning, A &&...x) {
1052 return AttachDeclaration(
1053 context.Warn(warning, std::forward<A>(x)...), symbol);
1054}
1055
1056// Check for references to impure procedures; returns the name
1057// of one to complain about, if any exist.
1058std::optional<std::string> FindImpureCall(
1059 FoldingContext &, const Expr<SomeType> &);
1060std::optional<std::string> FindImpureCall(
1061 FoldingContext &, const ProcedureRef &);
1062
1063// Predicate: does an expression contain anything that would prevent it from
1064// being duplicated so that two instances of it then appear in the same
1065// expression?
1066class UnsafeToCopyVisitor : public AnyTraverse<UnsafeToCopyVisitor> {
1067public:
1068 using Base = AnyTraverse<UnsafeToCopyVisitor>;
1069 using Base::operator();
1070 explicit UnsafeToCopyVisitor(bool admitPureCall)
1071 : Base{*this}, admitPureCall_{admitPureCall} {}
1072 template <typename T> bool operator()(const FunctionRef<T> &procRef) {
1073 return !admitPureCall_ || !procRef.proc().IsPure();
1074 }
1075 bool operator()(const CoarrayRef &) { return true; }
1076
1077private:
1078 bool admitPureCall_{false};
1079};
1080
1081template <typename A>
1082bool IsSafelyCopyable(const A &x, bool admitPureCall = false) {
1083 return !UnsafeToCopyVisitor{admitPureCall}(x);
1084}
1085
1086// Predicate: is a scalar expression suitable for naive scalar expansion
1087// in the flattening of an array expression?
1088// TODO: capture such scalar expansions in temporaries, flatten everything
1089template <typename T>
1090bool IsExpandableScalar(const Expr<T> &expr, FoldingContext &context,
1091 const Shape &shape, bool admitPureCall = false) {
1092 if (IsSafelyCopyable(expr, admitPureCall)) {
1093 return true;
1094 } else {
1095 auto extents{AsConstantExtents(context, shape)};
1096 return extents && !HasNegativeExtent(*extents) && GetSize(*extents) == 1;
1097 }
1098}
1099
1100// Common handling for procedure pointer compatibility of left- and right-hand
1101// sides. Returns nullopt if they're compatible. Otherwise, it returns a
1102// message that needs to be augmented by the names of the left and right sides.
1103std::optional<parser::MessageFixedText> CheckProcCompatibility(bool isCall,
1104 const std::optional<characteristics::Procedure> &lhsProcedure,
1105 const characteristics::Procedure *rhsProcedure,
1106 const SpecificIntrinsic *specificIntrinsic, std::string &whyNotCompatible,
1107 std::optional<std::string> &warning, bool ignoreImplicitVsExplicit);
1108
1109// Scalar constant expansion
1110class ScalarConstantExpander {
1111public:
1112 explicit ScalarConstantExpander(ConstantSubscripts &&extents)
1113 : extents_{std::move(extents)} {}
1114 ScalarConstantExpander(
1115 ConstantSubscripts &&extents, std::optional<ConstantSubscripts> &&lbounds)
1116 : extents_{std::move(extents)}, lbounds_{std::move(lbounds)} {}
1117 ScalarConstantExpander(
1118 ConstantSubscripts &&extents, ConstantSubscripts &&lbounds)
1119 : extents_{std::move(extents)}, lbounds_{std::move(lbounds)} {}
1120
1121 template <typename A> A Expand(A &&x) const {
1122 return std::move(x); // default case
1123 }
1124 template <typename T> Constant<T> Expand(Constant<T> &&x) {
1125 auto expanded{x.Reshape(std::move(extents_))};
1126 if (lbounds_) {
1127 expanded.set_lbounds(std::move(*lbounds_));
1128 }
1129 return expanded;
1130 }
1131 template <typename T> Expr<T> Expand(Parentheses<T> &&x) {
1132 return Expand(std::move(x.left())); // Constant<> can be parenthesized
1133 }
1134 template <typename T> Expr<T> Expand(Expr<T> &&x) {
1135 return common::visit(
1136 [&](auto &&x) { return Expr<T>{Expand(std::move(x))}; },
1137 std::move(x.u));
1138 }
1139
1140private:
1141 ConstantSubscripts extents_;
1142 std::optional<ConstantSubscripts> lbounds_;
1143};
1144
1145// Given a collection of element values, package them as a Constant.
1146// If the type is Character or a derived type, take the length or type
1147// (resp.) from a another Constant.
1148template <typename T>
1149Constant<T> PackageConstant(int kind, std::vector<Scalar<T>> &&elements,
1150 const Constant<T> &reference, const ConstantSubscripts &shape) {
1151 if constexpr (T::category == TypeCategory::Character) {
1152 return Constant<T>{
1153 kind, reference.LEN(), std::move(elements), ConstantSubscripts{shape}};
1154 } else if constexpr (T::category == TypeCategory::Derived) {
1155 return Constant<T>{reference.GetType().GetDerivedTypeSpec(),
1156 std::move(elements), ConstantSubscripts{shape}};
1157 } else {
1158 return Constant<T>{kind, std::move(elements), ConstantSubscripts{shape}};
1159 }
1160}
1161
1162// Nonstandard conversions of constants (integer->logical, logical->integer)
1163// that can appear in DATA statements as an extension.
1164std::optional<Expr<SomeType>> DataConstantConversionExtension(
1165 FoldingContext &, const DynamicType &, const Expr<SomeType> &);
1166
1167// Convert Hollerith or short character to a another type as if the
1168// Hollerith data had been BOZ.
1169std::optional<Expr<SomeType>> HollerithToBOZ(
1170 FoldingContext &, const Expr<SomeType> &, const DynamicType &);
1171
1172// Set explicit lower bounds on a constant array.
1173class ArrayConstantBoundChanger {
1174public:
1175 explicit ArrayConstantBoundChanger(ConstantSubscripts &&lbounds)
1176 : lbounds_{std::move(lbounds)} {}
1177
1178 template <typename A> A ChangeLbounds(A &&x) const {
1179 return std::move(x); // default case
1180 }
1181 template <typename T> Constant<T> ChangeLbounds(Constant<T> &&x) {
1182 x.set_lbounds(std::move(lbounds_));
1183 return std::move(x);
1184 }
1185 template <typename T> Expr<T> ChangeLbounds(Parentheses<T> &&x) {
1186 return ChangeLbounds(
1187 std::move(x.left())); // Constant<> can be parenthesized
1188 }
1189 template <typename T> Expr<T> ChangeLbounds(Expr<T> &&x) {
1190 return common::visit(
1191 [&](auto &&x) { return Expr<T>{ChangeLbounds(std::move(x))}; },
1192 std::move(x.u)); // recurse until we hit a constant
1193 }
1194
1195private:
1196 ConstantSubscripts &&lbounds_;
1197};
1198
1199// Predicate: should two expressions be considered identical for the purposes
1200// of determining whether two procedure interfaces are compatible, modulo
1201// naming of corresponding dummy arguments?
1202template <typename T>
1203std::optional<bool> AreEquivalentInInterface(const Expr<T> &, const Expr<T> &);
1204extern template std::optional<bool> AreEquivalentInInterface<SubscriptInteger>(
1206
1207bool CheckForCoindexedObject(parser::ContextualMessages &,
1208 const std::optional<ActualArgument> &, const std::string &procName,
1209 const std::string &argName);
1210
1211// Get the symbol vectors of the expression where symbols are grouped together
1212// if they are part of the same component expression.
1213//
1214// Example: a%b + c%d
1215// Will be grouped as: [(a, b), (c, d)]
1216std::vector<SymbolVector> GetSymbolVectors(const Expr<SomeType> &expr);
1217
1218bool IsCUDADeviceSymbol(const Symbol &sym);
1219bool IsCUDADeviceOnlySymbol(const Symbol &sym);
1220
1221// True if the data designated by the symbol has the CUDA data attribute. An
1222// associate name takes the attribute of the variable its selector designates.
1223bool IsCUDADataAttrSymbol(const Symbol &sym, common::CUDADataAttr attr);
1224
1225inline bool IsCUDAManagedOrUnifiedSymbol(const Symbol &sym) {
1226 return IsCUDADataAttrSymbol(sym, common::CUDADataAttr::Managed) ||
1227 IsCUDADataAttrSymbol(sym, common::CUDADataAttr::Unified);
1228}
1229
1230inline bool IsCUDAManagedSymbol(const Symbol &sym) {
1231 return IsCUDADataAttrSymbol(sym, common::CUDADataAttr::Managed);
1232}
1233
1234inline bool IsCUDAUnifiedSymbol(const Symbol &sym) {
1235 return IsCUDADataAttrSymbol(sym, common::CUDADataAttr::Unified);
1236}
1237
1238inline bool HasCUDADataAttr(const Symbol &sym) {
1239 const auto *details{
1240 sym.GetUltimate().detailsIf<semantics::ObjectEntityDetails>()};
1241 return details && details->cudaDataAttr().has_value();
1242}
1243
1244// Replace each associate name whose selector is a variable by the CUDA symbols
1245// of its selector, the same way GetSymbolVector expands it.
1246semantics::UnorderedSymbolSet ExpandCudaAssociations(
1247 semantics::UnorderedSymbolSet &&symbols);
1248
1249// The data attribute of a component describes the data that the component
1250// designates, so it hides the attribute of the object that the component is
1251// taken from: in a%b, where a is managed and b is device, a%b designates
1252// device data. Collect the symbols of the expression, leaving out the ones
1253// that a component with an attribute hides.
1254template <typename A>
1255semantics::UnorderedSymbolSet CollectEffectiveCudaSymbols(const A &expr) {
1256 // Associate names are expanded so that the set holds the symbols that
1257 // GetSymbolVector lists, which the hiding below relies on.
1258 semantics::UnorderedSymbolSet result{
1259 ExpandCudaAssociations(CollectCudaSymbols(expr))};
1260 SymbolVector symbols{GetSymbolVector(expr)};
1261 // GetSymbolVector lists the base of a component chain before its components.
1262 // Reverse it to visit the innermost component of a chain first.
1263 std::reverse(symbols.begin(), symbols.end());
1264 bool hidden{false};
1265 for (const Symbol &sym : symbols) {
1266 bool isComponent{sym.owner().IsDerivedType()};
1267 if (hidden) {
1268 result.erase(sym);
1269 } else if (isComponent && HasCUDADataAttr(sym)) {
1270 hidden = true;
1271 }
1272 if (!isComponent) {
1273 hidden = false; // The base ends the component chain.
1274 }
1275 }
1276 return result;
1277}
1278
1279// Get the number of symbols with the CUDA managed attribute in a set.
1280inline int CountCUDAManagedSymbols(
1281 const semantics::UnorderedSymbolSet &symbols) {
1282 int count{0};
1283 for (const Symbol &sym : symbols) {
1284 if (IsCUDAManagedSymbol(sym)) {
1285 ++count;
1286 }
1287 }
1288 return count;
1289}
1290
1291// Get the number of symbols with a CUDA device attribute other than unified in
1292// a set.
1293inline int CountCUDANonUnifiedSymbols(
1294 const semantics::UnorderedSymbolSet &symbols) {
1295 int count{0};
1296 for (const Symbol &sym : symbols) {
1297 if (IsCUDADeviceSymbol(sym) && !IsCUDAUnifiedSymbol(sym)) {
1298 ++count;
1299 }
1300 }
1301 return count;
1302}
1303
1304// Non-allocatable module-level managed/unified variables use pointer
1305// indirection through a companion global in __nv_managed_data__.
1306// Explicit data transfers (cudaMemcpy) must be avoided for these
1307// variables since they would target the shadow address rather than
1308// the actual unified memory address.
1309inline bool IsNonAllocatableModuleCUDAManagedSymbol(const Symbol &sym) {
1310 const Symbol &ultimate = sym.GetUltimate();
1311 if (!IsCUDAManagedOrUnifiedSymbol(ultimate))
1312 return false;
1313 if (ultimate.attrs().test(semantics::Attr::ALLOCATABLE))
1314 return false;
1315 return ultimate.owner().IsModule();
1316}
1317
1318template <typename A>
1319inline bool HasNonAllocatableModuleCUDAManagedSymbols(const A &expr) {
1320 for (const Symbol &sym : CollectCudaSymbols(expr))
1321 if (IsNonAllocatableModuleCUDAManagedSymbol(sym))
1322 return true;
1323 return false;
1324}
1325
1326// Get the number of distinct symbols with CUDA device
1327// attribute in the expression.
1328template <typename A> inline int GetNbOfCUDADeviceSymbols(const A &expr) {
1329 semantics::UnorderedSymbolSet symbols;
1330 for (const Symbol &sym : CollectCudaSymbols(expr)) {
1331 if (IsCUDADeviceSymbol(sym)) {
1332 symbols.insert(sym);
1333 }
1334 }
1335 return symbols.size();
1336}
1337
1338// Get the number of unique symbols with CUDA device attribute.
1339int GetNbOfUniqueCUDADeviceSymbols(const Expr<SomeType> &expr);
1340
1341// Get the number of unique symbols with CUDA device attribute that are managed
1342// or unified. Symbols are counted the same way as in
1343// GetNbOfUniqueCUDADeviceSymbols so the two counts can be compared.
1344int GetNbOfUniqueCUDAManagedOrUnifiedSymbols(const Expr<SomeType> &expr);
1345
1346// Get the number of distinct symbols with CUDA managed or unified
1347// attribute in the expression.
1348template <typename A>
1349inline int GetNbOfCUDAManagedOrUnifiedSymbols(const A &expr) {
1350 semantics::UnorderedSymbolSet symbols;
1351 for (const Symbol &sym : CollectCudaSymbols(expr)) {
1352 if (IsCUDAManagedOrUnifiedSymbol(sym)) {
1353 symbols.insert(sym);
1354 }
1355 }
1356 return symbols.size();
1357}
1358
1359// Check if any of the symbols part of the expression has a CUDA device
1360// attribute.
1361template <typename A> inline bool HasCUDADeviceAttrs(const A &expr) {
1362 return GetNbOfCUDADeviceSymbols(expr) > 0;
1363}
1364
1365// True for a whole reference to a managed array: a whole array variable, or a
1366// whole array component that itself has the managed attribute (a%b where b is
1367// managed). An array section, an array element, a component of a managed object
1368// and a computed value are all false.
1369template <typename A> inline bool IsWholeManagedArray(const A &expr) {
1370 const Symbol *sym{UnwrapWholeSymbolOrComponentDataRef(expr)};
1371 return expr.Rank() > 0 && sym && IsCUDAManagedSymbol(*sym);
1372}
1373
1374// CUDA Fortran Programming Guide 3.4.1 defines which assignments in host code
1375// are copies. A copy that reads or writes device, managed or constant data runs
1376// on stream zero, so it waits for previously launched kernels.
1377// - Device or constant data on one side and host data on the other is a copy,
1378// and so is device data on both sides.
1379// - A whole managed variable or array is copied when the other side is a
1380// constant, a host variable, a host array or a host array section.
1381// - A managed array section is assigned by host code when the other side is
1382// host or managed data.
1383// - A managed variable, array or array section is copied when the other side is
1384// device data, in both directions.
1385// One difference from the guide is that a managed array section is copied when
1386// the other side is a whole managed array, as the reference compiler does.
1387// Unified data is host memory that the device can also access, so it takes the
1388// place of host data in the rules above and an assignment between unified sides
1389// is host code.
1390// The side of an assignment is classified from the data it designates, so the
1391// attribute of a component prevails over the attribute of the object it is
1392// taken from.
1393// Return true if the assignment is one of the copies above.
1394template <typename A, typename B>
1395inline bool IsCUDADataTransfer(const A &lhs, const B &rhs) {
1396 semantics::UnorderedSymbolSet lhsSymbols{CollectEffectiveCudaSymbols(lhs)};
1397 semantics::UnorderedSymbolSet rhsSymbols{CollectEffectiveCudaSymbols(rhs)};
1398 // Unified data is left out of these counts and checks so that it is handled
1399 // as host data.
1400 bool lhsHasManaged{CountCUDAManagedSymbols(lhsSymbols) > 0};
1401 bool lhsIsHost{CountCUDANonUnifiedSymbols(lhsSymbols) == 0};
1402 int rhsNbManagedSymbols{CountCUDAManagedSymbols(rhsSymbols)};
1403 int rhsNbSymbols{CountCUDANonUnifiedSymbols(rhsSymbols)};
1404
1405 if (HasNonAllocatableModuleCUDAManagedSymbols(lhs))
1406 return false;
1407
1408 // The host can read and write managed data in place, and copying one section
1409 // at a time in a loop is slow, so only whole arrays are copied.
1410 bool wholeLhs{IsWholeManagedArray(lhs)};
1411 bool wholeRhs{IsWholeManagedArray(rhs)};
1412
1413 if (wholeLhs && rhsNbSymbols == 0 && rhsNbManagedSymbols == 0 &&
1414 (IsVariable(rhs) || IsConstantExpr(rhs))) {
1415 return true; // Whole managed array copied from constant or host data.
1416 }
1417
1418 // The host cannot reach device or constant data, unlike managed and unified
1419 // data, so an assignment with such a side is a copy, sections included.
1420 bool lhsIsDeviceOnly{!lhsHasManaged && !lhsIsHost};
1421 // The right-hand side can be an expression, so one device operand is enough.
1422 bool rhsHasDeviceOnly{rhsNbSymbols > rhsNbManagedSymbols};
1423
1424 // Assignments done on the host, with no copy.
1425 // - A whole allocatable left-hand side with no device data. The assignment
1426 // may reallocate it, which is done on the host.
1427 // - A managed left-hand side with no whole managed array on either side. Only
1428 // sections and elements are involved, and the host reads and writes them in
1429 // place.
1430 // - A host left-hand side assigned from a managed section or element.
1431 // - An expression involving managed data. Evaluating it on the host avoids a
1432 // temporary.
1433 // - A managed left-hand side assigned from host data. Whole arrays are copied
1434 // by the early return above.
1435 if ((IsAllocatableDesignator(lhs) && !lhsIsDeviceOnly && !rhsHasDeviceOnly &&
1436 (lhsHasManaged || rhsNbManagedSymbols >= 1)) ||
1437 (lhsHasManaged && !rhsHasDeviceOnly && !(wholeLhs || wholeRhs)) ||
1438 (lhsIsHost && rhsNbManagedSymbols >= 1 && !rhsHasDeviceOnly &&
1439 !wholeRhs) ||
1440 (rhsNbManagedSymbols >= 1 && !IsVariable(rhs) && !lhsIsDeviceOnly) ||
1441 (lhsHasManaged && rhsNbSymbols == 0)) {
1442 return false;
1443 }
1444 return !lhsIsHost || rhsNbSymbols > 0;
1445}
1446
1449bool HasCUDAImplicitTransfer(const Expr<SomeType> &expr);
1450
1453
1454// Checks whether the symbol on the LHS is present in the RHS expression.
1455bool CheckForSymbolMatch(const Expr<SomeType> *lhs, const Expr<SomeType> *rhs);
1456
1457namespace operation {
1458
1459enum class Operator {
1460 Unknown,
1461 Add,
1462 And,
1463 Associated,
1464 Call,
1465 Constant,
1466 Convert,
1467 Conditional,
1468 Div,
1469 Eq,
1470 Eqv,
1471 False,
1472 Ge,
1473 Gt,
1474 Identity,
1475 Intrinsic,
1476 Le,
1477 Lt,
1478 Max,
1479 Min,
1480 Mul,
1481 Ne,
1482 Neqv,
1483 Not,
1484 Or,
1485 Pow,
1486 Resize, // Convert within the same TypeCategory
1487 Sub,
1488 True,
1489};
1490
1491using OperatorSet = common::EnumSet<Operator, 32>;
1492
1493std::string ToString(Operator op);
1494
1495inline Operator OperationCode(const LogicalOperation &op) {
1496 switch (op.logicalOperator) {
1497 case common::LogicalOperator::And:
1498 return Operator::And;
1499 case common::LogicalOperator::Or:
1500 return Operator::Or;
1501 case common::LogicalOperator::Eqv:
1502 return Operator::Eqv;
1503 case common::LogicalOperator::Neqv:
1504 return Operator::Neqv;
1505 case common::LogicalOperator::Not:
1506 return Operator::Not;
1507 }
1508 return Operator::Unknown;
1509}
1510
1511Operator OperationCode(const Relational<SomeType> &op);
1512
1513template <typename T> Operator OperationCode(const Relational<T> &op) {
1514 switch (op.opr) {
1515 case common::RelationalOperator::LT:
1516 return Operator::Lt;
1517 case common::RelationalOperator::LE:
1518 return Operator::Le;
1519 case common::RelationalOperator::EQ:
1520 return Operator::Eq;
1521 case common::RelationalOperator::NE:
1522 return Operator::Ne;
1523 case common::RelationalOperator::GE:
1524 return Operator::Ge;
1525 case common::RelationalOperator::GT:
1526 return Operator::Gt;
1527 }
1528 return Operator::Unknown;
1529}
1530
1531template <typename T> Operator OperationCode(const Add<T> &op) {
1532 return Operator::Add;
1533}
1534
1535template <typename T> Operator OperationCode(const Subtract<T> &op) {
1536 return Operator::Sub;
1537}
1538
1539template <typename T> Operator OperationCode(const Multiply<T> &op) {
1540 return Operator::Mul;
1541}
1542
1543template <typename T> Operator OperationCode(const Divide<T> &op) {
1544 return Operator::Div;
1545}
1546
1547template <typename T> Operator OperationCode(const Power<T> &op) {
1548 return Operator::Pow;
1549}
1550
1551template <typename T> Operator OperationCode(const RealToIntPower<T> &op) {
1552 return Operator::Pow;
1553}
1554
1555template <typename T, common::TypeCategory C>
1556Operator OperationCode(const Convert<T, C> &op) {
1557 if constexpr (C == T::category) {
1558 return Operator::Resize;
1559 } else {
1560 return Operator::Convert;
1561 }
1562}
1563
1564template <typename T> Operator OperationCode(const Extremum<T> &op) {
1565 if (op.ordering == Ordering::Greater) {
1566 return Operator::Max;
1567 } else {
1568 return Operator::Min;
1569 }
1570}
1571
1572template <typename T> Operator OperationCode(const Constant<T> &x) {
1573 return Operator::Constant;
1574}
1575
1576template <typename T> Operator OperationCode(const Designator<T> &x) {
1577 return Operator::Identity;
1578}
1579
1580template <typename T> Operator OperationCode(const T &) {
1581 return Operator::Unknown;
1582}
1583
1584Operator OperationCode(const ProcedureDesignator &proc);
1585
1586} // namespace operation
1587
1588// Return information about the top-level operation (ignoring parentheses):
1589// the operation code and the list of arguments.
1590std::pair<operation::Operator, std::vector<Expr<SomeType>>>
1591GetTopLevelOperation(const Expr<SomeType> &expr);
1592
1593// Return information about the top-level operation (ignoring parentheses, and
1594// resizing converts)
1595std::pair<operation::Operator, std::vector<Expr<SomeType>>>
1596GetTopLevelOperationIgnoreResizing(const Expr<SomeType> &expr);
1597
1598// Check if expr is same as x, or a sequence of Convert operations on x.
1599bool IsSameOrConvertOf(const Expr<SomeType> &expr, const Expr<SomeType> &x);
1600
1601// Check if the Variable appears as a subexpression of the expression.
1602bool IsVarSubexpressionOf(
1603 const Expr<SomeType> &var, const Expr<SomeType> &super);
1604
1605// Strip away any top-level Convert operations (if any exist) and return
1606// the input value. A ComplexConstructor(x, 0) is also considered as a
1607// convert operation.
1608// If the input is not Operation, Designator, FunctionRef or Constant,
1609// it returns std::nullopt.
1610std::optional<Expr<SomeType>> GetConvertInput(const Expr<SomeType> &x);
1611
1612// How many ancestors does have a derived type have?
1613std::optional<int> CountDerivedTypeAncestors(const semantics::Scope &);
1614
1615// For an expression of enumeration type, extract the value of the hidden
1616// __ordinal component. Returns std::nullopt if the expression is not a
1617// constant or structure constructor of an enumeration-type value.
1618std::optional<Expr<SomeType>> GetEnumerationOrdinal(
1620
1621// Build INT(x), a default INTEGER reference to x's ordinal. The caller must
1622// ensure x is of enumeration type.
1623Expr<SomeType> MakeEnumerationIntCall(Expr<Type<TypeCategory::Derived>> &&);
1624
1625} // namespace Fortran::evaluate
1626
1627namespace Fortran::semantics {
1628
1629class Scope;
1630
1631// If a symbol represents an ENTRY, return the symbol of the main entry
1632// point to its subprogram.
1633const Symbol *GetMainEntry(const Symbol *);
1634
1635inline bool IsAlternateEntry(const Symbol *symbol) {
1636 // If symbol is not alternate entry symbol, GetMainEntry() returns the same
1637 // symbol.
1638 return symbol && GetMainEntry(symbol) != symbol;
1639}
1640
1641// These functions are used in Evaluate so they are defined here rather than in
1642// Semantics to avoid a link-time dependency on Semantics.
1643// All of these apply GetUltimate() or ResolveAssociations() to their arguments.
1644bool IsVariableName(const Symbol &);
1645bool IsPureProcedure(const Symbol &);
1646bool IsPureProcedure(const Scope &);
1647bool IsSimpleProcedure(const Symbol &);
1648bool IsSimpleProcedure(const Scope &);
1649bool IsExplicitlyImpureProcedure(const Symbol &);
1650bool IsElementalProcedure(const Symbol &);
1651bool IsFunction(const Symbol &);
1652bool IsFunction(const Scope &);
1653bool IsProcedure(const Symbol &);
1654bool IsProcedure(const Scope &);
1655bool IsProcedurePointer(const Symbol *);
1656bool IsProcedurePointer(const Symbol &);
1657bool IsObjectPointer(const Symbol *);
1658bool IsAllocatableOrObjectPointer(const Symbol *);
1659bool IsAutomatic(const Symbol &);
1660bool IsSaved(const Symbol &); // saved implicitly or explicitly
1661bool IsDummy(const Symbol &);
1662
1663bool IsAssumedRank(const Symbol &);
1664template <typename A> bool IsAssumedRank(const A &x) {
1665 auto *symbol{UnwrapWholeSymbolDataRef(x)};
1666 return symbol && IsAssumedRank(*symbol);
1667}
1668
1669bool IsAssumedShape(const Symbol &);
1670template <typename A> bool IsAssumedShape(const A &x) {
1671 auto *symbol{UnwrapWholeSymbolDataRef(x)};
1672 return symbol && IsAssumedShape(*symbol);
1673}
1674
1675bool IsDeferredShape(const Symbol &);
1676bool IsFunctionResult(const Symbol &);
1677bool IsKindTypeParameter(const Symbol &);
1678bool IsLenTypeParameter(const Symbol &);
1679bool IsExtensibleType(const DerivedTypeSpec *);
1680bool IsSequenceOrBindCType(const DerivedTypeSpec *);
1681bool IsBuiltinDerivedType(const DerivedTypeSpec *derived, const char *name);
1682bool IsBuiltinCPtr(const Symbol &);
1683bool IsFromBuiltinModule(const Symbol &);
1684bool IsEventType(const DerivedTypeSpec *);
1685bool IsLockType(const DerivedTypeSpec *);
1686bool IsNotifyType(const DerivedTypeSpec *);
1687// Is this derived type IEEE_FLAG_TYPE from module ISO_IEEE_EXCEPTIONS?
1688bool IsIeeeFlagType(const DerivedTypeSpec *);
1689// Is this derived type IEEE_ROUND_TYPE from module ISO_IEEE_ARITHMETIC?
1690bool IsIeeeRoundType(const DerivedTypeSpec *);
1691// Is this derived type TEAM_TYPE from module ISO_FORTRAN_ENV?
1692bool IsTeamType(const DerivedTypeSpec *);
1693// Is this derived type TEAM_TYPE, C_PTR, or C_FUNPTR?
1694bool IsBadCoarrayType(const DerivedTypeSpec *);
1695// Is this derived type either C_PTR or C_FUNPTR from module ISO_C_BINDING
1696bool IsIsoCType(const DerivedTypeSpec *);
1697bool IsEventTypeOrLockType(const DerivedTypeSpec *);
1698inline bool IsAssumedSizeArray(const Symbol &symbol) {
1699 if (const auto *object{symbol.detailsIf<ObjectEntityDetails>()}) {
1700 return (object->isDummy() || symbol.test(Symbol::Flag::CrayPointee)) &&
1701 object->shape().CanBeAssumedSize();
1702 } else if (const auto *assoc{symbol.detailsIf<AssocEntityDetails>()}) {
1703 return assoc->IsAssumedSize();
1704 } else {
1705 return false;
1706 }
1707}
1708
1709// ResolveAssociations() traverses use associations and host associations
1710// like GetUltimate(), but also resolves through whole variable associations
1711// with ASSOCIATE(x => y) and related constructs. GetAssociationRoot()
1712// applies ResolveAssociations() and then, in the case of resolution to
1713// a construct association with part of a variable that does not involve a
1714// vector subscript, returns the first symbol of that variable instead
1715// of the construct entity.
1716// (E.g., for ASSOCIATE(x => y%z), ResolveAssociations(x) returns x,
1717// while GetAssociationRoot(x) returns y.)
1718// In a SELECT RANK construct, ResolveAssociations() stops at a
1719// RANK(n) or RANK(*) case symbol, but traverses the selector for
1720// RANK DEFAULT.
1721const Symbol &ResolveAssociations(const Symbol &, bool stopAtTypeGuard = false);
1722const Symbol &GetAssociationRoot(const Symbol &, bool stopAtTypeGuard = false);
1723
1724const Symbol *FindCommonBlockContaining(const Symbol &);
1725int CountLenParameters(const DerivedTypeSpec &);
1726int CountNonConstantLenParameters(const DerivedTypeSpec &);
1727
1728const Symbol &GetUsedModule(const UseDetails &);
1729const Symbol *FindFunctionResult(const Symbol &);
1730
1731// Type compatibility predicate: are x and y effectively the same type?
1732// Uses DynamicType::IsTkCompatible(), which handles the case of distinct
1733// but identical derived types.
1734bool AreTkCompatibleTypes(const DeclTypeSpec *x, const DeclTypeSpec *y);
1735
1736common::IgnoreTKRSet GetIgnoreTKR(const Symbol &);
1737
1738std::optional<int> GetDummyArgumentNumber(const Symbol *);
1739
1740const Symbol *FindAncestorModuleProcedure(const Symbol *symInSubmodule);
1741
1742// Given a Cray pointee symbol, returns the related Cray pointer symbol.
1743const Symbol &GetCrayPointer(const Symbol &crayPointee);
1744
1745} // namespace Fortran::semantics
1746
1747#endif // FORTRAN_EVALUATE_TOOLS_H_
Definition variable.h:209
Definition variable.h:247
Definition variable.h:362
Definition variable.h:73
Definition expression.h:415
Definition constant.h:181
Definition variable.h:386
Definition type.h:101
Definition common.h:222
Definition common.h:224
Definition call.h:421
Definition variable.h:101
Definition call.h:356
Definition expression.h:757
Definition static-data.h:29
Definition variable.h:309
Definition type.h:61
Definition integer-value.h:35
Definition message.h:399
Definition scope.h:68
Definition symbol.h:905
Definition symbol.h:741
Definition call.h:34
bool HasCUDAImplicitTransfer(const Expr< SomeType > &expr)
Definition tools.cpp:1379
bool HasOnlyCUDAConstntImplicitTransfer(const Expr< SomeType > &expr)
Check if the expression is a mix of host and constant variables.
Definition tools.cpp:1389
Definition expression.h:275
Definition expression.h:373
Definition expression.h:218
Definition variable.h:293
Definition expression.h:263
Definition expression.h:287
Definition expression.h:237
Definition characteristics.h:350