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 "llvm/Support/raw_ostream.h"
20 #include <initializer_list>
21 
22 using namespace Fortran::parser::literals;
23 
24 namespace Fortran::evaluate::characteristics {
25 
26 // Copy attributes from a symbol to dst based on the mapping in pairs.
27 template <typename A, typename B>
28 static void CopyAttrs(const semantics::Symbol &src, A &dst,
29     const std::initializer_list<std::pair<semantics::Attr, B>> &pairs) {
30   for (const auto &pair : pairs) {
31     if (src.attrs().test(pair.first)) {
32       dst.attrs.set(pair.second);
33     }
34   }
35 }
36 
37 // Shapes of function results and dummy arguments have to have
38 // the same rank, the same deferred dimensions, and the same
39 // values for explicit dimensions when constant.
40 bool ShapesAreCompatible(const Shape &x, const Shape &y) {
41   if (x.size() != y.size()) {
42     return false;
43   }
44   auto yIter{y.begin()};
45   for (const auto &xDim : x) {
46     const auto &yDim{*yIter++};
47     if (xDim) {
48       if (!yDim || ToInt64(*xDim) != ToInt64(*yDim)) {
49         return false;
50       }
51     } else if (yDim) {
52       return false;
53     }
54   }
55   return true;
56 }
57 
58 bool TypeAndShape::operator==(const TypeAndShape &that) const {
59   return type_ == that.type_ && ShapesAreCompatible(shape_, that.shape_) &&
60       attrs_ == that.attrs_ && corank_ == that.corank_;
61 }
62 
63 TypeAndShape &TypeAndShape::Rewrite(FoldingContext &context) {
64   LEN_ = Fold(context, std::move(LEN_));
65   shape_ = Fold(context, std::move(shape_));
66   return *this;
67 }
68 
69 std::optional<TypeAndShape> TypeAndShape::Characterize(
70     const semantics::Symbol &symbol, FoldingContext &context) {
71   const auto &ultimate{symbol.GetUltimate()};
72   return common::visit(
73       common::visitors{
74           [&](const semantics::ProcEntityDetails &proc) {
75             const semantics::ProcInterface &interface { proc.interface() };
76             if (interface.type()) {
77               return Characterize(*interface.type(), context);
78             } else if (interface.symbol()) {
79               return Characterize(*interface.symbol(), context);
80             } else {
81               return std::optional<TypeAndShape>{};
82             }
83           },
84           [&](const semantics::AssocEntityDetails &assoc) {
85             return Characterize(assoc, context);
86           },
87           [&](const semantics::ProcBindingDetails &binding) {
88             return Characterize(binding.symbol(), context);
89           },
90           [&](const auto &x) -> std::optional<TypeAndShape> {
91             using Ty = std::decay_t<decltype(x)>;
92             if constexpr (std::is_same_v<Ty, semantics::EntityDetails> ||
93                 std::is_same_v<Ty, semantics::ObjectEntityDetails> ||
94                 std::is_same_v<Ty, semantics::TypeParamDetails>) {
95               if (const semantics::DeclTypeSpec * type{ultimate.GetType()}) {
96                 if (auto dyType{DynamicType::From(*type)}) {
97                   TypeAndShape result{
98                       std::move(*dyType), GetShape(context, ultimate)};
99                   result.AcquireAttrs(ultimate);
100                   result.AcquireLEN(ultimate);
101                   return std::move(result.Rewrite(context));
102                 }
103               }
104             }
105             return std::nullopt;
106           },
107       },
108       // GetUltimate() used here, not ResolveAssociations(), because
109       // we need the type/rank of an associate entity from TYPE IS,
110       // CLASS IS, or RANK statement.
111       ultimate.details());
112 }
113 
114 std::optional<TypeAndShape> TypeAndShape::Characterize(
115     const semantics::AssocEntityDetails &assoc, FoldingContext &context) {
116   std::optional<TypeAndShape> result;
117   if (auto type{DynamicType::From(assoc.type())}) {
118     if (auto rank{assoc.rank()}) {
119       if (*rank >= 0 && *rank <= common::maxRank) {
120         result = TypeAndShape{std::move(*type), Shape(*rank)};
121       }
122     } else if (auto shape{GetShape(context, assoc.expr())}) {
123       result = TypeAndShape{std::move(*type), std::move(*shape)};
124     }
125     if (result && type->category() == TypeCategory::Character) {
126       if (const auto *chExpr{UnwrapExpr<Expr<SomeCharacter>>(assoc.expr())}) {
127         if (auto len{chExpr->LEN()}) {
128           result->set_LEN(std::move(*len));
129         }
130       }
131     }
132   }
133   return Fold(context, std::move(result));
134 }
135 
136 std::optional<TypeAndShape> TypeAndShape::Characterize(
137     const semantics::DeclTypeSpec &spec, FoldingContext &context) {
138   if (auto type{DynamicType::From(spec)}) {
139     return Fold(context, TypeAndShape{std::move(*type)});
140   } else {
141     return std::nullopt;
142   }
143 }
144 
145 std::optional<TypeAndShape> TypeAndShape::Characterize(
146     const ActualArgument &arg, FoldingContext &context) {
147   return Characterize(arg.UnwrapExpr(), context);
148 }
149 
150 bool TypeAndShape::IsCompatibleWith(parser::ContextualMessages &messages,
151     const TypeAndShape &that, const char *thisIs, const char *thatIs,
152     bool omitShapeConformanceCheck,
153     enum CheckConformanceFlags::Flags flags) const {
154   if (!type_.IsTkCompatibleWith(that.type_)) {
155     messages.Say(
156         "%1$s type '%2$s' is not compatible with %3$s type '%4$s'"_err_en_US,
157         thatIs, that.AsFortran(), thisIs, AsFortran());
158     return false;
159   }
160   return omitShapeConformanceCheck ||
161       CheckConformance(messages, shape_, that.shape_, flags, thisIs, thatIs)
162           .value_or(true /*fail only when nonconformance is known now*/);
163 }
164 
165 std::optional<Expr<SubscriptInteger>> TypeAndShape::MeasureElementSizeInBytes(
166     FoldingContext &foldingContext, bool align) const {
167   if (LEN_) {
168     CHECK(type_.category() == TypeCategory::Character);
169     return Fold(foldingContext,
170         Expr<SubscriptInteger>{type_.kind()} * Expr<SubscriptInteger>{*LEN_});
171   }
172   if (auto elementBytes{type_.MeasureSizeInBytes(foldingContext, align)}) {
173     return Fold(foldingContext, std::move(*elementBytes));
174   }
175   return std::nullopt;
176 }
177 
178 std::optional<Expr<SubscriptInteger>> TypeAndShape::MeasureSizeInBytes(
179     FoldingContext &foldingContext) const {
180   if (auto elements{GetSize(Shape{shape_})}) {
181     // Sizes of arrays (even with single elements) are multiples of
182     // their alignments.
183     if (auto elementBytes{
184             MeasureElementSizeInBytes(foldingContext, GetRank(shape_) > 0)}) {
185       return Fold(
186           foldingContext, std::move(*elements) * std::move(*elementBytes));
187     }
188   }
189   return std::nullopt;
190 }
191 
192 void TypeAndShape::AcquireAttrs(const semantics::Symbol &symbol) {
193   if (IsAssumedShape(symbol)) {
194     attrs_.set(Attr::AssumedShape);
195   }
196   if (IsDeferredShape(symbol)) {
197     attrs_.set(Attr::DeferredShape);
198   }
199   if (const auto *object{
200           symbol.GetUltimate().detailsIf<semantics::ObjectEntityDetails>()}) {
201     corank_ = object->coshape().Rank();
202     if (object->IsAssumedRank()) {
203       attrs_.set(Attr::AssumedRank);
204     }
205     if (object->IsAssumedSize()) {
206       attrs_.set(Attr::AssumedSize);
207     }
208     if (object->IsCoarray()) {
209       attrs_.set(Attr::Coarray);
210     }
211   }
212 }
213 
214 void TypeAndShape::AcquireLEN() {
215   if (auto len{type_.GetCharLength()}) {
216     LEN_ = std::move(len);
217   }
218 }
219 
220 void TypeAndShape::AcquireLEN(const semantics::Symbol &symbol) {
221   if (type_.category() == TypeCategory::Character) {
222     if (auto len{DataRef{symbol}.LEN()}) {
223       LEN_ = std::move(*len);
224     }
225   }
226 }
227 
228 std::string TypeAndShape::AsFortran() const {
229   return type_.AsFortran(LEN_ ? LEN_->AsFortran() : "");
230 }
231 
232 llvm::raw_ostream &TypeAndShape::Dump(llvm::raw_ostream &o) const {
233   o << type_.AsFortran(LEN_ ? LEN_->AsFortran() : "");
234   attrs_.Dump(o, EnumToString);
235   if (!shape_.empty()) {
236     o << " dimension";
237     char sep{'('};
238     for (const auto &expr : shape_) {
239       o << sep;
240       sep = ',';
241       if (expr) {
242         expr->AsFortran(o);
243       } else {
244         o << ':';
245       }
246     }
247     o << ')';
248   }
249   return o;
250 }
251 
252 bool DummyDataObject::operator==(const DummyDataObject &that) const {
253   return type == that.type && attrs == that.attrs && intent == that.intent &&
254       coshape == that.coshape;
255 }
256 
257 bool DummyDataObject::IsCompatibleWith(const DummyDataObject &actual) const {
258   return type.shape() == actual.type.shape() &&
259       type.type().IsTkCompatibleWith(actual.type.type()) &&
260       attrs == actual.attrs && intent == actual.intent &&
261       coshape == actual.coshape;
262 }
263 
264 static common::Intent GetIntent(const semantics::Attrs &attrs) {
265   if (attrs.test(semantics::Attr::INTENT_IN)) {
266     return common::Intent::In;
267   } else if (attrs.test(semantics::Attr::INTENT_OUT)) {
268     return common::Intent::Out;
269   } else if (attrs.test(semantics::Attr::INTENT_INOUT)) {
270     return common::Intent::InOut;
271   } else {
272     return common::Intent::Default;
273   }
274 }
275 
276 std::optional<DummyDataObject> DummyDataObject::Characterize(
277     const semantics::Symbol &symbol, FoldingContext &context) {
278   if (symbol.has<semantics::ObjectEntityDetails>() ||
279       symbol.has<semantics::EntityDetails>()) {
280     if (auto type{TypeAndShape::Characterize(symbol, context)}) {
281       std::optional<DummyDataObject> result{std::move(*type)};
282       using semantics::Attr;
283       CopyAttrs<DummyDataObject, DummyDataObject::Attr>(symbol, *result,
284           {
285               {Attr::OPTIONAL, DummyDataObject::Attr::Optional},
286               {Attr::ALLOCATABLE, DummyDataObject::Attr::Allocatable},
287               {Attr::ASYNCHRONOUS, DummyDataObject::Attr::Asynchronous},
288               {Attr::CONTIGUOUS, DummyDataObject::Attr::Contiguous},
289               {Attr::VALUE, DummyDataObject::Attr::Value},
290               {Attr::VOLATILE, DummyDataObject::Attr::Volatile},
291               {Attr::POINTER, DummyDataObject::Attr::Pointer},
292               {Attr::TARGET, DummyDataObject::Attr::Target},
293           });
294       result->intent = GetIntent(symbol.attrs());
295       return result;
296     }
297   }
298   return std::nullopt;
299 }
300 
301 bool DummyDataObject::CanBePassedViaImplicitInterface() const {
302   if ((attrs &
303           Attrs{Attr::Allocatable, Attr::Asynchronous, Attr::Optional,
304               Attr::Pointer, Attr::Target, Attr::Value, Attr::Volatile})
305           .any()) {
306     return false; // 15.4.2.2(3)(a)
307   } else if ((type.attrs() &
308                  TypeAndShape::Attrs{TypeAndShape::Attr::AssumedShape,
309                      TypeAndShape::Attr::AssumedRank,
310                      TypeAndShape::Attr::Coarray})
311                  .any()) {
312     return false; // 15.4.2.2(3)(b-d)
313   } else if (type.type().IsPolymorphic()) {
314     return false; // 15.4.2.2(3)(f)
315   } else if (const auto *derived{GetDerivedTypeSpec(type.type())}) {
316     return derived->parameters().empty(); // 15.4.2.2(3)(e)
317   } else {
318     return true;
319   }
320 }
321 
322 llvm::raw_ostream &DummyDataObject::Dump(llvm::raw_ostream &o) const {
323   attrs.Dump(o, EnumToString);
324   if (intent != common::Intent::Default) {
325     o << "INTENT(" << common::EnumToString(intent) << ')';
326   }
327   type.Dump(o);
328   if (!coshape.empty()) {
329     char sep{'['};
330     for (const auto &expr : coshape) {
331       expr.AsFortran(o << sep);
332       sep = ',';
333     }
334   }
335   return o;
336 }
337 
338 DummyProcedure::DummyProcedure(Procedure &&p)
339     : procedure{new Procedure{std::move(p)}} {}
340 
341 bool DummyProcedure::operator==(const DummyProcedure &that) const {
342   return attrs == that.attrs && intent == that.intent &&
343       procedure.value() == that.procedure.value();
344 }
345 
346 bool DummyProcedure::IsCompatibleWith(const DummyProcedure &actual) const {
347   return attrs == actual.attrs && intent == actual.intent &&
348       procedure.value().IsCompatibleWith(actual.procedure.value());
349 }
350 
351 static std::string GetSeenProcs(
352     const semantics::UnorderedSymbolSet &seenProcs) {
353   // Sort the symbols so that they appear in the same order on all platforms
354   auto ordered{semantics::OrderBySourcePosition(seenProcs)};
355   std::string result;
356   llvm::interleave(
357       ordered,
358       [&](const SymbolRef p) { result += '\'' + p->name().ToString() + '\''; },
359       [&]() { result += ", "; });
360   return result;
361 }
362 
363 // These functions with arguments of type UnorderedSymbolSet are used with
364 // mutually recursive calls when characterizing a Procedure, a DummyArgument,
365 // or a DummyProcedure to detect circularly defined procedures as required by
366 // 15.4.3.6, paragraph 2.
367 static std::optional<DummyArgument> CharacterizeDummyArgument(
368     const semantics::Symbol &symbol, FoldingContext &context,
369     semantics::UnorderedSymbolSet seenProcs);
370 static std::optional<FunctionResult> CharacterizeFunctionResult(
371     const semantics::Symbol &symbol, FoldingContext &context,
372     semantics::UnorderedSymbolSet seenProcs);
373 
374 static std::optional<Procedure> CharacterizeProcedure(
375     const semantics::Symbol &original, FoldingContext &context,
376     semantics::UnorderedSymbolSet seenProcs) {
377   Procedure result;
378   const auto &symbol{ResolveAssociations(original)};
379   if (seenProcs.find(symbol) != seenProcs.end()) {
380     std::string procsList{GetSeenProcs(seenProcs)};
381     context.messages().Say(symbol.name(),
382         "Procedure '%s' is recursively defined.  Procedures in the cycle:"
383         " %s"_err_en_US,
384         symbol.name(), procsList);
385     return std::nullopt;
386   }
387   seenProcs.insert(symbol);
388   CopyAttrs<Procedure, Procedure::Attr>(symbol, result,
389       {
390           {semantics::Attr::ELEMENTAL, Procedure::Attr::Elemental},
391           {semantics::Attr::BIND_C, Procedure::Attr::BindC},
392       });
393   if (IsPureProcedure(symbol) || // works for ENTRY too
394       (!symbol.attrs().test(semantics::Attr::IMPURE) &&
395           result.attrs.test(Procedure::Attr::Elemental))) {
396     result.attrs.set(Procedure::Attr::Pure);
397   }
398   return common::visit(
399       common::visitors{
400           [&](const semantics::SubprogramDetails &subp)
401               -> std::optional<Procedure> {
402             if (subp.isFunction()) {
403               if (auto fr{CharacterizeFunctionResult(
404                       subp.result(), context, seenProcs)}) {
405                 result.functionResult = std::move(fr);
406               } else {
407                 return std::nullopt;
408               }
409             } else {
410               result.attrs.set(Procedure::Attr::Subroutine);
411             }
412             for (const semantics::Symbol *arg : subp.dummyArgs()) {
413               if (!arg) {
414                 if (subp.isFunction()) {
415                   return std::nullopt;
416                 } else {
417                   result.dummyArguments.emplace_back(AlternateReturn{});
418                 }
419               } else if (auto argCharacteristics{CharacterizeDummyArgument(
420                              *arg, context, seenProcs)}) {
421                 result.dummyArguments.emplace_back(
422                     std::move(argCharacteristics.value()));
423               } else {
424                 return std::nullopt;
425               }
426             }
427             return result;
428           },
429           [&](const semantics::ProcEntityDetails &proc)
430               -> std::optional<Procedure> {
431             if (symbol.attrs().test(semantics::Attr::INTRINSIC)) {
432               // Fails when the intrinsic is not a specific intrinsic function
433               // from F'2018 table 16.2.  In order to handle forward references,
434               // attempts to use impermissible intrinsic procedures as the
435               // interfaces of procedure pointers are caught and flagged in
436               // declaration checking in Semantics.
437               auto intrinsic{context.intrinsics().IsSpecificIntrinsicFunction(
438                   symbol.name().ToString())};
439               if (intrinsic && intrinsic->isRestrictedSpecific) {
440                 intrinsic.reset(); // Exclude intrinsics from table 16.3.
441               }
442               return intrinsic;
443             }
444             const semantics::ProcInterface &interface { proc.interface() };
445             if (const semantics::Symbol * interfaceSymbol{interface.symbol()}) {
446               return CharacterizeProcedure(
447                   *interfaceSymbol, context, seenProcs);
448             } else {
449               result.attrs.set(Procedure::Attr::ImplicitInterface);
450               const semantics::DeclTypeSpec *type{interface.type()};
451               if (symbol.test(semantics::Symbol::Flag::Subroutine)) {
452                 // ignore any implicit typing
453                 result.attrs.set(Procedure::Attr::Subroutine);
454               } else if (type) {
455                 if (auto resultType{DynamicType::From(*type)}) {
456                   result.functionResult = FunctionResult{*resultType};
457                 } else {
458                   return std::nullopt;
459                 }
460               } else if (symbol.test(semantics::Symbol::Flag::Function)) {
461                 return std::nullopt;
462               }
463               // The PASS name, if any, is not a characteristic.
464               return result;
465             }
466           },
467           [&](const semantics::ProcBindingDetails &binding) {
468             if (auto result{CharacterizeProcedure(
469                     binding.symbol(), context, seenProcs)}) {
470               if (!symbol.attrs().test(semantics::Attr::NOPASS)) {
471                 auto passName{binding.passName()};
472                 for (auto &dummy : result->dummyArguments) {
473                   if (!passName || dummy.name.c_str() == *passName) {
474                     dummy.pass = true;
475                     return result;
476                   }
477                 }
478                 DIE("PASS argument missing");
479               }
480               return result;
481             } else {
482               return std::optional<Procedure>{};
483             }
484           },
485           [&](const semantics::UseDetails &use) {
486             return CharacterizeProcedure(use.symbol(), context, seenProcs);
487           },
488           [&](const semantics::HostAssocDetails &assoc) {
489             return CharacterizeProcedure(assoc.symbol(), context, seenProcs);
490           },
491           [&](const semantics::EntityDetails &) {
492             context.messages().Say(
493                 "Procedure '%s' is referenced before being sufficiently defined in a context where it must be so"_err_en_US,
494                 symbol.name());
495             return std::optional<Procedure>{};
496           },
497           [&](const semantics::SubprogramNameDetails &) {
498             context.messages().Say(
499                 "Procedure '%s' is referenced before being sufficiently defined in a context where it must be so"_err_en_US,
500                 symbol.name());
501             return std::optional<Procedure>{};
502           },
503           [&](const auto &) {
504             context.messages().Say(
505                 "'%s' is not a procedure"_err_en_US, symbol.name());
506             return std::optional<Procedure>{};
507           },
508       },
509       symbol.details());
510 }
511 
512 static std::optional<DummyProcedure> CharacterizeDummyProcedure(
513     const semantics::Symbol &symbol, FoldingContext &context,
514     semantics::UnorderedSymbolSet seenProcs) {
515   if (auto procedure{CharacterizeProcedure(symbol, context, seenProcs)}) {
516     // Dummy procedures may not be elemental.  Elemental dummy procedure
517     // interfaces are errors when the interface is not intrinsic, and that
518     // error is caught elsewhere.  Elemental intrinsic interfaces are
519     // made non-elemental.
520     procedure->attrs.reset(Procedure::Attr::Elemental);
521     DummyProcedure result{std::move(procedure.value())};
522     CopyAttrs<DummyProcedure, DummyProcedure::Attr>(symbol, result,
523         {
524             {semantics::Attr::OPTIONAL, DummyProcedure::Attr::Optional},
525             {semantics::Attr::POINTER, DummyProcedure::Attr::Pointer},
526         });
527     result.intent = GetIntent(symbol.attrs());
528     return result;
529   } else {
530     return std::nullopt;
531   }
532 }
533 
534 llvm::raw_ostream &DummyProcedure::Dump(llvm::raw_ostream &o) const {
535   attrs.Dump(o, EnumToString);
536   if (intent != common::Intent::Default) {
537     o << "INTENT(" << common::EnumToString(intent) << ')';
538   }
539   procedure.value().Dump(o);
540   return o;
541 }
542 
543 llvm::raw_ostream &AlternateReturn::Dump(llvm::raw_ostream &o) const {
544   return o << '*';
545 }
546 
547 DummyArgument::~DummyArgument() {}
548 
549 bool DummyArgument::operator==(const DummyArgument &that) const {
550   return u == that.u; // name and passed-object usage are not characteristics
551 }
552 
553 bool DummyArgument::IsCompatibleWith(const DummyArgument &actual) const {
554   if (const auto *ifaceData{std::get_if<DummyDataObject>(&u)}) {
555     const auto *actualData{std::get_if<DummyDataObject>(&actual.u)};
556     return actualData && ifaceData->IsCompatibleWith(*actualData);
557   } else if (const auto *ifaceProc{std::get_if<DummyProcedure>(&u)}) {
558     const auto *actualProc{std::get_if<DummyProcedure>(&actual.u)};
559     return actualProc && ifaceProc->IsCompatibleWith(*actualProc);
560   } else {
561     return std::holds_alternative<AlternateReturn>(u) &&
562         std::holds_alternative<AlternateReturn>(actual.u);
563   }
564 }
565 
566 static std::optional<DummyArgument> CharacterizeDummyArgument(
567     const semantics::Symbol &symbol, FoldingContext &context,
568     semantics::UnorderedSymbolSet seenProcs) {
569   auto name{symbol.name().ToString()};
570   if (symbol.has<semantics::ObjectEntityDetails>() ||
571       symbol.has<semantics::EntityDetails>()) {
572     if (auto obj{DummyDataObject::Characterize(symbol, context)}) {
573       return DummyArgument{std::move(name), std::move(obj.value())};
574     }
575   } else if (auto proc{
576                  CharacterizeDummyProcedure(symbol, context, seenProcs)}) {
577     return DummyArgument{std::move(name), std::move(proc.value())};
578   }
579   return std::nullopt;
580 }
581 
582 std::optional<DummyArgument> DummyArgument::FromActual(
583     std::string &&name, const Expr<SomeType> &expr, FoldingContext &context) {
584   return common::visit(
585       common::visitors{
586           [&](const BOZLiteralConstant &) {
587             return std::make_optional<DummyArgument>(std::move(name),
588                 DummyDataObject{
589                     TypeAndShape{DynamicType::TypelessIntrinsicArgument()}});
590           },
591           [&](const NullPointer &) {
592             return std::make_optional<DummyArgument>(std::move(name),
593                 DummyDataObject{
594                     TypeAndShape{DynamicType::TypelessIntrinsicArgument()}});
595           },
596           [&](const ProcedureDesignator &designator) {
597             if (auto proc{Procedure::Characterize(designator, context)}) {
598               return std::make_optional<DummyArgument>(
599                   std::move(name), DummyProcedure{std::move(*proc)});
600             } else {
601               return std::optional<DummyArgument>{};
602             }
603           },
604           [&](const ProcedureRef &call) {
605             if (auto proc{Procedure::Characterize(call, context)}) {
606               return std::make_optional<DummyArgument>(
607                   std::move(name), DummyProcedure{std::move(*proc)});
608             } else {
609               return std::optional<DummyArgument>{};
610             }
611           },
612           [&](const auto &) {
613             if (auto type{TypeAndShape::Characterize(expr, context)}) {
614               return std::make_optional<DummyArgument>(
615                   std::move(name), DummyDataObject{std::move(*type)});
616             } else {
617               return std::optional<DummyArgument>{};
618             }
619           },
620       },
621       expr.u);
622 }
623 
624 bool DummyArgument::IsOptional() const {
625   return common::visit(
626       common::visitors{
627           [](const DummyDataObject &data) {
628             return data.attrs.test(DummyDataObject::Attr::Optional);
629           },
630           [](const DummyProcedure &proc) {
631             return proc.attrs.test(DummyProcedure::Attr::Optional);
632           },
633           [](const AlternateReturn &) { return false; },
634       },
635       u);
636 }
637 
638 void DummyArgument::SetOptional(bool value) {
639   common::visit(common::visitors{
640                     [value](DummyDataObject &data) {
641                       data.attrs.set(DummyDataObject::Attr::Optional, value);
642                     },
643                     [value](DummyProcedure &proc) {
644                       proc.attrs.set(DummyProcedure::Attr::Optional, value);
645                     },
646                     [](AlternateReturn &) { DIE("cannot set optional"); },
647                 },
648       u);
649 }
650 
651 void DummyArgument::SetIntent(common::Intent intent) {
652   common::visit(common::visitors{
653                     [intent](DummyDataObject &data) { data.intent = intent; },
654                     [intent](DummyProcedure &proc) { proc.intent = intent; },
655                     [](AlternateReturn &) { DIE("cannot set intent"); },
656                 },
657       u);
658 }
659 
660 common::Intent DummyArgument::GetIntent() const {
661   return common::visit(
662       common::visitors{
663           [](const DummyDataObject &data) { return data.intent; },
664           [](const DummyProcedure &proc) { return proc.intent; },
665           [](const AlternateReturn &) -> common::Intent {
666             DIE("Alternate returns have no intent");
667           },
668       },
669       u);
670 }
671 
672 bool DummyArgument::CanBePassedViaImplicitInterface() const {
673   if (const auto *object{std::get_if<DummyDataObject>(&u)}) {
674     return object->CanBePassedViaImplicitInterface();
675   } else {
676     return true;
677   }
678 }
679 
680 bool DummyArgument::IsTypelessIntrinsicDummy() const {
681   const auto *argObj{std::get_if<characteristics::DummyDataObject>(&u)};
682   return argObj && argObj->type.type().IsTypelessIntrinsicArgument();
683 }
684 
685 llvm::raw_ostream &DummyArgument::Dump(llvm::raw_ostream &o) const {
686   if (!name.empty()) {
687     o << name << '=';
688   }
689   if (pass) {
690     o << " PASS";
691   }
692   common::visit([&](const auto &x) { x.Dump(o); }, u);
693   return o;
694 }
695 
696 FunctionResult::FunctionResult(DynamicType t) : u{TypeAndShape{t}} {}
697 FunctionResult::FunctionResult(TypeAndShape &&t) : u{std::move(t)} {}
698 FunctionResult::FunctionResult(Procedure &&p) : u{std::move(p)} {}
699 FunctionResult::~FunctionResult() {}
700 
701 bool FunctionResult::operator==(const FunctionResult &that) const {
702   return attrs == that.attrs && u == that.u;
703 }
704 
705 static std::optional<FunctionResult> CharacterizeFunctionResult(
706     const semantics::Symbol &symbol, FoldingContext &context,
707     semantics::UnorderedSymbolSet seenProcs) {
708   if (symbol.has<semantics::ObjectEntityDetails>()) {
709     if (auto type{TypeAndShape::Characterize(symbol, context)}) {
710       FunctionResult result{std::move(*type)};
711       CopyAttrs<FunctionResult, FunctionResult::Attr>(symbol, result,
712           {
713               {semantics::Attr::ALLOCATABLE, FunctionResult::Attr::Allocatable},
714               {semantics::Attr::CONTIGUOUS, FunctionResult::Attr::Contiguous},
715               {semantics::Attr::POINTER, FunctionResult::Attr::Pointer},
716           });
717       return result;
718     }
719   } else if (auto maybeProc{
720                  CharacterizeProcedure(symbol, context, seenProcs)}) {
721     FunctionResult result{std::move(*maybeProc)};
722     result.attrs.set(FunctionResult::Attr::Pointer);
723     return result;
724   }
725   return std::nullopt;
726 }
727 
728 std::optional<FunctionResult> FunctionResult::Characterize(
729     const Symbol &symbol, FoldingContext &context) {
730   semantics::UnorderedSymbolSet seenProcs;
731   return CharacterizeFunctionResult(symbol, context, seenProcs);
732 }
733 
734 bool FunctionResult::IsAssumedLengthCharacter() const {
735   if (const auto *ts{std::get_if<TypeAndShape>(&u)}) {
736     return ts->type().IsAssumedLengthCharacter();
737   } else {
738     return false;
739   }
740 }
741 
742 bool FunctionResult::CanBeReturnedViaImplicitInterface() const {
743   if (attrs.test(Attr::Pointer) || attrs.test(Attr::Allocatable)) {
744     return false; // 15.4.2.2(4)(b)
745   } else if (const auto *typeAndShape{GetTypeAndShape()}) {
746     if (typeAndShape->Rank() > 0) {
747       return false; // 15.4.2.2(4)(a)
748     } else {
749       const DynamicType &type{typeAndShape->type()};
750       switch (type.category()) {
751       case TypeCategory::Character:
752         if (type.knownLength()) {
753           return true;
754         } else if (const auto *param{type.charLengthParamValue()}) {
755           if (const auto &expr{param->GetExplicit()}) {
756             return IsConstantExpr(*expr); // 15.4.2.2(4)(c)
757           } else if (param->isAssumed()) {
758             return true;
759           }
760         }
761         return false;
762       case TypeCategory::Derived:
763         if (!type.IsPolymorphic()) {
764           const auto &spec{type.GetDerivedTypeSpec()};
765           for (const auto &pair : spec.parameters()) {
766             if (const auto &expr{pair.second.GetExplicit()}) {
767               if (!IsConstantExpr(*expr)) {
768                 return false; // 15.4.2.2(4)(c)
769               }
770             }
771           }
772           return true;
773         }
774         return false;
775       default:
776         return true;
777       }
778     }
779   } else {
780     return false; // 15.4.2.2(4)(b) - procedure pointer
781   }
782 }
783 
784 bool FunctionResult::IsCompatibleWith(const FunctionResult &actual) const {
785   Attrs actualAttrs{actual.attrs};
786   actualAttrs.reset(Attr::Contiguous);
787   if (attrs != actualAttrs) {
788     return false;
789   } else if (const auto *ifaceTypeShape{std::get_if<TypeAndShape>(&u)}) {
790     if (const auto *actualTypeShape{std::get_if<TypeAndShape>(&actual.u)}) {
791       if (ifaceTypeShape->shape() != actualTypeShape->shape()) {
792         return false;
793       } else {
794         return ifaceTypeShape->type().IsTkCompatibleWith(
795             actualTypeShape->type());
796       }
797     } else {
798       return false;
799     }
800   } else {
801     const auto *ifaceProc{std::get_if<CopyableIndirection<Procedure>>(&u)};
802     if (const auto *actualProc{
803             std::get_if<CopyableIndirection<Procedure>>(&actual.u)}) {
804       return ifaceProc->value().IsCompatibleWith(actualProc->value());
805     } else {
806       return false;
807     }
808   }
809 }
810 
811 llvm::raw_ostream &FunctionResult::Dump(llvm::raw_ostream &o) const {
812   attrs.Dump(o, EnumToString);
813   common::visit(common::visitors{
814                     [&](const TypeAndShape &ts) { ts.Dump(o); },
815                     [&](const CopyableIndirection<Procedure> &p) {
816                       p.value().Dump(o << " procedure(") << ')';
817                     },
818                 },
819       u);
820   return o;
821 }
822 
823 Procedure::Procedure(FunctionResult &&fr, DummyArguments &&args, Attrs a)
824     : functionResult{std::move(fr)}, dummyArguments{std::move(args)}, attrs{a} {
825 }
826 Procedure::Procedure(DummyArguments &&args, Attrs a)
827     : dummyArguments{std::move(args)}, attrs{a} {}
828 Procedure::~Procedure() {}
829 
830 bool Procedure::operator==(const Procedure &that) const {
831   return attrs == that.attrs && functionResult == that.functionResult &&
832       dummyArguments == that.dummyArguments;
833 }
834 
835 bool Procedure::IsCompatibleWith(const Procedure &actual) const {
836   // 15.5.2.9(1): if dummy is not pure, actual need not be.
837   Attrs actualAttrs{actual.attrs};
838   if (!attrs.test(Attr::Pure)) {
839     actualAttrs.reset(Attr::Pure);
840   }
841   if (attrs != actualAttrs) {
842     return false;
843   } else if (IsFunction() != actual.IsFunction()) {
844     return false;
845   } else if (IsFunction() &&
846       !functionResult->IsCompatibleWith(*actual.functionResult)) {
847     return false;
848   } else if (dummyArguments.size() != actual.dummyArguments.size()) {
849     return false;
850   } else {
851     for (std::size_t j{0}; j < dummyArguments.size(); ++j) {
852       if (!dummyArguments[j].IsCompatibleWith(actual.dummyArguments[j])) {
853         return false;
854       }
855     }
856     return true;
857   }
858 }
859 
860 int Procedure::FindPassIndex(std::optional<parser::CharBlock> name) const {
861   int argCount{static_cast<int>(dummyArguments.size())};
862   int index{0};
863   if (name) {
864     while (index < argCount && *name != dummyArguments[index].name.c_str()) {
865       ++index;
866     }
867   }
868   CHECK(index < argCount);
869   return index;
870 }
871 
872 bool Procedure::CanOverride(
873     const Procedure &that, std::optional<int> passIndex) const {
874   // A pure procedure may override an impure one (7.5.7.3(2))
875   if ((that.attrs.test(Attr::Pure) && !attrs.test(Attr::Pure)) ||
876       that.attrs.test(Attr::Elemental) != attrs.test(Attr::Elemental) ||
877       functionResult != that.functionResult) {
878     return false;
879   }
880   int argCount{static_cast<int>(dummyArguments.size())};
881   if (argCount != static_cast<int>(that.dummyArguments.size())) {
882     return false;
883   }
884   for (int j{0}; j < argCount; ++j) {
885     if ((!passIndex || j != *passIndex) &&
886         dummyArguments[j] != that.dummyArguments[j]) {
887       return false;
888     }
889   }
890   return true;
891 }
892 
893 std::optional<Procedure> Procedure::Characterize(
894     const semantics::Symbol &original, FoldingContext &context) {
895   semantics::UnorderedSymbolSet seenProcs;
896   return CharacterizeProcedure(original, context, seenProcs);
897 }
898 
899 std::optional<Procedure> Procedure::Characterize(
900     const ProcedureDesignator &proc, FoldingContext &context) {
901   if (const auto *symbol{proc.GetSymbol()}) {
902     if (auto result{
903             characteristics::Procedure::Characterize(*symbol, context)}) {
904       return result;
905     }
906   } else if (const auto *intrinsic{proc.GetSpecificIntrinsic()}) {
907     return intrinsic->characteristics.value();
908   }
909   return std::nullopt;
910 }
911 
912 std::optional<Procedure> Procedure::Characterize(
913     const ProcedureRef &ref, FoldingContext &context) {
914   if (auto callee{Characterize(ref.proc(), context)}) {
915     if (callee->functionResult) {
916       if (const Procedure *
917           proc{callee->functionResult->IsProcedurePointer()}) {
918         return {*proc};
919       }
920     }
921   }
922   return std::nullopt;
923 }
924 
925 bool Procedure::CanBeCalledViaImplicitInterface() const {
926   // TODO: Pass back information on why we return false
927   if (attrs.test(Attr::Elemental) || attrs.test(Attr::BindC)) {
928     return false; // 15.4.2.2(5,6)
929   } else if (IsFunction() &&
930       !functionResult->CanBeReturnedViaImplicitInterface()) {
931     return false;
932   } else {
933     for (const DummyArgument &arg : dummyArguments) {
934       if (!arg.CanBePassedViaImplicitInterface()) {
935         return false;
936       }
937     }
938     return true;
939   }
940 }
941 
942 llvm::raw_ostream &Procedure::Dump(llvm::raw_ostream &o) const {
943   attrs.Dump(o, EnumToString);
944   if (functionResult) {
945     functionResult->Dump(o << "TYPE(") << ") FUNCTION";
946   } else {
947     o << "SUBROUTINE";
948   }
949   char sep{'('};
950   for (const auto &dummy : dummyArguments) {
951     dummy.Dump(o << sep);
952     sep = ',';
953   }
954   return o << (sep == '(' ? "()" : ")");
955 }
956 
957 // Utility class to determine if Procedures, etc. are distinguishable
958 class DistinguishUtils {
959 public:
960   explicit DistinguishUtils(const common::LanguageFeatureControl &features)
961       : features_{features} {}
962 
963   // Are these procedures distinguishable for a generic name?
964   bool Distinguishable(const Procedure &, const Procedure &) const;
965   // Are these procedures distinguishable for a generic operator or assignment?
966   bool DistinguishableOpOrAssign(const Procedure &, const Procedure &) const;
967 
968 private:
969   struct CountDummyProcedures {
970     CountDummyProcedures(const DummyArguments &args) {
971       for (const DummyArgument &arg : args) {
972         if (std::holds_alternative<DummyProcedure>(arg.u)) {
973           total += 1;
974           notOptional += !arg.IsOptional();
975         }
976       }
977     }
978     int total{0};
979     int notOptional{0};
980   };
981 
982   bool Rule3Distinguishable(const Procedure &, const Procedure &) const;
983   const DummyArgument *Rule1DistinguishingArg(
984       const DummyArguments &, const DummyArguments &) const;
985   int FindFirstToDistinguishByPosition(
986       const DummyArguments &, const DummyArguments &) const;
987   int FindLastToDistinguishByName(
988       const DummyArguments &, const DummyArguments &) const;
989   int CountCompatibleWith(const DummyArgument &, const DummyArguments &) const;
990   int CountNotDistinguishableFrom(
991       const DummyArgument &, const DummyArguments &) const;
992   bool Distinguishable(const DummyArgument &, const DummyArgument &) const;
993   bool Distinguishable(const DummyDataObject &, const DummyDataObject &) const;
994   bool Distinguishable(const DummyProcedure &, const DummyProcedure &) const;
995   bool Distinguishable(const FunctionResult &, const FunctionResult &) const;
996   bool Distinguishable(const TypeAndShape &, const TypeAndShape &) const;
997   bool IsTkrCompatible(const DummyArgument &, const DummyArgument &) const;
998   bool IsTkrCompatible(const TypeAndShape &, const TypeAndShape &) const;
999   const DummyArgument *GetAtEffectivePosition(
1000       const DummyArguments &, int) const;
1001   const DummyArgument *GetPassArg(const Procedure &) const;
1002 
1003   const common::LanguageFeatureControl &features_;
1004 };
1005 
1006 // Simpler distinguishability rules for operators and assignment
1007 bool DistinguishUtils::DistinguishableOpOrAssign(
1008     const Procedure &proc1, const Procedure &proc2) const {
1009   auto &args1{proc1.dummyArguments};
1010   auto &args2{proc2.dummyArguments};
1011   if (args1.size() != args2.size()) {
1012     return true; // C1511: distinguishable based on number of arguments
1013   }
1014   for (std::size_t i{0}; i < args1.size(); ++i) {
1015     if (Distinguishable(args1[i], args2[i])) {
1016       return true; // C1511, C1512: distinguishable based on this arg
1017     }
1018   }
1019   return false;
1020 }
1021 
1022 bool DistinguishUtils::Distinguishable(
1023     const Procedure &proc1, const Procedure &proc2) const {
1024   auto &args1{proc1.dummyArguments};
1025   auto &args2{proc2.dummyArguments};
1026   auto count1{CountDummyProcedures(args1)};
1027   auto count2{CountDummyProcedures(args2)};
1028   if (count1.notOptional > count2.total || count2.notOptional > count1.total) {
1029     return true; // distinguishable based on C1514 rule 2
1030   }
1031   if (Rule3Distinguishable(proc1, proc2)) {
1032     return true; // distinguishable based on C1514 rule 3
1033   }
1034   if (Rule1DistinguishingArg(args1, args2)) {
1035     return true; // distinguishable based on C1514 rule 1
1036   }
1037   int pos1{FindFirstToDistinguishByPosition(args1, args2)};
1038   int name1{FindLastToDistinguishByName(args1, args2)};
1039   if (pos1 >= 0 && pos1 <= name1) {
1040     return true; // distinguishable based on C1514 rule 4
1041   }
1042   int pos2{FindFirstToDistinguishByPosition(args2, args1)};
1043   int name2{FindLastToDistinguishByName(args2, args1)};
1044   if (pos2 >= 0 && pos2 <= name2) {
1045     return true; // distinguishable based on C1514 rule 4
1046   }
1047   return false;
1048 }
1049 
1050 // C1514 rule 3: Procedures are distinguishable if both have a passed-object
1051 // dummy argument and those are distinguishable.
1052 bool DistinguishUtils::Rule3Distinguishable(
1053     const Procedure &proc1, const Procedure &proc2) const {
1054   const DummyArgument *pass1{GetPassArg(proc1)};
1055   const DummyArgument *pass2{GetPassArg(proc2)};
1056   return pass1 && pass2 && Distinguishable(*pass1, *pass2);
1057 }
1058 
1059 // Find a non-passed-object dummy data object in one of the argument lists
1060 // that satisfies C1514 rule 1. I.e. x such that:
1061 // - m is the number of dummy data objects in one that are nonoptional,
1062 //   are not passed-object, that x is TKR compatible with
1063 // - n is the number of non-passed-object dummy data objects, in the other
1064 //   that are not distinguishable from x
1065 // - m is greater than n
1066 const DummyArgument *DistinguishUtils::Rule1DistinguishingArg(
1067     const DummyArguments &args1, const DummyArguments &args2) const {
1068   auto size1{args1.size()};
1069   auto size2{args2.size()};
1070   for (std::size_t i{0}; i < size1 + size2; ++i) {
1071     const DummyArgument &x{i < size1 ? args1[i] : args2[i - size1]};
1072     if (!x.pass && std::holds_alternative<DummyDataObject>(x.u)) {
1073       if (CountCompatibleWith(x, args1) >
1074               CountNotDistinguishableFrom(x, args2) ||
1075           CountCompatibleWith(x, args2) >
1076               CountNotDistinguishableFrom(x, args1)) {
1077         return &x;
1078       }
1079     }
1080   }
1081   return nullptr;
1082 }
1083 
1084 // Find the index of the first nonoptional non-passed-object dummy argument
1085 // in args1 at an effective position such that either:
1086 // - args2 has no dummy argument at that effective position
1087 // - the dummy argument at that position is distinguishable from it
1088 int DistinguishUtils::FindFirstToDistinguishByPosition(
1089     const DummyArguments &args1, const DummyArguments &args2) const {
1090   int effective{0}; // position of arg1 in list, ignoring passed arg
1091   for (std::size_t i{0}; i < args1.size(); ++i) {
1092     const DummyArgument &arg1{args1.at(i)};
1093     if (!arg1.pass && !arg1.IsOptional()) {
1094       const DummyArgument *arg2{GetAtEffectivePosition(args2, effective)};
1095       if (!arg2 || Distinguishable(arg1, *arg2)) {
1096         return i;
1097       }
1098     }
1099     effective += !arg1.pass;
1100   }
1101   return -1;
1102 }
1103 
1104 // Find the index of the last nonoptional non-passed-object dummy argument
1105 // in args1 whose name is such that either:
1106 // - args2 has no dummy argument with that name
1107 // - the dummy argument with that name is distinguishable from it
1108 int DistinguishUtils::FindLastToDistinguishByName(
1109     const DummyArguments &args1, const DummyArguments &args2) const {
1110   std::map<std::string, const DummyArgument *> nameToArg;
1111   for (const auto &arg2 : args2) {
1112     nameToArg.emplace(arg2.name, &arg2);
1113   }
1114   for (int i = args1.size() - 1; i >= 0; --i) {
1115     const DummyArgument &arg1{args1.at(i)};
1116     if (!arg1.pass && !arg1.IsOptional()) {
1117       auto it{nameToArg.find(arg1.name)};
1118       if (it == nameToArg.end() || Distinguishable(arg1, *it->second)) {
1119         return i;
1120       }
1121     }
1122   }
1123   return -1;
1124 }
1125 
1126 // Count the dummy data objects in args that are nonoptional, are not
1127 // passed-object, and that x is TKR compatible with
1128 int DistinguishUtils::CountCompatibleWith(
1129     const DummyArgument &x, const DummyArguments &args) const {
1130   return std::count_if(args.begin(), args.end(), [&](const DummyArgument &y) {
1131     return !y.pass && !y.IsOptional() && IsTkrCompatible(x, y);
1132   });
1133 }
1134 
1135 // Return the number of dummy data objects in args that are not
1136 // distinguishable from x and not passed-object.
1137 int DistinguishUtils::CountNotDistinguishableFrom(
1138     const DummyArgument &x, const DummyArguments &args) const {
1139   return std::count_if(args.begin(), args.end(), [&](const DummyArgument &y) {
1140     return !y.pass && std::holds_alternative<DummyDataObject>(y.u) &&
1141         !Distinguishable(y, x);
1142   });
1143 }
1144 
1145 bool DistinguishUtils::Distinguishable(
1146     const DummyArgument &x, const DummyArgument &y) const {
1147   if (x.u.index() != y.u.index()) {
1148     return true; // different kind: data/proc/alt-return
1149   }
1150   return common::visit(
1151       common::visitors{
1152           [&](const DummyDataObject &z) {
1153             return Distinguishable(z, std::get<DummyDataObject>(y.u));
1154           },
1155           [&](const DummyProcedure &z) {
1156             return Distinguishable(z, std::get<DummyProcedure>(y.u));
1157           },
1158           [&](const AlternateReturn &) { return false; },
1159       },
1160       x.u);
1161 }
1162 
1163 bool DistinguishUtils::Distinguishable(
1164     const DummyDataObject &x, const DummyDataObject &y) const {
1165   using Attr = DummyDataObject::Attr;
1166   if (Distinguishable(x.type, y.type)) {
1167     return true;
1168   } else if (x.attrs.test(Attr::Allocatable) && y.attrs.test(Attr::Pointer) &&
1169       y.intent != common::Intent::In) {
1170     return true;
1171   } else if (y.attrs.test(Attr::Allocatable) && x.attrs.test(Attr::Pointer) &&
1172       x.intent != common::Intent::In) {
1173     return true;
1174   } else if (features_.IsEnabled(
1175                  common::LanguageFeature::DistinguishableSpecifics) &&
1176       (x.attrs.test(Attr::Allocatable) || x.attrs.test(Attr::Pointer)) &&
1177       (y.attrs.test(Attr::Allocatable) || y.attrs.test(Attr::Pointer)) &&
1178       (x.type.type().IsUnlimitedPolymorphic() !=
1179               y.type.type().IsUnlimitedPolymorphic() ||
1180           x.type.type().IsPolymorphic() != y.type.type().IsPolymorphic())) {
1181     // Extension: Per 15.5.2.5(2), an allocatable/pointer dummy and its
1182     // corresponding actual argument must both or neither be polymorphic,
1183     // and must both or neither be unlimited polymorphic.  So when exactly
1184     // one of two dummy arguments is polymorphic or unlimited polymorphic,
1185     // any actual argument that is admissible to one of them cannot also match
1186     // the other one.
1187     return true;
1188   } else {
1189     return false;
1190   }
1191 }
1192 
1193 bool DistinguishUtils::Distinguishable(
1194     const DummyProcedure &x, const DummyProcedure &y) const {
1195   const Procedure &xProc{x.procedure.value()};
1196   const Procedure &yProc{y.procedure.value()};
1197   if (Distinguishable(xProc, yProc)) {
1198     return true;
1199   } else {
1200     const std::optional<FunctionResult> &xResult{xProc.functionResult};
1201     const std::optional<FunctionResult> &yResult{yProc.functionResult};
1202     return xResult ? !yResult || Distinguishable(*xResult, *yResult)
1203                    : yResult.has_value();
1204   }
1205 }
1206 
1207 bool DistinguishUtils::Distinguishable(
1208     const FunctionResult &x, const FunctionResult &y) const {
1209   if (x.u.index() != y.u.index()) {
1210     return true; // one is data object, one is procedure
1211   }
1212   return common::visit(
1213       common::visitors{
1214           [&](const TypeAndShape &z) {
1215             return Distinguishable(z, std::get<TypeAndShape>(y.u));
1216           },
1217           [&](const CopyableIndirection<Procedure> &z) {
1218             return Distinguishable(z.value(),
1219                 std::get<CopyableIndirection<Procedure>>(y.u).value());
1220           },
1221       },
1222       x.u);
1223 }
1224 
1225 bool DistinguishUtils::Distinguishable(
1226     const TypeAndShape &x, const TypeAndShape &y) const {
1227   return !IsTkrCompatible(x, y) && !IsTkrCompatible(y, x);
1228 }
1229 
1230 // Compatibility based on type, kind, and rank
1231 bool DistinguishUtils::IsTkrCompatible(
1232     const DummyArgument &x, const DummyArgument &y) const {
1233   const auto *obj1{std::get_if<DummyDataObject>(&x.u)};
1234   const auto *obj2{std::get_if<DummyDataObject>(&y.u)};
1235   return obj1 && obj2 && IsTkrCompatible(obj1->type, obj2->type);
1236 }
1237 bool DistinguishUtils::IsTkrCompatible(
1238     const TypeAndShape &x, const TypeAndShape &y) const {
1239   return x.type().IsTkCompatibleWith(y.type()) &&
1240       (x.attrs().test(TypeAndShape::Attr::AssumedRank) ||
1241           y.attrs().test(TypeAndShape::Attr::AssumedRank) ||
1242           x.Rank() == y.Rank());
1243 }
1244 
1245 // Return the argument at the given index, ignoring the passed arg
1246 const DummyArgument *DistinguishUtils::GetAtEffectivePosition(
1247     const DummyArguments &args, int index) const {
1248   for (const DummyArgument &arg : args) {
1249     if (!arg.pass) {
1250       if (index == 0) {
1251         return &arg;
1252       }
1253       --index;
1254     }
1255   }
1256   return nullptr;
1257 }
1258 
1259 // Return the passed-object dummy argument of this procedure, if any
1260 const DummyArgument *DistinguishUtils::GetPassArg(const Procedure &proc) const {
1261   for (const auto &arg : proc.dummyArguments) {
1262     if (arg.pass) {
1263       return &arg;
1264     }
1265   }
1266   return nullptr;
1267 }
1268 
1269 bool Distinguishable(const common::LanguageFeatureControl &features,
1270     const Procedure &x, const Procedure &y) {
1271   return DistinguishUtils{features}.Distinguishable(x, y);
1272 }
1273 
1274 bool DistinguishableOpOrAssign(const common::LanguageFeatureControl &features,
1275     const Procedure &x, const Procedure &y) {
1276   return DistinguishUtils{features}.DistinguishableOpOrAssign(x, y);
1277 }
1278 
1279 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(DummyArgument)
1280 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(DummyProcedure)
1281 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(FunctionResult)
1282 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(Procedure)
1283 } // namespace Fortran::evaluate::characteristics
1284 
1285 template class Fortran::common::Indirection<
1286     Fortran::evaluate::characteristics::Procedure, true>;
1287