1 //===-- lib/Evaluate/intrinsics.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/intrinsics.h" 10 #include "flang/Common/Fortran.h" 11 #include "flang/Common/enum-set.h" 12 #include "flang/Common/idioms.h" 13 #include "flang/Evaluate/common.h" 14 #include "flang/Evaluate/expression.h" 15 #include "flang/Evaluate/fold.h" 16 #include "flang/Evaluate/shape.h" 17 #include "flang/Evaluate/tools.h" 18 #include "flang/Evaluate/type.h" 19 #include "llvm/Support/raw_ostream.h" 20 #include <algorithm> 21 #include <map> 22 #include <string> 23 #include <utility> 24 25 using namespace Fortran::parser::literals; 26 27 namespace Fortran::evaluate { 28 29 class FoldingContext; 30 31 // This file defines the supported intrinsic procedures and implements 32 // their recognition and validation. It is largely table-driven. See 33 // documentation/intrinsics.md and section 16 of the Fortran 2018 standard 34 // for full details on each of the intrinsics. Be advised, they have 35 // complicated details, and the design of these tables has to accommodate 36 // that complexity. 37 38 // Dummy arguments to generic intrinsic procedures are each specified by 39 // their keyword name (rarely used, but always defined), allowable type 40 // categories, a kind pattern, a rank pattern, and information about 41 // optionality and defaults. The kind and rank patterns are represented 42 // here with code values that are significant to the matching/validation engine. 43 44 // An actual argument to an intrinsic procedure may be a procedure itself 45 // only if the dummy argument is Rank::reduceOperation, 46 // KindCode::addressable, or the special case of NULL(MOLD=procedurePointer). 47 48 // These are small bit-sets of type category enumerators. 49 // Note that typeless (BOZ literal) values don't have a distinct type category. 50 // These typeless arguments are represented in the tables as if they were 51 // INTEGER with a special "typeless" kind code. Arguments of intrinsic types 52 // that can also be typeless values are encoded with an "elementalOrBOZ" 53 // rank pattern. 54 // Assumed-type (TYPE(*)) dummy arguments can be forwarded along to some 55 // intrinsic functions that accept AnyType + Rank::anyOrAssumedRank or 56 // AnyType + Kind::addressable. 57 using CategorySet = common::EnumSet<TypeCategory, 8>; 58 static constexpr CategorySet IntType{TypeCategory::Integer}; 59 static constexpr CategorySet RealType{TypeCategory::Real}; 60 static constexpr CategorySet ComplexType{TypeCategory::Complex}; 61 static constexpr CategorySet CharType{TypeCategory::Character}; 62 static constexpr CategorySet LogicalType{TypeCategory::Logical}; 63 static constexpr CategorySet IntOrRealType{IntType | RealType}; 64 static constexpr CategorySet FloatingType{RealType | ComplexType}; 65 static constexpr CategorySet NumericType{IntType | RealType | ComplexType}; 66 static constexpr CategorySet RelatableType{IntType | RealType | CharType}; 67 static constexpr CategorySet DerivedType{TypeCategory::Derived}; 68 static constexpr CategorySet IntrinsicType{ 69 IntType | RealType | ComplexType | CharType | LogicalType}; 70 static constexpr CategorySet AnyType{IntrinsicType | DerivedType}; 71 72 ENUM_CLASS(KindCode, none, defaultIntegerKind, 73 defaultRealKind, // is also the default COMPLEX kind 74 doublePrecision, defaultCharKind, defaultLogicalKind, 75 any, // matches any kind value; each instance is independent 76 same, // match any kind, but all "same" kinds must be equal 77 operand, // match any kind, with promotion (non-standard) 78 typeless, // BOZ literals are INTEGER with this kind 79 teamType, // TEAM_TYPE from module ISO_FORTRAN_ENV (for coarrays) 80 kindArg, // this argument is KIND= 81 effectiveKind, // for function results: "kindArg" value, possibly defaulted 82 dimArg, // this argument is DIM= 83 likeMultiply, // for DOT_PRODUCT and MATMUL 84 subscript, // address-sized integer 85 size, // default KIND= for SIZE(), UBOUND, &c. 86 addressable, // for PRESENT(), &c.; anything (incl. procedure) but BOZ 87 ) 88 89 struct TypePattern { 90 CategorySet categorySet; 91 KindCode kindCode{KindCode::none}; 92 llvm::raw_ostream &Dump(llvm::raw_ostream &) const; 93 }; 94 95 // Abbreviations for argument and result patterns in the intrinsic prototypes: 96 97 // Match specific kinds of intrinsic types 98 static constexpr TypePattern DefaultInt{IntType, KindCode::defaultIntegerKind}; 99 static constexpr TypePattern DefaultReal{RealType, KindCode::defaultRealKind}; 100 static constexpr TypePattern DefaultComplex{ 101 ComplexType, KindCode::defaultRealKind}; 102 static constexpr TypePattern DefaultChar{CharType, KindCode::defaultCharKind}; 103 static constexpr TypePattern DefaultLogical{ 104 LogicalType, KindCode::defaultLogicalKind}; 105 static constexpr TypePattern BOZ{IntType, KindCode::typeless}; 106 static constexpr TypePattern TEAM_TYPE{IntType, KindCode::teamType}; 107 static constexpr TypePattern DoublePrecision{ 108 RealType, KindCode::doublePrecision}; 109 static constexpr TypePattern DoublePrecisionComplex{ 110 ComplexType, KindCode::doublePrecision}; 111 static constexpr TypePattern SubscriptInt{IntType, KindCode::subscript}; 112 113 // Match any kind of some intrinsic or derived types 114 static constexpr TypePattern AnyInt{IntType, KindCode::any}; 115 static constexpr TypePattern AnyReal{RealType, KindCode::any}; 116 static constexpr TypePattern AnyIntOrReal{IntOrRealType, KindCode::any}; 117 static constexpr TypePattern AnyComplex{ComplexType, KindCode::any}; 118 static constexpr TypePattern AnyFloating{FloatingType, KindCode::any}; 119 static constexpr TypePattern AnyNumeric{NumericType, KindCode::any}; 120 static constexpr TypePattern AnyChar{CharType, KindCode::any}; 121 static constexpr TypePattern AnyLogical{LogicalType, KindCode::any}; 122 static constexpr TypePattern AnyRelatable{RelatableType, KindCode::any}; 123 static constexpr TypePattern AnyIntrinsic{IntrinsicType, KindCode::any}; 124 static constexpr TypePattern ExtensibleDerived{DerivedType, KindCode::any}; 125 static constexpr TypePattern AnyData{AnyType, KindCode::any}; 126 127 // Type is irrelevant, but not BOZ (for PRESENT(), OPTIONAL(), &c.) 128 static constexpr TypePattern Addressable{AnyType, KindCode::addressable}; 129 130 // Match some kind of some intrinsic type(s); all "Same" values must match, 131 // even when not in the same category (e.g., SameComplex and SameReal). 132 // Can be used to specify a result so long as at least one argument is 133 // a "Same". 134 static constexpr TypePattern SameInt{IntType, KindCode::same}; 135 static constexpr TypePattern SameReal{RealType, KindCode::same}; 136 static constexpr TypePattern SameIntOrReal{IntOrRealType, KindCode::same}; 137 static constexpr TypePattern SameComplex{ComplexType, KindCode::same}; 138 static constexpr TypePattern SameFloating{FloatingType, KindCode::same}; 139 static constexpr TypePattern SameNumeric{NumericType, KindCode::same}; 140 static constexpr TypePattern SameChar{CharType, KindCode::same}; 141 static constexpr TypePattern SameLogical{LogicalType, KindCode::same}; 142 static constexpr TypePattern SameRelatable{RelatableType, KindCode::same}; 143 static constexpr TypePattern SameIntrinsic{IntrinsicType, KindCode::same}; 144 static constexpr TypePattern SameDerivedType{ 145 CategorySet{TypeCategory::Derived}, KindCode::same}; 146 static constexpr TypePattern SameType{AnyType, KindCode::same}; 147 148 // Match some kind of some INTEGER or REAL type(s); when argument types 149 // &/or kinds differ, their values are converted as if they were operands to 150 // an intrinsic operation like addition. This is a nonstandard but nearly 151 // universal extension feature. 152 static constexpr TypePattern OperandReal{RealType, KindCode::operand}; 153 static constexpr TypePattern OperandIntOrReal{IntOrRealType, KindCode::operand}; 154 155 // For DOT_PRODUCT and MATMUL, the result type depends on the arguments 156 static constexpr TypePattern ResultLogical{LogicalType, KindCode::likeMultiply}; 157 static constexpr TypePattern ResultNumeric{NumericType, KindCode::likeMultiply}; 158 159 // Result types with known category and KIND= 160 static constexpr TypePattern KINDInt{IntType, KindCode::effectiveKind}; 161 static constexpr TypePattern KINDReal{RealType, KindCode::effectiveKind}; 162 static constexpr TypePattern KINDComplex{ComplexType, KindCode::effectiveKind}; 163 static constexpr TypePattern KINDChar{CharType, KindCode::effectiveKind}; 164 static constexpr TypePattern KINDLogical{LogicalType, KindCode::effectiveKind}; 165 166 // The default rank pattern for dummy arguments and function results is 167 // "elemental". 168 ENUM_CLASS(Rank, 169 elemental, // scalar, or array that conforms with other array arguments 170 elementalOrBOZ, // elemental, or typeless BOZ literal scalar 171 scalar, vector, 172 shape, // INTEGER vector of known length and no negative element 173 matrix, 174 array, // not scalar, rank is known and greater than zero 175 known, // rank is known and can be scalar 176 anyOrAssumedRank, // rank can be unknown; assumed-type TYPE(*) allowed 177 conformable, // scalar, or array of same rank & shape as "array" argument 178 reduceOperation, // a pure function with constraints for REDUCE 179 dimReduced, // scalar if no DIM= argument, else rank(array)-1 180 dimRemoved, // scalar, or rank(array)-1 181 rankPlus1, // rank(known)+1 182 shaped, // rank is length of SHAPE vector 183 ) 184 185 ENUM_CLASS(Optionality, required, optional, 186 defaultsToSameKind, // for MatchingDefaultKIND 187 defaultsToDefaultForResult, // for DefaultingKIND 188 defaultsToSizeKind, // for SizeDefaultKIND 189 repeats, // for MAX/MIN and their several variants 190 ) 191 192 struct IntrinsicDummyArgument { 193 const char *keyword{nullptr}; 194 TypePattern typePattern; 195 Rank rank{Rank::elemental}; 196 Optionality optionality{Optionality::required}; 197 llvm::raw_ostream &Dump(llvm::raw_ostream &) const; 198 }; 199 200 // constexpr abbreviations for popular arguments: 201 // DefaultingKIND is a KIND= argument whose default value is the appropriate 202 // KIND(0), KIND(0.0), KIND(''), &c. value for the function result. 203 static constexpr IntrinsicDummyArgument DefaultingKIND{"kind", 204 {IntType, KindCode::kindArg}, Rank::scalar, 205 Optionality::defaultsToDefaultForResult}; 206 // MatchingDefaultKIND is a KIND= argument whose default value is the 207 // kind of any "Same" function argument (viz., the one whose kind pattern is 208 // "same"). 209 static constexpr IntrinsicDummyArgument MatchingDefaultKIND{"kind", 210 {IntType, KindCode::kindArg}, Rank::scalar, 211 Optionality::defaultsToSameKind}; 212 // SizeDefaultKind is a KIND= argument whose default value should be 213 // the kind of INTEGER used for address calculations, and can be 214 // set so with a compiler flag; but the standard mandates the 215 // kind of default INTEGER. 216 static constexpr IntrinsicDummyArgument SizeDefaultKIND{"kind", 217 {IntType, KindCode::kindArg}, Rank::scalar, 218 Optionality::defaultsToSizeKind}; 219 static constexpr IntrinsicDummyArgument RequiredDIM{ 220 "dim", {IntType, KindCode::dimArg}, Rank::scalar, Optionality::required}; 221 static constexpr IntrinsicDummyArgument OptionalDIM{ 222 "dim", {IntType, KindCode::dimArg}, Rank::scalar, Optionality::optional}; 223 static constexpr IntrinsicDummyArgument OptionalMASK{ 224 "mask", AnyLogical, Rank::conformable, Optionality::optional}; 225 226 struct IntrinsicInterface { 227 static constexpr int maxArguments{7}; // if not a MAX/MIN(...) 228 const char *name{nullptr}; 229 IntrinsicDummyArgument dummy[maxArguments]; 230 TypePattern result; 231 Rank rank{Rank::elemental}; 232 std::optional<SpecificCall> Match(const CallCharacteristics &, 233 const common::IntrinsicTypeDefaultKinds &, ActualArguments &, 234 FoldingContext &context) const; 235 int CountArguments() const; 236 llvm::raw_ostream &Dump(llvm::raw_ostream &) const; 237 }; 238 239 int IntrinsicInterface::CountArguments() const { 240 int n{0}; 241 while (n < maxArguments && dummy[n].keyword) { 242 ++n; 243 } 244 return n; 245 } 246 247 // GENERIC INTRINSIC FUNCTION INTERFACES 248 // Each entry in this table defines a pattern. Some intrinsic 249 // functions have more than one such pattern. Besides the name 250 // of the intrinsic function, each pattern has specifications for 251 // the dummy arguments and for the result of the function. 252 // The dummy argument patterns each have a name (these are from the 253 // standard, but rarely appear in actual code), a type and kind 254 // pattern, allowable ranks, and optionality indicators. 255 // Be advised, the default rank pattern is "elemental". 256 static const IntrinsicInterface genericIntrinsicFunction[]{ 257 {"abs", {{"a", SameIntOrReal}}, SameIntOrReal}, 258 {"abs", {{"a", SameComplex}}, SameReal}, 259 {"achar", {{"i", AnyInt, Rank::elementalOrBOZ}, DefaultingKIND}, KINDChar}, 260 {"acos", {{"x", SameFloating}}, SameFloating}, 261 {"acosd", {{"x", SameFloating}}, SameFloating}, 262 {"acosh", {{"x", SameFloating}}, SameFloating}, 263 {"adjustl", {{"string", SameChar}}, SameChar}, 264 {"adjustr", {{"string", SameChar}}, SameChar}, 265 {"aimag", {{"x", SameComplex}}, SameReal}, 266 {"aint", {{"a", SameReal}, MatchingDefaultKIND}, KINDReal}, 267 {"all", {{"mask", SameLogical, Rank::array}, OptionalDIM}, SameLogical, 268 Rank::dimReduced}, 269 {"allocated", {{"array", AnyData, Rank::array}}, DefaultLogical}, 270 {"allocated", {{"scalar", AnyData, Rank::scalar}}, DefaultLogical}, 271 {"anint", {{"a", SameReal}, MatchingDefaultKIND}, KINDReal}, 272 {"any", {{"mask", SameLogical, Rank::array}, OptionalDIM}, SameLogical, 273 Rank::dimReduced}, 274 {"asin", {{"x", SameFloating}}, SameFloating}, 275 {"asind", {{"x", SameFloating}}, SameFloating}, 276 {"asinh", {{"x", SameFloating}}, SameFloating}, 277 {"associated", 278 {{"pointer", Addressable, Rank::known}, 279 {"target", Addressable, Rank::known, Optionality::optional}}, 280 DefaultLogical}, 281 {"atan", {{"x", SameFloating}}, SameFloating}, 282 {"atand", {{"x", SameFloating}}, SameFloating}, 283 {"atan", {{"y", OperandReal}, {"x", OperandReal}}, OperandReal}, 284 {"atand", {{"y", OperandReal}, {"x", OperandReal}}, OperandReal}, 285 {"atan2", {{"y", OperandReal}, {"x", OperandReal}}, OperandReal}, 286 {"atan2d", {{"y", OperandReal}, {"x", OperandReal}}, OperandReal}, 287 {"atanh", {{"x", SameFloating}}, SameFloating}, 288 {"bessel_j0", {{"x", SameReal}}, SameReal}, 289 {"bessel_j1", {{"x", SameReal}}, SameReal}, 290 {"bessel_jn", {{"n", AnyInt}, {"x", SameReal}}, SameReal}, 291 {"bessel_jn", 292 {{"n1", AnyInt, Rank::scalar}, {"n2", AnyInt, Rank::scalar}, 293 {"x", SameReal, Rank::scalar}}, 294 SameReal, Rank::vector}, 295 {"bessel_y0", {{"x", SameReal}}, SameReal}, 296 {"bessel_y1", {{"x", SameReal}}, SameReal}, 297 {"bessel_yn", {{"n", AnyInt}, {"x", SameReal}}, SameReal}, 298 {"bessel_yn", 299 {{"n1", AnyInt, Rank::scalar}, {"n2", AnyInt, Rank::scalar}, 300 {"x", SameReal, Rank::scalar}}, 301 SameReal, Rank::vector}, 302 {"bge", 303 {{"i", AnyInt, Rank::elementalOrBOZ}, 304 {"j", AnyInt, Rank::elementalOrBOZ}}, 305 DefaultLogical}, 306 {"bgt", 307 {{"i", AnyInt, Rank::elementalOrBOZ}, 308 {"j", AnyInt, Rank::elementalOrBOZ}}, 309 DefaultLogical}, 310 {"bit_size", {{"i", SameInt, Rank::anyOrAssumedRank}}, SameInt, 311 Rank::scalar}, 312 {"ble", 313 {{"i", AnyInt, Rank::elementalOrBOZ}, 314 {"j", AnyInt, Rank::elementalOrBOZ}}, 315 DefaultLogical}, 316 {"blt", 317 {{"i", AnyInt, Rank::elementalOrBOZ}, 318 {"j", AnyInt, Rank::elementalOrBOZ}}, 319 DefaultLogical}, 320 {"btest", {{"i", AnyInt, Rank::elementalOrBOZ}, {"pos", AnyInt}}, 321 DefaultLogical}, 322 {"ceiling", {{"a", AnyReal}, DefaultingKIND}, KINDInt}, 323 {"char", {{"i", AnyInt, Rank::elementalOrBOZ}, DefaultingKIND}, KINDChar}, 324 {"cmplx", {{"x", AnyComplex}, DefaultingKIND}, KINDComplex}, 325 {"cmplx", 326 {{"x", AnyIntOrReal, Rank::elementalOrBOZ}, 327 {"y", AnyIntOrReal, Rank::elementalOrBOZ, Optionality::optional}, 328 DefaultingKIND}, 329 KINDComplex}, 330 {"command_argument_count", {}, DefaultInt, Rank::scalar}, 331 {"conjg", {{"z", SameComplex}}, SameComplex}, 332 {"cos", {{"x", SameFloating}}, SameFloating}, 333 {"cosd", {{"x", SameFloating}}, SameFloating}, 334 {"cosh", {{"x", SameFloating}}, SameFloating}, 335 {"count", {{"mask", AnyLogical, Rank::array}, OptionalDIM, DefaultingKIND}, 336 KINDInt, Rank::dimReduced}, 337 {"cshift", 338 {{"array", SameType, Rank::array}, {"shift", AnyInt, Rank::dimRemoved}, 339 OptionalDIM}, 340 SameType, Rank::conformable}, 341 {"dble", {{"a", AnyNumeric, Rank::elementalOrBOZ}}, DoublePrecision}, 342 {"digits", {{"x", AnyIntOrReal, Rank::anyOrAssumedRank}}, DefaultInt, 343 Rank::scalar}, 344 {"dim", {{"x", OperandIntOrReal}, {"y", OperandIntOrReal}}, 345 OperandIntOrReal}, 346 {"dot_product", 347 {{"vector_a", AnyLogical, Rank::vector}, 348 {"vector_b", AnyLogical, Rank::vector}}, 349 ResultLogical, Rank::scalar}, 350 {"dot_product", 351 {{"vector_a", AnyComplex, Rank::vector}, 352 {"vector_b", AnyNumeric, Rank::vector}}, 353 ResultNumeric, Rank::scalar}, // conjugates vector_a 354 {"dot_product", 355 {{"vector_a", AnyIntOrReal, Rank::vector}, 356 {"vector_b", AnyNumeric, Rank::vector}}, 357 ResultNumeric, Rank::scalar}, 358 {"dprod", {{"x", DefaultReal}, {"y", DefaultReal}}, DoublePrecision}, 359 {"dshiftl", 360 {{"i", SameInt}, {"j", SameInt, Rank::elementalOrBOZ}, 361 {"shift", AnyInt}}, 362 SameInt}, 363 {"dshiftl", {{"i", BOZ}, {"j", SameInt}, {"shift", AnyInt}}, SameInt}, 364 {"dshiftr", 365 {{"i", SameInt}, {"j", SameInt, Rank::elementalOrBOZ}, 366 {"shift", AnyInt}}, 367 SameInt}, 368 {"dshiftr", {{"i", BOZ}, {"j", SameInt}, {"shift", AnyInt}}, SameInt}, 369 {"eoshift", 370 {{"array", SameIntrinsic, Rank::array}, 371 {"shift", AnyInt, Rank::dimRemoved}, 372 {"boundary", SameIntrinsic, Rank::dimRemoved, 373 Optionality::optional}, 374 OptionalDIM}, 375 SameIntrinsic, Rank::conformable}, 376 {"eoshift", 377 {{"array", SameDerivedType, Rank::array}, 378 {"shift", AnyInt, Rank::dimRemoved}, 379 {"boundary", SameDerivedType, Rank::dimRemoved}, OptionalDIM}, 380 SameDerivedType, Rank::conformable}, 381 {"epsilon", {{"x", SameReal, Rank::anyOrAssumedRank}}, SameReal, 382 Rank::scalar}, 383 {"erf", {{"x", SameReal}}, SameReal}, 384 {"erfc", {{"x", SameReal}}, SameReal}, 385 {"erfc_scaled", {{"x", SameReal}}, SameReal}, 386 {"exp", {{"x", SameFloating}}, SameFloating}, 387 {"exponent", {{"x", AnyReal}}, DefaultInt}, 388 {"extends_type_of", 389 {{"a", ExtensibleDerived, Rank::anyOrAssumedRank}, 390 {"mold", ExtensibleDerived, Rank::anyOrAssumedRank}}, 391 DefaultLogical, Rank::scalar}, 392 {"findloc", 393 {{"array", AnyNumeric, Rank::array}, 394 {"value", AnyNumeric, Rank::scalar}, RequiredDIM, OptionalMASK, 395 SizeDefaultKIND, 396 {"back", AnyLogical, Rank::scalar, Optionality::optional}}, 397 KINDInt, Rank::dimRemoved}, 398 {"findloc", 399 {{"array", AnyNumeric, Rank::array}, 400 {"value", AnyNumeric, Rank::scalar}, OptionalMASK, SizeDefaultKIND, 401 {"back", AnyLogical, Rank::scalar, Optionality::optional}}, 402 KINDInt, Rank::vector}, 403 {"findloc", 404 {{"array", SameChar, Rank::array}, {"value", SameChar, Rank::scalar}, 405 RequiredDIM, OptionalMASK, SizeDefaultKIND, 406 {"back", AnyLogical, Rank::scalar, Optionality::optional}}, 407 KINDInt, Rank::dimRemoved}, 408 {"findloc", 409 {{"array", SameChar, Rank::array}, {"value", SameChar, Rank::scalar}, 410 OptionalMASK, SizeDefaultKIND, 411 {"back", AnyLogical, Rank::scalar, Optionality::optional}}, 412 KINDInt, Rank::vector}, 413 {"findloc", 414 {{"array", AnyLogical, Rank::array}, 415 {"value", AnyLogical, Rank::scalar}, RequiredDIM, OptionalMASK, 416 SizeDefaultKIND, 417 {"back", AnyLogical, Rank::scalar, Optionality::optional}}, 418 KINDInt, Rank::dimRemoved}, 419 {"findloc", 420 {{"array", AnyLogical, Rank::array}, 421 {"value", AnyLogical, Rank::scalar}, OptionalMASK, SizeDefaultKIND, 422 {"back", AnyLogical, Rank::scalar, Optionality::optional}}, 423 KINDInt, Rank::vector}, 424 {"floor", {{"a", AnyReal}, DefaultingKIND}, KINDInt}, 425 {"fraction", {{"x", SameReal}}, SameReal}, 426 {"gamma", {{"x", SameReal}}, SameReal}, 427 {"huge", {{"x", SameIntOrReal, Rank::anyOrAssumedRank}}, SameIntOrReal, 428 Rank::scalar}, 429 {"hypot", {{"x", OperandReal}, {"y", OperandReal}}, OperandReal}, 430 {"iachar", {{"c", AnyChar}, DefaultingKIND}, KINDInt}, 431 {"iall", {{"array", SameInt, Rank::array}, OptionalDIM, OptionalMASK}, 432 SameInt, Rank::dimReduced}, 433 {"iany", {{"array", SameInt, Rank::array}, OptionalDIM, OptionalMASK}, 434 SameInt, Rank::dimReduced}, 435 {"iparity", {{"array", SameInt, Rank::array}, OptionalDIM, OptionalMASK}, 436 SameInt, Rank::dimReduced}, 437 {"iand", {{"i", SameInt}, {"j", SameInt, Rank::elementalOrBOZ}}, SameInt}, 438 {"iand", {{"i", BOZ}, {"j", SameInt}}, SameInt}, 439 {"ibclr", {{"i", SameInt}, {"pos", AnyInt}}, SameInt}, 440 {"ibits", {{"i", SameInt}, {"pos", AnyInt}, {"len", AnyInt}}, SameInt}, 441 {"ibset", {{"i", SameInt}, {"pos", AnyInt}}, SameInt}, 442 {"ichar", {{"c", AnyChar}, DefaultingKIND}, KINDInt}, 443 {"ieor", {{"i", SameInt}, {"j", SameInt, Rank::elementalOrBOZ}}, SameInt}, 444 {"ieor", {{"i", BOZ}, {"j", SameInt}}, SameInt}, 445 {"image_status", 446 {{"image", SameInt}, 447 {"team", TEAM_TYPE, Rank::scalar, Optionality::optional}}, 448 DefaultInt}, 449 {"index", 450 {{"string", SameChar}, {"substring", SameChar}, 451 {"back", AnyLogical, Rank::scalar, Optionality::optional}, 452 DefaultingKIND}, 453 KINDInt}, 454 {"int", {{"a", AnyNumeric, Rank::elementalOrBOZ}, DefaultingKIND}, KINDInt}, 455 {"int_ptr_kind", {}, DefaultInt, Rank::scalar}, 456 {"ior", {{"i", SameInt}, {"j", SameInt, Rank::elementalOrBOZ}}, SameInt}, 457 {"ior", {{"i", BOZ}, {"j", SameInt}}, SameInt}, 458 {"ishft", {{"i", SameInt}, {"shift", AnyInt}}, SameInt}, 459 {"ishftc", 460 {{"i", SameInt}, {"shift", AnyInt}, 461 {"size", AnyInt, Rank::elemental, Optionality::optional}}, 462 SameInt}, 463 {"is_contiguous", {{"array", Addressable, Rank::anyOrAssumedRank}}, 464 DefaultLogical}, 465 {"is_iostat_end", {{"i", AnyInt}}, DefaultLogical}, 466 {"is_iostat_eor", {{"i", AnyInt}}, DefaultLogical}, 467 {"kind", {{"x", AnyIntrinsic}}, DefaultInt}, 468 {"lbound", 469 {{"array", AnyData, Rank::anyOrAssumedRank}, RequiredDIM, 470 SizeDefaultKIND}, 471 KINDInt, Rank::scalar}, 472 {"lbound", {{"array", AnyData, Rank::anyOrAssumedRank}, SizeDefaultKIND}, 473 KINDInt, Rank::vector}, 474 {"leadz", {{"i", AnyInt}}, DefaultInt}, 475 {"len", {{"string", AnyChar, Rank::anyOrAssumedRank}, DefaultingKIND}, 476 KINDInt, Rank::scalar}, 477 {"len_trim", {{"string", AnyChar}, DefaultingKIND}, KINDInt}, 478 {"lge", {{"string_a", SameChar}, {"string_b", SameChar}}, DefaultLogical}, 479 {"lgt", {{"string_a", SameChar}, {"string_b", SameChar}}, DefaultLogical}, 480 {"lle", {{"string_a", SameChar}, {"string_b", SameChar}}, DefaultLogical}, 481 {"llt", {{"string_a", SameChar}, {"string_b", SameChar}}, DefaultLogical}, 482 {"loc", {{"loc_argument", Addressable, Rank::anyOrAssumedRank}}, 483 SubscriptInt, Rank::scalar}, 484 {"log", {{"x", SameFloating}}, SameFloating}, 485 {"log10", {{"x", SameReal}}, SameReal}, 486 {"logical", {{"l", AnyLogical}, DefaultingKIND}, KINDLogical}, 487 {"log_gamma", {{"x", SameReal}}, SameReal}, 488 {"matmul", 489 {{"array_a", AnyLogical, Rank::vector}, 490 {"array_b", AnyLogical, Rank::matrix}}, 491 ResultLogical, Rank::vector}, 492 {"matmul", 493 {{"array_a", AnyLogical, Rank::matrix}, 494 {"array_b", AnyLogical, Rank::vector}}, 495 ResultLogical, Rank::vector}, 496 {"matmul", 497 {{"array_a", AnyLogical, Rank::matrix}, 498 {"array_b", AnyLogical, Rank::matrix}}, 499 ResultLogical, Rank::matrix}, 500 {"matmul", 501 {{"array_a", AnyNumeric, Rank::vector}, 502 {"array_b", AnyNumeric, Rank::matrix}}, 503 ResultNumeric, Rank::vector}, 504 {"matmul", 505 {{"array_a", AnyNumeric, Rank::matrix}, 506 {"array_b", AnyNumeric, Rank::vector}}, 507 ResultNumeric, Rank::vector}, 508 {"matmul", 509 {{"array_a", AnyNumeric, Rank::matrix}, 510 {"array_b", AnyNumeric, Rank::matrix}}, 511 ResultNumeric, Rank::matrix}, 512 {"maskl", {{"i", AnyInt}, DefaultingKIND}, KINDInt}, 513 {"maskr", {{"i", AnyInt}, DefaultingKIND}, KINDInt}, 514 {"max", 515 {{"a1", OperandIntOrReal}, {"a2", OperandIntOrReal}, 516 {"a3", OperandIntOrReal, Rank::elemental, Optionality::repeats}}, 517 OperandIntOrReal}, 518 {"max", 519 {{"a1", SameChar}, {"a2", SameChar}, 520 {"a3", SameChar, Rank::elemental, Optionality::repeats}}, 521 SameChar}, 522 {"maxexponent", {{"x", AnyReal, Rank::anyOrAssumedRank}}, DefaultInt, 523 Rank::scalar}, 524 {"maxloc", 525 {{"array", AnyRelatable, Rank::array}, OptionalDIM, OptionalMASK, 526 SizeDefaultKIND, 527 {"back", AnyLogical, Rank::scalar, Optionality::optional}}, 528 KINDInt, Rank::dimReduced}, 529 {"maxval", 530 {{"array", SameRelatable, Rank::array}, OptionalDIM, OptionalMASK}, 531 SameRelatable, Rank::dimReduced}, 532 {"merge", 533 {{"tsource", SameType}, {"fsource", SameType}, {"mask", AnyLogical}}, 534 SameType}, 535 {"merge_bits", 536 {{"i", SameInt}, {"j", SameInt, Rank::elementalOrBOZ}, 537 {"mask", SameInt, Rank::elementalOrBOZ}}, 538 SameInt}, 539 {"merge_bits", 540 {{"i", BOZ}, {"j", SameInt}, {"mask", SameInt, Rank::elementalOrBOZ}}, 541 SameInt}, 542 {"min", 543 {{"a1", OperandIntOrReal}, {"a2", OperandIntOrReal}, 544 {"a3", OperandIntOrReal, Rank::elemental, Optionality::repeats}}, 545 OperandIntOrReal}, 546 {"min", 547 {{"a1", SameChar}, {"a2", SameChar}, 548 {"a3", SameChar, Rank::elemental, Optionality::repeats}}, 549 SameChar}, 550 {"minexponent", {{"x", AnyReal, Rank::anyOrAssumedRank}}, DefaultInt, 551 Rank::scalar}, 552 {"minloc", 553 {{"array", AnyRelatable, Rank::array}, OptionalDIM, OptionalMASK, 554 SizeDefaultKIND, 555 {"back", AnyLogical, Rank::scalar, Optionality::optional}}, 556 KINDInt, Rank::dimReduced}, 557 {"minval", 558 {{"array", SameRelatable, Rank::array}, OptionalDIM, OptionalMASK}, 559 SameRelatable, Rank::dimReduced}, 560 {"mod", {{"a", OperandIntOrReal}, {"p", OperandIntOrReal}}, 561 OperandIntOrReal}, 562 {"modulo", {{"a", OperandIntOrReal}, {"p", OperandIntOrReal}}, 563 OperandIntOrReal}, 564 {"nearest", {{"x", SameReal}, {"s", AnyReal}}, SameReal}, 565 {"new_line", {{"x", SameChar, Rank::anyOrAssumedRank}}, SameChar, 566 Rank::scalar}, 567 {"nint", {{"a", AnyReal}, DefaultingKIND}, KINDInt}, 568 {"norm2", {{"x", SameReal, Rank::array}, OptionalDIM}, SameReal, 569 Rank::dimReduced}, 570 {"not", {{"i", SameInt}}, SameInt}, 571 // NULL() is a special case handled in Probe() below 572 {"out_of_range", 573 {{"x", AnyIntOrReal}, {"mold", AnyIntOrReal, Rank::scalar}}, 574 DefaultLogical}, 575 {"out_of_range", 576 {{"x", AnyReal}, {"mold", AnyInt, Rank::scalar}, 577 {"round", AnyLogical, Rank::scalar, Optionality::optional}}, 578 DefaultLogical}, 579 {"out_of_range", {{"x", AnyReal}, {"mold", AnyReal}}, DefaultLogical}, 580 {"pack", 581 {{"array", SameType, Rank::array}, 582 {"mask", AnyLogical, Rank::conformable}, 583 {"vector", SameType, Rank::vector, Optionality::optional}}, 584 SameType, Rank::vector}, 585 {"parity", {{"mask", SameLogical, Rank::array}, OptionalDIM}, SameLogical, 586 Rank::dimReduced}, 587 {"popcnt", {{"i", AnyInt}}, DefaultInt}, 588 {"poppar", {{"i", AnyInt}}, DefaultInt}, 589 {"product", 590 {{"array", SameNumeric, Rank::array}, OptionalDIM, OptionalMASK}, 591 SameNumeric, Rank::dimReduced}, 592 {"precision", {{"x", AnyFloating, Rank::anyOrAssumedRank}}, DefaultInt, 593 Rank::scalar}, 594 {"present", {{"a", Addressable, Rank::anyOrAssumedRank}}, DefaultLogical, 595 Rank::scalar}, 596 {"radix", {{"x", AnyIntOrReal, Rank::anyOrAssumedRank}}, DefaultInt, 597 Rank::scalar}, 598 {"range", {{"x", AnyNumeric, Rank::anyOrAssumedRank}}, DefaultInt, 599 Rank::scalar}, 600 {"rank", {{"a", AnyData, Rank::anyOrAssumedRank}}, DefaultInt, 601 Rank::scalar}, 602 {"real", {{"a", SameComplex, Rank::elemental}}, 603 SameReal}, // 16.9.160(4)(ii) 604 {"real", {{"a", AnyNumeric, Rank::elementalOrBOZ}, DefaultingKIND}, 605 KINDReal}, 606 {"reduce", 607 {{"array", SameType, Rank::array}, 608 {"operation", SameType, Rank::reduceOperation}, OptionalDIM, 609 OptionalMASK, {"identity", SameType, Rank::scalar}, 610 {"ordered", AnyLogical, Rank::scalar, Optionality::optional}}, 611 SameType, Rank::dimReduced}, 612 {"repeat", {{"string", SameChar, Rank::scalar}, {"ncopies", AnyInt}}, 613 SameChar, Rank::scalar}, 614 {"reshape", 615 {{"source", SameType, Rank::array}, {"shape", AnyInt, Rank::shape}, 616 {"pad", SameType, Rank::array, Optionality::optional}, 617 {"order", AnyInt, Rank::vector, Optionality::optional}}, 618 SameType, Rank::shaped}, 619 {"rrspacing", {{"x", SameReal}}, SameReal}, 620 {"same_type_as", 621 {{"a", ExtensibleDerived, Rank::anyOrAssumedRank}, 622 {"b", ExtensibleDerived, Rank::anyOrAssumedRank}}, 623 DefaultLogical, Rank::scalar}, 624 {"scale", {{"x", SameReal}, {"i", AnyInt}}, SameReal}, 625 {"scan", 626 {{"string", SameChar}, {"set", SameChar}, 627 {"back", AnyLogical, Rank::elemental, Optionality::optional}, 628 DefaultingKIND}, 629 KINDInt}, 630 {"selected_char_kind", {{"name", DefaultChar, Rank::scalar}}, DefaultInt, 631 Rank::scalar}, 632 {"selected_int_kind", {{"r", AnyInt, Rank::scalar}}, DefaultInt, 633 Rank::scalar}, 634 {"selected_real_kind", 635 {{"p", AnyInt, Rank::scalar}, 636 {"r", AnyInt, Rank::scalar, Optionality::optional}, 637 {"radix", AnyInt, Rank::scalar, Optionality::optional}}, 638 DefaultInt, Rank::scalar}, 639 {"selected_real_kind", 640 {{"p", AnyInt, Rank::scalar, Optionality::optional}, 641 {"r", AnyInt, Rank::scalar}, 642 {"radix", AnyInt, Rank::scalar, Optionality::optional}}, 643 DefaultInt, Rank::scalar}, 644 {"selected_real_kind", 645 {{"p", AnyInt, Rank::scalar, Optionality::optional}, 646 {"r", AnyInt, Rank::scalar, Optionality::optional}, 647 {"radix", AnyInt, Rank::scalar}}, 648 DefaultInt, Rank::scalar}, 649 {"set_exponent", {{"x", SameReal}, {"i", AnyInt}}, SameReal}, 650 {"shape", {{"source", AnyData, Rank::anyOrAssumedRank}, SizeDefaultKIND}, 651 KINDInt, Rank::vector}, 652 {"shifta", {{"i", SameInt}, {"shift", AnyInt}}, SameInt}, 653 {"shiftl", {{"i", SameInt}, {"shift", AnyInt}}, SameInt}, 654 {"shiftr", {{"i", SameInt}, {"shift", AnyInt}}, SameInt}, 655 {"sign", {{"a", SameIntOrReal}, {"b", SameIntOrReal}}, SameIntOrReal}, 656 {"sin", {{"x", SameFloating}}, SameFloating}, 657 {"sind", {{"x", SameFloating}}, SameFloating}, 658 {"sinh", {{"x", SameFloating}}, SameFloating}, 659 {"size", 660 {{"array", AnyData, Rank::anyOrAssumedRank}, OptionalDIM, 661 SizeDefaultKIND}, 662 KINDInt, Rank::scalar}, 663 {"spacing", {{"x", SameReal}}, SameReal}, 664 {"spread", 665 {{"source", SameType, Rank::known}, RequiredDIM, 666 {"ncopies", AnyInt, Rank::scalar}}, 667 SameType, Rank::rankPlus1}, 668 {"sqrt", {{"x", SameFloating}}, SameFloating}, 669 {"storage_size", {{"a", AnyData, Rank::anyOrAssumedRank}, SizeDefaultKIND}, 670 KINDInt, Rank::scalar}, 671 {"sum", {{"array", SameNumeric, Rank::array}, OptionalDIM, OptionalMASK}, 672 SameNumeric, Rank::dimReduced}, 673 {"tan", {{"x", SameFloating}}, SameFloating}, 674 {"tand", {{"x", SameFloating}}, SameFloating}, 675 {"tanh", {{"x", SameFloating}}, SameFloating}, 676 {"tiny", {{"x", SameReal, Rank::anyOrAssumedRank}}, SameReal, Rank::scalar}, 677 {"trailz", {{"i", AnyInt}}, DefaultInt}, 678 {"transfer", 679 {{"source", AnyData, Rank::known}, {"mold", SameType, Rank::scalar}}, 680 SameType, Rank::scalar}, 681 {"transfer", 682 {{"source", AnyData, Rank::known}, {"mold", SameType, Rank::array}}, 683 SameType, Rank::vector}, 684 {"transfer", 685 {{"source", AnyData, Rank::anyOrAssumedRank}, 686 {"mold", SameType, Rank::anyOrAssumedRank}, 687 {"size", AnyInt, Rank::scalar}}, 688 SameType, Rank::vector}, 689 {"transpose", {{"matrix", SameType, Rank::matrix}}, SameType, Rank::matrix}, 690 {"trim", {{"string", SameChar, Rank::scalar}}, SameChar, Rank::scalar}, 691 {"ubound", 692 {{"array", AnyData, Rank::anyOrAssumedRank}, RequiredDIM, 693 SizeDefaultKIND}, 694 KINDInt, Rank::scalar}, 695 {"ubound", {{"array", AnyData, Rank::anyOrAssumedRank}, SizeDefaultKIND}, 696 KINDInt, Rank::vector}, 697 {"unpack", 698 {{"vector", SameType, Rank::vector}, {"mask", AnyLogical, Rank::array}, 699 {"field", SameType, Rank::conformable}}, 700 SameType, Rank::conformable}, 701 {"verify", 702 {{"string", SameChar}, {"set", SameChar}, 703 {"back", AnyLogical, Rank::elemental, Optionality::optional}, 704 DefaultingKIND}, 705 KINDInt}, 706 }; 707 708 // TODO: Coarray intrinsic functions 709 // LCOBOUND, UCOBOUND, FAILED_IMAGES, GET_TEAM, IMAGE_INDEX, 710 // NUM_IMAGES, STOPPED_IMAGES, TEAM_NUMBER, THIS_IMAGE, 711 // COSHAPE 712 // TODO: Non-standard intrinsic functions 713 // AND, OR, XOR, LSHIFT, RSHIFT, SHIFT, ZEXT, IZEXT, 714 // COMPL, EQV, NEQV, INT8, JINT, JNINT, KNINT, 715 // QCMPLX, DFLOAT, QEXT, QFLOAT, QREAL, DNUM, 716 // INUM, JNUM, KNUM, QNUM, RNUM, RAN, RANF, ILEN, SIZEOF, 717 // MCLOCK, SECNDS, COTAN, IBCHNG, ISHA, ISHC, ISHL, IXOR 718 // IARG, IARGC, NARGS, NUMARG, BADDRESS, IADDR, CACHESIZE, 719 // EOF, FP_CLASS, INT_PTR_KIND, ISNAN, MALLOC 720 // probably more (these are PGI + Intel, possibly incomplete) 721 // TODO: Optionally warn on use of non-standard intrinsics: 722 // LOC, probably others 723 // TODO: Optionally warn on operand promotion extension 724 725 // The following table contains the intrinsic functions listed in 726 // Tables 16.2 and 16.3 in Fortran 2018. The "unrestricted" functions 727 // in Table 16.2 can be used as actual arguments, PROCEDURE() interfaces, 728 // and procedure pointer targets. 729 // Note that the restricted conversion functions dcmplx, dreal, float, idint, 730 // ifix, and sngl are extended to accept any argument kind because this is a 731 // common Fortran compilers behavior, and as far as we can tell, is safe and 732 // useful. 733 struct SpecificIntrinsicInterface : public IntrinsicInterface { 734 const char *generic{nullptr}; 735 bool isRestrictedSpecific{false}; 736 // Exact actual/dummy type matching is required by default for specific 737 // intrinsics. If useGenericAndForceResultType is set, then the probing will 738 // also attempt to use the related generic intrinsic and to convert the result 739 // to the specific intrinsic result type if needed. 740 // This is not enabled on all specific intrinsics because an alternative 741 // is to convert the actual arguments to the required dummy types and this is 742 // not numerically equivalent. 743 // e.g. IABS(INT(i), INT(j)) not equiv to INT(ABS(i, j)). 744 // This is allowed for restricted min/max specific functions because 745 // the expected behavior is clear from their definitions. A warning is though 746 // always emitted because other compilers' behavior is not ubiquitous here. 747 bool useGenericAndForceResultType{false}; 748 }; 749 750 static const SpecificIntrinsicInterface specificIntrinsicFunction[]{ 751 {{"abs", {{"a", DefaultReal}}, DefaultReal}}, 752 {{"acos", {{"x", DefaultReal}}, DefaultReal}}, 753 {{"aimag", {{"z", DefaultComplex}}, DefaultReal}}, 754 {{"aint", {{"a", DefaultReal}}, DefaultReal}}, 755 {{"alog", {{"x", DefaultReal}}, DefaultReal}, "log"}, 756 {{"alog10", {{"x", DefaultReal}}, DefaultReal}, "log10"}, 757 {{"amax0", 758 {{"a1", DefaultInt}, {"a2", DefaultInt}, 759 {"a3", DefaultInt, Rank::elemental, Optionality::repeats}}, 760 DefaultReal}, 761 "max", true, true}, 762 {{"amax1", 763 {{"a1", DefaultReal}, {"a2", DefaultReal}, 764 {"a3", DefaultReal, Rank::elemental, Optionality::repeats}}, 765 DefaultReal}, 766 "max", true, true}, 767 {{"amin0", 768 {{"a1", DefaultInt}, {"a2", DefaultInt}, 769 {"a3", DefaultInt, Rank::elemental, Optionality::repeats}}, 770 DefaultReal}, 771 "min", true, true}, 772 {{"amin1", 773 {{"a1", DefaultReal}, {"a2", DefaultReal}, 774 {"a3", DefaultReal, Rank::elemental, Optionality::repeats}}, 775 DefaultReal}, 776 "min", true, true}, 777 {{"amod", {{"a", DefaultReal}, {"p", DefaultReal}}, DefaultReal}, "mod"}, 778 {{"anint", {{"a", DefaultReal}}, DefaultReal}}, 779 {{"asin", {{"x", DefaultReal}}, DefaultReal}}, 780 {{"atan", {{"x", DefaultReal}}, DefaultReal}}, 781 {{"atan2", {{"y", DefaultReal}, {"x", DefaultReal}}, DefaultReal}}, 782 {{"cabs", {{"a", DefaultComplex}}, DefaultReal}, "abs"}, 783 {{"ccos", {{"a", DefaultComplex}}, DefaultComplex}, "cos"}, 784 {{"cdabs", {{"a", DoublePrecisionComplex}}, DoublePrecision}, "abs"}, 785 {{"cdcos", {{"a", DoublePrecisionComplex}}, DoublePrecisionComplex}, "cos"}, 786 {{"cdexp", {{"a", DoublePrecisionComplex}}, DoublePrecisionComplex}, "exp"}, 787 {{"cdlog", {{"a", DoublePrecisionComplex}}, DoublePrecisionComplex}, "log"}, 788 {{"cdsin", {{"a", DoublePrecisionComplex}}, DoublePrecisionComplex}, "sin"}, 789 {{"cdsqrt", {{"a", DoublePrecisionComplex}}, DoublePrecisionComplex}, 790 "sqrt"}, 791 {{"cexp", {{"a", DefaultComplex}}, DefaultComplex}, "exp"}, 792 {{"clog", {{"a", DefaultComplex}}, DefaultComplex}, "log"}, 793 {{"conjg", {{"a", DefaultComplex}}, DefaultComplex}}, 794 {{"cos", {{"x", DefaultReal}}, DefaultReal}}, 795 {{"cosh", {{"x", DefaultReal}}, DefaultReal}}, 796 {{"csin", {{"a", DefaultComplex}}, DefaultComplex}, "sin"}, 797 {{"csqrt", {{"a", DefaultComplex}}, DefaultComplex}, "sqrt"}, 798 {{"ctan", {{"a", DefaultComplex}}, DefaultComplex}, "tan"}, 799 {{"dabs", {{"a", DoublePrecision}}, DoublePrecision}, "abs"}, 800 {{"dacos", {{"x", DoublePrecision}}, DoublePrecision}, "acos"}, 801 {{"dasin", {{"x", DoublePrecision}}, DoublePrecision}, "asin"}, 802 {{"datan", {{"x", DoublePrecision}}, DoublePrecision}, "atan"}, 803 {{"datan2", {{"y", DoublePrecision}, {"x", DoublePrecision}}, 804 DoublePrecision}, 805 "atan2"}, 806 {{"dcmplx", {{"x", AnyComplex}}, DoublePrecisionComplex}, "cmplx", true}, 807 {{"dcmplx", 808 {{"x", AnyIntOrReal, Rank::elementalOrBOZ}, 809 {"y", AnyIntOrReal, Rank::elementalOrBOZ, Optionality::optional}}, 810 DoublePrecisionComplex}, 811 "cmplx", true}, 812 {{"dreal", {{"a", AnyComplex}}, DoublePrecision}, "real", true}, 813 {{"dconjg", {{"a", DoublePrecisionComplex}}, DoublePrecisionComplex}, 814 "conjg"}, 815 {{"dcos", {{"x", DoublePrecision}}, DoublePrecision}, "cos"}, 816 {{"dcosh", {{"x", DoublePrecision}}, DoublePrecision}, "cosh"}, 817 {{"ddim", {{"x", DoublePrecision}, {"y", DoublePrecision}}, 818 DoublePrecision}, 819 "dim"}, 820 {{"dimag", {{"a", DoublePrecisionComplex}}, DoublePrecision}, "aimag"}, 821 {{"dexp", {{"x", DoublePrecision}}, DoublePrecision}, "exp"}, 822 {{"dim", {{"x", DefaultReal}, {"y", DefaultReal}}, DefaultReal}}, 823 {{"dint", {{"a", DoublePrecision}}, DoublePrecision}, "aint"}, 824 {{"dlog", {{"x", DoublePrecision}}, DoublePrecision}, "log"}, 825 {{"dlog10", {{"x", DoublePrecision}}, DoublePrecision}, "log10"}, 826 {{"dmax1", 827 {{"a1", DoublePrecision}, {"a2", DoublePrecision}, 828 {"a3", DoublePrecision, Rank::elemental, Optionality::repeats}}, 829 DoublePrecision}, 830 "max", true, true}, 831 {{"dmin1", 832 {{"a1", DoublePrecision}, {"a2", DoublePrecision}, 833 {"a3", DoublePrecision, Rank::elemental, Optionality::repeats}}, 834 DoublePrecision}, 835 "min", true, true}, 836 {{"dmod", {{"a", DoublePrecision}, {"p", DoublePrecision}}, 837 DoublePrecision}, 838 "mod"}, 839 {{"dnint", {{"a", DoublePrecision}}, DoublePrecision}, "anint"}, 840 {{"dprod", {{"x", DefaultReal}, {"y", DefaultReal}}, DoublePrecision}}, 841 {{"dsign", {{"a", DoublePrecision}, {"b", DoublePrecision}}, 842 DoublePrecision}, 843 "sign"}, 844 {{"dsin", {{"x", DoublePrecision}}, DoublePrecision}, "sin"}, 845 {{"dsinh", {{"x", DoublePrecision}}, DoublePrecision}, "sinh"}, 846 {{"dsqrt", {{"x", DoublePrecision}}, DoublePrecision}, "sqrt"}, 847 {{"dtan", {{"x", DoublePrecision}}, DoublePrecision}, "tan"}, 848 {{"dtanh", {{"x", DoublePrecision}}, DoublePrecision}, "tanh"}, 849 {{"exp", {{"x", DefaultReal}}, DefaultReal}}, 850 {{"float", {{"i", AnyInt}}, DefaultReal}, "real", true}, 851 {{"iabs", {{"a", DefaultInt}}, DefaultInt}, "abs"}, 852 {{"idim", {{"x", DefaultInt}, {"y", DefaultInt}}, DefaultInt}, "dim"}, 853 {{"idint", {{"a", AnyReal}}, DefaultInt}, "int", true}, 854 {{"idnint", {{"a", DoublePrecision}}, DefaultInt}, "nint"}, 855 {{"ifix", {{"a", AnyReal}}, DefaultInt}, "int", true}, 856 {{"index", {{"string", DefaultChar}, {"substring", DefaultChar}}, 857 DefaultInt}}, 858 {{"isign", {{"a", DefaultInt}, {"b", DefaultInt}}, DefaultInt}, "sign"}, 859 {{"len", {{"string", DefaultChar, Rank::anyOrAssumedRank}}, DefaultInt, 860 Rank::scalar}}, 861 {{"lge", {{"string_a", DefaultChar}, {"string_b", DefaultChar}}, 862 DefaultLogical}}, 863 {{"lgt", {{"string_a", DefaultChar}, {"string_b", DefaultChar}}, 864 DefaultLogical}}, 865 {{"lle", {{"string_a", DefaultChar}, {"string_b", DefaultChar}}, 866 DefaultLogical}}, 867 {{"llt", {{"string_a", DefaultChar}, {"string_b", DefaultChar}}, 868 DefaultLogical}}, 869 {{"log", {{"x", DefaultReal}}, DefaultReal}}, 870 {{"log10", {{"x", DefaultReal}}, DefaultReal}}, 871 {{"max0", 872 {{"a1", DefaultInt}, {"a2", DefaultInt}, 873 {"a3", DefaultInt, Rank::elemental, Optionality::repeats}}, 874 DefaultInt}, 875 "max", true, true}, 876 {{"max1", 877 {{"a1", DefaultReal}, {"a2", DefaultReal}, 878 {"a3", DefaultReal, Rank::elemental, Optionality::repeats}}, 879 DefaultInt}, 880 "max", true, true}, 881 {{"min0", 882 {{"a1", DefaultInt}, {"a2", DefaultInt}, 883 {"a3", DefaultInt, Rank::elemental, Optionality::repeats}}, 884 DefaultInt}, 885 "min", true, true}, 886 {{"min1", 887 {{"a1", DefaultReal}, {"a2", DefaultReal}, 888 {"a3", DefaultReal, Rank::elemental, Optionality::repeats}}, 889 DefaultInt}, 890 "min", true, true}, 891 {{"mod", {{"a", DefaultInt}, {"p", DefaultInt}}, DefaultInt}}, 892 {{"nint", {{"a", DefaultReal}}, DefaultInt}}, 893 {{"sign", {{"a", DefaultReal}, {"b", DefaultReal}}, DefaultReal}}, 894 {{"sin", {{"x", DefaultReal}}, DefaultReal}}, 895 {{"sinh", {{"x", DefaultReal}}, DefaultReal}}, 896 {{"sngl", {{"a", AnyReal}}, DefaultReal}, "real", true}, 897 {{"sqrt", {{"x", DefaultReal}}, DefaultReal}}, 898 {{"tan", {{"x", DefaultReal}}, DefaultReal}}, 899 {{"tanh", {{"x", DefaultReal}}, DefaultReal}}, 900 }; 901 902 static const IntrinsicInterface intrinsicSubroutine[]{ 903 {"cpu_time", {{"time", AnyReal, Rank::scalar}}, {}}, 904 {"date_and_time", 905 {{"date", DefaultChar, Rank::scalar, Optionality::optional}, 906 {"time", DefaultChar, Rank::scalar, Optionality::optional}, 907 {"zone", DefaultChar, Rank::scalar, Optionality::optional}, 908 {"values", AnyInt, Rank::vector, Optionality::optional}}, 909 {}}, 910 {"execute_command_line", 911 {{"command", DefaultChar, Rank::scalar}, 912 {"wait", AnyLogical, Rank::scalar, Optionality::optional}, 913 {"exitstat", AnyInt, Rank::scalar, Optionality::optional}, 914 {"cmdstat", AnyInt, Rank::scalar, Optionality::optional}, 915 {"cmdmsg", DefaultChar, Rank::scalar, Optionality::optional}}, 916 {}}, 917 {"get_command", 918 {{"command", DefaultChar, Rank::scalar, Optionality::optional}, 919 {"length", AnyInt, Rank::scalar, Optionality::optional}, 920 {"status", AnyInt, Rank::scalar, Optionality::optional}, 921 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional}}, 922 {}}, 923 {"get_command_argument", 924 {{"number", AnyInt, Rank::scalar}, 925 {"value", DefaultChar, Rank::scalar, Optionality::optional}, 926 {"length", AnyInt, Rank::scalar, Optionality::optional}, 927 {"status", AnyInt, Rank::scalar, Optionality::optional}, 928 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional}}, 929 {}}, 930 {"get_environment_variable", 931 {{"name", DefaultChar, Rank::scalar}, 932 {"value", DefaultChar, Rank::scalar, Optionality::optional}, 933 {"length", AnyInt, Rank::scalar, Optionality::optional}, 934 {"status", AnyInt, Rank::scalar, Optionality::optional}, 935 {"trim_name", AnyLogical, Rank::scalar, Optionality::optional}, 936 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional}}, 937 {}}, 938 {"move_alloc", 939 {{"from", SameType, Rank::known}, {"to", SameType, Rank::known}, 940 {"stat", AnyInt, Rank::scalar, Optionality::optional}, 941 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional}}, 942 {}}, 943 {"mvbits", 944 {{"from", SameInt}, {"frompos", AnyInt}, {"len", AnyInt}, 945 {"to", SameInt}, {"topos", AnyInt}}, 946 {}}, // elemental 947 {"random_init", 948 {{"repeatable", AnyLogical, Rank::scalar}, 949 {"image_distinct", AnyLogical, Rank::scalar}}, 950 {}}, 951 {"random_number", {{"harvest", AnyReal, Rank::known}}, {}}, 952 {"random_seed", 953 {{"size", DefaultInt, Rank::scalar, Optionality::optional}, 954 {"put", DefaultInt, Rank::vector, Optionality::optional}, 955 {"get", DefaultInt, Rank::vector, Optionality::optional}}, 956 {}}, // TODO: at most one argument can be present 957 {"system_clock", 958 {{"count", AnyInt, Rank::scalar, Optionality::optional}, 959 {"count_rate", AnyIntOrReal, Rank::scalar, Optionality::optional}, 960 {"count_max", AnyInt, Rank::scalar, Optionality::optional}}, 961 {}}, 962 }; 963 964 // TODO: Intrinsic subroutine EVENT_QUERY 965 // TODO: Atomic intrinsic subroutines: ATOMIC_ADD &al. 966 // TODO: Collective intrinsic subroutines: CO_BROADCAST &al. 967 968 // Intrinsic interface matching against the arguments of a particular 969 // procedure reference. 970 std::optional<SpecificCall> IntrinsicInterface::Match( 971 const CallCharacteristics &call, 972 const common::IntrinsicTypeDefaultKinds &defaults, 973 ActualArguments &arguments, FoldingContext &context) const { 974 auto &messages{context.messages()}; 975 // Attempt to construct a 1-1 correspondence between the dummy arguments in 976 // a particular intrinsic procedure's generic interface and the actual 977 // arguments in a procedure reference. 978 std::size_t dummyArgPatterns{0}; 979 for (; dummyArgPatterns < maxArguments && dummy[dummyArgPatterns].keyword; 980 ++dummyArgPatterns) { 981 } 982 // MAX and MIN (and others that map to them) allow their last argument to 983 // be repeated indefinitely. The actualForDummy vector is sized 984 // and null-initialized to the non-repeated dummy argument count, 985 // but additional actual argument pointers can be pushed on it 986 // when this flag is set. 987 bool repeatLastDummy{dummyArgPatterns > 0 && 988 dummy[dummyArgPatterns - 1].optionality == Optionality::repeats}; 989 std::size_t nonRepeatedDummies{ 990 repeatLastDummy ? dummyArgPatterns - 1 : dummyArgPatterns}; 991 std::vector<ActualArgument *> actualForDummy(nonRepeatedDummies, nullptr); 992 int missingActualArguments{0}; 993 for (std::optional<ActualArgument> &arg : arguments) { 994 if (!arg) { 995 ++missingActualArguments; 996 } else { 997 if (arg->isAlternateReturn()) { 998 messages.Say( 999 "alternate return specifier not acceptable on call to intrinsic '%s'"_err_en_US, 1000 name); 1001 return std::nullopt; 1002 } 1003 bool found{false}; 1004 int slot{missingActualArguments}; 1005 for (std::size_t j{0}; j < nonRepeatedDummies && !found; ++j) { 1006 if (arg->keyword()) { 1007 found = *arg->keyword() == dummy[j].keyword; 1008 if (found) { 1009 if (const auto *previous{actualForDummy[j]}) { 1010 if (previous->keyword()) { 1011 messages.Say(*arg->keyword(), 1012 "repeated keyword argument to intrinsic '%s'"_err_en_US, 1013 name); 1014 } else { 1015 messages.Say(*arg->keyword(), 1016 "keyword argument to intrinsic '%s' was supplied " 1017 "positionally by an earlier actual argument"_err_en_US, 1018 name); 1019 } 1020 return std::nullopt; 1021 } 1022 } 1023 } else { 1024 found = !actualForDummy[j] && slot-- == 0; 1025 } 1026 if (found) { 1027 actualForDummy[j] = &*arg; 1028 } 1029 } 1030 if (!found) { 1031 if (repeatLastDummy && !arg->keyword()) { 1032 // MAX/MIN argument after the 2nd 1033 actualForDummy.push_back(&*arg); 1034 } else { 1035 if (arg->keyword()) { 1036 messages.Say(*arg->keyword(), 1037 "unknown keyword argument to intrinsic '%s'"_err_en_US, name); 1038 } else { 1039 messages.Say( 1040 "too many actual arguments for intrinsic '%s'"_err_en_US, name); 1041 } 1042 return std::nullopt; 1043 } 1044 } 1045 } 1046 } 1047 1048 std::size_t dummies{actualForDummy.size()}; 1049 1050 // Check types and kinds of the actual arguments against the intrinsic's 1051 // interface. Ensure that two or more arguments that have to have the same 1052 // (or compatible) type and kind do so. Check for missing non-optional 1053 // arguments now, too. 1054 const ActualArgument *sameArg{nullptr}; 1055 const ActualArgument *operandArg{nullptr}; 1056 const IntrinsicDummyArgument *kindDummyArg{nullptr}; 1057 const ActualArgument *kindArg{nullptr}; 1058 bool hasDimArg{false}; 1059 for (std::size_t j{0}; j < dummies; ++j) { 1060 const IntrinsicDummyArgument &d{dummy[std::min(j, dummyArgPatterns - 1)]}; 1061 if (d.typePattern.kindCode == KindCode::kindArg) { 1062 CHECK(!kindDummyArg); 1063 kindDummyArg = &d; 1064 } 1065 const ActualArgument *arg{actualForDummy[j]}; 1066 if (!arg) { 1067 if (d.optionality == Optionality::required) { 1068 messages.Say("missing mandatory '%s=' argument"_err_en_US, d.keyword); 1069 return std::nullopt; // missing non-OPTIONAL argument 1070 } else { 1071 continue; 1072 } 1073 } 1074 if (arg->GetAssumedTypeDummy()) { 1075 // TYPE(*) assumed-type dummy argument forwarded to intrinsic 1076 if (d.typePattern.categorySet == AnyType && 1077 d.rank == Rank::anyOrAssumedRank && 1078 (d.typePattern.kindCode == KindCode::any || 1079 d.typePattern.kindCode == KindCode::addressable)) { 1080 continue; 1081 } else { 1082 messages.Say("Assumed type TYPE(*) dummy argument not allowed " 1083 "for '%s=' intrinsic argument"_err_en_US, 1084 d.keyword); 1085 return std::nullopt; 1086 } 1087 } 1088 std::optional<DynamicType> type{arg->GetType()}; 1089 if (!type) { 1090 CHECK(arg->Rank() == 0); 1091 const Expr<SomeType> &expr{DEREF(arg->UnwrapExpr())}; 1092 if (std::holds_alternative<BOZLiteralConstant>(expr.u)) { 1093 if (d.typePattern.kindCode == KindCode::typeless || 1094 d.rank == Rank::elementalOrBOZ) { 1095 continue; 1096 } else { 1097 messages.Say( 1098 "Typeless (BOZ) not allowed for '%s=' argument"_err_en_US, 1099 d.keyword); 1100 } 1101 } else { 1102 // NULL(), procedure, or procedure pointer 1103 CHECK(IsProcedurePointer(expr)); 1104 if (d.typePattern.kindCode == KindCode::addressable || 1105 d.rank == Rank::reduceOperation) { 1106 continue; 1107 } else { 1108 messages.Say( 1109 "Actual argument for '%s=' may not be a procedure"_err_en_US, 1110 d.keyword); 1111 } 1112 } 1113 return std::nullopt; 1114 } else if (!d.typePattern.categorySet.test(type->category())) { 1115 messages.Say("Actual argument for '%s=' has bad type '%s'"_err_en_US, 1116 d.keyword, type->AsFortran()); 1117 return std::nullopt; // argument has invalid type category 1118 } 1119 bool argOk{false}; 1120 switch (d.typePattern.kindCode) { 1121 case KindCode::none: 1122 case KindCode::typeless: 1123 case KindCode::teamType: // TODO: TEAM_TYPE 1124 argOk = false; 1125 break; 1126 case KindCode::defaultIntegerKind: 1127 argOk = type->kind() == defaults.GetDefaultKind(TypeCategory::Integer); 1128 break; 1129 case KindCode::defaultRealKind: 1130 argOk = type->kind() == defaults.GetDefaultKind(TypeCategory::Real); 1131 break; 1132 case KindCode::doublePrecision: 1133 argOk = type->kind() == defaults.doublePrecisionKind(); 1134 break; 1135 case KindCode::defaultCharKind: 1136 argOk = type->kind() == defaults.GetDefaultKind(TypeCategory::Character); 1137 break; 1138 case KindCode::defaultLogicalKind: 1139 argOk = type->kind() == defaults.GetDefaultKind(TypeCategory::Logical); 1140 break; 1141 case KindCode::any: 1142 argOk = true; 1143 break; 1144 case KindCode::kindArg: 1145 CHECK(type->category() == TypeCategory::Integer); 1146 CHECK(!kindArg); 1147 kindArg = arg; 1148 argOk = true; 1149 break; 1150 case KindCode::dimArg: 1151 CHECK(type->category() == TypeCategory::Integer); 1152 hasDimArg = true; 1153 argOk = true; 1154 break; 1155 case KindCode::same: 1156 if (!sameArg) { 1157 sameArg = arg; 1158 } 1159 argOk = type->IsTkCompatibleWith(sameArg->GetType().value()); 1160 break; 1161 case KindCode::operand: 1162 if (!operandArg) { 1163 operandArg = arg; 1164 } else if (auto prev{operandArg->GetType()}) { 1165 if (type->category() == prev->category()) { 1166 if (type->kind() > prev->kind()) { 1167 operandArg = arg; 1168 } 1169 } else if (prev->category() == TypeCategory::Integer) { 1170 operandArg = arg; 1171 } 1172 } 1173 argOk = true; 1174 break; 1175 case KindCode::effectiveKind: 1176 common::die("INTERNAL: KindCode::effectiveKind appears on argument '%s' " 1177 "for intrinsic '%s'", 1178 d.keyword, name); 1179 break; 1180 case KindCode::addressable: 1181 argOk = true; 1182 break; 1183 default: 1184 CRASH_NO_CASE; 1185 } 1186 if (!argOk) { 1187 messages.Say( 1188 "Actual argument for '%s=' has bad type or kind '%s'"_err_en_US, 1189 d.keyword, type->AsFortran()); 1190 return std::nullopt; 1191 } 1192 } 1193 1194 // Check the ranks of the arguments against the intrinsic's interface. 1195 const ActualArgument *arrayArg{nullptr}; 1196 const ActualArgument *knownArg{nullptr}; 1197 std::optional<int> shapeArgSize; 1198 int elementalRank{0}; 1199 for (std::size_t j{0}; j < dummies; ++j) { 1200 const IntrinsicDummyArgument &d{dummy[std::min(j, dummyArgPatterns - 1)]}; 1201 if (const ActualArgument * arg{actualForDummy[j]}) { 1202 if (IsAssumedRank(*arg) && d.rank != Rank::anyOrAssumedRank) { 1203 messages.Say("Assumed-rank array cannot be forwarded to " 1204 "'%s=' argument"_err_en_US, 1205 d.keyword); 1206 return std::nullopt; 1207 } 1208 int rank{arg->Rank()}; 1209 bool argOk{false}; 1210 switch (d.rank) { 1211 case Rank::elemental: 1212 case Rank::elementalOrBOZ: 1213 if (elementalRank == 0) { 1214 elementalRank = rank; 1215 } 1216 argOk = rank == 0 || rank == elementalRank; 1217 break; 1218 case Rank::scalar: 1219 argOk = rank == 0; 1220 break; 1221 case Rank::vector: 1222 argOk = rank == 1; 1223 break; 1224 case Rank::shape: 1225 CHECK(!shapeArgSize); 1226 if (rank == 1) { 1227 if (auto shape{GetShape(context, *arg)}) { 1228 if (auto constShape{AsConstantShape(context, *shape)}) { 1229 shapeArgSize = constShape->At(ConstantSubscripts{1}).ToInt64(); 1230 CHECK(shapeArgSize >= 0); 1231 argOk = true; 1232 } 1233 } 1234 } 1235 if (!argOk) { 1236 messages.Say( 1237 "'shape=' argument must be a vector of known size"_err_en_US); 1238 return std::nullopt; 1239 } 1240 break; 1241 case Rank::matrix: 1242 argOk = rank == 2; 1243 break; 1244 case Rank::array: 1245 argOk = rank > 0; 1246 if (!arrayArg) { 1247 arrayArg = arg; 1248 } else { 1249 argOk &= rank == arrayArg->Rank(); 1250 } 1251 break; 1252 case Rank::known: 1253 if (!knownArg) { 1254 knownArg = arg; 1255 } 1256 argOk = rank == knownArg->Rank(); 1257 break; 1258 case Rank::anyOrAssumedRank: 1259 argOk = true; 1260 break; 1261 case Rank::conformable: 1262 CHECK(arrayArg); 1263 argOk = rank == 0 || rank == arrayArg->Rank(); 1264 break; 1265 case Rank::dimRemoved: 1266 CHECK(arrayArg); 1267 argOk = rank == 0 || rank + 1 == arrayArg->Rank(); 1268 break; 1269 case Rank::reduceOperation: 1270 // TODO: validate the reduction operation -- it must be a pure 1271 // function of two arguments with special constraints. 1272 CHECK(arrayArg); 1273 argOk = rank == 0; 1274 break; 1275 case Rank::dimReduced: 1276 case Rank::rankPlus1: 1277 case Rank::shaped: 1278 common::die("INTERNAL: result-only rank code appears on argument '%s' " 1279 "for intrinsic '%s'", 1280 d.keyword, name); 1281 } 1282 if (!argOk) { 1283 messages.Say("'%s=' argument has unacceptable rank %d"_err_en_US, 1284 d.keyword, rank); 1285 return std::nullopt; 1286 } 1287 } 1288 } 1289 1290 // Calculate the characteristics of the function result, if any 1291 std::optional<DynamicType> resultType; 1292 if (auto category{result.categorySet.LeastElement()}) { 1293 // The intrinsic is not a subroutine. 1294 if (call.isSubroutineCall) { 1295 return std::nullopt; 1296 } 1297 switch (result.kindCode) { 1298 case KindCode::defaultIntegerKind: 1299 CHECK(result.categorySet == IntType); 1300 CHECK(*category == TypeCategory::Integer); 1301 resultType = DynamicType{TypeCategory::Integer, 1302 defaults.GetDefaultKind(TypeCategory::Integer)}; 1303 break; 1304 case KindCode::defaultRealKind: 1305 CHECK(result.categorySet == CategorySet{*category}); 1306 CHECK(FloatingType.test(*category)); 1307 resultType = 1308 DynamicType{*category, defaults.GetDefaultKind(TypeCategory::Real)}; 1309 break; 1310 case KindCode::doublePrecision: 1311 CHECK(result.categorySet == CategorySet{*category}); 1312 CHECK(FloatingType.test(*category)); 1313 resultType = DynamicType{*category, defaults.doublePrecisionKind()}; 1314 break; 1315 case KindCode::defaultCharKind: 1316 CHECK(result.categorySet == CharType); 1317 CHECK(*category == TypeCategory::Character); 1318 resultType = DynamicType{TypeCategory::Character, 1319 defaults.GetDefaultKind(TypeCategory::Character)}; 1320 break; 1321 case KindCode::defaultLogicalKind: 1322 CHECK(result.categorySet == LogicalType); 1323 CHECK(*category == TypeCategory::Logical); 1324 resultType = DynamicType{TypeCategory::Logical, 1325 defaults.GetDefaultKind(TypeCategory::Logical)}; 1326 break; 1327 case KindCode::same: 1328 CHECK(sameArg); 1329 if (std::optional<DynamicType> aType{sameArg->GetType()}) { 1330 if (result.categorySet.test(aType->category())) { 1331 resultType = *aType; 1332 } else { 1333 resultType = DynamicType{*category, aType->kind()}; 1334 } 1335 } 1336 break; 1337 case KindCode::operand: 1338 CHECK(operandArg); 1339 resultType = operandArg->GetType(); 1340 CHECK(!resultType || result.categorySet.test(resultType->category())); 1341 break; 1342 case KindCode::effectiveKind: 1343 CHECK(kindDummyArg); 1344 CHECK(result.categorySet == CategorySet{*category}); 1345 if (kindArg) { 1346 if (auto *expr{kindArg->UnwrapExpr()}) { 1347 CHECK(expr->Rank() == 0); 1348 if (auto code{ToInt64(*expr)}) { 1349 if (IsValidKindOfIntrinsicType(*category, *code)) { 1350 resultType = DynamicType{*category, static_cast<int>(*code)}; 1351 break; 1352 } 1353 } 1354 } 1355 messages.Say("'kind=' argument must be a constant scalar integer " 1356 "whose value is a supported kind for the " 1357 "intrinsic result type"_err_en_US); 1358 return std::nullopt; 1359 } else if (kindDummyArg->optionality == Optionality::defaultsToSameKind) { 1360 CHECK(sameArg); 1361 resultType = *sameArg->GetType(); 1362 } else if (kindDummyArg->optionality == Optionality::defaultsToSizeKind) { 1363 CHECK(*category == TypeCategory::Integer); 1364 resultType = 1365 DynamicType{TypeCategory::Integer, defaults.sizeIntegerKind()}; 1366 } else { 1367 CHECK(kindDummyArg->optionality == 1368 Optionality::defaultsToDefaultForResult); 1369 resultType = DynamicType{*category, defaults.GetDefaultKind(*category)}; 1370 } 1371 break; 1372 case KindCode::likeMultiply: 1373 CHECK(dummies >= 2); 1374 CHECK(actualForDummy[0]); 1375 CHECK(actualForDummy[1]); 1376 resultType = actualForDummy[0]->GetType()->ResultTypeForMultiply( 1377 *actualForDummy[1]->GetType()); 1378 break; 1379 case KindCode::subscript: 1380 CHECK(result.categorySet == IntType); 1381 CHECK(*category == TypeCategory::Integer); 1382 resultType = 1383 DynamicType{TypeCategory::Integer, defaults.subscriptIntegerKind()}; 1384 break; 1385 case KindCode::size: 1386 CHECK(result.categorySet == IntType); 1387 CHECK(*category == TypeCategory::Integer); 1388 resultType = 1389 DynamicType{TypeCategory::Integer, defaults.sizeIntegerKind()}; 1390 break; 1391 case KindCode::typeless: 1392 case KindCode::teamType: 1393 case KindCode::any: 1394 case KindCode::kindArg: 1395 case KindCode::dimArg: 1396 common::die( 1397 "INTERNAL: bad KindCode appears on intrinsic '%s' result", name); 1398 break; 1399 default: 1400 CRASH_NO_CASE; 1401 } 1402 } else { 1403 if (!call.isSubroutineCall) { 1404 return std::nullopt; 1405 } 1406 CHECK(result.kindCode == KindCode::none); 1407 } 1408 1409 // At this point, the call is acceptable. 1410 // Determine the rank of the function result. 1411 int resultRank{0}; 1412 switch (rank) { 1413 case Rank::elemental: 1414 resultRank = elementalRank; 1415 break; 1416 case Rank::scalar: 1417 resultRank = 0; 1418 break; 1419 case Rank::vector: 1420 resultRank = 1; 1421 break; 1422 case Rank::matrix: 1423 resultRank = 2; 1424 break; 1425 case Rank::conformable: 1426 CHECK(arrayArg); 1427 resultRank = arrayArg->Rank(); 1428 break; 1429 case Rank::dimReduced: 1430 CHECK(arrayArg); 1431 resultRank = hasDimArg ? arrayArg->Rank() - 1 : 0; 1432 break; 1433 case Rank::dimRemoved: 1434 CHECK(arrayArg); 1435 resultRank = arrayArg->Rank() - 1; 1436 break; 1437 case Rank::rankPlus1: 1438 CHECK(knownArg); 1439 resultRank = knownArg->Rank() + 1; 1440 break; 1441 case Rank::shaped: 1442 CHECK(shapeArgSize); 1443 resultRank = *shapeArgSize; 1444 break; 1445 case Rank::elementalOrBOZ: 1446 case Rank::shape: 1447 case Rank::array: 1448 case Rank::known: 1449 case Rank::anyOrAssumedRank: 1450 case Rank::reduceOperation: 1451 common::die("INTERNAL: bad Rank code on intrinsic '%s' result", name); 1452 break; 1453 } 1454 CHECK(resultRank >= 0); 1455 1456 // Rearrange the actual arguments into dummy argument order. 1457 ActualArguments rearranged(dummies); 1458 for (std::size_t j{0}; j < dummies; ++j) { 1459 if (ActualArgument * arg{actualForDummy[j]}) { 1460 rearranged[j] = std::move(*arg); 1461 } 1462 } 1463 1464 // Characterize the specific intrinsic procedure. 1465 characteristics::DummyArguments dummyArgs; 1466 std::optional<int> sameDummyArg; 1467 for (std::size_t j{0}; j < dummies; ++j) { 1468 const IntrinsicDummyArgument &d{dummy[std::min(j, dummyArgPatterns - 1)]}; 1469 if (const auto &arg{rearranged[j]}) { 1470 if (const Expr<SomeType> *expr{arg->UnwrapExpr()}) { 1471 auto dc{characteristics::DummyArgument::FromActual( 1472 std::string{d.keyword}, *expr, context)}; 1473 CHECK(dc); 1474 dummyArgs.emplace_back(std::move(*dc)); 1475 if (d.typePattern.kindCode == KindCode::same && !sameDummyArg) { 1476 sameDummyArg = j; 1477 } 1478 } else { 1479 CHECK(arg->GetAssumedTypeDummy()); 1480 dummyArgs.emplace_back(std::string{d.keyword}, 1481 characteristics::DummyDataObject{DynamicType::AssumedType()}); 1482 } 1483 } else { 1484 // optional argument is absent 1485 CHECK(d.optionality != Optionality::required); 1486 if (d.typePattern.kindCode == KindCode::same) { 1487 dummyArgs.emplace_back(dummyArgs[sameDummyArg.value()]); 1488 } else { 1489 auto category{d.typePattern.categorySet.LeastElement().value()}; 1490 characteristics::TypeAndShape typeAndShape{ 1491 DynamicType{category, defaults.GetDefaultKind(category)}}; 1492 dummyArgs.emplace_back(std::string{d.keyword}, 1493 characteristics::DummyDataObject{std::move(typeAndShape)}); 1494 } 1495 dummyArgs.back().SetOptional(); 1496 } 1497 } 1498 characteristics::Procedure::Attrs attrs; 1499 if (elementalRank > 0) { 1500 attrs.set(characteristics::Procedure::Attr::Elemental); 1501 } 1502 if (call.isSubroutineCall) { 1503 return SpecificCall{ 1504 SpecificIntrinsic{ 1505 name, characteristics::Procedure{std::move(dummyArgs), attrs}}, 1506 std::move(rearranged)}; 1507 } else { 1508 attrs.set(characteristics::Procedure::Attr::Pure); 1509 characteristics::TypeAndShape typeAndShape{resultType.value(), resultRank}; 1510 characteristics::FunctionResult funcResult{std::move(typeAndShape)}; 1511 characteristics::Procedure chars{ 1512 std::move(funcResult), std::move(dummyArgs), attrs}; 1513 return SpecificCall{ 1514 SpecificIntrinsic{name, std::move(chars)}, std::move(rearranged)}; 1515 } 1516 } 1517 1518 class IntrinsicProcTable::Implementation { 1519 public: 1520 explicit Implementation(const common::IntrinsicTypeDefaultKinds &dfts) 1521 : defaults_{dfts} { 1522 for (const IntrinsicInterface &f : genericIntrinsicFunction) { 1523 genericFuncs_.insert(std::make_pair(std::string{f.name}, &f)); 1524 } 1525 for (const SpecificIntrinsicInterface &f : specificIntrinsicFunction) { 1526 specificFuncs_.insert(std::make_pair(std::string{f.name}, &f)); 1527 } 1528 for (const IntrinsicInterface &f : intrinsicSubroutine) { 1529 subroutines_.insert(std::make_pair(std::string{f.name}, &f)); 1530 } 1531 } 1532 1533 bool IsIntrinsic(const std::string &) const; 1534 1535 std::optional<SpecificCall> Probe(const CallCharacteristics &, 1536 ActualArguments &, FoldingContext &, const IntrinsicProcTable &) const; 1537 1538 std::optional<SpecificIntrinsicFunctionInterface> IsSpecificIntrinsicFunction( 1539 const std::string &) const; 1540 1541 llvm::raw_ostream &Dump(llvm::raw_ostream &) const; 1542 1543 private: 1544 DynamicType GetSpecificType(const TypePattern &) const; 1545 SpecificCall HandleNull( 1546 ActualArguments &, FoldingContext &, const IntrinsicProcTable &) const; 1547 std::optional<SpecificCall> HandleC_F_Pointer( 1548 ActualArguments &, FoldingContext &) const; 1549 1550 common::IntrinsicTypeDefaultKinds defaults_; 1551 std::multimap<std::string, const IntrinsicInterface *> genericFuncs_; 1552 std::multimap<std::string, const SpecificIntrinsicInterface *> specificFuncs_; 1553 std::multimap<std::string, const IntrinsicInterface *> subroutines_; 1554 }; 1555 1556 bool IntrinsicProcTable::Implementation::IsIntrinsic( 1557 const std::string &name) const { 1558 auto specificRange{specificFuncs_.equal_range(name)}; 1559 if (specificRange.first != specificRange.second) { 1560 return true; 1561 } 1562 auto genericRange{genericFuncs_.equal_range(name)}; 1563 if (genericRange.first != genericRange.second) { 1564 return true; 1565 } 1566 auto subrRange{subroutines_.equal_range(name)}; 1567 if (subrRange.first != subrRange.second) { 1568 return true; 1569 } 1570 // special cases 1571 return name == "null" || name == "__builtin_c_f_pointer"; 1572 } 1573 1574 bool CheckAndRearrangeArguments(ActualArguments &arguments, 1575 parser::ContextualMessages &messages, const char *const dummyKeywords[], 1576 std::size_t trailingOptionals) { 1577 std::size_t numDummies{0}; 1578 while (dummyKeywords[numDummies]) { 1579 ++numDummies; 1580 } 1581 CHECK(trailingOptionals <= numDummies); 1582 if (arguments.size() > numDummies) { 1583 messages.Say("Too many actual arguments (%zd > %zd)"_err_en_US, 1584 arguments.size(), numDummies); 1585 return false; 1586 } 1587 ActualArguments rearranged(numDummies); 1588 bool anyKeywords{false}; 1589 std::size_t position{0}; 1590 for (std::optional<ActualArgument> &arg : arguments) { 1591 std::size_t dummyIndex{0}; 1592 if (arg && arg->keyword()) { 1593 anyKeywords = true; 1594 for (; dummyIndex < numDummies; ++dummyIndex) { 1595 if (*arg->keyword() == dummyKeywords[dummyIndex]) { 1596 break; 1597 } 1598 } 1599 if (dummyIndex >= numDummies) { 1600 messages.Say(*arg->keyword(), 1601 "Unknown argument keyword '%s='"_err_en_US, *arg->keyword()); 1602 return false; 1603 } 1604 } else if (anyKeywords) { 1605 messages.Say( 1606 "A positional actual argument may not appear after any keyword arguments"_err_en_US); 1607 return false; 1608 } else { 1609 dummyIndex = position++; 1610 } 1611 if (rearranged[dummyIndex]) { 1612 messages.Say("Dummy argument '%s=' appears more than once"_err_en_US, 1613 dummyKeywords[dummyIndex]); 1614 return false; 1615 } 1616 rearranged[dummyIndex] = std::move(arg); 1617 arg.reset(); 1618 } 1619 bool anyMissing{false}; 1620 for (std::size_t j{0}; j < numDummies - trailingOptionals; ++j) { 1621 if (!rearranged[j]) { 1622 messages.Say("Dummy argument '%s=' is absent and not OPTIONAL"_err_en_US, 1623 dummyKeywords[j]); 1624 anyMissing = true; 1625 } 1626 } 1627 arguments = std::move(rearranged); 1628 return !anyMissing; 1629 } 1630 1631 // The NULL() intrinsic is a special case. 1632 SpecificCall IntrinsicProcTable::Implementation::HandleNull( 1633 ActualArguments &arguments, FoldingContext &context, 1634 const IntrinsicProcTable &intrinsics) const { 1635 static const char *const keywords[]{"mold", nullptr}; 1636 if (CheckAndRearrangeArguments(arguments, context.messages(), keywords, 1) && 1637 arguments[0]) { 1638 if (Expr<SomeType> * mold{arguments[0]->UnwrapExpr()}) { 1639 if (IsAllocatableOrPointer(*mold)) { 1640 characteristics::DummyArguments args; 1641 std::optional<characteristics::FunctionResult> fResult; 1642 if (IsProcedurePointer(*mold)) { 1643 // MOLD= procedure pointer 1644 const Symbol *last{GetLastSymbol(*mold)}; 1645 CHECK(last); 1646 auto procPointer{ 1647 characteristics::Procedure::Characterize(*last, intrinsics)}; 1648 CHECK(procPointer); 1649 args.emplace_back("mold"s, 1650 characteristics::DummyProcedure{common::Clone(*procPointer)}); 1651 fResult.emplace(std::move(*procPointer)); 1652 } else if (auto type{mold->GetType()}) { 1653 // MOLD= object pointer 1654 characteristics::TypeAndShape typeAndShape{ 1655 *type, GetShape(context, *mold)}; 1656 args.emplace_back( 1657 "mold"s, characteristics::DummyDataObject{typeAndShape}); 1658 fResult.emplace(std::move(typeAndShape)); 1659 } else { 1660 context.messages().Say( 1661 "MOLD= argument to NULL() lacks type"_err_en_US); 1662 } 1663 fResult->attrs.set(characteristics::FunctionResult::Attr::Pointer); 1664 characteristics::Procedure::Attrs attrs; 1665 attrs.set(characteristics::Procedure::Attr::NullPointer); 1666 characteristics::Procedure chars{ 1667 std::move(*fResult), std::move(args), attrs}; 1668 return SpecificCall{ 1669 SpecificIntrinsic{"null"s, std::move(chars)}, std::move(arguments)}; 1670 } 1671 } 1672 context.messages().Say( 1673 "MOLD= argument to NULL() must be a pointer or allocatable"_err_en_US); 1674 } 1675 characteristics::Procedure::Attrs attrs; 1676 attrs.set(characteristics::Procedure::Attr::NullPointer); 1677 attrs.set(characteristics::Procedure::Attr::Pure); 1678 arguments.clear(); 1679 return SpecificCall{ 1680 SpecificIntrinsic{"null"s, 1681 characteristics::Procedure{characteristics::DummyArguments{}, attrs}}, 1682 std::move(arguments)}; 1683 } 1684 1685 // Subroutine C_F_POINTER(CPTR=,FPTR=[,SHAPE=]) from 1686 // intrinsic module ISO_C_BINDING (18.2.3.3) 1687 std::optional<SpecificCall> 1688 IntrinsicProcTable::Implementation::HandleC_F_Pointer( 1689 ActualArguments &arguments, FoldingContext &context) const { 1690 characteristics::Procedure::Attrs attrs; 1691 attrs.set(characteristics::Procedure::Attr::Subroutine); 1692 static const char *const keywords[]{"cptr", "fptr", "shape", nullptr}; 1693 characteristics::DummyArguments dummies; 1694 if (CheckAndRearrangeArguments(arguments, context.messages(), keywords, 1)) { 1695 CHECK(arguments.size() == 3); 1696 if (const auto *expr{arguments[0].value().UnwrapExpr()}) { 1697 if (expr->Rank() > 0) { 1698 context.messages().Say( 1699 "CPTR= argument to C_F_POINTER() must be scalar"_err_en_US); 1700 } 1701 if (auto type{expr->GetType()}) { 1702 if (type->category() != TypeCategory::Derived || 1703 type->IsPolymorphic() || 1704 type->GetDerivedTypeSpec().typeSymbol().name() != 1705 "__builtin_c_ptr") { 1706 context.messages().Say( 1707 "CPTR= argument to C_F_POINTER() must be a C_PTR"_err_en_US); 1708 } 1709 characteristics::DummyDataObject cptr{ 1710 characteristics::TypeAndShape{*type}}; 1711 cptr.intent = common::Intent::In; 1712 dummies.emplace_back("cptr"s, std::move(cptr)); 1713 } 1714 } 1715 if (const auto *expr{arguments[1].value().UnwrapExpr()}) { 1716 int fptrRank{expr->Rank()}; 1717 if (auto type{expr->GetType()}) { 1718 if (type->HasDeferredTypeParameter()) { 1719 context.messages().Say( 1720 "FPTR= argument to C_F_POINTER() may not have a deferred type parameter"_err_en_US); 1721 } 1722 if (ExtractCoarrayRef(*expr)) { 1723 context.messages().Say( 1724 "FPTR= argument to C_F_POINTER() may not be a coindexed object"_err_en_US); 1725 } 1726 characteristics::DummyDataObject fptr{ 1727 characteristics::TypeAndShape{*type, fptrRank}}; 1728 fptr.intent = common::Intent::Out; 1729 fptr.attrs.set(characteristics::DummyDataObject::Attr::Pointer); 1730 dummies.emplace_back("fptr"s, std::move(fptr)); 1731 } 1732 if (arguments[2] && fptrRank == 0) { 1733 context.messages().Say( 1734 "SHAPE= argument to C_F_POINTER() may not appear when FPTR= is scalar"_err_en_US); 1735 } else if (!arguments[2] && fptrRank > 0) { 1736 context.messages().Say( 1737 "SHAPE= argument to C_F_POINTER() must appear when FPTR= is an array"_err_en_US); 1738 } 1739 if (arguments[2]) { 1740 DynamicType shapeType{ 1741 TypeCategory::Integer, defaults_.sizeIntegerKind()}; 1742 if (auto type{arguments[2]->GetType()}) { 1743 if (type->category() == TypeCategory::Integer) { 1744 shapeType = *type; 1745 } 1746 } 1747 characteristics::DummyDataObject shape{ 1748 characteristics::TypeAndShape{shapeType, 1}}; 1749 shape.intent = common::Intent::In; 1750 shape.attrs.set(characteristics::DummyDataObject::Attr::Optional); 1751 dummies.emplace_back("shape"s, std::move(shape)); 1752 } 1753 } 1754 } 1755 if (dummies.size() == 3) { 1756 return SpecificCall{ 1757 SpecificIntrinsic{"__builtin_c_f_pointer"s, 1758 characteristics::Procedure{std::move(dummies), attrs}}, 1759 std::move(arguments)}; 1760 } else { 1761 return std::nullopt; 1762 } 1763 } 1764 1765 // Applies any semantic checks peculiar to an intrinsic. 1766 static bool ApplySpecificChecks( 1767 SpecificCall &call, parser::ContextualMessages &messages) { 1768 bool ok{true}; 1769 const std::string &name{call.specificIntrinsic.name}; 1770 if (name == "allocated") { 1771 if (const auto &arg{call.arguments[0]}) { 1772 if (const auto *expr{arg->UnwrapExpr()}) { 1773 if (const Symbol * symbol{GetLastSymbol(*expr)}) { 1774 ok = symbol->attrs().test(semantics::Attr::ALLOCATABLE); 1775 } 1776 } 1777 } 1778 if (!ok) { 1779 messages.Say( 1780 "Argument of ALLOCATED() must be an ALLOCATABLE object or component"_err_en_US); 1781 } 1782 } else if (name == "associated") { 1783 if (const auto &arg{call.arguments[0]}) { 1784 if (const auto *expr{arg->UnwrapExpr()}) { 1785 if (const Symbol * symbol{GetLastSymbol(*expr)}) { 1786 ok = symbol->attrs().test(semantics::Attr::POINTER); 1787 // TODO: validate the TARGET= argument vs. the pointer 1788 } 1789 } 1790 } 1791 if (!ok) { 1792 messages.Say( 1793 "Arguments of ASSOCIATED() must be a POINTER and an optional valid target"_err_en_US); 1794 } 1795 } else if (name == "loc") { 1796 if (const auto &arg{call.arguments[0]}) { 1797 ok = arg->GetAssumedTypeDummy() || GetLastSymbol(arg->UnwrapExpr()); 1798 } 1799 if (!ok) { 1800 messages.Say( 1801 "Argument of LOC() must be an object or procedure"_err_en_US); 1802 } 1803 } else if (name == "present") { 1804 if (const auto &arg{call.arguments[0]}) { 1805 if (const auto *expr{arg->UnwrapExpr()}) { 1806 if (const Symbol * symbol{UnwrapWholeSymbolDataRef(*expr)}) { 1807 ok = symbol->attrs().test(semantics::Attr::OPTIONAL); 1808 } 1809 } 1810 } 1811 if (!ok) { 1812 messages.Say( 1813 "Argument of PRESENT() must be the name of an OPTIONAL dummy argument"_err_en_US); 1814 } 1815 } 1816 return ok; 1817 } 1818 1819 static DynamicType GetReturnType(const SpecificIntrinsicInterface &interface, 1820 const common::IntrinsicTypeDefaultKinds &defaults) { 1821 TypeCategory category{TypeCategory::Integer}; 1822 switch (interface.result.kindCode) { 1823 case KindCode::defaultIntegerKind: 1824 break; 1825 case KindCode::doublePrecision: 1826 case KindCode::defaultRealKind: 1827 category = TypeCategory::Real; 1828 break; 1829 default: 1830 CRASH_NO_CASE; 1831 } 1832 int kind{interface.result.kindCode == KindCode::doublePrecision 1833 ? defaults.doublePrecisionKind() 1834 : defaults.GetDefaultKind(category)}; 1835 return DynamicType{category, kind}; 1836 } 1837 1838 // Probe the configured intrinsic procedure pattern tables in search of a 1839 // match for a given procedure reference. 1840 std::optional<SpecificCall> IntrinsicProcTable::Implementation::Probe( 1841 const CallCharacteristics &call, ActualArguments &arguments, 1842 FoldingContext &context, const IntrinsicProcTable &intrinsics) const { 1843 1844 // All special cases handled here before the table probes below must 1845 // also be recognized as special names in IsIntrinsic(). 1846 if (call.isSubroutineCall) { 1847 if (call.name == "__builtin_c_f_pointer") { 1848 return HandleC_F_Pointer(arguments, context); 1849 } 1850 } else { 1851 if (call.name == "null") { 1852 return HandleNull(arguments, context, intrinsics); 1853 } 1854 } 1855 1856 if (call.isSubroutineCall) { 1857 parser::Messages buffer; 1858 auto subrRange{subroutines_.equal_range(call.name)}; 1859 for (auto iter{subrRange.first}; iter != subrRange.second; ++iter) { 1860 if (auto specificCall{ 1861 iter->second->Match(call, defaults_, arguments, context)}) { 1862 return specificCall; 1863 } 1864 } 1865 return std::nullopt; // TODO 1866 } 1867 1868 // Helper to avoid emitting errors before it is sure there is no match 1869 parser::Messages localBuffer; 1870 parser::Messages *finalBuffer{context.messages().messages()}; 1871 parser::ContextualMessages localMessages{ 1872 context.messages().at(), finalBuffer ? &localBuffer : nullptr}; 1873 FoldingContext localContext{context, localMessages}; 1874 auto matchOrBufferMessages{ 1875 [&](const IntrinsicInterface &intrinsic, 1876 parser::Messages &buffer) -> std::optional<SpecificCall> { 1877 if (auto specificCall{ 1878 intrinsic.Match(call, defaults_, arguments, localContext)}) { 1879 if (finalBuffer) { 1880 finalBuffer->Annex(std::move(localBuffer)); 1881 } 1882 return specificCall; 1883 } else if (buffer.empty()) { 1884 buffer.Annex(std::move(localBuffer)); 1885 } else { 1886 localBuffer.clear(); 1887 } 1888 return std::nullopt; 1889 }}; 1890 1891 // Probe the generic intrinsic function table first. 1892 parser::Messages genericBuffer; 1893 auto genericRange{genericFuncs_.equal_range(call.name)}; 1894 for (auto iter{genericRange.first}; iter != genericRange.second; ++iter) { 1895 if (auto specificCall{ 1896 matchOrBufferMessages(*iter->second, genericBuffer)}) { 1897 ApplySpecificChecks(*specificCall, context.messages()); 1898 return specificCall; 1899 } 1900 } 1901 1902 // Probe the specific intrinsic function table next. 1903 parser::Messages specificBuffer; 1904 auto specificRange{specificFuncs_.equal_range(call.name)}; 1905 for (auto specIter{specificRange.first}; specIter != specificRange.second; 1906 ++specIter) { 1907 // We only need to check the cases with distinct generic names. 1908 if (const char *genericName{specIter->second->generic}) { 1909 if (auto specificCall{ 1910 matchOrBufferMessages(*specIter->second, specificBuffer)}) { 1911 specificCall->specificIntrinsic.name = genericName; 1912 specificCall->specificIntrinsic.isRestrictedSpecific = 1913 specIter->second->isRestrictedSpecific; 1914 // TODO test feature AdditionalIntrinsics, warn on nonstandard 1915 // specifics with DoublePrecisionComplex arguments. 1916 return specificCall; 1917 } 1918 } 1919 } 1920 1921 // If there was no exact match with a specific, try to match the related 1922 // generic and convert the result to the specific required type. 1923 for (auto specIter{specificRange.first}; specIter != specificRange.second; 1924 ++specIter) { 1925 // We only need to check the cases with distinct generic names. 1926 if (const char *genericName{specIter->second->generic}) { 1927 if (specIter->second->useGenericAndForceResultType) { 1928 auto genericRange{genericFuncs_.equal_range(genericName)}; 1929 for (auto genIter{genericRange.first}; genIter != genericRange.second; 1930 ++genIter) { 1931 if (auto specificCall{ 1932 matchOrBufferMessages(*genIter->second, specificBuffer)}) { 1933 // Force the call result type to the specific intrinsic result type 1934 DynamicType newType{GetReturnType(*specIter->second, defaults_)}; 1935 context.messages().Say( 1936 "Argument type does not match specific intrinsic '%s' " 1937 "requirements; using '%s' generic instead and converting the " 1938 "result to %s if needed"_en_US, 1939 call.name, genericName, newType.AsFortran()); 1940 specificCall->specificIntrinsic.characteristics.value() 1941 .functionResult.value() 1942 .SetType(newType); 1943 return specificCall; 1944 } 1945 } 1946 } 1947 } 1948 } 1949 1950 // No match; report the right errors, if any 1951 if (finalBuffer) { 1952 if (specificBuffer.empty()) { 1953 finalBuffer->Annex(std::move(genericBuffer)); 1954 } else { 1955 finalBuffer->Annex(std::move(specificBuffer)); 1956 } 1957 } 1958 return std::nullopt; 1959 } 1960 1961 std::optional<SpecificIntrinsicFunctionInterface> 1962 IntrinsicProcTable::Implementation::IsSpecificIntrinsicFunction( 1963 const std::string &name) const { 1964 auto specificRange{specificFuncs_.equal_range(name)}; 1965 for (auto iter{specificRange.first}; iter != specificRange.second; ++iter) { 1966 const SpecificIntrinsicInterface &specific{*iter->second}; 1967 std::string genericName{name}; 1968 if (specific.generic) { 1969 genericName = std::string(specific.generic); 1970 } 1971 characteristics::FunctionResult fResult{GetSpecificType(specific.result)}; 1972 characteristics::DummyArguments args; 1973 int dummies{specific.CountArguments()}; 1974 for (int j{0}; j < dummies; ++j) { 1975 characteristics::DummyDataObject dummy{ 1976 GetSpecificType(specific.dummy[j].typePattern)}; 1977 dummy.intent = common::Intent::In; 1978 args.emplace_back( 1979 std::string{specific.dummy[j].keyword}, std::move(dummy)); 1980 } 1981 characteristics::Procedure::Attrs attrs; 1982 attrs.set(characteristics::Procedure::Attr::Pure) 1983 .set(characteristics::Procedure::Attr::Elemental); 1984 characteristics::Procedure chars{ 1985 std::move(fResult), std::move(args), attrs}; 1986 return SpecificIntrinsicFunctionInterface{ 1987 std::move(chars), genericName, specific.isRestrictedSpecific}; 1988 } 1989 return std::nullopt; 1990 } 1991 1992 DynamicType IntrinsicProcTable::Implementation::GetSpecificType( 1993 const TypePattern &pattern) const { 1994 const CategorySet &set{pattern.categorySet}; 1995 CHECK(set.count() == 1); 1996 TypeCategory category{set.LeastElement().value()}; 1997 return DynamicType{category, defaults_.GetDefaultKind(category)}; 1998 } 1999 2000 IntrinsicProcTable::~IntrinsicProcTable() { 2001 // Discard the configured tables. 2002 delete impl_; 2003 impl_ = nullptr; 2004 } 2005 2006 IntrinsicProcTable IntrinsicProcTable::Configure( 2007 const common::IntrinsicTypeDefaultKinds &defaults) { 2008 IntrinsicProcTable result; 2009 result.impl_ = new IntrinsicProcTable::Implementation(defaults); 2010 return result; 2011 } 2012 2013 bool IntrinsicProcTable::IsIntrinsic(const std::string &name) const { 2014 return DEREF(impl_).IsIntrinsic(name); 2015 } 2016 2017 std::optional<SpecificCall> IntrinsicProcTable::Probe( 2018 const CallCharacteristics &call, ActualArguments &arguments, 2019 FoldingContext &context) const { 2020 return DEREF(impl_).Probe(call, arguments, context, *this); 2021 } 2022 2023 std::optional<SpecificIntrinsicFunctionInterface> 2024 IntrinsicProcTable::IsSpecificIntrinsicFunction(const std::string &name) const { 2025 return DEREF(impl_).IsSpecificIntrinsicFunction(name); 2026 } 2027 2028 llvm::raw_ostream &TypePattern::Dump(llvm::raw_ostream &o) const { 2029 if (categorySet == AnyType) { 2030 o << "any type"; 2031 } else { 2032 const char *sep = ""; 2033 auto set{categorySet}; 2034 while (auto least{set.LeastElement()}) { 2035 o << sep << EnumToString(*least); 2036 sep = " or "; 2037 set.reset(*least); 2038 } 2039 } 2040 o << '(' << EnumToString(kindCode) << ')'; 2041 return o; 2042 } 2043 2044 llvm::raw_ostream &IntrinsicDummyArgument::Dump(llvm::raw_ostream &o) const { 2045 if (keyword) { 2046 o << keyword << '='; 2047 } 2048 return typePattern.Dump(o) 2049 << ' ' << EnumToString(rank) << ' ' << EnumToString(optionality); 2050 } 2051 2052 llvm::raw_ostream &IntrinsicInterface::Dump(llvm::raw_ostream &o) const { 2053 o << name; 2054 char sep{'('}; 2055 for (const auto &d : dummy) { 2056 if (d.typePattern.kindCode == KindCode::none) { 2057 break; 2058 } 2059 d.Dump(o << sep); 2060 sep = ','; 2061 } 2062 if (sep == '(') { 2063 o << "()"; 2064 } 2065 return result.Dump(o << " -> ") << ' ' << EnumToString(rank); 2066 } 2067 2068 llvm::raw_ostream &IntrinsicProcTable::Implementation::Dump( 2069 llvm::raw_ostream &o) const { 2070 o << "generic intrinsic functions:\n"; 2071 for (const auto &iter : genericFuncs_) { 2072 iter.second->Dump(o << iter.first << ": ") << '\n'; 2073 } 2074 o << "specific intrinsic functions:\n"; 2075 for (const auto &iter : specificFuncs_) { 2076 iter.second->Dump(o << iter.first << ": "); 2077 if (const char *g{iter.second->generic}) { 2078 o << " -> " << g; 2079 } 2080 o << '\n'; 2081 } 2082 o << "subroutines:\n"; 2083 for (const auto &iter : subroutines_) { 2084 iter.second->Dump(o << iter.first << ": ") << '\n'; 2085 } 2086 return o; 2087 } 2088 2089 llvm::raw_ostream &IntrinsicProcTable::Dump(llvm::raw_ostream &o) const { 2090 return impl_->Dump(o); 2091 } 2092 } // namespace Fortran::evaluate 2093