1 //===-- ConvertType.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/Lower/ConvertType.h" 10 #include "flang/Lower/AbstractConverter.h" 11 #include "flang/Lower/CallInterface.h" 12 #include "flang/Lower/ConvertVariable.h" 13 #include "flang/Lower/Mangler.h" 14 #include "flang/Lower/PFTBuilder.h" 15 #include "flang/Lower/Support/Utils.h" 16 #include "flang/Optimizer/Builder/Todo.h" 17 #include "flang/Optimizer/Dialect/FIRType.h" 18 #include "flang/Semantics/tools.h" 19 #include "flang/Semantics/type.h" 20 #include "mlir/IR/Builders.h" 21 #include "mlir/IR/BuiltinTypes.h" 22 #include "llvm/Support/Debug.h" 23 24 #define DEBUG_TYPE "flang-lower-type" 25 26 using Fortran::common::VectorElementCategory; 27 28 //===--------------------------------------------------------------------===// 29 // Intrinsic type translation helpers 30 //===--------------------------------------------------------------------===// 31 32 static mlir::Type genRealType(mlir::MLIRContext *context, int kind) { 33 if (Fortran::evaluate::IsValidKindOfIntrinsicType( 34 Fortran::common::TypeCategory::Real, kind)) { 35 switch (kind) { 36 case 2: 37 return mlir::FloatType::getF16(context); 38 case 3: 39 return mlir::FloatType::getBF16(context); 40 case 4: 41 return mlir::FloatType::getF32(context); 42 case 8: 43 return mlir::FloatType::getF64(context); 44 case 10: 45 return mlir::FloatType::getF80(context); 46 case 16: 47 return mlir::FloatType::getF128(context); 48 } 49 } 50 llvm_unreachable("REAL type translation not implemented"); 51 } 52 53 template <int KIND> 54 int getIntegerBits() { 55 return Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer, 56 KIND>::Scalar::bits; 57 } 58 static mlir::Type genIntegerType(mlir::MLIRContext *context, int kind, 59 bool isUnsigned = false) { 60 if (Fortran::evaluate::IsValidKindOfIntrinsicType( 61 Fortran::common::TypeCategory::Integer, kind)) { 62 mlir::IntegerType::SignednessSemantics signedness = 63 (isUnsigned ? mlir::IntegerType::SignednessSemantics::Unsigned 64 : mlir::IntegerType::SignednessSemantics::Signless); 65 66 switch (kind) { 67 case 1: 68 return mlir::IntegerType::get(context, getIntegerBits<1>(), signedness); 69 case 2: 70 return mlir::IntegerType::get(context, getIntegerBits<2>(), signedness); 71 case 4: 72 return mlir::IntegerType::get(context, getIntegerBits<4>(), signedness); 73 case 8: 74 return mlir::IntegerType::get(context, getIntegerBits<8>(), signedness); 75 case 16: 76 return mlir::IntegerType::get(context, getIntegerBits<16>(), signedness); 77 } 78 } 79 llvm_unreachable("INTEGER kind not translated"); 80 } 81 82 static mlir::Type genLogicalType(mlir::MLIRContext *context, int KIND) { 83 if (Fortran::evaluate::IsValidKindOfIntrinsicType( 84 Fortran::common::TypeCategory::Logical, KIND)) 85 return fir::LogicalType::get(context, KIND); 86 return {}; 87 } 88 89 static mlir::Type genCharacterType( 90 mlir::MLIRContext *context, int KIND, 91 Fortran::lower::LenParameterTy len = fir::CharacterType::unknownLen()) { 92 if (Fortran::evaluate::IsValidKindOfIntrinsicType( 93 Fortran::common::TypeCategory::Character, KIND)) 94 return fir::CharacterType::get(context, KIND, len); 95 return {}; 96 } 97 98 static mlir::Type genComplexType(mlir::MLIRContext *context, int KIND) { 99 if (Fortran::evaluate::IsValidKindOfIntrinsicType( 100 Fortran::common::TypeCategory::Complex, KIND)) 101 return fir::ComplexType::get(context, KIND); 102 return {}; 103 } 104 105 static mlir::Type 106 genFIRType(mlir::MLIRContext *context, Fortran::common::TypeCategory tc, 107 int kind, 108 llvm::ArrayRef<Fortran::lower::LenParameterTy> lenParameters) { 109 switch (tc) { 110 case Fortran::common::TypeCategory::Real: 111 return genRealType(context, kind); 112 case Fortran::common::TypeCategory::Integer: 113 return genIntegerType(context, kind); 114 case Fortran::common::TypeCategory::Complex: 115 return genComplexType(context, kind); 116 case Fortran::common::TypeCategory::Logical: 117 return genLogicalType(context, kind); 118 case Fortran::common::TypeCategory::Character: 119 if (!lenParameters.empty()) 120 return genCharacterType(context, kind, lenParameters[0]); 121 return genCharacterType(context, kind); 122 default: 123 break; 124 } 125 llvm_unreachable("unhandled type category"); 126 } 127 128 //===--------------------------------------------------------------------===// 129 // Symbol and expression type translation 130 //===--------------------------------------------------------------------===// 131 132 /// TypeBuilderImpl translates expression and symbol type taking into account 133 /// their shape and length parameters. For symbols, attributes such as 134 /// ALLOCATABLE or POINTER are reflected in the fir type. 135 /// It uses evaluate::DynamicType and evaluate::Shape when possible to 136 /// avoid re-implementing type/shape analysis here. 137 /// Do not use the FirOpBuilder from the AbstractConverter to get fir/mlir types 138 /// since it is not guaranteed to exist yet when we lower types. 139 namespace { 140 struct TypeBuilderImpl { 141 142 TypeBuilderImpl(Fortran::lower::AbstractConverter &converter) 143 : converter{converter}, context{&converter.getMLIRContext()} {} 144 145 template <typename A> 146 mlir::Type genExprType(const A &expr) { 147 std::optional<Fortran::evaluate::DynamicType> dynamicType = expr.GetType(); 148 if (!dynamicType) 149 return genTypelessExprType(expr); 150 Fortran::common::TypeCategory category = dynamicType->category(); 151 152 mlir::Type baseType; 153 bool isPolymorphic = (dynamicType->IsPolymorphic() || 154 dynamicType->IsUnlimitedPolymorphic()) && 155 !dynamicType->IsAssumedType(); 156 if (dynamicType->IsUnlimitedPolymorphic()) { 157 baseType = mlir::NoneType::get(context); 158 } else if (category == Fortran::common::TypeCategory::Derived) { 159 baseType = genDerivedType(dynamicType->GetDerivedTypeSpec()); 160 } else { 161 // LOGICAL, INTEGER, REAL, COMPLEX, CHARACTER 162 llvm::SmallVector<Fortran::lower::LenParameterTy> params; 163 translateLenParameters(params, category, expr); 164 baseType = genFIRType(context, category, dynamicType->kind(), params); 165 } 166 std::optional<Fortran::evaluate::Shape> shapeExpr = 167 Fortran::evaluate::GetShape(converter.getFoldingContext(), expr); 168 fir::SequenceType::Shape shape; 169 if (shapeExpr) { 170 translateShape(shape, std::move(*shapeExpr)); 171 } else { 172 // Shape static analysis cannot return something useful for the shape. 173 // Use unknown extents. 174 int rank = expr.Rank(); 175 if (rank < 0) 176 TODO(converter.getCurrentLocation(), "assumed rank expression types"); 177 for (int dim = 0; dim < rank; ++dim) 178 shape.emplace_back(fir::SequenceType::getUnknownExtent()); 179 } 180 181 if (!shape.empty()) { 182 if (isPolymorphic) 183 return fir::ClassType::get(fir::SequenceType::get(shape, baseType)); 184 return fir::SequenceType::get(shape, baseType); 185 } 186 if (isPolymorphic) 187 return fir::ClassType::get(baseType); 188 return baseType; 189 } 190 191 template <typename A> 192 void translateShape(A &shape, Fortran::evaluate::Shape &&shapeExpr) { 193 for (Fortran::evaluate::MaybeExtentExpr extentExpr : shapeExpr) { 194 fir::SequenceType::Extent extent = fir::SequenceType::getUnknownExtent(); 195 if (std::optional<std::int64_t> constantExtent = 196 toInt64(std::move(extentExpr))) 197 extent = *constantExtent; 198 shape.push_back(extent); 199 } 200 } 201 202 template <typename A> 203 std::optional<std::int64_t> toInt64(A &&expr) { 204 return Fortran::evaluate::ToInt64(Fortran::evaluate::Fold( 205 converter.getFoldingContext(), std::move(expr))); 206 } 207 208 template <typename A> 209 mlir::Type genTypelessExprType(const A &expr) { 210 fir::emitFatalError(converter.getCurrentLocation(), "not a typeless expr"); 211 } 212 213 mlir::Type genTypelessExprType(const Fortran::lower::SomeExpr &expr) { 214 return std::visit( 215 Fortran::common::visitors{ 216 [&](const Fortran::evaluate::BOZLiteralConstant &) -> mlir::Type { 217 return mlir::NoneType::get(context); 218 }, 219 [&](const Fortran::evaluate::NullPointer &) -> mlir::Type { 220 return fir::ReferenceType::get(mlir::NoneType::get(context)); 221 }, 222 [&](const Fortran::evaluate::ProcedureDesignator &proc) 223 -> mlir::Type { 224 return Fortran::lower::translateSignature(proc, converter); 225 }, 226 [&](const Fortran::evaluate::ProcedureRef &) -> mlir::Type { 227 return mlir::NoneType::get(context); 228 }, 229 [](const auto &x) -> mlir::Type { 230 using T = std::decay_t<decltype(x)>; 231 static_assert(!Fortran::common::HasMember< 232 T, Fortran::evaluate::TypelessExpression>, 233 "missing typeless expr handling"); 234 llvm::report_fatal_error("not a typeless expression"); 235 }, 236 }, 237 expr.u); 238 } 239 240 mlir::Type genSymbolType(const Fortran::semantics::Symbol &symbol, 241 bool isAlloc = false, bool isPtr = false) { 242 mlir::Location loc = converter.genLocation(symbol.name()); 243 mlir::Type ty; 244 // If the symbol is not the same as the ultimate one (i.e, it is host or use 245 // associated), all the symbol properties are the ones of the ultimate 246 // symbol but the volatile and asynchronous attributes that may differ. To 247 // avoid issues with helper functions that would not follow association 248 // links, the fir type is built based on the ultimate symbol. This relies 249 // on the fact volatile and asynchronous are not reflected in fir types. 250 const Fortran::semantics::Symbol &ultimate = symbol.GetUltimate(); 251 252 if (Fortran::semantics::IsProcedurePointer(ultimate)) { 253 Fortran::evaluate::ProcedureDesignator proc(ultimate); 254 auto procTy{Fortran::lower::translateSignature(proc, converter)}; 255 return fir::BoxProcType::get(context, procTy); 256 } 257 258 if (const Fortran::semantics::DeclTypeSpec *type = ultimate.GetType()) { 259 if (const Fortran::semantics::IntrinsicTypeSpec *tySpec = 260 type->AsIntrinsic()) { 261 int kind = toInt64(Fortran::common::Clone(tySpec->kind())).value(); 262 llvm::SmallVector<Fortran::lower::LenParameterTy> params; 263 translateLenParameters(params, tySpec->category(), ultimate); 264 ty = genFIRType(context, tySpec->category(), kind, params); 265 } else if (type->IsPolymorphic() && 266 !converter.getLoweringOptions().getPolymorphicTypeImpl()) { 267 // TODO is kept under experimental flag until feature is complete. 268 TODO(loc, "support for polymorphic types"); 269 } else if (type->IsUnlimitedPolymorphic()) { 270 ty = mlir::NoneType::get(context); 271 } else if (const Fortran::semantics::DerivedTypeSpec *tySpec = 272 type->AsDerived()) { 273 ty = genDerivedType(*tySpec); 274 } else { 275 fir::emitFatalError(loc, "symbol's type must have a type spec"); 276 } 277 } else { 278 fir::emitFatalError(loc, "symbol must have a type"); 279 } 280 bool isPolymorphic = (Fortran::semantics::IsPolymorphic(symbol) || 281 Fortran::semantics::IsUnlimitedPolymorphic(symbol)) && 282 !Fortran::semantics::IsAssumedType(symbol); 283 if (ultimate.IsObjectArray()) { 284 auto shapeExpr = 285 Fortran::evaluate::GetShape(converter.getFoldingContext(), ultimate); 286 if (!shapeExpr) 287 TODO(loc, "assumed rank symbol type"); 288 fir::SequenceType::Shape shape; 289 translateShape(shape, std::move(*shapeExpr)); 290 ty = fir::SequenceType::get(shape, ty); 291 } 292 if (Fortran::semantics::IsPointer(symbol)) 293 return fir::wrapInClassOrBoxType(fir::PointerType::get(ty), 294 isPolymorphic); 295 if (Fortran::semantics::IsAllocatable(symbol)) 296 return fir::wrapInClassOrBoxType(fir::HeapType::get(ty), isPolymorphic); 297 // isPtr and isAlloc are variable that were promoted to be on the 298 // heap or to be pointers, but they do not have Fortran allocatable 299 // or pointer semantics, so do not use box for them. 300 if (isPtr) 301 return fir::PointerType::get(ty); 302 if (isAlloc) 303 return fir::HeapType::get(ty); 304 if (isPolymorphic) 305 return fir::ClassType::get(ty); 306 return ty; 307 } 308 309 /// Does \p component has non deferred lower bounds that are not compile time 310 /// constant 1. 311 static bool componentHasNonDefaultLowerBounds( 312 const Fortran::semantics::Symbol &component) { 313 if (const auto *objDetails = 314 component.detailsIf<Fortran::semantics::ObjectEntityDetails>()) 315 for (const Fortran::semantics::ShapeSpec &bounds : objDetails->shape()) 316 if (auto lb = bounds.lbound().GetExplicit()) 317 if (auto constant = Fortran::evaluate::ToInt64(*lb)) 318 if (!constant || *constant != 1) 319 return true; 320 return false; 321 } 322 323 mlir::Type genVectorType(const Fortran::semantics::DerivedTypeSpec &tySpec) { 324 assert(tySpec.scope() && "Missing scope for Vector type"); 325 auto vectorSize{tySpec.scope()->size()}; 326 switch (tySpec.category()) { 327 SWITCH_COVERS_ALL_CASES 328 case (Fortran::semantics::DerivedTypeSpec::Category::IntrinsicVector): { 329 int64_t vecElemKind; 330 int64_t vecElemCategory; 331 332 for (const auto &pair : tySpec.parameters()) { 333 if (pair.first == "element_category") { 334 vecElemCategory = 335 Fortran::evaluate::ToInt64(pair.second.GetExplicit()) 336 .value_or(-1); 337 } else if (pair.first == "element_kind") { 338 vecElemKind = 339 Fortran::evaluate::ToInt64(pair.second.GetExplicit()).value_or(0); 340 } 341 } 342 343 assert((vecElemCategory >= 0 && 344 static_cast<size_t>(vecElemCategory) < 345 Fortran::common::VectorElementCategory_enumSize) && 346 "Vector element type is not specified"); 347 assert(vecElemKind && "Vector element kind is not specified"); 348 349 int64_t numOfElements = vectorSize / vecElemKind; 350 switch (static_cast<VectorElementCategory>(vecElemCategory)) { 351 SWITCH_COVERS_ALL_CASES 352 case VectorElementCategory::Integer: 353 return fir::VectorType::get(numOfElements, 354 genIntegerType(context, vecElemKind)); 355 case VectorElementCategory::Unsigned: 356 return fir::VectorType::get(numOfElements, 357 genIntegerType(context, vecElemKind, true)); 358 case VectorElementCategory::Real: 359 return fir::VectorType::get(numOfElements, 360 genRealType(context, vecElemKind)); 361 } 362 break; 363 } 364 case (Fortran::semantics::DerivedTypeSpec::Category::PairVector): 365 case (Fortran::semantics::DerivedTypeSpec::Category::QuadVector): 366 return fir::VectorType::get(vectorSize * 8, 367 mlir::IntegerType::get(context, 1)); 368 case (Fortran::semantics::DerivedTypeSpec::Category::DerivedType): 369 Fortran::common::die("Vector element type not implemented"); 370 } 371 } 372 373 mlir::Type genDerivedType(const Fortran::semantics::DerivedTypeSpec &tySpec) { 374 std::vector<std::pair<std::string, mlir::Type>> ps; 375 std::vector<std::pair<std::string, mlir::Type>> cs; 376 const Fortran::semantics::Symbol &typeSymbol = tySpec.typeSymbol(); 377 if (mlir::Type ty = getTypeIfDerivedAlreadyInConstruction(typeSymbol)) 378 return ty; 379 380 if (tySpec.IsVectorType()) { 381 return genVectorType(tySpec); 382 } 383 384 const Fortran::semantics::Scope &derivedScope = DEREF(tySpec.GetScope()); 385 386 auto rec = fir::RecordType::get(context, converter.mangleName(tySpec)); 387 // Maintain the stack of types for recursive references. 388 derivedTypeInConstruction.emplace_back(typeSymbol, rec); 389 390 // Gather the record type fields. 391 // (1) The data components. 392 if (converter.getLoweringOptions().getLowerToHighLevelFIR()) { 393 // In HLFIR the parent component is the first fir.type component. 394 for (const auto &componentName : 395 typeSymbol.get<Fortran::semantics::DerivedTypeDetails>() 396 .componentNames()) { 397 auto scopeIter = derivedScope.find(componentName); 398 assert(scopeIter != derivedScope.cend() && 399 "failed to find derived type component symbol"); 400 const Fortran::semantics::Symbol &component = scopeIter->second.get(); 401 if (IsProcedure(component)) 402 TODO(converter.genLocation(component.name()), "procedure components"); 403 mlir::Type ty = genSymbolType(component); 404 cs.emplace_back(converter.getRecordTypeFieldName(component), ty); 405 } 406 } else { 407 for (const auto &component : 408 Fortran::semantics::OrderedComponentIterator(tySpec)) { 409 // In the lowering to FIR the parent component does not appear in the 410 // fir.type and its components are inlined at the beginning of the 411 // fir.type<>. 412 // FIXME: this strategy leads to bugs because padding should be inserted 413 // after the component of the parents so that the next components do not 414 // end-up in the parent storage if the sum of the parent's component 415 // storage size is not a multiple of the parent type storage alignment. 416 417 // Lowering is assuming non deferred component lower bounds are 418 // always 1. Catch any situations where this is not true for now. 419 if (componentHasNonDefaultLowerBounds(component)) 420 TODO(converter.genLocation(component.name()), 421 "derived type components with non default lower bounds"); 422 if (IsProcedure(component)) 423 TODO(converter.genLocation(component.name()), "procedure components"); 424 mlir::Type ty = genSymbolType(component); 425 // Do not add the parent component (component of the parents are 426 // added and should be sufficient, the parent component would 427 // duplicate the fields). Note that genSymbolType must be called above 428 // on it so that the dispatch table for the parent type still gets 429 // emitted as needed. 430 if (component.test(Fortran::semantics::Symbol::Flag::ParentComp)) 431 continue; 432 cs.emplace_back(converter.getRecordTypeFieldName(component), ty); 433 } 434 } 435 436 mlir::Location loc = converter.genLocation(typeSymbol.name()); 437 // (2) The LEN type parameters. 438 for (const auto ¶m : 439 Fortran::semantics::OrderParameterDeclarations(typeSymbol)) 440 if (param->get<Fortran::semantics::TypeParamDetails>().attr() == 441 Fortran::common::TypeParamAttr::Len) { 442 TODO(loc, "parameterized derived types"); 443 // TODO: emplace in ps. Beware that param is the symbol in the type 444 // declaration, not instantiation: its kind may not be a constant. 445 // The instantiated symbol in tySpec.scope should be used instead. 446 ps.emplace_back(param->name().ToString(), genSymbolType(*param)); 447 } 448 449 rec.finalize(ps, cs); 450 popDerivedTypeInConstruction(); 451 452 if (!ps.empty()) { 453 // TODO: this type is a PDT (parametric derived type) with length 454 // parameter. Create the functions to use for allocation, dereferencing, 455 // and address arithmetic here. 456 } 457 LLVM_DEBUG(llvm::dbgs() << "derived type: " << rec << '\n'); 458 459 // Generate the type descriptor object if any 460 if (const Fortran::semantics::Symbol *typeInfoSym = 461 derivedScope.runtimeDerivedTypeDescription()) 462 converter.registerTypeInfo(loc, *typeInfoSym, tySpec, rec); 463 return rec; 464 } 465 466 // To get the character length from a symbol, make an fold a designator for 467 // the symbol to cover the case where the symbol is an assumed length named 468 // constant and its length comes from its init expression length. 469 template <int Kind> 470 fir::SequenceType::Extent 471 getCharacterLengthHelper(const Fortran::semantics::Symbol &symbol) { 472 using TC = 473 Fortran::evaluate::Type<Fortran::common::TypeCategory::Character, Kind>; 474 auto designator = Fortran::evaluate::Fold( 475 converter.getFoldingContext(), 476 Fortran::evaluate::Expr<TC>{Fortran::evaluate::Designator<TC>{symbol}}); 477 if (auto len = toInt64(std::move(designator.LEN()))) 478 return *len; 479 return fir::SequenceType::getUnknownExtent(); 480 } 481 482 template <typename T> 483 void translateLenParameters( 484 llvm::SmallVectorImpl<Fortran::lower::LenParameterTy> ¶ms, 485 Fortran::common::TypeCategory category, const T &exprOrSym) { 486 if (category == Fortran::common::TypeCategory::Character) 487 params.push_back(getCharacterLength(exprOrSym)); 488 else if (category == Fortran::common::TypeCategory::Derived) 489 TODO(converter.getCurrentLocation(), "derived type length parameters"); 490 } 491 Fortran::lower::LenParameterTy 492 getCharacterLength(const Fortran::semantics::Symbol &symbol) { 493 const Fortran::semantics::DeclTypeSpec *type = symbol.GetType(); 494 if (!type || 495 type->category() != Fortran::semantics::DeclTypeSpec::Character || 496 !type->AsIntrinsic()) 497 llvm::report_fatal_error("not a character symbol"); 498 int kind = 499 toInt64(Fortran::common::Clone(type->AsIntrinsic()->kind())).value(); 500 switch (kind) { 501 case 1: 502 return getCharacterLengthHelper<1>(symbol); 503 case 2: 504 return getCharacterLengthHelper<2>(symbol); 505 case 4: 506 return getCharacterLengthHelper<4>(symbol); 507 } 508 llvm_unreachable("unknown character kind"); 509 } 510 511 template <typename A> 512 Fortran::lower::LenParameterTy getCharacterLength(const A &expr) { 513 return fir::SequenceType::getUnknownExtent(); 514 } 515 516 template <typename T> 517 Fortran::lower::LenParameterTy 518 getCharacterLength(const Fortran::evaluate::FunctionRef<T> &funcRef) { 519 if (auto constantLen = toInt64(funcRef.LEN())) 520 return *constantLen; 521 return fir::SequenceType::getUnknownExtent(); 522 } 523 524 Fortran::lower::LenParameterTy 525 getCharacterLength(const Fortran::lower::SomeExpr &expr) { 526 // Do not use dynamic type length here. We would miss constant 527 // lengths opportunities because dynamic type only has the length 528 // if it comes from a declaration. 529 if (const auto *charExpr = std::get_if< 530 Fortran::evaluate::Expr<Fortran::evaluate::SomeCharacter>>( 531 &expr.u)) { 532 if (auto constantLen = toInt64(charExpr->LEN())) 533 return *constantLen; 534 } else if (auto dynamicType = expr.GetType()) { 535 // When generating derived type type descriptor as structure constructor, 536 // semantics wraps designators to data component initialization into 537 // CLASS(*), regardless of their actual type. 538 // GetType() will recover the actual symbol type as the dynamic type, so 539 // getCharacterLength may be reached even if expr is packaged as an 540 // Expr<SomeDerived> instead of an Expr<SomeChar>. 541 // Just use the dynamic type here again to retrieve the length. 542 if (auto constantLen = toInt64(dynamicType->GetCharLength())) 543 return *constantLen; 544 } 545 return fir::SequenceType::getUnknownExtent(); 546 } 547 548 mlir::Type genVariableType(const Fortran::lower::pft::Variable &var) { 549 return genSymbolType(var.getSymbol(), var.isHeapAlloc(), var.isPointer()); 550 } 551 552 /// Derived type can be recursive. That is, pointer components of a derived 553 /// type `t` have type `t`. This helper returns `t` if it is already being 554 /// lowered to avoid infinite loops. 555 mlir::Type getTypeIfDerivedAlreadyInConstruction( 556 const Fortran::lower::SymbolRef derivedSym) const { 557 for (const auto &[sym, type] : derivedTypeInConstruction) 558 if (sym == derivedSym) 559 return type; 560 return {}; 561 } 562 563 void popDerivedTypeInConstruction() { 564 assert(!derivedTypeInConstruction.empty()); 565 derivedTypeInConstruction.pop_back(); 566 } 567 568 /// Stack derived type being processed to avoid infinite loops in case of 569 /// recursive derived types. The depth of derived types is expected to be 570 /// shallow (<10), so a SmallVector is sufficient. 571 llvm::SmallVector<std::pair<const Fortran::lower::SymbolRef, mlir::Type>> 572 derivedTypeInConstruction; 573 Fortran::lower::AbstractConverter &converter; 574 mlir::MLIRContext *context; 575 }; 576 } // namespace 577 578 mlir::Type Fortran::lower::getFIRType(mlir::MLIRContext *context, 579 Fortran::common::TypeCategory tc, 580 int kind, 581 llvm::ArrayRef<LenParameterTy> params) { 582 return genFIRType(context, tc, kind, params); 583 } 584 585 mlir::Type Fortran::lower::translateDerivedTypeToFIRType( 586 Fortran::lower::AbstractConverter &converter, 587 const Fortran::semantics::DerivedTypeSpec &tySpec) { 588 return TypeBuilderImpl{converter}.genDerivedType(tySpec); 589 } 590 591 mlir::Type Fortran::lower::translateSomeExprToFIRType( 592 Fortran::lower::AbstractConverter &converter, const SomeExpr &expr) { 593 return TypeBuilderImpl{converter}.genExprType(expr); 594 } 595 596 mlir::Type Fortran::lower::translateSymbolToFIRType( 597 Fortran::lower::AbstractConverter &converter, const SymbolRef symbol) { 598 return TypeBuilderImpl{converter}.genSymbolType(symbol); 599 } 600 601 mlir::Type Fortran::lower::translateVariableToFIRType( 602 Fortran::lower::AbstractConverter &converter, 603 const Fortran::lower::pft::Variable &var) { 604 return TypeBuilderImpl{converter}.genVariableType(var); 605 } 606 607 mlir::Type Fortran::lower::convertReal(mlir::MLIRContext *context, int kind) { 608 return genRealType(context, kind); 609 } 610 611 bool Fortran::lower::isDerivedTypeWithLenParameters( 612 const Fortran::semantics::Symbol &sym) { 613 if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType()) 614 if (const Fortran::semantics::DerivedTypeSpec *derived = 615 declTy->AsDerived()) 616 return Fortran::semantics::CountLenParameters(*derived) > 0; 617 return false; 618 } 619 620 template <typename T> 621 mlir::Type Fortran::lower::TypeBuilder<T>::genType( 622 Fortran::lower::AbstractConverter &converter, 623 const Fortran::evaluate::FunctionRef<T> &funcRef) { 624 return TypeBuilderImpl{converter}.genExprType(funcRef); 625 } 626 627 const Fortran::semantics::DerivedTypeSpec & 628 Fortran::lower::ComponentReverseIterator::advanceToParentType() { 629 const Fortran::semantics::Scope *scope = currentParentType->GetScope(); 630 auto parentComp = 631 DEREF(scope).find(currentTypeDetails->GetParentComponentName().value()); 632 assert(parentComp != scope->cend() && "failed to get parent component"); 633 setCurrentType(parentComp->second->GetType()->derivedTypeSpec()); 634 return *currentParentType; 635 } 636 637 void Fortran::lower::ComponentReverseIterator::setCurrentType( 638 const Fortran::semantics::DerivedTypeSpec &derived) { 639 currentParentType = &derived; 640 currentTypeDetails = ¤tParentType->typeSymbol() 641 .get<Fortran::semantics::DerivedTypeDetails>(); 642 componentIt = currentTypeDetails->componentNames().crbegin(); 643 componentItEnd = currentTypeDetails->componentNames().crend(); 644 } 645 646 using namespace Fortran::evaluate; 647 using namespace Fortran::common; 648 FOR_EACH_SPECIFIC_TYPE(template class Fortran::lower::TypeBuilder, ) 649