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 
371 static std::optional<Procedure> CharacterizeProcedure(
372     const semantics::Symbol &original, FoldingContext &context,
373     semantics::UnorderedSymbolSet seenProcs) {
374   Procedure result;
375   const auto &symbol{ResolveAssociations(original)};
376   if (seenProcs.find(symbol) != seenProcs.end()) {
377     std::string procsList{GetSeenProcs(seenProcs)};
378     context.messages().Say(symbol.name(),
379         "Procedure '%s' is recursively defined.  Procedures in the cycle:"
380         " %s"_err_en_US,
381         symbol.name(), procsList);
382     return std::nullopt;
383   }
384   seenProcs.insert(symbol);
385   CopyAttrs<Procedure, Procedure::Attr>(symbol, result,
386       {
387           {semantics::Attr::ELEMENTAL, Procedure::Attr::Elemental},
388           {semantics::Attr::BIND_C, Procedure::Attr::BindC},
389       });
390   if (IsPureProcedure(symbol) || // works for ENTRY too
391       (!symbol.attrs().test(semantics::Attr::IMPURE) &&
392           result.attrs.test(Procedure::Attr::Elemental))) {
393     result.attrs.set(Procedure::Attr::Pure);
394   }
395   return common::visit(
396       common::visitors{
397           [&](const semantics::SubprogramDetails &subp)
398               -> std::optional<Procedure> {
399             if (subp.isFunction()) {
400               if (auto fr{
401                       FunctionResult::Characterize(subp.result(), context)}) {
402                 result.functionResult = std::move(fr);
403               } else {
404                 return std::nullopt;
405               }
406             } else {
407               result.attrs.set(Procedure::Attr::Subroutine);
408             }
409             for (const semantics::Symbol *arg : subp.dummyArgs()) {
410               if (!arg) {
411                 if (subp.isFunction()) {
412                   return std::nullopt;
413                 } else {
414                   result.dummyArguments.emplace_back(AlternateReturn{});
415                 }
416               } else if (auto argCharacteristics{CharacterizeDummyArgument(
417                              *arg, context, seenProcs)}) {
418                 result.dummyArguments.emplace_back(
419                     std::move(argCharacteristics.value()));
420               } else {
421                 return std::nullopt;
422               }
423             }
424             return result;
425           },
426           [&](const semantics::ProcEntityDetails &proc)
427               -> std::optional<Procedure> {
428             if (symbol.attrs().test(semantics::Attr::INTRINSIC)) {
429               // Fails when the intrinsic is not a specific intrinsic function
430               // from F'2018 table 16.2.  In order to handle forward references,
431               // attempts to use impermissible intrinsic procedures as the
432               // interfaces of procedure pointers are caught and flagged in
433               // declaration checking in Semantics.
434               auto intrinsic{context.intrinsics().IsSpecificIntrinsicFunction(
435                   symbol.name().ToString())};
436               if (intrinsic && intrinsic->isRestrictedSpecific) {
437                 intrinsic.reset(); // Exclude intrinsics from table 16.3.
438               }
439               return intrinsic;
440             }
441             const semantics::ProcInterface &interface{proc.interface()};
442             if (const semantics::Symbol * interfaceSymbol{interface.symbol()}) {
443               return CharacterizeProcedure(
444                   *interfaceSymbol, context, seenProcs);
445             } else {
446               result.attrs.set(Procedure::Attr::ImplicitInterface);
447               const semantics::DeclTypeSpec *type{interface.type()};
448               if (symbol.test(semantics::Symbol::Flag::Subroutine)) {
449                 // ignore any implicit typing
450                 result.attrs.set(Procedure::Attr::Subroutine);
451               } else if (type) {
452                 if (auto resultType{DynamicType::From(*type)}) {
453                   result.functionResult = FunctionResult{*resultType};
454                 } else {
455                   return std::nullopt;
456                 }
457               } else if (symbol.test(semantics::Symbol::Flag::Function)) {
458                 return std::nullopt;
459               }
460               // The PASS name, if any, is not a characteristic.
461               return result;
462             }
463           },
464           [&](const semantics::ProcBindingDetails &binding) {
465             if (auto result{CharacterizeProcedure(
466                     binding.symbol(), context, seenProcs)}) {
467               if (!symbol.attrs().test(semantics::Attr::NOPASS)) {
468                 auto passName{binding.passName()};
469                 for (auto &dummy : result->dummyArguments) {
470                   if (!passName || dummy.name.c_str() == *passName) {
471                     dummy.pass = true;
472                     return result;
473                   }
474                 }
475                 DIE("PASS argument missing");
476               }
477               return result;
478             } else {
479               return std::optional<Procedure>{};
480             }
481           },
482           [&](const semantics::UseDetails &use) {
483             return CharacterizeProcedure(use.symbol(), context, seenProcs);
484           },
485           [&](const semantics::HostAssocDetails &assoc) {
486             return CharacterizeProcedure(assoc.symbol(), context, seenProcs);
487           },
488           [&](const semantics::EntityDetails &) {
489             context.messages().Say(
490                 "Procedure '%s' is referenced before being sufficiently defined in a context where it must be so"_err_en_US,
491                 symbol.name());
492             return std::optional<Procedure>{};
493           },
494           [&](const semantics::SubprogramNameDetails &) {
495             context.messages().Say(
496                 "Procedure '%s' is referenced before being sufficiently defined in a context where it must be so"_err_en_US,
497                 symbol.name());
498             return std::optional<Procedure>{};
499           },
500           [&](const auto &) {
501             context.messages().Say(
502                 "'%s' is not a procedure"_err_en_US, symbol.name());
503             return std::optional<Procedure>{};
504           },
505       },
506       symbol.details());
507 }
508 
509 static std::optional<DummyProcedure> CharacterizeDummyProcedure(
510     const semantics::Symbol &symbol, FoldingContext &context,
511     semantics::UnorderedSymbolSet seenProcs) {
512   if (auto procedure{CharacterizeProcedure(symbol, context, seenProcs)}) {
513     // Dummy procedures may not be elemental.  Elemental dummy procedure
514     // interfaces are errors when the interface is not intrinsic, and that
515     // error is caught elsewhere.  Elemental intrinsic interfaces are
516     // made non-elemental.
517     procedure->attrs.reset(Procedure::Attr::Elemental);
518     DummyProcedure result{std::move(procedure.value())};
519     CopyAttrs<DummyProcedure, DummyProcedure::Attr>(symbol, result,
520         {
521             {semantics::Attr::OPTIONAL, DummyProcedure::Attr::Optional},
522             {semantics::Attr::POINTER, DummyProcedure::Attr::Pointer},
523         });
524     result.intent = GetIntent(symbol.attrs());
525     return result;
526   } else {
527     return std::nullopt;
528   }
529 }
530 
531 llvm::raw_ostream &DummyProcedure::Dump(llvm::raw_ostream &o) const {
532   attrs.Dump(o, EnumToString);
533   if (intent != common::Intent::Default) {
534     o << "INTENT(" << common::EnumToString(intent) << ')';
535   }
536   procedure.value().Dump(o);
537   return o;
538 }
539 
540 llvm::raw_ostream &AlternateReturn::Dump(llvm::raw_ostream &o) const {
541   return o << '*';
542 }
543 
544 DummyArgument::~DummyArgument() {}
545 
546 bool DummyArgument::operator==(const DummyArgument &that) const {
547   return u == that.u; // name and passed-object usage are not characteristics
548 }
549 
550 bool DummyArgument::IsCompatibleWith(const DummyArgument &actual) const {
551   if (const auto *ifaceData{std::get_if<DummyDataObject>(&u)}) {
552     const auto *actualData{std::get_if<DummyDataObject>(&actual.u)};
553     return actualData && ifaceData->IsCompatibleWith(*actualData);
554   } else if (const auto *ifaceProc{std::get_if<DummyProcedure>(&u)}) {
555     const auto *actualProc{std::get_if<DummyProcedure>(&actual.u)};
556     return actualProc && ifaceProc->IsCompatibleWith(*actualProc);
557   } else {
558     return std::holds_alternative<AlternateReturn>(u) &&
559         std::holds_alternative<AlternateReturn>(actual.u);
560   }
561 }
562 
563 static std::optional<DummyArgument> CharacterizeDummyArgument(
564     const semantics::Symbol &symbol, FoldingContext &context,
565     semantics::UnorderedSymbolSet seenProcs) {
566   auto name{symbol.name().ToString()};
567   if (symbol.has<semantics::ObjectEntityDetails>() ||
568       symbol.has<semantics::EntityDetails>()) {
569     if (auto obj{DummyDataObject::Characterize(symbol, context)}) {
570       return DummyArgument{std::move(name), std::move(obj.value())};
571     }
572   } else if (auto proc{
573                  CharacterizeDummyProcedure(symbol, context, seenProcs)}) {
574     return DummyArgument{std::move(name), std::move(proc.value())};
575   }
576   return std::nullopt;
577 }
578 
579 std::optional<DummyArgument> DummyArgument::FromActual(
580     std::string &&name, const Expr<SomeType> &expr, FoldingContext &context) {
581   return common::visit(
582       common::visitors{
583           [&](const BOZLiteralConstant &) {
584             return std::make_optional<DummyArgument>(std::move(name),
585                 DummyDataObject{
586                     TypeAndShape{DynamicType::TypelessIntrinsicArgument()}});
587           },
588           [&](const NullPointer &) {
589             return std::make_optional<DummyArgument>(std::move(name),
590                 DummyDataObject{
591                     TypeAndShape{DynamicType::TypelessIntrinsicArgument()}});
592           },
593           [&](const ProcedureDesignator &designator) {
594             if (auto proc{Procedure::Characterize(designator, context)}) {
595               return std::make_optional<DummyArgument>(
596                   std::move(name), DummyProcedure{std::move(*proc)});
597             } else {
598               return std::optional<DummyArgument>{};
599             }
600           },
601           [&](const ProcedureRef &call) {
602             if (auto proc{Procedure::Characterize(call, context)}) {
603               return std::make_optional<DummyArgument>(
604                   std::move(name), DummyProcedure{std::move(*proc)});
605             } else {
606               return std::optional<DummyArgument>{};
607             }
608           },
609           [&](const auto &) {
610             if (auto type{TypeAndShape::Characterize(expr, context)}) {
611               return std::make_optional<DummyArgument>(
612                   std::move(name), DummyDataObject{std::move(*type)});
613             } else {
614               return std::optional<DummyArgument>{};
615             }
616           },
617       },
618       expr.u);
619 }
620 
621 bool DummyArgument::IsOptional() const {
622   return common::visit(
623       common::visitors{
624           [](const DummyDataObject &data) {
625             return data.attrs.test(DummyDataObject::Attr::Optional);
626           },
627           [](const DummyProcedure &proc) {
628             return proc.attrs.test(DummyProcedure::Attr::Optional);
629           },
630           [](const AlternateReturn &) { return false; },
631       },
632       u);
633 }
634 
635 void DummyArgument::SetOptional(bool value) {
636   common::visit(common::visitors{
637                     [value](DummyDataObject &data) {
638                       data.attrs.set(DummyDataObject::Attr::Optional, value);
639                     },
640                     [value](DummyProcedure &proc) {
641                       proc.attrs.set(DummyProcedure::Attr::Optional, value);
642                     },
643                     [](AlternateReturn &) { DIE("cannot set optional"); },
644                 },
645       u);
646 }
647 
648 void DummyArgument::SetIntent(common::Intent intent) {
649   common::visit(common::visitors{
650                     [intent](DummyDataObject &data) { data.intent = intent; },
651                     [intent](DummyProcedure &proc) { proc.intent = intent; },
652                     [](AlternateReturn &) { DIE("cannot set intent"); },
653                 },
654       u);
655 }
656 
657 common::Intent DummyArgument::GetIntent() const {
658   return common::visit(
659       common::visitors{
660           [](const DummyDataObject &data) { return data.intent; },
661           [](const DummyProcedure &proc) { return proc.intent; },
662           [](const AlternateReturn &) -> common::Intent {
663             DIE("Alternate returns have no intent");
664           },
665       },
666       u);
667 }
668 
669 bool DummyArgument::CanBePassedViaImplicitInterface() const {
670   if (const auto *object{std::get_if<DummyDataObject>(&u)}) {
671     return object->CanBePassedViaImplicitInterface();
672   } else {
673     return true;
674   }
675 }
676 
677 bool DummyArgument::IsTypelessIntrinsicDummy() const {
678   const auto *argObj{std::get_if<characteristics::DummyDataObject>(&u)};
679   return argObj && argObj->type.type().IsTypelessIntrinsicArgument();
680 }
681 
682 llvm::raw_ostream &DummyArgument::Dump(llvm::raw_ostream &o) const {
683   if (!name.empty()) {
684     o << name << '=';
685   }
686   if (pass) {
687     o << " PASS";
688   }
689   common::visit([&](const auto &x) { x.Dump(o); }, u);
690   return o;
691 }
692 
693 FunctionResult::FunctionResult(DynamicType t) : u{TypeAndShape{t}} {}
694 FunctionResult::FunctionResult(TypeAndShape &&t) : u{std::move(t)} {}
695 FunctionResult::FunctionResult(Procedure &&p) : u{std::move(p)} {}
696 FunctionResult::~FunctionResult() {}
697 
698 bool FunctionResult::operator==(const FunctionResult &that) const {
699   return attrs == that.attrs && u == that.u;
700 }
701 
702 std::optional<FunctionResult> FunctionResult::Characterize(
703     const Symbol &symbol, FoldingContext &context) {
704   if (symbol.has<semantics::ObjectEntityDetails>()) {
705     if (auto type{TypeAndShape::Characterize(symbol, context)}) {
706       FunctionResult result{std::move(*type)};
707       CopyAttrs<FunctionResult, FunctionResult::Attr>(symbol, result,
708           {
709               {semantics::Attr::ALLOCATABLE, FunctionResult::Attr::Allocatable},
710               {semantics::Attr::CONTIGUOUS, FunctionResult::Attr::Contiguous},
711               {semantics::Attr::POINTER, FunctionResult::Attr::Pointer},
712           });
713       return result;
714     }
715   } else if (auto maybeProc{Procedure::Characterize(symbol, context)}) {
716     FunctionResult result{std::move(*maybeProc)};
717     result.attrs.set(FunctionResult::Attr::Pointer);
718     return result;
719   }
720   return std::nullopt;
721 }
722 
723 bool FunctionResult::IsAssumedLengthCharacter() const {
724   if (const auto *ts{std::get_if<TypeAndShape>(&u)}) {
725     return ts->type().IsAssumedLengthCharacter();
726   } else {
727     return false;
728   }
729 }
730 
731 bool FunctionResult::CanBeReturnedViaImplicitInterface() const {
732   if (attrs.test(Attr::Pointer) || attrs.test(Attr::Allocatable)) {
733     return false; // 15.4.2.2(4)(b)
734   } else if (const auto *typeAndShape{GetTypeAndShape()}) {
735     if (typeAndShape->Rank() > 0) {
736       return false; // 15.4.2.2(4)(a)
737     } else {
738       const DynamicType &type{typeAndShape->type()};
739       switch (type.category()) {
740       case TypeCategory::Character:
741         if (type.knownLength()) {
742           return true;
743         } else if (const auto *param{type.charLengthParamValue()}) {
744           if (const auto &expr{param->GetExplicit()}) {
745             return IsConstantExpr(*expr); // 15.4.2.2(4)(c)
746           } else if (param->isAssumed()) {
747             return true;
748           }
749         }
750         return false;
751       case TypeCategory::Derived:
752         if (!type.IsPolymorphic()) {
753           const auto &spec{type.GetDerivedTypeSpec()};
754           for (const auto &pair : spec.parameters()) {
755             if (const auto &expr{pair.second.GetExplicit()}) {
756               if (!IsConstantExpr(*expr)) {
757                 return false; // 15.4.2.2(4)(c)
758               }
759             }
760           }
761           return true;
762         }
763         return false;
764       default:
765         return true;
766       }
767     }
768   } else {
769     return false; // 15.4.2.2(4)(b) - procedure pointer
770   }
771 }
772 
773 bool FunctionResult::IsCompatibleWith(const FunctionResult &actual) const {
774   Attrs actualAttrs{actual.attrs};
775   actualAttrs.reset(Attr::Contiguous);
776   if (attrs != actualAttrs) {
777     return false;
778   } else if (const auto *ifaceTypeShape{std::get_if<TypeAndShape>(&u)}) {
779     if (const auto *actualTypeShape{std::get_if<TypeAndShape>(&actual.u)}) {
780       if (ifaceTypeShape->shape() != actualTypeShape->shape()) {
781         return false;
782       } else {
783         return ifaceTypeShape->type().IsTkCompatibleWith(
784             actualTypeShape->type());
785       }
786     } else {
787       return false;
788     }
789   } else {
790     const auto *ifaceProc{std::get_if<CopyableIndirection<Procedure>>(&u)};
791     if (const auto *actualProc{
792             std::get_if<CopyableIndirection<Procedure>>(&actual.u)}) {
793       return ifaceProc->value().IsCompatibleWith(actualProc->value());
794     } else {
795       return false;
796     }
797   }
798 }
799 
800 llvm::raw_ostream &FunctionResult::Dump(llvm::raw_ostream &o) const {
801   attrs.Dump(o, EnumToString);
802   common::visit(common::visitors{
803                     [&](const TypeAndShape &ts) { ts.Dump(o); },
804                     [&](const CopyableIndirection<Procedure> &p) {
805                       p.value().Dump(o << " procedure(") << ')';
806                     },
807                 },
808       u);
809   return o;
810 }
811 
812 Procedure::Procedure(FunctionResult &&fr, DummyArguments &&args, Attrs a)
813     : functionResult{std::move(fr)}, dummyArguments{std::move(args)}, attrs{a} {
814 }
815 Procedure::Procedure(DummyArguments &&args, Attrs a)
816     : dummyArguments{std::move(args)}, attrs{a} {}
817 Procedure::~Procedure() {}
818 
819 bool Procedure::operator==(const Procedure &that) const {
820   return attrs == that.attrs && functionResult == that.functionResult &&
821       dummyArguments == that.dummyArguments;
822 }
823 
824 bool Procedure::IsCompatibleWith(const Procedure &actual) const {
825   // 15.5.2.9(1): if dummy is not pure, actual need not be.
826   Attrs actualAttrs{actual.attrs};
827   if (!attrs.test(Attr::Pure)) {
828     actualAttrs.reset(Attr::Pure);
829   }
830   if (attrs != actualAttrs) {
831     return false;
832   } else if (IsFunction() != actual.IsFunction()) {
833     return false;
834   } else if (IsFunction() &&
835       !functionResult->IsCompatibleWith(*actual.functionResult)) {
836     return false;
837   } else if (dummyArguments.size() != actual.dummyArguments.size()) {
838     return false;
839   } else {
840     for (std::size_t j{0}; j < dummyArguments.size(); ++j) {
841       if (!dummyArguments[j].IsCompatibleWith(actual.dummyArguments[j])) {
842         return false;
843       }
844     }
845     return true;
846   }
847 }
848 
849 int Procedure::FindPassIndex(std::optional<parser::CharBlock> name) const {
850   int argCount{static_cast<int>(dummyArguments.size())};
851   int index{0};
852   if (name) {
853     while (index < argCount && *name != dummyArguments[index].name.c_str()) {
854       ++index;
855     }
856   }
857   CHECK(index < argCount);
858   return index;
859 }
860 
861 bool Procedure::CanOverride(
862     const Procedure &that, std::optional<int> passIndex) const {
863   // A pure procedure may override an impure one (7.5.7.3(2))
864   if ((that.attrs.test(Attr::Pure) && !attrs.test(Attr::Pure)) ||
865       that.attrs.test(Attr::Elemental) != attrs.test(Attr::Elemental) ||
866       functionResult != that.functionResult) {
867     return false;
868   }
869   int argCount{static_cast<int>(dummyArguments.size())};
870   if (argCount != static_cast<int>(that.dummyArguments.size())) {
871     return false;
872   }
873   for (int j{0}; j < argCount; ++j) {
874     if ((!passIndex || j != *passIndex) &&
875         dummyArguments[j] != that.dummyArguments[j]) {
876       return false;
877     }
878   }
879   return true;
880 }
881 
882 std::optional<Procedure> Procedure::Characterize(
883     const semantics::Symbol &original, FoldingContext &context) {
884   semantics::UnorderedSymbolSet seenProcs;
885   return CharacterizeProcedure(original, context, seenProcs);
886 }
887 
888 std::optional<Procedure> Procedure::Characterize(
889     const ProcedureDesignator &proc, FoldingContext &context) {
890   if (const auto *symbol{proc.GetSymbol()}) {
891     if (auto result{
892             characteristics::Procedure::Characterize(*symbol, context)}) {
893       return result;
894     }
895   } else if (const auto *intrinsic{proc.GetSpecificIntrinsic()}) {
896     return intrinsic->characteristics.value();
897   }
898   return std::nullopt;
899 }
900 
901 std::optional<Procedure> Procedure::Characterize(
902     const ProcedureRef &ref, FoldingContext &context) {
903   if (auto callee{Characterize(ref.proc(), context)}) {
904     if (callee->functionResult) {
905       if (const Procedure *
906           proc{callee->functionResult->IsProcedurePointer()}) {
907         return {*proc};
908       }
909     }
910   }
911   return std::nullopt;
912 }
913 
914 bool Procedure::CanBeCalledViaImplicitInterface() const {
915   // TODO: Pass back information on why we return false
916   if (attrs.test(Attr::Elemental) || attrs.test(Attr::BindC)) {
917     return false; // 15.4.2.2(5,6)
918   } else if (IsFunction() &&
919       !functionResult->CanBeReturnedViaImplicitInterface()) {
920     return false;
921   } else {
922     for (const DummyArgument &arg : dummyArguments) {
923       if (!arg.CanBePassedViaImplicitInterface()) {
924         return false;
925       }
926     }
927     return true;
928   }
929 }
930 
931 llvm::raw_ostream &Procedure::Dump(llvm::raw_ostream &o) const {
932   attrs.Dump(o, EnumToString);
933   if (functionResult) {
934     functionResult->Dump(o << "TYPE(") << ") FUNCTION";
935   } else {
936     o << "SUBROUTINE";
937   }
938   char sep{'('};
939   for (const auto &dummy : dummyArguments) {
940     dummy.Dump(o << sep);
941     sep = ',';
942   }
943   return o << (sep == '(' ? "()" : ")");
944 }
945 
946 // Utility class to determine if Procedures, etc. are distinguishable
947 class DistinguishUtils {
948 public:
949   explicit DistinguishUtils(const common::LanguageFeatureControl &features)
950       : features_{features} {}
951 
952   // Are these procedures distinguishable for a generic name?
953   bool Distinguishable(const Procedure &, const Procedure &) const;
954   // Are these procedures distinguishable for a generic operator or assignment?
955   bool DistinguishableOpOrAssign(const Procedure &, const Procedure &) const;
956 
957 private:
958   struct CountDummyProcedures {
959     CountDummyProcedures(const DummyArguments &args) {
960       for (const DummyArgument &arg : args) {
961         if (std::holds_alternative<DummyProcedure>(arg.u)) {
962           total += 1;
963           notOptional += !arg.IsOptional();
964         }
965       }
966     }
967     int total{0};
968     int notOptional{0};
969   };
970 
971   bool Rule3Distinguishable(const Procedure &, const Procedure &) const;
972   const DummyArgument *Rule1DistinguishingArg(
973       const DummyArguments &, const DummyArguments &) const;
974   int FindFirstToDistinguishByPosition(
975       const DummyArguments &, const DummyArguments &) const;
976   int FindLastToDistinguishByName(
977       const DummyArguments &, const DummyArguments &) const;
978   int CountCompatibleWith(const DummyArgument &, const DummyArguments &) const;
979   int CountNotDistinguishableFrom(
980       const DummyArgument &, const DummyArguments &) const;
981   bool Distinguishable(const DummyArgument &, const DummyArgument &) const;
982   bool Distinguishable(const DummyDataObject &, const DummyDataObject &) const;
983   bool Distinguishable(const DummyProcedure &, const DummyProcedure &) const;
984   bool Distinguishable(const FunctionResult &, const FunctionResult &) const;
985   bool Distinguishable(const TypeAndShape &, const TypeAndShape &) const;
986   bool IsTkrCompatible(const DummyArgument &, const DummyArgument &) const;
987   bool IsTkrCompatible(const TypeAndShape &, const TypeAndShape &) const;
988   const DummyArgument *GetAtEffectivePosition(
989       const DummyArguments &, int) const;
990   const DummyArgument *GetPassArg(const Procedure &) const;
991 
992   const common::LanguageFeatureControl &features_;
993 };
994 
995 // Simpler distinguishability rules for operators and assignment
996 bool DistinguishUtils::DistinguishableOpOrAssign(
997     const Procedure &proc1, const Procedure &proc2) const {
998   auto &args1{proc1.dummyArguments};
999   auto &args2{proc2.dummyArguments};
1000   if (args1.size() != args2.size()) {
1001     return true; // C1511: distinguishable based on number of arguments
1002   }
1003   for (std::size_t i{0}; i < args1.size(); ++i) {
1004     if (Distinguishable(args1[i], args2[i])) {
1005       return true; // C1511, C1512: distinguishable based on this arg
1006     }
1007   }
1008   return false;
1009 }
1010 
1011 bool DistinguishUtils::Distinguishable(
1012     const Procedure &proc1, const Procedure &proc2) const {
1013   auto &args1{proc1.dummyArguments};
1014   auto &args2{proc2.dummyArguments};
1015   auto count1{CountDummyProcedures(args1)};
1016   auto count2{CountDummyProcedures(args2)};
1017   if (count1.notOptional > count2.total || count2.notOptional > count1.total) {
1018     return true; // distinguishable based on C1514 rule 2
1019   }
1020   if (Rule3Distinguishable(proc1, proc2)) {
1021     return true; // distinguishable based on C1514 rule 3
1022   }
1023   if (Rule1DistinguishingArg(args1, args2)) {
1024     return true; // distinguishable based on C1514 rule 1
1025   }
1026   int pos1{FindFirstToDistinguishByPosition(args1, args2)};
1027   int name1{FindLastToDistinguishByName(args1, args2)};
1028   if (pos1 >= 0 && pos1 <= name1) {
1029     return true; // distinguishable based on C1514 rule 4
1030   }
1031   int pos2{FindFirstToDistinguishByPosition(args2, args1)};
1032   int name2{FindLastToDistinguishByName(args2, args1)};
1033   if (pos2 >= 0 && pos2 <= name2) {
1034     return true; // distinguishable based on C1514 rule 4
1035   }
1036   return false;
1037 }
1038 
1039 // C1514 rule 3: Procedures are distinguishable if both have a passed-object
1040 // dummy argument and those are distinguishable.
1041 bool DistinguishUtils::Rule3Distinguishable(
1042     const Procedure &proc1, const Procedure &proc2) const {
1043   const DummyArgument *pass1{GetPassArg(proc1)};
1044   const DummyArgument *pass2{GetPassArg(proc2)};
1045   return pass1 && pass2 && Distinguishable(*pass1, *pass2);
1046 }
1047 
1048 // Find a non-passed-object dummy data object in one of the argument lists
1049 // that satisfies C1514 rule 1. I.e. x such that:
1050 // - m is the number of dummy data objects in one that are nonoptional,
1051 //   are not passed-object, that x is TKR compatible with
1052 // - n is the number of non-passed-object dummy data objects, in the other
1053 //   that are not distinguishable from x
1054 // - m is greater than n
1055 const DummyArgument *DistinguishUtils::Rule1DistinguishingArg(
1056     const DummyArguments &args1, const DummyArguments &args2) const {
1057   auto size1{args1.size()};
1058   auto size2{args2.size()};
1059   for (std::size_t i{0}; i < size1 + size2; ++i) {
1060     const DummyArgument &x{i < size1 ? args1[i] : args2[i - size1]};
1061     if (!x.pass && std::holds_alternative<DummyDataObject>(x.u)) {
1062       if (CountCompatibleWith(x, args1) >
1063               CountNotDistinguishableFrom(x, args2) ||
1064           CountCompatibleWith(x, args2) >
1065               CountNotDistinguishableFrom(x, args1)) {
1066         return &x;
1067       }
1068     }
1069   }
1070   return nullptr;
1071 }
1072 
1073 // Find the index of the first nonoptional non-passed-object dummy argument
1074 // in args1 at an effective position such that either:
1075 // - args2 has no dummy argument at that effective position
1076 // - the dummy argument at that position is distinguishable from it
1077 int DistinguishUtils::FindFirstToDistinguishByPosition(
1078     const DummyArguments &args1, const DummyArguments &args2) const {
1079   int effective{0}; // position of arg1 in list, ignoring passed arg
1080   for (std::size_t i{0}; i < args1.size(); ++i) {
1081     const DummyArgument &arg1{args1.at(i)};
1082     if (!arg1.pass && !arg1.IsOptional()) {
1083       const DummyArgument *arg2{GetAtEffectivePosition(args2, effective)};
1084       if (!arg2 || Distinguishable(arg1, *arg2)) {
1085         return i;
1086       }
1087     }
1088     effective += !arg1.pass;
1089   }
1090   return -1;
1091 }
1092 
1093 // Find the index of the last nonoptional non-passed-object dummy argument
1094 // in args1 whose name is such that either:
1095 // - args2 has no dummy argument with that name
1096 // - the dummy argument with that name is distinguishable from it
1097 int DistinguishUtils::FindLastToDistinguishByName(
1098     const DummyArguments &args1, const DummyArguments &args2) const {
1099   std::map<std::string, const DummyArgument *> nameToArg;
1100   for (const auto &arg2 : args2) {
1101     nameToArg.emplace(arg2.name, &arg2);
1102   }
1103   for (int i = args1.size() - 1; i >= 0; --i) {
1104     const DummyArgument &arg1{args1.at(i)};
1105     if (!arg1.pass && !arg1.IsOptional()) {
1106       auto it{nameToArg.find(arg1.name)};
1107       if (it == nameToArg.end() || Distinguishable(arg1, *it->second)) {
1108         return i;
1109       }
1110     }
1111   }
1112   return -1;
1113 }
1114 
1115 // Count the dummy data objects in args that are nonoptional, are not
1116 // passed-object, and that x is TKR compatible with
1117 int DistinguishUtils::CountCompatibleWith(
1118     const DummyArgument &x, const DummyArguments &args) const {
1119   return std::count_if(args.begin(), args.end(), [&](const DummyArgument &y) {
1120     return !y.pass && !y.IsOptional() && IsTkrCompatible(x, y);
1121   });
1122 }
1123 
1124 // Return the number of dummy data objects in args that are not
1125 // distinguishable from x and not passed-object.
1126 int DistinguishUtils::CountNotDistinguishableFrom(
1127     const DummyArgument &x, const DummyArguments &args) const {
1128   return std::count_if(args.begin(), args.end(), [&](const DummyArgument &y) {
1129     return !y.pass && std::holds_alternative<DummyDataObject>(y.u) &&
1130         !Distinguishable(y, x);
1131   });
1132 }
1133 
1134 bool DistinguishUtils::Distinguishable(
1135     const DummyArgument &x, const DummyArgument &y) const {
1136   if (x.u.index() != y.u.index()) {
1137     return true; // different kind: data/proc/alt-return
1138   }
1139   return common::visit(
1140       common::visitors{
1141           [&](const DummyDataObject &z) {
1142             return Distinguishable(z, std::get<DummyDataObject>(y.u));
1143           },
1144           [&](const DummyProcedure &z) {
1145             return Distinguishable(z, std::get<DummyProcedure>(y.u));
1146           },
1147           [&](const AlternateReturn &) { return false; },
1148       },
1149       x.u);
1150 }
1151 
1152 bool DistinguishUtils::Distinguishable(
1153     const DummyDataObject &x, const DummyDataObject &y) const {
1154   using Attr = DummyDataObject::Attr;
1155   if (Distinguishable(x.type, y.type)) {
1156     return true;
1157   } else if (x.attrs.test(Attr::Allocatable) && y.attrs.test(Attr::Pointer) &&
1158       y.intent != common::Intent::In) {
1159     return true;
1160   } else if (y.attrs.test(Attr::Allocatable) && x.attrs.test(Attr::Pointer) &&
1161       x.intent != common::Intent::In) {
1162     return true;
1163   } else if (features_.IsEnabled(
1164                  common::LanguageFeature::DistinguishableSpecifics) &&
1165       (x.attrs.test(Attr::Allocatable) || x.attrs.test(Attr::Pointer)) &&
1166       (y.attrs.test(Attr::Allocatable) || y.attrs.test(Attr::Pointer)) &&
1167       (x.type.type().IsUnlimitedPolymorphic() !=
1168               y.type.type().IsUnlimitedPolymorphic() ||
1169           x.type.type().IsPolymorphic() != y.type.type().IsPolymorphic())) {
1170     // Extension: Per 15.5.2.5(2), an allocatable/pointer dummy and its
1171     // corresponding actual argument must both or neither be polymorphic,
1172     // and must both or neither be unlimited polymorphic.  So when exactly
1173     // one of two dummy arguments is polymorphic or unlimited polymorphic,
1174     // any actual argument that is admissible to one of them cannot also match
1175     // the other one.
1176     return true;
1177   } else {
1178     return false;
1179   }
1180 }
1181 
1182 bool DistinguishUtils::Distinguishable(
1183     const DummyProcedure &x, const DummyProcedure &y) const {
1184   const Procedure &xProc{x.procedure.value()};
1185   const Procedure &yProc{y.procedure.value()};
1186   if (Distinguishable(xProc, yProc)) {
1187     return true;
1188   } else {
1189     const std::optional<FunctionResult> &xResult{xProc.functionResult};
1190     const std::optional<FunctionResult> &yResult{yProc.functionResult};
1191     return xResult ? !yResult || Distinguishable(*xResult, *yResult)
1192                    : yResult.has_value();
1193   }
1194 }
1195 
1196 bool DistinguishUtils::Distinguishable(
1197     const FunctionResult &x, const FunctionResult &y) const {
1198   if (x.u.index() != y.u.index()) {
1199     return true; // one is data object, one is procedure
1200   }
1201   return common::visit(
1202       common::visitors{
1203           [&](const TypeAndShape &z) {
1204             return Distinguishable(z, std::get<TypeAndShape>(y.u));
1205           },
1206           [&](const CopyableIndirection<Procedure> &z) {
1207             return Distinguishable(z.value(),
1208                 std::get<CopyableIndirection<Procedure>>(y.u).value());
1209           },
1210       },
1211       x.u);
1212 }
1213 
1214 bool DistinguishUtils::Distinguishable(
1215     const TypeAndShape &x, const TypeAndShape &y) const {
1216   return !IsTkrCompatible(x, y) && !IsTkrCompatible(y, x);
1217 }
1218 
1219 // Compatibility based on type, kind, and rank
1220 bool DistinguishUtils::IsTkrCompatible(
1221     const DummyArgument &x, const DummyArgument &y) const {
1222   const auto *obj1{std::get_if<DummyDataObject>(&x.u)};
1223   const auto *obj2{std::get_if<DummyDataObject>(&y.u)};
1224   return obj1 && obj2 && IsTkrCompatible(obj1->type, obj2->type);
1225 }
1226 bool DistinguishUtils::IsTkrCompatible(
1227     const TypeAndShape &x, const TypeAndShape &y) const {
1228   return x.type().IsTkCompatibleWith(y.type()) &&
1229       (x.attrs().test(TypeAndShape::Attr::AssumedRank) ||
1230           y.attrs().test(TypeAndShape::Attr::AssumedRank) ||
1231           x.Rank() == y.Rank());
1232 }
1233 
1234 // Return the argument at the given index, ignoring the passed arg
1235 const DummyArgument *DistinguishUtils::GetAtEffectivePosition(
1236     const DummyArguments &args, int index) const {
1237   for (const DummyArgument &arg : args) {
1238     if (!arg.pass) {
1239       if (index == 0) {
1240         return &arg;
1241       }
1242       --index;
1243     }
1244   }
1245   return nullptr;
1246 }
1247 
1248 // Return the passed-object dummy argument of this procedure, if any
1249 const DummyArgument *DistinguishUtils::GetPassArg(const Procedure &proc) const {
1250   for (const auto &arg : proc.dummyArguments) {
1251     if (arg.pass) {
1252       return &arg;
1253     }
1254   }
1255   return nullptr;
1256 }
1257 
1258 bool Distinguishable(const common::LanguageFeatureControl &features,
1259     const Procedure &x, const Procedure &y) {
1260   return DistinguishUtils{features}.Distinguishable(x, y);
1261 }
1262 
1263 bool DistinguishableOpOrAssign(const common::LanguageFeatureControl &features,
1264     const Procedure &x, const Procedure &y) {
1265   return DistinguishUtils{features}.DistinguishableOpOrAssign(x, y);
1266 }
1267 
1268 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(DummyArgument)
1269 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(DummyProcedure)
1270 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(FunctionResult)
1271 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(Procedure)
1272 } // namespace Fortran::evaluate::characteristics
1273 
1274 template class Fortran::common::Indirection<
1275     Fortran::evaluate::characteristics::Procedure, true>;
1276