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