Debian Codegraph @

flang/lib/Evaluate/characteristics.cpp

raw
1 //===-- lib/Evaluate/characteristics.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/characteristics.h"
10 #include "flang/Common/indirection.h"
11 #include "flang/Evaluate/check-expression.h"
12 #include "flang/Evaluate/fold.h"
13 #include "flang/Evaluate/intrinsics.h"
14 #include "flang/Evaluate/tools.h"
15 #include "flang/Evaluate/type.h"
16 #include "flang/Parser/message.h"
17 #include "flang/Semantics/scope.h"
18 #include "flang/Semantics/symbol.h"
19 #include "flang/Semantics/tools.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include <initializer_list>
22
23 using namespace Fortran::parser::literals;
24
25 namespace Fortran::evaluate::characteristics {
26
27 // Copy attributes from a symbol to dst based on the mapping in pairs.
28 // An ASYNCHRONOUS attribute counts even if it is implied.
29 template <typename A, typename B>
30 static void CopyAttrs(const semantics::Symbol &src, A &dst,
31 const std::initializer_list<std::pair<semantics::Attr, B>> &pairs) {
32 for (const auto &pair : pairs) {
33 if (src.attrs().test(pair.first)) {
34 dst.attrs.set(pair.second);
35 }
36 }
37 }
38
39 // Shapes of function results and dummy arguments have to have
40 // the same rank, the same deferred dimensions, and the same
41 // values for explicit dimensions when constant.
42 bool ShapesAreCompatible(const std::optional<Shape> &x,
43 const std::optional<Shape> &y, bool *possibleWarning) {
44 if (!x || !y) {
45 return !x && !y;
46 }
47 if (x->size() != y->size()) {
48 return false;
49 }
50 auto yIter{y->begin()};
51 for (const auto &xDim : *x) {
52 const auto &yDim{*yIter++};
53 if (xDim && yDim) {
54 if (auto equiv{AreEquivalentInInterface(*xDim, *yDim)}) {
55 if (!*equiv) {
56 return false;
57 }
58 } else if (possibleWarning) {
59 *possibleWarning = true;
60 }
61 } else if (xDim || yDim) {
62 return false;
63 }
64 }
65 return true;
66 }
67
68 bool TypeAndShape::operator==(const TypeAndShape &that) const {
69 return type_ == that.type_ && ShapesAreCompatible(shape_, that.shape_) &&
70 attrs_ == that.attrs_ && corank_ == that.corank_;
71 }
72
73 TypeAndShape &TypeAndShape::Rewrite(FoldingContext &context) {
74 LEN_ = Fold(context, std::move(LEN_));
75 if (LEN_) {
76 if (auto n{ToInt64(*LEN_)}) {
77 type_ = DynamicType{type_.kind(), *n};
78 }
79 }
80 shape_ = Fold(context, std::move(shape_));
81 return *this;
82 }
83
84 std::optional<TypeAndShape> TypeAndShape::Characterize(
85 const semantics::Symbol &symbol, FoldingContext &context,
86 bool invariantOnly) {
87 const auto &ultimate{symbol.GetUltimate()};
88 return common::visit(
89 common::visitors{
90 [&](const semantics::ProcEntityDetails &proc) {
91 if (proc.procInterface()) {
92 return Characterize(
93 *proc.procInterface(), context, invariantOnly);
94 } else if (proc.type()) {
95 return Characterize(*proc.type(), context, invariantOnly);
96 } else {
97 return std::optional<TypeAndShape>{};
98 }
99 },
100 [&](const semantics::AssocEntityDetails &assoc) {
101 return Characterize(assoc, context, invariantOnly);
102 },
103 [&](const semantics::ProcBindingDetails &binding) {
104 return Characterize(binding.symbol(), context, invariantOnly);
105 },
106 [&](const auto &x) -> std::optional<TypeAndShape> {
107 using Ty = std::decay_t<decltype(x)>;
108 if constexpr (std::is_same_v<Ty, semantics::EntityDetails> ||
109 std::is_same_v<Ty, semantics::ObjectEntityDetails> ||
110 std::is_same_v<Ty, semantics::TypeParamDetails>) {
111 if (const semantics::DeclTypeSpec * type{ultimate.GetType()}) {
112 if (auto dyType{DynamicType::From(*type)}) {
113 TypeAndShape result{std::move(*dyType),
114 GetShape(context, ultimate, invariantOnly)};
115 result.AcquireAttrs(ultimate);
116 result.AcquireLEN(ultimate);
117 return std::move(result.Rewrite(context));
118 }
119 }
120 }
121 return std::nullopt;
122 },
123 },
124 // GetUltimate() used here, not ResolveAssociations(), because
125 // we need the type/rank of an associate entity from TYPE IS,
126 // CLASS IS, or RANK statement.
127 ultimate.details());
128 }
129
130 std::optional<TypeAndShape> TypeAndShape::Characterize(
131 const semantics::AssocEntityDetails &assoc, FoldingContext &context,
132 bool invariantOnly) {
133 std::optional<TypeAndShape> result;
134 if (auto type{DynamicType::From(assoc.type())}) {
135 if (auto rank{assoc.rank()}) {
136 if (*rank >= 0 && *rank <= common::maxRank) {
137 result = TypeAndShape{std::move(*type), Shape(*rank)};
138 }
139 } else if (auto shape{GetShape(context, assoc.expr(), invariantOnly)}) {
140 result = TypeAndShape{std::move(*type), std::move(*shape)};
141 }
142 if (result && type->category() == TypeCategory::Character) {
143 if (const auto *chExpr{UnwrapExpr<Expr<SomeCharacter>>(assoc.expr())}) {
144 if (auto len{chExpr->LEN()}) {
145 result->set_LEN(std::move(*len));
146 }
147 }
148 }
149 }
150 return Fold(context, std::move(result));
151 }
152
153 std::optional<TypeAndShape> TypeAndShape::Characterize(
154 const semantics::DeclTypeSpec &spec, FoldingContext &context,
155 bool /*invariantOnly=*/) {
156 if (auto type{DynamicType::From(spec)}) {
157 return Fold(context, TypeAndShape{std::move(*type)});
158 } else {
159 return std::nullopt;
160 }
161 }
162
163 std::optional<TypeAndShape> TypeAndShape::Characterize(
164 const ActualArgument &arg, FoldingContext &context, bool invariantOnly) {
165 if (const auto *expr{arg.UnwrapExpr()}) {
166 return Characterize(*expr, context, invariantOnly);
167 } else if (const Symbol * assumed{arg.GetAssumedTypeDummy()}) {
168 return Characterize(*assumed, context, invariantOnly);
169 } else {
170 return std::nullopt;
171 }
172 }
173
174 bool TypeAndShape::IsCompatibleWith(parser::ContextualMessages &messages,
175 const TypeAndShape &that, const char *thisIs, const char *thatIs,
176 bool omitShapeConformanceCheck,
177 enum CheckConformanceFlags::Flags flags) const {
178 if (!type_.IsTkCompatibleWith(that.type_)) {
179 messages.Say(
180 "%1$s type '%2$s' is not compatible with %3$s type '%4$s'"_err_en_US,
181 thatIs, that.AsFortran(), thisIs, AsFortran());
182 return false;
183 }
184 return omitShapeConformanceCheck || (!shape_ && !that.shape_) ||
185 (shape_ && that.shape_ &&
186 CheckConformance(
187 messages, *shape_, *that.shape_, flags, thisIs, thatIs)
188 .value_or(true /*fail only when nonconformance is known now*/));
189 }
190
191 std::optional<Expr<SubscriptInteger>> TypeAndShape::MeasureElementSizeInBytes(
192 FoldingContext &foldingContext, bool align) const {
193 if (LEN_) {
194 CHECK(type_.category() == TypeCategory::Character);
195 return Fold(foldingContext,
196 Expr<SubscriptInteger>{
197 foldingContext.targetCharacteristics().GetByteSize(
198 type_.category(), type_.kind())} *
199 Expr<SubscriptInteger>{*LEN_});
200 }
201 if (auto elementBytes{type_.MeasureSizeInBytes(foldingContext, align)}) {
202 return Fold(foldingContext, std::move(*elementBytes));
203 }
204 return std::nullopt;
205 }
206
207 std::optional<Expr<SubscriptInteger>> TypeAndShape::MeasureSizeInBytes(
208 FoldingContext &foldingContext) const {
209 if (auto elements{GetSize(shape_)}) {
210 // Sizes of arrays (even with single elements) are multiples of
211 // their alignments.
212 if (auto elementBytes{
213 MeasureElementSizeInBytes(foldingContext, Rank() > 0)}) {
214 return Fold(
215 foldingContext, std::move(*elements) * std::move(*elementBytes));
216 }
217 }
218 return std::nullopt;
219 }
220
221 void TypeAndShape::AcquireAttrs(const semantics::Symbol &symbol) {
222 if (IsAssumedShape(symbol)) {
223 attrs_.set(Attr::AssumedShape);
224 } else if (IsDeferredShape(symbol)) {
225 attrs_.set(Attr::DeferredShape);
226 } else if (semantics::IsAssumedSizeArray(symbol)) {
227 attrs_.set(Attr::AssumedSize);
228 }
229 if (const auto *object{
230 symbol.GetUltimate().detailsIf<semantics::ObjectEntityDetails>()}) {
231 corank_ = object->coshape().Rank();
232 if (object->IsAssumedRank()) {
233 attrs_.set(Attr::AssumedRank);
234 }
235 if (object->IsCoarray()) {
236 attrs_.set(Attr::Coarray);
237 }
238 }
239 }
240
241 void TypeAndShape::AcquireLEN() {
242 if (auto len{type_.GetCharLength()}) {
243 LEN_ = std::move(len);
244 }
245 }
246
247 void TypeAndShape::AcquireLEN(const semantics::Symbol &symbol) {
248 if (type_.category() == TypeCategory::Character) {
249 if (auto len{DataRef{symbol}.LEN()}) {
250 LEN_ = std::move(*len);
251 }
252 }
253 }
254
255 std::string TypeAndShape::AsFortran() const {
256 return type_.AsFortran(LEN_ ? LEN_->AsFortran() : "");
257 }
258
259 llvm::raw_ostream &TypeAndShape::Dump(llvm::raw_ostream &o) const {
260 o << type_.AsFortran(LEN_ ? LEN_->AsFortran() : "");
261 attrs_.Dump(o, EnumToString);
262 if (!shape_) {
263 o << " dimension(..)";
264 } else if (!shape_->empty()) {
265 o << " dimension";
266 char sep{'('};
267 for (const auto &expr : *shape_) {
268 o << sep;
269 sep = ',';
270 if (expr) {
271 expr->AsFortran(o);
272 } else {
273 o << ':';
274 }
275 }
276 o << ')';
277 }
278 return o;
279 }
280
281 bool DummyDataObject::operator==(const DummyDataObject &that) const {
282 return type == that.type && attrs == that.attrs && intent == that.intent &&
283 coshape == that.coshape && cudaDataAttr == that.cudaDataAttr;
284 }
285
286 bool DummyDataObject::IsCompatibleWith(const DummyDataObject &actual,
287 std::string *whyNot, std::optional<std::string> *warning) const {
288 bool possibleWarning{false};
289 if (!ShapesAreCompatible(
290 type.shape(), actual.type.shape(), &possibleWarning)) {
291 if (whyNot) {
292 *whyNot = "incompatible dummy data object shapes";
293 }
294 return false;
295 } else if (warning && possibleWarning) {
296 *warning = "distinct dummy data object shapes";
297 }
298 // Treat deduced dummy character type as if it were assumed-length character
299 // to avoid useless "implicit interfaces have distinct type" warnings from
300 // CALL FOO('abc'); CALL FOO('abcd').
301 bool deducedAssumedLength{type.type().category() == TypeCategory::Character &&
302 attrs.test(Attr::DeducedFromActual)};
303 bool compatibleTypes{deducedAssumedLength
304 ? type.type().IsTkCompatibleWith(actual.type.type())
305 : type.type().IsTkLenCompatibleWith(actual.type.type())};
306 if (!compatibleTypes) {
307 if (whyNot) {
308 *whyNot = "incompatible dummy data object types: "s +
309 type.type().AsFortran() + " vs " + actual.type.type().AsFortran();
310 }
311 return false;
312 }
313 if (type.type().IsPolymorphic() != actual.type.type().IsPolymorphic()) {
314 if (whyNot) {
315 *whyNot = "incompatible dummy data object polymorphism: "s +
316 type.type().AsFortran() + " vs " + actual.type.type().AsFortran();
317 }
318 return false;
319 }
320 if (type.type().category() == TypeCategory::Character &&
321 !deducedAssumedLength) {
322 if (actual.type.type().IsAssumedLengthCharacter() !=
323 type.type().IsAssumedLengthCharacter()) {
324 if (whyNot) {
325 *whyNot = "assumed-length character vs explicit-length character";
326 }
327 return false;
328 }
329 if (!type.type().IsAssumedLengthCharacter() && type.LEN() &&
330 actual.type.LEN()) {
331 auto len{ToInt64(*type.LEN())};
332 auto actualLen{ToInt64(*actual.type.LEN())};
333 if (len.has_value() != actualLen.has_value()) {
334 if (whyNot) {
335 *whyNot = "constant-length vs non-constant-length character dummy "
336 "arguments";
337 }
338 return false;
339 } else if (len && *len != *actualLen) {
340 if (whyNot) {
341 *whyNot = "character dummy arguments with distinct lengths";
342 }
343 return false;
344 }
345 }
346 }
347 if (!IdenticalSignificantAttrs(attrs, actual.attrs) ||
348 type.attrs() != actual.type.attrs()) {
349 if (whyNot) {
350 *whyNot = "incompatible dummy data object attributes";
351 }
352 return false;
353 }
354 if (intent != actual.intent) {
355 if (whyNot) {
356 *whyNot = "incompatible dummy data object intents";
357 }
358 return false;
359 }
360 if (coshape != actual.coshape) {
361 if (whyNot) {
362 *whyNot = "incompatible dummy data object coshapes";
363 }
364 return false;
365 }
366 if (ignoreTKR != actual.ignoreTKR) {
367 if (whyNot) {
368 *whyNot = "incompatible !DIR$ IGNORE_TKR directives";
369 }
370 }
371 if (!attrs.test(Attr::Value) &&
372 !common::AreCompatibleCUDADataAttrs(cudaDataAttr, actual.cudaDataAttr,
373 ignoreTKR,
374 /*allowUnifiedMatchingRule=*/false)) {
375 if (whyNot) {
376 *whyNot = "incompatible CUDA data attributes";
377 }
378 }
379 return true;
380 }
381
382 static common::Intent GetIntent(const semantics::Attrs &attrs) {
383 if (attrs.test(semantics::Attr::INTENT_IN)) {
384 return common::Intent::In;
385 } else if (attrs.test(semantics::Attr::INTENT_OUT)) {
386 return common::Intent::Out;
387 } else if (attrs.test(semantics::Attr::INTENT_INOUT)) {
388 return common::Intent::InOut;
389 } else {
390 return common::Intent::Default;
391 }
392 }
393
394 std::optional<DummyDataObject> DummyDataObject::Characterize(
395 const semantics::Symbol &symbol, FoldingContext &context) {
396 if (const auto *object{symbol.detailsIf<semantics::ObjectEntityDetails>()};
397 object || symbol.has<semantics::EntityDetails>()) {
398 if (auto type{TypeAndShape::Characterize(
399 symbol, context, /*invariantOnly=*/false)}) {
400 std::optional<DummyDataObject> result{std::move(*type)};
401 using semantics::Attr;
402 CopyAttrs<DummyDataObject, DummyDataObject::Attr>(symbol, *result,
403 {
404 {Attr::OPTIONAL, DummyDataObject::Attr::Optional},
405 {Attr::ALLOCATABLE, DummyDataObject::Attr::Allocatable},
406 {Attr::ASYNCHRONOUS, DummyDataObject::Attr::Asynchronous},
407 {Attr::CONTIGUOUS, DummyDataObject::Attr::Contiguous},
408 {Attr::VALUE, DummyDataObject::Attr::Value},
409 {Attr::VOLATILE, DummyDataObject::Attr::Volatile},
410 {Attr::POINTER, DummyDataObject::Attr::Pointer},
411 {Attr::TARGET, DummyDataObject::Attr::Target},
412 });
413 result->intent = GetIntent(symbol.attrs());
414 result->ignoreTKR = GetIgnoreTKR(symbol);
415 if (object) {
416 result->cudaDataAttr = object->cudaDataAttr();
417 if (!result->cudaDataAttr &&
418 !result->attrs.test(DummyDataObject::Attr::Value) &&
419 semantics::IsCUDADeviceContext(&symbol.owner())) {
420 result->cudaDataAttr = common::CUDADataAttr::Device;
421 }
422 }
423 return result;
424 }
425 }
426 return std::nullopt;
427 }
428
429 bool DummyDataObject::CanBePassedViaImplicitInterface(
430 std::string *whyNot) const {
431 if ((attrs &
432 Attrs{Attr::Allocatable, Attr::Asynchronous, Attr::Optional,
433 Attr::Pointer, Attr::Target, Attr::Value, Attr::Volatile})
434 .any()) {
435 if (whyNot) {
436 *whyNot = "a dummy argument has the allocatable, asynchronous, optional, "
437 "pointer, target, value, or volatile attribute";
438 }
439 return false; // 15.4.2.2(3)(a)
440 } else if ((type.attrs() &
441 TypeAndShape::Attrs{TypeAndShape::Attr::AssumedShape,
442 TypeAndShape::Attr::AssumedRank,
443 TypeAndShape::Attr::Coarray})
444 .any()) {
445 if (whyNot) {
446 *whyNot = "a dummy argument is assumed-shape, assumed-rank, or a coarray";
447 }
448 return false; // 15.4.2.2(3)(b-d)
449 } else if (type.type().IsPolymorphic()) {
450 if (whyNot) {
451 *whyNot = "a dummy argument is polymorphic";
452 }
453 return false; // 15.4.2.2(3)(f)
454 } else if (cudaDataAttr) {
455 if (whyNot) {
456 *whyNot = "a dummy argument has a CUDA data attribute";
457 }
458 return false;
459 } else if (const auto *derived{GetDerivedTypeSpec(type.type())}) {
460 if (derived->parameters().empty()) { // 15.4.2.2(3)(e)
461 return true;
462 } else {
463 if (whyNot) {
464 *whyNot = "a dummy argument has derived type parameters";
465 }
466 return false;
467 }
468 } else {
469 return true;
470 }
471 }
472
473 bool DummyDataObject::IsPassedByDescriptor(bool isBindC) const {
474 constexpr TypeAndShape::Attrs shapeRequiringBox = {
475 TypeAndShape::Attr::AssumedShape, TypeAndShape::Attr::DeferredShape,
476 TypeAndShape::Attr::AssumedRank, TypeAndShape::Attr::Coarray};
477 if ((attrs & Attrs{Attr::Allocatable, Attr::Pointer}).any()) {
478 return true;
479 } else if ((type.attrs() & shapeRequiringBox).any()) {
480 // Need to pass shape/coshape info in a descriptor.
481 return true;
482 } else if (type.type().IsPolymorphic() && !type.type().IsAssumedType()) {
483 // Need to pass dynamic type info in a descriptor.
484 return true;
485 } else if (const auto *derived{GetDerivedTypeSpec(type.type())}) {
486 if (!derived->parameters().empty()) {
487 for (const auto &param : derived->parameters()) {
488 if (param.second.isLen()) {
489 // Need to pass length type parameters in a descriptor.
490 return true;
491 }
492 }
493 }
494 } else if (isBindC && type.type().IsAssumedLengthCharacter()) {
495 // Fortran 2018 18.3.6 point 2 (5)
496 return true;
497 }
498 return false;
499 }
500
501 llvm::raw_ostream &DummyDataObject::Dump(llvm::raw_ostream &o) const {
502 attrs.Dump(o, EnumToString);
503 if (intent != common::Intent::Default) {
504 o << "INTENT(" << common::EnumToString(intent) << ')';
505 }
506 type.Dump(o);
507 if (!coshape.empty()) {
508 char sep{'['};
509 for (const auto &expr : coshape) {
510 expr.AsFortran(o << sep);
511 sep = ',';
512 }
513 }
514 if (cudaDataAttr) {
515 o << " cudaDataAttr: " << common::EnumToString(*cudaDataAttr);
516 }
517 if (!ignoreTKR.empty()) {
518 ignoreTKR.Dump(o << ' ', common::EnumToString);
519 }
520 return o;
521 }
522
523 DummyProcedure::DummyProcedure(Procedure &&p)
524 : procedure{new Procedure{std::move(p)}} {}
525
526 bool DummyProcedure::operator==(const DummyProcedure &that) const {
527 return attrs == that.attrs && intent == that.intent &&
528 procedure.value() == that.procedure.value();
529 }
530
531 bool DummyProcedure::IsCompatibleWith(
532 const DummyProcedure &actual, std::string *whyNot) const {
533 if (attrs != actual.attrs) {
534 if (whyNot) {
535 *whyNot = "incompatible dummy procedure attributes";
536 }
537 return false;
538 }
539 if (intent != actual.intent) {
540 if (whyNot) {
541 *whyNot = "incompatible dummy procedure intents";
542 }
543 return false;
544 }
545 if (!procedure.value().IsCompatibleWith(actual.procedure.value(),
546 /*ignoreImplicitVsExplicit=*/false, whyNot)) {
547 if (whyNot) {
548 *whyNot = "incompatible dummy procedure interfaces: "s + *whyNot;
549 }
550 return false;
551 }
552 return true;
553 }
554
555 bool DummyProcedure::CanBePassedViaImplicitInterface(
556 std::string *whyNot) const {
557 if ((attrs & Attrs{Attr::Optional, Attr::Pointer}).any()) {
558 if (whyNot) {
559 *whyNot = "a dummy procedure is optional or a pointer";
560 }
561 return false; // 15.4.2.2(3)(a)
562 }
563 return true;
564 }
565
566 static std::string GetSeenProcs(
567 const semantics::UnorderedSymbolSet &seenProcs) {
568 // Sort the symbols so that they appear in the same order on all platforms
569 auto ordered{semantics::OrderBySourcePosition(seenProcs)};
570 std::string result;
571 llvm::interleave(
572 ordered,
573 [&](const SymbolRef p) { result += '\'' + p->name().ToString() + '\''; },
574 [&]() { result += ", "; });
575 return result;
576 }
577
578 // These functions with arguments of type UnorderedSymbolSet are used with
579 // mutually recursive calls when characterizing a Procedure, a DummyArgument,
580 // or a DummyProcedure to detect circularly defined procedures as required by
581 // 15.4.3.6, paragraph 2.
582 static std::optional<DummyArgument> CharacterizeDummyArgument(
583 const semantics::Symbol &symbol, FoldingContext &context,
584 semantics::UnorderedSymbolSet seenProcs);
585 static std::optional<FunctionResult> CharacterizeFunctionResult(
586 const semantics::Symbol &symbol, FoldingContext &context,
587 semantics::UnorderedSymbolSet seenProcs, bool emitError);
588
589 static std::optional<Procedure> CharacterizeProcedure(
590 const semantics::Symbol &original, FoldingContext &context,
591 semantics::UnorderedSymbolSet seenProcs, bool emitError) {
592 const auto &symbol{ResolveAssociations(original)};
593 if (seenProcs.find(symbol) != seenProcs.end()) {
594 std::string procsList{GetSeenProcs(seenProcs)};
595 context.messages().Say(symbol.name(),
596 "Procedure '%s' is recursively defined. Procedures in the cycle:"
597 " %s"_err_en_US,
598 symbol.name(), procsList);
599 return std::nullopt;
600 }
601 seenProcs.insert(symbol);
602 auto CheckForNested{[&](const Symbol &symbol) {
603 if (emitError) {
604 context.messages().Say(
605 "Procedure '%s' is referenced before being sufficiently defined in a context where it must be so"_err_en_US,
606 symbol.name());
607 }
608 }};
609 auto result{common::visit(
610 common::visitors{
611 [&](const semantics::SubprogramDetails &subp)
612 -> std::optional<Procedure> {
613 Procedure result;
614 if (subp.isFunction()) {
615 if (auto fr{CharacterizeFunctionResult(
616 subp.result(), context, seenProcs, emitError)}) {
617 result.functionResult = std::move(fr);
618 } else {
619 return std::nullopt;
620 }
621 } else {
622 result.attrs.set(Procedure::Attr::Subroutine);
623 }
624 for (const semantics::Symbol *arg : subp.dummyArgs()) {
625 if (!arg) {
626 if (subp.isFunction()) {
627 return std::nullopt;
628 } else {
629 result.dummyArguments.emplace_back(AlternateReturn{});
630 }
631 } else if (auto argCharacteristics{CharacterizeDummyArgument(
632 *arg, context, seenProcs)}) {
633 result.dummyArguments.emplace_back(
634 std::move(argCharacteristics.value()));
635 } else {
636 return std::nullopt;
637 }
638 }
639 result.cudaSubprogramAttrs = subp.cudaSubprogramAttrs();
640 return std::move(result);
641 },
642 [&](const semantics::ProcEntityDetails &proc)
643 -> std::optional<Procedure> {
644 if (symbol.attrs().test(semantics::Attr::INTRINSIC)) {
645 // Fails when the intrinsic is not a specific intrinsic function
646 // from F'2018 table 16.2. In order to handle forward references,
647 // attempts to use impermissible intrinsic procedures as the
648 // interfaces of procedure pointers are caught and flagged in
649 // declaration checking in Semantics.
650 auto intrinsic{context.intrinsics().IsSpecificIntrinsicFunction(
651 symbol.name().ToString())};
652 if (intrinsic && intrinsic->isRestrictedSpecific) {
653 intrinsic.reset(); // Exclude intrinsics from table 16.3.
654 }
655 return intrinsic;
656 }
657 if (const semantics::Symbol *
658 interfaceSymbol{proc.procInterface()}) {
659 auto result{CharacterizeProcedure(
660 *interfaceSymbol, context, seenProcs, /*emitError=*/false)};
661 if (result && (IsDummy(symbol) || IsPointer(symbol))) {
662 // Dummy procedures and procedure pointers may not be
663 // ELEMENTAL, but we do accept the use of elemental intrinsic
664 // functions as their interfaces.
665 result->attrs.reset(Procedure::Attr::Elemental);
666 }
667 return result;
668 } else {
669 Procedure result;
670 result.attrs.set(Procedure::Attr::ImplicitInterface);
671 const semantics::DeclTypeSpec *type{proc.type()};
672 if (symbol.test(semantics::Symbol::Flag::Subroutine)) {
673 // ignore any implicit typing
674 result.attrs.set(Procedure::Attr::Subroutine);
675 if (proc.isCUDAKernel()) {
676 result.cudaSubprogramAttrs =
677 common::CUDASubprogramAttrs::Global;
678 }
679 } else if (type) {
680 if (auto resultType{DynamicType::From(*type)}) {
681 result.functionResult = FunctionResult{*resultType};
682 } else {
683 return std::nullopt;
684 }
685 } else if (symbol.test(semantics::Symbol::Flag::Function)) {
686 return std::nullopt;
687 }
688 // The PASS name, if any, is not a characteristic.
689 return std::move(result);
690 }
691 },
692 [&](const semantics::ProcBindingDetails &binding) {
693 if (auto result{CharacterizeProcedure(binding.symbol(), context,
694 seenProcs, /*emitError=*/false)}) {
695 if (binding.symbol().attrs().test(semantics::Attr::INTRINSIC)) {
696 result->attrs.reset(Procedure::Attr::Elemental);
697 }
698 if (!symbol.attrs().test(semantics::Attr::NOPASS)) {
699 auto passName{binding.passName()};
700 for (auto &dummy : result->dummyArguments) {
701 if (!passName || dummy.name.c_str() == *passName) {
702 dummy.pass = true;
703 break;
704 }
705 }
706 }
707 return result;
708 } else {
709 return std::optional<Procedure>{};
710 }
711 },
712 [&](const semantics::UseDetails &use) {
713 return CharacterizeProcedure(
714 use.symbol(), context, seenProcs, /*emitError=*/false);
715 },
716 [](const semantics::UseErrorDetails &) {
717 // Ambiguous use-association will be handled later during symbol
718 // checks, ignore UseErrorDetails here without actual symbol usage.
719 return std::optional<Procedure>{};
720 },
721 [&](const semantics::HostAssocDetails &assoc) {
722 return CharacterizeProcedure(
723 assoc.symbol(), context, seenProcs, /*emitError=*/false);
724 },
725 [&](const semantics::GenericDetails &generic) {
726 if (const semantics::Symbol * specific{generic.specific()}) {
727 return CharacterizeProcedure(
728 *specific, context, seenProcs, emitError);
729 } else {
730 return std::optional<Procedure>{};
731 }
732 },
733 [&](const semantics::EntityDetails &) {
734 CheckForNested(symbol);
735 return std::optional<Procedure>{};
736 },
737 [&](const semantics::SubprogramNameDetails &) {
738 CheckForNested(symbol);
739 return std::optional<Procedure>{};
740 },
741 [&](const auto &) {
742 context.messages().Say(
743 "'%s' is not a procedure"_err_en_US, symbol.name());
744 return std::optional<Procedure>{};
745 },
746 },
747 symbol.details())};
748 if (result && !symbol.has<semantics::ProcBindingDetails>()) {
749 CopyAttrs<Procedure, Procedure::Attr>(symbol, *result,
750 {
751 {semantics::Attr::BIND_C, Procedure::Attr::BindC},
752 });
753 CopyAttrs<Procedure, Procedure::Attr>(DEREF(GetMainEntry(&symbol)), *result,
754 {
755 {semantics::Attr::ELEMENTAL, Procedure::Attr::Elemental},
756 });
757 if (IsPureProcedure(symbol) || // works for ENTRY too
758 (!IsExplicitlyImpureProcedure(symbol) &&
759 result->attrs.test(Procedure::Attr::Elemental))) {
760 result->attrs.set(Procedure::Attr::Pure);
761 }
762 }
763 return result;
764 }
765
766 static std::optional<DummyProcedure> CharacterizeDummyProcedure(
767 const semantics::Symbol &symbol, FoldingContext &context,
768 semantics::UnorderedSymbolSet seenProcs) {
769 if (auto procedure{CharacterizeProcedure(
770 symbol, context, seenProcs, /*emitError=*/true)}) {
771 // Dummy procedures may not be elemental. Elemental dummy procedure
772 // interfaces are errors when the interface is not intrinsic, and that
773 // error is caught elsewhere. Elemental intrinsic interfaces are
774 // made non-elemental.
775 procedure->attrs.reset(Procedure::Attr::Elemental);
776 DummyProcedure result{std::move(procedure.value())};
777 CopyAttrs<DummyProcedure, DummyProcedure::Attr>(symbol, result,
778 {
779 {semantics::Attr::OPTIONAL, DummyProcedure::Attr::Optional},
780 {semantics::Attr::POINTER, DummyProcedure::Attr::Pointer},
781 });
782 result.intent = GetIntent(symbol.attrs());
783 return result;
784 } else {
785 return std::nullopt;
786 }
787 }
788
789 llvm::raw_ostream &DummyProcedure::Dump(llvm::raw_ostream &o) const {
790 attrs.Dump(o, EnumToString);
791 if (intent != common::Intent::Default) {
792 o << "INTENT(" << common::EnumToString(intent) << ')';
793 }
794 procedure.value().Dump(o);
795 return o;
796 }
797
798 llvm::raw_ostream &AlternateReturn::Dump(llvm::raw_ostream &o) const {
799 return o << '*';
800 }
801
802 DummyArgument::~DummyArgument() {}
803
804 bool DummyArgument::operator==(const DummyArgument &that) const {
805 return u == that.u; // name and passed-object usage are not characteristics
806 }
807
808 bool DummyArgument::IsCompatibleWith(const DummyArgument &actual,
809 std::string *whyNot, std::optional<std::string> *warning) const {
810 if (const auto *ifaceData{std::get_if<DummyDataObject>(&u)}) {
811 if (const auto *actualData{std::get_if<DummyDataObject>(&actual.u)}) {
812 return ifaceData->IsCompatibleWith(*actualData, whyNot, warning);
813 }
814 if (whyNot) {
815 *whyNot = "one dummy argument is an object, the other is not";
816 }
817 } else if (const auto *ifaceProc{std::get_if<DummyProcedure>(&u)}) {
818 if (const auto *actualProc{std::get_if<DummyProcedure>(&actual.u)}) {
819 return ifaceProc->IsCompatibleWith(*actualProc, whyNot);
820 }
821 if (whyNot) {
822 *whyNot = "one dummy argument is a procedure, the other is not";
823 }
824 } else {
825 CHECK(std::holds_alternative<AlternateReturn>(u));
826 if (std::holds_alternative<AlternateReturn>(actual.u)) {
827 return true;
828 }
829 if (whyNot) {
830 *whyNot = "one dummy argument is an alternate return, the other is not";
831 }
832 }
833 return false;
834 }
835
836 static std::optional<DummyArgument> CharacterizeDummyArgument(
837 const semantics::Symbol &symbol, FoldingContext &context,
838 semantics::UnorderedSymbolSet seenProcs) {
839 auto name{symbol.name().ToString()};
840 if (symbol.has<semantics::ObjectEntityDetails>() ||
841 symbol.has<semantics::EntityDetails>()) {
842 if (auto obj{DummyDataObject::Characterize(symbol, context)}) {
843 return DummyArgument{std::move(name), std::move(obj.value())};
844 }
845 } else if (auto proc{
846 CharacterizeDummyProcedure(symbol, context, seenProcs)}) {
847 return DummyArgument{std::move(name), std::move(proc.value())};
848 }
849 return std::nullopt;
850 }
851
852 std::optional<DummyArgument> DummyArgument::FromActual(std::string &&name,
853 const Expr<SomeType> &expr, FoldingContext &context,
854 bool forImplicitInterface) {
855 return common::visit(
856 common::visitors{
857 [&](const BOZLiteralConstant &) {
858 DummyDataObject obj{
859 TypeAndShape{DynamicType::TypelessIntrinsicArgument()}};
860 obj.attrs.set(DummyDataObject::Attr::DeducedFromActual);
861 return std::make_optional<DummyArgument>(
862 std::move(name), std::move(obj));
863 },
864 [&](const NullPointer &) {
865 DummyDataObject obj{
866 TypeAndShape{DynamicType::TypelessIntrinsicArgument()}};
867 obj.attrs.set(DummyDataObject::Attr::DeducedFromActual);
868 return std::make_optional<DummyArgument>(
869 std::move(name), std::move(obj));
870 },
871 [&](const ProcedureDesignator &designator) {
872 if (auto proc{Procedure::Characterize(
873 designator, context, /*emitError=*/true)}) {
874 return std::make_optional<DummyArgument>(
875 std::move(name), DummyProcedure{std::move(*proc)});
876 } else {
877 return std::optional<DummyArgument>{};
878 }
879 },
880 [&](const ProcedureRef &call) {
881 if (auto proc{Procedure::Characterize(call, context)}) {
882 return std::make_optional<DummyArgument>(
883 std::move(name), DummyProcedure{std::move(*proc)});
884 } else {
885 return std::optional<DummyArgument>{};
886 }
887 },
888 [&](const auto &) {
889 if (auto type{TypeAndShape::Characterize(expr, context)}) {
890 if (forImplicitInterface &&
891 !type->type().IsUnlimitedPolymorphic() &&
892 type->type().IsPolymorphic()) {
893 // Pass the monomorphic declared type to an implicit interface
894 type->set_type(DynamicType{
895 type->type().GetDerivedTypeSpec(), /*poly=*/false});
896 }
897 DummyDataObject obj{std::move(*type)};
898 obj.attrs.set(DummyDataObject::Attr::DeducedFromActual);
899 return std::make_optional<DummyArgument>(
900 std::move(name), std::move(obj));
901 } else {
902 return std::optional<DummyArgument>{};
903 }
904 },
905 },
906 expr.u);
907 }
908
909 std::optional<DummyArgument> DummyArgument::FromActual(std::string &&name,
910 const ActualArgument &arg, FoldingContext &context,
911 bool forImplicitInterface) {
912 if (const auto *expr{arg.UnwrapExpr()}) {
913 return FromActual(std::move(name), *expr, context, forImplicitInterface);
914 } else if (arg.GetAssumedTypeDummy()) {
915 return std::nullopt;
916 } else {
917 return DummyArgument{AlternateReturn{}};
918 }
919 }
920
921 bool DummyArgument::IsOptional() const {
922 return common::visit(
923 common::visitors{
924 [](const DummyDataObject &data) {
925 return data.attrs.test(DummyDataObject::Attr::Optional);
926 },
927 [](const DummyProcedure &proc) {
928 return proc.attrs.test(DummyProcedure::Attr::Optional);
929 },
930 [](const AlternateReturn &) { return false; },
931 },
932 u);
933 }
934
935 void DummyArgument::SetOptional(bool value) {
936 common::visit(common::visitors{
937 [value](DummyDataObject &data) {
938 data.attrs.set(DummyDataObject::Attr::Optional, value);
939 },
940 [value](DummyProcedure &proc) {
941 proc.attrs.set(DummyProcedure::Attr::Optional, value);
942 },
943 [](AlternateReturn &) { DIE("cannot set optional"); },
944 },
945 u);
946 }
947
948 void DummyArgument::SetIntent(common::Intent intent) {
949 common::visit(common::visitors{
950 [intent](DummyDataObject &data) { data.intent = intent; },
951 [intent](DummyProcedure &proc) { proc.intent = intent; },
952 [](AlternateReturn &) { DIE("cannot set intent"); },
953 },
954 u);
955 }
956
957 common::Intent DummyArgument::GetIntent() const {
958 return common::visit(
959 common::visitors{
960 [](const DummyDataObject &data) { return data.intent; },
961 [](const DummyProcedure &proc) { return proc.intent; },
962 [](const AlternateReturn &) -> common::Intent {
963 DIE("Alternate returns have no intent");
964 },
965 },
966 u);
967 }
968
969 bool DummyArgument::CanBePassedViaImplicitInterface(std::string *whyNot) const {
970 if (const auto *object{std::get_if<DummyDataObject>(&u)}) {
971 return object->CanBePassedViaImplicitInterface(whyNot);
972 } else if (const auto *proc{std::get_if<DummyProcedure>(&u)}) {
973 return proc->CanBePassedViaImplicitInterface(whyNot);
974 } else {
975 return true;
976 }
977 }
978
979 bool DummyArgument::IsTypelessIntrinsicDummy() const {
980 const auto *argObj{std::get_if<characteristics::DummyDataObject>(&u)};
981 return argObj && argObj->type.type().IsTypelessIntrinsicArgument();
982 }
983
984 llvm::raw_ostream &DummyArgument::Dump(llvm::raw_ostream &o) const {
985 if (!name.empty()) {
986 o << name << '=';
987 }
988 if (pass) {
989 o << " PASS";
990 }
991 common::visit([&](const auto &x) { x.Dump(o); }, u);
992 return o;
993 }
994
995 FunctionResult::FunctionResult(DynamicType t) : u{TypeAndShape{t}} {}
996 FunctionResult::FunctionResult(TypeAndShape &&t) : u{std::move(t)} {}
997 FunctionResult::FunctionResult(Procedure &&p) : u{std::move(p)} {}
998 FunctionResult::~FunctionResult() {}
999
1000 bool FunctionResult::operator==(const FunctionResult &that) const {
1001 return attrs == that.attrs && cudaDataAttr == that.cudaDataAttr &&
1002 u == that.u;
1003 }
1004
1005 static std::optional<FunctionResult> CharacterizeFunctionResult(
1006 const semantics::Symbol &symbol, FoldingContext &context,
1007 semantics::UnorderedSymbolSet seenProcs, bool emitError) {
1008 if (const auto *object{symbol.detailsIf<semantics::ObjectEntityDetails>()}) {
1009 if (auto type{TypeAndShape::Characterize(
1010 symbol, context, /*invariantOnly=*/false)}) {
1011 FunctionResult result{std::move(*type)};
1012 CopyAttrs<FunctionResult, FunctionResult::Attr>(symbol, result,
1013 {
1014 {semantics::Attr::ALLOCATABLE, FunctionResult::Attr::Allocatable},
1015 {semantics::Attr::CONTIGUOUS, FunctionResult::Attr::Contiguous},
1016 {semantics::Attr::POINTER, FunctionResult::Attr::Pointer},
1017 });
1018 result.cudaDataAttr = object->cudaDataAttr();
1019 return result;
1020 }
1021 } else if (auto maybeProc{CharacterizeProcedure(
1022 symbol, context, seenProcs, emitError)}) {
1023 FunctionResult result{std::move(*maybeProc)};
1024 result.attrs.set(FunctionResult::Attr::Pointer);
1025 return result;
1026 }
1027 return std::nullopt;
1028 }
1029
1030 std::optional<FunctionResult> FunctionResult::Characterize(
1031 const Symbol &symbol, FoldingContext &context) {
1032 semantics::UnorderedSymbolSet seenProcs;
1033 return CharacterizeFunctionResult(
1034 symbol, context, seenProcs, /*emitError=*/false);
1035 }
1036
1037 bool FunctionResult::IsAssumedLengthCharacter() const {
1038 if (const auto *ts{std::get_if<TypeAndShape>(&u)}) {
1039 return ts->type().IsAssumedLengthCharacter();
1040 } else {
1041 return false;
1042 }
1043 }
1044
1045 bool FunctionResult::CanBeReturnedViaImplicitInterface(
1046 std::string *whyNot) const {
1047 if (attrs.test(Attr::Pointer) || attrs.test(Attr::Allocatable)) {
1048 if (whyNot) {
1049 *whyNot = "the function result is a pointer or allocatable";
1050 }
1051 return false; // 15.4.2.2(4)(b)
1052 } else if (cudaDataAttr) {
1053 if (whyNot) {
1054 *whyNot = "the function result has CUDA attributes";
1055 }
1056 return false;
1057 } else if (const auto *typeAndShape{GetTypeAndShape()}) {
1058 if (typeAndShape->Rank() > 0) {
1059 if (whyNot) {
1060 *whyNot = "the function result is an array";
1061 }
1062 return false; // 15.4.2.2(4)(a)
1063 } else {
1064 const DynamicType &type{typeAndShape->type()};
1065 switch (type.category()) {
1066 case TypeCategory::Character:
1067 if (type.knownLength()) {
1068 return true;
1069 } else if (const auto *param{type.charLengthParamValue()}) {
1070 if (const auto &expr{param->GetExplicit()}) {
1071 if (IsConstantExpr(*expr)) { // 15.4.2.2(4)(c)
1072 return true;
1073 } else {
1074 if (whyNot) {
1075 *whyNot = "the function result's length is not constant";
1076 }
1077 return false;
1078 }
1079 } else if (param->isAssumed()) {
1080 return true;
1081 }
1082 }
1083 if (whyNot) {
1084 *whyNot = "the function result's length is not known to the caller";
1085 }
1086 return false;
1087 case TypeCategory::Derived:
1088 if (type.IsPolymorphic()) {
1089 if (whyNot) {
1090 *whyNot = "the function result is polymorphic";
1091 }
1092 return false;
1093 } else {
1094 const auto &spec{type.GetDerivedTypeSpec()};
1095 for (const auto &pair : spec.parameters()) {
1096 if (const auto &expr{pair.second.GetExplicit()}) {
1097 if (!IsConstantExpr(*expr)) {
1098 if (whyNot) {
1099 *whyNot = "the function result's derived type has a "
1100 "non-constant parameter";
1101 }
1102 return false; // 15.4.2.2(4)(c)
1103 }
1104 }
1105 }
1106 return true;
1107 }
1108 default:
1109 return true;
1110 }
1111 }
1112 } else {
1113 if (whyNot) {
1114 *whyNot = "the function result has unknown type or shape";
1115 }
1116 return false; // 15.4.2.2(4)(b) - procedure pointer?
1117 }
1118 }
1119
1120 static std::optional<std::string> AreIncompatibleFunctionResultShapes(
1121 const Shape &x, const Shape &y) {
1122 // Function results cannot be assumed-rank, hence the non optional arguments.
1123 int rank{GetRank(x)};
1124 if (int yrank{GetRank(y)}; yrank != rank) {
1125 return "rank "s + std::to_string(rank) + " vs " + std::to_string(yrank);
1126 }
1127 for (int j{0}; j < rank; ++j) {
1128 if (x[j] && y[j] && !(*x[j] == *y[j])) {
1129 return x[j]->AsFortran() + " vs " + y[j]->AsFortran();
1130 }
1131 }
1132 return std::nullopt;
1133 }
1134
1135 bool FunctionResult::IsCompatibleWith(
1136 const FunctionResult &actual, std::string *whyNot) const {
1137 Attrs actualAttrs{actual.attrs};
1138 if (!attrs.test(Attr::Contiguous)) {
1139 actualAttrs.reset(Attr::Contiguous);
1140 }
1141 if (attrs != actualAttrs) {
1142 if (whyNot) {
1143 *whyNot = "function results have incompatible attributes";
1144 }
1145 } else if (cudaDataAttr != actual.cudaDataAttr) {
1146 if (whyNot) {
1147 *whyNot = "function results have incompatible CUDA data attributes";
1148 }
1149 } else if (const auto *ifaceTypeShape{std::get_if<TypeAndShape>(&u)}) {
1150 if (const auto *actualTypeShape{std::get_if<TypeAndShape>(&actual.u)}) {
1151 std::optional<std::string> details;
1152 if (ifaceTypeShape->Rank() != actualTypeShape->Rank()) {
1153 if (whyNot) {
1154 *whyNot = "function results have distinct ranks";
1155 }
1156 } else if (!attrs.test(Attr::Allocatable) && !attrs.test(Attr::Pointer) &&
1157 (details = AreIncompatibleFunctionResultShapes(
1158 ifaceTypeShape->shape().value(),
1159 actualTypeShape->shape().value()))) {
1160 if (whyNot) {
1161 *whyNot = "function results have distinct extents (" + *details + ')';
1162 }
1163 } else if (ifaceTypeShape->type() != actualTypeShape->type()) {
1164 if (ifaceTypeShape->type().category() !=
1165 actualTypeShape->type().category()) {
1166 } else if (ifaceTypeShape->type().category() ==
1167 TypeCategory::Character) {
1168 if (ifaceTypeShape->type().kind() == actualTypeShape->type().kind()) {
1169 if (IsAssumedLengthCharacter() ||
1170 actual.IsAssumedLengthCharacter()) {
1171 return true;
1172 } else {
1173 auto len{ToInt64(ifaceTypeShape->LEN())};
1174 auto actualLen{ToInt64(actualTypeShape->LEN())};
1175 if (len.has_value() != actualLen.has_value()) {
1176 if (whyNot) {
1177 *whyNot = "constant-length vs non-constant-length character "
1178 "results";
1179 }
1180 } else if (len && *len != *actualLen) {
1181 if (whyNot) {
1182 *whyNot = "character results with distinct lengths";
1183 }
1184 } else {
1185 const auto *ifaceLenParam{
1186 ifaceTypeShape->type().charLengthParamValue()};
1187 const auto *actualLenParam{
1188 actualTypeShape->type().charLengthParamValue()};
1189 if (ifaceLenParam && actualLenParam &&
1190 ifaceLenParam->isExplicit() !=
1191 actualLenParam->isExplicit()) {
1192 if (whyNot) {
1193 *whyNot =
1194 "explicit-length vs deferred-length character results";
1195 }
1196 } else {
1197 return true;
1198 }
1199 }
1200 }
1201 }
1202 } else if (ifaceTypeShape->type().category() == TypeCategory::Derived) {
1203 if (ifaceTypeShape->type().IsPolymorphic() ==
1204 actualTypeShape->type().IsPolymorphic() &&
1205 !ifaceTypeShape->type().IsUnlimitedPolymorphic() &&
1206 !actualTypeShape->type().IsUnlimitedPolymorphic() &&
1207 AreSameDerivedType(ifaceTypeShape->type().GetDerivedTypeSpec(),
1208 actualTypeShape->type().GetDerivedTypeSpec())) {
1209 return true;
1210 }
1211 }
1212 if (whyNot) {
1213 *whyNot = "function results have distinct types: "s +
1214 ifaceTypeShape->type().AsFortran() + " vs "s +
1215 actualTypeShape->type().AsFortran();
1216 }
1217 } else {
1218 return true;
1219 }
1220 } else {
1221 if (whyNot) {
1222 *whyNot = "function result type and shape are not known";
1223 }
1224 }
1225 } else {
1226 const auto *ifaceProc{std::get_if<CopyableIndirection<Procedure>>(&u)};
1227 CHECK(ifaceProc != nullptr);
1228 if (const auto *actualProc{
1229 std::get_if<CopyableIndirection<Procedure>>(&actual.u)}) {
1230 if (ifaceProc->value().IsCompatibleWith(actualProc->value(),
1231 /*ignoreImplicitVsExplicit=*/false, whyNot)) {
1232 return true;
1233 }
1234 if (whyNot) {
1235 *whyNot =
1236 "function results are incompatible procedure pointers: "s + *whyNot;
1237 }
1238 } else {
1239 if (whyNot) {
1240 *whyNot =
1241 "one function result is a procedure pointer, the other is not";
1242 }
1243 }
1244 }
1245 return false;
1246 }
1247
1248 llvm::raw_ostream &FunctionResult::Dump(llvm::raw_ostream &o) const {
1249 attrs.Dump(o, EnumToString);
1250 common::visit(common::visitors{
1251 [&](const TypeAndShape &ts) { ts.Dump(o); },
1252 [&](const CopyableIndirection<Procedure> &p) {
1253 p.value().Dump(o << " procedure(") << ')';
1254 },
1255 },
1256 u);
1257 if (cudaDataAttr) {
1258 o << " cudaDataAttr: " << common::EnumToString(*cudaDataAttr);
1259 }
1260 return o;
1261 }
1262
1263 Procedure::Procedure(FunctionResult &&fr, DummyArguments &&args, Attrs a)
1264 : functionResult{std::move(fr)}, dummyArguments{std::move(args)}, attrs{a} {
1265 }
1266 Procedure::Procedure(DummyArguments &&args, Attrs a)
1267 : dummyArguments{std::move(args)}, attrs{a} {}
1268 Procedure::~Procedure() {}
1269
1270 bool Procedure::operator==(const Procedure &that) const {
1271 return attrs == that.attrs && functionResult == that.functionResult &&
1272 dummyArguments == that.dummyArguments &&
1273 cudaSubprogramAttrs == that.cudaSubprogramAttrs;
1274 }
1275
1276 bool Procedure::IsCompatibleWith(const Procedure &actual,
1277 bool ignoreImplicitVsExplicit, std::string *whyNot,
1278 const SpecificIntrinsic *specificIntrinsic,
1279 std::optional<std::string> *warning) const {
1280 // 15.5.2.9(1): if dummy is not pure, actual need not be.
1281 // Ditto with elemental.
1282 Attrs actualAttrs{actual.attrs};
1283 if (!attrs.test(Attr::Pure)) {
1284 actualAttrs.reset(Attr::Pure);
1285 }
1286 if (!attrs.test(Attr::Elemental) && specificIntrinsic) {
1287 actualAttrs.reset(Attr::Elemental);
1288 }
1289 Attrs differences{attrs ^ actualAttrs};
1290 differences.reset(Attr::Subroutine); // dealt with specifically later
1291 if (ignoreImplicitVsExplicit) {
1292 differences.reset(Attr::ImplicitInterface);
1293 }
1294 if (!differences.empty()) {
1295 if (whyNot) {
1296 auto sep{": "s};
1297 *whyNot = "incompatible procedure attributes";
1298 differences.IterateOverMembers([&](Attr x) {
1299 *whyNot += sep + std::string{EnumToString(x)};
1300 sep = ", ";
1301 });
1302 }
1303 } else if ((IsFunction() && actual.IsSubroutine()) ||
1304 (IsSubroutine() && actual.IsFunction())) {
1305 if (whyNot) {
1306 *whyNot =
1307 "incompatible procedures: one is a function, the other a subroutine";
1308 }
1309 } else if (functionResult && actual.functionResult &&
1310 !functionResult->IsCompatibleWith(*actual.functionResult, whyNot)) {
1311 } else if (cudaSubprogramAttrs != actual.cudaSubprogramAttrs) {
1312 if (whyNot) {
1313 *whyNot = "incompatible CUDA subprogram attributes";
1314 }
1315 } else if (dummyArguments.size() != actual.dummyArguments.size()) {
1316 if (whyNot) {
1317 *whyNot = "distinct numbers of dummy arguments";
1318 }
1319 } else {
1320 for (std::size_t j{0}; j < dummyArguments.size(); ++j) {
1321 // Subtlety: the dummy/actual distinction must be reversed for this
1322 // compatibility test in order to correctly check extended vs.
1323 // base types. Example:
1324 // subroutine s1(base); subroutine s2(extended)
1325 // procedure(s1), pointer :: p
1326 // p => s2 ! an error, s2 is more restricted, can't handle "base"
1327 std::optional<std::string> gotWarning;
1328 if (!actual.dummyArguments[j].IsCompatibleWith(
1329 dummyArguments[j], whyNot, warning ? &gotWarning : nullptr)) {
1330 if (whyNot) {
1331 *whyNot = "incompatible dummy argument #"s + std::to_string(j + 1) +
1332 ": "s + *whyNot;
1333 }
1334 return false;
1335 } else if (warning && !*warning && gotWarning) {
1336 *warning = "possibly incompatible dummy argument #"s +
1337 std::to_string(j + 1) + ": "s + std::move(*gotWarning);
1338 }
1339 }
1340 return true;
1341 }
1342 return false;
1343 }
1344
1345 std::optional<int> Procedure::FindPassIndex(
1346 std::optional<parser::CharBlock> name) const {
1347 int argCount{static_cast<int>(dummyArguments.size())};
1348 if (name) {
1349 for (int index{0}; index < argCount; ++index) {
1350 if (*name == dummyArguments[index].name.c_str()) {
1351 return index;
1352 }
1353 }
1354 return std::nullopt;
1355 } else if (argCount > 0) {
1356 return 0;
1357 } else {
1358 return std::nullopt;
1359 }
1360 }
1361
1362 bool Procedure::CanOverride(
1363 const Procedure &that, std::optional<int> passIndex) const {
1364 // A pure procedure may override an impure one (7.5.7.3(2))
1365 if ((that.attrs.test(Attr::Pure) && !attrs.test(Attr::Pure)) ||
1366 that.attrs.test(Attr::Elemental) != attrs.test(Attr::Elemental) ||
1367 functionResult != that.functionResult) {
1368 return false;
1369 }
1370 int argCount{static_cast<int>(dummyArguments.size())};
1371 if (argCount != static_cast<int>(that.dummyArguments.size())) {
1372 return false;
1373 }
1374 for (int j{0}; j < argCount; ++j) {
1375 if (passIndex && j == *passIndex) {
1376 if (!that.dummyArguments[j].IsCompatibleWith(dummyArguments[j])) {
1377 return false;
1378 }
1379 } else if (dummyArguments[j] != that.dummyArguments[j]) {
1380 return false;
1381 }
1382 }
1383 return true;
1384 }
1385
1386 std::optional<Procedure> Procedure::Characterize(
1387 const semantics::Symbol &symbol, FoldingContext &context) {
1388 semantics::UnorderedSymbolSet seenProcs;
1389 return CharacterizeProcedure(symbol, context, seenProcs, /*emitError=*/true);
1390 }
1391
1392 std::optional<Procedure> Procedure::Characterize(
1393 const ProcedureDesignator &proc, FoldingContext &context, bool emitError) {
1394 if (const auto *symbol{proc.GetSymbol()}) {
1395 semantics::UnorderedSymbolSet seenProcs;
1396 return CharacterizeProcedure(*symbol, context, seenProcs, emitError);
1397 } else if (const auto *intrinsic{proc.GetSpecificIntrinsic()}) {
1398 return intrinsic->characteristics.value();
1399 } else {
1400 return std::nullopt;
1401 }
1402 }
1403
1404 std::optional<Procedure> Procedure::Characterize(
1405 const ProcedureRef &ref, FoldingContext &context) {
1406 if (auto callee{Characterize(ref.proc(), context, /*emitError=*/true)}) {
1407 if (callee->functionResult) {
1408 if (const Procedure *
1409 proc{callee->functionResult->IsProcedurePointer()}) {
1410 return {*proc};
1411 }
1412 }
1413 }
1414 return std::nullopt;
1415 }
1416
1417 std::optional<Procedure> Procedure::Characterize(
1418 const Expr<SomeType> &expr, FoldingContext &context) {
1419 if (const auto *procRef{UnwrapProcedureRef(expr)}) {
1420 return Characterize(*procRef, context);
1421 } else if (const auto *procDesignator{
1422 std::get_if<ProcedureDesignator>(&expr.u)}) {
1423 return Characterize(*procDesignator, context, /*emitError=*/true);
1424 } else if (const Symbol * symbol{UnwrapWholeSymbolOrComponentDataRef(expr)}) {
1425 return Characterize(*symbol, context);
1426 } else {
1427 context.messages().Say(
1428 "Expression '%s' is not a procedure"_err_en_US, expr.AsFortran());
1429 return std::nullopt;
1430 }
1431 }
1432
1433 std::optional<Procedure> Procedure::FromActuals(const ProcedureDesignator &proc,
1434 const ActualArguments &args, FoldingContext &context) {
1435 auto callee{Characterize(proc, context, /*emitError=*/true)};
1436 if (callee) {
1437 if (callee->dummyArguments.empty() &&
1438 callee->attrs.test(Procedure::Attr::ImplicitInterface)) {
1439 int j{0};
1440 for (const auto &arg : args) {
1441 ++j;
1442 if (arg) {
1443 if (auto dummy{DummyArgument::FromActual("x"s + std::to_string(j),
1444 *arg, context,
1445 /*forImplicitInterface=*/true)}) {
1446 callee->dummyArguments.emplace_back(std::move(*dummy));
1447 continue;
1448 }
1449 }
1450 callee.reset();
1451 break;
1452 }
1453 }
1454 }
1455 return callee;
1456 }
1457
1458 bool Procedure::CanBeCalledViaImplicitInterface(std::string *whyNot) const {
1459 if (attrs.test(Attr::Elemental)) {
1460 if (whyNot) {
1461 *whyNot = "the procedure is elemental";
1462 }
1463 return false; // 15.4.2.2(5,6)
1464 } else if (attrs.test(Attr::BindC)) {
1465 if (whyNot) {
1466 *whyNot = "the procedure is BIND(C)";
1467 }
1468 return false; // 15.4.2.2(5,6)
1469 } else if (cudaSubprogramAttrs &&
1470 *cudaSubprogramAttrs != common::CUDASubprogramAttrs::Host &&
1471 *cudaSubprogramAttrs != common::CUDASubprogramAttrs::Global) {
1472 if (whyNot) {
1473 *whyNot = "the procedure is CUDA but neither HOST nor GLOBAL";
1474 }
1475 return false;
1476 } else if (IsFunction() &&
1477 !functionResult->CanBeReturnedViaImplicitInterface(whyNot)) {
1478 return false;
1479 } else {
1480 for (const DummyArgument &arg : dummyArguments) {
1481 if (!arg.CanBePassedViaImplicitInterface(whyNot)) {
1482 return false;
1483 }
1484 }
1485 return true;
1486 }
1487 }
1488
1489 llvm::raw_ostream &Procedure::Dump(llvm::raw_ostream &o) const {
1490 attrs.Dump(o, EnumToString);
1491 if (functionResult) {
1492 functionResult->Dump(o << "TYPE(") << ") FUNCTION";
1493 } else if (attrs.test(Attr::Subroutine)) {
1494 o << "SUBROUTINE";
1495 } else {
1496 o << "EXTERNAL";
1497 }
1498 char sep{'('};
1499 for (const auto &dummy : dummyArguments) {
1500 dummy.Dump(o << sep);
1501 sep = ',';
1502 }
1503 o << (sep == '(' ? "()" : ")");
1504 if (cudaSubprogramAttrs) {
1505 o << " cudaSubprogramAttrs: " << common::EnumToString(*cudaSubprogramAttrs);
1506 }
1507 return o;
1508 }
1509
1510 // Utility class to determine if Procedures, etc. are distinguishable
1511 class DistinguishUtils {
1512 public:
1513 explicit DistinguishUtils(const common::LanguageFeatureControl &features)
1514 : features_{features} {}
1515
1516 // Are these procedures distinguishable for a generic name?
1517 std::optional<bool> Distinguishable(
1518 const Procedure &, const Procedure &) const;
1519 // Are these procedures distinguishable for a generic operator or assignment?
1520 std::optional<bool> DistinguishableOpOrAssign(
1521 const Procedure &, const Procedure &) const;
1522
1523 private:
1524 struct CountDummyProcedures {
1525 CountDummyProcedures(const DummyArguments &args) {
1526 for (const DummyArgument &arg : args) {
1527 if (std::holds_alternative<DummyProcedure>(arg.u)) {
1528 total += 1;
1529 notOptional += !arg.IsOptional();
1530 }
1531 }
1532 }
1533 int total{0};
1534 int notOptional{0};
1535 };
1536
1537 bool AnyOptionalData(const DummyArguments &) const;
1538 bool AnyUnlimitedPolymorphicData(const DummyArguments &) const;
1539 bool Rule3Distinguishable(const Procedure &, const Procedure &) const;
1540 const DummyArgument *Rule1DistinguishingArg(
1541 const DummyArguments &, const DummyArguments &) const;
1542 int FindFirstToDistinguishByPosition(
1543 const DummyArguments &, const DummyArguments &) const;
1544 int FindLastToDistinguishByName(
1545 const DummyArguments &, const DummyArguments &) const;
1546 int CountCompatibleWith(const DummyArgument &, const DummyArguments &) const;
1547 int CountNotDistinguishableFrom(
1548 const DummyArgument &, const DummyArguments &) const;
1549 bool Distinguishable(const DummyArgument &, const DummyArgument &) const;
1550 bool Distinguishable(const DummyDataObject &, const DummyDataObject &) const;
1551 bool Distinguishable(const DummyProcedure &, const DummyProcedure &) const;
1552 bool Distinguishable(const FunctionResult &, const FunctionResult &) const;
1553 bool Distinguishable(
1554 const TypeAndShape &, const TypeAndShape &, common::IgnoreTKRSet) const;
1555 bool IsTkrCompatible(const DummyArgument &, const DummyArgument &) const;
1556 bool IsTkCompatible(const DummyDataObject &, const DummyDataObject &) const;
1557 const DummyArgument *GetAtEffectivePosition(
1558 const DummyArguments &, int) const;
1559 const DummyArgument *GetPassArg(const Procedure &) const;
1560
1561 const common::LanguageFeatureControl &features_;
1562 };
1563
1564 // Simpler distinguishability rules for operators and assignment
1565 std::optional<bool> DistinguishUtils::DistinguishableOpOrAssign(
1566 const Procedure &proc1, const Procedure &proc2) const {
1567 if ((proc1.IsFunction() && proc2.IsSubroutine()) ||
1568 (proc1.IsSubroutine() && proc2.IsFunction())) {
1569 return true;
1570 }
1571 auto &args1{proc1.dummyArguments};
1572 auto &args2{proc2.dummyArguments};
1573 if (args1.size() != args2.size()) {
1574 return true; // C1511: distinguishable based on number of arguments
1575 }
1576 for (std::size_t i{0}; i < args1.size(); ++i) {
1577 if (Distinguishable(args1[i], args2[i])) {
1578 return true; // C1511, C1512: distinguishable based on this arg
1579 }
1580 }
1581 return false;
1582 }
1583
1584 std::optional<bool> DistinguishUtils::Distinguishable(
1585 const Procedure &proc1, const Procedure &proc2) const {
1586 if ((proc1.IsFunction() && proc2.IsSubroutine()) ||
1587 (proc1.IsSubroutine() && proc2.IsFunction())) {
1588 return true;
1589 }
1590 auto &args1{proc1.dummyArguments};
1591 auto &args2{proc2.dummyArguments};
1592 auto count1{CountDummyProcedures(args1)};
1593 auto count2{CountDummyProcedures(args2)};
1594 if (count1.notOptional > count2.total || count2.notOptional > count1.total) {
1595 return true; // distinguishable based on C1514 rule 2
1596 }
1597 if (Rule3Distinguishable(proc1, proc2)) {
1598 return true; // distinguishable based on C1514 rule 3
1599 }
1600 if (Rule1DistinguishingArg(args1, args2)) {
1601 return true; // distinguishable based on C1514 rule 1
1602 }
1603 int pos1{FindFirstToDistinguishByPosition(args1, args2)};
1604 int name1{FindLastToDistinguishByName(args1, args2)};
1605 if (pos1 >= 0 && pos1 <= name1) {
1606 return true; // distinguishable based on C1514 rule 4
1607 }
1608 int pos2{FindFirstToDistinguishByPosition(args2, args1)};
1609 int name2{FindLastToDistinguishByName(args2, args1)};
1610 if (pos2 >= 0 && pos2 <= name2) {
1611 return true; // distinguishable based on C1514 rule 4
1612 }
1613 if (proc1.cudaSubprogramAttrs != proc2.cudaSubprogramAttrs) {
1614 return true;
1615 }
1616 // If there are no optional or unlimited polymorphic dummy arguments,
1617 // then we know the result for sure; otherwise, it's possible for
1618 // the procedures to be unambiguous.
1619 if ((AnyOptionalData(args1) || AnyUnlimitedPolymorphicData(args1)) &&
1620 (AnyOptionalData(args2) || AnyUnlimitedPolymorphicData(args2))) {
1621 return std::nullopt; // meaning "maybe"
1622 } else {
1623 return false;
1624 }
1625 }
1626
1627 bool DistinguishUtils::AnyOptionalData(const DummyArguments &args) const {
1628 for (const auto &arg : args) {
1629 if (std::holds_alternative<DummyDataObject>(arg.u) && arg.IsOptional()) {
1630 return true;
1631 }
1632 }
1633 return false;
1634 }
1635
1636 bool DistinguishUtils::AnyUnlimitedPolymorphicData(
1637 const DummyArguments &args) const {
1638 for (const auto &arg : args) {
1639 if (const auto *object{std::get_if<DummyDataObject>(&arg.u)}) {
1640 if (object->type.type().IsUnlimitedPolymorphic()) {
1641 return true;
1642 }
1643 }
1644 }
1645 return false;
1646 }
1647
1648 // C1514 rule 3: Procedures are distinguishable if both have a passed-object
1649 // dummy argument and those are distinguishable.
1650 bool DistinguishUtils::Rule3Distinguishable(
1651 const Procedure &proc1, const Procedure &proc2) const {
1652 const DummyArgument *pass1{GetPassArg(proc1)};
1653 const DummyArgument *pass2{GetPassArg(proc2)};
1654 return pass1 && pass2 && Distinguishable(*pass1, *pass2);
1655 }
1656
1657 // Find a non-passed-object dummy data object in one of the argument lists
1658 // that satisfies C1514 rule 1. I.e. x such that:
1659 // - m is the number of dummy data objects in one that are nonoptional,
1660 // are not passed-object, that x is TKR compatible with
1661 // - n is the number of non-passed-object dummy data objects, in the other
1662 // that are not distinguishable from x
1663 // - m is greater than n
1664 const DummyArgument *DistinguishUtils::Rule1DistinguishingArg(
1665 const DummyArguments &args1, const DummyArguments &args2) const {
1666 auto size1{args1.size()};
1667 auto size2{args2.size()};
1668 for (std::size_t i{0}; i < size1 + size2; ++i) {
1669 const DummyArgument &x{i < size1 ? args1[i] : args2[i - size1]};
1670 if (!x.pass && std::holds_alternative<DummyDataObject>(x.u)) {
1671 if (CountCompatibleWith(x, args1) >
1672 CountNotDistinguishableFrom(x, args2) ||
1673 CountCompatibleWith(x, args2) >
1674 CountNotDistinguishableFrom(x, args1)) {
1675 return &x;
1676 }
1677 }
1678 }
1679 return nullptr;
1680 }
1681
1682 // Find the index of the first nonoptional non-passed-object dummy argument
1683 // in args1 at an effective position such that either:
1684 // - args2 has no dummy argument at that effective position
1685 // - the dummy argument at that position is distinguishable from it
1686 int DistinguishUtils::FindFirstToDistinguishByPosition(
1687 const DummyArguments &args1, const DummyArguments &args2) const {
1688 int effective{0}; // position of arg1 in list, ignoring passed arg
1689 for (std::size_t i{0}; i < args1.size(); ++i) {
1690 const DummyArgument &arg1{args1.at(i)};
1691 if (!arg1.pass && !arg1.IsOptional()) {
1692 const DummyArgument *arg2{GetAtEffectivePosition(args2, effective)};
1693 if (!arg2 || Distinguishable(arg1, *arg2)) {
1694 return i;
1695 }
1696 }
1697 effective += !arg1.pass;
1698 }
1699 return -1;
1700 }
1701
1702 // Find the index of the last nonoptional non-passed-object dummy argument
1703 // in args1 whose name is such that either:
1704 // - args2 has no dummy argument with that name
1705 // - the dummy argument with that name is distinguishable from it
1706 int DistinguishUtils::FindLastToDistinguishByName(
1707 const DummyArguments &args1, const DummyArguments &args2) const {
1708 std::map<std::string, const DummyArgument *> nameToArg;
1709 for (const auto &arg2 : args2) {
1710 nameToArg.emplace(arg2.name, &arg2);
1711 }
1712 for (int i = args1.size() - 1; i >= 0; --i) {
1713 const DummyArgument &arg1{args1.at(i)};
1714 if (!arg1.pass && !arg1.IsOptional()) {
1715 auto it{nameToArg.find(arg1.name)};
1716 if (it == nameToArg.end() || Distinguishable(arg1, *it->second)) {
1717 return i;
1718 }
1719 }
1720 }
1721 return -1;
1722 }
1723
1724 // Count the dummy data objects in args that are nonoptional, are not
1725 // passed-object, and that x is TKR compatible with
1726 int DistinguishUtils::CountCompatibleWith(
1727 const DummyArgument &x, const DummyArguments &args) const {
1728 return llvm::count_if(args, [&](const DummyArgument &y) {
1729 return !y.pass && !y.IsOptional() && IsTkrCompatible(x, y);
1730 });
1731 }
1732
1733 // Return the number of dummy data objects in args that are not
1734 // distinguishable from x and not passed-object.
1735 int DistinguishUtils::CountNotDistinguishableFrom(
1736 const DummyArgument &x, const DummyArguments &args) const {
1737 return llvm::count_if(args, [&](const DummyArgument &y) {
1738 return !y.pass && std::holds_alternative<DummyDataObject>(y.u) &&
1739 !Distinguishable(y, x);
1740 });
1741 }
1742
1743 bool DistinguishUtils::Distinguishable(
1744 const DummyArgument &x, const DummyArgument &y) const {
1745 if (x.u.index() != y.u.index()) {
1746 return true; // different kind: data/proc/alt-return
1747 }
1748 return common::visit(
1749 common::visitors{
1750 [&](const DummyDataObject &z) {
1751 return Distinguishable(z, std::get<DummyDataObject>(y.u));
1752 },
1753 [&](const DummyProcedure &z) {
1754 return Distinguishable(z, std::get<DummyProcedure>(y.u));
1755 },
1756 [&](const AlternateReturn &) { return false; },
1757 },
1758 x.u);
1759 }
1760
1761 bool DistinguishUtils::Distinguishable(
1762 const DummyDataObject &x, const DummyDataObject &y) const {
1763 using Attr = DummyDataObject::Attr;
1764 if (Distinguishable(x.type, y.type, x.ignoreTKR | y.ignoreTKR)) {
1765 return true;
1766 } else if (x.attrs.test(Attr::Allocatable) && y.attrs.test(Attr::Pointer) &&
1767 y.intent != common::Intent::In) {
1768 return true;
1769 } else if (y.attrs.test(Attr::Allocatable) && x.attrs.test(Attr::Pointer) &&
1770 x.intent != common::Intent::In) {
1771 return true;
1772 } else if (!common::AreCompatibleCUDADataAttrs(x.cudaDataAttr, y.cudaDataAttr,
1773 x.ignoreTKR | y.ignoreTKR,
1774 /*allowUnifiedMatchingRule=*/false)) {
1775 return true;
1776 } else if (features_.IsEnabled(
1777 common::LanguageFeature::DistinguishableSpecifics) &&
1778 (x.attrs.test(Attr::Allocatable) || x.attrs.test(Attr::Pointer)) &&
1779 (y.attrs.test(Attr::Allocatable) || y.attrs.test(Attr::Pointer)) &&
1780 (x.type.type().IsUnlimitedPolymorphic() !=
1781 y.type.type().IsUnlimitedPolymorphic() ||
1782 x.type.type().IsPolymorphic() != y.type.type().IsPolymorphic())) {
1783 // Extension: Per 15.5.2.5(2), an allocatable/pointer dummy and its
1784 // corresponding actual argument must both or neither be polymorphic,
1785 // and must both or neither be unlimited polymorphic. So when exactly
1786 // one of two dummy arguments is polymorphic or unlimited polymorphic,
1787 // any actual argument that is admissible to one of them cannot also match
1788 // the other one.
1789 return true;
1790 } else {
1791 return false;
1792 }
1793 }
1794
1795 bool DistinguishUtils::Distinguishable(
1796 const DummyProcedure &x, const DummyProcedure &y) const {
1797 const Procedure &xProc{x.procedure.value()};
1798 const Procedure &yProc{y.procedure.value()};
1799 if (Distinguishable(xProc, yProc).value_or(false)) {
1800 return true;
1801 } else {
1802 const std::optional<FunctionResult> &xResult{xProc.functionResult};
1803 const std::optional<FunctionResult> &yResult{yProc.functionResult};
1804 return xResult ? !yResult || Distinguishable(*xResult, *yResult)
1805 : yResult.has_value();
1806 }
1807 }
1808
1809 bool DistinguishUtils::Distinguishable(
1810 const FunctionResult &x, const FunctionResult &y) const {
1811 if (x.u.index() != y.u.index()) {
1812 return true; // one is data object, one is procedure
1813 }
1814 if (x.cudaDataAttr != y.cudaDataAttr) {
1815 return true;
1816 }
1817 return common::visit(
1818 common::visitors{
1819 [&](const TypeAndShape &z) {
1820 return Distinguishable(
1821 z, std::get<TypeAndShape>(y.u), common::IgnoreTKRSet{});
1822 },
1823 [&](const CopyableIndirection<Procedure> &z) {
1824 return Distinguishable(z.value(),
1825 std::get<CopyableIndirection<Procedure>>(y.u).value())
1826 .value_or(false);
1827 },
1828 },
1829 x.u);
1830 }
1831
1832 bool DistinguishUtils::Distinguishable(const TypeAndShape &x,
1833 const TypeAndShape &y, common::IgnoreTKRSet ignoreTKR) const {
1834 if (!x.type().IsTkCompatibleWith(y.type(), ignoreTKR) &&
1835 !y.type().IsTkCompatibleWith(x.type(), ignoreTKR)) {
1836 return true;
1837 }
1838 if (ignoreTKR.test(common::IgnoreTKR::Rank)) {
1839 } else if (x.attrs().test(TypeAndShape::Attr::AssumedRank) ||
1840 y.attrs().test(TypeAndShape::Attr::AssumedRank)) {
1841 } else if (x.Rank() != y.Rank()) {
1842 return true;
1843 }
1844 return false;
1845 }
1846
1847 // Compatibility based on type, kind, and rank
1848
1849 bool DistinguishUtils::IsTkrCompatible(
1850 const DummyArgument &x, const DummyArgument &y) const {
1851 const auto *obj1{std::get_if<DummyDataObject>(&x.u)};
1852 const auto *obj2{std::get_if<DummyDataObject>(&y.u)};
1853 return obj1 && obj2 && IsTkCompatible(*obj1, *obj2) &&
1854 (obj1->type.Rank() == obj2->type.Rank() ||
1855 obj1->type.attrs().test(TypeAndShape::Attr::AssumedRank) ||
1856 obj2->type.attrs().test(TypeAndShape::Attr::AssumedRank) ||
1857 obj1->ignoreTKR.test(common::IgnoreTKR::Rank) ||
1858 obj2->ignoreTKR.test(common::IgnoreTKR::Rank));
1859 }
1860
1861 bool DistinguishUtils::IsTkCompatible(
1862 const DummyDataObject &x, const DummyDataObject &y) const {
1863 return x.type.type().IsTkCompatibleWith(
1864 y.type.type(), x.ignoreTKR | y.ignoreTKR);
1865 }
1866
1867 // Return the argument at the given index, ignoring the passed arg
1868 const DummyArgument *DistinguishUtils::GetAtEffectivePosition(
1869 const DummyArguments &args, int index) const {
1870 for (const DummyArgument &arg : args) {
1871 if (!arg.pass) {
1872 if (index == 0) {
1873 return &arg;
1874 }
1875 --index;
1876 }
1877 }
1878 return nullptr;
1879 }
1880
1881 // Return the passed-object dummy argument of this procedure, if any
1882 const DummyArgument *DistinguishUtils::GetPassArg(const Procedure &proc) const {
1883 for (const auto &arg : proc.dummyArguments) {
1884 if (arg.pass) {
1885 return &arg;
1886 }
1887 }
1888 return nullptr;
1889 }
1890
1891 std::optional<bool> Distinguishable(
1892 const common::LanguageFeatureControl &features, const Procedure &x,
1893 const Procedure &y) {
1894 return DistinguishUtils{features}.Distinguishable(x, y);
1895 }
1896
1897 std::optional<bool> DistinguishableOpOrAssign(
1898 const common::LanguageFeatureControl &features, const Procedure &x,
1899 const Procedure &y) {
1900 return DistinguishUtils{features}.DistinguishableOpOrAssign(x, y);
1901 }
1902
1903 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(DummyArgument)
1904 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(DummyProcedure)
1905 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(FunctionResult)
1906 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(Procedure)
1907 } // namespace Fortran::evaluate::characteristics
1908
1909 template class Fortran::common::Indirection<
1910 Fortran::evaluate::characteristics::Procedure, true>;