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