Debian Codegraph @

flang/lib/Evaluate/intrinsics.cpp

raw
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/check-expression.h"
14 #include "flang/Evaluate/common.h"
15 #include "flang/Evaluate/expression.h"
16 #include "flang/Evaluate/fold.h"
17 #include "flang/Evaluate/shape.h"
18 #include "flang/Evaluate/tools.h"
19 #include "flang/Evaluate/type.h"
20 #include "flang/Semantics/scope.h"
21 #include "flang/Semantics/tools.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <algorithm>
24 #include <cmath>
25 #include <map>
26 #include <string>
27 #include <utility>
28
29 using namespace Fortran::parser::literals;
30
31 namespace Fortran::evaluate {
32
33 class FoldingContext;
34
35 // This file defines the supported intrinsic procedures and implements
36 // their recognition and validation. It is largely table-driven. See
37 // docs/intrinsics.md and section 16 of the Fortran 2018 standard
38 // for full details on each of the intrinsics. Be advised, they have
39 // complicated details, and the design of these tables has to accommodate
40 // that complexity.
41
42 // Dummy arguments to generic intrinsic procedures are each specified by
43 // their keyword name (rarely used, but always defined), allowable type
44 // categories, a kind pattern, a rank pattern, and information about
45 // optionality and defaults. The kind and rank patterns are represented
46 // here with code values that are significant to the matching/validation engine.
47
48 // An actual argument to an intrinsic procedure may be a procedure itself
49 // only if the dummy argument is Rank::reduceOperation,
50 // KindCode::addressable, or the special case of NULL(MOLD=procedurePointer).
51
52 // These are small bit-sets of type category enumerators.
53 // Note that typeless (BOZ literal) values don't have a distinct type category.
54 // These typeless arguments are represented in the tables as if they were
55 // INTEGER with a special "typeless" kind code. Arguments of intrinsic types
56 // that can also be typeless values are encoded with an "elementalOrBOZ"
57 // rank pattern.
58 // Assumed-type (TYPE(*)) dummy arguments can be forwarded along to some
59 // intrinsic functions that accept AnyType + Rank::anyOrAssumedRank,
60 // AnyType + Rank::arrayOrAssumedRank, or AnyType + Kind::addressable.
61 using CategorySet = common::EnumSet<TypeCategory, 8>;
62 static constexpr CategorySet IntType{TypeCategory::Integer};
63 static constexpr CategorySet RealType{TypeCategory::Real};
64 static constexpr CategorySet ComplexType{TypeCategory::Complex};
65 static constexpr CategorySet CharType{TypeCategory::Character};
66 static constexpr CategorySet LogicalType{TypeCategory::Logical};
67 static constexpr CategorySet IntOrRealType{IntType | RealType};
68 static constexpr CategorySet IntOrRealOrCharType{IntType | RealType | CharType};
69 static constexpr CategorySet IntOrLogicalType{IntType | LogicalType};
70 static constexpr CategorySet FloatingType{RealType | ComplexType};
71 static constexpr CategorySet NumericType{IntType | RealType | ComplexType};
72 static constexpr CategorySet RelatableType{IntType | RealType | CharType};
73 static constexpr CategorySet DerivedType{TypeCategory::Derived};
74 static constexpr CategorySet IntrinsicType{
75 IntType | RealType | ComplexType | CharType | LogicalType};
76 static constexpr CategorySet AnyType{IntrinsicType | DerivedType};
77
78 ENUM_CLASS(KindCode, none, defaultIntegerKind,
79 defaultRealKind, // is also the default COMPLEX kind
80 doublePrecision, defaultCharKind, defaultLogicalKind,
81 greaterOrEqualToKind, // match kind value greater than or equal to a single
82 // explicit kind value
83 any, // matches any kind value; each instance is independent
84 // match any kind, but all "same" kinds must be equal. For characters, also
85 // implies that lengths must be equal.
86 same,
87 // for characters that only require the same kind, not length
88 sameKind,
89 operand, // match any kind, with promotion (non-standard)
90 typeless, // BOZ literals are INTEGER with this kind
91 ieeeFlagType, // IEEE_FLAG_TYPE from ISO_FORTRAN_EXCEPTION
92 ieeeRoundType, // IEEE_ROUND_TYPE from ISO_FORTRAN_ARITHMETIC
93 teamType, // TEAM_TYPE from module ISO_FORTRAN_ENV (for coarrays)
94 kindArg, // this argument is KIND=
95 effectiveKind, // for function results: "kindArg" value, possibly defaulted
96 dimArg, // this argument is DIM=
97 likeMultiply, // for DOT_PRODUCT and MATMUL
98 subscript, // address-sized integer
99 size, // default KIND= for SIZE(), UBOUND, &c.
100 addressable, // for PRESENT(), &c.; anything (incl. procedure) but BOZ
101 nullPointerType, // for ASSOCIATED(NULL())
102 exactKind, // a single explicit exactKindValue
103 atomicIntKind, // atomic_int_kind from iso_fortran_env
104 atomicIntOrLogicalKind, // atomic_int_kind or atomic_logical_kind
105 sameAtom, // same type and kind as atom
106 )
107
108 struct TypePattern {
109 CategorySet categorySet;
110 KindCode kindCode{KindCode::none};
111 int kindValue{0}; // for KindCode::exactKind and greaterOrEqualToKind
112 llvm::raw_ostream &Dump(llvm::raw_ostream &) const;
113 };
114
115 // Abbreviations for argument and result patterns in the intrinsic prototypes:
116
117 // Match specific kinds of intrinsic types
118 static constexpr TypePattern DefaultInt{IntType, KindCode::defaultIntegerKind};
119 static constexpr TypePattern DefaultReal{RealType, KindCode::defaultRealKind};
120 static constexpr TypePattern DefaultComplex{
121 ComplexType, KindCode::defaultRealKind};
122 static constexpr TypePattern DefaultChar{CharType, KindCode::defaultCharKind};
123 static constexpr TypePattern DefaultLogical{
124 LogicalType, KindCode::defaultLogicalKind};
125 static constexpr TypePattern BOZ{IntType, KindCode::typeless};
126 static constexpr TypePattern IeeeFlagType{DerivedType, KindCode::ieeeFlagType};
127 static constexpr TypePattern IeeeRoundType{
128 DerivedType, KindCode::ieeeRoundType};
129 static constexpr TypePattern TeamType{DerivedType, KindCode::teamType};
130 static constexpr TypePattern DoublePrecision{
131 RealType, KindCode::doublePrecision};
132 static constexpr TypePattern DoublePrecisionComplex{
133 ComplexType, KindCode::doublePrecision};
134 static constexpr TypePattern SubscriptInt{IntType, KindCode::subscript};
135
136 // Match any kind of some intrinsic or derived types
137 static constexpr TypePattern AnyInt{IntType, KindCode::any};
138 static constexpr TypePattern AnyReal{RealType, KindCode::any};
139 static constexpr TypePattern AnyIntOrReal{IntOrRealType, KindCode::any};
140 static constexpr TypePattern AnyIntOrRealOrChar{
141 IntOrRealOrCharType, KindCode::any};
142 static constexpr TypePattern AnyIntOrLogical{IntOrLogicalType, KindCode::any};
143 static constexpr TypePattern AnyComplex{ComplexType, KindCode::any};
144 static constexpr TypePattern AnyFloating{FloatingType, KindCode::any};
145 static constexpr TypePattern AnyNumeric{NumericType, KindCode::any};
146 static constexpr TypePattern AnyChar{CharType, KindCode::any};
147 static constexpr TypePattern AnyLogical{LogicalType, KindCode::any};
148 static constexpr TypePattern AnyRelatable{RelatableType, KindCode::any};
149 static constexpr TypePattern AnyIntrinsic{IntrinsicType, KindCode::any};
150 static constexpr TypePattern ExtensibleDerived{DerivedType, KindCode::any};
151 static constexpr TypePattern AnyData{AnyType, KindCode::any};
152
153 // Type is irrelevant, but not BOZ (for PRESENT(), OPTIONAL(), &c.)
154 static constexpr TypePattern Addressable{AnyType, KindCode::addressable};
155
156 // Match some kind of some intrinsic type(s); all "Same" values must match,
157 // even when not in the same category (e.g., SameComplex and SameReal).
158 // Can be used to specify a result so long as at least one argument is
159 // a "Same".
160 static constexpr TypePattern SameInt{IntType, KindCode::same};
161 static constexpr TypePattern SameReal{RealType, KindCode::same};
162 static constexpr TypePattern SameIntOrReal{IntOrRealType, KindCode::same};
163 static constexpr TypePattern SameComplex{ComplexType, KindCode::same};
164 static constexpr TypePattern SameFloating{FloatingType, KindCode::same};
165 static constexpr TypePattern SameNumeric{NumericType, KindCode::same};
166 static constexpr TypePattern SameChar{CharType, KindCode::same};
167 static constexpr TypePattern SameCharNoLen{CharType, KindCode::sameKind};
168 static constexpr TypePattern SameLogical{LogicalType, KindCode::same};
169 static constexpr TypePattern SameRelatable{RelatableType, KindCode::same};
170 static constexpr TypePattern SameIntrinsic{IntrinsicType, KindCode::same};
171 static constexpr TypePattern SameDerivedType{
172 CategorySet{TypeCategory::Derived}, KindCode::same};
173 static constexpr TypePattern SameType{AnyType, KindCode::same};
174
175 // Match some kind of some INTEGER or REAL type(s); when argument types
176 // &/or kinds differ, their values are converted as if they were operands to
177 // an intrinsic operation like addition. This is a nonstandard but nearly
178 // universal extension feature.
179 static constexpr TypePattern OperandReal{RealType, KindCode::operand};
180 static constexpr TypePattern OperandInt{IntType, KindCode::operand};
181 static constexpr TypePattern OperandIntOrReal{IntOrRealType, KindCode::operand};
182
183 // For ASSOCIATED, the first argument is a typeless pointer
184 static constexpr TypePattern AnyPointer{AnyType, KindCode::nullPointerType};
185
186 // For DOT_PRODUCT and MATMUL, the result type depends on the arguments
187 static constexpr TypePattern ResultLogical{LogicalType, KindCode::likeMultiply};
188 static constexpr TypePattern ResultNumeric{NumericType, KindCode::likeMultiply};
189
190 // Result types with known category and KIND=
191 static constexpr TypePattern KINDInt{IntType, KindCode::effectiveKind};
192 static constexpr TypePattern KINDReal{RealType, KindCode::effectiveKind};
193 static constexpr TypePattern KINDComplex{ComplexType, KindCode::effectiveKind};
194 static constexpr TypePattern KINDChar{CharType, KindCode::effectiveKind};
195 static constexpr TypePattern KINDLogical{LogicalType, KindCode::effectiveKind};
196
197 static constexpr TypePattern AtomicInt{IntType, KindCode::atomicIntKind};
198 static constexpr TypePattern AtomicIntOrLogical{
199 IntOrLogicalType, KindCode::atomicIntOrLogicalKind};
200 static constexpr TypePattern SameAtom{IntOrLogicalType, KindCode::sameAtom};
201
202 // The default rank pattern for dummy arguments and function results is
203 // "elemental".
204 ENUM_CLASS(Rank,
205 elemental, // scalar, or array that conforms with other array arguments
206 elementalOrBOZ, // elemental, or typeless BOZ literal scalar
207 scalar, vector,
208 shape, // INTEGER vector of known length and no negative element
209 matrix,
210 array, // not scalar, rank is known and greater than zero
211 coarray, // rank is known and can be scalar; has nonzero corank
212 atom, // is scalar and has nonzero corank or is coindexed
213 known, // rank is known and can be scalar
214 anyOrAssumedRank, // any rank, or assumed; assumed-type TYPE(*) allowed
215 arrayOrAssumedRank, // rank >= 1 or assumed; assumed-type TYPE(*) allowed
216 conformable, // scalar, or array of same rank & shape as "array" argument
217 reduceOperation, // a pure function with constraints for REDUCE
218 dimReduced, // scalar if no DIM= argument, else rank(array)-1
219 dimRemovedOrScalar, // rank(array)-1 (less DIM) or scalar
220 scalarIfDim, // scalar if DIM= argument is present, else rank one array
221 locReduced, // vector(1:rank) if no DIM= argument, else rank(array)-1
222 rankPlus1, // rank(known)+1
223 shaped, // rank is length of SHAPE vector
224 )
225
226 ENUM_CLASS(Optionality, required,
227 optional, // unless DIM= for SIZE(assumedSize)
228 missing, // for DIM= cases like FINDLOC
229 repeats, // for MAX/MIN and their several variants
230 )
231
232 ENUM_CLASS(ArgFlag, none,
233 canBeNull, // actual argument can be NULL(with or without MOLD=)
234 canBeMoldNull, // actual argument can be NULL(with MOLD=)
235 defaultsToSameKind, // for MatchingDefaultKIND
236 defaultsToSizeKind, // for SizeDefaultKIND
237 defaultsToDefaultForResult, // for DefaultingKIND
238 notAssumedSize)
239
240 struct IntrinsicDummyArgument {
241 const char *keyword{nullptr};
242 TypePattern typePattern;
243 Rank rank{Rank::elemental};
244 Optionality optionality{Optionality::required};
245 common::Intent intent{common::Intent::In};
246 common::EnumSet<ArgFlag, 32> flags{};
247 llvm::raw_ostream &Dump(llvm::raw_ostream &) const;
248 };
249
250 // constexpr abbreviations for popular arguments:
251 // DefaultingKIND is a KIND= argument whose default value is the appropriate
252 // KIND(0), KIND(0.0), KIND(''), &c. value for the function result.
253 static constexpr IntrinsicDummyArgument DefaultingKIND{"kind",
254 {IntType, KindCode::kindArg}, Rank::scalar, Optionality::optional,
255 common::Intent::In, {ArgFlag::defaultsToDefaultForResult}};
256 // MatchingDefaultKIND is a KIND= argument whose default value is the
257 // kind of any "Same" function argument (viz., the one whose kind pattern is
258 // "same").
259 static constexpr IntrinsicDummyArgument MatchingDefaultKIND{"kind",
260 {IntType, KindCode::kindArg}, Rank::scalar, Optionality::optional,
261 common::Intent::In, {ArgFlag::defaultsToSameKind}};
262 // SizeDefaultKind is a KIND= argument whose default value should be
263 // the kind of INTEGER used for address calculations, and can be
264 // set so with a compiler flag; but the standard mandates the
265 // kind of default INTEGER.
266 static constexpr IntrinsicDummyArgument SizeDefaultKIND{"kind",
267 {IntType, KindCode::kindArg}, Rank::scalar, Optionality::optional,
268 common::Intent::In, {ArgFlag::defaultsToSizeKind}};
269 static constexpr IntrinsicDummyArgument RequiredDIM{"dim",
270 {IntType, KindCode::dimArg}, Rank::scalar, Optionality::required,
271 common::Intent::In};
272 static constexpr IntrinsicDummyArgument OptionalDIM{"dim",
273 {IntType, KindCode::dimArg}, Rank::scalar, Optionality::optional,
274 common::Intent::In};
275 static constexpr IntrinsicDummyArgument MissingDIM{"dim",
276 {IntType, KindCode::dimArg}, Rank::scalar, Optionality::missing,
277 common::Intent::In};
278 static constexpr IntrinsicDummyArgument OptionalMASK{"mask", AnyLogical,
279 Rank::conformable, Optionality::optional, common::Intent::In};
280 static constexpr IntrinsicDummyArgument OptionalTEAM{
281 "team", TeamType, Rank::scalar, Optionality::optional, common::Intent::In};
282
283 struct IntrinsicInterface {
284 static constexpr int maxArguments{7}; // if not a MAX/MIN(...)
285 const char *name{nullptr};
286 IntrinsicDummyArgument dummy[maxArguments];
287 TypePattern result;
288 Rank rank{Rank::elemental};
289 IntrinsicClass intrinsicClass{IntrinsicClass::elementalFunction};
290 std::optional<SpecificCall> Match(const CallCharacteristics &,
291 const common::IntrinsicTypeDefaultKinds &, ActualArguments &,
292 FoldingContext &context, const semantics::Scope *builtins) const;
293 int CountArguments() const;
294 llvm::raw_ostream &Dump(llvm::raw_ostream &) const;
295 };
296
297 int IntrinsicInterface::CountArguments() const {
298 int n{0};
299 while (n < maxArguments && dummy[n].keyword) {
300 ++n;
301 }
302 return n;
303 }
304
305 // GENERIC INTRINSIC FUNCTION INTERFACES
306 // Each entry in this table defines a pattern. Some intrinsic
307 // functions have more than one such pattern. Besides the name
308 // of the intrinsic function, each pattern has specifications for
309 // the dummy arguments and for the result of the function.
310 // The dummy argument patterns each have a name (these are from the
311 // standard, but rarely appear in actual code), a type and kind
312 // pattern, allowable ranks, and optionality indicators.
313 // Be advised, the default rank pattern is "elemental".
314 static const IntrinsicInterface genericIntrinsicFunction[]{
315 {"abs", {{"a", SameIntOrReal}}, SameIntOrReal},
316 {"abs", {{"a", SameComplex}}, SameReal},
317 {"achar", {{"i", AnyInt, Rank::elementalOrBOZ}, DefaultingKIND}, KINDChar},
318 {"acos", {{"x", SameFloating}}, SameFloating},
319 {"acosd", {{"x", SameFloating}}, SameFloating},
320 {"acosh", {{"x", SameFloating}}, SameFloating},
321 {"adjustl", {{"string", SameChar}}, SameChar},
322 {"adjustr", {{"string", SameChar}}, SameChar},
323 {"aimag", {{"z", SameComplex}}, SameReal},
324 {"aint", {{"a", SameReal}, MatchingDefaultKIND}, KINDReal},
325 {"all", {{"mask", SameLogical, Rank::array}, OptionalDIM}, SameLogical,
326 Rank::dimReduced, IntrinsicClass::transformationalFunction},
327 {"allocated", {{"scalar", AnyData, Rank::scalar}}, DefaultLogical,
328 Rank::elemental, IntrinsicClass::inquiryFunction},
329 {"allocated", {{"array", AnyData, Rank::anyOrAssumedRank}}, DefaultLogical,
330 Rank::elemental, IntrinsicClass::inquiryFunction},
331 {"anint", {{"a", SameReal}, MatchingDefaultKIND}, KINDReal},
332 {"any", {{"mask", SameLogical, Rank::array}, OptionalDIM}, SameLogical,
333 Rank::dimReduced, IntrinsicClass::transformationalFunction},
334 {"asin", {{"x", SameFloating}}, SameFloating},
335 {"asind", {{"x", SameFloating}}, SameFloating},
336 {"asinh", {{"x", SameFloating}}, SameFloating},
337 {"associated",
338 {{"pointer", AnyPointer, Rank::anyOrAssumedRank, Optionality::required,
339 common::Intent::In, {ArgFlag::canBeNull}},
340 {"target", Addressable, Rank::anyOrAssumedRank,
341 Optionality::optional, common::Intent::In,
342 {ArgFlag::canBeNull}}},
343 DefaultLogical, Rank::elemental, IntrinsicClass::inquiryFunction},
344 {"atan", {{"x", SameFloating}}, SameFloating},
345 {"atan", {{"y", OperandReal}, {"x", OperandReal}}, OperandReal},
346 {"atand", {{"x", SameFloating}}, SameFloating},
347 {"atand", {{"y", OperandReal}, {"x", OperandReal}}, OperandReal},
348 {"atan2", {{"y", OperandReal}, {"x", OperandReal}}, OperandReal},
349 {"atan2d", {{"y", OperandReal}, {"x", OperandReal}}, OperandReal},
350 {"atanpi", {{"x", SameFloating}}, SameFloating},
351 {"atanpi", {{"y", OperandReal}, {"x", OperandReal}}, OperandReal},
352 {"atan2pi", {{"y", OperandReal}, {"x", OperandReal}}, OperandReal},
353 {"atanh", {{"x", SameFloating}}, SameFloating},
354 {"bessel_j0", {{"x", SameReal}}, SameReal},
355 {"bessel_j1", {{"x", SameReal}}, SameReal},
356 {"bessel_jn", {{"n", AnyInt}, {"x", SameReal}}, SameReal},
357 {"bessel_jn",
358 {{"n1", AnyInt, Rank::scalar}, {"n2", AnyInt, Rank::scalar},
359 {"x", SameReal, Rank::scalar}},
360 SameReal, Rank::vector, IntrinsicClass::transformationalFunction},
361 {"bessel_y0", {{"x", SameReal}}, SameReal},
362 {"bessel_y1", {{"x", SameReal}}, SameReal},
363 {"bessel_yn", {{"n", AnyInt}, {"x", SameReal}}, SameReal},
364 {"bessel_yn",
365 {{"n1", AnyInt, Rank::scalar}, {"n2", AnyInt, Rank::scalar},
366 {"x", SameReal, Rank::scalar}},
367 SameReal, Rank::vector, IntrinsicClass::transformationalFunction},
368 {"bge",
369 {{"i", AnyInt, Rank::elementalOrBOZ},
370 {"j", AnyInt, Rank::elementalOrBOZ}},
371 DefaultLogical},
372 {"bgt",
373 {{"i", AnyInt, Rank::elementalOrBOZ},
374 {"j", AnyInt, Rank::elementalOrBOZ}},
375 DefaultLogical},
376 {"bit_size",
377 {{"i", SameInt, Rank::anyOrAssumedRank, Optionality::required,
378 common::Intent::In, {ArgFlag::canBeMoldNull}}},
379 SameInt, Rank::scalar, IntrinsicClass::inquiryFunction},
380 {"ble",
381 {{"i", AnyInt, Rank::elementalOrBOZ},
382 {"j", AnyInt, Rank::elementalOrBOZ}},
383 DefaultLogical},
384 {"blt",
385 {{"i", AnyInt, Rank::elementalOrBOZ},
386 {"j", AnyInt, Rank::elementalOrBOZ}},
387 DefaultLogical},
388 {"btest", {{"i", AnyInt, Rank::elementalOrBOZ}, {"pos", AnyInt}},
389 DefaultLogical},
390 {"ceiling", {{"a", AnyReal}, DefaultingKIND}, KINDInt},
391 {"char", {{"i", AnyInt, Rank::elementalOrBOZ}, DefaultingKIND}, KINDChar},
392 {"cmplx", {{"x", AnyComplex}, DefaultingKIND}, KINDComplex},
393 {"cmplx",
394 {{"x", AnyIntOrReal, Rank::elementalOrBOZ},
395 {"y", AnyIntOrReal, Rank::elementalOrBOZ, Optionality::optional},
396 DefaultingKIND},
397 KINDComplex},
398 {"command_argument_count", {}, DefaultInt, Rank::scalar,
399 IntrinsicClass::transformationalFunction},
400 {"conjg", {{"z", SameComplex}}, SameComplex},
401 {"cos", {{"x", SameFloating}}, SameFloating},
402 {"cosd", {{"x", SameFloating}}, SameFloating},
403 {"cosh", {{"x", SameFloating}}, SameFloating},
404 {"count", {{"mask", AnyLogical, Rank::array}, OptionalDIM, DefaultingKIND},
405 KINDInt, Rank::dimReduced, IntrinsicClass::transformationalFunction},
406 {"cshift",
407 {{"array", SameType, Rank::array},
408 {"shift", AnyInt, Rank::dimRemovedOrScalar}, OptionalDIM},
409 SameType, Rank::conformable, IntrinsicClass::transformationalFunction},
410 {"dble", {{"a", AnyNumeric, Rank::elementalOrBOZ}}, DoublePrecision},
411 {"digits",
412 {{"x", AnyIntOrReal, Rank::anyOrAssumedRank, Optionality::required,
413 common::Intent::In, {ArgFlag::canBeMoldNull}}},
414 DefaultInt, Rank::scalar, IntrinsicClass::inquiryFunction},
415 {"dim", {{"x", OperandIntOrReal}, {"y", OperandIntOrReal}},
416 OperandIntOrReal},
417 {"dot_product",
418 {{"vector_a", AnyLogical, Rank::vector},
419 {"vector_b", AnyLogical, Rank::vector}},
420 ResultLogical, Rank::scalar, IntrinsicClass::transformationalFunction},
421 {"dot_product",
422 {{"vector_a", AnyComplex, Rank::vector},
423 {"vector_b", AnyNumeric, Rank::vector}},
424 ResultNumeric, Rank::scalar, // conjugates vector_a
425 IntrinsicClass::transformationalFunction},
426 {"dot_product",
427 {{"vector_a", AnyIntOrReal, Rank::vector},
428 {"vector_b", AnyNumeric, Rank::vector}},
429 ResultNumeric, Rank::scalar, IntrinsicClass::transformationalFunction},
430 {"dprod", {{"x", DefaultReal}, {"y", DefaultReal}}, DoublePrecision},
431 {"dshiftl",
432 {{"i", SameInt}, {"j", SameInt, Rank::elementalOrBOZ},
433 {"shift", AnyInt}},
434 SameInt},
435 {"dshiftl", {{"i", BOZ}, {"j", SameInt}, {"shift", AnyInt}}, SameInt},
436 {"dshiftr",
437 {{"i", SameInt}, {"j", SameInt, Rank::elementalOrBOZ},
438 {"shift", AnyInt}},
439 SameInt},
440 {"dshiftr", {{"i", BOZ}, {"j", SameInt}, {"shift", AnyInt}}, SameInt},
441 {"eoshift",
442 {{"array", SameIntrinsic, Rank::array},
443 {"shift", AnyInt, Rank::dimRemovedOrScalar},
444 {"boundary", SameIntrinsic, Rank::dimRemovedOrScalar,
445 Optionality::optional},
446 OptionalDIM},
447 SameIntrinsic, Rank::conformable,
448 IntrinsicClass::transformationalFunction},
449 {"eoshift",
450 {{"array", SameDerivedType, Rank::array},
451 {"shift", AnyInt, Rank::dimRemovedOrScalar},
452 // BOUNDARY= is not optional for derived types
453 {"boundary", SameDerivedType, Rank::dimRemovedOrScalar},
454 OptionalDIM},
455 SameDerivedType, Rank::conformable,
456 IntrinsicClass::transformationalFunction},
457 {"epsilon",
458 {{"x", SameReal, Rank::anyOrAssumedRank, Optionality::required,
459 common::Intent::In, {ArgFlag::canBeMoldNull}}},
460 SameReal, Rank::scalar, IntrinsicClass::inquiryFunction},
461 {"erf", {{"x", SameReal}}, SameReal},
462 {"erfc", {{"x", SameReal}}, SameReal},
463 {"erfc_scaled", {{"x", SameReal}}, SameReal},
464 {"etime",
465 {{"values", TypePattern{RealType, KindCode::exactKind, 4}, Rank::vector,
466 Optionality::required, common::Intent::Out}},
467 TypePattern{RealType, KindCode::exactKind, 4}},
468 {"exp", {{"x", SameFloating}}, SameFloating},
469 {"exp", {{"x", SameFloating}}, SameFloating},
470 {"exponent", {{"x", AnyReal}}, DefaultInt},
471 {"exp", {{"x", SameFloating}}, SameFloating},
472 {"extends_type_of",
473 {{"a", ExtensibleDerived, Rank::anyOrAssumedRank, Optionality::required,
474 common::Intent::In, {ArgFlag::canBeMoldNull}},
475 {"mold", ExtensibleDerived, Rank::anyOrAssumedRank,
476 Optionality::required, common::Intent::In,
477 {ArgFlag::canBeMoldNull}}},
478 DefaultLogical, Rank::scalar, IntrinsicClass::inquiryFunction},
479 {"failed_images", {OptionalTEAM, SizeDefaultKIND}, KINDInt, Rank::vector,
480 IntrinsicClass::transformationalFunction},
481 {"findloc",
482 {{"array", AnyNumeric, Rank::array},
483 {"value", AnyNumeric, Rank::scalar}, RequiredDIM, OptionalMASK,
484 SizeDefaultKIND,
485 {"back", AnyLogical, Rank::scalar, Optionality::optional}},
486 KINDInt, Rank::locReduced, IntrinsicClass::transformationalFunction},
487 {"findloc",
488 {{"array", AnyNumeric, Rank::array},
489 {"value", AnyNumeric, Rank::scalar}, MissingDIM, OptionalMASK,
490 SizeDefaultKIND,
491 {"back", AnyLogical, Rank::scalar, Optionality::optional}},
492 KINDInt, Rank::vector, IntrinsicClass::transformationalFunction},
493 {"findloc",
494 {{"array", SameCharNoLen, Rank::array},
495 {"value", SameCharNoLen, Rank::scalar}, RequiredDIM, OptionalMASK,
496 SizeDefaultKIND,
497 {"back", AnyLogical, Rank::scalar, Optionality::optional}},
498 KINDInt, Rank::locReduced, IntrinsicClass::transformationalFunction},
499 {"findloc",
500 {{"array", SameCharNoLen, Rank::array},
501 {"value", SameCharNoLen, Rank::scalar}, MissingDIM, OptionalMASK,
502 SizeDefaultKIND,
503 {"back", AnyLogical, Rank::scalar, Optionality::optional}},
504 KINDInt, Rank::vector, IntrinsicClass::transformationalFunction},
505 {"findloc",
506 {{"array", AnyLogical, Rank::array},
507 {"value", AnyLogical, Rank::scalar}, RequiredDIM, OptionalMASK,
508 SizeDefaultKIND,
509 {"back", AnyLogical, Rank::scalar, Optionality::optional}},
510 KINDInt, Rank::locReduced, IntrinsicClass::transformationalFunction},
511 {"findloc",
512 {{"array", AnyLogical, Rank::array},
513 {"value", AnyLogical, Rank::scalar}, MissingDIM, OptionalMASK,
514 SizeDefaultKIND,
515 {"back", AnyLogical, Rank::scalar, Optionality::optional}},
516 KINDInt, Rank::vector, IntrinsicClass::transformationalFunction},
517 {"floor", {{"a", AnyReal}, DefaultingKIND}, KINDInt},
518 {"fraction", {{"x", SameReal}}, SameReal},
519 {"gamma", {{"x", SameReal}}, SameReal},
520 {"get_team", {{"level", DefaultInt, Rank::scalar, Optionality::optional}},
521 TeamType, Rank::scalar, IntrinsicClass::transformationalFunction},
522 {"getcwd",
523 {{"c", DefaultChar, Rank::scalar, Optionality::required,
524 common::Intent::Out}},
525 TypePattern{IntType, KindCode::greaterOrEqualToKind, 4}},
526 {"getpid", {}, DefaultInt},
527 {"huge",
528 {{"x", SameIntOrReal, Rank::anyOrAssumedRank, Optionality::required,
529 common::Intent::In, {ArgFlag::canBeMoldNull}}},
530 SameIntOrReal, Rank::scalar, IntrinsicClass::inquiryFunction},
531 {"hypot", {{"x", OperandReal}, {"y", OperandReal}}, OperandReal},
532 {"iachar", {{"c", AnyChar}, DefaultingKIND}, KINDInt},
533 {"iall", {{"array", SameInt, Rank::array}, RequiredDIM, OptionalMASK},
534 SameInt, Rank::dimReduced, IntrinsicClass::transformationalFunction},
535 {"iall", {{"array", SameInt, Rank::array}, MissingDIM, OptionalMASK},
536 SameInt, Rank::scalar, IntrinsicClass::transformationalFunction},
537 {"iany", {{"array", SameInt, Rank::array}, RequiredDIM, OptionalMASK},
538 SameInt, Rank::dimReduced, IntrinsicClass::transformationalFunction},
539 {"iany", {{"array", SameInt, Rank::array}, MissingDIM, OptionalMASK},
540 SameInt, Rank::scalar, IntrinsicClass::transformationalFunction},
541 {"iparity", {{"array", SameInt, Rank::array}, RequiredDIM, OptionalMASK},
542 SameInt, Rank::dimReduced, IntrinsicClass::transformationalFunction},
543 {"iparity", {{"array", SameInt, Rank::array}, MissingDIM, OptionalMASK},
544 SameInt, Rank::scalar, IntrinsicClass::transformationalFunction},
545 {"iand", {{"i", OperandInt}, {"j", OperandInt, Rank::elementalOrBOZ}},
546 OperandInt},
547 {"iand", {{"i", BOZ}, {"j", SameInt}}, SameInt},
548 {"ibclr", {{"i", SameInt}, {"pos", AnyInt}}, SameInt},
549 {"ibits", {{"i", SameInt}, {"pos", AnyInt}, {"len", AnyInt}}, SameInt},
550 {"ibset", {{"i", SameInt}, {"pos", AnyInt}}, SameInt},
551 {"ichar", {{"c", AnyChar}, DefaultingKIND}, KINDInt},
552 {"ieor", {{"i", OperandInt}, {"j", OperandInt, Rank::elementalOrBOZ}},
553 OperandInt},
554 {"ieor", {{"i", BOZ}, {"j", SameInt}}, SameInt},
555 {"image_index",
556 {{"coarray", AnyData, Rank::coarray}, {"sub", AnyInt, Rank::vector}},
557 DefaultInt, Rank::scalar, IntrinsicClass::transformationalFunction},
558 {"image_index",
559 {{"coarray", AnyData, Rank::coarray}, {"sub", AnyInt, Rank::vector},
560 {"team", TeamType, Rank::scalar}},
561 DefaultInt, Rank::scalar, IntrinsicClass::transformationalFunction},
562 {"image_index",
563 {{"coarray", AnyData, Rank::coarray}, {"sub", AnyInt, Rank::vector},
564 {"team_number", AnyInt, Rank::scalar}},
565 DefaultInt, Rank::scalar, IntrinsicClass::transformationalFunction},
566 {"image_status", {{"image", SameInt}, OptionalTEAM}, DefaultInt},
567 {"index",
568 {{"string", SameCharNoLen}, {"substring", SameCharNoLen},
569 {"back", AnyLogical, Rank::elemental, Optionality::optional},
570 DefaultingKIND},
571 KINDInt},
572 {"int", {{"a", AnyNumeric, Rank::elementalOrBOZ}, DefaultingKIND}, KINDInt},
573 {"int_ptr_kind", {}, DefaultInt, Rank::scalar},
574 {"ior", {{"i", OperandInt}, {"j", OperandInt, Rank::elementalOrBOZ}},
575 OperandInt},
576 {"ior", {{"i", BOZ}, {"j", SameInt}}, SameInt},
577 {"ishft", {{"i", SameInt}, {"shift", AnyInt}}, SameInt},
578 {"ishftc",
579 {{"i", SameInt}, {"shift", AnyInt},
580 {"size", AnyInt, Rank::elemental, Optionality::optional}},
581 SameInt},
582 {"isnan", {{"a", AnyFloating}}, DefaultLogical},
583 {"is_contiguous", {{"array", Addressable, Rank::anyOrAssumedRank}},
584 DefaultLogical, Rank::elemental, IntrinsicClass::inquiryFunction},
585 {"is_iostat_end", {{"i", AnyInt}}, DefaultLogical},
586 {"is_iostat_eor", {{"i", AnyInt}}, DefaultLogical},
587 {"izext", {{"i", AnyInt}}, TypePattern{IntType, KindCode::exactKind, 2}},
588 {"jzext", {{"i", AnyInt}}, DefaultInt},
589 {"kind",
590 {{"x", AnyIntrinsic, Rank::elemental, Optionality::required,
591 common::Intent::In, {ArgFlag::canBeMoldNull}}},
592 DefaultInt, Rank::elemental, IntrinsicClass::inquiryFunction},
593 {"lbound",
594 {{"array", AnyData, Rank::anyOrAssumedRank}, RequiredDIM,
595 SizeDefaultKIND},
596 KINDInt, Rank::scalar, IntrinsicClass::inquiryFunction},
597 {"lbound", {{"array", AnyData, Rank::arrayOrAssumedRank}, SizeDefaultKIND},
598 KINDInt, Rank::vector, IntrinsicClass::inquiryFunction},
599 {"lcobound",
600 {{"coarray", AnyData, Rank::coarray}, OptionalDIM, SizeDefaultKIND},
601 KINDInt, Rank::scalarIfDim, IntrinsicClass::inquiryFunction},
602 {"leadz", {{"i", AnyInt}}, DefaultInt},
603 {"len",
604 {{"string", AnyChar, Rank::anyOrAssumedRank, Optionality::required,
605 common::Intent::In, {ArgFlag::canBeMoldNull}},
606 DefaultingKIND},
607 KINDInt, Rank::scalar, IntrinsicClass::inquiryFunction},
608 {"len_trim", {{"string", AnyChar}, DefaultingKIND}, KINDInt},
609 {"lge", {{"string_a", SameCharNoLen}, {"string_b", SameCharNoLen}},
610 DefaultLogical},
611 {"lgt", {{"string_a", SameCharNoLen}, {"string_b", SameCharNoLen}},
612 DefaultLogical},
613 {"lle", {{"string_a", SameCharNoLen}, {"string_b", SameCharNoLen}},
614 DefaultLogical},
615 {"llt", {{"string_a", SameCharNoLen}, {"string_b", SameCharNoLen}},
616 DefaultLogical},
617 {"loc", {{"x", Addressable, Rank::anyOrAssumedRank}}, SubscriptInt,
618 Rank::scalar},
619 {"log", {{"x", SameFloating}}, SameFloating},
620 {"log10", {{"x", SameReal}}, SameReal},
621 {"logical", {{"l", AnyLogical}, DefaultingKIND}, KINDLogical},
622 {"log_gamma", {{"x", SameReal}}, SameReal},
623 {"matmul",
624 {{"matrix_a", AnyLogical, Rank::vector},
625 {"matrix_b", AnyLogical, Rank::matrix}},
626 ResultLogical, Rank::vector, IntrinsicClass::transformationalFunction},
627 {"matmul",
628 {{"matrix_a", AnyLogical, Rank::matrix},
629 {"matrix_b", AnyLogical, Rank::vector}},
630 ResultLogical, Rank::vector, IntrinsicClass::transformationalFunction},
631 {"matmul",
632 {{"matrix_a", AnyLogical, Rank::matrix},
633 {"matrix_b", AnyLogical, Rank::matrix}},
634 ResultLogical, Rank::matrix, IntrinsicClass::transformationalFunction},
635 {"matmul",
636 {{"matrix_a", AnyNumeric, Rank::vector},
637 {"matrix_b", AnyNumeric, Rank::matrix}},
638 ResultNumeric, Rank::vector, IntrinsicClass::transformationalFunction},
639 {"matmul",
640 {{"matrix_a", AnyNumeric, Rank::matrix},
641 {"matrix_b", AnyNumeric, Rank::vector}},
642 ResultNumeric, Rank::vector, IntrinsicClass::transformationalFunction},
643 {"matmul",
644 {{"matrix_a", AnyNumeric, Rank::matrix},
645 {"matrix_b", AnyNumeric, Rank::matrix}},
646 ResultNumeric, Rank::matrix, IntrinsicClass::transformationalFunction},
647 {"maskl", {{"i", AnyInt}, DefaultingKIND}, KINDInt},
648 {"maskr", {{"i", AnyInt}, DefaultingKIND}, KINDInt},
649 {"max",
650 {{"a1", OperandIntOrReal}, {"a2", OperandIntOrReal},
651 {"a3", OperandIntOrReal, Rank::elemental, Optionality::repeats}},
652 OperandIntOrReal},
653 {"max",
654 {{"a1", SameCharNoLen}, {"a2", SameCharNoLen},
655 {"a3", SameCharNoLen, Rank::elemental, Optionality::repeats}},
656 SameCharNoLen},
657 {"maxexponent",
658 {{"x", AnyReal, Rank::anyOrAssumedRank, Optionality::required,
659 common::Intent::In, {ArgFlag::canBeMoldNull}}},
660 DefaultInt, Rank::scalar, IntrinsicClass::inquiryFunction},
661 {"maxloc",
662 {{"array", AnyRelatable, Rank::array}, RequiredDIM, OptionalMASK,
663 SizeDefaultKIND,
664 {"back", AnyLogical, Rank::scalar, Optionality::optional}},
665 KINDInt, Rank::locReduced, IntrinsicClass::transformationalFunction},
666 {"maxloc",
667 {{"array", AnyRelatable, Rank::array}, MissingDIM, OptionalMASK,
668 SizeDefaultKIND,
669 {"back", AnyLogical, Rank::scalar, Optionality::optional}},
670 KINDInt, Rank::locReduced, IntrinsicClass::transformationalFunction},
671 {"maxval",
672 {{"array", SameRelatable, Rank::array}, RequiredDIM, OptionalMASK},
673 SameRelatable, Rank::dimReduced,
674 IntrinsicClass::transformationalFunction},
675 {"maxval",
676 {{"array", SameRelatable, Rank::array}, MissingDIM, OptionalMASK},
677 SameRelatable, Rank::scalar, IntrinsicClass::transformationalFunction},
678 {"merge",
679 {{"tsource", SameType}, {"fsource", SameType}, {"mask", AnyLogical}},
680 SameType},
681 {"merge_bits",
682 {{"i", SameInt}, {"j", SameInt, Rank::elementalOrBOZ},
683 {"mask", SameInt, Rank::elementalOrBOZ}},
684 SameInt},
685 {"merge_bits",
686 {{"i", BOZ}, {"j", SameInt}, {"mask", SameInt, Rank::elementalOrBOZ}},
687 SameInt},
688 {"min",
689 {{"a1", OperandIntOrReal}, {"a2", OperandIntOrReal},
690 {"a3", OperandIntOrReal, Rank::elemental, Optionality::repeats}},
691 OperandIntOrReal},
692 {"min",
693 {{"a1", SameCharNoLen}, {"a2", SameCharNoLen},
694 {"a3", SameCharNoLen, Rank::elemental, Optionality::repeats}},
695 SameCharNoLen},
696 {"minexponent",
697 {{"x", AnyReal, Rank::anyOrAssumedRank, Optionality::required,
698 common::Intent::In, {ArgFlag::canBeMoldNull}}},
699 DefaultInt, Rank::scalar, IntrinsicClass::inquiryFunction},
700 {"minloc",
701 {{"array", AnyRelatable, Rank::array}, RequiredDIM, OptionalMASK,
702 SizeDefaultKIND,
703 {"back", AnyLogical, Rank::scalar, Optionality::optional}},
704 KINDInt, Rank::locReduced, IntrinsicClass::transformationalFunction},
705 {"minloc",
706 {{"array", AnyRelatable, Rank::array}, MissingDIM, OptionalMASK,
707 SizeDefaultKIND,
708 {"back", AnyLogical, Rank::scalar, Optionality::optional}},
709 KINDInt, Rank::locReduced, IntrinsicClass::transformationalFunction},
710 {"minval",
711 {{"array", SameRelatable, Rank::array}, RequiredDIM, OptionalMASK},
712 SameRelatable, Rank::dimReduced,
713 IntrinsicClass::transformationalFunction},
714 {"minval",
715 {{"array", SameRelatable, Rank::array}, MissingDIM, OptionalMASK},
716 SameRelatable, Rank::scalar, IntrinsicClass::transformationalFunction},
717 {"mod", {{"a", OperandIntOrReal}, {"p", OperandIntOrReal}},
718 OperandIntOrReal},
719 {"modulo", {{"a", OperandIntOrReal}, {"p", OperandIntOrReal}},
720 OperandIntOrReal},
721 {"nearest", {{"x", SameReal}, {"s", AnyReal}}, SameReal},
722 {"new_line",
723 {{"a", SameCharNoLen, Rank::anyOrAssumedRank, Optionality::required,
724 common::Intent::In, {ArgFlag::canBeMoldNull}}},
725 SameCharNoLen, Rank::scalar, IntrinsicClass::inquiryFunction},
726 {"nint", {{"a", AnyReal}, DefaultingKIND}, KINDInt},
727 {"norm2", {{"x", SameReal, Rank::array}, RequiredDIM}, SameReal,
728 Rank::dimReduced, IntrinsicClass::transformationalFunction},
729 {"norm2", {{"x", SameReal, Rank::array}, MissingDIM}, SameReal,
730 Rank::scalar, IntrinsicClass::transformationalFunction},
731 {"not", {{"i", SameInt}}, SameInt},
732 // NULL() is a special case handled in Probe() below
733 {"num_images", {}, DefaultInt, Rank::scalar,
734 IntrinsicClass::transformationalFunction},
735 {"num_images", {{"team", TeamType, Rank::scalar}}, DefaultInt, Rank::scalar,
736 IntrinsicClass::transformationalFunction},
737 {"num_images", {{"team_number", AnyInt, Rank::scalar}}, DefaultInt,
738 Rank::scalar, IntrinsicClass::transformationalFunction},
739 {"out_of_range",
740 {{"x", AnyIntOrReal}, {"mold", AnyIntOrReal, Rank::scalar}},
741 DefaultLogical},
742 {"out_of_range",
743 {{"x", AnyReal}, {"mold", AnyInt, Rank::scalar},
744 {"round", AnyLogical, Rank::scalar, Optionality::optional}},
745 DefaultLogical},
746 {"out_of_range", {{"x", AnyReal}, {"mold", AnyReal}}, DefaultLogical},
747 {"pack",
748 {{"array", SameType, Rank::array},
749 {"mask", AnyLogical, Rank::conformable},
750 {"vector", SameType, Rank::vector, Optionality::optional}},
751 SameType, Rank::vector, IntrinsicClass::transformationalFunction},
752 {"parity", {{"mask", SameLogical, Rank::array}, OptionalDIM}, SameLogical,
753 Rank::dimReduced, IntrinsicClass::transformationalFunction},
754 {"popcnt", {{"i", AnyInt}}, DefaultInt},
755 {"poppar", {{"i", AnyInt}}, DefaultInt},
756 {"product",
757 {{"array", SameNumeric, Rank::array}, RequiredDIM, OptionalMASK},
758 SameNumeric, Rank::dimReduced,
759 IntrinsicClass::transformationalFunction},
760 {"product", {{"array", SameNumeric, Rank::array}, MissingDIM, OptionalMASK},
761 SameNumeric, Rank::scalar, IntrinsicClass::transformationalFunction},
762 {"precision",
763 {{"x", AnyFloating, Rank::anyOrAssumedRank, Optionality::required,
764 common::Intent::In, {ArgFlag::canBeMoldNull}}},
765 DefaultInt, Rank::scalar, IntrinsicClass::inquiryFunction},
766 {"present", {{"a", Addressable, Rank::anyOrAssumedRank}}, DefaultLogical,
767 Rank::scalar, IntrinsicClass::inquiryFunction},
768 {"radix",
769 {{"x", AnyIntOrReal, Rank::anyOrAssumedRank, Optionality::required,
770 common::Intent::In, {ArgFlag::canBeMoldNull}}},
771 DefaultInt, Rank::scalar, IntrinsicClass::inquiryFunction},
772 {"range",
773 {{"x", AnyNumeric, Rank::anyOrAssumedRank, Optionality::required,
774 common::Intent::In, {ArgFlag::canBeMoldNull}}},
775 DefaultInt, Rank::scalar, IntrinsicClass::inquiryFunction},
776 {"rank",
777 {{"a", AnyData, Rank::anyOrAssumedRank, Optionality::required,
778 common::Intent::In, {ArgFlag::canBeMoldNull}}},
779 DefaultInt, Rank::scalar, IntrinsicClass::inquiryFunction},
780 {"real", {{"a", SameComplex, Rank::elemental}},
781 SameReal}, // 16.9.160(4)(ii)
782 {"real", {{"a", AnyNumeric, Rank::elementalOrBOZ}, DefaultingKIND},
783 KINDReal},
784 {"reduce",
785 {{"array", SameType, Rank::array},
786 {"operation", SameType, Rank::reduceOperation}, RequiredDIM,
787 OptionalMASK,
788 {"identity", SameType, Rank::scalar, Optionality::optional},
789 {"ordered", AnyLogical, Rank::scalar, Optionality::optional}},
790 SameType, Rank::dimReduced, IntrinsicClass::transformationalFunction},
791 {"reduce",
792 {{"array", SameType, Rank::array},
793 {"operation", SameType, Rank::reduceOperation}, MissingDIM,
794 OptionalMASK,
795 {"identity", SameType, Rank::scalar, Optionality::optional},
796 {"ordered", AnyLogical, Rank::scalar, Optionality::optional}},
797 SameType, Rank::scalar, IntrinsicClass::transformationalFunction},
798 {"rename",
799 {{"path1", DefaultChar, Rank::scalar},
800 {"path2", DefaultChar, Rank::scalar}},
801 DefaultInt, Rank::scalar},
802 {"repeat",
803 {{"string", SameCharNoLen, Rank::scalar},
804 {"ncopies", AnyInt, Rank::scalar}},
805 SameCharNoLen, Rank::scalar, IntrinsicClass::transformationalFunction},
806 {"reshape",
807 {{"source", SameType, Rank::array}, {"shape", AnyInt, Rank::shape},
808 {"pad", SameType, Rank::array, Optionality::optional},
809 {"order", AnyInt, Rank::vector, Optionality::optional}},
810 SameType, Rank::shaped, IntrinsicClass::transformationalFunction},
811 {"rrspacing", {{"x", SameReal}}, SameReal},
812 {"same_type_as",
813 {{"a", ExtensibleDerived, Rank::anyOrAssumedRank, Optionality::required,
814 common::Intent::In, {ArgFlag::canBeMoldNull}},
815 {"b", ExtensibleDerived, Rank::anyOrAssumedRank,
816 Optionality::required, common::Intent::In,
817 {ArgFlag::canBeMoldNull}}},
818 DefaultLogical, Rank::scalar, IntrinsicClass::inquiryFunction},
819 {"scale", {{"x", SameReal}, {"i", AnyInt}}, SameReal}, // == IEEE_SCALB()
820 {"scan",
821 {{"string", SameCharNoLen}, {"set", SameCharNoLen},
822 {"back", AnyLogical, Rank::elemental, Optionality::optional},
823 DefaultingKIND},
824 KINDInt},
825 {"second", {}, DefaultReal, Rank::scalar},
826 {"selected_char_kind", {{"name", DefaultChar, Rank::scalar}}, DefaultInt,
827 Rank::scalar, IntrinsicClass::transformationalFunction},
828 {"selected_int_kind", {{"r", AnyInt, Rank::scalar}}, DefaultInt,
829 Rank::scalar, IntrinsicClass::transformationalFunction},
830 {"selected_logical_kind", {{"bits", AnyInt, Rank::scalar}}, DefaultInt,
831 Rank::scalar, IntrinsicClass::transformationalFunction},
832 {"selected_real_kind",
833 {{"p", AnyInt, Rank::scalar},
834 {"r", AnyInt, Rank::scalar, Optionality::optional},
835 {"radix", AnyInt, Rank::scalar, Optionality::optional}},
836 DefaultInt, Rank::scalar, IntrinsicClass::transformationalFunction},
837 {"selected_real_kind",
838 {{"p", AnyInt, Rank::scalar, Optionality::optional},
839 {"r", AnyInt, Rank::scalar},
840 {"radix", AnyInt, Rank::scalar, Optionality::optional}},
841 DefaultInt, Rank::scalar, IntrinsicClass::transformationalFunction},
842 {"selected_real_kind",
843 {{"p", AnyInt, Rank::scalar, Optionality::optional},
844 {"r", AnyInt, Rank::scalar, Optionality::optional},
845 {"radix", AnyInt, Rank::scalar}},
846 DefaultInt, Rank::scalar, IntrinsicClass::transformationalFunction},
847 {"set_exponent", {{"x", SameReal}, {"i", AnyInt}}, SameReal},
848 {"shape", {{"source", AnyData, Rank::anyOrAssumedRank}, SizeDefaultKIND},
849 KINDInt, Rank::vector, IntrinsicClass::inquiryFunction},
850 {"shifta", {{"i", SameInt}, {"shift", AnyInt}}, SameInt},
851 {"shiftl", {{"i", SameInt}, {"shift", AnyInt}}, SameInt},
852 {"shiftr", {{"i", SameInt}, {"shift", AnyInt}}, SameInt},
853 {"sign", {{"a", SameInt}, {"b", AnyInt}}, SameInt},
854 {"sign", {{"a", SameReal}, {"b", AnyReal}}, SameReal},
855 {"sin", {{"x", SameFloating}}, SameFloating},
856 {"sind", {{"x", SameFloating}}, SameFloating},
857 {"sinh", {{"x", SameFloating}}, SameFloating},
858 {"size",
859 {{"array", AnyData, Rank::arrayOrAssumedRank},
860 OptionalDIM, // unless array is assumed-size
861 SizeDefaultKIND},
862 KINDInt, Rank::scalar, IntrinsicClass::inquiryFunction},
863 {"sizeof", {{"a", AnyData, Rank::anyOrAssumedRank}}, SubscriptInt,
864 Rank::scalar, IntrinsicClass::inquiryFunction},
865 {"spacing", {{"x", SameReal}}, SameReal},
866 {"spread",
867 {{"source", SameType, Rank::known, Optionality::required,
868 common::Intent::In, {ArgFlag::notAssumedSize}},
869 RequiredDIM, {"ncopies", AnyInt, Rank::scalar}},
870 SameType, Rank::rankPlus1, IntrinsicClass::transformationalFunction},
871 {"sqrt", {{"x", SameFloating}}, SameFloating},
872 {"stopped_images", {OptionalTEAM, SizeDefaultKIND}, KINDInt, Rank::vector,
873 IntrinsicClass::transformationalFunction},
874 {"storage_size",
875 {{"a", AnyData, Rank::anyOrAssumedRank, Optionality::required,
876 common::Intent::In, {ArgFlag::canBeMoldNull}},
877 SizeDefaultKIND},
878 KINDInt, Rank::scalar, IntrinsicClass::inquiryFunction},
879 {"sum", {{"array", SameNumeric, Rank::array}, RequiredDIM, OptionalMASK},
880 SameNumeric, Rank::dimReduced,
881 IntrinsicClass::transformationalFunction},
882 {"sum", {{"array", SameNumeric, Rank::array}, MissingDIM, OptionalMASK},
883 SameNumeric, Rank::scalar, IntrinsicClass::transformationalFunction},
884 {"tan", {{"x", SameFloating}}, SameFloating},
885 {"tand", {{"x", SameFloating}}, SameFloating},
886 {"tanh", {{"x", SameFloating}}, SameFloating},
887 {"team_number", {OptionalTEAM}, DefaultInt, Rank::scalar,
888 IntrinsicClass::transformationalFunction},
889 {"this_image",
890 {{"coarray", AnyData, Rank::coarray}, RequiredDIM, OptionalTEAM},
891 DefaultInt, Rank::scalar, IntrinsicClass::transformationalFunction},
892 {"this_image", {{"coarray", AnyData, Rank::coarray}, OptionalTEAM},
893 DefaultInt, Rank::scalar, IntrinsicClass::transformationalFunction},
894 {"this_image", {OptionalTEAM}, DefaultInt, Rank::scalar,
895 IntrinsicClass::transformationalFunction},
896 {"tiny",
897 {{"x", SameReal, Rank::anyOrAssumedRank, Optionality::required,
898 common::Intent::In, {ArgFlag::canBeMoldNull}}},
899 SameReal, Rank::scalar, IntrinsicClass::inquiryFunction},
900 {"trailz", {{"i", AnyInt}}, DefaultInt},
901 {"transfer",
902 {{"source", AnyData, Rank::known}, {"mold", SameType, Rank::scalar}},
903 SameType, Rank::scalar, IntrinsicClass::transformationalFunction},
904 {"transfer",
905 {{"source", AnyData, Rank::known}, {"mold", SameType, Rank::array}},
906 SameType, Rank::vector, IntrinsicClass::transformationalFunction},
907 {"transfer",
908 {{"source", AnyData, Rank::anyOrAssumedRank},
909 {"mold", SameType, Rank::anyOrAssumedRank},
910 {"size", AnyInt, Rank::scalar}},
911 SameType, Rank::vector, IntrinsicClass::transformationalFunction},
912 {"transpose", {{"matrix", SameType, Rank::matrix}}, SameType, Rank::matrix,
913 IntrinsicClass::transformationalFunction},
914 {"trim", {{"string", SameCharNoLen, Rank::scalar}}, SameCharNoLen,
915 Rank::scalar, IntrinsicClass::transformationalFunction},
916 {"ubound",
917 {{"array", AnyData, Rank::anyOrAssumedRank}, RequiredDIM,
918 SizeDefaultKIND},
919 KINDInt, Rank::scalar, IntrinsicClass::inquiryFunction},
920 {"ubound", {{"array", AnyData, Rank::arrayOrAssumedRank}, SizeDefaultKIND},
921 KINDInt, Rank::vector, IntrinsicClass::inquiryFunction},
922 {"ucobound",
923 {{"coarray", AnyData, Rank::coarray}, OptionalDIM, SizeDefaultKIND},
924 KINDInt, Rank::scalarIfDim, IntrinsicClass::inquiryFunction},
925 {"unpack",
926 {{"vector", SameType, Rank::vector}, {"mask", AnyLogical, Rank::array},
927 {"field", SameType, Rank::conformable}},
928 SameType, Rank::conformable, IntrinsicClass::transformationalFunction},
929 {"verify",
930 {{"string", SameCharNoLen}, {"set", SameCharNoLen},
931 {"back", AnyLogical, Rank::elemental, Optionality::optional},
932 DefaultingKIND},
933 KINDInt},
934 {"__builtin_compiler_options", {}, DefaultChar},
935 {"__builtin_compiler_version", {}, DefaultChar},
936 {"__builtin_fma", {{"f1", SameReal}, {"f2", SameReal}, {"f3", SameReal}},
937 SameReal},
938 {"__builtin_ieee_is_nan", {{"a", AnyFloating}}, DefaultLogical},
939 {"__builtin_ieee_is_negative", {{"a", AnyFloating}}, DefaultLogical},
940 {"__builtin_ieee_is_normal", {{"a", AnyFloating}}, DefaultLogical},
941 {"__builtin_ieee_next_after", {{"x", SameReal}, {"y", AnyReal}}, SameReal},
942 {"__builtin_ieee_next_down", {{"x", SameReal}}, SameReal},
943 {"__builtin_ieee_next_up", {{"x", SameReal}}, SameReal},
944 {"__builtin_ieee_support_datatype",
945 {{"x", AnyReal, Rank::elemental, Optionality::optional}},
946 DefaultLogical},
947 {"__builtin_ieee_support_denormal",
948 {{"x", AnyReal, Rank::elemental, Optionality::optional}},
949 DefaultLogical},
950 {"__builtin_ieee_support_divide",
951 {{"x", AnyReal, Rank::elemental, Optionality::optional}},
952 DefaultLogical},
953 {"__builtin_ieee_support_flag",
954 {{"flag", IeeeFlagType, Rank::scalar},
955 {"x", AnyReal, Rank::elemental, Optionality::optional}},
956 DefaultLogical},
957 {"__builtin_ieee_support_halting", {{"flag", IeeeFlagType, Rank::scalar}},
958 DefaultLogical},
959 {"__builtin_ieee_support_inf",
960 {{"x", AnyReal, Rank::elemental, Optionality::optional}},
961 DefaultLogical},
962 {"__builtin_ieee_support_io",
963 {{"x", AnyReal, Rank::elemental, Optionality::optional}},
964 DefaultLogical},
965 {"__builtin_ieee_support_nan",
966 {{"x", AnyReal, Rank::elemental, Optionality::optional}},
967 DefaultLogical},
968 {"__builtin_ieee_support_rounding",
969 {{"round_value", IeeeRoundType, Rank::scalar},
970 {"x", AnyReal, Rank::elemental, Optionality::optional}},
971 DefaultLogical},
972 {"__builtin_ieee_support_sqrt",
973 {{"x", AnyReal, Rank::elemental, Optionality::optional}},
974 DefaultLogical},
975 {"__builtin_ieee_support_standard",
976 {{"x", AnyReal, Rank::elemental, Optionality::optional}},
977 DefaultLogical},
978 {"__builtin_ieee_support_subnormal",
979 {{"x", AnyReal, Rank::elemental, Optionality::optional}},
980 DefaultLogical},
981 {"__builtin_ieee_support_underflow_control",
982 {{"x", AnyReal, Rank::elemental, Optionality::optional}},
983 DefaultLogical},
984 {"__builtin_numeric_storage_size", {}, DefaultInt},
985 };
986
987 // TODO: Coarray intrinsic functions
988 // COSHAPE
989 // TODO: Non-standard intrinsic functions
990 // SHIFT,
991 // COMPL, EQV, NEQV, INT8, JINT, JNINT, KNINT,
992 // QCMPLX, QEXT, QFLOAT, QREAL, DNUM,
993 // INUM, JNUM, KNUM, QNUM, RNUM, RAN, RANF, ILEN,
994 // MCLOCK, SECNDS, COTAN, IBCHNG, ISHA, ISHC, ISHL, IXOR
995 // IARG, IARGC, NARGS, NUMARG, BADDRESS, IADDR, CACHESIZE,
996 // EOF, FP_CLASS, INT_PTR_KIND, MALLOC
997 // probably more (these are PGI + Intel, possibly incomplete)
998 // TODO: Optionally warn on use of non-standard intrinsics:
999 // LOC, probably others
1000 // TODO: Optionally warn on operand promotion extension
1001
1002 // Aliases for a few generic intrinsic functions for legacy
1003 // compatibility and builtins.
1004 static const std::pair<const char *, const char *> genericAlias[]{
1005 {"and", "iand"},
1006 {"getenv", "get_environment_variable"},
1007 {"imag", "aimag"},
1008 {"lshift", "shiftl"},
1009 {"or", "ior"},
1010 {"rshift", "shifta"},
1011 {"xor", "ieor"},
1012 {"__builtin_ieee_selected_real_kind", "selected_real_kind"},
1013 };
1014
1015 // The following table contains the intrinsic functions listed in
1016 // Tables 16.2 and 16.3 in Fortran 2018. The "unrestricted" functions
1017 // in Table 16.2 can be used as actual arguments, PROCEDURE() interfaces,
1018 // and procedure pointer targets.
1019 // Note that the restricted conversion functions dcmplx, dreal, float, idint,
1020 // ifix, and sngl are extended to accept any argument kind because this is a
1021 // common Fortran compilers behavior, and as far as we can tell, is safe and
1022 // useful.
1023 struct SpecificIntrinsicInterface : public IntrinsicInterface {
1024 const char *generic{nullptr};
1025 bool isRestrictedSpecific{false};
1026 // Exact actual/dummy type matching is required by default for specific
1027 // intrinsics. If useGenericAndForceResultType is set, then the probing will
1028 // also attempt to use the related generic intrinsic and to convert the result
1029 // to the specific intrinsic result type if needed. This also prevents
1030 // using the generic name so that folding can insert the conversion on the
1031 // result and not the arguments.
1032 //
1033 // This is not enabled on all specific intrinsics because an alternative
1034 // is to convert the actual arguments to the required dummy types and this is
1035 // not numerically equivalent.
1036 // e.g. IABS(INT(i, 4)) not equiv to INT(ABS(i), 4).
1037 // This is allowed for restricted min/max specific functions because
1038 // the expected behavior is clear from their definitions. A warning is though
1039 // always emitted because other compilers' behavior is not ubiquitous here and
1040 // the results in case of conversion overflow might not be equivalent.
1041 // e.g for MIN0: INT(MIN(2147483647_8, 2*2147483647_8), 4) = 2147483647_4
1042 // but: MIN(INT(2147483647_8, 4), INT(2*2147483647_8, 4)) = -2_4
1043 // xlf and ifort return the first, and pgfortran the later. f18 will return
1044 // the first because this matches more closely the MIN0 definition in
1045 // Fortran 2018 table 16.3 (although it is still an extension to allow
1046 // non default integer argument in MIN0).
1047 bool useGenericAndForceResultType{false};
1048 };
1049
1050 static const SpecificIntrinsicInterface specificIntrinsicFunction[]{
1051 {{"abs", {{"a", DefaultReal}}, DefaultReal}},
1052 {{"acos", {{"x", DefaultReal}}, DefaultReal}},
1053 {{"aimag", {{"z", DefaultComplex}}, DefaultReal}},
1054 {{"aint", {{"a", DefaultReal}}, DefaultReal}},
1055 {{"alog", {{"x", DefaultReal}}, DefaultReal}, "log"},
1056 {{"alog10", {{"x", DefaultReal}}, DefaultReal}, "log10"},
1057 {{"amax0",
1058 {{"a1", DefaultInt}, {"a2", DefaultInt},
1059 {"a3", DefaultInt, Rank::elemental, Optionality::repeats}},
1060 DefaultReal},
1061 "max", true, true},
1062 {{"amax1",
1063 {{"a1", DefaultReal}, {"a2", DefaultReal},
1064 {"a3", DefaultReal, Rank::elemental, Optionality::repeats}},
1065 DefaultReal},
1066 "max", true, true},
1067 {{"amin0",
1068 {{"a1", DefaultInt}, {"a2", DefaultInt},
1069 {"a3", DefaultInt, Rank::elemental, Optionality::repeats}},
1070 DefaultReal},
1071 "min", true, true},
1072 {{"amin1",
1073 {{"a1", DefaultReal}, {"a2", DefaultReal},
1074 {"a3", DefaultReal, Rank::elemental, Optionality::repeats}},
1075 DefaultReal},
1076 "min", true, true},
1077 {{"amod", {{"a", DefaultReal}, {"p", DefaultReal}}, DefaultReal}, "mod"},
1078 {{"anint", {{"a", DefaultReal}}, DefaultReal}},
1079 {{"asin", {{"x", DefaultReal}}, DefaultReal}},
1080 {{"atan", {{"x", DefaultReal}}, DefaultReal}},
1081 {{"atan2", {{"y", DefaultReal}, {"x", DefaultReal}}, DefaultReal}},
1082 {{"babs", {{"a", TypePattern{IntType, KindCode::exactKind, 1}}},
1083 TypePattern{IntType, KindCode::exactKind, 1}},
1084 "abs"},
1085 {{"cabs", {{"a", DefaultComplex}}, DefaultReal}, "abs"},
1086 {{"ccos", {{"x", DefaultComplex}}, DefaultComplex}, "cos"},
1087 {{"cdabs", {{"a", DoublePrecisionComplex}}, DoublePrecision}, "abs"},
1088 {{"cdcos", {{"x", DoublePrecisionComplex}}, DoublePrecisionComplex}, "cos"},
1089 {{"cdexp", {{"x", DoublePrecisionComplex}}, DoublePrecisionComplex}, "exp"},
1090 {{"cdlog", {{"x", DoublePrecisionComplex}}, DoublePrecisionComplex}, "log"},
1091 {{"cdsin", {{"x", DoublePrecisionComplex}}, DoublePrecisionComplex}, "sin"},
1092 {{"cdsqrt", {{"x", DoublePrecisionComplex}}, DoublePrecisionComplex},
1093 "sqrt"},
1094 {{"cexp", {{"x", DefaultComplex}}, DefaultComplex}, "exp"},
1095 {{"clog", {{"x", DefaultComplex}}, DefaultComplex}, "log"},
1096 {{"conjg", {{"z", DefaultComplex}}, DefaultComplex}},
1097 {{"cos", {{"x", DefaultReal}}, DefaultReal}},
1098 {{"cosh", {{"x", DefaultReal}}, DefaultReal}},
1099 {{"csin", {{"x", DefaultComplex}}, DefaultComplex}, "sin"},
1100 {{"csqrt", {{"x", DefaultComplex}}, DefaultComplex}, "sqrt"},
1101 {{"ctan", {{"x", DefaultComplex}}, DefaultComplex}, "tan"},
1102 {{"dabs", {{"a", DoublePrecision}}, DoublePrecision}, "abs"},
1103 {{"dacos", {{"x", DoublePrecision}}, DoublePrecision}, "acos"},
1104 {{"dasin", {{"x", DoublePrecision}}, DoublePrecision}, "asin"},
1105 {{"datan", {{"x", DoublePrecision}}, DoublePrecision}, "atan"},
1106 {{"datan2", {{"y", DoublePrecision}, {"x", DoublePrecision}},
1107 DoublePrecision},
1108 "atan2"},
1109 {{"dcmplx", {{"x", AnyComplex}}, DoublePrecisionComplex}, "cmplx", true},
1110 {{"dcmplx",
1111 {{"x", AnyIntOrReal, Rank::elementalOrBOZ},
1112 {"y", AnyIntOrReal, Rank::elementalOrBOZ, Optionality::optional}},
1113 DoublePrecisionComplex},
1114 "cmplx", true},
1115 {{"dconjg", {{"z", DoublePrecisionComplex}}, DoublePrecisionComplex},
1116 "conjg"},
1117 {{"dcos", {{"x", DoublePrecision}}, DoublePrecision}, "cos"},
1118 {{"dcosh", {{"x", DoublePrecision}}, DoublePrecision}, "cosh"},
1119 {{"ddim", {{"x", DoublePrecision}, {"y", DoublePrecision}},
1120 DoublePrecision},
1121 "dim"},
1122 {{"derf", {{"x", DoublePrecision}}, DoublePrecision}, "erf"},
1123 {{"dexp", {{"x", DoublePrecision}}, DoublePrecision}, "exp"},
1124 {{"dfloat", {{"a", AnyInt}}, DoublePrecision}, "real", true},
1125 {{"dim", {{"x", DefaultReal}, {"y", DefaultReal}}, DefaultReal}},
1126 {{"dimag", {{"z", DoublePrecisionComplex}}, DoublePrecision}, "aimag"},
1127 {{"dint", {{"a", DoublePrecision}}, DoublePrecision}, "aint"},
1128 {{"dlog", {{"x", DoublePrecision}}, DoublePrecision}, "log"},
1129 {{"dlog10", {{"x", DoublePrecision}}, DoublePrecision}, "log10"},
1130 {{"dmax1",
1131 {{"a1", DoublePrecision}, {"a2", DoublePrecision},
1132 {"a3", DoublePrecision, Rank::elemental, Optionality::repeats}},
1133 DoublePrecision},
1134 "max", true, true},
1135 {{"dmin1",
1136 {{"a1", DoublePrecision}, {"a2", DoublePrecision},
1137 {"a3", DoublePrecision, Rank::elemental, Optionality::repeats}},
1138 DoublePrecision},
1139 "min", true, true},
1140 {{"dmod", {{"a", DoublePrecision}, {"p", DoublePrecision}},
1141 DoublePrecision},
1142 "mod"},
1143 {{"dnint", {{"a", DoublePrecision}}, DoublePrecision}, "anint"},
1144 {{"dprod", {{"x", DefaultReal}, {"y", DefaultReal}}, DoublePrecision}},
1145 {{"dreal", {{"a", AnyComplex}}, DoublePrecision}, "real", true},
1146 {{"dsign", {{"a", DoublePrecision}, {"b", DoublePrecision}},
1147 DoublePrecision},
1148 "sign"},
1149 {{"dsin", {{"x", DoublePrecision}}, DoublePrecision}, "sin"},
1150 {{"dsinh", {{"x", DoublePrecision}}, DoublePrecision}, "sinh"},
1151 {{"dsqrt", {{"x", DoublePrecision}}, DoublePrecision}, "sqrt"},
1152 {{"dtan", {{"x", DoublePrecision}}, DoublePrecision}, "tan"},
1153 {{"dtanh", {{"x", DoublePrecision}}, DoublePrecision}, "tanh"},
1154 {{"exp", {{"x", DefaultReal}}, DefaultReal}},
1155 {{"float", {{"a", AnyInt}}, DefaultReal}, "real", true},
1156 {{"iabs", {{"a", DefaultInt}}, DefaultInt}, "abs"},
1157 {{"idim", {{"x", DefaultInt}, {"y", DefaultInt}}, DefaultInt}, "dim"},
1158 {{"idint", {{"a", AnyReal}}, DefaultInt}, "int", true},
1159 {{"idnint", {{"a", DoublePrecision}}, DefaultInt}, "nint"},
1160 {{"ifix", {{"a", AnyReal}}, DefaultInt}, "int", true},
1161 {{"iiabs", {{"a", TypePattern{IntType, KindCode::exactKind, 2}}},
1162 TypePattern{IntType, KindCode::exactKind, 2}},
1163 "abs"},
1164 // The definition of the unrestricted specific intrinsic function INDEX
1165 // in F'77 and F'90 has only two arguments; later standards omit the
1166 // argument information for all unrestricted specific intrinsic
1167 // procedures. No compiler supports an implementation that allows
1168 // INDEX with BACK= to work when associated as an actual procedure or
1169 // procedure pointer target.
1170 {{"index", {{"string", DefaultChar}, {"substring", DefaultChar}},
1171 DefaultInt}},
1172 {{"isign", {{"a", DefaultInt}, {"b", DefaultInt}}, DefaultInt}, "sign"},
1173 {{"jiabs", {{"a", TypePattern{IntType, KindCode::exactKind, 4}}},
1174 TypePattern{IntType, KindCode::exactKind, 4}},
1175 "abs"},
1176 {{"kiabs", {{"a", TypePattern{IntType, KindCode::exactKind, 8}}},
1177 TypePattern{IntType, KindCode::exactKind, 8}},
1178 "abs"},
1179 {{"kidnnt", {{"a", DoublePrecision}},
1180 TypePattern{IntType, KindCode::exactKind, 8}},
1181 "nint"},
1182 {{"knint", {{"a", DefaultReal}},
1183 TypePattern{IntType, KindCode::exactKind, 8}},
1184 "nint"},
1185 {{"len", {{"string", DefaultChar, Rank::anyOrAssumedRank}}, DefaultInt,
1186 Rank::scalar, IntrinsicClass::inquiryFunction}},
1187 {{"lge", {{"string_a", DefaultChar}, {"string_b", DefaultChar}},
1188 DefaultLogical},
1189 "lge", true},
1190 {{"lgt", {{"string_a", DefaultChar}, {"string_b", DefaultChar}},
1191 DefaultLogical},
1192 "lgt", true},
1193 {{"lle", {{"string_a", DefaultChar}, {"string_b", DefaultChar}},
1194 DefaultLogical},
1195 "lle", true},
1196 {{"llt", {{"string_a", DefaultChar}, {"string_b", DefaultChar}},
1197 DefaultLogical},
1198 "llt", true},
1199 {{"log", {{"x", DefaultReal}}, DefaultReal}},
1200 {{"log10", {{"x", DefaultReal}}, DefaultReal}},
1201 {{"max0",
1202 {{"a1", DefaultInt}, {"a2", DefaultInt},
1203 {"a3", DefaultInt, Rank::elemental, Optionality::repeats}},
1204 DefaultInt},
1205 "max", true, true},
1206 {{"max1",
1207 {{"a1", DefaultReal}, {"a2", DefaultReal},
1208 {"a3", DefaultReal, Rank::elemental, Optionality::repeats}},
1209 DefaultInt},
1210 "max", true, true},
1211 {{"min0",
1212 {{"a1", DefaultInt}, {"a2", DefaultInt},
1213 {"a3", DefaultInt, Rank::elemental, Optionality::repeats}},
1214 DefaultInt},
1215 "min", true, true},
1216 {{"min1",
1217 {{"a1", DefaultReal}, {"a2", DefaultReal},
1218 {"a3", DefaultReal, Rank::elemental, Optionality::repeats}},
1219 DefaultInt},
1220 "min", true, true},
1221 {{"mod", {{"a", DefaultInt}, {"p", DefaultInt}}, DefaultInt}},
1222 {{"nint", {{"a", DefaultReal}}, DefaultInt}},
1223 {{"sign", {{"a", DefaultReal}, {"b", DefaultReal}}, DefaultReal}},
1224 {{"sin", {{"x", DefaultReal}}, DefaultReal}},
1225 {{"sinh", {{"x", DefaultReal}}, DefaultReal}},
1226 {{"sngl", {{"a", AnyReal}}, DefaultReal}, "real", true},
1227 {{"sqrt", {{"x", DefaultReal}}, DefaultReal}},
1228 {{"tan", {{"x", DefaultReal}}, DefaultReal}},
1229 {{"tanh", {{"x", DefaultReal}}, DefaultReal}},
1230 {{"zabs", {{"a", TypePattern{ComplexType, KindCode::exactKind, 8}}},
1231 TypePattern{RealType, KindCode::exactKind, 8}},
1232 "abs"},
1233 };
1234
1235 static const IntrinsicInterface intrinsicSubroutine[]{
1236 {"abort", {}, {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1237 {"atomic_and",
1238 {{"atom", AtomicInt, Rank::atom, Optionality::required,
1239 common::Intent::InOut},
1240 {"value", AnyInt, Rank::scalar, Optionality::required,
1241 common::Intent::In},
1242 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1243 common::Intent::Out}},
1244 {}, Rank::elemental, IntrinsicClass::atomicSubroutine},
1245 {"atomic_cas",
1246 {{"atom", SameAtom, Rank::atom, Optionality::required,
1247 common::Intent::InOut},
1248 {"old", SameAtom, Rank::scalar, Optionality::required,
1249 common::Intent::Out},
1250 {"compare", SameAtom, Rank::scalar, Optionality::required,
1251 common::Intent::In},
1252 {"new", SameAtom, Rank::scalar, Optionality::required,
1253 common::Intent::In},
1254 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1255 common::Intent::Out}},
1256 {}, Rank::elemental, IntrinsicClass::atomicSubroutine},
1257 {"atomic_define",
1258 {{"atom", AtomicIntOrLogical, Rank::atom, Optionality::required,
1259 common::Intent::Out},
1260 {"value", AnyIntOrLogical, Rank::scalar, Optionality::required,
1261 common::Intent::In},
1262 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1263 common::Intent::Out}},
1264 {}, Rank::elemental, IntrinsicClass::atomicSubroutine},
1265 {"atomic_fetch_add",
1266 {{"atom", AtomicInt, Rank::atom, Optionality::required,
1267 common::Intent::InOut},
1268 {"value", AnyInt, Rank::scalar, Optionality::required,
1269 common::Intent::In},
1270 {"old", AtomicInt, Rank::scalar, Optionality::required,
1271 common::Intent::Out},
1272 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1273 common::Intent::Out}},
1274 {}, Rank::elemental, IntrinsicClass::atomicSubroutine},
1275 {"atomic_fetch_and",
1276 {{"atom", AtomicInt, Rank::atom, Optionality::required,
1277 common::Intent::InOut},
1278 {"value", AnyInt, Rank::scalar, Optionality::required,
1279 common::Intent::In},
1280 {"old", AtomicInt, Rank::scalar, Optionality::required,
1281 common::Intent::Out},
1282 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1283 common::Intent::Out}},
1284 {}, Rank::elemental, IntrinsicClass::atomicSubroutine},
1285 {"atomic_fetch_or",
1286 {{"atom", AtomicInt, Rank::atom, Optionality::required,
1287 common::Intent::InOut},
1288 {"value", AnyInt, Rank::scalar, Optionality::required,
1289 common::Intent::In},
1290 {"old", AtomicInt, Rank::scalar, Optionality::required,
1291 common::Intent::Out},
1292 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1293 common::Intent::Out}},
1294 {}, Rank::elemental, IntrinsicClass::atomicSubroutine},
1295 {"atomic_fetch_xor",
1296 {{"atom", AtomicInt, Rank::atom, Optionality::required,
1297 common::Intent::InOut},
1298 {"value", AnyInt, Rank::scalar, Optionality::required,
1299 common::Intent::In},
1300 {"old", AtomicInt, Rank::scalar, Optionality::required,
1301 common::Intent::Out},
1302 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1303 common::Intent::Out}},
1304 {}, Rank::elemental, IntrinsicClass::atomicSubroutine},
1305 {"atomic_or",
1306 {{"atom", AtomicInt, Rank::atom, Optionality::required,
1307 common::Intent::InOut},
1308 {"value", AnyInt, Rank::scalar, Optionality::required,
1309 common::Intent::In},
1310 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1311 common::Intent::Out}},
1312 {}, Rank::elemental, IntrinsicClass::atomicSubroutine},
1313 {"atomic_ref",
1314 {{"value", AnyIntOrLogical, Rank::scalar, Optionality::required,
1315 common::Intent::Out},
1316 {"atom", AtomicIntOrLogical, Rank::atom, Optionality::required,
1317 common::Intent::In},
1318 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1319 common::Intent::Out}},
1320 {}, Rank::elemental, IntrinsicClass::atomicSubroutine},
1321 {"atomic_xor",
1322 {{"atom", AtomicInt, Rank::atom, Optionality::required,
1323 common::Intent::InOut},
1324 {"value", AnyInt, Rank::scalar, Optionality::required,
1325 common::Intent::In},
1326 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1327 common::Intent::Out}},
1328 {}, Rank::elemental, IntrinsicClass::atomicSubroutine},
1329 {"co_broadcast",
1330 {{"a", AnyData, Rank::anyOrAssumedRank, Optionality::required,
1331 common::Intent::InOut},
1332 {"source_image", AnyInt, Rank::scalar, Optionality::required,
1333 common::Intent::In},
1334 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1335 common::Intent::Out},
1336 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional,
1337 common::Intent::InOut}},
1338 {}, Rank::elemental, IntrinsicClass::collectiveSubroutine},
1339 {"co_max",
1340 {{"a", AnyIntOrRealOrChar, Rank::anyOrAssumedRank,
1341 Optionality::required, common::Intent::InOut},
1342 {"result_image", AnyInt, Rank::scalar, Optionality::optional,
1343 common::Intent::In},
1344 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1345 common::Intent::Out},
1346 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional,
1347 common::Intent::InOut}},
1348 {}, Rank::elemental, IntrinsicClass::collectiveSubroutine},
1349 {"co_min",
1350 {{"a", AnyIntOrRealOrChar, Rank::anyOrAssumedRank,
1351 Optionality::required, common::Intent::InOut},
1352 {"result_image", AnyInt, Rank::scalar, Optionality::optional,
1353 common::Intent::In},
1354 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1355 common::Intent::Out},
1356 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional,
1357 common::Intent::InOut}},
1358 {}, Rank::elemental, IntrinsicClass::collectiveSubroutine},
1359 {"co_sum",
1360 {{"a", AnyNumeric, Rank::anyOrAssumedRank, Optionality::required,
1361 common::Intent::InOut},
1362 {"result_image", AnyInt, Rank::scalar, Optionality::optional,
1363 common::Intent::In},
1364 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1365 common::Intent::Out},
1366 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional,
1367 common::Intent::InOut}},
1368 {}, Rank::elemental, IntrinsicClass::collectiveSubroutine},
1369 {"cpu_time",
1370 {{"time", AnyReal, Rank::scalar, Optionality::required,
1371 common::Intent::Out}},
1372 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1373 {"date_and_time",
1374 {{"date", DefaultChar, Rank::scalar, Optionality::optional,
1375 common::Intent::Out},
1376 {"time", DefaultChar, Rank::scalar, Optionality::optional,
1377 common::Intent::Out},
1378 {"zone", DefaultChar, Rank::scalar, Optionality::optional,
1379 common::Intent::Out},
1380 {"values", AnyInt, Rank::vector, Optionality::optional,
1381 common::Intent::Out}},
1382 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1383 {"etime",
1384 {{"values", TypePattern{RealType, KindCode::exactKind, 4}, Rank::vector,
1385 Optionality::required, common::Intent::Out},
1386 {"time", TypePattern{RealType, KindCode::exactKind, 4},
1387 Rank::scalar, Optionality::required, common::Intent::Out}},
1388 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1389 {"execute_command_line",
1390 {{"command", DefaultChar, Rank::scalar},
1391 {"wait", AnyLogical, Rank::scalar, Optionality::optional},
1392 {"exitstat",
1393 TypePattern{IntType, KindCode::greaterOrEqualToKind, 4},
1394 Rank::scalar, Optionality::optional, common::Intent::InOut},
1395 {"cmdstat", TypePattern{IntType, KindCode::greaterOrEqualToKind, 2},
1396 Rank::scalar, Optionality::optional, common::Intent::Out},
1397 {"cmdmsg", DefaultChar, Rank::scalar, Optionality::optional,
1398 common::Intent::InOut}},
1399 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1400 {"exit", {{"status", DefaultInt, Rank::scalar, Optionality::optional}}, {},
1401 Rank::elemental, IntrinsicClass::impureSubroutine},
1402 {"get_command",
1403 {{"command", DefaultChar, Rank::scalar, Optionality::optional,
1404 common::Intent::Out},
1405 {"length", AnyInt, Rank::scalar, Optionality::optional,
1406 common::Intent::Out},
1407 {"status", AnyInt, Rank::scalar, Optionality::optional,
1408 common::Intent::Out},
1409 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional,
1410 common::Intent::InOut}},
1411 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1412 {"get_command_argument",
1413 {{"number", AnyInt, Rank::scalar},
1414 {"value", DefaultChar, Rank::scalar, Optionality::optional,
1415 common::Intent::Out},
1416 {"length", AnyInt, Rank::scalar, Optionality::optional,
1417 common::Intent::Out},
1418 {"status", AnyInt, Rank::scalar, Optionality::optional,
1419 common::Intent::Out},
1420 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional,
1421 common::Intent::InOut}},
1422 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1423 {"get_environment_variable",
1424 {{"name", DefaultChar, Rank::scalar},
1425 {"value", DefaultChar, Rank::scalar, Optionality::optional,
1426 common::Intent::Out},
1427 {"length", AnyInt, Rank::scalar, Optionality::optional,
1428 common::Intent::Out},
1429 {"status", AnyInt, Rank::scalar, Optionality::optional,
1430 common::Intent::Out},
1431 {"trim_name", AnyLogical, Rank::scalar, Optionality::optional},
1432 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional,
1433 common::Intent::InOut}},
1434 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1435 {"getcwd",
1436 {{"c", DefaultChar, Rank::scalar, Optionality::required,
1437 common::Intent::Out},
1438 {"status", TypePattern{IntType, KindCode::greaterOrEqualToKind, 4},
1439 Rank::scalar, Optionality::optional, common::Intent::Out}},
1440 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1441 {"move_alloc",
1442 {{"from", SameType, Rank::known, Optionality::required,
1443 common::Intent::InOut},
1444 {"to", SameType, Rank::known, Optionality::required,
1445 common::Intent::Out},
1446 {"stat", AnyInt, Rank::scalar, Optionality::optional,
1447 common::Intent::Out},
1448 {"errmsg", DefaultChar, Rank::scalar, Optionality::optional,
1449 common::Intent::InOut}},
1450 {}, Rank::elemental, IntrinsicClass::pureSubroutine},
1451 {"mvbits",
1452 {{"from", SameInt}, {"frompos", AnyInt}, {"len", AnyInt},
1453 {"to", SameInt, Rank::elemental, Optionality::required,
1454 common::Intent::Out},
1455 {"topos", AnyInt}},
1456 {}, Rank::elemental, IntrinsicClass::elementalSubroutine}, // elemental
1457 {"random_init",
1458 {{"repeatable", AnyLogical, Rank::scalar},
1459 {"image_distinct", AnyLogical, Rank::scalar}},
1460 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1461 {"random_number",
1462 {{"harvest", AnyReal, Rank::known, Optionality::required,
1463 common::Intent::Out, {ArgFlag::notAssumedSize}}},
1464 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1465 {"random_seed",
1466 {{"size", DefaultInt, Rank::scalar, Optionality::optional,
1467 common::Intent::Out},
1468 {"put", DefaultInt, Rank::vector, Optionality::optional},
1469 {"get", DefaultInt, Rank::vector, Optionality::optional,
1470 common::Intent::Out}},
1471 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1472 {"rename",
1473 {{"path1", DefaultChar, Rank::scalar},
1474 {"path2", DefaultChar, Rank::scalar},
1475 {"status", DefaultInt, Rank::scalar, Optionality::optional,
1476 common::Intent::Out}},
1477 {}, Rank::scalar, IntrinsicClass::impureSubroutine},
1478 {"second", {{"time", DefaultReal, Rank::scalar}}, {}, Rank::scalar,
1479 IntrinsicClass::impureSubroutine},
1480 {"system",
1481 {{"command", DefaultChar, Rank::scalar},
1482 {"exitstat", DefaultInt, Rank::scalar, Optionality::optional,
1483 common::Intent::Out}},
1484 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1485 {"system_clock",
1486 {{"count", AnyInt, Rank::scalar, Optionality::optional,
1487 common::Intent::Out},
1488 {"count_rate", AnyIntOrReal, Rank::scalar, Optionality::optional,
1489 common::Intent::Out},
1490 {"count_max", AnyInt, Rank::scalar, Optionality::optional,
1491 common::Intent::Out}},
1492 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1493 {"signal",
1494 {{"number", AnyInt, Rank::scalar, Optionality::required,
1495 common::Intent::In},
1496 // note: any pointer also accepts AnyInt
1497 {"handler", AnyPointer, Rank::scalar, Optionality::required,
1498 common::Intent::In},
1499 {"status", AnyInt, Rank::scalar, Optionality::optional,
1500 common::Intent::Out}},
1501 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1502 {"sleep",
1503 {{"seconds", AnyInt, Rank::scalar, Optionality::required,
1504 common::Intent::In}},
1505 {}, Rank::elemental, IntrinsicClass::impureSubroutine},
1506 };
1507
1508 // TODO: Intrinsic subroutine EVENT_QUERY
1509 // TODO: Atomic intrinsic subroutines: ATOMIC_ADD
1510 // TODO: Collective intrinsic subroutines: co_reduce
1511
1512 // Finds a built-in derived type and returns it as a DynamicType.
1513 static DynamicType GetBuiltinDerivedType(
1514 const semantics::Scope *builtinsScope, const char *which) {
1515 if (!builtinsScope) {
1516 common::die("INTERNAL: The __fortran_builtins module was not found, and "
1517 "the type '%s' was required",
1518 which);
1519 }
1520 auto iter{
1521 builtinsScope->find(semantics::SourceName{which, std::strlen(which)})};
1522 if (iter == builtinsScope->cend()) {
1523 // keep the string all together
1524 // clang-format off
1525 common::die(
1526 "INTERNAL: The __fortran_builtins module does not define the type '%s'",
1527 which);
1528 // clang-format on
1529 }
1530 const semantics::Symbol &symbol{*iter->second};
1531 const semantics::Scope &scope{DEREF(symbol.scope())};
1532 const semantics::DerivedTypeSpec &derived{DEREF(scope.derivedTypeSpec())};
1533 return DynamicType{derived};
1534 }
1535
1536 static std::int64_t GetBuiltinKind(
1537 const semantics::Scope *builtinsScope, const char *which) {
1538 if (!builtinsScope) {
1539 common::die("INTERNAL: The __fortran_builtins module was not found, and "
1540 "the kind '%s' was required",
1541 which);
1542 }
1543 auto iter{
1544 builtinsScope->find(semantics::SourceName{which, std::strlen(which)})};
1545 if (iter == builtinsScope->cend()) {
1546 common::die(
1547 "INTERNAL: The __fortran_builtins module does not define the kind '%s'",
1548 which);
1549 }
1550 const semantics::Symbol &symbol{*iter->second};
1551 const auto &details{
1552 DEREF(symbol.detailsIf<semantics::ObjectEntityDetails>())};
1553 if (const auto kind{ToInt64(details.init())}) {
1554 return *kind;
1555 } else {
1556 common::die(
1557 "INTERNAL: The __fortran_builtins module does not define the kind '%s'",
1558 which);
1559 return -1;
1560 }
1561 }
1562
1563 // Ensure that the keywords of arguments to MAX/MIN and their variants
1564 // are of the form A123 with no duplicates or leading zeroes.
1565 static bool CheckMaxMinArgument(parser::CharBlock keyword,
1566 std::set<parser::CharBlock> &set, const char *intrinsicName,
1567 parser::ContextualMessages &messages) {
1568 std::size_t j{1};
1569 for (; j < keyword.size(); ++j) {
1570 char ch{(keyword)[j]};
1571 if (ch < (j == 1 ? '1' : '0') || ch > '9') {
1572 break;
1573 }
1574 }
1575 if (keyword.size() < 2 || (keyword)[0] != 'a' || j < keyword.size()) {
1576 messages.Say(keyword,
1577 "argument keyword '%s=' is not known in call to '%s'"_err_en_US,
1578 keyword, intrinsicName);
1579 return false;
1580 }
1581 if (!set.insert(keyword).second) {
1582 messages.Say(keyword,
1583 "argument keyword '%s=' was repeated in call to '%s'"_err_en_US,
1584 keyword, intrinsicName);
1585 return false;
1586 }
1587 return true;
1588 }
1589
1590 // Validate the keyword, if any, and ensure that A1 and A2 are always placed in
1591 // first and second position in actualForDummy. A1 and A2 are special since they
1592 // are not optional. The rest of the arguments are not sorted, there are no
1593 // differences between them.
1594 static bool CheckAndPushMinMaxArgument(ActualArgument &arg,
1595 std::vector<ActualArgument *> &actualForDummy,
1596 std::set<parser::CharBlock> &set, const char *intrinsicName,
1597 parser::ContextualMessages &messages) {
1598 if (std::optional<parser::CharBlock> keyword{arg.keyword()}) {
1599 if (!CheckMaxMinArgument(*keyword, set, intrinsicName, messages)) {
1600 return false;
1601 }
1602 const bool isA1{*keyword == parser::CharBlock{"a1", 2}};
1603 if (isA1 && !actualForDummy[0]) {
1604 actualForDummy[0] = &arg;
1605 return true;
1606 }
1607 const bool isA2{*keyword == parser::CharBlock{"a2", 2}};
1608 if (isA2 && !actualForDummy[1]) {
1609 actualForDummy[1] = &arg;
1610 return true;
1611 }
1612 if (isA1 || isA2) {
1613 // Note that for arguments other than a1 and a2, this error will be caught
1614 // later in check-call.cpp.
1615 messages.Say(*keyword,
1616 "keyword argument '%s=' to intrinsic '%s' was supplied "
1617 "positionally by an earlier actual argument"_err_en_US,
1618 *keyword, intrinsicName);
1619 return false;
1620 }
1621 } else {
1622 if (actualForDummy.size() == 2) {
1623 if (!actualForDummy[0] && !actualForDummy[1]) {
1624 actualForDummy[0] = &arg;
1625 return true;
1626 } else if (!actualForDummy[1]) {
1627 actualForDummy[1] = &arg;
1628 return true;
1629 }
1630 }
1631 }
1632 actualForDummy.push_back(&arg);
1633 return true;
1634 }
1635
1636 static bool CheckAtomicKind(const ActualArgument &arg,
1637 const semantics::Scope *builtinsScope,
1638 parser::ContextualMessages &messages) {
1639 std::string atomicKindStr;
1640 std::optional<DynamicType> type{arg.GetType()};
1641
1642 if (type->category() == TypeCategory::Integer) {
1643 atomicKindStr = "atomic_int_kind";
1644 } else if (type->category() == TypeCategory::Logical) {
1645 atomicKindStr = "atomic_logical_kind";
1646 } else {
1647 common::die("atomic_int_kind or atomic_logical_kind from iso_fortran_env "
1648 "must be used with IntType or LogicalType");
1649 }
1650
1651 bool argOk = type->kind() ==
1652 GetBuiltinKind(builtinsScope, ("__builtin_" + atomicKindStr).c_str());
1653 if (!argOk) {
1654 messages.Say(arg.sourceLocation(),
1655 "Actual argument for 'atom=' must have kind=atomic_int_kind or atomic_logical_kind, but is '%s'"_err_en_US,
1656 type->AsFortran());
1657 }
1658 return argOk;
1659 }
1660
1661 // Intrinsic interface matching against the arguments of a particular
1662 // procedure reference.
1663 std::optional<SpecificCall> IntrinsicInterface::Match(
1664 const CallCharacteristics &call,
1665 const common::IntrinsicTypeDefaultKinds &defaults,
1666 ActualArguments &arguments, FoldingContext &context,
1667 const semantics::Scope *builtinsScope) const {
1668 auto &messages{context.messages()};
1669 // Attempt to construct a 1-1 correspondence between the dummy arguments in
1670 // a particular intrinsic procedure's generic interface and the actual
1671 // arguments in a procedure reference.
1672 std::size_t dummyArgPatterns{0};
1673 for (; dummyArgPatterns < maxArguments && dummy[dummyArgPatterns].keyword;
1674 ++dummyArgPatterns) {
1675 }
1676 // MAX and MIN (and others that map to them) allow their last argument to
1677 // be repeated indefinitely. The actualForDummy vector is sized
1678 // and null-initialized to the non-repeated dummy argument count
1679 // for other instrinsics.
1680 bool isMaxMin{dummyArgPatterns > 0 &&
1681 dummy[dummyArgPatterns - 1].optionality == Optionality::repeats};
1682 std::vector<ActualArgument *> actualForDummy(
1683 isMaxMin ? 2 : dummyArgPatterns, nullptr);
1684 bool anyMissingActualArgument{false};
1685 std::set<parser::CharBlock> maxMinKeywords;
1686 bool anyKeyword{false};
1687 int which{0};
1688 for (std::optional<ActualArgument> &arg : arguments) {
1689 ++which;
1690 if (arg) {
1691 if (arg->isAlternateReturn()) {
1692 messages.Say(arg->sourceLocation(),
1693 "alternate return specifier not acceptable on call to intrinsic '%s'"_err_en_US,
1694 name);
1695 return std::nullopt;
1696 }
1697 if (arg->keyword()) {
1698 anyKeyword = true;
1699 } else if (anyKeyword) {
1700 messages.Say(arg ? arg->sourceLocation() : std::nullopt,
1701 "actual argument #%d without a keyword may not follow an actual argument with a keyword"_err_en_US,
1702 which);
1703 return std::nullopt;
1704 }
1705 } else {
1706 anyMissingActualArgument = true;
1707 continue;
1708 }
1709 if (isMaxMin) {
1710 if (!CheckAndPushMinMaxArgument(
1711 *arg, actualForDummy, maxMinKeywords, name, messages)) {
1712 return std::nullopt;
1713 }
1714 } else {
1715 bool found{false};
1716 for (std::size_t j{0}; j < dummyArgPatterns && !found; ++j) {
1717 if (dummy[j].optionality == Optionality::missing) {
1718 continue;
1719 }
1720 if (arg->keyword()) {
1721 found = *arg->keyword() == dummy[j].keyword;
1722 if (found) {
1723 if (const auto *previous{actualForDummy[j]}) {
1724 if (previous->keyword()) {
1725 messages.Say(*arg->keyword(),
1726 "repeated keyword argument to intrinsic '%s'"_err_en_US,
1727 name);
1728 } else {
1729 messages.Say(*arg->keyword(),
1730 "keyword argument to intrinsic '%s' was supplied "
1731 "positionally by an earlier actual argument"_err_en_US,
1732 name);
1733 }
1734 return std::nullopt;
1735 }
1736 }
1737 } else {
1738 found = !actualForDummy[j] && !anyMissingActualArgument;
1739 }
1740 if (found) {
1741 actualForDummy[j] = &*arg;
1742 }
1743 }
1744 if (!found) {
1745 if (arg->keyword()) {
1746 messages.Say(*arg->keyword(),
1747 "unknown keyword argument to intrinsic '%s'"_err_en_US, name);
1748 } else {
1749 messages.Say(
1750 "too many actual arguments for intrinsic '%s'"_err_en_US, name);
1751 }
1752 return std::nullopt;
1753 }
1754 }
1755 }
1756
1757 std::size_t dummies{actualForDummy.size()};
1758
1759 // Check types and kinds of the actual arguments against the intrinsic's
1760 // interface. Ensure that two or more arguments that have to have the same
1761 // (or compatible) type and kind do so. Check for missing non-optional
1762 // arguments now, too.
1763 const ActualArgument *sameArg{nullptr};
1764 const ActualArgument *operandArg{nullptr};
1765 const IntrinsicDummyArgument *kindDummyArg{nullptr};
1766 const ActualArgument *kindArg{nullptr};
1767 std::optional<int> dimArg;
1768 for (std::size_t j{0}; j < dummies; ++j) {
1769 const IntrinsicDummyArgument &d{dummy[std::min(j, dummyArgPatterns - 1)]};
1770 if (d.typePattern.kindCode == KindCode::kindArg) {
1771 CHECK(!kindDummyArg);
1772 kindDummyArg = &d;
1773 }
1774 const ActualArgument *arg{actualForDummy[j]};
1775 if (!arg) {
1776 if (d.optionality == Optionality::required) {
1777 std::string kw{d.keyword};
1778 if (isMaxMin && !actualForDummy[0] && !actualForDummy[1]) {
1779 messages.Say("missing mandatory 'a1=' and 'a2=' arguments"_err_en_US);
1780 } else {
1781 messages.Say(
1782 "missing mandatory '%s=' argument"_err_en_US, kw.c_str());
1783 }
1784 return std::nullopt; // missing non-OPTIONAL argument
1785 } else {
1786 continue;
1787 }
1788 }
1789 if (d.optionality == Optionality::missing) {
1790 messages.Say(arg->sourceLocation(), "unexpected '%s=' argument"_err_en_US,
1791 d.keyword);
1792 return std::nullopt;
1793 }
1794 if (!d.flags.test(ArgFlag::canBeNull)) {
1795 if (const auto *expr{arg->UnwrapExpr()}; expr && IsNullPointer(*expr)) {
1796 if (!IsBareNullPointer(expr) && IsNullObjectPointer(*expr) &&
1797 d.flags.test(ArgFlag::canBeMoldNull)) {
1798 // ok
1799 } else {
1800 messages.Say(arg->sourceLocation(),
1801 "A NULL() pointer is not allowed for '%s=' intrinsic argument"_err_en_US,
1802 d.keyword);
1803 return std::nullopt;
1804 }
1805 }
1806 }
1807 if (d.flags.test(ArgFlag::notAssumedSize)) {
1808 if (auto named{ExtractNamedEntity(*arg)}) {
1809 if (semantics::IsAssumedSizeArray(named->GetLastSymbol())) {
1810 messages.Say(arg->sourceLocation(),
1811 "The '%s=' argument to the intrinsic procedure '%s' may not be assumed-size"_err_en_US,
1812 d.keyword, name);
1813 return std::nullopt;
1814 }
1815 }
1816 }
1817 if (arg->GetAssumedTypeDummy()) {
1818 // TYPE(*) assumed-type dummy argument forwarded to intrinsic
1819 if (d.typePattern.categorySet == AnyType &&
1820 (d.rank == Rank::anyOrAssumedRank ||
1821 d.rank == Rank::arrayOrAssumedRank) &&
1822 (d.typePattern.kindCode == KindCode::any ||
1823 d.typePattern.kindCode == KindCode::addressable)) {
1824 continue;
1825 } else {
1826 messages.Say(arg->sourceLocation(),
1827 "Assumed type TYPE(*) dummy argument not allowed for '%s=' intrinsic argument"_err_en_US,
1828 d.keyword);
1829 return std::nullopt;
1830 }
1831 }
1832 std::optional<DynamicType> type{arg->GetType()};
1833 if (!type) {
1834 CHECK(arg->Rank() == 0);
1835 const Expr<SomeType> &expr{DEREF(arg->UnwrapExpr())};
1836 if (IsBOZLiteral(expr)) {
1837 if (d.typePattern.kindCode == KindCode::typeless ||
1838 d.rank == Rank::elementalOrBOZ) {
1839 continue;
1840 } else {
1841 const IntrinsicDummyArgument *nextParam{
1842 j + 1 < dummies ? &dummy[j + 1] : nullptr};
1843 if (nextParam && nextParam->rank == Rank::elementalOrBOZ) {
1844 messages.Say(arg->sourceLocation(),
1845 "Typeless (BOZ) not allowed for both '%s=' & '%s=' arguments"_err_en_US, // C7109
1846 d.keyword, nextParam->keyword);
1847 } else {
1848 messages.Say(arg->sourceLocation(),
1849 "Typeless (BOZ) not allowed for '%s=' argument"_err_en_US,
1850 d.keyword);
1851 }
1852 }
1853 } else {
1854 // NULL(no MOLD=), procedure, or procedure pointer
1855 CHECK(IsProcedurePointerTarget(expr));
1856 if (d.typePattern.kindCode == KindCode::addressable ||
1857 d.rank == Rank::reduceOperation) {
1858 continue;
1859 } else if (d.typePattern.kindCode == KindCode::nullPointerType) {
1860 continue;
1861 } else if (IsBareNullPointer(&expr)) {
1862 // checked elsewhere
1863 continue;
1864 } else {
1865 CHECK(IsProcedure(expr) || IsProcedurePointer(expr));
1866 messages.Say(arg->sourceLocation(),
1867 "Actual argument for '%s=' may not be a procedure"_err_en_US,
1868 d.keyword);
1869 }
1870 }
1871 return std::nullopt;
1872 } else if (!d.typePattern.categorySet.test(type->category())) {
1873 messages.Say(arg->sourceLocation(),
1874 "Actual argument for '%s=' has bad type '%s'"_err_en_US, d.keyword,
1875 type->AsFortran());
1876 return std::nullopt; // argument has invalid type category
1877 }
1878 bool argOk{false};
1879 switch (d.typePattern.kindCode) {
1880 case KindCode::none:
1881 case KindCode::typeless:
1882 argOk = false;
1883 break;
1884 case KindCode::ieeeFlagType:
1885 argOk = !type->IsUnlimitedPolymorphic() &&
1886 type->category() == TypeCategory::Derived &&
1887 semantics::IsIeeeFlagType(&type->GetDerivedTypeSpec());
1888 break;
1889 case KindCode::ieeeRoundType:
1890 argOk = !type->IsUnlimitedPolymorphic() &&
1891 type->category() == TypeCategory::Derived &&
1892 semantics::IsIeeeRoundType(&type->GetDerivedTypeSpec());
1893 break;
1894 case KindCode::teamType:
1895 argOk = !type->IsUnlimitedPolymorphic() &&
1896 type->category() == TypeCategory::Derived &&
1897 semantics::IsTeamType(&type->GetDerivedTypeSpec());
1898 break;
1899 case KindCode::defaultIntegerKind:
1900 argOk = type->kind() == defaults.GetDefaultKind(TypeCategory::Integer);
1901 break;
1902 case KindCode::defaultRealKind:
1903 argOk = type->kind() == defaults.GetDefaultKind(TypeCategory::Real);
1904 break;
1905 case KindCode::doublePrecision:
1906 argOk = type->kind() == defaults.doublePrecisionKind();
1907 break;
1908 case KindCode::defaultCharKind:
1909 argOk = type->kind() == defaults.GetDefaultKind(TypeCategory::Character);
1910 break;
1911 case KindCode::defaultLogicalKind:
1912 argOk = type->kind() == defaults.GetDefaultKind(TypeCategory::Logical);
1913 break;
1914 case KindCode::any:
1915 argOk = true;
1916 break;
1917 case KindCode::kindArg:
1918 CHECK(type->category() == TypeCategory::Integer);
1919 CHECK(!kindArg);
1920 kindArg = arg;
1921 argOk = true;
1922 break;
1923 case KindCode::dimArg:
1924 CHECK(type->category() == TypeCategory::Integer);
1925 dimArg = j;
1926 argOk = true;
1927 break;
1928 case KindCode::same:
1929 if (!sameArg) {
1930 sameArg = arg;
1931 }
1932 argOk = type->IsTkLenCompatibleWith(sameArg->GetType().value());
1933 break;
1934 case KindCode::sameKind:
1935 if (!sameArg) {
1936 sameArg = arg;
1937 }
1938 argOk = type->IsTkCompatibleWith(sameArg->GetType().value());
1939 break;
1940 case KindCode::operand:
1941 if (!operandArg) {
1942 operandArg = arg;
1943 } else if (auto prev{operandArg->GetType()}) {
1944 if (type->category() == prev->category()) {
1945 if (type->kind() > prev->kind()) {
1946 operandArg = arg;
1947 }
1948 } else if (prev->category() == TypeCategory::Integer) {
1949 operandArg = arg;
1950 }
1951 }
1952 argOk = true;
1953 break;
1954 case KindCode::effectiveKind:
1955 common::die("INTERNAL: KindCode::effectiveKind appears on argument '%s' "
1956 "for intrinsic '%s'",
1957 d.keyword, name);
1958 break;
1959 case KindCode::addressable:
1960 case KindCode::nullPointerType:
1961 argOk = true;
1962 break;
1963 case KindCode::exactKind:
1964 argOk = type->kind() == d.typePattern.kindValue;
1965 break;
1966 case KindCode::greaterOrEqualToKind:
1967 argOk = type->kind() >= d.typePattern.kindValue;
1968 break;
1969 case KindCode::sameAtom:
1970 if (!sameArg) {
1971 sameArg = arg;
1972 argOk = CheckAtomicKind(DEREF(arg), builtinsScope, messages);
1973 } else {
1974 argOk = type->IsTkCompatibleWith(sameArg->GetType().value());
1975 if (!argOk) {
1976 messages.Say(arg->sourceLocation(),
1977 "Actual argument for '%s=' must have same type and kind as 'atom=', but is '%s'"_err_en_US,
1978 d.keyword, type->AsFortran());
1979 }
1980 }
1981 if (!argOk)
1982 return std::nullopt;
1983 break;
1984 case KindCode::atomicIntKind:
1985 argOk = type->kind() ==
1986 GetBuiltinKind(builtinsScope, "__builtin_atomic_int_kind");
1987 if (!argOk) {
1988 messages.Say(arg->sourceLocation(),
1989 "Actual argument for '%s=' must have kind=atomic_int_kind, but is '%s'"_err_en_US,
1990 d.keyword, type->AsFortran());
1991 return std::nullopt;
1992 }
1993 break;
1994 case KindCode::atomicIntOrLogicalKind:
1995 argOk = CheckAtomicKind(DEREF(arg), builtinsScope, messages);
1996 if (!argOk)
1997 return std::nullopt;
1998 break;
1999 default:
2000 CRASH_NO_CASE;
2001 }
2002 if (!argOk) {
2003 messages.Say(arg->sourceLocation(),
2004 "Actual argument for '%s=' has bad type or kind '%s'"_err_en_US,
2005 d.keyword, type->AsFortran());
2006 return std::nullopt;
2007 }
2008 }
2009
2010 // Check the ranks of the arguments against the intrinsic's interface.
2011 const ActualArgument *arrayArg{nullptr};
2012 const char *arrayArgName{nullptr};
2013 const ActualArgument *knownArg{nullptr};
2014 std::optional<int> shapeArgSize;
2015 int elementalRank{0};
2016 for (std::size_t j{0}; j < dummies; ++j) {
2017 const IntrinsicDummyArgument &d{dummy[std::min(j, dummyArgPatterns - 1)]};
2018 if (const ActualArgument *arg{actualForDummy[j]}) {
2019 bool isAssumedRank{IsAssumedRank(*arg)};
2020 if (isAssumedRank && d.rank != Rank::anyOrAssumedRank &&
2021 d.rank != Rank::arrayOrAssumedRank) {
2022 messages.Say(arg->sourceLocation(),
2023 "Assumed-rank array cannot be forwarded to '%s=' argument"_err_en_US,
2024 d.keyword);
2025 return std::nullopt;
2026 }
2027 int rank{arg->Rank()};
2028 bool argOk{false};
2029 switch (d.rank) {
2030 case Rank::elemental:
2031 case Rank::elementalOrBOZ:
2032 if (elementalRank == 0) {
2033 elementalRank = rank;
2034 }
2035 argOk = rank == 0 || rank == elementalRank;
2036 break;
2037 case Rank::scalar:
2038 argOk = rank == 0;
2039 break;
2040 case Rank::vector:
2041 argOk = rank == 1;
2042 break;
2043 case Rank::shape:
2044 CHECK(!shapeArgSize);
2045 if (rank != 1) {
2046 messages.Say(arg->sourceLocation(),
2047 "'shape=' argument must be an array of rank 1"_err_en_US);
2048 return std::nullopt;
2049 } else {
2050 if (auto shape{GetShape(context, *arg)}) {
2051 if (auto constShape{AsConstantShape(context, *shape)}) {
2052 shapeArgSize = constShape->At(ConstantSubscripts{1}).ToInt64();
2053 CHECK(*shapeArgSize >= 0);
2054 argOk = true;
2055 }
2056 }
2057 }
2058 if (!argOk) {
2059 messages.Say(arg->sourceLocation(),
2060 "'shape=' argument must be a vector of known size"_err_en_US);
2061 return std::nullopt;
2062 }
2063 break;
2064 case Rank::matrix:
2065 argOk = rank == 2;
2066 break;
2067 case Rank::array:
2068 argOk = rank > 0;
2069 if (!arrayArg) {
2070 arrayArg = arg;
2071 arrayArgName = d.keyword;
2072 }
2073 break;
2074 case Rank::coarray:
2075 argOk = IsCoarray(*arg);
2076 if (!argOk) {
2077 messages.Say(arg->sourceLocation(),
2078 "'coarray=' argument must have corank > 0 for intrinsic '%s'"_err_en_US,
2079 name);
2080 return std::nullopt;
2081 }
2082 break;
2083 case Rank::atom:
2084 argOk = rank == 0 && (IsCoarray(*arg) || ExtractCoarrayRef(*arg));
2085 if (!argOk) {
2086 messages.Say(arg->sourceLocation(),
2087 "'%s=' argument must be a scalar coarray or coindexed object for intrinsic '%s'"_err_en_US,
2088 d.keyword, name);
2089 return std::nullopt;
2090 }
2091 break;
2092 case Rank::known:
2093 if (!knownArg) {
2094 knownArg = arg;
2095 }
2096 argOk = !isAssumedRank && rank == knownArg->Rank();
2097 break;
2098 case Rank::anyOrAssumedRank:
2099 case Rank::arrayOrAssumedRank:
2100 if (isAssumedRank) {
2101 argOk = true;
2102 break;
2103 }
2104 if (d.rank == Rank::arrayOrAssumedRank && rank == 0) {
2105 argOk = false;
2106 break;
2107 }
2108 if (!knownArg) {
2109 knownArg = arg;
2110 }
2111 if (!dimArg && rank > 0 &&
2112 (std::strcmp(name, "shape") == 0 ||
2113 std::strcmp(name, "size") == 0 ||
2114 std::strcmp(name, "ubound") == 0)) {
2115 // Check for a whole assumed-size array argument.
2116 // These are disallowed for SHAPE, and require DIM= for
2117 // SIZE and UBOUND.
2118 // (A previous error message for UBOUND will take precedence
2119 // over this one, as this error is caught by the second entry
2120 // for UBOUND.)
2121 if (auto named{ExtractNamedEntity(*arg)}) {
2122 if (semantics::IsAssumedSizeArray(named->GetLastSymbol())) {
2123 if (strcmp(name, "shape") == 0) {
2124 messages.Say(arg->sourceLocation(),
2125 "The 'source=' argument to the intrinsic function 'shape' may not be assumed-size"_err_en_US);
2126 } else {
2127 messages.Say(arg->sourceLocation(),
2128 "A dim= argument is required for '%s' when the array is assumed-size"_err_en_US,
2129 name);
2130 }
2131 return std::nullopt;
2132 }
2133 }
2134 }
2135 argOk = true;
2136 break;
2137 case Rank::conformable: // arg must be conformable with previous arrayArg
2138 CHECK(arrayArg);
2139 CHECK(arrayArgName);
2140 if (const std::optional<Shape> &arrayArgShape{
2141 GetShape(context, *arrayArg)}) {
2142 if (std::optional<Shape> argShape{GetShape(context, *arg)}) {
2143 std::string arrayArgMsg{"'"};
2144 arrayArgMsg = arrayArgMsg + arrayArgName + "='" + " argument";
2145 std::string argMsg{"'"};
2146 argMsg = argMsg + d.keyword + "='" + " argument";
2147 CheckConformance(context.messages(), *arrayArgShape, *argShape,
2148 CheckConformanceFlags::RightScalarExpandable,
2149 arrayArgMsg.c_str(), argMsg.c_str());
2150 }
2151 }
2152 argOk = true; // Avoid an additional error message
2153 break;
2154 case Rank::dimReduced:
2155 case Rank::dimRemovedOrScalar:
2156 CHECK(arrayArg);
2157 argOk = rank == 0 || rank + 1 == arrayArg->Rank();
2158 break;
2159 case Rank::reduceOperation:
2160 // The reduction function is validated in ApplySpecificChecks().
2161 argOk = true;
2162 break;
2163 case Rank::scalarIfDim:
2164 case Rank::locReduced:
2165 case Rank::rankPlus1:
2166 case Rank::shaped:
2167 common::die("INTERNAL: result-only rank code appears on argument '%s' "
2168 "for intrinsic '%s'",
2169 d.keyword, name);
2170 }
2171 if (!argOk) {
2172 messages.Say(arg->sourceLocation(),
2173 "'%s=' argument has unacceptable rank %d"_err_en_US, d.keyword,
2174 rank);
2175 return std::nullopt;
2176 }
2177 }
2178 }
2179
2180 // Calculate the characteristics of the function result, if any
2181 std::optional<DynamicType> resultType;
2182 if (auto category{result.categorySet.LeastElement()}) {
2183 // The intrinsic is not a subroutine.
2184 if (call.isSubroutineCall) {
2185 return std::nullopt;
2186 }
2187 switch (result.kindCode) {
2188 case KindCode::defaultIntegerKind:
2189 CHECK(result.categorySet == IntType);
2190 CHECK(*category == TypeCategory::Integer);
2191 resultType = DynamicType{TypeCategory::Integer,
2192 defaults.GetDefaultKind(TypeCategory::Integer)};
2193 break;
2194 case KindCode::defaultRealKind:
2195 CHECK(result.categorySet == CategorySet{*category});
2196 CHECK(FloatingType.test(*category));
2197 resultType =
2198 DynamicType{*category, defaults.GetDefaultKind(TypeCategory::Real)};
2199 break;
2200 case KindCode::doublePrecision:
2201 CHECK(result.categorySet == CategorySet{*category});
2202 CHECK(FloatingType.test(*category));
2203 resultType = DynamicType{*category, defaults.doublePrecisionKind()};
2204 break;
2205 case KindCode::defaultLogicalKind:
2206 CHECK(result.categorySet == LogicalType);
2207 CHECK(*category == TypeCategory::Logical);
2208 resultType = DynamicType{TypeCategory::Logical,
2209 defaults.GetDefaultKind(TypeCategory::Logical)};
2210 break;
2211 case KindCode::defaultCharKind:
2212 CHECK(result.categorySet == CharType);
2213 CHECK(*category == TypeCategory::Character);
2214 resultType = DynamicType{TypeCategory::Character,
2215 defaults.GetDefaultKind(TypeCategory::Character)};
2216 break;
2217 case KindCode::same:
2218 CHECK(sameArg);
2219 if (std::optional<DynamicType> aType{sameArg->GetType()}) {
2220 if (result.categorySet.test(aType->category())) {
2221 if (const auto *sameChar{UnwrapExpr<Expr<SomeCharacter>>(*sameArg)}) {
2222 if (auto len{ToInt64(Fold(context, sameChar->LEN()))}) {
2223 resultType = DynamicType{aType->kind(), *len};
2224 } else {
2225 resultType = *aType;
2226 }
2227 } else {
2228 resultType = *aType;
2229 }
2230 } else {
2231 resultType = DynamicType{*category, aType->kind()};
2232 }
2233 }
2234 break;
2235 case KindCode::sameKind:
2236 CHECK(sameArg);
2237 if (std::optional<DynamicType> aType{sameArg->GetType()}) {
2238 resultType = DynamicType{*category, aType->kind()};
2239 }
2240 break;
2241 case KindCode::operand:
2242 CHECK(operandArg);
2243 resultType = operandArg->GetType();
2244 CHECK(!resultType || result.categorySet.test(resultType->category()));
2245 break;
2246 case KindCode::effectiveKind:
2247 CHECK(kindDummyArg);
2248 CHECK(result.categorySet == CategorySet{*category});
2249 if (kindArg) {
2250 if (auto *expr{kindArg->UnwrapExpr()}) {
2251 CHECK(expr->Rank() == 0);
2252 if (auto code{ToInt64(*expr)}) {
2253 if (context.targetCharacteristics().IsTypeEnabled(
2254 *category, *code)) {
2255 if (*category == TypeCategory::Character) { // ACHAR & CHAR
2256 resultType = DynamicType{static_cast<int>(*code), 1};
2257 } else {
2258 resultType = DynamicType{*category, static_cast<int>(*code)};
2259 }
2260 break;
2261 }
2262 }
2263 }
2264 messages.Say("'kind=' argument must be a constant scalar integer "
2265 "whose value is a supported kind for the "
2266 "intrinsic result type"_err_en_US);
2267 return std::nullopt;
2268 } else if (kindDummyArg->flags.test(ArgFlag::defaultsToSameKind)) {
2269 CHECK(sameArg);
2270 resultType = *sameArg->GetType();
2271 } else if (kindDummyArg->flags.test(ArgFlag::defaultsToSizeKind)) {
2272 CHECK(*category == TypeCategory::Integer);
2273 resultType =
2274 DynamicType{TypeCategory::Integer, defaults.sizeIntegerKind()};
2275 } else {
2276 CHECK(kindDummyArg->flags.test(ArgFlag::defaultsToDefaultForResult));
2277 int kind{defaults.GetDefaultKind(*category)};
2278 if (*category == TypeCategory::Character) { // ACHAR & CHAR
2279 resultType = DynamicType{kind, 1};
2280 } else {
2281 resultType = DynamicType{*category, kind};
2282 }
2283 }
2284 break;
2285 case KindCode::likeMultiply:
2286 CHECK(dummies >= 2);
2287 CHECK(actualForDummy[0]);
2288 CHECK(actualForDummy[1]);
2289 resultType = actualForDummy[0]->GetType()->ResultTypeForMultiply(
2290 *actualForDummy[1]->GetType());
2291 break;
2292 case KindCode::subscript:
2293 CHECK(result.categorySet == IntType);
2294 CHECK(*category == TypeCategory::Integer);
2295 resultType =
2296 DynamicType{TypeCategory::Integer, defaults.subscriptIntegerKind()};
2297 break;
2298 case KindCode::size:
2299 CHECK(result.categorySet == IntType);
2300 CHECK(*category == TypeCategory::Integer);
2301 resultType =
2302 DynamicType{TypeCategory::Integer, defaults.sizeIntegerKind()};
2303 break;
2304 case KindCode::teamType:
2305 CHECK(result.categorySet == DerivedType);
2306 CHECK(*category == TypeCategory::Derived);
2307 resultType = DynamicType{
2308 GetBuiltinDerivedType(builtinsScope, "__builtin_team_type")};
2309 break;
2310 case KindCode::greaterOrEqualToKind:
2311 case KindCode::exactKind:
2312 resultType = DynamicType{*category, result.kindValue};
2313 break;
2314 case KindCode::typeless:
2315 case KindCode::any:
2316 case KindCode::kindArg:
2317 case KindCode::dimArg:
2318 common::die(
2319 "INTERNAL: bad KindCode appears on intrinsic '%s' result", name);
2320 break;
2321 default:
2322 CRASH_NO_CASE;
2323 }
2324 } else {
2325 if (!call.isSubroutineCall) {
2326 return std::nullopt;
2327 }
2328 CHECK(result.kindCode == KindCode::none);
2329 }
2330
2331 // Emit warnings when the syntactic presence of a DIM= argument determines
2332 // the semantics of the call but the associated actual argument may not be
2333 // present at execution time.
2334 if (dimArg) {
2335 std::optional<int> arrayRank;
2336 if (arrayArg) {
2337 arrayRank = arrayArg->Rank();
2338 if (auto dimVal{ToInt64(actualForDummy[*dimArg])}) {
2339 if (*dimVal < 1) {
2340 messages.Say(
2341 "The value of DIM= (%jd) may not be less than 1"_err_en_US,
2342 static_cast<std::intmax_t>(*dimVal));
2343 } else if (*dimVal > *arrayRank) {
2344 messages.Say(
2345 "The value of DIM= (%jd) may not be greater than %d"_err_en_US,
2346 static_cast<std::intmax_t>(*dimVal), *arrayRank);
2347 }
2348 }
2349 }
2350 switch (rank) {
2351 case Rank::dimReduced:
2352 case Rank::dimRemovedOrScalar:
2353 case Rank::locReduced:
2354 case Rank::scalarIfDim:
2355 if (dummy[*dimArg].optionality == Optionality::required) {
2356 if (const Symbol *whole{
2357 UnwrapWholeSymbolOrComponentDataRef(actualForDummy[*dimArg])}) {
2358 if (IsOptional(*whole) || IsAllocatableOrObjectPointer(whole)) {
2359 if (context.languageFeatures().ShouldWarn(
2360 common::UsageWarning::OptionalMustBePresent)) {
2361 if (rank == Rank::scalarIfDim || arrayRank.value_or(-1) == 1) {
2362 messages.Say(
2363 "The actual argument for DIM= is optional, pointer, or allocatable, and it is assumed to be present and equal to 1 at execution time"_warn_en_US);
2364 } else {
2365 messages.Say(
2366 "The actual argument for DIM= is optional, pointer, or allocatable, and may not be absent during execution; parenthesize to silence this warning"_warn_en_US);
2367 }
2368 }
2369 }
2370 }
2371 }
2372 break;
2373 default:;
2374 }
2375 }
2376
2377 // At this point, the call is acceptable.
2378 // Determine the rank of the function result.
2379 int resultRank{0};
2380 switch (rank) {
2381 case Rank::elemental:
2382 resultRank = elementalRank;
2383 break;
2384 case Rank::scalar:
2385 resultRank = 0;
2386 break;
2387 case Rank::vector:
2388 resultRank = 1;
2389 break;
2390 case Rank::matrix:
2391 resultRank = 2;
2392 break;
2393 case Rank::conformable:
2394 CHECK(arrayArg);
2395 resultRank = arrayArg->Rank();
2396 break;
2397 case Rank::dimReduced:
2398 CHECK(arrayArg);
2399 resultRank = dimArg ? arrayArg->Rank() - 1 : 0;
2400 break;
2401 case Rank::locReduced:
2402 CHECK(arrayArg);
2403 resultRank = dimArg ? arrayArg->Rank() - 1 : 1;
2404 break;
2405 case Rank::rankPlus1:
2406 CHECK(knownArg);
2407 resultRank = knownArg->Rank() + 1;
2408 break;
2409 case Rank::shaped:
2410 CHECK(shapeArgSize);
2411 resultRank = *shapeArgSize;
2412 break;
2413 case Rank::scalarIfDim:
2414 resultRank = dimArg ? 0 : 1;
2415 break;
2416 case Rank::elementalOrBOZ:
2417 case Rank::shape:
2418 case Rank::array:
2419 case Rank::coarray:
2420 case Rank::atom:
2421 case Rank::known:
2422 case Rank::anyOrAssumedRank:
2423 case Rank::arrayOrAssumedRank:
2424 case Rank::reduceOperation:
2425 case Rank::dimRemovedOrScalar:
2426 common::die("INTERNAL: bad Rank code on intrinsic '%s' result", name);
2427 break;
2428 }
2429 CHECK(resultRank >= 0);
2430
2431 // Rearrange the actual arguments into dummy argument order.
2432 ActualArguments rearranged(dummies);
2433 for (std::size_t j{0}; j < dummies; ++j) {
2434 if (ActualArgument *arg{actualForDummy[j]}) {
2435 rearranged[j] = std::move(*arg);
2436 }
2437 }
2438
2439 // Characterize the specific intrinsic procedure.
2440 characteristics::DummyArguments dummyArgs;
2441 std::optional<int> sameDummyArg;
2442
2443 for (std::size_t j{0}; j < dummies; ++j) {
2444 const IntrinsicDummyArgument &d{dummy[std::min(j, dummyArgPatterns - 1)]};
2445 if (const auto &arg{rearranged[j]}) {
2446 if (const Expr<SomeType> *expr{arg->UnwrapExpr()}) {
2447 std::string kw{d.keyword};
2448 if (arg->keyword()) {
2449 kw = arg->keyword()->ToString();
2450 } else if (isMaxMin) {
2451 for (std::size_t k{j + 1};; ++k) {
2452 kw = "a"s + std::to_string(k);
2453 auto iter{std::find_if(dummyArgs.begin(), dummyArgs.end(),
2454 [&kw](const characteristics::DummyArgument &prev) {
2455 return prev.name == kw;
2456 })};
2457 if (iter == dummyArgs.end()) {
2458 break;
2459 }
2460 }
2461 }
2462 if (auto dc{characteristics::DummyArgument::FromActual(std::move(kw),
2463 *expr, context, /*forImplicitInterface=*/false)}) {
2464 if (auto *dummyProc{
2465 std::get_if<characteristics::DummyProcedure>(&dc->u)}) {
2466 // Dummy procedures are never elemental.
2467 dummyProc->procedure.value().attrs.reset(
2468 characteristics::Procedure::Attr::Elemental);
2469 }
2470 dummyArgs.emplace_back(std::move(*dc));
2471 if (d.typePattern.kindCode == KindCode::same && !sameDummyArg) {
2472 sameDummyArg = j;
2473 }
2474 } else { // error recovery
2475 messages.Say(
2476 "Could not characterize intrinsic function actual argument '%s'"_err_en_US,
2477 expr->AsFortran().c_str());
2478 return std::nullopt;
2479 }
2480 } else {
2481 CHECK(arg->GetAssumedTypeDummy());
2482 dummyArgs.emplace_back(std::string{d.keyword},
2483 characteristics::DummyDataObject{DynamicType::AssumedType()});
2484 }
2485 } else {
2486 // optional argument is absent
2487 CHECK(d.optionality != Optionality::required);
2488 if (d.typePattern.kindCode == KindCode::same) {
2489 dummyArgs.emplace_back(dummyArgs[sameDummyArg.value()]);
2490 } else {
2491 auto category{d.typePattern.categorySet.LeastElement().value()};
2492 if (category == TypeCategory::Derived) {
2493 // TODO: any other built-in derived types used as optional intrinsic
2494 // dummies?
2495 CHECK(d.typePattern.kindCode == KindCode::teamType);
2496 characteristics::TypeAndShape typeAndShape{
2497 GetBuiltinDerivedType(builtinsScope, "__builtin_team_type")};
2498 dummyArgs.emplace_back(std::string{d.keyword},
2499 characteristics::DummyDataObject{std::move(typeAndShape)});
2500 } else {
2501 characteristics::TypeAndShape typeAndShape{
2502 DynamicType{category, defaults.GetDefaultKind(category)}};
2503 dummyArgs.emplace_back(std::string{d.keyword},
2504 characteristics::DummyDataObject{std::move(typeAndShape)});
2505 }
2506 }
2507 dummyArgs.back().SetOptional();
2508 }
2509 dummyArgs.back().SetIntent(d.intent);
2510 }
2511 characteristics::Procedure::Attrs attrs;
2512 if (elementalRank > 0) {
2513 attrs.set(characteristics::Procedure::Attr::Elemental);
2514 }
2515 if (call.isSubroutineCall) {
2516 if (intrinsicClass == IntrinsicClass::pureSubroutine /* MOVE_ALLOC */ ||
2517 intrinsicClass == IntrinsicClass::elementalSubroutine /* MVBITS */) {
2518 attrs.set(characteristics::Procedure::Attr::Pure);
2519 }
2520 return SpecificCall{
2521 SpecificIntrinsic{
2522 name, characteristics::Procedure{std::move(dummyArgs), attrs}},
2523 std::move(rearranged)};
2524 } else {
2525 attrs.set(characteristics::Procedure::Attr::Pure);
2526 characteristics::TypeAndShape typeAndShape{resultType.value(), resultRank};
2527 characteristics::FunctionResult funcResult{std::move(typeAndShape)};
2528 characteristics::Procedure chars{
2529 std::move(funcResult), std::move(dummyArgs), attrs};
2530 return SpecificCall{
2531 SpecificIntrinsic{name, std::move(chars)}, std::move(rearranged)};
2532 }
2533 }
2534
2535 class IntrinsicProcTable::Implementation {
2536 public:
2537 explicit Implementation(const common::IntrinsicTypeDefaultKinds &dfts)
2538 : defaults_{dfts} {
2539 for (const IntrinsicInterface &f : genericIntrinsicFunction) {
2540 genericFuncs_.insert(std::make_pair(std::string{f.name}, &f));
2541 }
2542 for (const std::pair<const char *, const char *> &a : genericAlias) {
2543 aliases_.insert(
2544 std::make_pair(std::string{a.first}, std::string{a.second}));
2545 }
2546 for (const SpecificIntrinsicInterface &f : specificIntrinsicFunction) {
2547 specificFuncs_.insert(std::make_pair(std::string{f.name}, &f));
2548 }
2549 for (const IntrinsicInterface &f : intrinsicSubroutine) {
2550 subroutines_.insert(std::make_pair(std::string{f.name}, &f));
2551 }
2552 }
2553
2554 void SupplyBuiltins(const semantics::Scope &builtins) {
2555 builtinsScope_ = &builtins;
2556 }
2557
2558 bool IsIntrinsic(const std::string &) const;
2559 bool IsIntrinsicFunction(const std::string &) const;
2560 bool IsIntrinsicSubroutine(const std::string &) const;
2561 bool IsDualIntrinsic(const std::string &) const;
2562
2563 IntrinsicClass GetIntrinsicClass(const std::string &) const;
2564 std::string GetGenericIntrinsicName(const std::string &) const;
2565
2566 std::optional<SpecificCall> Probe(
2567 const CallCharacteristics &, ActualArguments &, FoldingContext &) const;
2568
2569 std::optional<SpecificIntrinsicFunctionInterface> IsSpecificIntrinsicFunction(
2570 const std::string &) const;
2571
2572 llvm::raw_ostream &Dump(llvm::raw_ostream &) const;
2573
2574 private:
2575 DynamicType GetSpecificType(const TypePattern &) const;
2576 SpecificCall HandleNull(ActualArguments &, FoldingContext &) const;
2577 std::optional<SpecificCall> HandleC_F_Pointer(
2578 ActualArguments &, FoldingContext &) const;
2579 std::optional<SpecificCall> HandleC_Loc(
2580 ActualArguments &, FoldingContext &) const;
2581 const std::string &ResolveAlias(const std::string &name) const {
2582 auto iter{aliases_.find(name)};
2583 return iter == aliases_.end() ? name : iter->second;
2584 }
2585
2586 common::IntrinsicTypeDefaultKinds defaults_;
2587 std::multimap<std::string, const IntrinsicInterface *> genericFuncs_;
2588 std::multimap<std::string, const SpecificIntrinsicInterface *> specificFuncs_;
2589 std::multimap<std::string, const IntrinsicInterface *> subroutines_;
2590 const semantics::Scope *builtinsScope_{nullptr};
2591 std::map<std::string, std::string> aliases_;
2592 semantics::ParamValue assumedLen_{
2593 semantics::ParamValue::Assumed(common::TypeParamAttr::Len)};
2594 };
2595
2596 bool IntrinsicProcTable::Implementation::IsIntrinsicFunction(
2597 const std::string &name0) const {
2598 const std::string &name{ResolveAlias(name0)};
2599 auto specificRange{specificFuncs_.equal_range(name)};
2600 if (specificRange.first != specificRange.second) {
2601 return true;
2602 }
2603 auto genericRange{genericFuncs_.equal_range(name)};
2604 if (genericRange.first != genericRange.second) {
2605 return true;
2606 }
2607 // special cases
2608 return name == "__builtin_c_loc" || name == "null";
2609 }
2610 bool IntrinsicProcTable::Implementation::IsIntrinsicSubroutine(
2611 const std::string &name0) const {
2612 const std::string &name{ResolveAlias(name0)};
2613 auto subrRange{subroutines_.equal_range(name)};
2614 if (subrRange.first != subrRange.second) {
2615 return true;
2616 }
2617 // special cases
2618 return name == "__builtin_c_f_pointer";
2619 }
2620 bool IntrinsicProcTable::Implementation::IsIntrinsic(
2621 const std::string &name) const {
2622 return IsIntrinsicFunction(name) || IsIntrinsicSubroutine(name);
2623 }
2624 bool IntrinsicProcTable::Implementation::IsDualIntrinsic(
2625 const std::string &name) const {
2626 // Collection for some intrinsics with function and subroutine form,
2627 // in order to pass the semantic check.
2628 static const std::string dualIntrinsic[]{
2629 {"etime"s}, {"getcwd"s}, {"rename"s}, {"second"s}};
2630
2631 return std::find_if(std::begin(dualIntrinsic), std::end(dualIntrinsic),
2632 [&name](const std::string &dualName) {
2633 return dualName == name;
2634 }) != std::end(dualIntrinsic);
2635 }
2636
2637 IntrinsicClass IntrinsicProcTable::Implementation::GetIntrinsicClass(
2638 const std::string &name) const {
2639 auto specificIntrinsic{specificFuncs_.find(name)};
2640 if (specificIntrinsic != specificFuncs_.end()) {
2641 return specificIntrinsic->second->intrinsicClass;
2642 }
2643 auto genericIntrinsic{genericFuncs_.find(name)};
2644 if (genericIntrinsic != genericFuncs_.end()) {
2645 return genericIntrinsic->second->intrinsicClass;
2646 }
2647 auto subrIntrinsic{subroutines_.find(name)};
2648 if (subrIntrinsic != subroutines_.end()) {
2649 return subrIntrinsic->second->intrinsicClass;
2650 }
2651 return IntrinsicClass::noClass;
2652 }
2653
2654 std::string IntrinsicProcTable::Implementation::GetGenericIntrinsicName(
2655 const std::string &name) const {
2656 auto specificIntrinsic{specificFuncs_.find(name)};
2657 if (specificIntrinsic != specificFuncs_.end()) {
2658 if (const char *genericName{specificIntrinsic->second->generic}) {
2659 return {genericName};
2660 }
2661 }
2662 return name;
2663 }
2664
2665 bool CheckAndRearrangeArguments(ActualArguments &arguments,
2666 parser::ContextualMessages &messages, const char *const dummyKeywords[],
2667 std::size_t trailingOptionals) {
2668 std::size_t numDummies{0};
2669 while (dummyKeywords[numDummies]) {
2670 ++numDummies;
2671 }
2672 CHECK(trailingOptionals <= numDummies);
2673 if (arguments.size() > numDummies) {
2674 messages.Say("Too many actual arguments (%zd > %zd)"_err_en_US,
2675 arguments.size(), numDummies);
2676 return false;
2677 }
2678 ActualArguments rearranged(numDummies);
2679 bool anyKeywords{false};
2680 std::size_t position{0};
2681 for (std::optional<ActualArgument> &arg : arguments) {
2682 std::size_t dummyIndex{0};
2683 if (arg && arg->keyword()) {
2684 anyKeywords = true;
2685 for (; dummyIndex < numDummies; ++dummyIndex) {
2686 if (*arg->keyword() == dummyKeywords[dummyIndex]) {
2687 break;
2688 }
2689 }
2690 if (dummyIndex >= numDummies) {
2691 messages.Say(*arg->keyword(),
2692 "Unknown argument keyword '%s='"_err_en_US, *arg->keyword());
2693 return false;
2694 }
2695 } else if (anyKeywords) {
2696 messages.Say(arg ? arg->sourceLocation() : messages.at(),
2697 "A positional actual argument may not appear after any keyword arguments"_err_en_US);
2698 return false;
2699 } else {
2700 dummyIndex = position++;
2701 }
2702 if (rearranged[dummyIndex]) {
2703 messages.Say(arg ? arg->sourceLocation() : messages.at(),
2704 "Dummy argument '%s=' appears more than once"_err_en_US,
2705 dummyKeywords[dummyIndex]);
2706 return false;
2707 }
2708 rearranged[dummyIndex] = std::move(arg);
2709 arg.reset();
2710 }
2711 bool anyMissing{false};
2712 for (std::size_t j{0}; j < numDummies - trailingOptionals; ++j) {
2713 if (!rearranged[j]) {
2714 messages.Say("Dummy argument '%s=' is absent and not OPTIONAL"_err_en_US,
2715 dummyKeywords[j]);
2716 anyMissing = true;
2717 }
2718 }
2719 arguments = std::move(rearranged);
2720 return !anyMissing;
2721 }
2722
2723 // The NULL() intrinsic is a special case.
2724 SpecificCall IntrinsicProcTable::Implementation::HandleNull(
2725 ActualArguments &arguments, FoldingContext &context) const {
2726 static const char *const keywords[]{"mold", nullptr};
2727 if (CheckAndRearrangeArguments(arguments, context.messages(), keywords, 1) &&
2728 arguments[0]) {
2729 Expr<SomeType> *mold{arguments[0]->UnwrapExpr()};
2730 bool isBareNull{IsBareNullPointer(mold)};
2731 if (isBareNull) {
2732 // NULL(NULL()), NULL(NULL(NULL())), &c. are all just NULL()
2733 mold = nullptr;
2734 }
2735 if (mold) {
2736 if (IsAssumedRank(*arguments[0])) {
2737 context.messages().Say(arguments[0]->sourceLocation(),
2738 "MOLD= argument to NULL() must not be assumed-rank"_err_en_US);
2739 }
2740 bool isProcPtrTarget{
2741 IsProcedurePointerTarget(*mold) && !IsNullObjectPointer(*mold)};
2742 if (isProcPtrTarget || IsAllocatableOrPointerObject(*mold)) {
2743 characteristics::DummyArguments args;
2744 std::optional<characteristics::FunctionResult> fResult;
2745 if (isProcPtrTarget) {
2746 // MOLD= procedure pointer
2747 std::optional<characteristics::Procedure> procPointer;
2748 if (IsNullProcedurePointer(*mold)) {
2749 procPointer =
2750 characteristics::Procedure::Characterize(*mold, context);
2751 } else {
2752 const Symbol *last{GetLastSymbol(*mold)};
2753 procPointer =
2754 characteristics::Procedure::Characterize(DEREF(last), context);
2755 }
2756 // procPointer is vacant if there was an error with the analysis
2757 // associated with the procedure pointer
2758 if (procPointer) {
2759 args.emplace_back("mold"s,
2760 characteristics::DummyProcedure{common::Clone(*procPointer)});
2761 fResult.emplace(std::move(*procPointer));
2762 }
2763 } else if (auto type{mold->GetType()}) {
2764 // MOLD= object pointer
2765 characteristics::TypeAndShape typeAndShape{
2766 *type, GetShape(context, *mold)};
2767 args.emplace_back(
2768 "mold"s, characteristics::DummyDataObject{typeAndShape});
2769 fResult.emplace(std::move(typeAndShape));
2770 } else {
2771 context.messages().Say(arguments[0]->sourceLocation(),
2772 "MOLD= argument to NULL() lacks type"_err_en_US);
2773 }
2774 if (fResult) {
2775 fResult->attrs.set(characteristics::FunctionResult::Attr::Pointer);
2776 characteristics::Procedure::Attrs attrs;
2777 attrs.set(characteristics::Procedure::Attr::NullPointer);
2778 characteristics::Procedure chars{
2779 std::move(*fResult), std::move(args), attrs};
2780 return SpecificCall{SpecificIntrinsic{"null"s, std::move(chars)},
2781 std::move(arguments)};
2782 }
2783 }
2784 }
2785 if (!isBareNull) {
2786 context.messages().Say(arguments[0]->sourceLocation(),
2787 "MOLD= argument to NULL() must be a pointer or allocatable"_err_en_US);
2788 }
2789 }
2790 characteristics::Procedure::Attrs attrs;
2791 attrs.set(characteristics::Procedure::Attr::NullPointer);
2792 attrs.set(characteristics::Procedure::Attr::Pure);
2793 arguments.clear();
2794 return SpecificCall{
2795 SpecificIntrinsic{"null"s,
2796 characteristics::Procedure{characteristics::DummyArguments{}, attrs}},
2797 std::move(arguments)};
2798 }
2799
2800 // Subroutine C_F_POINTER(CPTR=,FPTR=[,SHAPE=]) from
2801 // intrinsic module ISO_C_BINDING (18.2.3.3)
2802 std::optional<SpecificCall>
2803 IntrinsicProcTable::Implementation::HandleC_F_Pointer(
2804 ActualArguments &arguments, FoldingContext &context) const {
2805 characteristics::Procedure::Attrs attrs;
2806 attrs.set(characteristics::Procedure::Attr::Subroutine);
2807 static const char *const keywords[]{"cptr", "fptr", "shape", nullptr};
2808 characteristics::DummyArguments dummies;
2809 if (CheckAndRearrangeArguments(arguments, context.messages(), keywords, 1)) {
2810 CHECK(arguments.size() == 3);
2811 if (const auto *expr{arguments[0].value().UnwrapExpr()}) {
2812 // General semantic checks will catch an actual argument that's not
2813 // scalar.
2814 if (auto type{expr->GetType()}) {
2815 if (type->category() != TypeCategory::Derived ||
2816 type->IsPolymorphic() ||
2817 type->GetDerivedTypeSpec().typeSymbol().name() !=
2818 "__builtin_c_ptr") {
2819 context.messages().Say(arguments[0]->sourceLocation(),
2820 "CPTR= argument to C_F_POINTER() must be a C_PTR"_err_en_US);
2821 }
2822 characteristics::DummyDataObject cptr{
2823 characteristics::TypeAndShape{*type}};
2824 cptr.intent = common::Intent::In;
2825 dummies.emplace_back("cptr"s, std::move(cptr));
2826 }
2827 }
2828 if (const auto *expr{arguments[1].value().UnwrapExpr()}) {
2829 int fptrRank{expr->Rank()};
2830 auto at{arguments[1]->sourceLocation()};
2831 if (auto type{expr->GetType()}) {
2832 if (type->HasDeferredTypeParameter()) {
2833 context.messages().Say(at,
2834 "FPTR= argument to C_F_POINTER() may not have a deferred type parameter"_err_en_US);
2835 } else if (type->category() == TypeCategory::Derived) {
2836 if (context.languageFeatures().ShouldWarn(
2837 common::UsageWarning::Interoperability)) {
2838 if (type->IsUnlimitedPolymorphic()) {
2839 context.messages().Say(at,
2840 "FPTR= argument to C_F_POINTER() should not be unlimited polymorphic"_warn_en_US);
2841 } else if (!type->GetDerivedTypeSpec().typeSymbol().attrs().test(
2842 semantics::Attr::BIND_C)) {
2843 context.messages().Say(at,
2844 "FPTR= argument to C_F_POINTER() should not have a derived type that is not BIND(C)"_warn_en_US);
2845 }
2846 }
2847 } else if (!IsInteroperableIntrinsicType(
2848 *type, &context.languageFeatures())
2849 .value_or(true) &&
2850 context.languageFeatures().ShouldWarn(
2851 common::UsageWarning::Interoperability)) {
2852 context.messages().Say(at,
2853 "FPTR= argument to C_F_POINTER() should not have the non-interoperable intrinsic type %s"_warn_en_US,
2854 type->AsFortran());
2855 }
2856 if (ExtractCoarrayRef(*expr)) {
2857 context.messages().Say(at,
2858 "FPTR= argument to C_F_POINTER() may not be a coindexed object"_err_en_US);
2859 }
2860 characteristics::DummyDataObject fptr{
2861 characteristics::TypeAndShape{*type, fptrRank}};
2862 fptr.intent = common::Intent::Out;
2863 fptr.attrs.set(characteristics::DummyDataObject::Attr::Pointer);
2864 dummies.emplace_back("fptr"s, std::move(fptr));
2865 } else {
2866 context.messages().Say(
2867 at, "FPTR= argument to C_F_POINTER() must have a type"_err_en_US);
2868 }
2869 if (arguments[2] && fptrRank == 0) {
2870 context.messages().Say(arguments[2]->sourceLocation(),
2871 "SHAPE= argument to C_F_POINTER() may not appear when FPTR= is scalar"_err_en_US);
2872 } else if (!arguments[2] && fptrRank > 0) {
2873 context.messages().Say(
2874 "SHAPE= argument to C_F_POINTER() must appear when FPTR= is an array"_err_en_US);
2875 } else if (arguments[2]) {
2876 if (const auto *argExpr{arguments[2].value().UnwrapExpr()}) {
2877 if (argExpr->Rank() > 1) {
2878 context.messages().Say(arguments[2]->sourceLocation(),
2879 "SHAPE= argument to C_F_POINTER() must be a rank-one array."_err_en_US);
2880 } else if (argExpr->Rank() == 1) {
2881 if (auto constShape{GetConstantShape(context, *argExpr)}) {
2882 if (constShape->At(ConstantSubscripts{1}).ToInt64() != fptrRank) {
2883 context.messages().Say(arguments[2]->sourceLocation(),
2884 "SHAPE= argument to C_F_POINTER() must have size equal to the rank of FPTR="_err_en_US);
2885 }
2886 }
2887 }
2888 }
2889 }
2890 }
2891 }
2892 if (dummies.size() == 2) {
2893 DynamicType shapeType{TypeCategory::Integer, defaults_.sizeIntegerKind()};
2894 if (arguments[2]) {
2895 if (auto type{arguments[2]->GetType()}) {
2896 if (type->category() == TypeCategory::Integer) {
2897 shapeType = *type;
2898 }
2899 }
2900 }
2901 characteristics::DummyDataObject shape{
2902 characteristics::TypeAndShape{shapeType, 1}};
2903 shape.intent = common::Intent::In;
2904 shape.attrs.set(characteristics::DummyDataObject::Attr::Optional);
2905 dummies.emplace_back("shape"s, std::move(shape));
2906 return SpecificCall{
2907 SpecificIntrinsic{"__builtin_c_f_pointer"s,
2908 characteristics::Procedure{std::move(dummies), attrs}},
2909 std::move(arguments)};
2910 } else {
2911 return std::nullopt;
2912 }
2913 }
2914
2915 // Function C_LOC(X) from intrinsic module ISO_C_BINDING (18.2.3.6)
2916 std::optional<SpecificCall> IntrinsicProcTable::Implementation::HandleC_Loc(
2917 ActualArguments &arguments, FoldingContext &context) const {
2918 static const char *const keywords[]{"x", nullptr};
2919 if (CheckAndRearrangeArguments(arguments, context.messages(), keywords)) {
2920 CHECK(arguments.size() == 1);
2921 CheckForCoindexedObject(context.messages(), arguments[0], "c_loc", "x");
2922 const auto *expr{arguments[0].value().UnwrapExpr()};
2923 if (expr &&
2924 !(IsObjectPointer(*expr) ||
2925 (IsVariable(*expr) && GetLastTarget(GetSymbolVector(*expr))))) {
2926 context.messages().Say(arguments[0]->sourceLocation(),
2927 "C_LOC() argument must be a data pointer or target"_err_en_US);
2928 }
2929 if (auto typeAndShape{characteristics::TypeAndShape::Characterize(
2930 arguments[0], context)}) {
2931 if (expr && !IsContiguous(*expr, context).value_or(true)) {
2932 context.messages().Say(arguments[0]->sourceLocation(),
2933 "C_LOC() argument must be contiguous"_err_en_US);
2934 }
2935 if (auto constExtents{AsConstantExtents(context, typeAndShape->shape())};
2936 constExtents && GetSize(*constExtents) == 0) {
2937 context.messages().Say(arguments[0]->sourceLocation(),
2938 "C_LOC() argument may not be a zero-sized array"_err_en_US);
2939 }
2940 if (!(typeAndShape->type().category() != TypeCategory::Derived ||
2941 typeAndShape->type().IsAssumedType() ||
2942 (!typeAndShape->type().IsPolymorphic() &&
2943 CountNonConstantLenParameters(
2944 typeAndShape->type().GetDerivedTypeSpec()) == 0))) {
2945 context.messages().Say(arguments[0]->sourceLocation(),
2946 "C_LOC() argument must have an intrinsic type, assumed type, or non-polymorphic derived type with no non-constant length parameter"_err_en_US);
2947 } else if (typeAndShape->type().knownLength().value_or(1) == 0) {
2948 context.messages().Say(arguments[0]->sourceLocation(),
2949 "C_LOC() argument may not be zero-length character"_err_en_US);
2950 } else if (typeAndShape->type().category() != TypeCategory::Derived &&
2951 !IsInteroperableIntrinsicType(typeAndShape->type()).value_or(true) &&
2952 context.languageFeatures().ShouldWarn(
2953 common::UsageWarning::Interoperability)) {
2954 context.messages().Say(arguments[0]->sourceLocation(),
2955 "C_LOC() argument has non-interoperable intrinsic type, kind, or length"_warn_en_US);
2956 }
2957
2958 characteristics::DummyDataObject ddo{std::move(*typeAndShape)};
2959 ddo.intent = common::Intent::In;
2960 return SpecificCall{
2961 SpecificIntrinsic{"__builtin_c_loc"s,
2962 characteristics::Procedure{
2963 characteristics::FunctionResult{
2964 DynamicType{GetBuiltinDerivedType(
2965 builtinsScope_, "__builtin_c_ptr")}},
2966 characteristics::DummyArguments{
2967 characteristics::DummyArgument{"x"s, std::move(ddo)}},
2968 characteristics::Procedure::Attrs{
2969 characteristics::Procedure::Attr::Pure}}},
2970 std::move(arguments)};
2971 }
2972 }
2973 return std::nullopt;
2974 }
2975
2976 static bool CheckForNonPositiveValues(FoldingContext &context,
2977 const ActualArgument &arg, const std::string &procName,
2978 const std::string &argName) {
2979 bool ok{true};
2980 if (arg.Rank() > 0) {
2981 if (const Expr<SomeType> *expr{arg.UnwrapExpr()}) {
2982 if (const auto *intExpr{std::get_if<Expr<SomeInteger>>(&expr->u)}) {
2983 Fortran::common::visit(
2984 [&](const auto &kindExpr) {
2985 using IntType = typename std::decay_t<decltype(kindExpr)>::Result;
2986 if (const auto *constArray{
2987 UnwrapConstantValue<IntType>(kindExpr)}) {
2988 for (std::size_t j{0}; j < constArray->size(); ++j) {
2989 auto arrayExpr{constArray->values().at(j)};
2990 if (arrayExpr.IsNegative() || arrayExpr.IsZero()) {
2991 ok = false;
2992 context.messages().Say(arg.sourceLocation(),
2993 "'%s=' argument for intrinsic '%s' must contain all positive values"_err_en_US,
2994 argName, procName);
2995 }
2996 }
2997 }
2998 },
2999 intExpr->u);
3000 }
3001 }
3002 } else {
3003 if (auto val{ToInt64(arg.UnwrapExpr())}) {
3004 if (*val <= 0) {
3005 ok = false;
3006 context.messages().Say(arg.sourceLocation(),
3007 "'%s=' argument for intrinsic '%s' must be a positive value, but is %jd"_err_en_US,
3008 argName, procName, static_cast<std::intmax_t>(*val));
3009 }
3010 }
3011 }
3012 return ok;
3013 }
3014
3015 static bool CheckDimAgainstCorank(SpecificCall &call, FoldingContext &context) {
3016 bool ok{true};
3017 if (const auto &coarrayArg{call.arguments[0]}) {
3018 if (const auto &dimArg{call.arguments[1]}) {
3019 if (const auto *symbol{
3020 UnwrapWholeSymbolDataRef(coarrayArg->UnwrapExpr())}) {
3021 const auto corank = symbol->Corank();
3022 if (const auto dimNum{ToInt64(dimArg->UnwrapExpr())}) {
3023 if (dimNum < 1 || dimNum > corank) {
3024 ok = false;
3025 context.messages().Say(dimArg->sourceLocation(),
3026 "DIM=%jd dimension is out of range for coarray with corank %d"_err_en_US,
3027 static_cast<std::intmax_t>(*dimNum), corank);
3028 }
3029 }
3030 }
3031 }
3032 }
3033 return ok;
3034 }
3035
3036 static bool CheckAtomicDefineAndRef(FoldingContext &context,
3037 const std::optional<ActualArgument> &atomArg,
3038 const std::optional<ActualArgument> &valueArg,
3039 const std::optional<ActualArgument> &statArg, const std::string &procName) {
3040 bool sameType{true};
3041 if (valueArg && atomArg) {
3042 // for atomic_define and atomic_ref, 'value' arg must be the same type as
3043 // 'atom', but it doesn't have to be the same kind
3044 if (valueArg->GetType()->category() != atomArg->GetType()->category()) {
3045 sameType = false;
3046 context.messages().Say(valueArg->sourceLocation(),
3047 "'value=' argument to '%s' must have same type as 'atom=', but is '%s'"_err_en_US,
3048 procName, valueArg->GetType()->AsFortran());
3049 }
3050 }
3051
3052 return sameType &&
3053 CheckForCoindexedObject(context.messages(), statArg, procName, "stat");
3054 }
3055
3056 // Applies any semantic checks peculiar to an intrinsic.
3057 // TODO: Move the rest of these checks to Semantics/check-call.cpp.
3058 static bool ApplySpecificChecks(SpecificCall &call, FoldingContext &context) {
3059 bool ok{true};
3060 const std::string &name{call.specificIntrinsic.name};
3061 if (name == "allocated") {
3062 const auto &arg{call.arguments[0]};
3063 if (arg) {
3064 if (const auto *expr{arg->UnwrapExpr()}) {
3065 ok = evaluate::IsAllocatableDesignator(*expr);
3066 }
3067 }
3068 if (!ok) {
3069 context.messages().Say(
3070 arg ? arg->sourceLocation() : context.messages().at(),
3071 "Argument of ALLOCATED() must be an ALLOCATABLE object or component"_err_en_US);
3072 }
3073 } else if (name == "atomic_and" || name == "atomic_or" ||
3074 name == "atomic_xor") {
3075 return CheckForCoindexedObject(
3076 context.messages(), call.arguments[2], name, "stat");
3077 } else if (name == "atomic_cas") {
3078 return CheckForCoindexedObject(
3079 context.messages(), call.arguments[4], name, "stat");
3080 } else if (name == "atomic_define") {
3081 return CheckAtomicDefineAndRef(
3082 context, call.arguments[0], call.arguments[1], call.arguments[2], name);
3083 } else if (name == "atomic_fetch_add" || name == "atomic_fetch_and" ||
3084 name == "atomic_fetch_or" || name == "atomic_fetch_xor") {
3085 return CheckForCoindexedObject(
3086 context.messages(), call.arguments[3], name, "stat");
3087 } else if (name == "atomic_ref") {
3088 return CheckAtomicDefineAndRef(
3089 context, call.arguments[1], call.arguments[0], call.arguments[2], name);
3090 } else if (name == "co_broadcast" || name == "co_max" || name == "co_min" ||
3091 name == "co_sum") {
3092 bool aOk{CheckForCoindexedObject(
3093 context.messages(), call.arguments[0], name, "a")};
3094 bool statOk{CheckForCoindexedObject(
3095 context.messages(), call.arguments[2], name, "stat")};
3096 bool errmsgOk{CheckForCoindexedObject(
3097 context.messages(), call.arguments[3], name, "errmsg")};
3098 ok = aOk && statOk && errmsgOk;
3099 } else if (name == "image_status") {
3100 if (const auto &arg{call.arguments[0]}) {
3101 ok = CheckForNonPositiveValues(context, *arg, name, "image");
3102 }
3103 } else if (name == "lcobound") {
3104 return CheckDimAgainstCorank(call, context);
3105 } else if (name == "loc") {
3106 const auto &arg{call.arguments[0]};
3107 ok =
3108 arg && (arg->GetAssumedTypeDummy() || GetLastSymbol(arg->UnwrapExpr()));
3109 if (!ok) {
3110 context.messages().Say(
3111 arg ? arg->sourceLocation() : context.messages().at(),
3112 "Argument of LOC() must be an object or procedure"_err_en_US);
3113 }
3114 } else if (name == "ucobound") {
3115 return CheckDimAgainstCorank(call, context);
3116 }
3117 return ok;
3118 }
3119
3120 static DynamicType GetReturnType(const SpecificIntrinsicInterface &interface,
3121 const common::IntrinsicTypeDefaultKinds &defaults) {
3122 TypeCategory category{TypeCategory::Integer};
3123 switch (interface.result.kindCode) {
3124 case KindCode::defaultIntegerKind:
3125 break;
3126 case KindCode::doublePrecision:
3127 case KindCode::defaultRealKind:
3128 category = TypeCategory::Real;
3129 break;
3130 default:
3131 CRASH_NO_CASE;
3132 }
3133 int kind{interface.result.kindCode == KindCode::doublePrecision
3134 ? defaults.doublePrecisionKind()
3135 : defaults.GetDefaultKind(category)};
3136 return DynamicType{category, kind};
3137 }
3138
3139 // Probe the configured intrinsic procedure pattern tables in search of a
3140 // match for a given procedure reference.
3141 std::optional<SpecificCall> IntrinsicProcTable::Implementation::Probe(
3142 const CallCharacteristics &call, ActualArguments &arguments,
3143 FoldingContext &context) const {
3144
3145 // All special cases handled here before the table probes below must
3146 // also be recognized as special names in IsIntrinsicSubroutine().
3147 if (call.isSubroutineCall) {
3148 if (call.name == "__builtin_c_f_pointer") {
3149 return HandleC_F_Pointer(arguments, context);
3150 } else if (call.name == "random_seed") {
3151 int optionalCount{0};
3152 for (const auto &arg : arguments) {
3153 if (const auto *expr{arg->UnwrapExpr()}) {
3154 optionalCount +=
3155 Fortran::evaluate::MayBePassedAsAbsentOptional(*expr);
3156 }
3157 }
3158 if (arguments.size() - optionalCount > 1) {
3159 context.messages().Say(
3160 "RANDOM_SEED must have either 1 or no arguments"_err_en_US);
3161 }
3162 }
3163 } else { // function
3164 if (call.name == "__builtin_c_loc") {
3165 return HandleC_Loc(arguments, context);
3166 } else if (call.name == "null") {
3167 return HandleNull(arguments, context);
3168 }
3169 }
3170
3171 if (call.isSubroutineCall) {
3172 const std::string &name{ResolveAlias(call.name)};
3173 auto subrRange{subroutines_.equal_range(name)};
3174 for (auto iter{subrRange.first}; iter != subrRange.second; ++iter) {
3175 if (auto specificCall{iter->second->Match(
3176 call, defaults_, arguments, context, builtinsScope_)}) {
3177 ApplySpecificChecks(*specificCall, context);
3178 return specificCall;
3179 }
3180 }
3181 if (IsIntrinsicFunction(call.name) && !IsDualIntrinsic(call.name)) {
3182 context.messages().Say(
3183 "Cannot use intrinsic function '%s' as a subroutine"_err_en_US,
3184 call.name);
3185 }
3186 return std::nullopt;
3187 }
3188
3189 // Helper to avoid emitting errors before it is sure there is no match
3190 parser::Messages localBuffer;
3191 parser::Messages *finalBuffer{context.messages().messages()};
3192 parser::ContextualMessages localMessages{
3193 context.messages().at(), finalBuffer ? &localBuffer : nullptr};
3194 FoldingContext localContext{context, localMessages};
3195 auto matchOrBufferMessages{
3196 [&](const IntrinsicInterface &intrinsic,
3197 parser::Messages &buffer) -> std::optional<SpecificCall> {
3198 if (auto specificCall{intrinsic.Match(
3199 call, defaults_, arguments, localContext, builtinsScope_)}) {
3200 if (finalBuffer) {
3201 finalBuffer->Annex(std::move(localBuffer));
3202 }
3203 return specificCall;
3204 } else if (buffer.empty()) {
3205 buffer.Annex(std::move(localBuffer));
3206 } else {
3207 // When there are multiple entries in the table for an
3208 // intrinsic that has multiple forms depending on the
3209 // presence of DIM=, use messages from a later entry if
3210 // the messages from an earlier entry complain about the
3211 // DIM= argument and it wasn't specified with a keyword.
3212 for (const auto &m : buffer.messages()) {
3213 if (m.ToString().find("'dim='") != std::string::npos) {
3214 bool hadDimKeyword{false};
3215 for (const auto &a : arguments) {
3216 if (a) {
3217 if (auto kw{a->keyword()}; kw && kw == "dim") {
3218 hadDimKeyword = true;
3219 break;
3220 }
3221 }
3222 }
3223 if (!hadDimKeyword) {
3224 buffer = std::move(localBuffer);
3225 }
3226 break;
3227 }
3228 }
3229 localBuffer.clear();
3230 }
3231 return std::nullopt;
3232 }};
3233
3234 // Probe the generic intrinsic function table first; allow for
3235 // the use of a legacy alias.
3236 parser::Messages genericBuffer;
3237 const std::string &name{ResolveAlias(call.name)};
3238 auto genericRange{genericFuncs_.equal_range(name)};
3239 for (auto iter{genericRange.first}; iter != genericRange.second; ++iter) {
3240 if (auto specificCall{
3241 matchOrBufferMessages(*iter->second, genericBuffer)}) {
3242 ApplySpecificChecks(*specificCall, context);
3243 return specificCall;
3244 }
3245 }
3246
3247 // Probe the specific intrinsic function table next.
3248 parser::Messages specificBuffer;
3249 auto specificRange{specificFuncs_.equal_range(call.name)};
3250 for (auto specIter{specificRange.first}; specIter != specificRange.second;
3251 ++specIter) {
3252 // We only need to check the cases with distinct generic names.
3253 if (const char *genericName{specIter->second->generic}) {
3254 if (auto specificCall{
3255 matchOrBufferMessages(*specIter->second, specificBuffer)}) {
3256 if (!specIter->second->useGenericAndForceResultType) {
3257 specificCall->specificIntrinsic.name = genericName;
3258 }
3259 specificCall->specificIntrinsic.isRestrictedSpecific =
3260 specIter->second->isRestrictedSpecific;
3261 // TODO test feature AdditionalIntrinsics, warn on nonstandard
3262 // specifics with DoublePrecisionComplex arguments.
3263 return specificCall;
3264 }
3265 }
3266 }
3267
3268 // If there was no exact match with a specific, try to match the related
3269 // generic and convert the result to the specific required type.
3270 if (context.languageFeatures().IsEnabled(common::LanguageFeature::
3271 UseGenericIntrinsicWhenSpecificDoesntMatch)) {
3272 for (auto specIter{specificRange.first}; specIter != specificRange.second;
3273 ++specIter) {
3274 // We only need to check the cases with distinct generic names.
3275 if (const char *genericName{specIter->second->generic}) {
3276 if (specIter->second->useGenericAndForceResultType) {
3277 auto genericRange{genericFuncs_.equal_range(genericName)};
3278 for (auto genIter{genericRange.first}; genIter != genericRange.second;
3279 ++genIter) {
3280 if (auto specificCall{
3281 matchOrBufferMessages(*genIter->second, specificBuffer)}) {
3282 // Force the call result type to the specific intrinsic result
3283 // type, if possible.
3284 DynamicType genericType{
3285 DEREF(specificCall->specificIntrinsic.characteristics.value()
3286 .functionResult.value()
3287 .GetTypeAndShape())
3288 .type()};
3289 DynamicType newType{GetReturnType(*specIter->second, defaults_)};
3290 if (genericType.category() == newType.category() ||
3291 ((genericType.category() == TypeCategory::Integer ||
3292 genericType.category() == TypeCategory::Real) &&
3293 (newType.category() == TypeCategory::Integer ||
3294 newType.category() == TypeCategory::Real))) {
3295 if (context.languageFeatures().ShouldWarn(
3296 common::LanguageFeature::
3297 UseGenericIntrinsicWhenSpecificDoesntMatch)) {
3298 context.messages().Say(
3299 "Argument types do not match specific intrinsic '%s' requirements; using '%s' generic instead and converting the result to %s if needed"_port_en_US,
3300 call.name, genericName, newType.AsFortran());
3301 }
3302 specificCall->specificIntrinsic.name = call.name;
3303 specificCall->specificIntrinsic.characteristics.value()
3304 .functionResult.value()
3305 .SetType(newType);
3306 return specificCall;
3307 }
3308 }
3309 }
3310 }
3311 }
3312 }
3313 }
3314
3315 if (specificBuffer.empty() && genericBuffer.empty() &&
3316 IsIntrinsicSubroutine(call.name) && !IsDualIntrinsic(call.name)) {
3317 context.messages().Say(
3318 "Cannot use intrinsic subroutine '%s' as a function"_err_en_US,
3319 call.name);
3320 }
3321
3322 // No match; report the right errors, if any
3323 if (finalBuffer) {
3324 if (specificBuffer.empty()) {
3325 finalBuffer->Annex(std::move(genericBuffer));
3326 } else {
3327 finalBuffer->Annex(std::move(specificBuffer));
3328 }
3329 }
3330 return std::nullopt;
3331 }
3332
3333 std::optional<SpecificIntrinsicFunctionInterface>
3334 IntrinsicProcTable::Implementation::IsSpecificIntrinsicFunction(
3335 const std::string &name) const {
3336 auto specificRange{specificFuncs_.equal_range(name)};
3337 for (auto iter{specificRange.first}; iter != specificRange.second; ++iter) {
3338 const SpecificIntrinsicInterface &specific{*iter->second};
3339 std::string genericName{name};
3340 if (specific.generic) {
3341 genericName = std::string(specific.generic);
3342 }
3343 characteristics::FunctionResult fResult{GetSpecificType(specific.result)};
3344 characteristics::DummyArguments args;
3345 int dummies{specific.CountArguments()};
3346 for (int j{0}; j < dummies; ++j) {
3347 characteristics::DummyDataObject dummy{
3348 GetSpecificType(specific.dummy[j].typePattern)};
3349 dummy.intent = specific.dummy[j].intent;
3350 args.emplace_back(
3351 std::string{specific.dummy[j].keyword}, std::move(dummy));
3352 }
3353 characteristics::Procedure::Attrs attrs;
3354 attrs.set(characteristics::Procedure::Attr::Pure)
3355 .set(characteristics::Procedure::Attr::Elemental);
3356 characteristics::Procedure chars{
3357 std::move(fResult), std::move(args), attrs};
3358 return SpecificIntrinsicFunctionInterface{
3359 std::move(chars), genericName, specific.isRestrictedSpecific};
3360 }
3361 return std::nullopt;
3362 }
3363
3364 DynamicType IntrinsicProcTable::Implementation::GetSpecificType(
3365 const TypePattern &pattern) const {
3366 const CategorySet &set{pattern.categorySet};
3367 CHECK(set.count() == 1);
3368 TypeCategory category{set.LeastElement().value()};
3369 if (pattern.kindCode == KindCode::doublePrecision) {
3370 return DynamicType{category, defaults_.doublePrecisionKind()};
3371 } else if (category == TypeCategory::Character) {
3372 // All character arguments to specific intrinsic functions are
3373 // assumed-length.
3374 return DynamicType{defaults_.GetDefaultKind(category), assumedLen_};
3375 } else {
3376 return DynamicType{category, defaults_.GetDefaultKind(category)};
3377 }
3378 }
3379
3380 IntrinsicProcTable::~IntrinsicProcTable() = default;
3381
3382 IntrinsicProcTable IntrinsicProcTable::Configure(
3383 const common::IntrinsicTypeDefaultKinds &defaults) {
3384 IntrinsicProcTable result;
3385 result.impl_ = std::make_unique<IntrinsicProcTable::Implementation>(defaults);
3386 return result;
3387 }
3388
3389 void IntrinsicProcTable::SupplyBuiltins(
3390 const semantics::Scope &builtins) const {
3391 DEREF(impl_.get()).SupplyBuiltins(builtins);
3392 }
3393
3394 bool IntrinsicProcTable::IsIntrinsic(const std::string &name) const {
3395 return DEREF(impl_.get()).IsIntrinsic(name);
3396 }
3397 bool IntrinsicProcTable::IsIntrinsicFunction(const std::string &name) const {
3398 return DEREF(impl_.get()).IsIntrinsicFunction(name);
3399 }
3400 bool IntrinsicProcTable::IsIntrinsicSubroutine(const std::string &name) const {
3401 return DEREF(impl_.get()).IsIntrinsicSubroutine(name);
3402 }
3403
3404 IntrinsicClass IntrinsicProcTable::GetIntrinsicClass(
3405 const std::string &name) const {
3406 return DEREF(impl_.get()).GetIntrinsicClass(name);
3407 }
3408
3409 std::string IntrinsicProcTable::GetGenericIntrinsicName(
3410 const std::string &name) const {
3411 return DEREF(impl_.get()).GetGenericIntrinsicName(name);
3412 }
3413
3414 std::optional<SpecificCall> IntrinsicProcTable::Probe(
3415 const CallCharacteristics &call, ActualArguments &arguments,
3416 FoldingContext &context) const {
3417 return DEREF(impl_.get()).Probe(call, arguments, context);
3418 }
3419
3420 std::optional<SpecificIntrinsicFunctionInterface>
3421 IntrinsicProcTable::IsSpecificIntrinsicFunction(const std::string &name) const {
3422 return DEREF(impl_.get()).IsSpecificIntrinsicFunction(name);
3423 }
3424
3425 llvm::raw_ostream &TypePattern::Dump(llvm::raw_ostream &o) const {
3426 if (categorySet == AnyType) {
3427 o << "any type";
3428 } else {
3429 const char *sep = "";
3430 auto set{categorySet};
3431 while (auto least{set.LeastElement()}) {
3432 o << sep << EnumToString(*least);
3433 sep = " or ";
3434 set.reset(*least);
3435 }
3436 }
3437 o << '(' << EnumToString(kindCode) << ')';
3438 return o;
3439 }
3440
3441 llvm::raw_ostream &IntrinsicDummyArgument::Dump(llvm::raw_ostream &o) const {
3442 if (keyword) {
3443 o << keyword << '=';
3444 }
3445 return typePattern.Dump(o)
3446 << ' ' << EnumToString(rank) << ' ' << EnumToString(optionality)
3447 << EnumToString(intent);
3448 }
3449
3450 llvm::raw_ostream &IntrinsicInterface::Dump(llvm::raw_ostream &o) const {
3451 o << name;
3452 char sep{'('};
3453 for (const auto &d : dummy) {
3454 if (d.typePattern.kindCode == KindCode::none) {
3455 break;
3456 }
3457 d.Dump(o << sep);
3458 sep = ',';
3459 }
3460 if (sep == '(') {
3461 o << "()";
3462 }
3463 return result.Dump(o << " -> ") << ' ' << EnumToString(rank);
3464 }
3465
3466 llvm::raw_ostream &IntrinsicProcTable::Implementation::Dump(
3467 llvm::raw_ostream &o) const {
3468 o << "generic intrinsic functions:\n";
3469 for (const auto &iter : genericFuncs_) {
3470 iter.second->Dump(o << iter.first << ": ") << '\n';
3471 }
3472 o << "specific intrinsic functions:\n";
3473 for (const auto &iter : specificFuncs_) {
3474 iter.second->Dump(o << iter.first << ": ");
3475 if (const char *g{iter.second->generic}) {
3476 o << " -> " << g;
3477 }
3478 o << '\n';
3479 }
3480 o << "subroutines:\n";
3481 for (const auto &iter : subroutines_) {
3482 iter.second->Dump(o << iter.first << ": ") << '\n';
3483 }
3484 return o;
3485 }
3486
3487 llvm::raw_ostream &IntrinsicProcTable::Dump(llvm::raw_ostream &o) const {
3488 return DEREF(impl_.get()).Dump(o);
3489 }
3490
3491 // In general C846 prohibits allocatable coarrays to be passed to INTENT(OUT)
3492 // dummy arguments. This rule does not apply to intrinsics in general.
3493 // Some intrinsic explicitly allow coarray allocatable in their description.
3494 // It is assumed that unless explicitly allowed for an intrinsic,
3495 // this is forbidden.
3496 // Since there are very few intrinsic identified that allow this, they are
3497 // listed here instead of adding a field in the table.
3498 bool AcceptsIntentOutAllocatableCoarray(const std::string &intrinsic) {
3499 return intrinsic == "move_alloc";
3500 }
3501 } // namespace Fortran::evaluate