xref: /llvm-project/flang/lib/Evaluate/characteristics.cpp (revision 5e8094bae50b1dd533ca0a20693d28a58b9c0d59)
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 { proc.interface() };
503             if (const semantics::Symbol * interfaceSymbol{interface.symbol()}) {
504               auto interface {
505                 CharacterizeProcedure(*interfaceSymbol, context, seenProcs)
506               };
507               if (interface && IsPointer(symbol)) {
508                 interface->attrs.reset(Procedure::Attr::Elemental);
509               }
510               return interface;
511             } else {
512               result.attrs.set(Procedure::Attr::ImplicitInterface);
513               const semantics::DeclTypeSpec *type{interface.type()};
514               if (symbol.test(semantics::Symbol::Flag::Subroutine)) {
515                 // ignore any implicit typing
516                 result.attrs.set(Procedure::Attr::Subroutine);
517               } else if (type) {
518                 if (auto resultType{DynamicType::From(*type)}) {
519                   result.functionResult = FunctionResult{*resultType};
520                 } else {
521                   return std::nullopt;
522                 }
523               } else if (symbol.test(semantics::Symbol::Flag::Function)) {
524                 return std::nullopt;
525               }
526               // The PASS name, if any, is not a characteristic.
527               return result;
528             }
529           },
530           [&](const semantics::ProcBindingDetails &binding) {
531             if (auto result{CharacterizeProcedure(
532                     binding.symbol(), context, seenProcs)}) {
533               if (binding.symbol().attrs().test(semantics::Attr::INTRINSIC)) {
534                 result->attrs.reset(Procedure::Attr::Elemental);
535               }
536               if (!symbol.attrs().test(semantics::Attr::NOPASS)) {
537                 auto passName{binding.passName()};
538                 for (auto &dummy : result->dummyArguments) {
539                   if (!passName || dummy.name.c_str() == *passName) {
540                     dummy.pass = true;
541                     break;
542                   }
543                 }
544               }
545               return result;
546             } else {
547               return std::optional<Procedure>{};
548             }
549           },
550           [&](const semantics::UseDetails &use) {
551             return CharacterizeProcedure(use.symbol(), context, seenProcs);
552           },
553           [](const semantics::UseErrorDetails &) {
554             // Ambiguous use-association will be handled later during symbol
555             // checks, ignore UseErrorDetails here without actual symbol usage.
556             return std::optional<Procedure>{};
557           },
558           [&](const semantics::HostAssocDetails &assoc) {
559             return CharacterizeProcedure(assoc.symbol(), context, seenProcs);
560           },
561           [&](const semantics::EntityDetails &) {
562             context.messages().Say(
563                 "Procedure '%s' is referenced before being sufficiently defined in a context where it must be so"_err_en_US,
564                 symbol.name());
565             return std::optional<Procedure>{};
566           },
567           [&](const semantics::SubprogramNameDetails &) {
568             context.messages().Say(
569                 "Procedure '%s' is referenced before being sufficiently defined in a context where it must be so"_err_en_US,
570                 symbol.name());
571             return std::optional<Procedure>{};
572           },
573           [&](const auto &) {
574             context.messages().Say(
575                 "'%s' is not a procedure"_err_en_US, symbol.name());
576             return std::optional<Procedure>{};
577           },
578       },
579       symbol.details());
580 }
581 
582 static std::optional<DummyProcedure> CharacterizeDummyProcedure(
583     const semantics::Symbol &symbol, FoldingContext &context,
584     semantics::UnorderedSymbolSet seenProcs) {
585   if (auto procedure{CharacterizeProcedure(symbol, context, seenProcs)}) {
586     // Dummy procedures may not be elemental.  Elemental dummy procedure
587     // interfaces are errors when the interface is not intrinsic, and that
588     // error is caught elsewhere.  Elemental intrinsic interfaces are
589     // made non-elemental.
590     procedure->attrs.reset(Procedure::Attr::Elemental);
591     DummyProcedure result{std::move(procedure.value())};
592     CopyAttrs<DummyProcedure, DummyProcedure::Attr>(symbol, result,
593         {
594             {semantics::Attr::OPTIONAL, DummyProcedure::Attr::Optional},
595             {semantics::Attr::POINTER, DummyProcedure::Attr::Pointer},
596         });
597     result.intent = GetIntent(symbol.attrs());
598     return result;
599   } else {
600     return std::nullopt;
601   }
602 }
603 
604 llvm::raw_ostream &DummyProcedure::Dump(llvm::raw_ostream &o) const {
605   attrs.Dump(o, EnumToString);
606   if (intent != common::Intent::Default) {
607     o << "INTENT(" << common::EnumToString(intent) << ')';
608   }
609   procedure.value().Dump(o);
610   return o;
611 }
612 
613 llvm::raw_ostream &AlternateReturn::Dump(llvm::raw_ostream &o) const {
614   return o << '*';
615 }
616 
617 DummyArgument::~DummyArgument() {}
618 
619 bool DummyArgument::operator==(const DummyArgument &that) const {
620   return u == that.u; // name and passed-object usage are not characteristics
621 }
622 
623 bool DummyArgument::IsCompatibleWith(
624     const DummyArgument &actual, std::string *whyNot) const {
625   if (const auto *ifaceData{std::get_if<DummyDataObject>(&u)}) {
626     if (const auto *actualData{std::get_if<DummyDataObject>(&actual.u)}) {
627       return ifaceData->IsCompatibleWith(*actualData, whyNot);
628     }
629     if (whyNot) {
630       *whyNot = "one dummy argument is an object, the other is not";
631     }
632   } else if (const auto *ifaceProc{std::get_if<DummyProcedure>(&u)}) {
633     if (const auto *actualProc{std::get_if<DummyProcedure>(&actual.u)}) {
634       return ifaceProc->IsCompatibleWith(*actualProc, whyNot);
635     }
636     if (whyNot) {
637       *whyNot = "one dummy argument is a procedure, the other is not";
638     }
639   } else {
640     CHECK(std::holds_alternative<AlternateReturn>(u));
641     if (std::holds_alternative<AlternateReturn>(actual.u)) {
642       return true;
643     }
644     if (whyNot) {
645       *whyNot = "one dummy argument is an alternate return, the other is not";
646     }
647   }
648   return false;
649 }
650 
651 static std::optional<DummyArgument> CharacterizeDummyArgument(
652     const semantics::Symbol &symbol, FoldingContext &context,
653     semantics::UnorderedSymbolSet seenProcs) {
654   auto name{symbol.name().ToString()};
655   if (symbol.has<semantics::ObjectEntityDetails>() ||
656       symbol.has<semantics::EntityDetails>()) {
657     if (auto obj{DummyDataObject::Characterize(symbol, context)}) {
658       return DummyArgument{std::move(name), std::move(obj.value())};
659     }
660   } else if (auto proc{
661                  CharacterizeDummyProcedure(symbol, context, seenProcs)}) {
662     return DummyArgument{std::move(name), std::move(proc.value())};
663   }
664   return std::nullopt;
665 }
666 
667 std::optional<DummyArgument> DummyArgument::FromActual(
668     std::string &&name, const Expr<SomeType> &expr, FoldingContext &context) {
669   return common::visit(
670       common::visitors{
671           [&](const BOZLiteralConstant &) {
672             return std::make_optional<DummyArgument>(std::move(name),
673                 DummyDataObject{
674                     TypeAndShape{DynamicType::TypelessIntrinsicArgument()}});
675           },
676           [&](const NullPointer &) {
677             return std::make_optional<DummyArgument>(std::move(name),
678                 DummyDataObject{
679                     TypeAndShape{DynamicType::TypelessIntrinsicArgument()}});
680           },
681           [&](const ProcedureDesignator &designator) {
682             if (auto proc{Procedure::Characterize(designator, context)}) {
683               return std::make_optional<DummyArgument>(
684                   std::move(name), DummyProcedure{std::move(*proc)});
685             } else {
686               return std::optional<DummyArgument>{};
687             }
688           },
689           [&](const ProcedureRef &call) {
690             if (auto proc{Procedure::Characterize(call, context)}) {
691               return std::make_optional<DummyArgument>(
692                   std::move(name), DummyProcedure{std::move(*proc)});
693             } else {
694               return std::optional<DummyArgument>{};
695             }
696           },
697           [&](const auto &) {
698             if (auto type{TypeAndShape::Characterize(expr, context)}) {
699               return std::make_optional<DummyArgument>(
700                   std::move(name), DummyDataObject{std::move(*type)});
701             } else {
702               return std::optional<DummyArgument>{};
703             }
704           },
705       },
706       expr.u);
707 }
708 
709 bool DummyArgument::IsOptional() const {
710   return common::visit(
711       common::visitors{
712           [](const DummyDataObject &data) {
713             return data.attrs.test(DummyDataObject::Attr::Optional);
714           },
715           [](const DummyProcedure &proc) {
716             return proc.attrs.test(DummyProcedure::Attr::Optional);
717           },
718           [](const AlternateReturn &) { return false; },
719       },
720       u);
721 }
722 
723 void DummyArgument::SetOptional(bool value) {
724   common::visit(common::visitors{
725                     [value](DummyDataObject &data) {
726                       data.attrs.set(DummyDataObject::Attr::Optional, value);
727                     },
728                     [value](DummyProcedure &proc) {
729                       proc.attrs.set(DummyProcedure::Attr::Optional, value);
730                     },
731                     [](AlternateReturn &) { DIE("cannot set optional"); },
732                 },
733       u);
734 }
735 
736 void DummyArgument::SetIntent(common::Intent intent) {
737   common::visit(common::visitors{
738                     [intent](DummyDataObject &data) { data.intent = intent; },
739                     [intent](DummyProcedure &proc) { proc.intent = intent; },
740                     [](AlternateReturn &) { DIE("cannot set intent"); },
741                 },
742       u);
743 }
744 
745 common::Intent DummyArgument::GetIntent() const {
746   return common::visit(
747       common::visitors{
748           [](const DummyDataObject &data) { return data.intent; },
749           [](const DummyProcedure &proc) { return proc.intent; },
750           [](const AlternateReturn &) -> common::Intent {
751             DIE("Alternate returns have no intent");
752           },
753       },
754       u);
755 }
756 
757 bool DummyArgument::CanBePassedViaImplicitInterface() const {
758   if (const auto *object{std::get_if<DummyDataObject>(&u)}) {
759     return object->CanBePassedViaImplicitInterface();
760   } else {
761     return true;
762   }
763 }
764 
765 bool DummyArgument::IsTypelessIntrinsicDummy() const {
766   const auto *argObj{std::get_if<characteristics::DummyDataObject>(&u)};
767   return argObj && argObj->type.type().IsTypelessIntrinsicArgument();
768 }
769 
770 llvm::raw_ostream &DummyArgument::Dump(llvm::raw_ostream &o) const {
771   if (!name.empty()) {
772     o << name << '=';
773   }
774   if (pass) {
775     o << " PASS";
776   }
777   common::visit([&](const auto &x) { x.Dump(o); }, u);
778   return o;
779 }
780 
781 FunctionResult::FunctionResult(DynamicType t) : u{TypeAndShape{t}} {}
782 FunctionResult::FunctionResult(TypeAndShape &&t) : u{std::move(t)} {}
783 FunctionResult::FunctionResult(Procedure &&p) : u{std::move(p)} {}
784 FunctionResult::~FunctionResult() {}
785 
786 bool FunctionResult::operator==(const FunctionResult &that) const {
787   return attrs == that.attrs && u == that.u;
788 }
789 
790 static std::optional<FunctionResult> CharacterizeFunctionResult(
791     const semantics::Symbol &symbol, FoldingContext &context,
792     semantics::UnorderedSymbolSet seenProcs) {
793   if (symbol.has<semantics::ObjectEntityDetails>()) {
794     if (auto type{TypeAndShape::Characterize(symbol, context)}) {
795       FunctionResult result{std::move(*type)};
796       CopyAttrs<FunctionResult, FunctionResult::Attr>(symbol, result,
797           {
798               {semantics::Attr::ALLOCATABLE, FunctionResult::Attr::Allocatable},
799               {semantics::Attr::CONTIGUOUS, FunctionResult::Attr::Contiguous},
800               {semantics::Attr::POINTER, FunctionResult::Attr::Pointer},
801           });
802       return result;
803     }
804   } else if (auto maybeProc{
805                  CharacterizeProcedure(symbol, context, seenProcs)}) {
806     FunctionResult result{std::move(*maybeProc)};
807     result.attrs.set(FunctionResult::Attr::Pointer);
808     return result;
809   }
810   return std::nullopt;
811 }
812 
813 std::optional<FunctionResult> FunctionResult::Characterize(
814     const Symbol &symbol, FoldingContext &context) {
815   semantics::UnorderedSymbolSet seenProcs;
816   return CharacterizeFunctionResult(symbol, context, seenProcs);
817 }
818 
819 bool FunctionResult::IsAssumedLengthCharacter() const {
820   if (const auto *ts{std::get_if<TypeAndShape>(&u)}) {
821     return ts->type().IsAssumedLengthCharacter();
822   } else {
823     return false;
824   }
825 }
826 
827 bool FunctionResult::CanBeReturnedViaImplicitInterface() const {
828   if (attrs.test(Attr::Pointer) || attrs.test(Attr::Allocatable)) {
829     return false; // 15.4.2.2(4)(b)
830   } else if (const auto *typeAndShape{GetTypeAndShape()}) {
831     if (typeAndShape->Rank() > 0) {
832       return false; // 15.4.2.2(4)(a)
833     } else {
834       const DynamicType &type{typeAndShape->type()};
835       switch (type.category()) {
836       case TypeCategory::Character:
837         if (type.knownLength()) {
838           return true;
839         } else if (const auto *param{type.charLengthParamValue()}) {
840           if (const auto &expr{param->GetExplicit()}) {
841             return IsConstantExpr(*expr); // 15.4.2.2(4)(c)
842           } else if (param->isAssumed()) {
843             return true;
844           }
845         }
846         return false;
847       case TypeCategory::Derived:
848         if (!type.IsPolymorphic()) {
849           const auto &spec{type.GetDerivedTypeSpec()};
850           for (const auto &pair : spec.parameters()) {
851             if (const auto &expr{pair.second.GetExplicit()}) {
852               if (!IsConstantExpr(*expr)) {
853                 return false; // 15.4.2.2(4)(c)
854               }
855             }
856           }
857           return true;
858         }
859         return false;
860       default:
861         return true;
862       }
863     }
864   } else {
865     return false; // 15.4.2.2(4)(b) - procedure pointer
866   }
867 }
868 
869 bool FunctionResult::IsCompatibleWith(
870     const FunctionResult &actual, std::string *whyNot) const {
871   Attrs actualAttrs{actual.attrs};
872   if (!attrs.test(Attr::Contiguous)) {
873     actualAttrs.reset(Attr::Contiguous);
874   }
875   if (attrs != actualAttrs) {
876     if (whyNot) {
877       *whyNot = "function results have incompatible attributes";
878     }
879   } else if (const auto *ifaceTypeShape{std::get_if<TypeAndShape>(&u)}) {
880     if (const auto *actualTypeShape{std::get_if<TypeAndShape>(&actual.u)}) {
881       if (ifaceTypeShape->Rank() != actualTypeShape->Rank()) {
882         if (whyNot) {
883           *whyNot = "function results have distinct ranks";
884         }
885       } else if (!attrs.test(Attr::Allocatable) && !attrs.test(Attr::Pointer) &&
886           ifaceTypeShape->shape() != actualTypeShape->shape()) {
887         if (whyNot) {
888           *whyNot = "function results have distinct extents";
889         }
890       } else if (!ifaceTypeShape->type().IsTkCompatibleWith(
891                      actualTypeShape->type())) {
892         if (whyNot) {
893           *whyNot = "function results have incompatible types: "s +
894               ifaceTypeShape->type().AsFortran() + " vs "s +
895               actualTypeShape->type().AsFortran();
896         }
897       } else {
898         return true;
899       }
900     } else {
901       if (whyNot) {
902         *whyNot = "function result type and shape are not known";
903       }
904     }
905   } else {
906     const auto *ifaceProc{std::get_if<CopyableIndirection<Procedure>>(&u)};
907     CHECK(ifaceProc != nullptr);
908     if (const auto *actualProc{
909             std::get_if<CopyableIndirection<Procedure>>(&actual.u)}) {
910       if (ifaceProc->value().IsCompatibleWith(actualProc->value(), whyNot)) {
911         return true;
912       }
913       if (whyNot) {
914         *whyNot =
915             "function results are incompatible procedure pointers: "s + *whyNot;
916       }
917     } else {
918       if (whyNot) {
919         *whyNot =
920             "one function result is a procedure pointer, the other is not";
921       }
922     }
923   }
924   return false;
925 }
926 
927 llvm::raw_ostream &FunctionResult::Dump(llvm::raw_ostream &o) const {
928   attrs.Dump(o, EnumToString);
929   common::visit(common::visitors{
930                     [&](const TypeAndShape &ts) { ts.Dump(o); },
931                     [&](const CopyableIndirection<Procedure> &p) {
932                       p.value().Dump(o << " procedure(") << ')';
933                     },
934                 },
935       u);
936   return o;
937 }
938 
939 Procedure::Procedure(FunctionResult &&fr, DummyArguments &&args, Attrs a)
940     : functionResult{std::move(fr)}, dummyArguments{std::move(args)}, attrs{a} {
941 }
942 Procedure::Procedure(DummyArguments &&args, Attrs a)
943     : dummyArguments{std::move(args)}, attrs{a} {}
944 Procedure::~Procedure() {}
945 
946 bool Procedure::operator==(const Procedure &that) const {
947   return attrs == that.attrs && functionResult == that.functionResult &&
948       dummyArguments == that.dummyArguments;
949 }
950 
951 bool Procedure::IsCompatibleWith(const Procedure &actual, std::string *whyNot,
952     const SpecificIntrinsic *specificIntrinsic) const {
953   // 15.5.2.9(1): if dummy is not pure, actual need not be.
954   // Ditto with elemental.
955   Attrs actualAttrs{actual.attrs};
956   if (!attrs.test(Attr::Pure)) {
957     actualAttrs.reset(Attr::Pure);
958   }
959   if (!attrs.test(Attr::Elemental) && specificIntrinsic) {
960     actualAttrs.reset(Attr::Elemental);
961   }
962   Attrs differences{attrs ^ actualAttrs};
963   differences.reset(Attr::Subroutine); // dealt with specifically later
964   if (!differences.empty()) {
965     if (whyNot) {
966       auto sep{": "s};
967       *whyNot = "incompatible procedure attributes";
968       differences.IterateOverMembers([&](Attr x) {
969         *whyNot += sep + EnumToString(x);
970         sep = ", ";
971       });
972     }
973   } else if ((IsFunction() && actual.IsSubroutine()) ||
974       (IsSubroutine() && actual.IsFunction())) {
975     if (whyNot) {
976       *whyNot =
977           "incompatible procedures: one is a function, the other a subroutine";
978     }
979   } else if (functionResult && actual.functionResult &&
980       !functionResult->IsCompatibleWith(*actual.functionResult, whyNot)) {
981   } else if (dummyArguments.size() != actual.dummyArguments.size()) {
982     if (whyNot) {
983       *whyNot = "distinct numbers of dummy arguments";
984     }
985   } else {
986     for (std::size_t j{0}; j < dummyArguments.size(); ++j) {
987       if (!dummyArguments[j].IsCompatibleWith(
988               actual.dummyArguments[j], whyNot)) {
989         if (whyNot) {
990           *whyNot = "incompatible dummy argument #"s + std::to_string(j + 1) +
991               ": "s + *whyNot;
992         }
993         return false;
994       }
995     }
996     return true;
997   }
998   return false;
999 }
1000 
1001 int Procedure::FindPassIndex(std::optional<parser::CharBlock> name) const {
1002   int argCount{static_cast<int>(dummyArguments.size())};
1003   int index{0};
1004   if (name) {
1005     while (index < argCount && *name != dummyArguments[index].name.c_str()) {
1006       ++index;
1007     }
1008   }
1009   CHECK(index < argCount);
1010   return index;
1011 }
1012 
1013 bool Procedure::CanOverride(
1014     const Procedure &that, std::optional<int> passIndex) const {
1015   // A pure procedure may override an impure one (7.5.7.3(2))
1016   if ((that.attrs.test(Attr::Pure) && !attrs.test(Attr::Pure)) ||
1017       that.attrs.test(Attr::Elemental) != attrs.test(Attr::Elemental) ||
1018       functionResult != that.functionResult) {
1019     return false;
1020   }
1021   int argCount{static_cast<int>(dummyArguments.size())};
1022   if (argCount != static_cast<int>(that.dummyArguments.size())) {
1023     return false;
1024   }
1025   for (int j{0}; j < argCount; ++j) {
1026     if ((!passIndex || j != *passIndex) &&
1027         dummyArguments[j] != that.dummyArguments[j]) {
1028       return false;
1029     }
1030   }
1031   return true;
1032 }
1033 
1034 std::optional<Procedure> Procedure::Characterize(
1035     const semantics::Symbol &original, FoldingContext &context) {
1036   semantics::UnorderedSymbolSet seenProcs;
1037   return CharacterizeProcedure(original, context, seenProcs);
1038 }
1039 
1040 std::optional<Procedure> Procedure::Characterize(
1041     const ProcedureDesignator &proc, FoldingContext &context) {
1042   if (const auto *symbol{proc.GetSymbol()}) {
1043     if (auto result{
1044             characteristics::Procedure::Characterize(*symbol, context)}) {
1045       return result;
1046     }
1047   } else if (const auto *intrinsic{proc.GetSpecificIntrinsic()}) {
1048     return intrinsic->characteristics.value();
1049   }
1050   return std::nullopt;
1051 }
1052 
1053 std::optional<Procedure> Procedure::Characterize(
1054     const ProcedureRef &ref, FoldingContext &context) {
1055   if (auto callee{Characterize(ref.proc(), context)}) {
1056     if (callee->functionResult) {
1057       if (const Procedure *
1058           proc{callee->functionResult->IsProcedurePointer()}) {
1059         return {*proc};
1060       }
1061     }
1062   }
1063   return std::nullopt;
1064 }
1065 
1066 bool Procedure::CanBeCalledViaImplicitInterface() const {
1067   // TODO: Pass back information on why we return false
1068   if (attrs.test(Attr::Elemental) || attrs.test(Attr::BindC)) {
1069     return false; // 15.4.2.2(5,6)
1070   } else if (IsFunction() &&
1071       !functionResult->CanBeReturnedViaImplicitInterface()) {
1072     return false;
1073   } else {
1074     for (const DummyArgument &arg : dummyArguments) {
1075       if (!arg.CanBePassedViaImplicitInterface()) {
1076         return false;
1077       }
1078     }
1079     return true;
1080   }
1081 }
1082 
1083 llvm::raw_ostream &Procedure::Dump(llvm::raw_ostream &o) const {
1084   attrs.Dump(o, EnumToString);
1085   if (functionResult) {
1086     functionResult->Dump(o << "TYPE(") << ") FUNCTION";
1087   } else if (attrs.test(Attr::Subroutine)) {
1088     o << "SUBROUTINE";
1089   } else {
1090     o << "EXTERNAL";
1091   }
1092   char sep{'('};
1093   for (const auto &dummy : dummyArguments) {
1094     dummy.Dump(o << sep);
1095     sep = ',';
1096   }
1097   return o << (sep == '(' ? "()" : ")");
1098 }
1099 
1100 // Utility class to determine if Procedures, etc. are distinguishable
1101 class DistinguishUtils {
1102 public:
1103   explicit DistinguishUtils(const common::LanguageFeatureControl &features)
1104       : features_{features} {}
1105 
1106   // Are these procedures distinguishable for a generic name?
1107   bool Distinguishable(const Procedure &, const Procedure &) const;
1108   // Are these procedures distinguishable for a generic operator or assignment?
1109   bool DistinguishableOpOrAssign(const Procedure &, const Procedure &) const;
1110 
1111 private:
1112   struct CountDummyProcedures {
1113     CountDummyProcedures(const DummyArguments &args) {
1114       for (const DummyArgument &arg : args) {
1115         if (std::holds_alternative<DummyProcedure>(arg.u)) {
1116           total += 1;
1117           notOptional += !arg.IsOptional();
1118         }
1119       }
1120     }
1121     int total{0};
1122     int notOptional{0};
1123   };
1124 
1125   bool Rule3Distinguishable(const Procedure &, const Procedure &) const;
1126   const DummyArgument *Rule1DistinguishingArg(
1127       const DummyArguments &, const DummyArguments &) const;
1128   int FindFirstToDistinguishByPosition(
1129       const DummyArguments &, const DummyArguments &) const;
1130   int FindLastToDistinguishByName(
1131       const DummyArguments &, const DummyArguments &) const;
1132   int CountCompatibleWith(const DummyArgument &, const DummyArguments &) const;
1133   int CountNotDistinguishableFrom(
1134       const DummyArgument &, const DummyArguments &) const;
1135   bool Distinguishable(const DummyArgument &, const DummyArgument &) const;
1136   bool Distinguishable(const DummyDataObject &, const DummyDataObject &) const;
1137   bool Distinguishable(const DummyProcedure &, const DummyProcedure &) const;
1138   bool Distinguishable(const FunctionResult &, const FunctionResult &) const;
1139   bool Distinguishable(const TypeAndShape &, const TypeAndShape &) const;
1140   bool IsTkrCompatible(const DummyArgument &, const DummyArgument &) const;
1141   bool IsTkrCompatible(const TypeAndShape &, const TypeAndShape &) const;
1142   const DummyArgument *GetAtEffectivePosition(
1143       const DummyArguments &, int) const;
1144   const DummyArgument *GetPassArg(const Procedure &) const;
1145 
1146   const common::LanguageFeatureControl &features_;
1147 };
1148 
1149 // Simpler distinguishability rules for operators and assignment
1150 bool DistinguishUtils::DistinguishableOpOrAssign(
1151     const Procedure &proc1, const Procedure &proc2) const {
1152   auto &args1{proc1.dummyArguments};
1153   auto &args2{proc2.dummyArguments};
1154   if (args1.size() != args2.size()) {
1155     return true; // C1511: distinguishable based on number of arguments
1156   }
1157   for (std::size_t i{0}; i < args1.size(); ++i) {
1158     if (Distinguishable(args1[i], args2[i])) {
1159       return true; // C1511, C1512: distinguishable based on this arg
1160     }
1161   }
1162   return false;
1163 }
1164 
1165 bool DistinguishUtils::Distinguishable(
1166     const Procedure &proc1, const Procedure &proc2) const {
1167   auto &args1{proc1.dummyArguments};
1168   auto &args2{proc2.dummyArguments};
1169   auto count1{CountDummyProcedures(args1)};
1170   auto count2{CountDummyProcedures(args2)};
1171   if (count1.notOptional > count2.total || count2.notOptional > count1.total) {
1172     return true; // distinguishable based on C1514 rule 2
1173   }
1174   if (Rule3Distinguishable(proc1, proc2)) {
1175     return true; // distinguishable based on C1514 rule 3
1176   }
1177   if (Rule1DistinguishingArg(args1, args2)) {
1178     return true; // distinguishable based on C1514 rule 1
1179   }
1180   int pos1{FindFirstToDistinguishByPosition(args1, args2)};
1181   int name1{FindLastToDistinguishByName(args1, args2)};
1182   if (pos1 >= 0 && pos1 <= name1) {
1183     return true; // distinguishable based on C1514 rule 4
1184   }
1185   int pos2{FindFirstToDistinguishByPosition(args2, args1)};
1186   int name2{FindLastToDistinguishByName(args2, args1)};
1187   if (pos2 >= 0 && pos2 <= name2) {
1188     return true; // distinguishable based on C1514 rule 4
1189   }
1190   return false;
1191 }
1192 
1193 // C1514 rule 3: Procedures are distinguishable if both have a passed-object
1194 // dummy argument and those are distinguishable.
1195 bool DistinguishUtils::Rule3Distinguishable(
1196     const Procedure &proc1, const Procedure &proc2) const {
1197   const DummyArgument *pass1{GetPassArg(proc1)};
1198   const DummyArgument *pass2{GetPassArg(proc2)};
1199   return pass1 && pass2 && Distinguishable(*pass1, *pass2);
1200 }
1201 
1202 // Find a non-passed-object dummy data object in one of the argument lists
1203 // that satisfies C1514 rule 1. I.e. x such that:
1204 // - m is the number of dummy data objects in one that are nonoptional,
1205 //   are not passed-object, that x is TKR compatible with
1206 // - n is the number of non-passed-object dummy data objects, in the other
1207 //   that are not distinguishable from x
1208 // - m is greater than n
1209 const DummyArgument *DistinguishUtils::Rule1DistinguishingArg(
1210     const DummyArguments &args1, const DummyArguments &args2) const {
1211   auto size1{args1.size()};
1212   auto size2{args2.size()};
1213   for (std::size_t i{0}; i < size1 + size2; ++i) {
1214     const DummyArgument &x{i < size1 ? args1[i] : args2[i - size1]};
1215     if (!x.pass && std::holds_alternative<DummyDataObject>(x.u)) {
1216       if (CountCompatibleWith(x, args1) >
1217               CountNotDistinguishableFrom(x, args2) ||
1218           CountCompatibleWith(x, args2) >
1219               CountNotDistinguishableFrom(x, args1)) {
1220         return &x;
1221       }
1222     }
1223   }
1224   return nullptr;
1225 }
1226 
1227 // Find the index of the first nonoptional non-passed-object dummy argument
1228 // in args1 at an effective position such that either:
1229 // - args2 has no dummy argument at that effective position
1230 // - the dummy argument at that position is distinguishable from it
1231 int DistinguishUtils::FindFirstToDistinguishByPosition(
1232     const DummyArguments &args1, const DummyArguments &args2) const {
1233   int effective{0}; // position of arg1 in list, ignoring passed arg
1234   for (std::size_t i{0}; i < args1.size(); ++i) {
1235     const DummyArgument &arg1{args1.at(i)};
1236     if (!arg1.pass && !arg1.IsOptional()) {
1237       const DummyArgument *arg2{GetAtEffectivePosition(args2, effective)};
1238       if (!arg2 || Distinguishable(arg1, *arg2)) {
1239         return i;
1240       }
1241     }
1242     effective += !arg1.pass;
1243   }
1244   return -1;
1245 }
1246 
1247 // Find the index of the last nonoptional non-passed-object dummy argument
1248 // in args1 whose name is such that either:
1249 // - args2 has no dummy argument with that name
1250 // - the dummy argument with that name is distinguishable from it
1251 int DistinguishUtils::FindLastToDistinguishByName(
1252     const DummyArguments &args1, const DummyArguments &args2) const {
1253   std::map<std::string, const DummyArgument *> nameToArg;
1254   for (const auto &arg2 : args2) {
1255     nameToArg.emplace(arg2.name, &arg2);
1256   }
1257   for (int i = args1.size() - 1; i >= 0; --i) {
1258     const DummyArgument &arg1{args1.at(i)};
1259     if (!arg1.pass && !arg1.IsOptional()) {
1260       auto it{nameToArg.find(arg1.name)};
1261       if (it == nameToArg.end() || Distinguishable(arg1, *it->second)) {
1262         return i;
1263       }
1264     }
1265   }
1266   return -1;
1267 }
1268 
1269 // Count the dummy data objects in args that are nonoptional, are not
1270 // passed-object, and that x is TKR compatible with
1271 int DistinguishUtils::CountCompatibleWith(
1272     const DummyArgument &x, const DummyArguments &args) const {
1273   return std::count_if(args.begin(), args.end(), [&](const DummyArgument &y) {
1274     return !y.pass && !y.IsOptional() && IsTkrCompatible(x, y);
1275   });
1276 }
1277 
1278 // Return the number of dummy data objects in args that are not
1279 // distinguishable from x and not passed-object.
1280 int DistinguishUtils::CountNotDistinguishableFrom(
1281     const DummyArgument &x, const DummyArguments &args) const {
1282   return std::count_if(args.begin(), args.end(), [&](const DummyArgument &y) {
1283     return !y.pass && std::holds_alternative<DummyDataObject>(y.u) &&
1284         !Distinguishable(y, x);
1285   });
1286 }
1287 
1288 bool DistinguishUtils::Distinguishable(
1289     const DummyArgument &x, const DummyArgument &y) const {
1290   if (x.u.index() != y.u.index()) {
1291     return true; // different kind: data/proc/alt-return
1292   }
1293   return common::visit(
1294       common::visitors{
1295           [&](const DummyDataObject &z) {
1296             return Distinguishable(z, std::get<DummyDataObject>(y.u));
1297           },
1298           [&](const DummyProcedure &z) {
1299             return Distinguishable(z, std::get<DummyProcedure>(y.u));
1300           },
1301           [&](const AlternateReturn &) { return false; },
1302       },
1303       x.u);
1304 }
1305 
1306 bool DistinguishUtils::Distinguishable(
1307     const DummyDataObject &x, const DummyDataObject &y) const {
1308   using Attr = DummyDataObject::Attr;
1309   if (Distinguishable(x.type, y.type)) {
1310     return true;
1311   } else if (x.attrs.test(Attr::Allocatable) && y.attrs.test(Attr::Pointer) &&
1312       y.intent != common::Intent::In) {
1313     return true;
1314   } else if (y.attrs.test(Attr::Allocatable) && x.attrs.test(Attr::Pointer) &&
1315       x.intent != common::Intent::In) {
1316     return true;
1317   } else if (features_.IsEnabled(
1318                  common::LanguageFeature::DistinguishableSpecifics) &&
1319       (x.attrs.test(Attr::Allocatable) || x.attrs.test(Attr::Pointer)) &&
1320       (y.attrs.test(Attr::Allocatable) || y.attrs.test(Attr::Pointer)) &&
1321       (x.type.type().IsUnlimitedPolymorphic() !=
1322               y.type.type().IsUnlimitedPolymorphic() ||
1323           x.type.type().IsPolymorphic() != y.type.type().IsPolymorphic())) {
1324     // Extension: Per 15.5.2.5(2), an allocatable/pointer dummy and its
1325     // corresponding actual argument must both or neither be polymorphic,
1326     // and must both or neither be unlimited polymorphic.  So when exactly
1327     // one of two dummy arguments is polymorphic or unlimited polymorphic,
1328     // any actual argument that is admissible to one of them cannot also match
1329     // the other one.
1330     return true;
1331   } else {
1332     return false;
1333   }
1334 }
1335 
1336 bool DistinguishUtils::Distinguishable(
1337     const DummyProcedure &x, const DummyProcedure &y) const {
1338   const Procedure &xProc{x.procedure.value()};
1339   const Procedure &yProc{y.procedure.value()};
1340   if (Distinguishable(xProc, yProc)) {
1341     return true;
1342   } else {
1343     const std::optional<FunctionResult> &xResult{xProc.functionResult};
1344     const std::optional<FunctionResult> &yResult{yProc.functionResult};
1345     return xResult ? !yResult || Distinguishable(*xResult, *yResult)
1346                    : yResult.has_value();
1347   }
1348 }
1349 
1350 bool DistinguishUtils::Distinguishable(
1351     const FunctionResult &x, const FunctionResult &y) const {
1352   if (x.u.index() != y.u.index()) {
1353     return true; // one is data object, one is procedure
1354   }
1355   return common::visit(
1356       common::visitors{
1357           [&](const TypeAndShape &z) {
1358             return Distinguishable(z, std::get<TypeAndShape>(y.u));
1359           },
1360           [&](const CopyableIndirection<Procedure> &z) {
1361             return Distinguishable(z.value(),
1362                 std::get<CopyableIndirection<Procedure>>(y.u).value());
1363           },
1364       },
1365       x.u);
1366 }
1367 
1368 bool DistinguishUtils::Distinguishable(
1369     const TypeAndShape &x, const TypeAndShape &y) const {
1370   return !IsTkrCompatible(x, y) && !IsTkrCompatible(y, x);
1371 }
1372 
1373 // Compatibility based on type, kind, and rank
1374 bool DistinguishUtils::IsTkrCompatible(
1375     const DummyArgument &x, const DummyArgument &y) const {
1376   const auto *obj1{std::get_if<DummyDataObject>(&x.u)};
1377   const auto *obj2{std::get_if<DummyDataObject>(&y.u)};
1378   return obj1 && obj2 && IsTkrCompatible(obj1->type, obj2->type);
1379 }
1380 bool DistinguishUtils::IsTkrCompatible(
1381     const TypeAndShape &x, const TypeAndShape &y) const {
1382   return x.type().IsTkCompatibleWith(y.type()) &&
1383       (x.attrs().test(TypeAndShape::Attr::AssumedRank) ||
1384           y.attrs().test(TypeAndShape::Attr::AssumedRank) ||
1385           x.Rank() == y.Rank());
1386 }
1387 
1388 // Return the argument at the given index, ignoring the passed arg
1389 const DummyArgument *DistinguishUtils::GetAtEffectivePosition(
1390     const DummyArguments &args, int index) const {
1391   for (const DummyArgument &arg : args) {
1392     if (!arg.pass) {
1393       if (index == 0) {
1394         return &arg;
1395       }
1396       --index;
1397     }
1398   }
1399   return nullptr;
1400 }
1401 
1402 // Return the passed-object dummy argument of this procedure, if any
1403 const DummyArgument *DistinguishUtils::GetPassArg(const Procedure &proc) const {
1404   for (const auto &arg : proc.dummyArguments) {
1405     if (arg.pass) {
1406       return &arg;
1407     }
1408   }
1409   return nullptr;
1410 }
1411 
1412 bool Distinguishable(const common::LanguageFeatureControl &features,
1413     const Procedure &x, const Procedure &y) {
1414   return DistinguishUtils{features}.Distinguishable(x, y);
1415 }
1416 
1417 bool DistinguishableOpOrAssign(const common::LanguageFeatureControl &features,
1418     const Procedure &x, const Procedure &y) {
1419   return DistinguishUtils{features}.DistinguishableOpOrAssign(x, y);
1420 }
1421 
1422 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(DummyArgument)
1423 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(DummyProcedure)
1424 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(FunctionResult)
1425 DEFINE_DEFAULT_CONSTRUCTORS_AND_ASSIGNMENTS(Procedure)
1426 } // namespace Fortran::evaluate::characteristics
1427 
1428 template class Fortran::common::Indirection<
1429     Fortran::evaluate::characteristics::Procedure, true>;
1430