FLANG
IntrinsicCall.h
1//===-- Builder/IntrinsicCall.h -- lowering of intrinsics -------*- C++ -*-===//
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#ifndef FORTRAN_LOWER_INTRINSICCALL_H
10#define FORTRAN_LOWER_INTRINSICCALL_H
11
12#include "flang/Optimizer/Builder/BoxValue.h"
13#include "flang/Optimizer/Builder/FIRBuilder.h"
14#include "flang/Optimizer/Builder/Runtime/Character.h"
15#include "flang/Optimizer/Builder/Runtime/Numeric.h"
17#include "flang/Runtime/entry-names.h"
18#include "flang/Runtime/iostat-consts.h"
19#include "mlir/Dialect/Complex/IR/Complex.h"
20#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
21#include "mlir/Dialect/Math/IR/Math.h"
22#include <optional>
23
24namespace Fortran {
25namespace lower {
26// TODO: remove the usage of AbstractConverter to avoid making IntrinsicCall.cpp
27// depend upon Lower/Evaluate and use a data structure to pass options to
28// IntrinsicLibrary.
30} // namespace lower
31} // namespace Fortran
32
33namespace fir {
34
35class StatementContext;
37
43std::pair<fir::ExtendedValue, bool>
44genIntrinsicCall(fir::FirOpBuilder &, mlir::Location, llvm::StringRef name,
45 std::optional<mlir::Type> resultType,
46 llvm::ArrayRef<fir::ExtendedValue> args,
47 Fortran::lower::AbstractConverter *converter = nullptr);
48
52std::pair<fir::ExtendedValue, bool>
53genIntrinsicCall(fir::FirOpBuilder &, mlir::Location,
55 std::optional<mlir::Type> resultType,
56 llvm::ArrayRef<fir::ExtendedValue> args,
57 Fortran::lower::AbstractConverter *converter = nullptr);
58
60enum class Extremum { Min, Max };
61
62// There are different ways to deal with NaNs in MIN and MAX.
63// Known existing behaviors are listed below and can be selected for
64// f18 MIN/MAX implementation.
65enum class ExtremumBehavior {
66 // Note: the Signaling/quiet aspect of NaNs in the behaviors below are
67 // not described because there is no way to control/observe such aspect in
68 // MLIR/LLVM yet. The IEEE behaviors come with requirements regarding this
69 // aspect that are therefore currently not enforced. In the descriptions
70 // below, NaNs can be signaling or quite. Returned NaNs may be signaling
71 // if one of the input NaN was signaling but it cannot be guaranteed either.
72 // Existing compilers using an IEEE behavior (gfortran) also do not fulfill
73 // signaling/quiet requirements.
74 IeeeMinMaximumNumber,
75 // IEEE minimumNumber/maximumNumber behavior (754-2019, section 9.6):
76 // If one of the argument is and number and the other is NaN, return the
77 // number. If both arguements are NaN, return NaN.
78 // Compilers: gfortran.
79 IeeeMinMaximum,
80 // IEEE minimum/maximum behavior (754-2019, section 9.6):
81 // If one of the argument is NaN, return NaN.
82 MinMaxss,
83 // x86 minss/maxss behavior:
84 // If the second argument is a number and the other is NaN, return the number.
85 // In all other cases where at least one operand is NaN, return NaN.
86 // Compilers: xlf (only for MAX), ifort, pgfortran -nollvm, and nagfor.
87 PgfortranLlvm,
88 // "Opposite of" x86 minss/maxss behavior:
89 // If the first argument is a number and the other is NaN, return the
90 // number.
91 // In all other cases where at least one operand is NaN, return NaN.
92 // Compilers: xlf (only for MIN), and pgfortran (with llvm).
93 IeeeMinMaxNum
94 // IEEE minNum/maxNum behavior (754-2008, section 5.3.1):
95 // TODO: Not implemented.
96 // It is the only behavior where the signaling/quiet aspect of a NaN argument
97 // impacts if the result should be NaN or the argument that is a number.
98 // LLVM/MLIR do not provide ways to observe this aspect, so it is not
99 // possible to implement it without some target dependent runtime.
100};
101
117
120 LowerIntrinsicArgAs lowerAs;
122 // - Numerical: 0
123 // - Logical : false
124 // - Derived/character: not possible. Need custom intrinsic lowering.
125 // Addr:
126 // - nullptr
127 // Box:
128 // - absent box
129 // AsInquired:
130 // - no-op
132};
133
134constexpr auto asValue = fir::LowerIntrinsicArgAs::Value;
135constexpr auto asAddr = fir::LowerIntrinsicArgAs::Addr;
136constexpr auto asBox = fir::LowerIntrinsicArgAs::Box;
137constexpr auto asInquired = fir::LowerIntrinsicArgAs::Inquired;
138
142
143// TODO error handling -> return a code or directly emit messages ?
144struct IntrinsicLibrary {
145
146 // Constructors.
147 explicit IntrinsicLibrary(
148 fir::FirOpBuilder &builder, mlir::Location loc,
149 Fortran::lower::AbstractConverter *converter = nullptr)
150 : builder{builder}, loc{loc}, converter{converter} {}
151 IntrinsicLibrary() = delete;
152 IntrinsicLibrary(const IntrinsicLibrary &) = delete;
153
157 std::pair<fir::ExtendedValue, bool>
158 genIntrinsicCall(llvm::StringRef name, std::optional<mlir::Type> resultType,
160
168 mlir::Value genRuntimeCall(llvm::StringRef name, mlir::Type,
170
171 using RuntimeCallGenerator = std::function<mlir::Value(
173 RuntimeCallGenerator
174 getRuntimeCallGenerator(llvm::StringRef name,
175 mlir::FunctionType soughtFuncType);
176
182 mlir::Value genAbs(mlir::Type, llvm::ArrayRef<mlir::Value>);
183 mlir::Value genAcosd(mlir::Type, llvm::ArrayRef<mlir::Value>);
184 mlir::Value genAcospi(mlir::Type, llvm::ArrayRef<mlir::Value>);
185 template <void (*CallRuntime)(fir::FirOpBuilder &, mlir::Location loc,
186 mlir::Value, mlir::Value)>
187 fir::ExtendedValue genAdjustRtCall(mlir::Type,
189 mlir::Value genAimag(mlir::Type, llvm::ArrayRef<mlir::Value>);
190 mlir::Value genAint(mlir::Type, llvm::ArrayRef<mlir::Value>);
192 fir::ExtendedValue genAllocated(mlir::Type,
194 mlir::Value genAnint(mlir::Type, llvm::ArrayRef<mlir::Value>);
196 mlir::Value genAtanpi(mlir::Type, llvm::ArrayRef<mlir::Value>);
198 genCommandArgumentCount(mlir::Type, llvm::ArrayRef<fir::ExtendedValue>);
199 mlir::Value genAsind(mlir::Type, llvm::ArrayRef<mlir::Value>);
200 mlir::Value genAsinpi(mlir::Type, llvm::ArrayRef<mlir::Value>);
201 fir::ExtendedValue genAssociated(mlir::Type,
203 mlir::Value genAtand(mlir::Type, llvm::ArrayRef<mlir::Value>);
204 fir::ExtendedValue genBesselJn(mlir::Type,
206 fir::ExtendedValue genBesselYn(mlir::Type,
208 template <mlir::arith::CmpIPredicate pred>
209 mlir::Value genBitwiseCompare(mlir::Type resultType,
211
212 mlir::Value genBtest(mlir::Type, llvm::ArrayRef<mlir::Value>);
213 mlir::Value genCeiling(mlir::Type, llvm::ArrayRef<mlir::Value>);
215 fir::ExtendedValue genChdir(std::optional<mlir::Type> resultType,
217 template <mlir::arith::CmpIPredicate pred>
218 fir::ExtendedValue genCharacterCompare(mlir::Type,
220 mlir::Value genCmplx(mlir::Type, llvm::ArrayRef<mlir::Value>);
221 mlir::Value genConjg(mlir::Type, llvm::ArrayRef<mlir::Value>);
223 void genCpuTime(llvm::ArrayRef<fir::ExtendedValue>);
230 mlir::Value genErfcScaled(mlir::Type resultType,
232 void genCFPointer(llvm::ArrayRef<fir::ExtendedValue>);
233 void genCFProcPointer(llvm::ArrayRef<fir::ExtendedValue>);
236 template <mlir::arith::CmpIPredicate pred>
237 fir::ExtendedValue genCPtrCompare(mlir::Type,
239 void genCoBroadcast(llvm::ArrayRef<fir::ExtendedValue>);
243 mlir::Value genCosd(mlir::Type, llvm::ArrayRef<mlir::Value>);
244 mlir::Value genCospi(mlir::Type, llvm::ArrayRef<mlir::Value>);
245 void genDateAndTime(llvm::ArrayRef<fir::ExtendedValue>);
246 fir::ExtendedValue genDsecnds(mlir::Type resultType,
248 mlir::Value genDim(mlir::Type, llvm::ArrayRef<mlir::Value>);
249 fir::ExtendedValue genDotProduct(mlir::Type,
251 mlir::Value genDprod(mlir::Type, llvm::ArrayRef<mlir::Value>);
252 mlir::Value genDshiftl(mlir::Type, llvm::ArrayRef<mlir::Value>);
253 mlir::Value genDshiftr(mlir::Type, llvm::ArrayRef<mlir::Value>);
256 void genExecuteCommandLine(mlir::ArrayRef<fir::ExtendedValue> args);
257 fir::ExtendedValue genEtime(std::optional<mlir::Type>,
258 mlir::ArrayRef<fir::ExtendedValue> args);
259 mlir::Value genExponent(mlir::Type, llvm::ArrayRef<mlir::Value>);
260 fir::ExtendedValue genExtendsTypeOf(mlir::Type,
262 template <Extremum, ExtremumBehavior>
263 mlir::Value genExtremum(mlir::Type, llvm::ArrayRef<mlir::Value>);
264 mlir::Value genFloor(mlir::Type, llvm::ArrayRef<mlir::Value>);
266 mlir::Value genFraction(mlir::Type resultType,
267 mlir::ArrayRef<mlir::Value> args);
268 void genFree(mlir::ArrayRef<fir::ExtendedValue> args);
269 fir::ExtendedValue genFseek(std::optional<mlir::Type>,
270 mlir::ArrayRef<fir::ExtendedValue> args);
271 fir::ExtendedValue genFtell(std::optional<mlir::Type>,
272 mlir::ArrayRef<fir::ExtendedValue> args);
273 fir::ExtendedValue genGetCwd(std::optional<mlir::Type> resultType,
275 void genGetCommand(mlir::ArrayRef<fir::ExtendedValue> args);
276 mlir::Value genGetPID(mlir::Type resultType,
278 void genGetCommandArgument(mlir::ArrayRef<fir::ExtendedValue> args);
279 void genGetEnvironmentVariable(llvm::ArrayRef<fir::ExtendedValue>);
280 mlir::Value genGetGID(mlir::Type resultType,
282 mlir::Value genGetTeam(mlir::Type, llvm::ArrayRef<mlir::Value>);
283 mlir::Value genGetUID(mlir::Type resultType,
285 fir::ExtendedValue genHostnm(std::optional<mlir::Type> resultType,
288 mlir::Value genIand(mlir::Type, llvm::ArrayRef<mlir::Value>);
290 mlir::Value genIbclr(mlir::Type, llvm::ArrayRef<mlir::Value>);
291 mlir::Value genIbits(mlir::Type, llvm::ArrayRef<mlir::Value>);
292 mlir::Value genIbset(mlir::Type, llvm::ArrayRef<mlir::Value>);
295 mlir::Value genIeeeClass(mlir::Type, llvm::ArrayRef<mlir::Value>);
296 mlir::Value genIeeeCopySign(mlir::Type, llvm::ArrayRef<mlir::Value>);
297 void genIeeeGetFlag(llvm::ArrayRef<fir::ExtendedValue>);
298 void genIeeeGetHaltingMode(llvm::ArrayRef<fir::ExtendedValue>);
299 template <bool isGet, bool isModes>
300 void genIeeeGetOrSetModesOrStatus(llvm::ArrayRef<fir::ExtendedValue>);
301 void genIeeeGetRoundingMode(llvm::ArrayRef<fir::ExtendedValue>);
302 void genIeeeGetUnderflowMode(llvm::ArrayRef<fir::ExtendedValue>);
303 mlir::Value genIeeeInt(mlir::Type, llvm::ArrayRef<mlir::Value>);
304 mlir::Value genIeeeIsFinite(mlir::Type, llvm::ArrayRef<mlir::Value>);
305 mlir::Value genIeeeIsNan(mlir::Type, llvm::ArrayRef<mlir::Value>);
306 mlir::Value genIeeeIsNegative(mlir::Type, llvm::ArrayRef<mlir::Value>);
307 mlir::Value genIeeeIsNormal(mlir::Type, llvm::ArrayRef<mlir::Value>);
308 mlir::Value genIeeeLogb(mlir::Type, mlir::ArrayRef<mlir::Value>);
309 template <bool isMax, bool isNum, bool isMag>
310 mlir::Value genIeeeMaxMin(mlir::Type, llvm::ArrayRef<mlir::Value>);
311 template <mlir::arith::CmpFPredicate pred>
312 mlir::Value genIeeeQuietCompare(mlir::Type resultType,
314 mlir::Value genIeeeReal(mlir::Type, llvm::ArrayRef<mlir::Value>);
315 mlir::Value genIeeeRem(mlir::Type, llvm::ArrayRef<mlir::Value>);
316 mlir::Value genIeeeRint(mlir::Type, llvm::ArrayRef<mlir::Value>);
317 template <bool isFlag>
318 void genIeeeSetFlagOrHaltingMode(llvm::ArrayRef<fir::ExtendedValue>);
319 void genIeeeSetRoundingMode(llvm::ArrayRef<fir::ExtendedValue>);
320 void genIeeeSetUnderflowMode(llvm::ArrayRef<fir::ExtendedValue>);
321 template <mlir::arith::CmpFPredicate pred>
322 mlir::Value genIeeeSignalingCompare(mlir::Type resultType,
324 mlir::Value genIeeeSignbit(mlir::Type, llvm::ArrayRef<mlir::Value>);
325 fir::ExtendedValue genIeeeSupportFlag(mlir::Type,
327 fir::ExtendedValue genIeeeSupportHalting(mlir::Type,
329 fir::ExtendedValue genIeeeSupportRounding(mlir::Type,
331 fir::ExtendedValue genIeeeSupportStandard(mlir::Type,
333 template <mlir::arith::CmpIPredicate pred>
334 mlir::Value genIeeeTypeCompare(mlir::Type, llvm::ArrayRef<mlir::Value>);
335 mlir::Value genIeeeUnordered(mlir::Type, llvm::ArrayRef<mlir::Value>);
336 mlir::Value genIeeeValue(mlir::Type, llvm::ArrayRef<mlir::Value>);
337 mlir::Value genIeor(mlir::Type, llvm::ArrayRef<mlir::Value>);
339 mlir::Value genIor(mlir::Type, llvm::ArrayRef<mlir::Value>);
341 fir::ExtendedValue genIrand(mlir::Type resultType,
343 fir::ExtendedValue genIsContiguous(mlir::Type,
345 template <Fortran::runtime::io::Iostat value>
346 mlir::Value genIsIostatValue(mlir::Type, llvm::ArrayRef<mlir::Value>);
347 mlir::Value genIsFPClass(mlir::Type, llvm::ArrayRef<mlir::Value>,
348 int fpclass);
349 mlir::Value genIshft(mlir::Type, llvm::ArrayRef<mlir::Value>);
350 mlir::Value genIshftc(mlir::Type, llvm::ArrayRef<mlir::Value>);
352 mlir::Value genLeadz(mlir::Type, llvm::ArrayRef<mlir::Value>);
356 mlir::Value genMalloc(mlir::Type, llvm::ArrayRef<mlir::Value>);
357 template <typename Shift>
358 mlir::Value genMask(mlir::Type, llvm::ArrayRef<mlir::Value>);
360 fir::ExtendedValue genMatmulTranspose(mlir::Type,
365 mlir::Value genMergeBits(mlir::Type, llvm::ArrayRef<mlir::Value>);
368 mlir::Value genMod(mlir::Type, llvm::ArrayRef<mlir::Value>);
369 mlir::Value genModulo(mlir::Type, llvm::ArrayRef<mlir::Value>);
370 void genMoveAlloc(llvm::ArrayRef<fir::ExtendedValue>);
372 enum class NearestProc { Nearest, NextAfter, NextDown, NextUp };
373 template <NearestProc>
374 mlir::Value genNearest(mlir::Type, llvm::ArrayRef<mlir::Value>);
375 mlir::Value genNint(mlir::Type, llvm::ArrayRef<mlir::Value>);
377 mlir::Value genNot(mlir::Type, llvm::ArrayRef<mlir::Value>);
379 fir::ExtendedValue genNumImages(mlir::Type,
384 mlir::Value genPopcnt(mlir::Type, llvm::ArrayRef<mlir::Value>);
385 mlir::Value genPoppar(mlir::Type, llvm::ArrayRef<mlir::Value>);
388 fir::ExtendedValue genPutenv(std::optional<mlir::Type>,
390 fir::ExtendedValue genRand(mlir::Type resultType,
392 void genRandomInit(llvm::ArrayRef<fir::ExtendedValue>);
393 void genRandomNumber(llvm::ArrayRef<fir::ExtendedValue>);
394 void genRandomSeed(llvm::ArrayRef<fir::ExtendedValue>);
396 fir::ExtendedValue genReduceDim(mlir::Type,
398 fir::ExtendedValue genRename(std::optional<mlir::Type>,
399 mlir::ArrayRef<fir::ExtendedValue>);
402 mlir::Value genRRSpacing(mlir::Type resultType,
404 fir::ExtendedValue genSameTypeAs(mlir::Type,
406 mlir::Value genScale(mlir::Type, llvm::ArrayRef<mlir::Value>);
408 fir::ExtendedValue genSecnds(mlir::Type resultType,
410 fir::ExtendedValue genSecond(std::optional<mlir::Type>,
411 mlir::ArrayRef<fir::ExtendedValue>);
412 fir::ExtendedValue genSelectedCharKind(mlir::Type,
414 mlir::Value genSelectedIntKind(mlir::Type, llvm::ArrayRef<mlir::Value>);
415 mlir::Value genSelectedLogicalKind(mlir::Type, llvm::ArrayRef<mlir::Value>);
416 mlir::Value genSelectedRealKind(mlir::Type, llvm::ArrayRef<mlir::Value>);
417 mlir::Value genSetExponent(mlir::Type resultType,
419 fir::ExtendedValue genShape(mlir::Type resultType,
421 template <typename Shift>
422 mlir::Value genShift(mlir::Type resultType, llvm::ArrayRef<mlir::Value>);
423 mlir::Value genShiftA(mlir::Type resultType, llvm::ArrayRef<mlir::Value>);
424 void genShowDescriptor(llvm::ArrayRef<fir::ExtendedValue>);
425 mlir::Value genSign(mlir::Type, llvm::ArrayRef<mlir::Value>);
426 mlir::Value genSind(mlir::Type, llvm::ArrayRef<mlir::Value>);
427 mlir::Value genSinpi(mlir::Type, llvm::ArrayRef<mlir::Value>);
430 mlir::Value genSpacing(mlir::Type resultType,
433 fir::ExtendedValue genStorageSize(mlir::Type,
436 void genSignalSubroutine(llvm::ArrayRef<fir::ExtendedValue>);
438 fir::ExtendedValue genSystem(std::optional<mlir::Type>,
439 mlir::ArrayRef<fir::ExtendedValue> args);
440 void genSystemClock(llvm::ArrayRef<fir::ExtendedValue>);
441 mlir::Value genTand(mlir::Type, llvm::ArrayRef<mlir::Value>);
442 mlir::Value genTanpi(mlir::Type, llvm::ArrayRef<mlir::Value>);
443 fir::ExtendedValue genTeamNumber(mlir::Type,
445 mlir::Value genTime(mlir::Type, llvm::ArrayRef<mlir::Value>);
446 mlir::Value genTrailz(mlir::Type, llvm::ArrayRef<mlir::Value>);
447 fir::ExtendedValue genTransfer(mlir::Type,
449 fir::ExtendedValue genTranspose(mlir::Type,
451 fir::ExtendedValue genThisImage(mlir::Type,
455 fir::ExtendedValue genUnlink(std::optional<mlir::Type> resultType,
459
463 mlir::Value genConversion(mlir::Type, llvm::ArrayRef<mlir::Value>);
464
470 template <typename FN, typename FD>
471 fir::ExtendedValue genExtremumloc(FN func, FD funcDim, llvm::StringRef errMsg,
472 mlir::Type,
474 template <typename FN, typename FD, typename FC>
476 fir::ExtendedValue genExtremumVal(FN func, FD funcDim, FC funcChar,
477 llvm::StringRef errMsg,
478 mlir::Type resultType,
481 template <typename FN, typename FD>
482 fir::ExtendedValue genReduction(FN func, FD funcDim, llvm::StringRef errMsg,
483 mlir::Type resultType,
485
488 void genRaiseExcept(int excepts, mlir::Value cond = {});
489
491 mlir::Value genQNan(mlir::Type resultType);
492
496 using ExtendedGenerator = decltype(&IntrinsicLibrary::genLenTrim);
497 using SubroutineGenerator = decltype(&IntrinsicLibrary::genDateAndTime);
499 using DualGenerator = decltype(&IntrinsicLibrary::genEtime);
500 using Generator = std::variant<ElementalGenerator, ExtendedGenerator,
501 SubroutineGenerator, DualGenerator>;
502
509 template <typename GeneratorType>
510 mlir::Value outlineInWrapper(GeneratorType, llvm::StringRef name,
511 mlir::Type resultType,
513 template <typename GeneratorType>
515 outlineInExtendedWrapper(GeneratorType, llvm::StringRef name,
516 std::optional<mlir::Type> resultType,
518
519 template <typename GeneratorType>
520 mlir::func::FuncOp getWrapper(GeneratorType, llvm::StringRef name,
521 mlir::FunctionType,
522 bool loadRefArguments = false);
523
525 template <typename GeneratorType>
527 genElementalCall(GeneratorType, llvm::StringRef name, mlir::Type resultType,
528 llvm::ArrayRef<fir::ExtendedValue> args, bool outline);
529
531 mlir::Value invokeGenerator(ElementalGenerator generator,
532 mlir::Type resultType,
534 mlir::Value invokeGenerator(RuntimeCallGenerator generator,
535 mlir::Type resultType,
537 mlir::Value invokeGenerator(ExtendedGenerator generator,
538 mlir::Type resultType,
540 mlir::Value invokeGenerator(SubroutineGenerator generator,
542 mlir::Value invokeGenerator(DualGenerator generator,
544 mlir::Value invokeGenerator(DualGenerator generator, mlir::Type resultType,
546
549 mlir::SymbolRefAttr
550 getUnrestrictedIntrinsicSymbolRefAttr(llvm::StringRef name,
551 mlir::FunctionType signature);
552
555 mlir::Type resultType,
556 llvm::StringRef errMsg);
557
558 void setResultMustBeFreed() { resultMustBeFreed = true; }
559
560 fir::FirOpBuilder &builder;
561 mlir::Location loc;
562 bool resultMustBeFreed = false;
563 Fortran::lower::AbstractConverter *converter = nullptr;
564};
565
567 const char *name = nullptr;
569 bool handleDynamicOptional = false;
570};
571
576 constexpr bool hasDefaultRules() const { return args[0].name == nullptr; }
577};
578
582 const char *name;
583 IntrinsicLibrary::Generator generator;
584 // The following may be omitted in the table below.
585 fir::IntrinsicArgumentLoweringRules argLoweringRules = {};
586 bool isElemental = true;
589 bool outline = false;
590};
591
593 // llvm::StringRef comparison operator are not constexpr, so use string_view.
594 using Key = std::string_view;
595 // Needed for implicit compare with keys.
596 constexpr operator Key() const { return key; }
597 Key key; // intrinsic name
598
599 // Name of a runtime function that implements the operation.
600 llvm::StringRef symbol;
601 fir::runtime::FuncTypeBuilderFunc typeGenerator;
602};
603
605 // Callback type for generating lowering for a math operation.
606 using MathGeneratorTy = mlir::Value (*)(fir::FirOpBuilder &, mlir::Location,
607 const MathOperation &,
608 mlir::FunctionType,
610
611 // Overrides fir::runtime::FuncTypeBuilderFunc to add FirOpBuilder argument.
612 using FuncTypeBuilderFunc = mlir::FunctionType (*)(mlir::MLIRContext *,
614
615 // llvm::StringRef comparison operator are not constexpr, so use string_view.
616 using Key = std::string_view;
617 // Needed for implicit compare with keys.
618 constexpr operator Key() const { return key; }
619 // Intrinsic name.
620 Key key;
621
622 // Name of a runtime function that implements the operation.
623 llvm::StringRef runtimeFunc;
624 FuncTypeBuilderFunc typeGenerator;
625
626 // A callback to generate FIR for the intrinsic defined by 'key'.
627 // A callback may generate either dedicated MLIR operation(s) or
628 // a function call to a runtime function with name defined by
629 // 'runtimeFunc'.
630 MathGeneratorTy funcGenerator;
631};
632
633// Enum of most supported intrinsic argument or return types.
634enum class ParamTypeId {
635 Void,
636 Address, // pointer (to an [array of] Integers of some kind)
637 Integer,
638 Real,
639 Complex,
640 IntegerVector,
641 UnsignedVector,
642 RealVector,
643};
644
645// Helper function to get length of a 16-byte vector of element type eleTy.
646static int getVecLen(mlir::Type eleTy) {
647 assert((mlir::isa<mlir::IntegerType>(eleTy) ||
648 mlir::isa<mlir::FloatType>(eleTy)) &&
649 "unsupported vector element type");
650 return 16 / (eleTy.getIntOrFloatBitWidth() / 8);
651}
652
653template <ParamTypeId t, int k>
654struct ParamType {
655 // Supported kinds can be checked with static asserts at compile time.
656 static_assert(t != ParamTypeId::Integer || k == 1 || k == 2 || k == 4 ||
657 k == 8,
658 "Unsupported integer kind");
659 static_assert(t != ParamTypeId::Real || k == 4 || k == 8 || k == 10 ||
660 k == 16,
661 "Unsupported real kind");
662 static_assert(t != ParamTypeId::Complex || k == 2 || k == 3 || k == 4 ||
663 k == 8 || k == 10 || k == 16,
664 "Unsupported complex kind");
665
666 static const ParamTypeId ty = t;
667 static const int kind = k;
668};
669
670// Namespace encapsulating type definitions for parameter types.
671namespace Ty {
673template <int k>
675template <int k>
677template <int k>
679template <int k>
681template <int k>
682using IntegerVector = ParamType<ParamTypeId::IntegerVector, k>;
683template <int k>
684using UnsignedVector = ParamType<ParamTypeId::UnsignedVector, k>;
685template <int k>
687} // namespace Ty
688
689// Helper function that generates most types that are supported for intrinsic
690// arguments and return type. Used by `genFuncType` to generate function
691// types for most of the intrinsics.
692static inline mlir::Type getTypeHelper(mlir::MLIRContext *context,
693 fir::FirOpBuilder &builder,
694 ParamTypeId typeId, int kind) {
695 mlir::Type r;
696 unsigned bits{0};
697 switch (typeId) {
698 case ParamTypeId::Void:
699 llvm::report_fatal_error("can not get type of void");
700 break;
701 case ParamTypeId::Address:
702 bits = builder.getKindMap().getIntegerBitsize(kind);
703 assert(bits != 0 && "failed to convert address kind to integer bitsize");
704 r = fir::ReferenceType::get(mlir::IntegerType::get(context, bits));
705 break;
706 case ParamTypeId::Integer:
707 case ParamTypeId::IntegerVector:
708 bits = builder.getKindMap().getIntegerBitsize(kind);
709 assert(bits != 0 && "failed to convert kind to integer bitsize");
710 r = mlir::IntegerType::get(context, bits);
711 break;
712 case ParamTypeId::UnsignedVector:
713 bits = builder.getKindMap().getIntegerBitsize(kind);
714 assert(bits != 0 && "failed to convert kind to unsigned bitsize");
715 r = mlir::IntegerType::get(context, bits, mlir::IntegerType::Unsigned);
716 break;
717 case ParamTypeId::Real:
718 case ParamTypeId::RealVector:
719 r = builder.getRealType(kind);
720 break;
721 case ParamTypeId::Complex:
722 r = mlir::ComplexType::get(builder.getRealType(kind));
723 break;
724 }
725
726 switch (typeId) {
727 case ParamTypeId::Void:
728 case ParamTypeId::Address:
729 case ParamTypeId::Integer:
730 case ParamTypeId::Real:
731 case ParamTypeId::Complex:
732 break;
733 case ParamTypeId::IntegerVector:
734 case ParamTypeId::UnsignedVector:
735 case ParamTypeId::RealVector:
736 // convert to vector type
737 r = fir::VectorType::get(getVecLen(r), r);
738 }
739 return r;
740}
741
742// Generic function type generator that supports most of the function types
743// used by intrinsics.
744template <typename TyR, typename... ArgTys>
745static inline mlir::FunctionType genFuncType(mlir::MLIRContext *context,
746 fir::FirOpBuilder &builder) {
747 llvm::SmallVector<ParamTypeId> argTys = {ArgTys::ty...};
748 llvm::SmallVector<int> argKinds = {ArgTys::kind...};
749 llvm::SmallVector<mlir::Type> argTypes;
750
751 for (size_t i = 0; i < argTys.size(); ++i) {
752 argTypes.push_back(getTypeHelper(context, builder, argTys[i], argKinds[i]));
753 }
754
755 if (TyR::ty == ParamTypeId::Void)
756 return mlir::FunctionType::get(context, argTypes, {});
757
758 auto resType = getTypeHelper(context, builder, TyR::ty, TyR::kind);
759 return mlir::FunctionType::get(context, argTypes, {resType});
760}
761
763struct IntrinsicHandlerEntry {
764 using RuntimeGeneratorRange =
765 std::pair<const MathOperation *, const MathOperation *>;
766 IntrinsicHandlerEntry(const IntrinsicHandler *handler) : entry{handler} {
767 assert(handler && "handler must not be nullptr");
768 };
769 IntrinsicHandlerEntry(RuntimeGeneratorRange rt) : entry{rt} {};
770 const IntrinsicArgumentLoweringRules *getArgumentLoweringRules() const;
771 std::variant<const IntrinsicHandler *, RuntimeGeneratorRange> entry;
772};
773
774//===----------------------------------------------------------------------===//
775// Helper functions for argument handling.
776//===----------------------------------------------------------------------===//
777static inline mlir::Type getConvertedElementType(mlir::MLIRContext *context,
778 mlir::Type eleTy) {
779 if (mlir::isa<mlir::IntegerType>(eleTy) && !eleTy.isSignlessInteger()) {
780 const auto intTy{mlir::dyn_cast<mlir::IntegerType>(eleTy)};
781 auto newEleTy{mlir::IntegerType::get(context, intTy.getWidth())};
782 return newEleTy;
783 }
784 return eleTy;
785}
786
787static inline llvm::SmallVector<mlir::Value, 4>
788getBasesForArgs(llvm::ArrayRef<fir::ExtendedValue> args) {
789 llvm::SmallVector<mlir::Value, 4> baseVec;
790 for (auto arg : args)
791 baseVec.push_back(getBase(arg));
792 return baseVec;
793}
794
795static inline llvm::SmallVector<mlir::Type, 4>
796getTypesForArgs(llvm::ArrayRef<mlir::Value> args) {
797 llvm::SmallVector<mlir::Type, 4> typeVec;
798 for (auto arg : args)
799 typeVec.push_back(arg.getType());
800 return typeVec;
801}
802
803mlir::Value genLibCall(fir::FirOpBuilder &builder, mlir::Location loc,
804 const MathOperation &mathOp,
805 mlir::FunctionType libFuncType,
806 llvm::ArrayRef<mlir::Value> args);
807
808template <typename T>
809mlir::Value genMathOp(fir::FirOpBuilder &builder, mlir::Location loc,
810 const MathOperation &mathOp,
811 mlir::FunctionType mathLibFuncType,
812 llvm::ArrayRef<mlir::Value> args);
813
814template <typename T>
815mlir::Value genComplexMathOp(fir::FirOpBuilder &builder, mlir::Location loc,
816 const MathOperation &mathOp,
817 mlir::FunctionType mathLibFuncType,
818 llvm::ArrayRef<mlir::Value> args);
819
820mlir::Value genLibSplitComplexArgsCall(fir::FirOpBuilder &builder,
821 mlir::Location loc,
822 const MathOperation &mathOp,
823 mlir::FunctionType libFuncType,
824 llvm::ArrayRef<mlir::Value> args);
825
828std::optional<IntrinsicHandlerEntry>
829lookupIntrinsicHandler(fir::FirOpBuilder &, llvm::StringRef intrinsicName,
830 std::optional<mlir::Type> resultType);
831
833void crashOnMissingIntrinsic(mlir::Location loc, llvm::StringRef name);
834
838getIntrinsicArgumentLowering(llvm::StringRef intrinsicName);
839
843 unsigned position);
844
846fir::ExtendedValue getAbsentIntrinsicArgument();
847
849// implementation) of an unrestricted intrinsic (defined by its signature
850// and generic name)
851mlir::SymbolRefAttr
852getUnrestrictedIntrinsicSymbolRefAttr(fir::FirOpBuilder &, mlir::Location,
853 llvm::StringRef name,
854 mlir::FunctionType signature);
855
856//===----------------------------------------------------------------------===//
857// Direct access to intrinsics that may be used by lowering outside
858// of intrinsic call lowering.
859//===----------------------------------------------------------------------===//
860
863mlir::Value genMax(fir::FirOpBuilder &, mlir::Location,
864 llvm::ArrayRef<mlir::Value> args);
865
867mlir::Value genMin(fir::FirOpBuilder &, mlir::Location,
868 llvm::ArrayRef<mlir::Value> args);
869
872mlir::Value genDivC(fir::FirOpBuilder &builder, mlir::Location loc,
873 mlir::Type resultType, mlir::Value x, mlir::Value y);
874
877mlir::Value genPow(fir::FirOpBuilder &, mlir::Location, mlir::Type resultType,
878 mlir::Value x, mlir::Value y);
879
880} // namespace fir
881
882#endif // FORTRAN_LOWER_INTRINSICCALL_H
Definition AbstractConverter.h:87
Definition BoxValue.h:478
Definition FIRBuilder.h:55
const fir::KindMapping & getKindMap()
Get a reference to the kind map.
Definition FIRBuilder.h:122
mlir::Type getRealType(int kind)
Get the mlir float type that implements Fortran REAL(kind).
Definition FIRBuilder.cpp:118
Bitsize getIntegerBitsize(KindTy kind) const
Get the size in bits of !fir.int<kind>
Definition KindMapping.cpp:283
Definition BoxValue.h:360
Definition FIRType.h:92
Definition ParserActions.h:24
Definition bit-population-count.h:20
Definition AbstractConverter.h:37
std::optional< IntrinsicHandlerEntry > lookupIntrinsicHandler(fir::FirOpBuilder &, llvm::StringRef intrinsicName, std::optional< mlir::Type > resultType)
Definition IntrinsicCall.cpp:1869
Extremum
Enums used to templatize and share lowering of MIN and MAX.
Definition IntrinsicCall.h:60
const IntrinsicArgumentLoweringRules * getIntrinsicArgumentLowering(llvm::StringRef intrinsicName)
Definition IntrinsicCall.cpp:8882
mlir::Value getBase(const ExtendedValue &exv)
Definition BoxValue.cpp:21
mlir::Value genMin(fir::FirOpBuilder &, mlir::Location, llvm::ArrayRef< mlir::Value > args)
Generate minimum. Same constraints as genMax.
Definition IntrinsicCall.cpp:8939
mlir::Value genPow(fir::FirOpBuilder &, mlir::Location, mlir::Type resultType, mlir::Value x, mlir::Value y)
Definition IntrinsicCall.cpp:8952
mlir::Value genDivC(fir::FirOpBuilder &builder, mlir::Location loc, mlir::Type resultType, mlir::Value x, mlir::Value y)
Definition IntrinsicCall.cpp:8947
fir::ExtendedValue getAbsentIntrinsicArgument()
Return place-holder for absent intrinsic arguments.
Definition IntrinsicCall.cpp:80
void crashOnMissingIntrinsic(mlir::Location loc, llvm::StringRef name)
Generate a TODO error message for an as yet unimplemented intrinsic.
Definition IntrinsicCall.cpp:1894
ArgLoweringRule lowerIntrinsicArgumentAs(const IntrinsicArgumentLoweringRules &, unsigned position)
Definition IntrinsicCall.cpp:8910
mlir::SymbolRefAttr getUnrestrictedIntrinsicSymbolRefAttr(fir::FirOpBuilder &, mlir::Location, llvm::StringRef name, mlir::FunctionType signature)
Get SymbolRefAttr of runtime (or wrapper function containing inlined.
Definition IntrinsicCall.cpp:8973
LowerIntrinsicArgAs
Definition IntrinsicCall.h:104
@ Addr
Definition IntrinsicCall.h:109
@ Inquired
Definition IntrinsicCall.h:115
@ Box
Lower argument to a box.
Definition IntrinsicCall.h:111
@ Value
Lower argument to a value. Mainly intended for scalar arguments.
Definition IntrinsicCall.h:106
std::pair< fir::ExtendedValue, bool > genIntrinsicCall(fir::FirOpBuilder &, mlir::Location, llvm::StringRef name, std::optional< mlir::Type > resultType, llvm::ArrayRef< fir::ExtendedValue > args, Fortran::lower::AbstractConverter *converter=nullptr)
Definition IntrinsicCall.cpp:8923
mlir::Value genMax(fir::FirOpBuilder &, mlir::Location, llvm::ArrayRef< mlir::Value > args)
Definition IntrinsicCall.cpp:8931
Define how a given intrinsic argument must be lowered.
Definition IntrinsicCall.h:119
bool handleDynamicOptional
Value:
Definition IntrinsicCall.h:131
This is shared by intrinsics and intrinsic module procedures.
Definition IntrinsicCall.h:573
IntrinsicDummyArgument args[7]
There is no more than 7 non repeated arguments in Fortran intrinsics.
Definition IntrinsicCall.h:575
Definition IntrinsicCall.h:566
Entry into the tables describing how an intrinsic must be lowered.
Definition IntrinsicCall.h:763
Definition IntrinsicCall.h:581
bool outline
Definition IntrinsicCall.h:589
mlir::SymbolRefAttr getUnrestrictedIntrinsicSymbolRefAttr(llvm::StringRef name, mlir::FunctionType signature)
Definition IntrinsicCall.cpp:2401
fir::ExtendedValue genElementalCall(GeneratorType, llvm::StringRef name, mlir::Type resultType, llvm::ArrayRef< fir::ExtendedValue > args, bool outline)
Generate calls to ElementalGenerator, handling the elemental aspects.
Definition IntrinsicCall.cpp:1906
fir::ExtendedValue genReduction(FN func, FD funcDim, llvm::StringRef errMsg, mlir::Type resultType, llvm::ArrayRef< fir::ExtendedValue > args)
Process calls to Product, Sum, IAll, IAny, IParity intrinsic functions.
Definition IntrinsicCall.cpp:4352
std::pair< fir::ExtendedValue, bool > genIntrinsicCall(llvm::StringRef name, std::optional< mlir::Type > resultType, llvm::ArrayRef< fir::ExtendedValue > arg)
Definition IntrinsicCall.cpp:2091
decltype(&IntrinsicLibrary::genEtime) DualGenerator
The generator for intrinsic that has both function and subroutine form.
Definition IntrinsicCall.h:499
mlir::Value outlineInWrapper(GeneratorType, llvm::StringRef name, mlir::Type resultType, llvm::ArrayRef< mlir::Value > args)
Definition IntrinsicCall.cpp:2300
mlir::Value genRuntimeCall(llvm::StringRef name, mlir::Type, llvm::ArrayRef< mlir::Value >)
Definition IntrinsicCall.cpp:2472
mlir::Value genQNan(mlir::Type resultType)
Generate a quiet NaN of a given floating point type.
Definition IntrinsicCall.cpp:4565
mlir::Value genConversion(mlir::Type, llvm::ArrayRef< mlir::Value >)
Definition IntrinsicCall.cpp:2480
mlir::Value genAbs(mlir::Type, llvm::ArrayRef< mlir::Value >)
Definition IntrinsicCall.cpp:2494
fir::ExtendedValue genExtremumVal(FN func, FD funcDim, FC funcChar, llvm::StringRef errMsg, mlir::Type resultType, llvm::ArrayRef< fir::ExtendedValue > args)
Helper for MinVal/MaxVal.
Definition IntrinsicCall.cpp:8791
fir::ExtendedValue readAndAddCleanUp(fir::MutableBoxValue resultMutableBox, mlir::Type resultType, llvm::StringRef errMsg)
Helper function for generating code clean-up for result descriptors.
Definition IntrinsicCall.cpp:2435
decltype(&IntrinsicLibrary::genAbs) ElementalGenerator
Definition IntrinsicCall.h:495
fir::ExtendedValue genCAssociatedCPtr(mlir::Type, llvm::ArrayRef< fir::ExtendedValue >)
C_ASSOCIATED (C_PTR [, C_PTR])
Definition IntrinsicCall.cpp:3142
fir::ExtendedValue genCAssociatedCFunPtr(mlir::Type, llvm::ArrayRef< fir::ExtendedValue >)
C_ASSOCIATED (C_FUNPTR [, C_FUNPTR])
Definition IntrinsicCall.cpp:3135
void genRaiseExcept(int excepts, mlir::Value cond={})
Definition IntrinsicCall.cpp:4572
mlir::Value invokeGenerator(ElementalGenerator generator, mlir::Type resultType, llvm::ArrayRef< mlir::Value > args)
Helper to invoke code generator for the intrinsics given arguments.
Definition IntrinsicCall.cpp:2106
fir::ExtendedValue genExtremumloc(FN func, FD funcDim, llvm::StringRef errMsg, mlir::Type, llvm::ArrayRef< fir::ExtendedValue >)
Process calls to Minloc, Maxloc intrinsic functions.
Definition IntrinsicCall.cpp:8710
Definition IntrinsicCall.h:604
Definition IntrinsicCall.h:654
Definition IntrinsicCall.h:592