xref: /llvm-project/flang/lib/Evaluate/type.cpp (revision 8c1270740f6bf659e5fbf556c1145ddaa7aa5366)
1 //===-- lib/Evaluate/type.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/type.h"
10 #include "flang/Common/idioms.h"
11 #include "flang/Evaluate/expression.h"
12 #include "flang/Evaluate/fold.h"
13 #include "flang/Evaluate/target.h"
14 #include "flang/Parser/characters.h"
15 #include "flang/Semantics/scope.h"
16 #include "flang/Semantics/symbol.h"
17 #include "flang/Semantics/tools.h"
18 #include "flang/Semantics/type.h"
19 #include <algorithm>
20 #include <optional>
21 #include <string>
22 
23 // IsDescriptor() predicate: true when a symbol is implemented
24 // at runtime with a descriptor.
25 namespace Fortran::semantics {
26 
27 static bool IsDescriptor(const DeclTypeSpec *type) {
28   if (type) {
29     if (auto dynamicType{evaluate::DynamicType::From(*type)}) {
30       return dynamicType->RequiresDescriptor();
31     }
32   }
33   return false;
34 }
35 
36 static bool IsDescriptor(const ObjectEntityDetails &details) {
37   if (IsDescriptor(details.type()) || details.IsAssumedRank()) {
38     return true;
39   }
40   std::size_t j{0};
41   for (const ShapeSpec &shapeSpec : details.shape()) {
42     ++j;
43     if (const auto &lb{shapeSpec.lbound().GetExplicit()};
44         !lb || !IsConstantExpr(*lb)) {
45       return true;
46     }
47     if (const auto &ub{shapeSpec.ubound().GetExplicit()}) {
48       if (!IsConstantExpr(*ub)) {
49         return true;
50       }
51     } else if (j == details.shape().size() && details.isDummy()) {
52       // assumed size array
53     } else {
54       return true;
55     }
56   }
57   return false;
58 }
59 
60 bool IsDescriptor(const Symbol &symbol) {
61   return common::visit(
62       common::visitors{
63           [&](const ObjectEntityDetails &d) {
64             return IsAllocatableOrPointer(symbol) || IsDescriptor(d);
65           },
66           [&](const ProcEntityDetails &d) { return false; },
67           [&](const EntityDetails &d) { return IsDescriptor(d.type()); },
68           [](const AssocEntityDetails &d) {
69             if (const auto &expr{d.expr()}) {
70               if (expr->Rank() > 0) {
71                 return true;
72               }
73               if (const auto dynamicType{expr->GetType()}) {
74                 if (dynamicType->RequiresDescriptor()) {
75                   return true;
76                 }
77               }
78             }
79             return false;
80           },
81           [](const SubprogramDetails &d) {
82             return d.isFunction() && IsDescriptor(d.result());
83           },
84           [](const UseDetails &d) { return IsDescriptor(d.symbol()); },
85           [](const HostAssocDetails &d) { return IsDescriptor(d.symbol()); },
86           [](const auto &) { return false; },
87       },
88       symbol.details());
89 }
90 
91 bool IsPassedViaDescriptor(const Symbol &symbol) {
92   if (!IsDescriptor(symbol)) {
93     return false;
94   }
95   if (IsAllocatableOrPointer(symbol)) {
96     return true;
97   }
98   if (const auto *object{
99           symbol.GetUltimate().detailsIf<ObjectEntityDetails>()}) {
100     if (object->isDummy()) {
101       if (object->type() &&
102           object->type()->category() == DeclTypeSpec::Character) {
103         return false;
104       }
105       if (object->IsAssumedSize()) {
106         return false;
107       }
108       bool isExplicitShape{true};
109       for (const ShapeSpec &shapeSpec : object->shape()) {
110         if (!shapeSpec.lbound().GetExplicit() ||
111             !shapeSpec.ubound().GetExplicit()) {
112           isExplicitShape = false;
113           break;
114         }
115       }
116       if (isExplicitShape) {
117         return false; // explicit shape but non-constant bounds
118       }
119     }
120   }
121   return true;
122 }
123 } // namespace Fortran::semantics
124 
125 namespace Fortran::evaluate {
126 
127 DynamicType::DynamicType(int k, const semantics::ParamValue &pv)
128     : category_{TypeCategory::Character}, kind_{k} {
129   CHECK(IsValidKindOfIntrinsicType(category_, kind_));
130   if (auto n{ToInt64(pv.GetExplicit())}) {
131     knownLength_ = *n > 0 ? *n : 0;
132   } else {
133     charLengthParamValue_ = &pv;
134   }
135 }
136 
137 template <typename A> inline bool PointeeComparison(const A *x, const A *y) {
138   return x == y || (x && y && *x == *y);
139 }
140 
141 bool DynamicType::operator==(const DynamicType &that) const {
142   return category_ == that.category_ && kind_ == that.kind_ &&
143       PointeeComparison(charLengthParamValue_, that.charLengthParamValue_) &&
144       knownLength().has_value() == that.knownLength().has_value() &&
145       (!knownLength() || *knownLength() == *that.knownLength()) &&
146       PointeeComparison(derived_, that.derived_);
147 }
148 
149 std::optional<Expr<SubscriptInteger>> DynamicType::GetCharLength() const {
150   if (category_ == TypeCategory::Character) {
151     if (knownLength()) {
152       return AsExpr(Constant<SubscriptInteger>(*knownLength()));
153     } else if (charLengthParamValue_) {
154       if (auto length{charLengthParamValue_->GetExplicit()}) {
155         return ConvertToType<SubscriptInteger>(std::move(*length));
156       }
157     }
158   }
159   return std::nullopt;
160 }
161 
162 std::size_t DynamicType::GetAlignment(
163     const TargetCharacteristics &targetCharacteristics) const {
164   if (category_ == TypeCategory::Derived) {
165     switch (GetDerivedTypeSpec().category()) {
166       SWITCH_COVERS_ALL_CASES
167     case semantics::DerivedTypeSpec::Category::DerivedType:
168       if (derived_ && derived_->scope()) {
169         return derived_->scope()->alignment().value_or(1);
170       }
171       break;
172     case semantics::DerivedTypeSpec::Category::IntrinsicVector:
173     case semantics::DerivedTypeSpec::Category::PairVector:
174     case semantics::DerivedTypeSpec::Category::QuadVector:
175       if (derived_ && derived_->scope()) {
176         return derived_->scope()->size();
177       } else {
178         common::die("Missing scope for Vector type.");
179       }
180     }
181   } else {
182     return targetCharacteristics.GetAlignment(category_, kind());
183   }
184   return 1; // needs to be after switch to dodge a bogus gcc warning
185 }
186 
187 std::optional<Expr<SubscriptInteger>> DynamicType::MeasureSizeInBytes(
188     FoldingContext &context, bool aligned,
189     std::optional<std::int64_t> charLength) const {
190   switch (category_) {
191   case TypeCategory::Integer:
192   case TypeCategory::Real:
193   case TypeCategory::Complex:
194   case TypeCategory::Logical:
195     return Expr<SubscriptInteger>{
196         context.targetCharacteristics().GetByteSize(category_, kind())};
197   case TypeCategory::Character:
198     if (auto len{charLength ? Expr<SubscriptInteger>{Constant<SubscriptInteger>{
199                                   *charLength}}
200                             : GetCharLength()}) {
201       return Fold(context,
202           Expr<SubscriptInteger>{
203               context.targetCharacteristics().GetByteSize(category_, kind())} *
204               std::move(*len));
205     }
206     break;
207   case TypeCategory::Derived:
208     if (!IsPolymorphic() && derived_ && derived_->scope()) {
209       auto size{derived_->scope()->size()};
210       auto align{aligned ? derived_->scope()->alignment().value_or(0) : 0};
211       auto alignedSize{align > 0 ? ((size + align - 1) / align) * align : size};
212       return Expr<SubscriptInteger>{
213           static_cast<ConstantSubscript>(alignedSize)};
214     }
215     break;
216   }
217   return std::nullopt;
218 }
219 
220 bool DynamicType::IsAssumedLengthCharacter() const {
221   return category_ == TypeCategory::Character && charLengthParamValue_ &&
222       charLengthParamValue_->isAssumed();
223 }
224 
225 bool DynamicType::IsNonConstantLengthCharacter() const {
226   if (category_ != TypeCategory::Character) {
227     return false;
228   } else if (knownLength()) {
229     return false;
230   } else if (!charLengthParamValue_) {
231     return true;
232   } else if (const auto &expr{charLengthParamValue_->GetExplicit()}) {
233     return !IsConstantExpr(*expr);
234   } else {
235     return true;
236   }
237 }
238 
239 bool DynamicType::IsTypelessIntrinsicArgument() const {
240   return category_ == TypeCategory::Integer && kind_ == TypelessKind;
241 }
242 
243 const semantics::DerivedTypeSpec *GetDerivedTypeSpec(
244     const std::optional<DynamicType> &type) {
245   return type ? GetDerivedTypeSpec(*type) : nullptr;
246 }
247 
248 const semantics::DerivedTypeSpec *GetDerivedTypeSpec(const DynamicType &type) {
249   if (type.category() == TypeCategory::Derived &&
250       !type.IsUnlimitedPolymorphic()) {
251     return &type.GetDerivedTypeSpec();
252   } else {
253     return nullptr;
254   }
255 }
256 
257 static const semantics::Symbol *FindParentComponent(
258     const semantics::DerivedTypeSpec &derived) {
259   const semantics::Symbol &typeSymbol{derived.typeSymbol()};
260   const semantics::Scope *scope{derived.scope()};
261   if (!scope) {
262     scope = typeSymbol.scope();
263   }
264   if (scope) {
265     const auto &dtDetails{typeSymbol.get<semantics::DerivedTypeDetails>()};
266     // TODO: Combine with semantics::DerivedTypeDetails::GetParentComponent
267     if (auto extends{dtDetails.GetParentComponentName()}) {
268       if (auto iter{scope->find(*extends)}; iter != scope->cend()) {
269         if (const semantics::Symbol & symbol{*iter->second};
270             symbol.test(semantics::Symbol::Flag::ParentComp)) {
271           return &symbol;
272         }
273       }
274     }
275   }
276   return nullptr;
277 }
278 
279 const semantics::DerivedTypeSpec *GetParentTypeSpec(
280     const semantics::DerivedTypeSpec &derived) {
281   if (const semantics::Symbol * parent{FindParentComponent(derived)}) {
282     return &parent->get<semantics::ObjectEntityDetails>()
283                 .type()
284                 ->derivedTypeSpec();
285   } else {
286     return nullptr;
287   }
288 }
289 
290 // Compares two derived type representations to see whether they both
291 // represent the "same type" in the sense of section 7.5.2.4.
292 using SetOfDerivedTypePairs =
293     std::set<std::pair<const semantics::DerivedTypeSpec *,
294         const semantics::DerivedTypeSpec *>>;
295 
296 static bool AreSameDerivedType(const semantics::DerivedTypeSpec &,
297     const semantics::DerivedTypeSpec &, bool ignoreTypeParameterValues,
298     bool ignoreLenParameters, SetOfDerivedTypePairs &inProgress);
299 
300 // F2023 7.5.3.2
301 static bool AreSameComponent(const semantics::Symbol &x,
302     const semantics::Symbol &y, SetOfDerivedTypePairs &inProgress) {
303   if (x.attrs() != y.attrs()) {
304     return false;
305   }
306   if (x.attrs().test(semantics::Attr::PRIVATE)) {
307     return false;
308   }
309   if (x.size() && y.size()) {
310     if (x.offset() != y.offset() || x.size() != y.size()) {
311       return false;
312     }
313   }
314   const auto *xObj{x.detailsIf<semantics::ObjectEntityDetails>()};
315   const auto *yObj{y.detailsIf<semantics::ObjectEntityDetails>()};
316   const auto *xProc{x.detailsIf<semantics::ProcEntityDetails>()};
317   const auto *yProc{y.detailsIf<semantics::ProcEntityDetails>()};
318   if (!xObj != !yObj || !xProc != !yProc) {
319     return false;
320   }
321   auto xType{DynamicType::From(x)};
322   auto yType{DynamicType::From(y)};
323   if (xType && yType) {
324     if (xType->category() == TypeCategory::Derived) {
325       if (yType->category() != TypeCategory::Derived ||
326           !xType->IsUnlimitedPolymorphic() !=
327               !yType->IsUnlimitedPolymorphic() ||
328           (!xType->IsUnlimitedPolymorphic() &&
329               !AreSameDerivedType(xType->GetDerivedTypeSpec(),
330                   yType->GetDerivedTypeSpec(), false, false, inProgress))) {
331         return false;
332       }
333     } else if (!xType->IsTkLenCompatibleWith(*yType)) {
334       return false;
335     }
336   } else if (xType || yType || !(xProc && yProc)) {
337     return false;
338   }
339   if (xProc) {
340     // TODO: compare argument types, &c.
341   }
342   return true;
343 }
344 
345 // TODO: These utilities were cloned out of Semantics to avoid a cyclic
346 // dependency and should be repackaged into then "namespace semantics"
347 // part of Evaluate/tools.cpp.
348 
349 static const semantics::Symbol *GetParentComponent(
350     const semantics::DerivedTypeDetails &details,
351     const semantics::Scope &scope) {
352   if (auto extends{details.GetParentComponentName()}) {
353     if (auto iter{scope.find(*extends)}; iter != scope.cend()) {
354       if (const Symbol & symbol{*iter->second};
355           symbol.test(semantics::Symbol::Flag::ParentComp)) {
356         return &symbol;
357       }
358     }
359   }
360   return nullptr;
361 }
362 
363 static const semantics::Symbol *GetParentComponent(
364     const semantics::Symbol *symbol, const semantics::Scope &scope) {
365   if (symbol) {
366     if (const auto *dtDetails{
367             symbol->detailsIf<semantics::DerivedTypeDetails>()}) {
368       return GetParentComponent(*dtDetails, scope);
369     }
370   }
371   return nullptr;
372 }
373 
374 static const semantics::DerivedTypeSpec *GetParentTypeSpec(
375     const semantics::Symbol *symbol, const semantics::Scope &scope) {
376   if (const Symbol * parentComponent{GetParentComponent(symbol, scope)}) {
377     return &parentComponent->get<semantics::ObjectEntityDetails>()
378                 .type()
379                 ->derivedTypeSpec();
380   } else {
381     return nullptr;
382   }
383 }
384 
385 static const semantics::Scope *GetDerivedTypeParent(
386     const semantics::Scope *scope) {
387   if (scope) {
388     CHECK(scope->IsDerivedType());
389     if (const auto *parent{GetParentTypeSpec(scope->GetSymbol(), *scope)}) {
390       return parent->scope();
391     }
392   }
393   return nullptr;
394 }
395 
396 static const semantics::Symbol *FindComponent(
397     const semantics::Scope *scope, parser::CharBlock name) {
398   if (!scope) {
399     return nullptr;
400   }
401   CHECK(scope->IsDerivedType());
402   auto found{scope->find(name)};
403   if (found != scope->end()) {
404     return &*found->second;
405   } else {
406     return FindComponent(GetDerivedTypeParent(scope), name);
407   }
408 }
409 
410 static bool AreTypeParamCompatible(const semantics::DerivedTypeSpec &x,
411     const semantics::DerivedTypeSpec &y, bool ignoreLenParameters) {
412   const auto *xScope{x.typeSymbol().scope()};
413   const auto *yScope{y.typeSymbol().scope()};
414   for (const auto &[paramName, value] : x.parameters()) {
415     const auto *yValue{y.FindParameter(paramName)};
416     if (!yValue) {
417       return false;
418     }
419     const auto *xParm{FindComponent(xScope, paramName)};
420     const auto *yParm{FindComponent(yScope, paramName)};
421     if (xParm && yParm) {
422       const auto *xTPD{xParm->detailsIf<semantics::TypeParamDetails>()};
423       const auto *yTPD{yParm->detailsIf<semantics::TypeParamDetails>()};
424       if (xTPD && yTPD) {
425         if (xTPD->attr() != yTPD->attr()) {
426           return false;
427         }
428         if (!ignoreLenParameters ||
429             xTPD->attr() != common::TypeParamAttr::Len) {
430           auto xExpr{value.GetExplicit()};
431           auto yExpr{yValue->GetExplicit()};
432           if (xExpr && yExpr) {
433             auto xVal{ToInt64(*xExpr)};
434             auto yVal{ToInt64(*yExpr)};
435             if (xVal && yVal && *xVal != *yVal) {
436               return false;
437             }
438           }
439         }
440       }
441     }
442   }
443   for (const auto &[paramName, _] : y.parameters()) {
444     if (!x.FindParameter(paramName)) {
445       return false; // y has more parameters than x
446     }
447   }
448   return true;
449 }
450 
451 // F2023 7.5.3.2
452 static bool AreSameDerivedType(const semantics::DerivedTypeSpec &x,
453     const semantics::DerivedTypeSpec &y, bool ignoreTypeParameterValues,
454     bool ignoreLenParameters, SetOfDerivedTypePairs &inProgress) {
455   if (&x == &y) {
456     return true;
457   }
458   if (!ignoreTypeParameterValues &&
459       !AreTypeParamCompatible(x, y, ignoreLenParameters)) {
460     return false;
461   }
462   const auto &xSymbol{x.typeSymbol().GetUltimate()};
463   const auto &ySymbol{y.typeSymbol().GetUltimate()};
464   if (xSymbol == ySymbol) {
465     return true;
466   }
467   if (xSymbol.name() != ySymbol.name()) {
468     return false;
469   }
470   auto thisQuery{std::make_pair(&x, &y)};
471   if (inProgress.find(thisQuery) != inProgress.end()) {
472     return true; // recursive use of types in components
473   }
474   inProgress.insert(thisQuery);
475   const auto &xDetails{xSymbol.get<semantics::DerivedTypeDetails>()};
476   const auto &yDetails{ySymbol.get<semantics::DerivedTypeDetails>()};
477   if (!(xDetails.sequence() && yDetails.sequence()) &&
478       !(xSymbol.attrs().test(semantics::Attr::BIND_C) &&
479           ySymbol.attrs().test(semantics::Attr::BIND_C))) {
480     // PGI does not enforce this requirement; all other Fortran
481     // compilers do with a hard error when violations are caught.
482     return false;
483   }
484   // Compare the component lists in their orders of declaration.
485   auto xEnd{xDetails.componentNames().cend()};
486   auto yComponentName{yDetails.componentNames().cbegin()};
487   auto yEnd{yDetails.componentNames().cend()};
488   for (auto xComponentName{xDetails.componentNames().cbegin()};
489        xComponentName != xEnd; ++xComponentName, ++yComponentName) {
490     if (yComponentName == yEnd || *xComponentName != *yComponentName ||
491         !xSymbol.scope() || !ySymbol.scope()) {
492       return false;
493     }
494     const auto xLookup{xSymbol.scope()->find(*xComponentName)};
495     const auto yLookup{ySymbol.scope()->find(*yComponentName)};
496     if (xLookup == xSymbol.scope()->end() ||
497         yLookup == ySymbol.scope()->end() ||
498         !AreSameComponent(*xLookup->second, *yLookup->second, inProgress)) {
499       return false;
500     }
501   }
502   return yComponentName == yEnd;
503 }
504 
505 bool AreSameDerivedType(
506     const semantics::DerivedTypeSpec &x, const semantics::DerivedTypeSpec &y) {
507   SetOfDerivedTypePairs inProgress;
508   return AreSameDerivedType(x, y, false, false, inProgress);
509 }
510 
511 static bool AreCompatibleDerivedTypes(const semantics::DerivedTypeSpec *x,
512     const semantics::DerivedTypeSpec *y, bool isPolymorphic,
513     bool ignoreTypeParameterValues, bool ignoreLenTypeParameters) {
514   if (!x || !y) {
515     return false;
516   } else {
517     SetOfDerivedTypePairs inProgress;
518     if (AreSameDerivedType(*x, *y, ignoreTypeParameterValues,
519             ignoreLenTypeParameters, inProgress)) {
520       return true;
521     } else {
522       return isPolymorphic &&
523           AreCompatibleDerivedTypes(x, GetParentTypeSpec(*y), true,
524               ignoreTypeParameterValues, ignoreLenTypeParameters);
525     }
526   }
527 }
528 
529 static bool AreCompatibleTypes(const DynamicType &x, const DynamicType &y,
530     bool ignoreTypeParameterValues, bool ignoreLengths) {
531   if (x.IsUnlimitedPolymorphic()) {
532     return true;
533   } else if (y.IsUnlimitedPolymorphic()) {
534     return false;
535   } else if (x.category() != y.category()) {
536     return false;
537   } else if (x.category() == TypeCategory::Character) {
538     const auto xLen{x.knownLength()};
539     const auto yLen{y.knownLength()};
540     return x.kind() == y.kind() &&
541         (ignoreLengths || !xLen || !yLen || *xLen == *yLen);
542   } else if (x.category() != TypeCategory::Derived) {
543     if (x.IsTypelessIntrinsicArgument()) {
544       return y.IsTypelessIntrinsicArgument();
545     } else {
546       return !y.IsTypelessIntrinsicArgument() && x.kind() == y.kind();
547     }
548   } else {
549     const auto *xdt{GetDerivedTypeSpec(x)};
550     const auto *ydt{GetDerivedTypeSpec(y)};
551     return AreCompatibleDerivedTypes(
552         xdt, ydt, x.IsPolymorphic(), ignoreTypeParameterValues, false);
553   }
554 }
555 
556 // See 7.3.2.3 (5) & 15.5.2.4
557 bool DynamicType::IsTkCompatibleWith(const DynamicType &that) const {
558   return AreCompatibleTypes(*this, that, false, true);
559 }
560 
561 bool DynamicType::IsTkCompatibleWith(
562     const DynamicType &that, common::IgnoreTKRSet ignoreTKR) const {
563   if (ignoreTKR.test(common::IgnoreTKR::Type) &&
564       (category() == TypeCategory::Derived ||
565           that.category() == TypeCategory::Derived ||
566           category() != that.category())) {
567     return true;
568   } else if (ignoreTKR.test(common::IgnoreTKR::Kind) &&
569       category() == that.category()) {
570     return true;
571   } else {
572     return AreCompatibleTypes(*this, that, false, true);
573   }
574 }
575 
576 bool DynamicType::IsTkLenCompatibleWith(const DynamicType &that) const {
577   return AreCompatibleTypes(*this, that, false, false);
578 }
579 
580 // 16.9.165
581 std::optional<bool> DynamicType::SameTypeAs(const DynamicType &that) const {
582   bool x{AreCompatibleTypes(*this, that, true, true)};
583   bool y{AreCompatibleTypes(that, *this, true, true)};
584   if (!x && !y) {
585     return false;
586   } else if (x && y && !IsPolymorphic() && !that.IsPolymorphic()) {
587     return true;
588   } else {
589     return std::nullopt;
590   }
591 }
592 
593 // 16.9.76
594 std::optional<bool> DynamicType::ExtendsTypeOf(const DynamicType &that) const {
595   if (IsUnlimitedPolymorphic() || that.IsUnlimitedPolymorphic()) {
596     return std::nullopt; // unknown
597   }
598   const auto *thisDts{evaluate::GetDerivedTypeSpec(*this)};
599   const auto *thatDts{evaluate::GetDerivedTypeSpec(that)};
600   if (!thisDts || !thatDts) {
601     return std::nullopt;
602   } else if (!AreCompatibleDerivedTypes(thatDts, thisDts, true, true, true)) {
603     // Note that I check *thisDts, not its parent, so that EXTENDS_TYPE_OF()
604     // is .true. when they are the same type.  This is technically
605     // an implementation-defined case in the standard, but every other
606     // compiler works this way.
607     if (IsPolymorphic() &&
608         AreCompatibleDerivedTypes(thisDts, thatDts, true, true, true)) {
609       // 'that' is *this or an extension of *this, and so runtime *this
610       // could be an extension of 'that'
611       return std::nullopt;
612     } else {
613       return false;
614     }
615   } else if (that.IsPolymorphic()) {
616     return std::nullopt; // unknown
617   } else {
618     return true;
619   }
620 }
621 
622 std::optional<DynamicType> DynamicType::From(
623     const semantics::DeclTypeSpec &type) {
624   if (const auto *intrinsic{type.AsIntrinsic()}) {
625     if (auto kind{ToInt64(intrinsic->kind())}) {
626       TypeCategory category{intrinsic->category()};
627       if (IsValidKindOfIntrinsicType(category, *kind)) {
628         if (category == TypeCategory::Character) {
629           const auto &charType{type.characterTypeSpec()};
630           return DynamicType{static_cast<int>(*kind), charType.length()};
631         } else {
632           return DynamicType{category, static_cast<int>(*kind)};
633         }
634       }
635     }
636   } else if (const auto *derived{type.AsDerived()}) {
637     return DynamicType{
638         *derived, type.category() == semantics::DeclTypeSpec::ClassDerived};
639   } else if (type.category() == semantics::DeclTypeSpec::ClassStar) {
640     return DynamicType::UnlimitedPolymorphic();
641   } else if (type.category() == semantics::DeclTypeSpec::TypeStar) {
642     return DynamicType::AssumedType();
643   } else {
644     common::die("DynamicType::From(DeclTypeSpec): failed");
645   }
646   return std::nullopt;
647 }
648 
649 std::optional<DynamicType> DynamicType::From(const semantics::Symbol &symbol) {
650   return From(symbol.GetType()); // Symbol -> DeclTypeSpec -> DynamicType
651 }
652 
653 DynamicType DynamicType::ResultTypeForMultiply(const DynamicType &that) const {
654   switch (category_) {
655   case TypeCategory::Integer:
656     switch (that.category_) {
657     case TypeCategory::Integer:
658       return DynamicType{TypeCategory::Integer, std::max(kind(), that.kind())};
659     case TypeCategory::Real:
660     case TypeCategory::Complex:
661       return that;
662     default:
663       CRASH_NO_CASE;
664     }
665     break;
666   case TypeCategory::Real:
667     switch (that.category_) {
668     case TypeCategory::Integer:
669       return *this;
670     case TypeCategory::Real:
671       return DynamicType{TypeCategory::Real, std::max(kind(), that.kind())};
672     case TypeCategory::Complex:
673       return DynamicType{TypeCategory::Complex, std::max(kind(), that.kind())};
674     default:
675       CRASH_NO_CASE;
676     }
677     break;
678   case TypeCategory::Complex:
679     switch (that.category_) {
680     case TypeCategory::Integer:
681       return *this;
682     case TypeCategory::Real:
683     case TypeCategory::Complex:
684       return DynamicType{TypeCategory::Complex, std::max(kind(), that.kind())};
685     default:
686       CRASH_NO_CASE;
687     }
688     break;
689   case TypeCategory::Logical:
690     switch (that.category_) {
691     case TypeCategory::Logical:
692       return DynamicType{TypeCategory::Logical, std::max(kind(), that.kind())};
693     default:
694       CRASH_NO_CASE;
695     }
696     break;
697   default:
698     CRASH_NO_CASE;
699   }
700   return *this;
701 }
702 
703 bool DynamicType::RequiresDescriptor() const {
704   return IsPolymorphic() || IsNonConstantLengthCharacter() ||
705       (derived_ && CountNonConstantLenParameters(*derived_) > 0);
706 }
707 
708 bool DynamicType::HasDeferredTypeParameter() const {
709   if (derived_) {
710     for (const auto &pair : derived_->parameters()) {
711       if (pair.second.isDeferred()) {
712         return true;
713       }
714     }
715   }
716   return charLengthParamValue_ && charLengthParamValue_->isDeferred();
717 }
718 
719 bool SomeKind<TypeCategory::Derived>::operator==(
720     const SomeKind<TypeCategory::Derived> &that) const {
721   return PointeeComparison(derivedTypeSpec_, that.derivedTypeSpec_);
722 }
723 
724 int SelectedCharKind(const std::string &s, int defaultKind) { // 16.9.168
725   auto lower{parser::ToLowerCaseLetters(s)};
726   auto n{lower.size()};
727   while (n > 0 && lower[0] == ' ') {
728     lower.erase(0, 1);
729     --n;
730   }
731   while (n > 0 && lower[n - 1] == ' ') {
732     lower.erase(--n, 1);
733   }
734   if (lower == "ascii") {
735     return 1;
736   } else if (lower == "ucs-2") {
737     return 2;
738   } else if (lower == "iso_10646" || lower == "ucs-4") {
739     return 4;
740   } else if (lower == "default") {
741     return defaultKind;
742   } else {
743     return -1;
744   }
745 }
746 
747 std::optional<DynamicType> ComparisonType(
748     const DynamicType &t1, const DynamicType &t2) {
749   switch (t1.category()) {
750   case TypeCategory::Integer:
751     switch (t2.category()) {
752     case TypeCategory::Integer:
753       return DynamicType{TypeCategory::Integer, std::max(t1.kind(), t2.kind())};
754     case TypeCategory::Real:
755     case TypeCategory::Complex:
756       return t2;
757     default:
758       return std::nullopt;
759     }
760   case TypeCategory::Real:
761     switch (t2.category()) {
762     case TypeCategory::Integer:
763       return t1;
764     case TypeCategory::Real:
765     case TypeCategory::Complex:
766       return DynamicType{t2.category(), std::max(t1.kind(), t2.kind())};
767     default:
768       return std::nullopt;
769     }
770   case TypeCategory::Complex:
771     switch (t2.category()) {
772     case TypeCategory::Integer:
773       return t1;
774     case TypeCategory::Real:
775     case TypeCategory::Complex:
776       return DynamicType{TypeCategory::Complex, std::max(t1.kind(), t2.kind())};
777     default:
778       return std::nullopt;
779     }
780   case TypeCategory::Character:
781     switch (t2.category()) {
782     case TypeCategory::Character:
783       return DynamicType{
784           TypeCategory::Character, std::max(t1.kind(), t2.kind())};
785     default:
786       return std::nullopt;
787     }
788   case TypeCategory::Logical:
789     switch (t2.category()) {
790     case TypeCategory::Logical:
791       return DynamicType{TypeCategory::Logical, LogicalResult::kind};
792     default:
793       return std::nullopt;
794     }
795   default:
796     return std::nullopt;
797   }
798 }
799 
800 bool IsInteroperableIntrinsicType(const DynamicType &type,
801     const common::LanguageFeatureControl *features, bool checkCharLength) {
802   switch (type.category()) {
803   case TypeCategory::Integer:
804     return true;
805   case TypeCategory::Real:
806   case TypeCategory::Complex:
807     return (features && features->IsEnabled(common::LanguageFeature::CUDA)) ||
808         type.kind() >= 4; // no short or half floats
809   case TypeCategory::Logical:
810     return type.kind() == 1; // C_BOOL
811   case TypeCategory::Character:
812     if (checkCharLength && type.knownLength().value_or(0) != 1) {
813       return false;
814     }
815     return type.kind() == 1 /* C_CHAR */;
816   default:
817     // Derived types are tested in Semantics/check-declarations.cpp
818     return false;
819   }
820 }
821 
822 bool IsCUDAIntrinsicType(const DynamicType &type) {
823   switch (type.category()) {
824   case TypeCategory::Integer:
825   case TypeCategory::Logical:
826     return type.kind() <= 8;
827   case TypeCategory::Real:
828     return type.kind() >= 2 && type.kind() <= 8;
829   case TypeCategory::Complex:
830     return type.kind() == 2 || type.kind() == 4 || type.kind() == 8;
831   case TypeCategory::Character:
832     return type.kind() == 1;
833   default:
834     // Derived types are tested in Semantics/check-declarations.cpp
835     return false;
836   }
837 }
838 
839 DynamicType DynamicType::DropNonConstantCharacterLength() const {
840   if (charLengthParamValue_ && charLengthParamValue_->isExplicit()) {
841     if (std::optional<std::int64_t> len{knownLength()}) {
842       return DynamicType(kind_, *len);
843     } else {
844       return DynamicType(category_, kind_);
845     }
846   }
847   return *this;
848 }
849 
850 } // namespace Fortran::evaluate
851