Debian Codegraph @

flang/lib/Optimizer/Builder/IntrinsicCall.cpp

raw
1 //===-- IntrinsicCall.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 // Helper routines for constructing the FIR dialect of MLIR. As FIR is a
10 // dialect of MLIR, it makes extensive use of MLIR interfaces and MLIR's coding
11 // style (https://mlir.llvm.org/getting_started/DeveloperGuide/) is used in this
12 // module.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "flang/Optimizer/Builder/IntrinsicCall.h"
17 #include "flang/Common/static-multimap-view.h"
18 #include "flang/Optimizer/Builder/BoxValue.h"
19 #include "flang/Optimizer/Builder/Character.h"
20 #include "flang/Optimizer/Builder/Complex.h"
21 #include "flang/Optimizer/Builder/FIRBuilder.h"
22 #include "flang/Optimizer/Builder/MutableBox.h"
23 #include "flang/Optimizer/Builder/PPCIntrinsicCall.h"
24 #include "flang/Optimizer/Builder/Runtime/Allocatable.h"
25 #include "flang/Optimizer/Builder/Runtime/Character.h"
26 #include "flang/Optimizer/Builder/Runtime/Command.h"
27 #include "flang/Optimizer/Builder/Runtime/Derived.h"
28 #include "flang/Optimizer/Builder/Runtime/Exceptions.h"
29 #include "flang/Optimizer/Builder/Runtime/Execute.h"
30 #include "flang/Optimizer/Builder/Runtime/Inquiry.h"
31 #include "flang/Optimizer/Builder/Runtime/Intrinsics.h"
32 #include "flang/Optimizer/Builder/Runtime/Numeric.h"
33 #include "flang/Optimizer/Builder/Runtime/RTBuilder.h"
34 #include "flang/Optimizer/Builder/Runtime/Reduction.h"
35 #include "flang/Optimizer/Builder/Runtime/Stop.h"
36 #include "flang/Optimizer/Builder/Runtime/Transformational.h"
37 #include "flang/Optimizer/Builder/Todo.h"
38 #include "flang/Optimizer/Dialect/FIROps.h"
39 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
40 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
41 #include "flang/Optimizer/Support/FatalError.h"
42 #include "flang/Optimizer/Support/Utils.h"
43 #include "flang/Runtime/entry-names.h"
44 #include "flang/Runtime/iostat.h"
45 #include "mlir/Dialect/Complex/IR/Complex.h"
46 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
47 #include "mlir/Dialect/Math/IR/Math.h"
48 #include "mlir/Dialect/Vector/IR/VectorOps.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include <mlir/IR/Value.h>
54 #include <optional>
55
56 #define DEBUG_TYPE "flang-lower-intrinsic"
57
58 /// This file implements lowering of Fortran intrinsic procedures and Fortran
59 /// intrinsic module procedures. A call may be inlined with a mix of FIR and
60 /// MLIR operations, or as a call to a runtime function or LLVM intrinsic.
61
62 /// Lowering of intrinsic procedure calls is based on a map that associates
63 /// Fortran intrinsic generic names to FIR generator functions.
64 /// All generator functions are member functions of the IntrinsicLibrary class
65 /// and have the same interface.
66 /// If no generator is given for an intrinsic name, a math runtime library
67 /// is searched for an implementation and, if a runtime function is found,
68 /// a call is generated for it. LLVM intrinsics are handled as a math
69 /// runtime library here.
70
71 namespace fir {
72
73 fir::ExtendedValue getAbsentIntrinsicArgument() { return fir::UnboxedValue{}; }
74
75 /// Test if an ExtendedValue is absent. This is used to test if an intrinsic
76 /// argument are absent at compile time.
77 static bool isStaticallyAbsent(const fir::ExtendedValue &exv) {
78 return !fir::getBase(exv);
79 }
80 static bool isStaticallyAbsent(llvm::ArrayRef<fir::ExtendedValue> args,
81 size_t argIndex) {
82 return args.size() <= argIndex || isStaticallyAbsent(args[argIndex]);
83 }
84 static bool isStaticallyAbsent(llvm::ArrayRef<mlir::Value> args,
85 size_t argIndex) {
86 return args.size() <= argIndex || !args[argIndex];
87 }
88
89 /// Test if an ExtendedValue is present. This is used to test if an intrinsic
90 /// argument is present at compile time. This does not imply that the related
91 /// value may not be an absent dummy optional, disassociated pointer, or a
92 /// deallocated allocatable. See `handleDynamicOptional` to deal with these
93 /// cases when it makes sense.
94 static bool isStaticallyPresent(const fir::ExtendedValue &exv) {
95 return !isStaticallyAbsent(exv);
96 }
97
98 /// IEEE module procedure names not yet implemented for genModuleProcTODO.
99 static constexpr char ieee_int[] = "ieee_int";
100 static constexpr char ieee_get_underflow_mode[] = "ieee_get_underflow_mode";
101 static constexpr char ieee_next_after[] = "ieee_next_after";
102 static constexpr char ieee_next_down[] = "ieee_next_down";
103 static constexpr char ieee_next_up[] = "ieee_next_up";
104 static constexpr char ieee_real[] = "ieee_real";
105 static constexpr char ieee_rem[] = "ieee_rem";
106 static constexpr char ieee_rint[] = "ieee_rint";
107 static constexpr char ieee_set_underflow_mode[] = "ieee_set_underflow_mode";
108
109 using I = IntrinsicLibrary;
110
111 /// Flag to indicate that an intrinsic argument has to be handled as
112 /// being dynamically optional (e.g. special handling when actual
113 /// argument is an optional variable in the current scope).
114 static constexpr bool handleDynamicOptional = true;
115
116 /// Table that drives the fir generation depending on the intrinsic or intrinsic
117 /// module procedure one to one mapping with Fortran arguments. If no mapping is
118 /// defined here for a generic intrinsic, genRuntimeCall will be called
119 /// to look for a match in the runtime a emit a call. Note that the argument
120 /// lowering rules for an intrinsic need to be provided only if at least one
121 /// argument must not be lowered by value. In which case, the lowering rules
122 /// should be provided for all the intrinsic arguments for completeness.
123 static constexpr IntrinsicHandler handlers[]{
124 {"abort", &I::genAbort},
125 {"abs", &I::genAbs},
126 {"achar", &I::genChar},
127 {"acosd", &I::genAcosd},
128 {"adjustl",
129 &I::genAdjustRtCall<fir::runtime::genAdjustL>,
130 {{{"string", asAddr}}},
131 /*isElemental=*/true},
132 {"adjustr",
133 &I::genAdjustRtCall<fir::runtime::genAdjustR>,
134 {{{"string", asAddr}}},
135 /*isElemental=*/true},
136 {"aimag", &I::genAimag},
137 {"aint", &I::genAint},
138 {"all",
139 &I::genAll,
140 {{{"mask", asAddr}, {"dim", asValue}}},
141 /*isElemental=*/false},
142 {"allocated",
143 &I::genAllocated,
144 {{{"array", asInquired}, {"scalar", asInquired}}},
145 /*isElemental=*/false},
146 {"anint", &I::genAnint},
147 {"any",
148 &I::genAny,
149 {{{"mask", asAddr}, {"dim", asValue}}},
150 /*isElemental=*/false},
151 {"asind", &I::genAsind},
152 {"associated",
153 &I::genAssociated,
154 {{{"pointer", asInquired}, {"target", asInquired}}},
155 /*isElemental=*/false},
156 {"atan2d", &I::genAtand},
157 {"atan2pi", &I::genAtanpi},
158 {"atand", &I::genAtand},
159 {"atanpi", &I::genAtanpi},
160 {"bessel_jn",
161 &I::genBesselJn,
162 {{{"n1", asValue}, {"n2", asValue}, {"x", asValue}}},
163 /*isElemental=*/false},
164 {"bessel_yn",
165 &I::genBesselYn,
166 {{{"n1", asValue}, {"n2", asValue}, {"x", asValue}}},
167 /*isElemental=*/false},
168 {"bge", &I::genBitwiseCompare<mlir::arith::CmpIPredicate::uge>},
169 {"bgt", &I::genBitwiseCompare<mlir::arith::CmpIPredicate::ugt>},
170 {"ble", &I::genBitwiseCompare<mlir::arith::CmpIPredicate::ule>},
171 {"blt", &I::genBitwiseCompare<mlir::arith::CmpIPredicate::ult>},
172 {"btest", &I::genBtest},
173 {"c_associated_c_funptr",
174 &I::genCAssociatedCFunPtr,
175 {{{"c_ptr_1", asAddr}, {"c_ptr_2", asAddr, handleDynamicOptional}}},
176 /*isElemental=*/false},
177 {"c_associated_c_ptr",
178 &I::genCAssociatedCPtr,
179 {{{"c_ptr_1", asAddr}, {"c_ptr_2", asAddr, handleDynamicOptional}}},
180 /*isElemental=*/false},
181 {"c_f_pointer",
182 &I::genCFPointer,
183 {{{"cptr", asValue},
184 {"fptr", asInquired},
185 {"shape", asAddr, handleDynamicOptional}}},
186 /*isElemental=*/false},
187 {"c_f_procpointer",
188 &I::genCFProcPointer,
189 {{{"cptr", asValue}, {"fptr", asInquired}}},
190 /*isElemental=*/false},
191 {"c_funloc", &I::genCFunLoc, {{{"x", asBox}}}, /*isElemental=*/false},
192 {"c_loc", &I::genCLoc, {{{"x", asBox}}}, /*isElemental=*/false},
193 {"c_ptr_eq", &I::genCPtrCompare<mlir::arith::CmpIPredicate::eq>},
194 {"c_ptr_ne", &I::genCPtrCompare<mlir::arith::CmpIPredicate::ne>},
195 {"ceiling", &I::genCeiling},
196 {"char", &I::genChar},
197 {"cmplx",
198 &I::genCmplx,
199 {{{"x", asValue}, {"y", asValue, handleDynamicOptional}}}},
200 {"command_argument_count", &I::genCommandArgumentCount},
201 {"conjg", &I::genConjg},
202 {"cosd", &I::genCosd},
203 {"count",
204 &I::genCount,
205 {{{"mask", asAddr}, {"dim", asValue}, {"kind", asValue}}},
206 /*isElemental=*/false},
207 {"cpu_time",
208 &I::genCpuTime,
209 {{{"time", asAddr}}},
210 /*isElemental=*/false},
211 {"cshift",
212 &I::genCshift,
213 {{{"array", asAddr}, {"shift", asAddr}, {"dim", asValue}}},
214 /*isElemental=*/false},
215 {"date_and_time",
216 &I::genDateAndTime,
217 {{{"date", asAddr, handleDynamicOptional},
218 {"time", asAddr, handleDynamicOptional},
219 {"zone", asAddr, handleDynamicOptional},
220 {"values", asBox, handleDynamicOptional}}},
221 /*isElemental=*/false},
222 {"dble", &I::genConversion},
223 {"dim", &I::genDim},
224 {"dot_product",
225 &I::genDotProduct,
226 {{{"vector_a", asBox}, {"vector_b", asBox}}},
227 /*isElemental=*/false},
228 {"dprod", &I::genDprod},
229 {"dshiftl", &I::genDshiftl},
230 {"dshiftr", &I::genDshiftr},
231 {"eoshift",
232 &I::genEoshift,
233 {{{"array", asBox},
234 {"shift", asAddr},
235 {"boundary", asBox, handleDynamicOptional},
236 {"dim", asValue}}},
237 /*isElemental=*/false},
238 {"erfc_scaled", &I::genErfcScaled},
239 {"etime",
240 &I::genEtime,
241 {{{"values", asBox}, {"time", asBox}}},
242 /*isElemental=*/false},
243 {"execute_command_line",
244 &I::genExecuteCommandLine,
245 {{{"command", asBox},
246 {"wait", asAddr, handleDynamicOptional},
247 {"exitstat", asBox, handleDynamicOptional},
248 {"cmdstat", asBox, handleDynamicOptional},
249 {"cmdmsg", asBox, handleDynamicOptional}}},
250 /*isElemental=*/false},
251 {"exit",
252 &I::genExit,
253 {{{"status", asValue, handleDynamicOptional}}},
254 /*isElemental=*/false},
255 {"exponent", &I::genExponent},
256 {"extends_type_of",
257 &I::genExtendsTypeOf,
258 {{{"a", asBox}, {"mold", asBox}}},
259 /*isElemental=*/false},
260 {"findloc",
261 &I::genFindloc,
262 {{{"array", asBox},
263 {"value", asAddr},
264 {"dim", asValue},
265 {"mask", asBox, handleDynamicOptional},
266 {"kind", asValue},
267 {"back", asValue, handleDynamicOptional}}},
268 /*isElemental=*/false},
269 {"floor", &I::genFloor},
270 {"fraction", &I::genFraction},
271 {"get_command",
272 &I::genGetCommand,
273 {{{"command", asBox, handleDynamicOptional},
274 {"length", asBox, handleDynamicOptional},
275 {"status", asAddr, handleDynamicOptional},
276 {"errmsg", asBox, handleDynamicOptional}}},
277 /*isElemental=*/false},
278 {"get_command_argument",
279 &I::genGetCommandArgument,
280 {{{"number", asValue},
281 {"value", asBox, handleDynamicOptional},
282 {"length", asBox, handleDynamicOptional},
283 {"status", asAddr, handleDynamicOptional},
284 {"errmsg", asBox, handleDynamicOptional}}},
285 /*isElemental=*/false},
286 {"get_environment_variable",
287 &I::genGetEnvironmentVariable,
288 {{{"name", asBox},
289 {"value", asBox, handleDynamicOptional},
290 {"length", asBox, handleDynamicOptional},
291 {"status", asAddr, handleDynamicOptional},
292 {"trim_name", asAddr, handleDynamicOptional},
293 {"errmsg", asBox, handleDynamicOptional}}},
294 /*isElemental=*/false},
295 {"getcwd",
296 &I::genGetCwd,
297 {{{"c", asBox}, {"status", asAddr, handleDynamicOptional}}},
298 /*isElemental=*/false},
299 {"getpid", &I::genGetPID},
300 {"iachar", &I::genIchar},
301 {"iall",
302 &I::genIall,
303 {{{"array", asBox},
304 {"dim", asValue},
305 {"mask", asBox, handleDynamicOptional}}},
306 /*isElemental=*/false},
307 {"iand", &I::genIand},
308 {"iany",
309 &I::genIany,
310 {{{"array", asBox},
311 {"dim", asValue},
312 {"mask", asBox, handleDynamicOptional}}},
313 /*isElemental=*/false},
314 {"ibclr", &I::genIbclr},
315 {"ibits", &I::genIbits},
316 {"ibset", &I::genIbset},
317 {"ichar", &I::genIchar},
318 {"ieee_class", &I::genIeeeClass},
319 {"ieee_class_eq", &I::genIeeeTypeCompare<mlir::arith::CmpIPredicate::eq>},
320 {"ieee_class_ne", &I::genIeeeTypeCompare<mlir::arith::CmpIPredicate::ne>},
321 {"ieee_copy_sign", &I::genIeeeCopySign},
322 {"ieee_get_flag",
323 &I::genIeeeGetFlag,
324 {{{"flag", asValue}, {"flag_value", asAddr}}}},
325 {"ieee_get_halting_mode",
326 &I::genIeeeGetHaltingMode,
327 {{{"flag", asValue}, {"halting", asAddr}}}},
328 {"ieee_get_modes", &I::genIeeeGetOrSetModes</*isGet=*/true>},
329 {"ieee_get_rounding_mode",
330 &I::genIeeeGetRoundingMode,
331 {{{"round_value", asAddr, handleDynamicOptional},
332 {"radix", asValue, handleDynamicOptional}}},
333 /*isElemental=*/false},
334 {"ieee_get_status", &I::genIeeeGetOrSetStatus</*isGet=*/true>},
335 {"ieee_get_underflow_mode", &I::genModuleProcTODO<ieee_get_underflow_mode>},
336 {"ieee_int", &I::genModuleProcTODO<ieee_int>},
337 {"ieee_is_finite", &I::genIeeeIsFinite},
338 {"ieee_is_nan", &I::genIeeeIsNan},
339 {"ieee_is_negative", &I::genIeeeIsNegative},
340 {"ieee_is_normal", &I::genIeeeIsNormal},
341 {"ieee_logb", &I::genIeeeLogb},
342 {"ieee_max",
343 &I::genIeeeMaxMin</*isMax=*/true, /*isNum=*/false, /*isMag=*/false>},
344 {"ieee_max_mag",
345 &I::genIeeeMaxMin</*isMax=*/true, /*isNum=*/false, /*isMag=*/true>},
346 {"ieee_max_num",
347 &I::genIeeeMaxMin</*isMax=*/true, /*isNum=*/true, /*isMag=*/false>},
348 {"ieee_max_num_mag",
349 &I::genIeeeMaxMin</*isMax=*/true, /*isNum=*/true, /*isMag=*/true>},
350 {"ieee_min",
351 &I::genIeeeMaxMin</*isMax=*/false, /*isNum=*/false, /*isMag=*/false>},
352 {"ieee_min_mag",
353 &I::genIeeeMaxMin</*isMax=*/false, /*isNum=*/false, /*isMag=*/true>},
354 {"ieee_min_num",
355 &I::genIeeeMaxMin</*isMax=*/false, /*isNum=*/true, /*isMag=*/false>},
356 {"ieee_min_num_mag",
357 &I::genIeeeMaxMin</*isMax=*/false, /*isNum=*/true, /*isMag=*/true>},
358 {"ieee_next_after", &I::genModuleProcTODO<ieee_next_after>},
359 {"ieee_next_down", &I::genModuleProcTODO<ieee_next_down>},
360 {"ieee_next_up", &I::genModuleProcTODO<ieee_next_up>},
361 {"ieee_quiet_eq", &I::genIeeeQuietCompare<mlir::arith::CmpFPredicate::OEQ>},
362 {"ieee_quiet_ge", &I::genIeeeQuietCompare<mlir::arith::CmpFPredicate::OGE>},
363 {"ieee_quiet_gt", &I::genIeeeQuietCompare<mlir::arith::CmpFPredicate::OGT>},
364 {"ieee_quiet_le", &I::genIeeeQuietCompare<mlir::arith::CmpFPredicate::OLE>},
365 {"ieee_quiet_lt", &I::genIeeeQuietCompare<mlir::arith::CmpFPredicate::OLT>},
366 {"ieee_quiet_ne", &I::genIeeeQuietCompare<mlir::arith::CmpFPredicate::UNE>},
367 {"ieee_real", &I::genModuleProcTODO<ieee_real>},
368 {"ieee_rem", &I::genModuleProcTODO<ieee_rem>},
369 {"ieee_rint", &I::genModuleProcTODO<ieee_rint>},
370 {"ieee_round_eq", &I::genIeeeTypeCompare<mlir::arith::CmpIPredicate::eq>},
371 {"ieee_round_ne", &I::genIeeeTypeCompare<mlir::arith::CmpIPredicate::ne>},
372 {"ieee_set_flag", &I::genIeeeSetFlagOrHaltingMode</*isFlag=*/true>},
373 {"ieee_set_halting_mode",
374 &I::genIeeeSetFlagOrHaltingMode</*isFlag=*/false>},
375 {"ieee_set_modes", &I::genIeeeGetOrSetModes</*isGet=*/false>},
376 {"ieee_set_rounding_mode",
377 &I::genIeeeSetRoundingMode,
378 {{{"round_value", asValue, handleDynamicOptional},
379 {"radix", asValue, handleDynamicOptional}}},
380 /*isElemental=*/false},
381 {"ieee_set_status", &I::genIeeeGetOrSetStatus</*isGet=*/false>},
382 {"ieee_set_underflow_mode", &I::genModuleProcTODO<ieee_set_underflow_mode>},
383 {"ieee_signaling_eq",
384 &I::genIeeeSignalingCompare<mlir::arith::CmpFPredicate::OEQ>},
385 {"ieee_signaling_ge",
386 &I::genIeeeSignalingCompare<mlir::arith::CmpFPredicate::OGE>},
387 {"ieee_signaling_gt",
388 &I::genIeeeSignalingCompare<mlir::arith::CmpFPredicate::OGT>},
389 {"ieee_signaling_le",
390 &I::genIeeeSignalingCompare<mlir::arith::CmpFPredicate::OLE>},
391 {"ieee_signaling_lt",
392 &I::genIeeeSignalingCompare<mlir::arith::CmpFPredicate::OLT>},
393 {"ieee_signaling_ne",
394 &I::genIeeeSignalingCompare<mlir::arith::CmpFPredicate::UNE>},
395 {"ieee_signbit", &I::genIeeeSignbit},
396 {"ieee_support_flag",
397 &I::genIeeeSupportFlagOrHalting,
398 {{{"flag", asValue}, {"x", asInquired, handleDynamicOptional}}},
399 /*isElemental=*/false},
400 {"ieee_support_halting", &I::genIeeeSupportFlagOrHalting},
401 {"ieee_support_rounding", &I::genIeeeSupportRounding},
402 {"ieee_unordered", &I::genIeeeUnordered},
403 {"ieee_value", &I::genIeeeValue},
404 {"ieor", &I::genIeor},
405 {"index",
406 &I::genIndex,
407 {{{"string", asAddr},
408 {"substring", asAddr},
409 {"back", asValue, handleDynamicOptional},
410 {"kind", asValue}}}},
411 {"ior", &I::genIor},
412 {"iparity",
413 &I::genIparity,
414 {{{"array", asBox},
415 {"dim", asValue},
416 {"mask", asBox, handleDynamicOptional}}},
417 /*isElemental=*/false},
418 {"is_contiguous",
419 &I::genIsContiguous,
420 {{{"array", asBox}}},
421 /*isElemental=*/false},
422 {"is_iostat_end", &I::genIsIostatValue<Fortran::runtime::io::IostatEnd>},
423 {"is_iostat_eor", &I::genIsIostatValue<Fortran::runtime::io::IostatEor>},
424 {"ishft", &I::genIshft},
425 {"ishftc", &I::genIshftc},
426 {"isnan", &I::genIeeeIsNan},
427 {"lbound",
428 &I::genLbound,
429 {{{"array", asInquired}, {"dim", asValue}, {"kind", asValue}}},
430 /*isElemental=*/false},
431 {"leadz", &I::genLeadz},
432 {"len",
433 &I::genLen,
434 {{{"string", asInquired}, {"kind", asValue}}},
435 /*isElemental=*/false},
436 {"len_trim", &I::genLenTrim},
437 {"lge", &I::genCharacterCompare<mlir::arith::CmpIPredicate::sge>},
438 {"lgt", &I::genCharacterCompare<mlir::arith::CmpIPredicate::sgt>},
439 {"lle", &I::genCharacterCompare<mlir::arith::CmpIPredicate::sle>},
440 {"llt", &I::genCharacterCompare<mlir::arith::CmpIPredicate::slt>},
441 {"loc", &I::genLoc, {{{"x", asBox}}}, /*isElemental=*/false},
442 {"maskl", &I::genMask<mlir::arith::ShLIOp>},
443 {"maskr", &I::genMask<mlir::arith::ShRUIOp>},
444 {"matmul",
445 &I::genMatmul,
446 {{{"matrix_a", asAddr}, {"matrix_b", asAddr}}},
447 /*isElemental=*/false},
448 {"matmul_transpose",
449 &I::genMatmulTranspose,
450 {{{"matrix_a", asAddr}, {"matrix_b", asAddr}}},
451 /*isElemental=*/false},
452 {"max", &I::genExtremum<Extremum::Max, ExtremumBehavior::MinMaxss>},
453 {"maxloc",
454 &I::genMaxloc,
455 {{{"array", asBox},
456 {"dim", asValue},
457 {"mask", asBox, handleDynamicOptional},
458 {"kind", asValue},
459 {"back", asValue, handleDynamicOptional}}},
460 /*isElemental=*/false},
461 {"maxval",
462 &I::genMaxval,
463 {{{"array", asBox},
464 {"dim", asValue},
465 {"mask", asBox, handleDynamicOptional}}},
466 /*isElemental=*/false},
467 {"merge", &I::genMerge},
468 {"merge_bits", &I::genMergeBits},
469 {"min", &I::genExtremum<Extremum::Min, ExtremumBehavior::MinMaxss>},
470 {"minloc",
471 &I::genMinloc,
472 {{{"array", asBox},
473 {"dim", asValue},
474 {"mask", asBox, handleDynamicOptional},
475 {"kind", asValue},
476 {"back", asValue, handleDynamicOptional}}},
477 /*isElemental=*/false},
478 {"minval",
479 &I::genMinval,
480 {{{"array", asBox},
481 {"dim", asValue},
482 {"mask", asBox, handleDynamicOptional}}},
483 /*isElemental=*/false},
484 {"mod", &I::genMod},
485 {"modulo", &I::genModulo},
486 {"move_alloc",
487 &I::genMoveAlloc,
488 {{{"from", asInquired},
489 {"to", asInquired},
490 {"status", asAddr, handleDynamicOptional},
491 {"errMsg", asBox, handleDynamicOptional}}},
492 /*isElemental=*/false},
493 {"mvbits",
494 &I::genMvbits,
495 {{{"from", asValue},
496 {"frompos", asValue},
497 {"len", asValue},
498 {"to", asAddr},
499 {"topos", asValue}}}},
500 {"nearest", &I::genNearest},
501 {"nint", &I::genNint},
502 {"norm2",
503 &I::genNorm2,
504 {{{"array", asBox}, {"dim", asValue}}},
505 /*isElemental=*/false},
506 {"not", &I::genNot},
507 {"null", &I::genNull, {{{"mold", asInquired}}}, /*isElemental=*/false},
508 {"pack",
509 &I::genPack,
510 {{{"array", asBox},
511 {"mask", asBox},
512 {"vector", asBox, handleDynamicOptional}}},
513 /*isElemental=*/false},
514 {"parity",
515 &I::genParity,
516 {{{"mask", asBox}, {"dim", asValue}}},
517 /*isElemental=*/false},
518 {"popcnt", &I::genPopcnt},
519 {"poppar", &I::genPoppar},
520 {"present",
521 &I::genPresent,
522 {{{"a", asInquired}}},
523 /*isElemental=*/false},
524 {"product",
525 &I::genProduct,
526 {{{"array", asBox},
527 {"dim", asValue},
528 {"mask", asBox, handleDynamicOptional}}},
529 /*isElemental=*/false},
530 {"random_init",
531 &I::genRandomInit,
532 {{{"repeatable", asValue}, {"image_distinct", asValue}}},
533 /*isElemental=*/false},
534 {"random_number",
535 &I::genRandomNumber,
536 {{{"harvest", asBox}}},
537 /*isElemental=*/false},
538 {"random_seed",
539 &I::genRandomSeed,
540 {{{"size", asBox, handleDynamicOptional},
541 {"put", asBox, handleDynamicOptional},
542 {"get", asBox, handleDynamicOptional}}},
543 /*isElemental=*/false},
544 {"reduce",
545 &I::genReduce,
546 {{{"array", asBox},
547 {"operation", asAddr},
548 {"dim", asValue},
549 {"mask", asBox, handleDynamicOptional},
550 {"identity", asAddr, handleDynamicOptional},
551 {"ordered", asValue, handleDynamicOptional}}},
552 /*isElemental=*/false},
553 {"rename",
554 &I::genRename,
555 {{{"path1", asBox},
556 {"path2", asBox},
557 {"status", asBox, handleDynamicOptional}}},
558 /*isElemental=*/false},
559 {"repeat",
560 &I::genRepeat,
561 {{{"string", asAddr}, {"ncopies", asValue}}},
562 /*isElemental=*/false},
563 {"reshape",
564 &I::genReshape,
565 {{{"source", asBox},
566 {"shape", asBox},
567 {"pad", asBox, handleDynamicOptional},
568 {"order", asBox, handleDynamicOptional}}},
569 /*isElemental=*/false},
570 {"rrspacing", &I::genRRSpacing},
571 {"same_type_as",
572 &I::genSameTypeAs,
573 {{{"a", asBox}, {"b", asBox}}},
574 /*isElemental=*/false},
575 {"scale",
576 &I::genScale,
577 {{{"x", asValue}, {"i", asValue}}},
578 /*isElemental=*/true},
579 {"scan",
580 &I::genScan,
581 {{{"string", asAddr},
582 {"set", asAddr},
583 {"back", asValue, handleDynamicOptional},
584 {"kind", asValue}}},
585 /*isElemental=*/true},
586 {"second",
587 &I::genSecond,
588 {{{"time", asAddr}}},
589 /*isElemental=*/false},
590 {"selected_char_kind",
591 &I::genSelectedCharKind,
592 {{{"name", asAddr}}},
593 /*isElemental=*/false},
594 {"selected_int_kind",
595 &I::genSelectedIntKind,
596 {{{"scalar", asAddr}}},
597 /*isElemental=*/false},
598 {"selected_logical_kind",
599 &I::genSelectedLogicalKind,
600 {{{"bits", asAddr}}},
601 /*isElemental=*/false},
602 {"selected_real_kind",
603 &I::genSelectedRealKind,
604 {{{"precision", asAddr, handleDynamicOptional},
605 {"range", asAddr, handleDynamicOptional},
606 {"radix", asAddr, handleDynamicOptional}}},
607 /*isElemental=*/false},
608 {"set_exponent", &I::genSetExponent},
609 {"shape",
610 &I::genShape,
611 {{{"source", asBox}, {"kind", asValue}}},
612 /*isElemental=*/false},
613 {"shifta", &I::genShiftA},
614 {"shiftl", &I::genShift<mlir::arith::ShLIOp>},
615 {"shiftr", &I::genShift<mlir::arith::ShRUIOp>},
616 {"sign", &I::genSign},
617 {"signal",
618 &I::genSignalSubroutine,
619 {{{"number", asValue}, {"handler", asAddr}, {"status", asAddr}}},
620 /*isElemental=*/false},
621 {"sind", &I::genSind},
622 {"size",
623 &I::genSize,
624 {{{"array", asBox},
625 {"dim", asAddr, handleDynamicOptional},
626 {"kind", asValue}}},
627 /*isElemental=*/false},
628 {"sizeof",
629 &I::genSizeOf,
630 {{{"a", asBox}}},
631 /*isElemental=*/false},
632 {"sleep", &I::genSleep, {{{"seconds", asValue}}}, /*isElemental=*/false},
633 {"spacing", &I::genSpacing},
634 {"spread",
635 &I::genSpread,
636 {{{"source", asBox}, {"dim", asValue}, {"ncopies", asValue}}},
637 /*isElemental=*/false},
638 {"storage_size",
639 &I::genStorageSize,
640 {{{"a", asInquired}, {"kind", asValue}}},
641 /*isElemental=*/false},
642 {"sum",
643 &I::genSum,
644 {{{"array", asBox},
645 {"dim", asValue},
646 {"mask", asBox, handleDynamicOptional}}},
647 /*isElemental=*/false},
648 {"system",
649 &I::genSystem,
650 {{{"command", asBox}, {"exitstat", asBox, handleDynamicOptional}}},
651 /*isElemental=*/false},
652 {"system_clock",
653 &I::genSystemClock,
654 {{{"count", asAddr}, {"count_rate", asAddr}, {"count_max", asAddr}}},
655 /*isElemental=*/false},
656 {"tand", &I::genTand},
657 {"trailz", &I::genTrailz},
658 {"transfer",
659 &I::genTransfer,
660 {{{"source", asAddr}, {"mold", asAddr}, {"size", asValue}}},
661 /*isElemental=*/false},
662 {"transpose",
663 &I::genTranspose,
664 {{{"matrix", asAddr}}},
665 /*isElemental=*/false},
666 {"trim", &I::genTrim, {{{"string", asAddr}}}, /*isElemental=*/false},
667 {"ubound",
668 &I::genUbound,
669 {{{"array", asBox}, {"dim", asValue}, {"kind", asValue}}},
670 /*isElemental=*/false},
671 {"unpack",
672 &I::genUnpack,
673 {{{"vector", asBox}, {"mask", asBox}, {"field", asBox}}},
674 /*isElemental=*/false},
675 {"verify",
676 &I::genVerify,
677 {{{"string", asAddr},
678 {"set", asAddr},
679 {"back", asValue, handleDynamicOptional},
680 {"kind", asValue}}},
681 /*isElemental=*/true},
682 };
683
684 static const IntrinsicHandler *findIntrinsicHandler(llvm::StringRef name) {
685 auto compare = [](const IntrinsicHandler &handler, llvm::StringRef name) {
686 return name.compare(handler.name) > 0;
687 };
688 auto result = llvm::lower_bound(handlers, name, compare);
689 return result != std::end(handlers) && result->name == name ? result
690 : nullptr;
691 }
692
693 /// To make fir output more readable for debug, one can outline all intrinsic
694 /// implementation in wrappers (overrides the IntrinsicHandler::outline flag).
695 static llvm::cl::opt<bool> outlineAllIntrinsics(
696 "outline-intrinsics",
697 llvm::cl::desc(
698 "Lower all intrinsic procedure implementation in their own functions"),
699 llvm::cl::init(false));
700
701 //===----------------------------------------------------------------------===//
702 // Math runtime description and matching utility
703 //===----------------------------------------------------------------------===//
704
705 /// Command line option to modify math runtime behavior used to implement
706 /// intrinsics. This option applies both to early and late math-lowering modes.
707 enum MathRuntimeVersion { fastVersion, relaxedVersion, preciseVersion };
708 llvm::cl::opt<MathRuntimeVersion> mathRuntimeVersion(
709 "math-runtime", llvm::cl::desc("Select math operations' runtime behavior:"),
710 llvm::cl::values(
711 clEnumValN(fastVersion, "fast", "use fast runtime behavior"),
712 clEnumValN(relaxedVersion, "relaxed", "use relaxed runtime behavior"),
713 clEnumValN(preciseVersion, "precise", "use precise runtime behavior")),
714 llvm::cl::init(fastVersion));
715
716 static llvm::cl::opt<bool>
717 forceMlirComplex("force-mlir-complex",
718 llvm::cl::desc("Force using MLIR complex operations "
719 "instead of libm complex operations"),
720 llvm::cl::init(false));
721
722 /// Return a string containing the given Fortran intrinsic name
723 /// with the type of its arguments specified in funcType
724 /// surrounded by the given prefix/suffix.
725 static std::string
726 prettyPrintIntrinsicName(fir::FirOpBuilder &builder, mlir::Location loc,
727 llvm::StringRef prefix, llvm::StringRef name,
728 llvm::StringRef suffix, mlir::FunctionType funcType) {
729 std::string output = prefix.str();
730 llvm::raw_string_ostream sstream(output);
731 if (name == "pow") {
732 assert(funcType.getNumInputs() == 2 && "power operator has two arguments");
733 std::string displayName{" ** "};
734 sstream << mlirTypeToIntrinsicFortran(builder, funcType.getInput(0), loc,
735 displayName)
736 << displayName
737 << mlirTypeToIntrinsicFortran(builder, funcType.getInput(1), loc,
738 displayName);
739 } else {
740 sstream << name.upper() << "(";
741 if (funcType.getNumInputs() > 0)
742 sstream << mlirTypeToIntrinsicFortran(builder, funcType.getInput(0), loc,
743 name);
744 for (mlir::Type argType : funcType.getInputs().drop_front()) {
745 sstream << ", "
746 << mlirTypeToIntrinsicFortran(builder, argType, loc, name);
747 }
748 sstream << ")";
749 }
750 sstream << suffix;
751 return output;
752 }
753
754 // Generate a call to the Fortran runtime library providing
755 // support for 128-bit float math.
756 // On 'LDBL_MANT_DIG == 113' targets the implementation
757 // is provided by FortranRuntime, otherwise, it is done via
758 // FortranFloat128Math library. In the latter case the compiler
759 // has to be built with FLANG_RUNTIME_F128_MATH_LIB to guarantee
760 // proper linking actions in the driver.
761 static mlir::Value genLibF128Call(fir::FirOpBuilder &builder,
762 mlir::Location loc,
763 const MathOperation &mathOp,
764 mlir::FunctionType libFuncType,
765 llvm::ArrayRef<mlir::Value> args) {
766 // TODO: if we knew that the C 'long double' does not have 113-bit mantissa
767 // on the target, we could have asserted that FLANG_RUNTIME_F128_MATH_LIB
768 // must be specified. For now just always generate the call even
769 // if it will be unresolved.
770 return genLibCall(builder, loc, mathOp, libFuncType, args);
771 }
772
773 mlir::Value genLibCall(fir::FirOpBuilder &builder, mlir::Location loc,
774 const MathOperation &mathOp,
775 mlir::FunctionType libFuncType,
776 llvm::ArrayRef<mlir::Value> args) {
777 llvm::StringRef libFuncName = mathOp.runtimeFunc;
778 LLVM_DEBUG(llvm::dbgs() << "Generating '" << libFuncName
779 << "' call with type ";
780 libFuncType.dump(); llvm::dbgs() << "\n");
781 mlir::func::FuncOp funcOp = builder.getNamedFunction(libFuncName);
782
783 if (!funcOp) {
784 funcOp = builder.createFunction(loc, libFuncName, libFuncType);
785 // C-interoperability rules apply to these library functions.
786 funcOp->setAttr(fir::getSymbolAttrName(),
787 mlir::StringAttr::get(builder.getContext(), libFuncName));
788 // Set fir.runtime attribute to distinguish the function that
789 // was just created from user functions with the same name.
790 funcOp->setAttr(fir::FIROpsDialect::getFirRuntimeAttrName(),
791 builder.getUnitAttr());
792 auto libCall = builder.create<fir::CallOp>(loc, funcOp, args);
793 // TODO: ensure 'strictfp' setting on the call for "precise/strict"
794 // FP mode. Set appropriate Fast-Math Flags otherwise.
795 // TODO: we should also mark as many libm function as possible
796 // with 'pure' attribute (of course, not in strict FP mode).
797 LLVM_DEBUG(libCall.dump(); llvm::dbgs() << "\n");
798 return libCall.getResult(0);
799 }
800
801 // The function with the same name already exists.
802 fir::CallOp libCall;
803 mlir::Type soughtFuncType = funcOp.getFunctionType();
804
805 if (soughtFuncType == libFuncType) {
806 libCall = builder.create<fir::CallOp>(loc, funcOp, args);
807 } else {
808 // A function with the same name might have been declared
809 // before (e.g. with an explicit interface and a binding label).
810 // It is in general incorrect to use the same definition for the library
811 // call, but we have no other options. Type cast the function to match
812 // the requested signature and generate an indirect call to avoid
813 // later failures caused by the signature mismatch.
814 LLVM_DEBUG(mlir::emitWarning(
815 loc, llvm::Twine("function signature mismatch for '") +
816 llvm::Twine(libFuncName) +
817 llvm::Twine("' may lead to undefined behavior.")));
818 mlir::SymbolRefAttr funcSymbolAttr = builder.getSymbolRefAttr(libFuncName);
819 mlir::Value funcPointer =
820 builder.create<fir::AddrOfOp>(loc, soughtFuncType, funcSymbolAttr);
821 funcPointer = builder.createConvert(loc, libFuncType, funcPointer);
822
823 llvm::SmallVector<mlir::Value, 3> operands{funcPointer};
824 operands.append(args.begin(), args.end());
825 libCall = builder.create<fir::CallOp>(loc, libFuncType.getResults(),
826 nullptr, operands);
827 }
828
829 LLVM_DEBUG(libCall.dump(); llvm::dbgs() << "\n");
830 return libCall.getResult(0);
831 }
832
833 mlir::Value genLibSplitComplexArgsCall(fir::FirOpBuilder &builder,
834 mlir::Location loc,
835 const MathOperation &mathOp,
836 mlir::FunctionType libFuncType,
837 llvm::ArrayRef<mlir::Value> args) {
838 assert(args.size() == 2 && "Incorrect #args to genLibSplitComplexArgsCall");
839
840 auto getSplitComplexArgsType = [&builder, &args]() -> mlir::FunctionType {
841 mlir::Type ctype = args[0].getType();
842 auto fKind = mlir::cast<fir::ComplexType>(ctype).getFKind();
843 mlir::Type ftype;
844
845 if (fKind == 2)
846 ftype = builder.getF16Type();
847 else if (fKind == 3)
848 ftype = builder.getBF16Type();
849 else if (fKind == 4)
850 ftype = builder.getF32Type();
851 else if (fKind == 8)
852 ftype = builder.getF64Type();
853 else if (fKind == 10)
854 ftype = builder.getF80Type();
855 else if (fKind == 16)
856 ftype = builder.getF128Type();
857 else
858 assert(0 && "Unsupported Complex Type");
859
860 return builder.getFunctionType({ftype, ftype, ftype, ftype}, {ctype});
861 };
862
863 llvm::SmallVector<mlir::Value, 4> splitArgs;
864 mlir::Value cplx1 = args[0];
865 auto real1 = fir::factory::Complex{builder, loc}.extractComplexPart(
866 cplx1, /*isImagPart=*/false);
867 splitArgs.push_back(real1);
868 auto imag1 = fir::factory::Complex{builder, loc}.extractComplexPart(
869 cplx1, /*isImagPart=*/true);
870 splitArgs.push_back(imag1);
871 mlir::Value cplx2 = args[1];
872 auto real2 = fir::factory::Complex{builder, loc}.extractComplexPart(
873 cplx2, /*isImagPart=*/false);
874 splitArgs.push_back(real2);
875 auto imag2 = fir::factory::Complex{builder, loc}.extractComplexPart(
876 cplx2, /*isImagPart=*/true);
877 splitArgs.push_back(imag2);
878
879 return genLibCall(builder, loc, mathOp, getSplitComplexArgsType(), splitArgs);
880 }
881
882 template <typename T>
883 mlir::Value genMathOp(fir::FirOpBuilder &builder, mlir::Location loc,
884 const MathOperation &mathOp,
885 mlir::FunctionType mathLibFuncType,
886 llvm::ArrayRef<mlir::Value> args) {
887 // TODO: we have to annotate the math operations with flags
888 // that will allow to define FP accuracy/exception
889 // behavior per operation, so that after early multi-module
890 // MLIR inlining we can distiguish operation that were
891 // compiled with different settings.
892 // Suggestion:
893 // * For "relaxed" FP mode set all Fast-Math Flags
894 // (see "[RFC] FastMath flags support in MLIR (arith dialect)"
895 // topic at discourse.llvm.org).
896 // * For "fast" FP mode set all Fast-Math Flags except 'afn'.
897 // * For "precise/strict" FP mode generate fir.calls to libm
898 // entries and annotate them with an attribute that will
899 // end up transformed into 'strictfp' LLVM attribute (TBD).
900 // Elsewhere, "precise/strict" FP mode should also set
901 // 'strictfp' for all user functions and calls so that
902 // LLVM backend does the right job.
903 // * Operations that cannot be reasonably optimized in MLIR
904 // can be also lowered to libm calls for "fast" and "relaxed"
905 // modes.
906 mlir::Value result;
907 llvm::StringRef mathLibFuncName = mathOp.runtimeFunc;
908 if (mathRuntimeVersion == preciseVersion &&
909 // Some operations do not have to be lowered as conservative
910 // calls, since they do not affect strict FP behavior.
911 // For example, purely integer operations like exponentiation
912 // with integer operands fall into this class.
913 !mathLibFuncName.empty()) {
914 result = genLibCall(builder, loc, mathOp, mathLibFuncType, args);
915 } else {
916 LLVM_DEBUG(llvm::dbgs() << "Generating '" << mathLibFuncName
917 << "' operation with type ";
918 mathLibFuncType.dump(); llvm::dbgs() << "\n");
919 result = builder.create<T>(loc, args);
920 }
921 LLVM_DEBUG(result.dump(); llvm::dbgs() << "\n");
922 return result;
923 }
924
925 template <typename T>
926 mlir::Value genComplexMathOp(fir::FirOpBuilder &builder, mlir::Location loc,
927 const MathOperation &mathOp,
928 mlir::FunctionType mathLibFuncType,
929 llvm::ArrayRef<mlir::Value> args) {
930 mlir::Value result;
931 bool canUseApprox = mlir::arith::bitEnumContainsAny(
932 builder.getFastMathFlags(), mlir::arith::FastMathFlags::afn);
933
934 // If we have libm functions, we can attempt to generate the more precise
935 // version of the complex math operation.
936 llvm::StringRef mathLibFuncName = mathOp.runtimeFunc;
937 if (!mathLibFuncName.empty()) {
938 // If we enabled MLIR complex or can use approximate operations, we should
939 // NOT use libm.
940 if (!forceMlirComplex && !canUseApprox) {
941 result = genLibCall(builder, loc, mathOp, mathLibFuncType, args);
942 LLVM_DEBUG(result.dump(); llvm::dbgs() << "\n");
943 return result;
944 }
945 }
946
947 LLVM_DEBUG(llvm::dbgs() << "Generating '" << mathLibFuncName
948 << "' operation with type ";
949 mathLibFuncType.dump(); llvm::dbgs() << "\n");
950 auto type = mlir::cast<fir::ComplexType>(mathLibFuncType.getInput(0));
951 auto kind = mlir::cast<fir::RealType>(type.getElementType()).getFKind();
952 auto realTy = builder.getRealType(kind);
953 auto mComplexTy = mlir::ComplexType::get(realTy);
954
955 llvm::SmallVector<mlir::Value, 2> cargs;
956 for (const mlir::Value &arg : args) {
957 // Convert the fir.complex to a mlir::complex
958 cargs.push_back(builder.createConvert(loc, mComplexTy, arg));
959 }
960
961 // Builder expects an extra return type to be provided if different to
962 // the argument types for an operation
963 if constexpr (T::template hasTrait<
964 mlir::OpTrait::SameOperandsAndResultType>()) {
965 result = builder.create<T>(loc, cargs);
966 result = builder.createConvert(loc, mathLibFuncType.getResult(0), result);
967 } else {
968 result = builder.create<T>(loc, realTy, cargs);
969 result = builder.createConvert(loc, mathLibFuncType.getResult(0), result);
970 }
971
972 LLVM_DEBUG(result.dump(); llvm::dbgs() << "\n");
973 return result;
974 }
975
976 /// Mapping between mathematical intrinsic operations and MLIR operations
977 /// of some appropriate dialect (math, complex, etc.) or libm calls.
978 /// TODO: support remaining Fortran math intrinsics.
979 /// See https://gcc.gnu.org/onlinedocs/gcc-12.1.0/gfortran/\
980 /// Intrinsic-Procedures.html for a reference.
981 constexpr auto FuncTypeReal16Real16 = genFuncType<Ty::Real<16>, Ty::Real<16>>;
982 constexpr auto FuncTypeReal16Real16Real16 =
983 genFuncType<Ty::Real<16>, Ty::Real<16>, Ty::Real<16>>;
984 constexpr auto FuncTypeReal16Real16Real16Real16 =
985 genFuncType<Ty::Real<16>, Ty::Real<16>, Ty::Real<16>, Ty::Real<16>>;
986 constexpr auto FuncTypeReal16Integer4Real16 =
987 genFuncType<Ty::Real<16>, Ty::Integer<4>, Ty::Real<16>>;
988 constexpr auto FuncTypeInteger4Real16 =
989 genFuncType<Ty::Integer<4>, Ty::Real<16>>;
990 constexpr auto FuncTypeInteger8Real16 =
991 genFuncType<Ty::Integer<8>, Ty::Real<16>>;
992 constexpr auto FuncTypeReal16Complex16 =
993 genFuncType<Ty::Real<16>, Ty::Complex<16>>;
994 constexpr auto FuncTypeComplex16Complex16 =
995 genFuncType<Ty::Complex<16>, Ty::Complex<16>>;
996 constexpr auto FuncTypeComplex16Complex16Complex16 =
997 genFuncType<Ty::Complex<16>, Ty::Complex<16>, Ty::Complex<16>>;
998 constexpr auto FuncTypeComplex16Complex16Integer4 =
999 genFuncType<Ty::Complex<16>, Ty::Complex<16>, Ty::Integer<4>>;
1000 constexpr auto FuncTypeComplex16Complex16Integer8 =
1001 genFuncType<Ty::Complex<16>, Ty::Complex<16>, Ty::Integer<8>>;
1002
1003 static constexpr MathOperation mathOperations[] = {
1004 {"abs", "fabsf", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1005 genMathOp<mlir::math::AbsFOp>},
1006 {"abs", "fabs", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1007 genMathOp<mlir::math::AbsFOp>},
1008 {"abs", "llvm.fabs.f128", genFuncType<Ty::Real<16>, Ty::Real<16>>,
1009 genMathOp<mlir::math::AbsFOp>},
1010 {"abs", "cabsf", genFuncType<Ty::Real<4>, Ty::Complex<4>>,
1011 genComplexMathOp<mlir::complex::AbsOp>},
1012 {"abs", "cabs", genFuncType<Ty::Real<8>, Ty::Complex<8>>,
1013 genComplexMathOp<mlir::complex::AbsOp>},
1014 {"abs", RTNAME_STRING(CAbsF128), FuncTypeReal16Complex16, genLibF128Call},
1015 {"acos", "acosf", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1016 {"acos", "acos", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1017 {"acos", RTNAME_STRING(AcosF128), FuncTypeReal16Real16, genLibF128Call},
1018 {"acos", "cacosf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>, genLibCall},
1019 {"acos", "cacos", genFuncType<Ty::Complex<8>, Ty::Complex<8>>, genLibCall},
1020 {"acos", RTNAME_STRING(CAcosF128), FuncTypeComplex16Complex16,
1021 genLibF128Call},
1022 {"acosh", "acoshf", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1023 {"acosh", "acosh", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1024 {"acosh", RTNAME_STRING(AcoshF128), FuncTypeReal16Real16, genLibF128Call},
1025 {"acosh", "cacoshf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>,
1026 genLibCall},
1027 {"acosh", "cacosh", genFuncType<Ty::Complex<8>, Ty::Complex<8>>,
1028 genLibCall},
1029 {"acosh", RTNAME_STRING(CAcoshF128), FuncTypeComplex16Complex16,
1030 genLibF128Call},
1031 // llvm.trunc behaves the same way as libm's trunc.
1032 {"aint", "llvm.trunc.f32", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1033 genLibCall},
1034 {"aint", "llvm.trunc.f64", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1035 genLibCall},
1036 {"aint", "llvm.trunc.f80", genFuncType<Ty::Real<10>, Ty::Real<10>>,
1037 genLibCall},
1038 {"aint", RTNAME_STRING(TruncF128), FuncTypeReal16Real16, genLibF128Call},
1039 // llvm.round behaves the same way as libm's round.
1040 {"anint", "llvm.round.f32", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1041 genMathOp<mlir::LLVM::RoundOp>},
1042 {"anint", "llvm.round.f64", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1043 genMathOp<mlir::LLVM::RoundOp>},
1044 {"anint", "llvm.round.f80", genFuncType<Ty::Real<10>, Ty::Real<10>>,
1045 genMathOp<mlir::LLVM::RoundOp>},
1046 {"anint", RTNAME_STRING(RoundF128), FuncTypeReal16Real16, genLibF128Call},
1047 {"asin", "asinf", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1048 {"asin", "asin", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1049 {"asin", RTNAME_STRING(AsinF128), FuncTypeReal16Real16, genLibF128Call},
1050 {"asin", "casinf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>, genLibCall},
1051 {"asin", "casin", genFuncType<Ty::Complex<8>, Ty::Complex<8>>, genLibCall},
1052 {"asin", RTNAME_STRING(CAsinF128), FuncTypeComplex16Complex16,
1053 genLibF128Call},
1054 {"asinh", "asinhf", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1055 {"asinh", "asinh", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1056 {"asinh", RTNAME_STRING(AsinhF128), FuncTypeReal16Real16, genLibF128Call},
1057 {"asinh", "casinhf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>,
1058 genLibCall},
1059 {"asinh", "casinh", genFuncType<Ty::Complex<8>, Ty::Complex<8>>,
1060 genLibCall},
1061 {"asinh", RTNAME_STRING(CAsinhF128), FuncTypeComplex16Complex16,
1062 genLibF128Call},
1063 {"atan", "atanf", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1064 genMathOp<mlir::math::AtanOp>},
1065 {"atan", "atan", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1066 genMathOp<mlir::math::AtanOp>},
1067 {"atan", RTNAME_STRING(AtanF128), FuncTypeReal16Real16, genLibF128Call},
1068 {"atan", "catanf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>, genLibCall},
1069 {"atan", "catan", genFuncType<Ty::Complex<8>, Ty::Complex<8>>, genLibCall},
1070 {"atan", RTNAME_STRING(CAtanF128), FuncTypeComplex16Complex16,
1071 genLibF128Call},
1072 {"atan", "atan2f", genFuncType<Ty::Real<4>, Ty::Real<4>, Ty::Real<4>>,
1073 genMathOp<mlir::math::Atan2Op>},
1074 {"atan", "atan2", genFuncType<Ty::Real<8>, Ty::Real<8>, Ty::Real<8>>,
1075 genMathOp<mlir::math::Atan2Op>},
1076 {"atan", RTNAME_STRING(Atan2F128), FuncTypeReal16Real16Real16,
1077 genLibF128Call},
1078 {"atan2", "atan2f", genFuncType<Ty::Real<4>, Ty::Real<4>, Ty::Real<4>>,
1079 genMathOp<mlir::math::Atan2Op>},
1080 {"atan2", "atan2", genFuncType<Ty::Real<8>, Ty::Real<8>, Ty::Real<8>>,
1081 genMathOp<mlir::math::Atan2Op>},
1082 {"atan2", RTNAME_STRING(Atan2F128), FuncTypeReal16Real16Real16,
1083 genLibF128Call},
1084 {"atanh", "atanhf", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1085 {"atanh", "atanh", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1086 {"atanh", RTNAME_STRING(AtanhF128), FuncTypeReal16Real16, genLibF128Call},
1087 {"atanh", "catanhf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>,
1088 genLibCall},
1089 {"atanh", "catanh", genFuncType<Ty::Complex<8>, Ty::Complex<8>>,
1090 genLibCall},
1091 {"atanh", RTNAME_STRING(CAtanhF128), FuncTypeComplex16Complex16,
1092 genLibF128Call},
1093 {"bessel_j0", "j0f", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1094 {"bessel_j0", "j0", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1095 {"bessel_j0", RTNAME_STRING(J0F128), FuncTypeReal16Real16, genLibF128Call},
1096 {"bessel_j1", "j1f", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1097 {"bessel_j1", "j1", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1098 {"bessel_j1", RTNAME_STRING(J1F128), FuncTypeReal16Real16, genLibF128Call},
1099 {"bessel_jn", "jnf", genFuncType<Ty::Real<4>, Ty::Integer<4>, Ty::Real<4>>,
1100 genLibCall},
1101 {"bessel_jn", "jn", genFuncType<Ty::Real<8>, Ty::Integer<4>, Ty::Real<8>>,
1102 genLibCall},
1103 {"bessel_jn", RTNAME_STRING(JnF128), FuncTypeReal16Integer4Real16,
1104 genLibF128Call},
1105 {"bessel_y0", "y0f", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1106 {"bessel_y0", "y0", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1107 {"bessel_y0", RTNAME_STRING(Y0F128), FuncTypeReal16Real16, genLibF128Call},
1108 {"bessel_y1", "y1f", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1109 {"bessel_y1", "y1", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1110 {"bessel_y1", RTNAME_STRING(Y1F128), FuncTypeReal16Real16, genLibF128Call},
1111 {"bessel_yn", "ynf", genFuncType<Ty::Real<4>, Ty::Integer<4>, Ty::Real<4>>,
1112 genLibCall},
1113 {"bessel_yn", "yn", genFuncType<Ty::Real<8>, Ty::Integer<4>, Ty::Real<8>>,
1114 genLibCall},
1115 {"bessel_yn", RTNAME_STRING(YnF128), FuncTypeReal16Integer4Real16,
1116 genLibF128Call},
1117 // math::CeilOp returns a real, while Fortran CEILING returns integer.
1118 {"ceil", "ceilf", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1119 genMathOp<mlir::math::CeilOp>},
1120 {"ceil", "ceil", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1121 genMathOp<mlir::math::CeilOp>},
1122 {"ceil", RTNAME_STRING(CeilF128), FuncTypeReal16Real16, genLibF128Call},
1123 {"cos", "cosf", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1124 genMathOp<mlir::math::CosOp>},
1125 {"cos", "cos", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1126 genMathOp<mlir::math::CosOp>},
1127 {"cos", RTNAME_STRING(CosF128), FuncTypeReal16Real16, genLibF128Call},
1128 {"cos", "ccosf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>,
1129 genComplexMathOp<mlir::complex::CosOp>},
1130 {"cos", "ccos", genFuncType<Ty::Complex<8>, Ty::Complex<8>>,
1131 genComplexMathOp<mlir::complex::CosOp>},
1132 {"cos", RTNAME_STRING(CCosF128), FuncTypeComplex16Complex16,
1133 genLibF128Call},
1134 {"cosh", "coshf", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1135 {"cosh", "cosh", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1136 {"cosh", RTNAME_STRING(CoshF128), FuncTypeReal16Real16, genLibF128Call},
1137 {"cosh", "ccoshf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>, genLibCall},
1138 {"cosh", "ccosh", genFuncType<Ty::Complex<8>, Ty::Complex<8>>, genLibCall},
1139 {"cosh", RTNAME_STRING(CCoshF128), FuncTypeComplex16Complex16,
1140 genLibF128Call},
1141 {"divc",
1142 {},
1143 genFuncType<Ty::Complex<2>, Ty::Complex<2>, Ty::Complex<2>>,
1144 genComplexMathOp<mlir::complex::DivOp>},
1145 {"divc",
1146 {},
1147 genFuncType<Ty::Complex<3>, Ty::Complex<3>, Ty::Complex<3>>,
1148 genComplexMathOp<mlir::complex::DivOp>},
1149 {"divc", "__divsc3",
1150 genFuncType<Ty::Complex<4>, Ty::Complex<4>, Ty::Complex<4>>,
1151 genLibSplitComplexArgsCall},
1152 {"divc", "__divdc3",
1153 genFuncType<Ty::Complex<8>, Ty::Complex<8>, Ty::Complex<8>>,
1154 genLibSplitComplexArgsCall},
1155 {"divc", "__divxc3",
1156 genFuncType<Ty::Complex<10>, Ty::Complex<10>, Ty::Complex<10>>,
1157 genLibSplitComplexArgsCall},
1158 {"divc", "__divtc3",
1159 genFuncType<Ty::Complex<16>, Ty::Complex<16>, Ty::Complex<16>>,
1160 genLibSplitComplexArgsCall},
1161 {"erf", "erff", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1162 genMathOp<mlir::math::ErfOp>},
1163 {"erf", "erf", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1164 genMathOp<mlir::math::ErfOp>},
1165 {"erf", RTNAME_STRING(ErfF128), FuncTypeReal16Real16, genLibF128Call},
1166 {"erfc", "erfcf", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1167 {"erfc", "erfc", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1168 {"erfc", RTNAME_STRING(ErfcF128), FuncTypeReal16Real16, genLibF128Call},
1169 {"exp", "expf", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1170 genMathOp<mlir::math::ExpOp>},
1171 {"exp", "exp", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1172 genMathOp<mlir::math::ExpOp>},
1173 {"exp", RTNAME_STRING(ExpF128), FuncTypeReal16Real16, genLibF128Call},
1174 {"exp", "cexpf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>,
1175 genComplexMathOp<mlir::complex::ExpOp>},
1176 {"exp", "cexp", genFuncType<Ty::Complex<8>, Ty::Complex<8>>,
1177 genComplexMathOp<mlir::complex::ExpOp>},
1178 {"exp", RTNAME_STRING(CExpF128), FuncTypeComplex16Complex16,
1179 genLibF128Call},
1180 {"feclearexcept", "feclearexcept",
1181 genFuncType<Ty::Integer<4>, Ty::Integer<4>>, genLibCall},
1182 {"fedisableexcept", "fedisableexcept",
1183 genFuncType<Ty::Integer<4>, Ty::Integer<4>>, genLibCall},
1184 {"feenableexcept", "feenableexcept",
1185 genFuncType<Ty::Integer<4>, Ty::Integer<4>>, genLibCall},
1186 {"fegetenv", "fegetenv", genFuncType<Ty::Integer<4>, Ty::Address<4>>,
1187 genLibCall},
1188 {"fegetexcept", "fegetexcept", genFuncType<Ty::Integer<4>>, genLibCall},
1189 {"fegetmode", "fegetmode", genFuncType<Ty::Integer<4>, Ty::Address<4>>,
1190 genLibCall},
1191 {"feraiseexcept", "feraiseexcept",
1192 genFuncType<Ty::Integer<4>, Ty::Integer<4>>, genLibCall},
1193 {"fesetenv", "fesetenv", genFuncType<Ty::Integer<4>, Ty::Address<4>>,
1194 genLibCall},
1195 {"fesetmode", "fesetmode", genFuncType<Ty::Integer<4>, Ty::Address<4>>,
1196 genLibCall},
1197 {"fetestexcept", "fetestexcept",
1198 genFuncType<Ty::Integer<4>, Ty::Integer<4>>, genLibCall},
1199 {"feupdateenv", "feupdateenv", genFuncType<Ty::Integer<4>, Ty::Address<4>>,
1200 genLibCall},
1201 // math::FloorOp returns a real, while Fortran FLOOR returns integer.
1202 {"floor", "floorf", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1203 genMathOp<mlir::math::FloorOp>},
1204 {"floor", "floor", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1205 genMathOp<mlir::math::FloorOp>},
1206 {"floor", RTNAME_STRING(FloorF128), FuncTypeReal16Real16, genLibF128Call},
1207 {"fma", "llvm.fma.f32",
1208 genFuncType<Ty::Real<4>, Ty::Real<4>, Ty::Real<4>, Ty::Real<4>>,
1209 genMathOp<mlir::math::FmaOp>},
1210 {"fma", "llvm.fma.f64",
1211 genFuncType<Ty::Real<8>, Ty::Real<8>, Ty::Real<8>, Ty::Real<8>>,
1212 genMathOp<mlir::math::FmaOp>},
1213 {"fma", RTNAME_STRING(FmaF128), FuncTypeReal16Real16Real16Real16,
1214 genLibF128Call},
1215 {"gamma", "tgammaf", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1216 {"gamma", "tgamma", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1217 {"gamma", RTNAME_STRING(TgammaF128), FuncTypeReal16Real16, genLibF128Call},
1218 {"hypot", "hypotf", genFuncType<Ty::Real<4>, Ty::Real<4>, Ty::Real<4>>,
1219 genLibCall},
1220 {"hypot", "hypot", genFuncType<Ty::Real<8>, Ty::Real<8>, Ty::Real<8>>,
1221 genLibCall},
1222 {"hypot", RTNAME_STRING(HypotF128), FuncTypeReal16Real16Real16,
1223 genLibF128Call},
1224 {"log", "logf", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1225 genMathOp<mlir::math::LogOp>},
1226 {"log", "log", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1227 genMathOp<mlir::math::LogOp>},
1228 {"log", RTNAME_STRING(LogF128), FuncTypeReal16Real16, genLibF128Call},
1229 {"log", "clogf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>,
1230 genComplexMathOp<mlir::complex::LogOp>},
1231 {"log", "clog", genFuncType<Ty::Complex<8>, Ty::Complex<8>>,
1232 genComplexMathOp<mlir::complex::LogOp>},
1233 {"log", RTNAME_STRING(CLogF128), FuncTypeComplex16Complex16,
1234 genLibF128Call},
1235 {"log10", "log10f", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1236 genMathOp<mlir::math::Log10Op>},
1237 {"log10", "log10", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1238 genMathOp<mlir::math::Log10Op>},
1239 {"log10", RTNAME_STRING(Log10F128), FuncTypeReal16Real16, genLibF128Call},
1240 {"log_gamma", "lgammaf", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1241 {"log_gamma", "lgamma", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1242 {"log_gamma", RTNAME_STRING(LgammaF128), FuncTypeReal16Real16,
1243 genLibF128Call},
1244 // llvm.lround behaves the same way as libm's lround.
1245 {"nint", "llvm.lround.i64.f64", genFuncType<Ty::Integer<8>, Ty::Real<8>>,
1246 genLibCall},
1247 {"nint", "llvm.lround.i64.f32", genFuncType<Ty::Integer<8>, Ty::Real<4>>,
1248 genLibCall},
1249 {"nint", RTNAME_STRING(LlroundF128), FuncTypeInteger8Real16,
1250 genLibF128Call},
1251 {"nint", "llvm.lround.i32.f64", genFuncType<Ty::Integer<4>, Ty::Real<8>>,
1252 genLibCall},
1253 {"nint", "llvm.lround.i32.f32", genFuncType<Ty::Integer<4>, Ty::Real<4>>,
1254 genLibCall},
1255 {"nint", RTNAME_STRING(LroundF128), FuncTypeInteger4Real16, genLibF128Call},
1256 {"pow",
1257 {},
1258 genFuncType<Ty::Integer<1>, Ty::Integer<1>, Ty::Integer<1>>,
1259 genMathOp<mlir::math::IPowIOp>},
1260 {"pow",
1261 {},
1262 genFuncType<Ty::Integer<2>, Ty::Integer<2>, Ty::Integer<2>>,
1263 genMathOp<mlir::math::IPowIOp>},
1264 {"pow",
1265 {},
1266 genFuncType<Ty::Integer<4>, Ty::Integer<4>, Ty::Integer<4>>,
1267 genMathOp<mlir::math::IPowIOp>},
1268 {"pow",
1269 {},
1270 genFuncType<Ty::Integer<8>, Ty::Integer<8>, Ty::Integer<8>>,
1271 genMathOp<mlir::math::IPowIOp>},
1272 {"pow", "powf", genFuncType<Ty::Real<4>, Ty::Real<4>, Ty::Real<4>>,
1273 genMathOp<mlir::math::PowFOp>},
1274 {"pow", "pow", genFuncType<Ty::Real<8>, Ty::Real<8>, Ty::Real<8>>,
1275 genMathOp<mlir::math::PowFOp>},
1276 {"pow", RTNAME_STRING(PowF128), FuncTypeReal16Real16Real16, genLibF128Call},
1277 {"pow", "cpowf",
1278 genFuncType<Ty::Complex<4>, Ty::Complex<4>, Ty::Complex<4>>,
1279 genComplexMathOp<mlir::complex::PowOp>},
1280 {"pow", "cpow", genFuncType<Ty::Complex<8>, Ty::Complex<8>, Ty::Complex<8>>,
1281 genComplexMathOp<mlir::complex::PowOp>},
1282 {"pow", RTNAME_STRING(CPowF128), FuncTypeComplex16Complex16Complex16,
1283 genLibF128Call},
1284 {"pow", RTNAME_STRING(FPow4i),
1285 genFuncType<Ty::Real<4>, Ty::Real<4>, Ty::Integer<4>>,
1286 genMathOp<mlir::math::FPowIOp>},
1287 {"pow", RTNAME_STRING(FPow8i),
1288 genFuncType<Ty::Real<8>, Ty::Real<8>, Ty::Integer<4>>,
1289 genMathOp<mlir::math::FPowIOp>},
1290 {"pow", RTNAME_STRING(FPow16i),
1291 genFuncType<Ty::Real<16>, Ty::Real<16>, Ty::Integer<4>>,
1292 genMathOp<mlir::math::FPowIOp>},
1293 {"pow", RTNAME_STRING(FPow4k),
1294 genFuncType<Ty::Real<4>, Ty::Real<4>, Ty::Integer<8>>,
1295 genMathOp<mlir::math::FPowIOp>},
1296 {"pow", RTNAME_STRING(FPow8k),
1297 genFuncType<Ty::Real<8>, Ty::Real<8>, Ty::Integer<8>>,
1298 genMathOp<mlir::math::FPowIOp>},
1299 {"pow", RTNAME_STRING(FPow16k),
1300 genFuncType<Ty::Real<16>, Ty::Real<16>, Ty::Integer<8>>,
1301 genMathOp<mlir::math::FPowIOp>},
1302 {"pow", RTNAME_STRING(cpowi),
1303 genFuncType<Ty::Complex<4>, Ty::Complex<4>, Ty::Integer<4>>, genLibCall},
1304 {"pow", RTNAME_STRING(zpowi),
1305 genFuncType<Ty::Complex<8>, Ty::Complex<8>, Ty::Integer<4>>, genLibCall},
1306 {"pow", RTNAME_STRING(cqpowi), FuncTypeComplex16Complex16Integer4,
1307 genLibF128Call},
1308 {"pow", RTNAME_STRING(cpowk),
1309 genFuncType<Ty::Complex<4>, Ty::Complex<4>, Ty::Integer<8>>, genLibCall},
1310 {"pow", RTNAME_STRING(zpowk),
1311 genFuncType<Ty::Complex<8>, Ty::Complex<8>, Ty::Integer<8>>, genLibCall},
1312 {"pow", RTNAME_STRING(cqpowk), FuncTypeComplex16Complex16Integer8,
1313 genLibF128Call},
1314 {"sign", "copysignf", genFuncType<Ty::Real<4>, Ty::Real<4>, Ty::Real<4>>,
1315 genMathOp<mlir::math::CopySignOp>},
1316 {"sign", "copysign", genFuncType<Ty::Real<8>, Ty::Real<8>, Ty::Real<8>>,
1317 genMathOp<mlir::math::CopySignOp>},
1318 {"sign", "copysignl", genFuncType<Ty::Real<10>, Ty::Real<10>, Ty::Real<10>>,
1319 genMathOp<mlir::math::CopySignOp>},
1320 {"sign", "llvm.copysign.f128",
1321 genFuncType<Ty::Real<16>, Ty::Real<16>, Ty::Real<16>>,
1322 genMathOp<mlir::math::CopySignOp>},
1323 {"sin", "sinf", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1324 genMathOp<mlir::math::SinOp>},
1325 {"sin", "sin", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1326 genMathOp<mlir::math::SinOp>},
1327 {"sin", RTNAME_STRING(SinF128), FuncTypeReal16Real16, genLibF128Call},
1328 {"sin", "csinf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>,
1329 genComplexMathOp<mlir::complex::SinOp>},
1330 {"sin", "csin", genFuncType<Ty::Complex<8>, Ty::Complex<8>>,
1331 genComplexMathOp<mlir::complex::SinOp>},
1332 {"sin", RTNAME_STRING(CSinF128), FuncTypeComplex16Complex16,
1333 genLibF128Call},
1334 {"sinh", "sinhf", genFuncType<Ty::Real<4>, Ty::Real<4>>, genLibCall},
1335 {"sinh", "sinh", genFuncType<Ty::Real<8>, Ty::Real<8>>, genLibCall},
1336 {"sinh", RTNAME_STRING(SinhF128), FuncTypeReal16Real16, genLibF128Call},
1337 {"sinh", "csinhf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>, genLibCall},
1338 {"sinh", "csinh", genFuncType<Ty::Complex<8>, Ty::Complex<8>>, genLibCall},
1339 {"sinh", RTNAME_STRING(CSinhF128), FuncTypeComplex16Complex16,
1340 genLibF128Call},
1341 {"sqrt", "sqrtf", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1342 genMathOp<mlir::math::SqrtOp>},
1343 {"sqrt", "sqrt", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1344 genMathOp<mlir::math::SqrtOp>},
1345 {"sqrt", RTNAME_STRING(SqrtF128), FuncTypeReal16Real16, genLibF128Call},
1346 {"sqrt", "csqrtf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>,
1347 genComplexMathOp<mlir::complex::SqrtOp>},
1348 {"sqrt", "csqrt", genFuncType<Ty::Complex<8>, Ty::Complex<8>>,
1349 genComplexMathOp<mlir::complex::SqrtOp>},
1350 {"sqrt", RTNAME_STRING(CSqrtF128), FuncTypeComplex16Complex16,
1351 genLibF128Call},
1352 {"tan", "tanf", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1353 genMathOp<mlir::math::TanOp>},
1354 {"tan", "tan", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1355 genMathOp<mlir::math::TanOp>},
1356 {"tan", RTNAME_STRING(TanF128), FuncTypeReal16Real16, genLibF128Call},
1357 {"tan", "ctanf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>,
1358 genComplexMathOp<mlir::complex::TanOp>},
1359 {"tan", "ctan", genFuncType<Ty::Complex<8>, Ty::Complex<8>>,
1360 genComplexMathOp<mlir::complex::TanOp>},
1361 {"tan", RTNAME_STRING(CTanF128), FuncTypeComplex16Complex16,
1362 genLibF128Call},
1363 {"tanh", "tanhf", genFuncType<Ty::Real<4>, Ty::Real<4>>,
1364 genMathOp<mlir::math::TanhOp>},
1365 {"tanh", "tanh", genFuncType<Ty::Real<8>, Ty::Real<8>>,
1366 genMathOp<mlir::math::TanhOp>},
1367 {"tanh", RTNAME_STRING(TanhF128), FuncTypeReal16Real16, genLibF128Call},
1368 {"tanh", "ctanhf", genFuncType<Ty::Complex<4>, Ty::Complex<4>>,
1369 genComplexMathOp<mlir::complex::TanhOp>},
1370 {"tanh", "ctanh", genFuncType<Ty::Complex<8>, Ty::Complex<8>>,
1371 genComplexMathOp<mlir::complex::TanhOp>},
1372 {"tanh", RTNAME_STRING(CTanhF128), FuncTypeComplex16Complex16,
1373 genLibF128Call},
1374 };
1375
1376 // This helper class computes a "distance" between two function types.
1377 // The distance measures how many narrowing conversions of actual arguments
1378 // and result of "from" must be made in order to use "to" instead of "from".
1379 // For instance, the distance between ACOS(REAL(10)) and ACOS(REAL(8)) is
1380 // greater than the one between ACOS(REAL(10)) and ACOS(REAL(16)). This means
1381 // if no implementation of ACOS(REAL(10)) is available, it is better to use
1382 // ACOS(REAL(16)) with casts rather than ACOS(REAL(8)).
1383 // Note that this is not a symmetric distance and the order of "from" and "to"
1384 // arguments matters, d(foo, bar) may not be the same as d(bar, foo) because it
1385 // may be safe to replace foo by bar, but not the opposite.
1386 class FunctionDistance {
1387 public:
1388 FunctionDistance() : infinite{true} {}
1389
1390 FunctionDistance(mlir::FunctionType from, mlir::FunctionType to) {
1391 unsigned nInputs = from.getNumInputs();
1392 unsigned nResults = from.getNumResults();
1393 if (nResults != to.getNumResults() || nInputs != to.getNumInputs()) {
1394 infinite = true;
1395 } else {
1396 for (decltype(nInputs) i = 0; i < nInputs && !infinite; ++i)
1397 addArgumentDistance(from.getInput(i), to.getInput(i));
1398 for (decltype(nResults) i = 0; i < nResults && !infinite; ++i)
1399 addResultDistance(to.getResult(i), from.getResult(i));
1400 }
1401 }
1402
1403 /// Beware both d1.isSmallerThan(d2) *and* d2.isSmallerThan(d1) may be
1404 /// false if both d1 and d2 are infinite. This implies that
1405 /// d1.isSmallerThan(d2) is not equivalent to !d2.isSmallerThan(d1)
1406 bool isSmallerThan(const FunctionDistance &d) const {
1407 return !infinite &&
1408 (d.infinite || std::lexicographical_compare(
1409 conversions.begin(), conversions.end(),
1410 d.conversions.begin(), d.conversions.end()));
1411 }
1412
1413 bool isLosingPrecision() const {
1414 return conversions[narrowingArg] != 0 || conversions[extendingResult] != 0;
1415 }
1416
1417 bool isInfinite() const { return infinite; }
1418
1419 private:
1420 enum class Conversion { Forbidden, None, Narrow, Extend };
1421
1422 void addArgumentDistance(mlir::Type from, mlir::Type to) {
1423 switch (conversionBetweenTypes(from, to)) {
1424 case Conversion::Forbidden:
1425 infinite = true;
1426 break;
1427 case Conversion::None:
1428 break;
1429 case Conversion::Narrow:
1430 conversions[narrowingArg]++;
1431 break;
1432 case Conversion::Extend:
1433 conversions[nonNarrowingArg]++;
1434 break;
1435 }
1436 }
1437
1438 void addResultDistance(mlir::Type from, mlir::Type to) {
1439 switch (conversionBetweenTypes(from, to)) {
1440 case Conversion::Forbidden:
1441 infinite = true;
1442 break;
1443 case Conversion::None:
1444 break;
1445 case Conversion::Narrow:
1446 conversions[nonExtendingResult]++;
1447 break;
1448 case Conversion::Extend:
1449 conversions[extendingResult]++;
1450 break;
1451 }
1452 }
1453
1454 // Floating point can be mlir::FloatType or fir::real
1455 static unsigned getFloatingPointWidth(mlir::Type t) {
1456 if (auto f{mlir::dyn_cast<mlir::FloatType>(t)})
1457 return f.getWidth();
1458 // FIXME: Get width another way for fir.real/complex
1459 // - use fir/KindMapping.h and llvm::Type
1460 // - or use evaluate/type.h
1461 if (auto r{mlir::dyn_cast<fir::RealType>(t)})
1462 return r.getFKind() * 4;
1463 if (auto cplx{mlir::dyn_cast<fir::ComplexType>(t)})
1464 return cplx.getFKind() * 4;
1465 llvm_unreachable("not a floating-point type");
1466 }
1467
1468 static Conversion conversionBetweenTypes(mlir::Type from, mlir::Type to) {
1469 if (from == to)
1470 return Conversion::None;
1471
1472 if (auto fromIntTy{mlir::dyn_cast<mlir::IntegerType>(from)}) {
1473 if (auto toIntTy{mlir::dyn_cast<mlir::IntegerType>(to)}) {
1474 return fromIntTy.getWidth() > toIntTy.getWidth() ? Conversion::Narrow
1475 : Conversion::Extend;
1476 }
1477 }
1478
1479 if (fir::isa_real(from) && fir::isa_real(to)) {
1480 return getFloatingPointWidth(from) > getFloatingPointWidth(to)
1481 ? Conversion::Narrow
1482 : Conversion::Extend;
1483 }
1484
1485 if (auto fromCplxTy{mlir::dyn_cast<fir::ComplexType>(from)}) {
1486 if (auto toCplxTy{mlir::dyn_cast<fir::ComplexType>(to)}) {
1487 return getFloatingPointWidth(fromCplxTy) >
1488 getFloatingPointWidth(toCplxTy)
1489 ? Conversion::Narrow
1490 : Conversion::Extend;
1491 }
1492 }
1493 // Notes:
1494 // - No conversion between character types, specialization of runtime
1495 // functions should be made instead.
1496 // - It is not clear there is a use case for automatic conversions
1497 // around Logical and it may damage hidden information in the physical
1498 // storage so do not do it.
1499 return Conversion::Forbidden;
1500 }
1501
1502 // Below are indexes to access data in conversions.
1503 // The order in data does matter for lexicographical_compare
1504 enum {
1505 narrowingArg = 0, // usually bad
1506 extendingResult, // usually bad
1507 nonExtendingResult, // usually ok
1508 nonNarrowingArg, // usually ok
1509 dataSize
1510 };
1511
1512 std::array<int, dataSize> conversions = {};
1513 bool infinite = false; // When forbidden conversion or wrong argument number
1514 };
1515
1516 using RtMap = Fortran::common::StaticMultimapView<MathOperation>;
1517 static constexpr RtMap mathOps(mathOperations);
1518 static_assert(mathOps.Verify() && "map must be sorted");
1519
1520 /// Look for a MathOperation entry specifying how to lower a mathematical
1521 /// operation defined by \p name with its result' and operands' types
1522 /// specified in the form of a FunctionType \p funcType.
1523 /// If exact match for the given types is found, then the function
1524 /// returns a pointer to the corresponding MathOperation.
1525 /// Otherwise, the function returns nullptr.
1526 /// If there is a MathOperation that can be used with additional
1527 /// type casts for the operands or/and result (non-exact match),
1528 /// then it is returned via \p bestNearMatch argument, and
1529 /// \p bestMatchDistance specifies the FunctionDistance between
1530 /// the requested operation and the non-exact match.
1531 static const MathOperation *
1532 searchMathOperation(fir::FirOpBuilder &builder,
1533 const IntrinsicHandlerEntry::RuntimeGeneratorRange &range,
1534 mlir::FunctionType funcType,
1535 const MathOperation **bestNearMatch,
1536 FunctionDistance &bestMatchDistance) {
1537 for (auto iter = range.first; iter != range.second && iter; ++iter) {
1538 const auto &impl = *iter;
1539 auto implType = impl.typeGenerator(builder.getContext(), builder);
1540 if (funcType == implType) {
1541 return &impl; // exact match
1542 }
1543
1544 FunctionDistance distance(funcType, implType);
1545 if (distance.isSmallerThan(bestMatchDistance)) {
1546 *bestNearMatch = &impl;
1547 bestMatchDistance = std::move(distance);
1548 }
1549 }
1550 return nullptr;
1551 }
1552
1553 /// Implementation of the operation defined by \p name with type
1554 /// \p funcType is not precise, and the actual available implementation
1555 /// is \p distance away from the requested. If using the available
1556 /// implementation results in a precision loss, emit an error message
1557 /// with the given code location \p loc.
1558 static void checkPrecisionLoss(llvm::StringRef name,
1559 mlir::FunctionType funcType,
1560 const FunctionDistance &distance,
1561 fir::FirOpBuilder &builder, mlir::Location loc) {
1562 if (!distance.isLosingPrecision())
1563 return;
1564
1565 // Using this runtime version requires narrowing the arguments
1566 // or extending the result. It is not numerically safe. There
1567 // is currently no quad math library that was described in
1568 // lowering and could be used here. Emit an error and continue
1569 // generating the code with the narrowing cast so that the user
1570 // can get a complete list of the problematic intrinsic calls.
1571 std::string message = prettyPrintIntrinsicName(
1572 builder, loc, "not yet implemented: no math runtime available for '",
1573 name, "'", funcType);
1574 mlir::emitError(loc, message);
1575 }
1576
1577 /// Helpers to get function type from arguments and result type.
1578 static mlir::FunctionType getFunctionType(std::optional<mlir::Type> resultType,
1579 llvm::ArrayRef<mlir::Value> arguments,
1580 fir::FirOpBuilder &builder) {
1581 llvm::SmallVector<mlir::Type> argTypes;
1582 for (mlir::Value arg : arguments)
1583 argTypes.push_back(arg.getType());
1584 llvm::SmallVector<mlir::Type> resTypes;
1585 if (resultType)
1586 resTypes.push_back(*resultType);
1587 return mlir::FunctionType::get(builder.getModule().getContext(), argTypes,
1588 resTypes);
1589 }
1590
1591 /// fir::ExtendedValue to mlir::Value translation layer
1592
1593 fir::ExtendedValue toExtendedValue(mlir::Value val, fir::FirOpBuilder &builder,
1594 mlir::Location loc) {
1595 assert(val && "optional unhandled here");
1596 mlir::Type type = val.getType();
1597 mlir::Value base = val;
1598 mlir::IndexType indexType = builder.getIndexType();
1599 llvm::SmallVector<mlir::Value> extents;
1600
1601 fir::factory::CharacterExprHelper charHelper{builder, loc};
1602 // FIXME: we may want to allow non character scalar here.
1603 if (charHelper.isCharacterScalar(type))
1604 return charHelper.toExtendedValue(val);
1605
1606 if (auto refType = mlir::dyn_cast<fir::ReferenceType>(type))
1607 type = refType.getEleTy();
1608
1609 if (auto arrayType = mlir::dyn_cast<fir::SequenceType>(type)) {
1610 type = arrayType.getEleTy();
1611 for (fir::SequenceType::Extent extent : arrayType.getShape()) {
1612 if (extent == fir::SequenceType::getUnknownExtent())
1613 break;
1614 extents.emplace_back(
1615 builder.createIntegerConstant(loc, indexType, extent));
1616 }
1617 // Last extent might be missing in case of assumed-size. If more extents
1618 // could not be deduced from type, that's an error (a fir.box should
1619 // have been used in the interface).
1620 if (extents.size() + 1 < arrayType.getShape().size())
1621 mlir::emitError(loc, "cannot retrieve array extents from type");
1622 } else if (mlir::isa<fir::BoxType>(type) ||
1623 mlir::isa<fir::RecordType>(type)) {
1624 fir::emitFatalError(loc, "not yet implemented: descriptor or derived type");
1625 }
1626
1627 if (!extents.empty())
1628 return fir::ArrayBoxValue{base, extents};
1629 return base;
1630 }
1631
1632 mlir::Value toValue(const fir::ExtendedValue &val, fir::FirOpBuilder &builder,
1633 mlir::Location loc) {
1634 if (const fir::CharBoxValue *charBox = val.getCharBox()) {
1635 mlir::Value buffer = charBox->getBuffer();
1636 auto buffTy = buffer.getType();
1637 if (mlir::isa<mlir::FunctionType>(buffTy))
1638 fir::emitFatalError(
1639 loc, "A character's buffer type cannot be a function type.");
1640 if (mlir::isa<fir::BoxCharType>(buffTy))
1641 return buffer;
1642 return fir::factory::CharacterExprHelper{builder, loc}.createEmboxChar(
1643 buffer, charBox->getLen());
1644 }
1645
1646 // FIXME: need to access other ExtendedValue variants and handle them
1647 // properly.
1648 return fir::getBase(val);
1649 }
1650
1651 //===----------------------------------------------------------------------===//
1652 // IntrinsicLibrary
1653 //===----------------------------------------------------------------------===//
1654
1655 static bool isIntrinsicModuleProcedure(llvm::StringRef name) {
1656 return name.starts_with("c_") || name.starts_with("compiler_") ||
1657 name.starts_with("ieee_") || name.starts_with("__ppc_");
1658 }
1659
1660 static bool isCoarrayIntrinsic(llvm::StringRef name) {
1661 return name.starts_with("atomic_") || name.starts_with("co_") ||
1662 name.contains("image") || name.ends_with("cobound") ||
1663 name == "team_number";
1664 }
1665
1666 /// Return the generic name of an intrinsic module procedure specific name.
1667 /// Remove any "__builtin_" prefix, and any specific suffix of the form
1668 /// {_[ail]?[0-9]+}*, such as _1 or _a4.
1669 llvm::StringRef genericName(llvm::StringRef specificName) {
1670 const std::string builtin = "__builtin_";
1671 llvm::StringRef name = specificName.starts_with(builtin)
1672 ? specificName.drop_front(builtin.size())
1673 : specificName;
1674 size_t size = name.size();
1675 if (isIntrinsicModuleProcedure(name))
1676 while (isdigit(name[size - 1]))
1677 while (name[--size] != '_')
1678 ;
1679 return name.drop_back(name.size() - size);
1680 }
1681
1682 std::optional<IntrinsicHandlerEntry::RuntimeGeneratorRange>
1683 lookupRuntimeGenerator(llvm::StringRef name, bool isPPCTarget) {
1684 if (auto range = mathOps.equal_range(name); range.first != range.second)
1685 return std::make_optional<IntrinsicHandlerEntry::RuntimeGeneratorRange>(
1686 range);
1687 // Search ppcMathOps only if targetting PowerPC arch
1688 if (isPPCTarget)
1689 if (auto range = checkPPCMathOperationsRange(name);
1690 range.first != range.second)
1691 return std::make_optional<IntrinsicHandlerEntry::RuntimeGeneratorRange>(
1692 range);
1693 return std::nullopt;
1694 }
1695
1696 std::optional<IntrinsicHandlerEntry>
1697 lookupIntrinsicHandler(fir::FirOpBuilder &builder,
1698 llvm::StringRef intrinsicName,
1699 std::optional<mlir::Type> resultType) {
1700 llvm::StringRef name = genericName(intrinsicName);
1701 if (const IntrinsicHandler *handler = findIntrinsicHandler(name))
1702 return std::make_optional<IntrinsicHandlerEntry>(handler);
1703 bool isPPCTarget = fir::getTargetTriple(builder.getModule()).isPPC();
1704 // If targeting PowerPC, check PPC intrinsic handlers.
1705 if (isPPCTarget)
1706 if (const IntrinsicHandler *ppcHandler = findPPCIntrinsicHandler(name))
1707 return std::make_optional<IntrinsicHandlerEntry>(ppcHandler);
1708 // Subroutines should have a handler.
1709 if (!resultType)
1710 return std::nullopt;
1711 // Try the runtime if no special handler was defined for the
1712 // intrinsic being called. Maths runtime only has numerical elemental.
1713 if (auto runtimeGeneratorRange = lookupRuntimeGenerator(name, isPPCTarget))
1714 return std::make_optional<IntrinsicHandlerEntry>(*runtimeGeneratorRange);
1715 return std::nullopt;
1716 }
1717
1718 /// Generate a TODO error message for an as yet unimplemented intrinsic.
1719 void crashOnMissingIntrinsic(mlir::Location loc,
1720 llvm::StringRef intrinsicName) {
1721 llvm::StringRef name = genericName(intrinsicName);
1722 if (isIntrinsicModuleProcedure(name))
1723 TODO(loc, "intrinsic module procedure: " + llvm::Twine(name));
1724 else if (isCoarrayIntrinsic(name))
1725 TODO(loc, "coarray: intrinsic " + llvm::Twine(name));
1726 else
1727 TODO(loc, "intrinsic: " + llvm::Twine(name.upper()));
1728 }
1729
1730 template <typename GeneratorType>
1731 fir::ExtendedValue IntrinsicLibrary::genElementalCall(
1732 GeneratorType generator, llvm::StringRef name, mlir::Type resultType,
1733 llvm::ArrayRef<fir::ExtendedValue> args, bool outline) {
1734 llvm::SmallVector<mlir::Value> scalarArgs;
1735 for (const fir::ExtendedValue &arg : args)
1736 if (arg.getUnboxed() || arg.getCharBox())
1737 scalarArgs.emplace_back(fir::getBase(arg));
1738 else
1739 fir::emitFatalError(loc, "nonscalar intrinsic argument");
1740 if (outline)
1741 return outlineInWrapper(generator, name, resultType, scalarArgs);
1742 return invokeGenerator(generator, resultType, scalarArgs);
1743 }
1744
1745 template <>
1746 fir::ExtendedValue
1747 IntrinsicLibrary::genElementalCall<IntrinsicLibrary::ExtendedGenerator>(
1748 ExtendedGenerator generator, llvm::StringRef name, mlir::Type resultType,
1749 llvm::ArrayRef<fir::ExtendedValue> args, bool outline) {
1750 for (const fir::ExtendedValue &arg : args) {
1751 auto *box = arg.getBoxOf<fir::BoxValue>();
1752 if (!arg.getUnboxed() && !arg.getCharBox() &&
1753 !(box && fir::isScalarBoxedRecordType(fir::getBase(*box).getType())))
1754 fir::emitFatalError(loc, "nonscalar intrinsic argument");
1755 }
1756 if (outline)
1757 return outlineInExtendedWrapper(generator, name, resultType, args);
1758 return std::invoke(generator, *this, resultType, args);
1759 }
1760
1761 template <>
1762 fir::ExtendedValue
1763 IntrinsicLibrary::genElementalCall<IntrinsicLibrary::SubroutineGenerator>(
1764 SubroutineGenerator generator, llvm::StringRef name, mlir::Type resultType,
1765 llvm::ArrayRef<fir::ExtendedValue> args, bool outline) {
1766 for (const fir::ExtendedValue &arg : args)
1767 if (!arg.getUnboxed() && !arg.getCharBox())
1768 // fir::emitFatalError(loc, "nonscalar intrinsic argument");
1769 crashOnMissingIntrinsic(loc, name);
1770 if (outline)
1771 return outlineInExtendedWrapper(generator, name, resultType, args);
1772 std::invoke(generator, *this, args);
1773 return mlir::Value();
1774 }
1775
1776 template <>
1777 fir::ExtendedValue
1778 IntrinsicLibrary::genElementalCall<IntrinsicLibrary::DualGenerator>(
1779 DualGenerator generator, llvm::StringRef name, mlir::Type resultType,
1780 llvm::ArrayRef<fir::ExtendedValue> args, bool outline) {
1781 assert(resultType.getImpl() && "expect elemental intrinsic to be functions");
1782
1783 for (const fir::ExtendedValue &arg : args)
1784 if (!arg.getUnboxed() && !arg.getCharBox())
1785 // fir::emitFatalError(loc, "nonscalar intrinsic argument");
1786 crashOnMissingIntrinsic(loc, name);
1787 if (outline)
1788 return outlineInExtendedWrapper(generator, name, resultType, args);
1789
1790 return std::invoke(generator, *this, std::optional<mlir::Type>{resultType},
1791 args);
1792 }
1793
1794 static fir::ExtendedValue
1795 invokeHandler(IntrinsicLibrary::ElementalGenerator generator,
1796 const IntrinsicHandler &handler,
1797 std::optional<mlir::Type> resultType,
1798 llvm::ArrayRef<fir::ExtendedValue> args, bool outline,
1799 IntrinsicLibrary &lib) {
1800 assert(resultType && "expect elemental intrinsic to be functions");
1801 return lib.genElementalCall(generator, handler.name, *resultType, args,
1802 outline);
1803 }
1804
1805 static fir::ExtendedValue
1806 invokeHandler(IntrinsicLibrary::ExtendedGenerator generator,
1807 const IntrinsicHandler &handler,
1808 std::optional<mlir::Type> resultType,
1809 llvm::ArrayRef<fir::ExtendedValue> args, bool outline,
1810 IntrinsicLibrary &lib) {
1811 assert(resultType && "expect intrinsic function");
1812 if (handler.isElemental)
1813 return lib.genElementalCall(generator, handler.name, *resultType, args,
1814 outline);
1815 if (outline)
1816 return lib.outlineInExtendedWrapper(generator, handler.name, *resultType,
1817 args);
1818 return std::invoke(generator, lib, *resultType, args);
1819 }
1820
1821 static fir::ExtendedValue
1822 invokeHandler(IntrinsicLibrary::SubroutineGenerator generator,
1823 const IntrinsicHandler &handler,
1824 std::optional<mlir::Type> resultType,
1825 llvm::ArrayRef<fir::ExtendedValue> args, bool outline,
1826 IntrinsicLibrary &lib) {
1827 if (handler.isElemental)
1828 return lib.genElementalCall(generator, handler.name, mlir::Type{}, args,
1829 outline);
1830 if (outline)
1831 return lib.outlineInExtendedWrapper(generator, handler.name, resultType,
1832 args);
1833 std::invoke(generator, lib, args);
1834 return mlir::Value{};
1835 }
1836
1837 static fir::ExtendedValue
1838 invokeHandler(IntrinsicLibrary::DualGenerator generator,
1839 const IntrinsicHandler &handler,
1840 std::optional<mlir::Type> resultType,
1841 llvm::ArrayRef<fir::ExtendedValue> args, bool outline,
1842 IntrinsicLibrary &lib) {
1843 if (handler.isElemental)
1844 return lib.genElementalCall(generator, handler.name, mlir::Type{}, args,
1845 outline);
1846 if (outline)
1847 return lib.outlineInExtendedWrapper(generator, handler.name, resultType,
1848 args);
1849
1850 return std::invoke(generator, lib, resultType, args);
1851 }
1852
1853 static std::pair<fir::ExtendedValue, bool> genIntrinsicCallHelper(
1854 const IntrinsicHandler *handler, std::optional<mlir::Type> resultType,
1855 llvm::ArrayRef<fir::ExtendedValue> args, IntrinsicLibrary &lib) {
1856 assert(handler && "must be set");
1857 bool outline = handler->outline || outlineAllIntrinsics;
1858 return {Fortran::common::visit(
1859 [&](auto &generator) -> fir::ExtendedValue {
1860 return invokeHandler(generator, *handler, resultType, args,
1861 outline, lib);
1862 },
1863 handler->generator),
1864 lib.resultMustBeFreed};
1865 }
1866
1867 static IntrinsicLibrary::RuntimeCallGenerator getRuntimeCallGeneratorHelper(
1868 const IntrinsicHandlerEntry::RuntimeGeneratorRange &, mlir::FunctionType,
1869 fir::FirOpBuilder &, mlir::Location);
1870
1871 static std::pair<fir::ExtendedValue, bool> genIntrinsicCallHelper(
1872 const IntrinsicHandlerEntry::RuntimeGeneratorRange &range,
1873 std::optional<mlir::Type> resultType,
1874 llvm::ArrayRef<fir::ExtendedValue> args, IntrinsicLibrary &lib) {
1875 assert(resultType.has_value() && "RuntimeGenerator are for functions only");
1876 assert(range.first != nullptr && "range should not be empty");
1877 fir::FirOpBuilder &builder = lib.builder;
1878 mlir::Location loc = lib.loc;
1879 llvm::StringRef name = range.first->key;
1880 // FIXME: using toValue to get the type won't work with array arguments.
1881 llvm::SmallVector<mlir::Value> mlirArgs;
1882 for (const fir::ExtendedValue &extendedVal : args) {
1883 mlir::Value val = toValue(extendedVal, builder, loc);
1884 if (!val)
1885 // If an absent optional gets there, most likely its handler has just
1886 // not yet been defined.
1887 crashOnMissingIntrinsic(loc, name);
1888 mlirArgs.emplace_back(val);
1889 }
1890 mlir::FunctionType soughtFuncType =
1891 getFunctionType(*resultType, mlirArgs, builder);
1892
1893 IntrinsicLibrary::RuntimeCallGenerator runtimeCallGenerator =
1894 getRuntimeCallGeneratorHelper(range, soughtFuncType, builder, loc);
1895 return {lib.genElementalCall(runtimeCallGenerator, name, *resultType, args,
1896 /*outline=*/outlineAllIntrinsics),
1897 lib.resultMustBeFreed};
1898 }
1899
1900 std::pair<fir::ExtendedValue, bool>
1901 genIntrinsicCall(fir::FirOpBuilder &builder, mlir::Location loc,
1902 const IntrinsicHandlerEntry &intrinsic,
1903 std::optional<mlir::Type> resultType,
1904 llvm::ArrayRef<fir::ExtendedValue> args,
1905 Fortran::lower::AbstractConverter *converter) {
1906 IntrinsicLibrary library{builder, loc, converter};
1907 return std::visit(
1908 [&](auto handler) -> auto {
1909 return genIntrinsicCallHelper(handler, resultType, args, library);
1910 },
1911 intrinsic.entry);
1912 }
1913
1914 std::pair<fir::ExtendedValue, bool>
1915 IntrinsicLibrary::genIntrinsicCall(llvm::StringRef specificName,
1916 std::optional<mlir::Type> resultType,
1917 llvm::ArrayRef<fir::ExtendedValue> args) {
1918 std::optional<IntrinsicHandlerEntry> intrinsic =
1919 lookupIntrinsicHandler(builder, specificName, resultType);
1920 if (!intrinsic.has_value())
1921 crashOnMissingIntrinsic(loc, specificName);
1922 return std::visit(
1923 [&](auto handler) -> auto {
1924 return genIntrinsicCallHelper(handler, resultType, args, *this);
1925 },
1926 intrinsic->entry);
1927 }
1928
1929 mlir::Value
1930 IntrinsicLibrary::invokeGenerator(ElementalGenerator generator,
1931 mlir::Type resultType,
1932 llvm::ArrayRef<mlir::Value> args) {
1933 return std::invoke(generator, *this, resultType, args);
1934 }
1935
1936 mlir::Value
1937 IntrinsicLibrary::invokeGenerator(RuntimeCallGenerator generator,
1938 mlir::Type resultType,
1939 llvm::ArrayRef<mlir::Value> args) {
1940 return generator(builder, loc, args);
1941 }
1942
1943 mlir::Value
1944 IntrinsicLibrary::invokeGenerator(ExtendedGenerator generator,
1945 mlir::Type resultType,
1946 llvm::ArrayRef<mlir::Value> args) {
1947 llvm::SmallVector<fir::ExtendedValue> extendedArgs;
1948 for (mlir::Value arg : args)
1949 extendedArgs.emplace_back(toExtendedValue(arg, builder, loc));
1950 auto extendedResult = std::invoke(generator, *this, resultType, extendedArgs);
1951 return toValue(extendedResult, builder, loc);
1952 }
1953
1954 mlir::Value
1955 IntrinsicLibrary::invokeGenerator(SubroutineGenerator generator,
1956 llvm::ArrayRef<mlir::Value> args) {
1957 llvm::SmallVector<fir::ExtendedValue> extendedArgs;
1958 for (mlir::Value arg : args)
1959 extendedArgs.emplace_back(toExtendedValue(arg, builder, loc));
1960 std::invoke(generator, *this, extendedArgs);
1961 return {};
1962 }
1963
1964 mlir::Value
1965 IntrinsicLibrary::invokeGenerator(DualGenerator generator,
1966 llvm::ArrayRef<mlir::Value> args) {
1967 llvm::SmallVector<fir::ExtendedValue> extendedArgs;
1968 for (mlir::Value arg : args)
1969 extendedArgs.emplace_back(toExtendedValue(arg, builder, loc));
1970 std::invoke(generator, *this, std::optional<mlir::Type>{}, extendedArgs);
1971 return {};
1972 }
1973
1974 mlir::Value
1975 IntrinsicLibrary::invokeGenerator(DualGenerator generator,
1976 mlir::Type resultType,
1977 llvm::ArrayRef<mlir::Value> args) {
1978 llvm::SmallVector<fir::ExtendedValue> extendedArgs;
1979 for (mlir::Value arg : args)
1980 extendedArgs.emplace_back(toExtendedValue(arg, builder, loc));
1981
1982 if (resultType.getImpl() == nullptr) {
1983 // TODO:
1984 assert(false && "result type is null");
1985 }
1986
1987 auto extendedResult = std::invoke(
1988 generator, *this, std::optional<mlir::Type>{resultType}, extendedArgs);
1989 return toValue(extendedResult, builder, loc);
1990 }
1991
1992 //===----------------------------------------------------------------------===//
1993 // Intrinsic Procedure Mangling
1994 //===----------------------------------------------------------------------===//
1995
1996 /// Helper to encode type into string for intrinsic procedure names.
1997 /// Note: mlir has Type::dump(ostream) methods but it may add "!" that is not
1998 /// suitable for function names.
1999 static std::string typeToString(mlir::Type t) {
2000 if (auto refT{mlir::dyn_cast<fir::ReferenceType>(t)})
2001 return "ref_" + typeToString(refT.getEleTy());
2002 if (auto i{mlir::dyn_cast<mlir::IntegerType>(t)}) {
2003 return "i" + std::to_string(i.getWidth());
2004 }
2005 if (auto cplx{mlir::dyn_cast<fir::ComplexType>(t)}) {
2006 return "z" + std::to_string(cplx.getFKind());
2007 }
2008 if (auto real{mlir::dyn_cast<fir::RealType>(t)}) {
2009 return "r" + std::to_string(real.getFKind());
2010 }
2011 if (auto f{mlir::dyn_cast<mlir::FloatType>(t)}) {
2012 return "f" + std::to_string(f.getWidth());
2013 }
2014 if (auto logical{mlir::dyn_cast<fir::LogicalType>(t)}) {
2015 return "l" + std::to_string(logical.getFKind());
2016 }
2017 if (auto character{mlir::dyn_cast<fir::CharacterType>(t)}) {
2018 return "c" + std::to_string(character.getFKind());
2019 }
2020 if (auto boxCharacter{mlir::dyn_cast<fir::BoxCharType>(t)}) {
2021 return "bc" + std::to_string(boxCharacter.getEleTy().getFKind());
2022 }
2023 llvm_unreachable("no mangling for type");
2024 }
2025
2026 /// Returns a name suitable to define mlir functions for Fortran intrinsic
2027 /// Procedure. These names are guaranteed to not conflict with user defined
2028 /// procedures. This is needed to implement Fortran generic intrinsics as
2029 /// several mlir functions specialized for the argument types.
2030 /// The result is guaranteed to be distinct for different mlir::FunctionType
2031 /// arguments. The mangling pattern is:
2032 /// fir.<generic name>.<result type>.<arg type>...
2033 /// e.g ACOS(COMPLEX(4)) is mangled as fir.acos.z4.z4
2034 /// For subroutines no result type is return but in order to still provide
2035 /// a unique mangled name, we use "void" as the return type. As in:
2036 /// fir.<generic name>.void.<arg type>...
2037 /// e.g. FREE(INTEGER(4)) is mangled as fir.free.void.i4
2038 static std::string mangleIntrinsicProcedure(llvm::StringRef intrinsic,
2039 mlir::FunctionType funTy) {
2040 std::string name = "fir.";
2041 name.append(intrinsic.str()).append(".");
2042 if (funTy.getNumResults() == 1)
2043 name.append(typeToString(funTy.getResult(0)));
2044 else if (funTy.getNumResults() == 0)
2045 name.append("void");
2046 else
2047 llvm_unreachable("more than one result value for function");
2048 unsigned e = funTy.getNumInputs();
2049 for (decltype(e) i = 0; i < e; ++i)
2050 name.append(".").append(typeToString(funTy.getInput(i)));
2051 return name;
2052 }
2053
2054 template <typename GeneratorType>
2055 mlir::func::FuncOp IntrinsicLibrary::getWrapper(GeneratorType generator,
2056 llvm::StringRef name,
2057 mlir::FunctionType funcType,
2058 bool loadRefArguments) {
2059 std::string wrapperName = mangleIntrinsicProcedure(name, funcType);
2060 mlir::func::FuncOp function = builder.getNamedFunction(wrapperName);
2061 if (!function) {
2062 // First time this wrapper is needed, build it.
2063 function = builder.createFunction(loc, wrapperName, funcType);
2064 function->setAttr("fir.intrinsic", builder.getUnitAttr());
2065 fir::factory::setInternalLinkage(function);
2066 function.addEntryBlock();
2067
2068 // Create local context to emit code into the newly created function
2069 // This new function is not linked to a source file location, only
2070 // its calls will be.
2071 auto localBuilder = std::make_unique<fir::FirOpBuilder>(
2072 function, builder.getKindMap(), builder.getMLIRSymbolTable());
2073 localBuilder->setFastMathFlags(builder.getFastMathFlags());
2074 localBuilder->setInsertionPointToStart(&function.front());
2075 // Location of code inside wrapper of the wrapper is independent from
2076 // the location of the intrinsic call.
2077 mlir::Location localLoc = localBuilder->getUnknownLoc();
2078 llvm::SmallVector<mlir::Value> localArguments;
2079 for (mlir::BlockArgument bArg : function.front().getArguments()) {
2080 auto refType = mlir::dyn_cast<fir::ReferenceType>(bArg.getType());
2081 if (loadRefArguments && refType) {
2082 auto loaded = localBuilder->create<fir::LoadOp>(localLoc, bArg);
2083 localArguments.push_back(loaded);
2084 } else {
2085 localArguments.push_back(bArg);
2086 }
2087 }
2088
2089 IntrinsicLibrary localLib{*localBuilder, localLoc};
2090
2091 if constexpr (std::is_same_v<GeneratorType, SubroutineGenerator>) {
2092 localLib.invokeGenerator(generator, localArguments);
2093 localBuilder->create<mlir::func::ReturnOp>(localLoc);
2094 } else {
2095 assert(funcType.getNumResults() == 1 &&
2096 "expect one result for intrinsic function wrapper type");
2097 mlir::Type resultType = funcType.getResult(0);
2098 auto result =
2099 localLib.invokeGenerator(generator, resultType, localArguments);
2100 localBuilder->create<mlir::func::ReturnOp>(localLoc, result);
2101 }
2102 } else {
2103 // Wrapper was already built, ensure it has the sought type
2104 assert(function.getFunctionType() == funcType &&
2105 "conflict between intrinsic wrapper types");
2106 }
2107 return function;
2108 }
2109
2110 /// Helpers to detect absent optional (not yet supported in outlining).
2111 bool static hasAbsentOptional(llvm::ArrayRef<mlir::Value> args) {
2112 for (const mlir::Value &arg : args)
2113 if (!arg)
2114 return true;
2115 return false;
2116 }
2117 bool static hasAbsentOptional(llvm::ArrayRef<fir::ExtendedValue> args) {
2118 for (const fir::ExtendedValue &arg : args)
2119 if (!fir::getBase(arg))
2120 return true;
2121 return false;
2122 }
2123
2124 template <typename GeneratorType>
2125 mlir::Value
2126 IntrinsicLibrary::outlineInWrapper(GeneratorType generator,
2127 llvm::StringRef name, mlir::Type resultType,
2128 llvm::ArrayRef<mlir::Value> args) {
2129 if (hasAbsentOptional(args)) {
2130 // TODO: absent optional in outlining is an issue: we cannot just ignore
2131 // them. Needs a better interface here. The issue is that we cannot easily
2132 // tell that a value is optional or not here if it is presents. And if it is
2133 // absent, we cannot tell what it type should be.
2134 TODO(loc, "cannot outline call to intrinsic " + llvm::Twine(name) +
2135 " with absent optional argument");
2136 }
2137
2138 mlir::FunctionType funcType = getFunctionType(resultType, args, builder);
2139 std::string funcName{name};
2140 llvm::raw_string_ostream nameOS{funcName};
2141 if (std::string fmfString{builder.getFastMathFlagsString()};
2142 !fmfString.empty()) {
2143 nameOS << '.' << fmfString;
2144 }
2145 mlir::func::FuncOp wrapper = getWrapper(generator, funcName, funcType);
2146 return builder.create<fir::CallOp>(loc, wrapper, args).getResult(0);
2147 }
2148
2149 template <typename GeneratorType>
2150 fir::ExtendedValue IntrinsicLibrary::outlineInExtendedWrapper(
2151 GeneratorType generator, llvm::StringRef name,
2152 std::optional<mlir::Type> resultType,
2153 llvm::ArrayRef<fir::ExtendedValue> args) {
2154 if (hasAbsentOptional(args))
2155 TODO(loc, "cannot outline call to intrinsic " + llvm::Twine(name) +
2156 " with absent optional argument");
2157 llvm::SmallVector<mlir::Value> mlirArgs;
2158 for (const auto &extendedVal : args)
2159 mlirArgs.emplace_back(toValue(extendedVal, builder, loc));
2160 mlir::FunctionType funcType = getFunctionType(resultType, mlirArgs, builder);
2161 mlir::func::FuncOp wrapper = getWrapper(generator, name, funcType);
2162 auto call = builder.create<fir::CallOp>(loc, wrapper, mlirArgs);
2163 if (resultType)
2164 return toExtendedValue(call.getResult(0), builder, loc);
2165 // Subroutine calls
2166 return mlir::Value{};
2167 }
2168
2169 static IntrinsicLibrary::RuntimeCallGenerator getRuntimeCallGeneratorHelper(
2170 const IntrinsicHandlerEntry::RuntimeGeneratorRange &range,
2171 mlir::FunctionType soughtFuncType, fir::FirOpBuilder &builder,
2172 mlir::Location loc) {
2173 assert(range.first != nullptr && "range should not be empty");
2174 llvm::StringRef name = range.first->key;
2175 // Look for a dedicated math operation generator, which
2176 // normally produces a single MLIR operation implementing
2177 // the math operation.
2178 const MathOperation *bestNearMatch = nullptr;
2179 FunctionDistance bestMatchDistance;
2180 const MathOperation *mathOp = searchMathOperation(
2181 builder, range, soughtFuncType, &bestNearMatch, bestMatchDistance);
2182 if (!mathOp && bestNearMatch) {
2183 // Use the best near match, optionally issuing an error,
2184 // if types conversions cause precision loss.
2185 checkPrecisionLoss(name, soughtFuncType, bestMatchDistance, builder, loc);
2186 mathOp = bestNearMatch;
2187 }
2188
2189 if (!mathOp) {
2190 std::string nameAndType;
2191 llvm::raw_string_ostream sstream(nameAndType);
2192 sstream << name << "\nrequested type: " << soughtFuncType;
2193 crashOnMissingIntrinsic(loc, nameAndType);
2194 }
2195
2196 mlir::FunctionType actualFuncType =
2197 mathOp->typeGenerator(builder.getContext(), builder);
2198
2199 assert(actualFuncType.getNumResults() == soughtFuncType.getNumResults() &&
2200 actualFuncType.getNumInputs() == soughtFuncType.getNumInputs() &&
2201 actualFuncType.getNumResults() == 1 && "Bad intrinsic match");
2202
2203 return [actualFuncType, mathOp,
2204 soughtFuncType](fir::FirOpBuilder &builder, mlir::Location loc,
2205 llvm::ArrayRef<mlir::Value> args) {
2206 llvm::SmallVector<mlir::Value> convertedArguments;
2207 for (auto [fst, snd] : llvm::zip(actualFuncType.getInputs(), args))
2208 convertedArguments.push_back(builder.createConvert(loc, fst, snd));
2209 mlir::Value result = mathOp->funcGenerator(
2210 builder, loc, *mathOp, actualFuncType, convertedArguments);
2211 mlir::Type soughtType = soughtFuncType.getResult(0);
2212 return builder.createConvert(loc, soughtType, result);
2213 };
2214 }
2215
2216 IntrinsicLibrary::RuntimeCallGenerator
2217 IntrinsicLibrary::getRuntimeCallGenerator(llvm::StringRef name,
2218 mlir::FunctionType soughtFuncType) {
2219 bool isPPCTarget = fir::getTargetTriple(builder.getModule()).isPPC();
2220 std::optional<IntrinsicHandlerEntry::RuntimeGeneratorRange> range =
2221 lookupRuntimeGenerator(name, isPPCTarget);
2222 if (!range.has_value())
2223 crashOnMissingIntrinsic(loc, name);
2224 return getRuntimeCallGeneratorHelper(*range, soughtFuncType, builder, loc);
2225 }
2226
2227 mlir::SymbolRefAttr IntrinsicLibrary::getUnrestrictedIntrinsicSymbolRefAttr(
2228 llvm::StringRef name, mlir::FunctionType signature) {
2229 // Unrestricted intrinsics signature follows implicit rules: argument
2230 // are passed by references. But the runtime versions expect values.
2231 // So instead of duplicating the runtime, just have the wrappers loading
2232 // this before calling the code generators.
2233 bool loadRefArguments = true;
2234 mlir::func::FuncOp funcOp;
2235 if (const IntrinsicHandler *handler = findIntrinsicHandler(name))
2236 funcOp = Fortran::common::visit(
2237 [&](auto generator) {
2238 return getWrapper(generator, name, signature, loadRefArguments);
2239 },
2240 handler->generator);
2241
2242 if (!funcOp) {
2243 llvm::SmallVector<mlir::Type> argTypes;
2244 for (mlir::Type type : signature.getInputs()) {
2245 if (auto refType = mlir::dyn_cast<fir::ReferenceType>(type))
2246 argTypes.push_back(refType.getEleTy());
2247 else
2248 argTypes.push_back(type);
2249 }
2250 mlir::FunctionType soughtFuncType =
2251 builder.getFunctionType(argTypes, signature.getResults());
2252 IntrinsicLibrary::RuntimeCallGenerator rtCallGenerator =
2253 getRuntimeCallGenerator(name, soughtFuncType);
2254 funcOp = getWrapper(rtCallGenerator, name, signature, loadRefArguments);
2255 }
2256
2257 return mlir::SymbolRefAttr::get(funcOp);
2258 }
2259
2260 fir::ExtendedValue
2261 IntrinsicLibrary::readAndAddCleanUp(fir::MutableBoxValue resultMutableBox,
2262 mlir::Type resultType,
2263 llvm::StringRef intrinsicName) {
2264 fir::ExtendedValue res =
2265 fir::factory::genMutableBoxRead(builder, loc, resultMutableBox);
2266 return res.match(
2267 [&](const fir::ArrayBoxValue &box) -> fir::ExtendedValue {
2268 setResultMustBeFreed();
2269 return box;
2270 },
2271 [&](const fir::BoxValue &box) -> fir::ExtendedValue {
2272 setResultMustBeFreed();
2273 return box;
2274 },
2275 [&](const fir::CharArrayBoxValue &box) -> fir::ExtendedValue {
2276 setResultMustBeFreed();
2277 return box;
2278 },
2279 [&](const mlir::Value &tempAddr) -> fir::ExtendedValue {
2280 auto load = builder.create<fir::LoadOp>(loc, resultType, tempAddr);
2281 // Temp can be freed right away since it was loaded.
2282 builder.create<fir::FreeMemOp>(loc, tempAddr);
2283 return load;
2284 },
2285 [&](const fir::CharBoxValue &box) -> fir::ExtendedValue {
2286 setResultMustBeFreed();
2287 return box;
2288 },
2289 [&](const auto &) -> fir::ExtendedValue {
2290 fir::emitFatalError(loc, "unexpected result for " + intrinsicName);
2291 });
2292 }
2293
2294 //===----------------------------------------------------------------------===//
2295 // Code generators for the intrinsic
2296 //===----------------------------------------------------------------------===//
2297
2298 mlir::Value IntrinsicLibrary::genRuntimeCall(llvm::StringRef name,
2299 mlir::Type resultType,
2300 llvm::ArrayRef<mlir::Value> args) {
2301 mlir::FunctionType soughtFuncType =
2302 getFunctionType(resultType, args, builder);
2303 return getRuntimeCallGenerator(name, soughtFuncType)(builder, loc, args);
2304 }
2305
2306 mlir::Value IntrinsicLibrary::genConversion(mlir::Type resultType,
2307 llvm::ArrayRef<mlir::Value> args) {
2308 // There can be an optional kind in second argument.
2309 assert(args.size() >= 1);
2310 return builder.convertWithSemantics(loc, resultType, args[0]);
2311 }
2312
2313 template <const char *intrinsicName>
2314 void IntrinsicLibrary::genModuleProcTODO(
2315 llvm::ArrayRef<fir::ExtendedValue> args) {
2316 crashOnMissingIntrinsic(loc, intrinsicName);
2317 }
2318
2319 // ABORT
2320 void IntrinsicLibrary::genAbort(llvm::ArrayRef<fir::ExtendedValue> args) {
2321 assert(args.size() == 0);
2322 fir::runtime::genAbort(builder, loc);
2323 }
2324
2325 // ABS
2326 mlir::Value IntrinsicLibrary::genAbs(mlir::Type resultType,
2327 llvm::ArrayRef<mlir::Value> args) {
2328 assert(args.size() == 1);
2329 mlir::Value arg = args[0];
2330 mlir::Type type = arg.getType();
2331 if (fir::isa_real(type) || fir::isa_complex(type)) {
2332 // Runtime call to fp abs. An alternative would be to use mlir
2333 // math::AbsFOp but it does not support all fir floating point types.
2334 return genRuntimeCall("abs", resultType, args);
2335 }
2336 if (auto intType = mlir::dyn_cast<mlir::IntegerType>(type)) {
2337 // At the time of this implementation there is no abs op in mlir.
2338 // So, implement abs here without branching.
2339 mlir::Value shift =
2340 builder.createIntegerConstant(loc, intType, intType.getWidth() - 1);
2341 auto mask = builder.create<mlir::arith::ShRSIOp>(loc, arg, shift);
2342 auto xored = builder.create<mlir::arith::XOrIOp>(loc, arg, mask);
2343 return builder.create<mlir::arith::SubIOp>(loc, xored, mask);
2344 }
2345 llvm_unreachable("unexpected type in ABS argument");
2346 }
2347
2348 // ACOSD
2349 mlir::Value IntrinsicLibrary::genAcosd(mlir::Type resultType,
2350 llvm::ArrayRef<mlir::Value> args) {
2351 assert(args.size() == 1);
2352 mlir::MLIRContext *context = builder.getContext();
2353 mlir::FunctionType ftype =
2354 mlir::FunctionType::get(context, {resultType}, {args[0].getType()});
2355 llvm::APFloat pi = llvm::APFloat(llvm::numbers::pi);
2356 mlir::Value dfactor = builder.createRealConstant(
2357 loc, mlir::FloatType::getF64(context), pi / llvm::APFloat(180.0));
2358 mlir::Value factor = builder.createConvert(loc, args[0].getType(), dfactor);
2359 mlir::Value arg = builder.create<mlir::arith::MulFOp>(loc, args[0], factor);
2360 return getRuntimeCallGenerator("acos", ftype)(builder, loc, {arg});
2361 }
2362
2363 // ADJUSTL & ADJUSTR
2364 template <void (*CallRuntime)(fir::FirOpBuilder &, mlir::Location loc,
2365 mlir::Value, mlir::Value)>
2366 fir::ExtendedValue
2367 IntrinsicLibrary::genAdjustRtCall(mlir::Type resultType,
2368 llvm::ArrayRef<fir::ExtendedValue> args) {
2369 assert(args.size() == 1);
2370 mlir::Value string = builder.createBox(loc, args[0]);
2371 // Create a mutable fir.box to be passed to the runtime for the result.
2372 fir::MutableBoxValue resultMutableBox =
2373 fir::factory::createTempMutableBox(builder, loc, resultType);
2374 mlir::Value resultIrBox =
2375 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
2376
2377 // Call the runtime -- the runtime will allocate the result.
2378 CallRuntime(builder, loc, resultIrBox, string);
2379 // Read result from mutable fir.box and add it to the list of temps to be
2380 // finalized by the StatementContext.
2381 return readAndAddCleanUp(resultMutableBox, resultType, "ADJUSTL or ADJUSTR");
2382 }
2383
2384 // AIMAG
2385 mlir::Value IntrinsicLibrary::genAimag(mlir::Type resultType,
2386 llvm::ArrayRef<mlir::Value> args) {
2387 assert(args.size() == 1);
2388 return fir::factory::Complex{builder, loc}.extractComplexPart(
2389 args[0], /*isImagPart=*/true);
2390 }
2391
2392 // AINT
2393 mlir::Value IntrinsicLibrary::genAint(mlir::Type resultType,
2394 llvm::ArrayRef<mlir::Value> args) {
2395 assert(args.size() >= 1 && args.size() <= 2);
2396 // Skip optional kind argument to search the runtime; it is already reflected
2397 // in result type.
2398 return genRuntimeCall("aint", resultType, {args[0]});
2399 }
2400
2401 // ALL
2402 fir::ExtendedValue
2403 IntrinsicLibrary::genAll(mlir::Type resultType,
2404 llvm::ArrayRef<fir::ExtendedValue> args) {
2405
2406 assert(args.size() == 2);
2407 // Handle required mask argument
2408 mlir::Value mask = builder.createBox(loc, args[0]);
2409
2410 fir::BoxValue maskArry = builder.createBox(loc, args[0]);
2411 int rank = maskArry.rank();
2412 assert(rank >= 1);
2413
2414 // Handle optional dim argument
2415 bool absentDim = isStaticallyAbsent(args[1]);
2416 mlir::Value dim =
2417 absentDim ? builder.createIntegerConstant(loc, builder.getIndexType(), 1)
2418 : fir::getBase(args[1]);
2419
2420 if (rank == 1 || absentDim)
2421 return builder.createConvert(loc, resultType,
2422 fir::runtime::genAll(builder, loc, mask, dim));
2423
2424 // else use the result descriptor AllDim() intrinsic
2425
2426 // Create mutable fir.box to be passed to the runtime for the result.
2427
2428 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, rank - 1);
2429 fir::MutableBoxValue resultMutableBox =
2430 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
2431 mlir::Value resultIrBox =
2432 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
2433 // Call runtime. The runtime is allocating the result.
2434 fir::runtime::genAllDescriptor(builder, loc, resultIrBox, mask, dim);
2435 return readAndAddCleanUp(resultMutableBox, resultType, "ALL");
2436 }
2437
2438 // ALLOCATED
2439 fir::ExtendedValue
2440 IntrinsicLibrary::genAllocated(mlir::Type resultType,
2441 llvm::ArrayRef<fir::ExtendedValue> args) {
2442 assert(args.size() == 1);
2443 return args[0].match(
2444 [&](const fir::MutableBoxValue &x) -> fir::ExtendedValue {
2445 return fir::factory::genIsAllocatedOrAssociatedTest(builder, loc, x);
2446 },
2447 [&](const auto &) -> fir::ExtendedValue {
2448 fir::emitFatalError(loc,
2449 "allocated arg not lowered to MutableBoxValue");
2450 });
2451 }
2452
2453 // ANINT
2454 mlir::Value IntrinsicLibrary::genAnint(mlir::Type resultType,
2455 llvm::ArrayRef<mlir::Value> args) {
2456 assert(args.size() >= 1 && args.size() <= 2);
2457 // Skip optional kind argument to search the runtime; it is already reflected
2458 // in result type.
2459 return genRuntimeCall("anint", resultType, {args[0]});
2460 }
2461
2462 // ANY
2463 fir::ExtendedValue
2464 IntrinsicLibrary::genAny(mlir::Type resultType,
2465 llvm::ArrayRef<fir::ExtendedValue> args) {
2466
2467 assert(args.size() == 2);
2468 // Handle required mask argument
2469 mlir::Value mask = builder.createBox(loc, args[0]);
2470
2471 fir::BoxValue maskArry = builder.createBox(loc, args[0]);
2472 int rank = maskArry.rank();
2473 assert(rank >= 1);
2474
2475 // Handle optional dim argument
2476 bool absentDim = isStaticallyAbsent(args[1]);
2477 mlir::Value dim =
2478 absentDim ? builder.createIntegerConstant(loc, builder.getIndexType(), 1)
2479 : fir::getBase(args[1]);
2480
2481 if (rank == 1 || absentDim)
2482 return builder.createConvert(loc, resultType,
2483 fir::runtime::genAny(builder, loc, mask, dim));
2484
2485 // else use the result descriptor AnyDim() intrinsic
2486
2487 // Create mutable fir.box to be passed to the runtime for the result.
2488
2489 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, rank - 1);
2490 fir::MutableBoxValue resultMutableBox =
2491 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
2492 mlir::Value resultIrBox =
2493 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
2494 // Call runtime. The runtime is allocating the result.
2495 fir::runtime::genAnyDescriptor(builder, loc, resultIrBox, mask, dim);
2496 return readAndAddCleanUp(resultMutableBox, resultType, "ANY");
2497 }
2498
2499 // ASIND
2500 mlir::Value IntrinsicLibrary::genAsind(mlir::Type resultType,
2501 llvm::ArrayRef<mlir::Value> args) {
2502 assert(args.size() == 1);
2503 mlir::MLIRContext *context = builder.getContext();
2504 mlir::FunctionType ftype =
2505 mlir::FunctionType::get(context, {resultType}, {args[0].getType()});
2506 llvm::APFloat pi = llvm::APFloat(llvm::numbers::pi);
2507 mlir::Value dfactor = builder.createRealConstant(
2508 loc, mlir::FloatType::getF64(context), pi / llvm::APFloat(180.0));
2509 mlir::Value factor = builder.createConvert(loc, args[0].getType(), dfactor);
2510 mlir::Value arg = builder.create<mlir::arith::MulFOp>(loc, args[0], factor);
2511 return getRuntimeCallGenerator("asin", ftype)(builder, loc, {arg});
2512 }
2513
2514 // ATAND, ATAN2D
2515 mlir::Value IntrinsicLibrary::genAtand(mlir::Type resultType,
2516 llvm::ArrayRef<mlir::Value> args) {
2517 // assert for: atand(X), atand(Y,X), atan2d(Y,X)
2518 assert(args.size() >= 1 && args.size() <= 2);
2519
2520 mlir::MLIRContext *context = builder.getContext();
2521 mlir::Value atan;
2522
2523 // atand = atan * 180/pi
2524 if (args.size() == 2) {
2525 atan = builder.create<mlir::math::Atan2Op>(loc, fir::getBase(args[0]),
2526 fir::getBase(args[1]));
2527 } else {
2528 mlir::FunctionType ftype =
2529 mlir::FunctionType::get(context, {resultType}, {args[0].getType()});
2530 atan = getRuntimeCallGenerator("atan", ftype)(builder, loc, args);
2531 }
2532 llvm::APFloat pi = llvm::APFloat(llvm::numbers::pi);
2533 mlir::Value dfactor = builder.createRealConstant(
2534 loc, mlir::FloatType::getF64(context), llvm::APFloat(180.0) / pi);
2535 mlir::Value factor = builder.createConvert(loc, resultType, dfactor);
2536 return builder.create<mlir::arith::MulFOp>(loc, atan, factor);
2537 }
2538
2539 // ATANPI, ATAN2PI
2540 mlir::Value IntrinsicLibrary::genAtanpi(mlir::Type resultType,
2541 llvm::ArrayRef<mlir::Value> args) {
2542 // assert for: atanpi(X), atanpi(Y,X), atan2pi(Y,X)
2543 assert(args.size() >= 1 && args.size() <= 2);
2544
2545 mlir::Value atan;
2546 mlir::MLIRContext *context = builder.getContext();
2547
2548 // atanpi = atan / pi
2549 if (args.size() == 2) {
2550 atan = builder.create<mlir::math::Atan2Op>(loc, fir::getBase(args[0]),
2551 fir::getBase(args[1]));
2552 } else {
2553 mlir::FunctionType ftype =
2554 mlir::FunctionType::get(context, {resultType}, {args[0].getType()});
2555 atan = getRuntimeCallGenerator("atan", ftype)(builder, loc, args);
2556 }
2557 llvm::APFloat inv_pi = llvm::APFloat(llvm::numbers::inv_pi);
2558 mlir::Value dfactor =
2559 builder.createRealConstant(loc, mlir::FloatType::getF64(context), inv_pi);
2560 mlir::Value factor = builder.createConvert(loc, resultType, dfactor);
2561 return builder.create<mlir::arith::MulFOp>(loc, atan, factor);
2562 }
2563
2564 // ASSOCIATED
2565 fir::ExtendedValue
2566 IntrinsicLibrary::genAssociated(mlir::Type resultType,
2567 llvm::ArrayRef<fir::ExtendedValue> args) {
2568 assert(args.size() == 2);
2569 mlir::Type ptrTy = fir::getBase(args[0]).getType();
2570 if (ptrTy && (fir::isBoxProcAddressType(ptrTy) ||
2571 mlir::isa<fir::BoxProcType>(ptrTy))) {
2572 mlir::Value pointerBoxProc =
2573 fir::isBoxProcAddressType(ptrTy)
2574 ? builder.create<fir::LoadOp>(loc, fir::getBase(args[0]))
2575 : fir::getBase(args[0]);
2576 mlir::Value pointerTarget =
2577 builder.create<fir::BoxAddrOp>(loc, pointerBoxProc);
2578 if (isStaticallyAbsent(args[1]))
2579 return builder.genIsNotNullAddr(loc, pointerTarget);
2580 mlir::Value target = fir::getBase(args[1]);
2581 if (fir::isBoxProcAddressType(target.getType()))
2582 target = builder.create<fir::LoadOp>(loc, target);
2583 if (mlir::isa<fir::BoxProcType>(target.getType()))
2584 target = builder.create<fir::BoxAddrOp>(loc, target);
2585 mlir::Type intPtrTy = builder.getIntPtrType();
2586 mlir::Value pointerInt =
2587 builder.createConvert(loc, intPtrTy, pointerTarget);
2588 mlir::Value targetInt = builder.createConvert(loc, intPtrTy, target);
2589 mlir::Value sameTarget = builder.create<mlir::arith::CmpIOp>(
2590 loc, mlir::arith::CmpIPredicate::eq, pointerInt, targetInt);
2591 mlir::Value zero = builder.createIntegerConstant(loc, intPtrTy, 0);
2592 mlir::Value notNull = builder.create<mlir::arith::CmpIOp>(
2593 loc, mlir::arith::CmpIPredicate::ne, zero, pointerInt);
2594 // The not notNull test covers the following two cases:
2595 // - TARGET is a procedure that is OPTIONAL and absent at runtime.
2596 // - TARGET is a procedure pointer that is NULL.
2597 // In both cases, ASSOCIATED should be false if POINTER is NULL.
2598 return builder.create<mlir::arith::AndIOp>(loc, sameTarget, notNull);
2599 }
2600 auto *pointer =
2601 args[0].match([&](const fir::MutableBoxValue &x) { return &x; },
2602 [&](const auto &) -> const fir::MutableBoxValue * {
2603 fir::emitFatalError(loc, "pointer not a MutableBoxValue");
2604 });
2605 const fir::ExtendedValue &target = args[1];
2606 if (isStaticallyAbsent(target))
2607 return fir::factory::genIsAllocatedOrAssociatedTest(builder, loc, *pointer);
2608 mlir::Value targetBox = builder.createBox(loc, target);
2609 mlir::Value pointerBoxRef =
2610 fir::factory::getMutableIRBox(builder, loc, *pointer);
2611 auto pointerBox = builder.create<fir::LoadOp>(loc, pointerBoxRef);
2612 return fir::runtime::genAssociated(builder, loc, pointerBox, targetBox);
2613 }
2614
2615 // BESSEL_JN
2616 fir::ExtendedValue
2617 IntrinsicLibrary::genBesselJn(mlir::Type resultType,
2618 llvm::ArrayRef<fir::ExtendedValue> args) {
2619 assert(args.size() == 2 || args.size() == 3);
2620
2621 mlir::Value x = fir::getBase(args.back());
2622
2623 if (args.size() == 2) {
2624 mlir::Value n = fir::getBase(args[0]);
2625
2626 return genRuntimeCall("bessel_jn", resultType, {n, x});
2627 } else {
2628 mlir::Value n1 = fir::getBase(args[0]);
2629 mlir::Value n2 = fir::getBase(args[1]);
2630
2631 mlir::Type intTy = n1.getType();
2632 mlir::Type floatTy = x.getType();
2633 mlir::Value zero = builder.createRealZeroConstant(loc, floatTy);
2634 mlir::Value one = builder.createIntegerConstant(loc, intTy, 1);
2635
2636 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, 1);
2637 fir::MutableBoxValue resultMutableBox =
2638 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
2639 mlir::Value resultBox =
2640 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
2641
2642 mlir::Value cmpXEq0 = builder.create<mlir::arith::CmpFOp>(
2643 loc, mlir::arith::CmpFPredicate::UEQ, x, zero);
2644 mlir::Value cmpN1LtN2 = builder.create<mlir::arith::CmpIOp>(
2645 loc, mlir::arith::CmpIPredicate::slt, n1, n2);
2646 mlir::Value cmpN1EqN2 = builder.create<mlir::arith::CmpIOp>(
2647 loc, mlir::arith::CmpIPredicate::eq, n1, n2);
2648
2649 auto genXEq0 = [&]() {
2650 fir::runtime::genBesselJnX0(builder, loc, floatTy, resultBox, n1, n2);
2651 };
2652
2653 auto genN1LtN2 = [&]() {
2654 // The runtime generates the values in the range using a backward
2655 // recursion from n2 to n1. (see https://dlmf.nist.gov/10.74.iv and
2656 // https://dlmf.nist.gov/10.6.E1). When n1 < n2, this requires
2657 // the values of BESSEL_JN(n2) and BESSEL_JN(n2 - 1) since they
2658 // are the anchors of the recursion.
2659 mlir::Value n2_1 = builder.create<mlir::arith::SubIOp>(loc, n2, one);
2660 mlir::Value bn2 = genRuntimeCall("bessel_jn", resultType, {n2, x});
2661 mlir::Value bn2_1 = genRuntimeCall("bessel_jn", resultType, {n2_1, x});
2662 fir::runtime::genBesselJn(builder, loc, resultBox, n1, n2, x, bn2, bn2_1);
2663 };
2664
2665 auto genN1EqN2 = [&]() {
2666 // When n1 == n2, only BESSEL_JN(n2) is needed.
2667 mlir::Value bn2 = genRuntimeCall("bessel_jn", resultType, {n2, x});
2668 fir::runtime::genBesselJn(builder, loc, resultBox, n1, n2, x, bn2, zero);
2669 };
2670
2671 auto genN1GtN2 = [&]() {
2672 // The standard requires n1 <= n2. However, we still need to allocate
2673 // a zero-length array and return it when n1 > n2, so we do need to call
2674 // the runtime function.
2675 fir::runtime::genBesselJn(builder, loc, resultBox, n1, n2, x, zero, zero);
2676 };
2677
2678 auto genN1GeN2 = [&] {
2679 builder.genIfThenElse(loc, cmpN1EqN2)
2680 .genThen(genN1EqN2)
2681 .genElse(genN1GtN2)
2682 .end();
2683 };
2684
2685 auto genXNeq0 = [&]() {
2686 builder.genIfThenElse(loc, cmpN1LtN2)
2687 .genThen(genN1LtN2)
2688 .genElse(genN1GeN2)
2689 .end();
2690 };
2691
2692 builder.genIfThenElse(loc, cmpXEq0)
2693 .genThen(genXEq0)
2694 .genElse(genXNeq0)
2695 .end();
2696 return readAndAddCleanUp(resultMutableBox, resultType, "BESSEL_JN");
2697 }
2698 }
2699
2700 // BESSEL_YN
2701 fir::ExtendedValue
2702 IntrinsicLibrary::genBesselYn(mlir::Type resultType,
2703 llvm::ArrayRef<fir::ExtendedValue> args) {
2704 assert(args.size() == 2 || args.size() == 3);
2705
2706 mlir::Value x = fir::getBase(args.back());
2707
2708 if (args.size() == 2) {
2709 mlir::Value n = fir::getBase(args[0]);
2710
2711 return genRuntimeCall("bessel_yn", resultType, {n, x});
2712 } else {
2713 mlir::Value n1 = fir::getBase(args[0]);
2714 mlir::Value n2 = fir::getBase(args[1]);
2715
2716 mlir::Type floatTy = x.getType();
2717 mlir::Type intTy = n1.getType();
2718 mlir::Value zero = builder.createRealZeroConstant(loc, floatTy);
2719 mlir::Value one = builder.createIntegerConstant(loc, intTy, 1);
2720
2721 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, 1);
2722 fir::MutableBoxValue resultMutableBox =
2723 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
2724 mlir::Value resultBox =
2725 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
2726
2727 mlir::Value cmpXEq0 = builder.create<mlir::arith::CmpFOp>(
2728 loc, mlir::arith::CmpFPredicate::UEQ, x, zero);
2729 mlir::Value cmpN1LtN2 = builder.create<mlir::arith::CmpIOp>(
2730 loc, mlir::arith::CmpIPredicate::slt, n1, n2);
2731 mlir::Value cmpN1EqN2 = builder.create<mlir::arith::CmpIOp>(
2732 loc, mlir::arith::CmpIPredicate::eq, n1, n2);
2733
2734 auto genXEq0 = [&]() {
2735 fir::runtime::genBesselYnX0(builder, loc, floatTy, resultBox, n1, n2);
2736 };
2737
2738 auto genN1LtN2 = [&]() {
2739 // The runtime generates the values in the range using a forward
2740 // recursion from n1 to n2. (see https://dlmf.nist.gov/10.74.iv and
2741 // https://dlmf.nist.gov/10.6.E1). When n1 < n2, this requires
2742 // the values of BESSEL_YN(n1) and BESSEL_YN(n1 + 1) since they
2743 // are the anchors of the recursion.
2744 mlir::Value n1_1 = builder.create<mlir::arith::AddIOp>(loc, n1, one);
2745 mlir::Value bn1 = genRuntimeCall("bessel_yn", resultType, {n1, x});
2746 mlir::Value bn1_1 = genRuntimeCall("bessel_yn", resultType, {n1_1, x});
2747 fir::runtime::genBesselYn(builder, loc, resultBox, n1, n2, x, bn1, bn1_1);
2748 };
2749
2750 auto genN1EqN2 = [&]() {
2751 // When n1 == n2, only BESSEL_YN(n1) is needed.
2752 mlir::Value bn1 = genRuntimeCall("bessel_yn", resultType, {n1, x});
2753 fir::runtime::genBesselYn(builder, loc, resultBox, n1, n2, x, bn1, zero);
2754 };
2755
2756 auto genN1GtN2 = [&]() {
2757 // The standard requires n1 <= n2. However, we still need to allocate
2758 // a zero-length array and return it when n1 > n2, so we do need to call
2759 // the runtime function.
2760 fir::runtime::genBesselYn(builder, loc, resultBox, n1, n2, x, zero, zero);
2761 };
2762
2763 auto genN1GeN2 = [&] {
2764 builder.genIfThenElse(loc, cmpN1EqN2)
2765 .genThen(genN1EqN2)
2766 .genElse(genN1GtN2)
2767 .end();
2768 };
2769
2770 auto genXNeq0 = [&]() {
2771 builder.genIfThenElse(loc, cmpN1LtN2)
2772 .genThen(genN1LtN2)
2773 .genElse(genN1GeN2)
2774 .end();
2775 };
2776
2777 builder.genIfThenElse(loc, cmpXEq0)
2778 .genThen(genXEq0)
2779 .genElse(genXNeq0)
2780 .end();
2781 return readAndAddCleanUp(resultMutableBox, resultType, "BESSEL_YN");
2782 }
2783 }
2784
2785 // BGE, BGT, BLE, BLT
2786 template <mlir::arith::CmpIPredicate pred>
2787 mlir::Value
2788 IntrinsicLibrary::genBitwiseCompare(mlir::Type resultType,
2789 llvm::ArrayRef<mlir::Value> args) {
2790 assert(args.size() == 2);
2791
2792 mlir::Value arg0 = args[0];
2793 mlir::Value arg1 = args[1];
2794 mlir::Type arg0Ty = arg0.getType();
2795 mlir::Type arg1Ty = arg1.getType();
2796 unsigned bits0 = arg0Ty.getIntOrFloatBitWidth();
2797 unsigned bits1 = arg1Ty.getIntOrFloatBitWidth();
2798
2799 // Arguments do not have to be of the same integer type. However, if neither
2800 // of the arguments is a BOZ literal, then the shorter of the two needs
2801 // to be converted to the longer by zero-extending (not sign-extending)
2802 // to the left [Fortran 2008, 13.3.2].
2803 //
2804 // In the case of BOZ literals, the standard describes zero-extension or
2805 // truncation depending on the kind of the result [Fortran 2008, 13.3.3].
2806 // However, that seems to be relevant for the case where the type of the
2807 // result must match the type of the BOZ literal. That is not the case for
2808 // these intrinsics, so, again, zero-extend to the larger type.
2809 //
2810 if (bits0 > bits1)
2811 arg1 = builder.create<mlir::arith::ExtUIOp>(loc, arg0Ty, arg1);
2812 else if (bits0 < bits1)
2813 arg0 = builder.create<mlir::arith::ExtUIOp>(loc, arg1Ty, arg0);
2814
2815 return builder.create<mlir::arith::CmpIOp>(loc, pred, arg0, arg1);
2816 }
2817
2818 // BTEST
2819 mlir::Value IntrinsicLibrary::genBtest(mlir::Type resultType,
2820 llvm::ArrayRef<mlir::Value> args) {
2821 // A conformant BTEST(I,POS) call satisfies:
2822 // POS >= 0
2823 // POS < BIT_SIZE(I)
2824 // Return: (I >> POS) & 1
2825 assert(args.size() == 2);
2826 mlir::Type argType = args[0].getType();
2827 mlir::Value pos = builder.createConvert(loc, argType, args[1]);
2828 auto shift = builder.create<mlir::arith::ShRUIOp>(loc, args[0], pos);
2829 mlir::Value one = builder.createIntegerConstant(loc, argType, 1);
2830 auto res = builder.create<mlir::arith::AndIOp>(loc, shift, one);
2831 return builder.createConvert(loc, resultType, res);
2832 }
2833
2834 static mlir::Value getAddrFromBox(fir::FirOpBuilder &builder,
2835 mlir::Location loc, fir::ExtendedValue arg,
2836 bool isFunc) {
2837 mlir::Value argValue = fir::getBase(arg);
2838 mlir::Value addr{nullptr};
2839 if (isFunc) {
2840 auto funcTy = mlir::cast<fir::BoxProcType>(argValue.getType()).getEleTy();
2841 addr = builder.create<fir::BoxAddrOp>(loc, funcTy, argValue);
2842 } else {
2843 const auto *box = arg.getBoxOf<fir::BoxValue>();
2844 addr = builder.create<fir::BoxAddrOp>(loc, box->getMemTy(),
2845 fir::getBase(*box));
2846 }
2847 return addr;
2848 }
2849
2850 static fir::ExtendedValue
2851 genCLocOrCFunLoc(fir::FirOpBuilder &builder, mlir::Location loc,
2852 mlir::Type resultType, llvm::ArrayRef<fir::ExtendedValue> args,
2853 bool isFunc = false) {
2854 assert(args.size() == 1);
2855 mlir::Value res = builder.create<fir::AllocaOp>(loc, resultType);
2856 mlir::Value resAddr =
2857 fir::factory::genCPtrOrCFunptrAddr(builder, loc, res, resultType);
2858 assert(fir::isa_box_type(fir::getBase(args[0]).getType()) &&
2859 "argument must have been lowered to box type");
2860 mlir::Value argAddr = getAddrFromBox(builder, loc, args[0], isFunc);
2861 mlir::Value argAddrVal = builder.createConvert(
2862 loc, fir::unwrapRefType(resAddr.getType()), argAddr);
2863 builder.create<fir::StoreOp>(loc, argAddrVal, resAddr);
2864 return res;
2865 }
2866
2867 /// C_ASSOCIATED
2868 static fir::ExtendedValue
2869 genCAssociated(fir::FirOpBuilder &builder, mlir::Location loc,
2870 mlir::Type resultType, llvm::ArrayRef<fir::ExtendedValue> args) {
2871 assert(args.size() == 2);
2872 mlir::Value cPtr1 = fir::getBase(args[0]);
2873 mlir::Value cPtrVal1 =
2874 fir::factory::genCPtrOrCFunptrValue(builder, loc, cPtr1);
2875 mlir::Value zero = builder.createIntegerConstant(loc, cPtrVal1.getType(), 0);
2876 mlir::Value res = builder.create<mlir::arith::CmpIOp>(
2877 loc, mlir::arith::CmpIPredicate::ne, cPtrVal1, zero);
2878
2879 if (isStaticallyPresent(args[1])) {
2880 mlir::Type i1Ty = builder.getI1Type();
2881 mlir::Value cPtr2 = fir::getBase(args[1]);
2882 mlir::Value isDynamicallyAbsent = builder.genIsNullAddr(loc, cPtr2);
2883 res =
2884 builder
2885 .genIfOp(loc, {i1Ty}, isDynamicallyAbsent, /*withElseRegion=*/true)
2886 .genThen([&]() { builder.create<fir::ResultOp>(loc, res); })
2887 .genElse([&]() {
2888 mlir::Value cPtrVal2 =
2889 fir::factory::genCPtrOrCFunptrValue(builder, loc, cPtr2);
2890 mlir::Value cmpVal = builder.create<mlir::arith::CmpIOp>(
2891 loc, mlir::arith::CmpIPredicate::eq, cPtrVal1, cPtrVal2);
2892 mlir::Value newRes =
2893 builder.create<mlir::arith::AndIOp>(loc, res, cmpVal);
2894 builder.create<fir::ResultOp>(loc, newRes);
2895 })
2896 .getResults()[0];
2897 }
2898 return builder.createConvert(loc, resultType, res);
2899 }
2900
2901 /// C_ASSOCIATED (C_FUNPTR [, C_FUNPTR])
2902 fir::ExtendedValue IntrinsicLibrary::genCAssociatedCFunPtr(
2903 mlir::Type resultType, llvm::ArrayRef<fir::ExtendedValue> args) {
2904 return genCAssociated(builder, loc, resultType, args);
2905 }
2906
2907 /// C_ASSOCIATED (C_PTR [, C_PTR])
2908 fir::ExtendedValue
2909 IntrinsicLibrary::genCAssociatedCPtr(mlir::Type resultType,
2910 llvm::ArrayRef<fir::ExtendedValue> args) {
2911 return genCAssociated(builder, loc, resultType, args);
2912 }
2913
2914 // C_F_POINTER
2915 void IntrinsicLibrary::genCFPointer(llvm::ArrayRef<fir::ExtendedValue> args) {
2916 assert(args.size() == 3);
2917 // Handle CPTR argument
2918 // Get the value of the C address or the result of a reference to C_LOC.
2919 mlir::Value cPtr = fir::getBase(args[0]);
2920 mlir::Value cPtrAddrVal =
2921 fir::factory::genCPtrOrCFunptrValue(builder, loc, cPtr);
2922
2923 // Handle FPTR argument
2924 const auto *fPtr = args[1].getBoxOf<fir::MutableBoxValue>();
2925 assert(fPtr && "FPTR must be a pointer");
2926
2927 auto getCPtrExtVal = [&](fir::MutableBoxValue box) -> fir::ExtendedValue {
2928 mlir::Value addr =
2929 builder.createConvert(loc, fPtr->getMemTy(), cPtrAddrVal);
2930 mlir::SmallVector<mlir::Value> extents;
2931 if (box.hasRank()) {
2932 assert(isStaticallyPresent(args[2]) &&
2933 "FPTR argument must be an array if SHAPE argument exists");
2934 mlir::Value shape = fir::getBase(args[2]);
2935 int arrayRank = box.rank();
2936 mlir::Type shapeElementType =
2937 fir::unwrapSequenceType(fir::unwrapPassByRefType(shape.getType()));
2938 mlir::Type idxType = builder.getIndexType();
2939 for (int i = 0; i < arrayRank; ++i) {
2940 mlir::Value index = builder.createIntegerConstant(loc, idxType, i);
2941 mlir::Value var = builder.create<fir::CoordinateOp>(
2942 loc, builder.getRefType(shapeElementType), shape, index);
2943 mlir::Value load = builder.create<fir::LoadOp>(loc, var);
2944 extents.push_back(builder.createConvert(loc, idxType, load));
2945 }
2946 }
2947 if (box.isCharacter()) {
2948 mlir::Value len = box.nonDeferredLenParams()[0];
2949 if (box.hasRank())
2950 return fir::CharArrayBoxValue{addr, len, extents};
2951 return fir::CharBoxValue{addr, len};
2952 }
2953 if (box.isDerivedWithLenParameters())
2954 TODO(loc, "get length parameters of derived type");
2955 if (box.hasRank())
2956 return fir::ArrayBoxValue{addr, extents};
2957 return addr;
2958 };
2959
2960 fir::factory::associateMutableBox(builder, loc, *fPtr, getCPtrExtVal(*fPtr),
2961 /*lbounds=*/mlir::ValueRange{});
2962 }
2963
2964 // C_F_PROCPOINTER
2965 void IntrinsicLibrary::genCFProcPointer(
2966 llvm::ArrayRef<fir::ExtendedValue> args) {
2967 assert(args.size() == 2);
2968 mlir::Value cptr =
2969 fir::factory::genCPtrOrCFunptrValue(builder, loc, fir::getBase(args[0]));
2970 mlir::Value fptr = fir::getBase(args[1]);
2971 auto boxProcType =
2972 mlir::cast<fir::BoxProcType>(fir::unwrapRefType(fptr.getType()));
2973 mlir::Value cptrCast =
2974 builder.createConvert(loc, boxProcType.getEleTy(), cptr);
2975 mlir::Value cptrBox =
2976 builder.create<fir::EmboxProcOp>(loc, boxProcType, cptrCast);
2977 builder.create<fir::StoreOp>(loc, cptrBox, fptr);
2978 }
2979
2980 // C_FUNLOC
2981 fir::ExtendedValue
2982 IntrinsicLibrary::genCFunLoc(mlir::Type resultType,
2983 llvm::ArrayRef<fir::ExtendedValue> args) {
2984 return genCLocOrCFunLoc(builder, loc, resultType, args, /*isFunc=*/true);
2985 }
2986
2987 // C_LOC
2988 fir::ExtendedValue
2989 IntrinsicLibrary::genCLoc(mlir::Type resultType,
2990 llvm::ArrayRef<fir::ExtendedValue> args) {
2991 return genCLocOrCFunLoc(builder, loc, resultType, args);
2992 }
2993
2994 // C_PTR_EQ and C_PTR_NE
2995 template <mlir::arith::CmpIPredicate pred>
2996 fir::ExtendedValue
2997 IntrinsicLibrary::genCPtrCompare(mlir::Type resultType,
2998 llvm::ArrayRef<fir::ExtendedValue> args) {
2999 assert(args.size() == 2);
3000 mlir::Value cPtr1 = fir::getBase(args[0]);
3001 mlir::Value cPtrVal1 =
3002 fir::factory::genCPtrOrCFunptrValue(builder, loc, cPtr1);
3003 mlir::Value cPtr2 = fir::getBase(args[1]);
3004 mlir::Value cPtrVal2 =
3005 fir::factory::genCPtrOrCFunptrValue(builder, loc, cPtr2);
3006 mlir::Value cmp =
3007 builder.create<mlir::arith::CmpIOp>(loc, pred, cPtrVal1, cPtrVal2);
3008 return builder.createConvert(loc, resultType, cmp);
3009 }
3010
3011 // CEILING
3012 mlir::Value IntrinsicLibrary::genCeiling(mlir::Type resultType,
3013 llvm::ArrayRef<mlir::Value> args) {
3014 // Optional KIND argument.
3015 assert(args.size() >= 1);
3016 mlir::Value arg = args[0];
3017 // Use ceil that is not an actual Fortran intrinsic but that is
3018 // an llvm intrinsic that does the same, but return a floating
3019 // point.
3020 mlir::Value ceil = genRuntimeCall("ceil", arg.getType(), {arg});
3021 return builder.createConvert(loc, resultType, ceil);
3022 }
3023
3024 // CHAR
3025 fir::ExtendedValue
3026 IntrinsicLibrary::genChar(mlir::Type type,
3027 llvm::ArrayRef<fir::ExtendedValue> args) {
3028 // Optional KIND argument.
3029 assert(args.size() >= 1);
3030 const mlir::Value *arg = args[0].getUnboxed();
3031 // expect argument to be a scalar integer
3032 if (!arg)
3033 mlir::emitError(loc, "CHAR intrinsic argument not unboxed");
3034 fir::factory::CharacterExprHelper helper{builder, loc};
3035 fir::CharacterType::KindTy kind = helper.getCharacterType(type).getFKind();
3036 mlir::Value cast = helper.createSingletonFromCode(*arg, kind);
3037 mlir::Value len =
3038 builder.createIntegerConstant(loc, builder.getCharacterLengthType(), 1);
3039 return fir::CharBoxValue{cast, len};
3040 }
3041
3042 // CMPLX
3043 mlir::Value IntrinsicLibrary::genCmplx(mlir::Type resultType,
3044 llvm::ArrayRef<mlir::Value> args) {
3045 assert(args.size() >= 1);
3046 fir::factory::Complex complexHelper(builder, loc);
3047 mlir::Type partType = complexHelper.getComplexPartType(resultType);
3048 mlir::Value real = builder.createConvert(loc, partType, args[0]);
3049 mlir::Value imag = isStaticallyAbsent(args, 1)
3050 ? builder.createRealZeroConstant(loc, partType)
3051 : builder.createConvert(loc, partType, args[1]);
3052 return fir::factory::Complex{builder, loc}.createComplex(resultType, real,
3053 imag);
3054 }
3055
3056 // COMMAND_ARGUMENT_COUNT
3057 fir::ExtendedValue IntrinsicLibrary::genCommandArgumentCount(
3058 mlir::Type resultType, llvm::ArrayRef<fir::ExtendedValue> args) {
3059 assert(args.size() == 0);
3060 assert(resultType == builder.getDefaultIntegerType() &&
3061 "result type is not default integer kind type");
3062 return builder.createConvert(
3063 loc, resultType, fir::runtime::genCommandArgumentCount(builder, loc));
3064 ;
3065 }
3066
3067 // CONJG
3068 mlir::Value IntrinsicLibrary::genConjg(mlir::Type resultType,
3069 llvm::ArrayRef<mlir::Value> args) {
3070 assert(args.size() == 1);
3071 if (resultType != args[0].getType())
3072 llvm_unreachable("argument type mismatch");
3073
3074 mlir::Value cplx = args[0];
3075 auto imag = fir::factory::Complex{builder, loc}.extractComplexPart(
3076 cplx, /*isImagPart=*/true);
3077 auto negImag = builder.create<mlir::arith::NegFOp>(loc, imag);
3078 return fir::factory::Complex{builder, loc}.insertComplexPart(
3079 cplx, negImag, /*isImagPart=*/true);
3080 }
3081
3082 // COSD
3083 mlir::Value IntrinsicLibrary::genCosd(mlir::Type resultType,
3084 llvm::ArrayRef<mlir::Value> args) {
3085 assert(args.size() == 1);
3086 mlir::MLIRContext *context = builder.getContext();
3087 mlir::FunctionType ftype =
3088 mlir::FunctionType::get(context, {resultType}, {args[0].getType()});
3089 llvm::APFloat pi = llvm::APFloat(llvm::numbers::pi);
3090 mlir::Value dfactor = builder.createRealConstant(
3091 loc, mlir::FloatType::getF64(context), pi / llvm::APFloat(180.0));
3092 mlir::Value factor = builder.createConvert(loc, args[0].getType(), dfactor);
3093 mlir::Value arg = builder.create<mlir::arith::MulFOp>(loc, args[0], factor);
3094 return getRuntimeCallGenerator("cos", ftype)(builder, loc, {arg});
3095 }
3096
3097 // COUNT
3098 fir::ExtendedValue
3099 IntrinsicLibrary::genCount(mlir::Type resultType,
3100 llvm::ArrayRef<fir::ExtendedValue> args) {
3101 assert(args.size() == 3);
3102
3103 // Handle mask argument
3104 fir::BoxValue mask = builder.createBox(loc, args[0]);
3105 unsigned maskRank = mask.rank();
3106
3107 assert(maskRank > 0);
3108
3109 // Handle optional dim argument
3110 bool absentDim = isStaticallyAbsent(args[1]);
3111 mlir::Value dim =
3112 absentDim ? builder.createIntegerConstant(loc, builder.getIndexType(), 0)
3113 : fir::getBase(args[1]);
3114
3115 if (absentDim || maskRank == 1) {
3116 // Result is scalar if no dim argument or mask is rank 1.
3117 // So, call specialized Count runtime routine.
3118 return builder.createConvert(
3119 loc, resultType,
3120 fir::runtime::genCount(builder, loc, fir::getBase(mask), dim));
3121 }
3122
3123 // Call general CountDim runtime routine.
3124
3125 // Handle optional kind argument
3126 bool absentKind = isStaticallyAbsent(args[2]);
3127 mlir::Value kind = absentKind ? builder.createIntegerConstant(
3128 loc, builder.getIndexType(),
3129 builder.getKindMap().defaultIntegerKind())
3130 : fir::getBase(args[2]);
3131
3132 // Create mutable fir.box to be passed to the runtime for the result.
3133 mlir::Type type = builder.getVarLenSeqTy(resultType, maskRank - 1);
3134 fir::MutableBoxValue resultMutableBox =
3135 fir::factory::createTempMutableBox(builder, loc, type);
3136
3137 mlir::Value resultIrBox =
3138 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
3139
3140 fir::runtime::genCountDim(builder, loc, resultIrBox, fir::getBase(mask), dim,
3141 kind);
3142 // Handle cleanup of allocatable result descriptor and return
3143 return readAndAddCleanUp(resultMutableBox, resultType, "COUNT");
3144 }
3145
3146 // CPU_TIME
3147 void IntrinsicLibrary::genCpuTime(llvm::ArrayRef<fir::ExtendedValue> args) {
3148 assert(args.size() == 1);
3149 const mlir::Value *arg = args[0].getUnboxed();
3150 assert(arg && "nonscalar cpu_time argument");
3151 mlir::Value res1 = fir::runtime::genCpuTime(builder, loc);
3152 mlir::Value res2 =
3153 builder.createConvert(loc, fir::dyn_cast_ptrEleTy(arg->getType()), res1);
3154 builder.create<fir::StoreOp>(loc, res2, *arg);
3155 }
3156
3157 // CSHIFT
3158 fir::ExtendedValue
3159 IntrinsicLibrary::genCshift(mlir::Type resultType,
3160 llvm::ArrayRef<fir::ExtendedValue> args) {
3161 assert(args.size() == 3);
3162
3163 // Handle required ARRAY argument
3164 fir::BoxValue arrayBox = builder.createBox(loc, args[0]);
3165 mlir::Value array = fir::getBase(arrayBox);
3166 unsigned arrayRank = arrayBox.rank();
3167
3168 // Create mutable fir.box to be passed to the runtime for the result.
3169 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, arrayRank);
3170 fir::MutableBoxValue resultMutableBox = fir::factory::createTempMutableBox(
3171 builder, loc, resultArrayType, {},
3172 fir::isPolymorphicType(array.getType()) ? array : mlir::Value{});
3173 mlir::Value resultIrBox =
3174 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
3175
3176 if (arrayRank == 1) {
3177 // Vector case
3178 // Handle required SHIFT argument as a scalar
3179 const mlir::Value *shiftAddr = args[1].getUnboxed();
3180 assert(shiftAddr && "nonscalar CSHIFT argument");
3181 auto shift = builder.create<fir::LoadOp>(loc, *shiftAddr);
3182
3183 fir::runtime::genCshiftVector(builder, loc, resultIrBox, array, shift);
3184 } else {
3185 // Non-vector case
3186 // Handle required SHIFT argument as an array
3187 mlir::Value shift = builder.createBox(loc, args[1]);
3188
3189 // Handle optional DIM argument
3190 mlir::Value dim =
3191 isStaticallyAbsent(args[2])
3192 ? builder.createIntegerConstant(loc, builder.getIndexType(), 1)
3193 : fir::getBase(args[2]);
3194 fir::runtime::genCshift(builder, loc, resultIrBox, array, shift, dim);
3195 }
3196 return readAndAddCleanUp(resultMutableBox, resultType, "CSHIFT");
3197 }
3198
3199 // DATE_AND_TIME
3200 void IntrinsicLibrary::genDateAndTime(llvm::ArrayRef<fir::ExtendedValue> args) {
3201 assert(args.size() == 4 && "date_and_time has 4 args");
3202 llvm::SmallVector<std::optional<fir::CharBoxValue>> charArgs(3);
3203 for (unsigned i = 0; i < 3; ++i)
3204 if (const fir::CharBoxValue *charBox = args[i].getCharBox())
3205 charArgs[i] = *charBox;
3206
3207 mlir::Value values = fir::getBase(args[3]);
3208 if (!values)
3209 values = builder.create<fir::AbsentOp>(
3210 loc, fir::BoxType::get(builder.getNoneType()));
3211
3212 fir::runtime::genDateAndTime(builder, loc, charArgs[0], charArgs[1],
3213 charArgs[2], values);
3214 }
3215
3216 // DIM
3217 mlir::Value IntrinsicLibrary::genDim(mlir::Type resultType,
3218 llvm::ArrayRef<mlir::Value> args) {
3219 assert(args.size() == 2);
3220 if (mlir::isa<mlir::IntegerType>(resultType)) {
3221 mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
3222 auto diff = builder.create<mlir::arith::SubIOp>(loc, args[0], args[1]);
3223 auto cmp = builder.create<mlir::arith::CmpIOp>(
3224 loc, mlir::arith::CmpIPredicate::sgt, diff, zero);
3225 return builder.create<mlir::arith::SelectOp>(loc, cmp, diff, zero);
3226 }
3227 assert(fir::isa_real(resultType) && "Only expects real and integer in DIM");
3228 mlir::Value zero = builder.createRealZeroConstant(loc, resultType);
3229 auto diff = builder.create<mlir::arith::SubFOp>(loc, args[0], args[1]);
3230 auto cmp = builder.create<mlir::arith::CmpFOp>(
3231 loc, mlir::arith::CmpFPredicate::OGT, diff, zero);
3232 return builder.create<mlir::arith::SelectOp>(loc, cmp, diff, zero);
3233 }
3234
3235 // DOT_PRODUCT
3236 fir::ExtendedValue
3237 IntrinsicLibrary::genDotProduct(mlir::Type resultType,
3238 llvm::ArrayRef<fir::ExtendedValue> args) {
3239 assert(args.size() == 2);
3240
3241 // Handle required vector arguments
3242 mlir::Value vectorA = fir::getBase(args[0]);
3243 mlir::Value vectorB = fir::getBase(args[1]);
3244 // Result type is used for picking appropriate runtime function.
3245 mlir::Type eleTy = resultType;
3246
3247 if (fir::isa_complex(eleTy)) {
3248 mlir::Value result = builder.createTemporary(loc, eleTy);
3249 fir::runtime::genDotProduct(builder, loc, vectorA, vectorB, result);
3250 return builder.create<fir::LoadOp>(loc, result);
3251 }
3252
3253 // This operation is only used to pass the result type
3254 // information to the DotProduct generator.
3255 auto resultBox = builder.create<fir::AbsentOp>(loc, fir::BoxType::get(eleTy));
3256 return fir::runtime::genDotProduct(builder, loc, vectorA, vectorB, resultBox);
3257 }
3258
3259 // DPROD
3260 mlir::Value IntrinsicLibrary::genDprod(mlir::Type resultType,
3261 llvm::ArrayRef<mlir::Value> args) {
3262 assert(args.size() == 2);
3263 assert(fir::isa_real(resultType) &&
3264 "Result must be double precision in DPROD");
3265 mlir::Value a = builder.createConvert(loc, resultType, args[0]);
3266 mlir::Value b = builder.createConvert(loc, resultType, args[1]);
3267 return builder.create<mlir::arith::MulFOp>(loc, a, b);
3268 }
3269
3270 // DSHIFTL
3271 mlir::Value IntrinsicLibrary::genDshiftl(mlir::Type resultType,
3272 llvm::ArrayRef<mlir::Value> args) {
3273 assert(args.size() == 3);
3274
3275 mlir::Value i = args[0];
3276 mlir::Value j = args[1];
3277 mlir::Value shift = builder.createConvert(loc, resultType, args[2]);
3278 mlir::Value bitSize = builder.createIntegerConstant(
3279 loc, resultType, resultType.getIntOrFloatBitWidth());
3280
3281 // Per the standard, the value of DSHIFTL(I, J, SHIFT) is equal to
3282 // IOR (SHIFTL(I, SHIFT), SHIFTR(J, BIT_SIZE(J) - SHIFT))
3283 mlir::Value diff = builder.create<mlir::arith::SubIOp>(loc, bitSize, shift);
3284
3285 mlir::Value lArgs[2]{i, shift};
3286 mlir::Value lft = genShift<mlir::arith::ShLIOp>(resultType, lArgs);
3287
3288 mlir::Value rArgs[2]{j, diff};
3289 mlir::Value rgt = genShift<mlir::arith::ShRUIOp>(resultType, rArgs);
3290
3291 return builder.create<mlir::arith::OrIOp>(loc, lft, rgt);
3292 }
3293
3294 // DSHIFTR
3295 mlir::Value IntrinsicLibrary::genDshiftr(mlir::Type resultType,
3296 llvm::ArrayRef<mlir::Value> args) {
3297 assert(args.size() == 3);
3298
3299 mlir::Value i = args[0];
3300 mlir::Value j = args[1];
3301 mlir::Value shift = builder.createConvert(loc, resultType, args[2]);
3302 mlir::Value bitSize = builder.createIntegerConstant(
3303 loc, resultType, resultType.getIntOrFloatBitWidth());
3304
3305 // Per the standard, the value of DSHIFTR(I, J, SHIFT) is equal to
3306 // IOR (SHIFTL(I, BIT_SIZE(I) - SHIFT), SHIFTR(J, SHIFT))
3307 mlir::Value diff = builder.create<mlir::arith::SubIOp>(loc, bitSize, shift);
3308
3309 mlir::Value lArgs[2]{i, diff};
3310 mlir::Value lft = genShift<mlir::arith::ShLIOp>(resultType, lArgs);
3311
3312 mlir::Value rArgs[2]{j, shift};
3313 mlir::Value rgt = genShift<mlir::arith::ShRUIOp>(resultType, rArgs);
3314
3315 return builder.create<mlir::arith::OrIOp>(loc, lft, rgt);
3316 }
3317
3318 // EOSHIFT
3319 fir::ExtendedValue
3320 IntrinsicLibrary::genEoshift(mlir::Type resultType,
3321 llvm::ArrayRef<fir::ExtendedValue> args) {
3322 assert(args.size() == 4);
3323
3324 // Handle required ARRAY argument
3325 fir::BoxValue arrayBox = builder.createBox(loc, args[0]);
3326 mlir::Value array = fir::getBase(arrayBox);
3327 unsigned arrayRank = arrayBox.rank();
3328
3329 // Create mutable fir.box to be passed to the runtime for the result.
3330 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, arrayRank);
3331 fir::MutableBoxValue resultMutableBox = fir::factory::createTempMutableBox(
3332 builder, loc, resultArrayType, {},
3333 fir::isPolymorphicType(array.getType()) ? array : mlir::Value{});
3334 mlir::Value resultIrBox =
3335 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
3336
3337 // Handle optional BOUNDARY argument
3338 mlir::Value boundary =
3339 isStaticallyAbsent(args[2])
3340 ? builder.create<fir::AbsentOp>(
3341 loc, fir::BoxType::get(builder.getNoneType()))
3342 : builder.createBox(loc, args[2]);
3343
3344 if (arrayRank == 1) {
3345 // Vector case
3346 // Handle required SHIFT argument as a scalar
3347 const mlir::Value *shiftAddr = args[1].getUnboxed();
3348 assert(shiftAddr && "nonscalar EOSHIFT SHIFT argument");
3349 auto shift = builder.create<fir::LoadOp>(loc, *shiftAddr);
3350 fir::runtime::genEoshiftVector(builder, loc, resultIrBox, array, shift,
3351 boundary);
3352 } else {
3353 // Non-vector case
3354 // Handle required SHIFT argument as an array
3355 mlir::Value shift = builder.createBox(loc, args[1]);
3356
3357 // Handle optional DIM argument
3358 mlir::Value dim =
3359 isStaticallyAbsent(args[3])
3360 ? builder.createIntegerConstant(loc, builder.getIndexType(), 1)
3361 : fir::getBase(args[3]);
3362 fir::runtime::genEoshift(builder, loc, resultIrBox, array, shift, boundary,
3363 dim);
3364 }
3365 return readAndAddCleanUp(resultMutableBox, resultType, "EOSHIFT");
3366 }
3367
3368 // EXECUTE_COMMAND_LINE
3369 void IntrinsicLibrary::genExecuteCommandLine(
3370 llvm::ArrayRef<fir::ExtendedValue> args) {
3371 assert(args.size() == 5);
3372
3373 mlir::Value command = fir::getBase(args[0]);
3374 // Optional arguments: wait, exitstat, cmdstat, cmdmsg.
3375 const fir::ExtendedValue &wait = args[1];
3376 const fir::ExtendedValue &exitstat = args[2];
3377 const fir::ExtendedValue &cmdstat = args[3];
3378 const fir::ExtendedValue &cmdmsg = args[4];
3379
3380 if (!command)
3381 fir::emitFatalError(loc, "expected COMMAND parameter");
3382
3383 mlir::Type boxNoneTy = fir::BoxType::get(builder.getNoneType());
3384
3385 mlir::Value waitBool;
3386 if (isStaticallyAbsent(wait)) {
3387 waitBool = builder.createBool(loc, true);
3388 } else {
3389 mlir::Type i1Ty = builder.getI1Type();
3390 mlir::Value waitAddr = fir::getBase(wait);
3391 mlir::Value waitIsPresentAtRuntime =
3392 builder.genIsNotNullAddr(loc, waitAddr);
3393 waitBool = builder
3394 .genIfOp(loc, {i1Ty}, waitIsPresentAtRuntime,
3395 /*withElseRegion=*/true)
3396 .genThen([&]() {
3397 auto waitLoad = builder.create<fir::LoadOp>(loc, waitAddr);
3398 mlir::Value cast =
3399 builder.createConvert(loc, i1Ty, waitLoad);
3400 builder.create<fir::ResultOp>(loc, cast);
3401 })
3402 .genElse([&]() {
3403 mlir::Value trueVal = builder.createBool(loc, true);
3404 builder.create<fir::ResultOp>(loc, trueVal);
3405 })
3406 .getResults()[0];
3407 }
3408
3409 mlir::Value exitstatBox =
3410 isStaticallyPresent(exitstat)
3411 ? fir::getBase(exitstat)
3412 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3413 mlir::Value cmdstatBox =
3414 isStaticallyPresent(cmdstat)
3415 ? fir::getBase(cmdstat)
3416 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3417 mlir::Value cmdmsgBox =
3418 isStaticallyPresent(cmdmsg)
3419 ? fir::getBase(cmdmsg)
3420 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3421 fir::runtime::genExecuteCommandLine(builder, loc, command, waitBool,
3422 exitstatBox, cmdstatBox, cmdmsgBox);
3423 }
3424
3425 // ETIME
3426 fir::ExtendedValue
3427 IntrinsicLibrary::genEtime(std::optional<mlir::Type> resultType,
3428 llvm::ArrayRef<fir::ExtendedValue> args) {
3429 assert((args.size() == 2 && !resultType.has_value()) ||
3430 (args.size() == 1 && resultType.has_value()));
3431
3432 mlir::Value values = fir::getBase(args[0]);
3433 if (resultType.has_value()) {
3434 // function form
3435 if (!values)
3436 fir::emitFatalError(loc, "expected VALUES parameter");
3437
3438 auto timeAddr = builder.createTemporary(loc, *resultType);
3439 auto timeBox = builder.createBox(loc, timeAddr);
3440 fir::runtime::genEtime(builder, loc, values, timeBox);
3441 return builder.create<fir::LoadOp>(loc, timeAddr);
3442 } else {
3443 // subroutine form
3444 mlir::Value time = fir::getBase(args[1]);
3445 if (!values)
3446 fir::emitFatalError(loc, "expected VALUES parameter");
3447 if (!time)
3448 fir::emitFatalError(loc, "expected TIME parameter");
3449
3450 fir::runtime::genEtime(builder, loc, values, time);
3451 return {};
3452 }
3453 return {};
3454 }
3455
3456 // EXIT
3457 void IntrinsicLibrary::genExit(llvm::ArrayRef<fir::ExtendedValue> args) {
3458 assert(args.size() == 1);
3459
3460 mlir::Value status =
3461 isStaticallyAbsent(args[0])
3462 ? builder.createIntegerConstant(loc, builder.getDefaultIntegerType(),
3463 EXIT_SUCCESS)
3464 : fir::getBase(args[0]);
3465
3466 assert(status.getType() == builder.getDefaultIntegerType() &&
3467 "STATUS parameter must be an INTEGER of default kind");
3468
3469 fir::runtime::genExit(builder, loc, status);
3470 }
3471
3472 // EXPONENT
3473 mlir::Value IntrinsicLibrary::genExponent(mlir::Type resultType,
3474 llvm::ArrayRef<mlir::Value> args) {
3475 assert(args.size() == 1);
3476
3477 return builder.createConvert(
3478 loc, resultType,
3479 fir::runtime::genExponent(builder, loc, resultType,
3480 fir::getBase(args[0])));
3481 }
3482
3483 // EXTENDS_TYPE_OF
3484 fir::ExtendedValue
3485 IntrinsicLibrary::genExtendsTypeOf(mlir::Type resultType,
3486 llvm::ArrayRef<fir::ExtendedValue> args) {
3487 assert(args.size() == 2);
3488
3489 return builder.createConvert(
3490 loc, resultType,
3491 fir::runtime::genExtendsTypeOf(builder, loc, fir::getBase(args[0]),
3492 fir::getBase(args[1])));
3493 }
3494
3495 // FINDLOC
3496 fir::ExtendedValue
3497 IntrinsicLibrary::genFindloc(mlir::Type resultType,
3498 llvm::ArrayRef<fir::ExtendedValue> args) {
3499 assert(args.size() == 6);
3500
3501 // Handle required array argument
3502 mlir::Value array = builder.createBox(loc, args[0]);
3503 unsigned rank = fir::BoxValue(array).rank();
3504 assert(rank >= 1);
3505
3506 // Handle required value argument
3507 mlir::Value val = builder.createBox(loc, args[1]);
3508
3509 // Check if dim argument is present
3510 bool absentDim = isStaticallyAbsent(args[2]);
3511
3512 // Handle optional mask argument
3513 auto mask = isStaticallyAbsent(args[3])
3514 ? builder.create<fir::AbsentOp>(
3515 loc, fir::BoxType::get(builder.getI1Type()))
3516 : builder.createBox(loc, args[3]);
3517
3518 // Handle optional kind argument
3519 auto kind = isStaticallyAbsent(args[4])
3520 ? builder.createIntegerConstant(
3521 loc, builder.getIndexType(),
3522 builder.getKindMap().defaultIntegerKind())
3523 : fir::getBase(args[4]);
3524
3525 // Handle optional back argument
3526 auto back = isStaticallyAbsent(args[5]) ? builder.createBool(loc, false)
3527 : fir::getBase(args[5]);
3528
3529 if (!absentDim && rank == 1) {
3530 // If dim argument is present and the array is rank 1, then the result is
3531 // a scalar (since the the result is rank-1 or 0).
3532 // Therefore, we use a scalar result descriptor with FindlocDim().
3533 // Create mutable fir.box to be passed to the runtime for the result.
3534 fir::MutableBoxValue resultMutableBox =
3535 fir::factory::createTempMutableBox(builder, loc, resultType);
3536 mlir::Value resultIrBox =
3537 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
3538 mlir::Value dim = fir::getBase(args[2]);
3539
3540 fir::runtime::genFindlocDim(builder, loc, resultIrBox, array, val, dim,
3541 mask, kind, back);
3542 // Handle cleanup of allocatable result descriptor and return
3543 return readAndAddCleanUp(resultMutableBox, resultType, "FINDLOC");
3544 }
3545
3546 // The result will be an array. Create mutable fir.box to be passed to the
3547 // runtime for the result.
3548 mlir::Type resultArrayType =
3549 builder.getVarLenSeqTy(resultType, absentDim ? 1 : rank - 1);
3550 fir::MutableBoxValue resultMutableBox =
3551 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
3552 mlir::Value resultIrBox =
3553 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
3554
3555 if (absentDim) {
3556 fir::runtime::genFindloc(builder, loc, resultIrBox, array, val, mask, kind,
3557 back);
3558 } else {
3559 mlir::Value dim = fir::getBase(args[2]);
3560 fir::runtime::genFindlocDim(builder, loc, resultIrBox, array, val, dim,
3561 mask, kind, back);
3562 }
3563 return readAndAddCleanUp(resultMutableBox, resultType, "FINDLOC");
3564 }
3565
3566 // FLOOR
3567 mlir::Value IntrinsicLibrary::genFloor(mlir::Type resultType,
3568 llvm::ArrayRef<mlir::Value> args) {
3569 // Optional KIND argument.
3570 assert(args.size() >= 1);
3571 mlir::Value arg = args[0];
3572 // Use LLVM floor that returns real.
3573 mlir::Value floor = genRuntimeCall("floor", arg.getType(), {arg});
3574 return builder.createConvert(loc, resultType, floor);
3575 }
3576
3577 // FRACTION
3578 mlir::Value IntrinsicLibrary::genFraction(mlir::Type resultType,
3579 llvm::ArrayRef<mlir::Value> args) {
3580 assert(args.size() == 1);
3581
3582 return builder.createConvert(
3583 loc, resultType,
3584 fir::runtime::genFraction(builder, loc, fir::getBase(args[0])));
3585 }
3586
3587 // GETCWD
3588 fir::ExtendedValue
3589 IntrinsicLibrary::genGetCwd(std::optional<mlir::Type> resultType,
3590 llvm::ArrayRef<fir::ExtendedValue> args) {
3591 assert((args.size() == 1 && resultType.has_value()) ||
3592 (args.size() >= 1 && !resultType.has_value()));
3593
3594 mlir::Value cwd = fir::getBase(args[0]);
3595 mlir::Value statusValue = fir::runtime::genGetCwd(builder, loc, cwd);
3596
3597 if (resultType.has_value()) {
3598 // Function form, return status.
3599 return statusValue;
3600 } else {
3601 // Subroutine form, store status and return none.
3602 const fir::ExtendedValue &status = args[1];
3603 if (!isStaticallyAbsent(status)) {
3604 mlir::Value statusAddr = fir::getBase(status);
3605 mlir::Value statusIsPresentAtRuntime =
3606 builder.genIsNotNullAddr(loc, statusAddr);
3607 builder.genIfThen(loc, statusIsPresentAtRuntime)
3608 .genThen([&]() {
3609 builder.createStoreWithConvert(loc, statusValue, statusAddr);
3610 })
3611 .end();
3612 }
3613 }
3614
3615 return {};
3616 }
3617
3618 // GET_COMMAND
3619 void IntrinsicLibrary::genGetCommand(llvm::ArrayRef<fir::ExtendedValue> args) {
3620 assert(args.size() == 4);
3621 const fir::ExtendedValue &command = args[0];
3622 const fir::ExtendedValue &length = args[1];
3623 const fir::ExtendedValue &status = args[2];
3624 const fir::ExtendedValue &errmsg = args[3];
3625
3626 // If none of the optional parameters are present, do nothing.
3627 if (!isStaticallyPresent(command) && !isStaticallyPresent(length) &&
3628 !isStaticallyPresent(status) && !isStaticallyPresent(errmsg))
3629 return;
3630
3631 mlir::Type boxNoneTy = fir::BoxType::get(builder.getNoneType());
3632 mlir::Value commandBox =
3633 isStaticallyPresent(command)
3634 ? fir::getBase(command)
3635 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3636 mlir::Value lenBox =
3637 isStaticallyPresent(length)
3638 ? fir::getBase(length)
3639 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3640 mlir::Value errBox =
3641 isStaticallyPresent(errmsg)
3642 ? fir::getBase(errmsg)
3643 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3644 mlir::Value stat =
3645 fir::runtime::genGetCommand(builder, loc, commandBox, lenBox, errBox);
3646 if (isStaticallyPresent(status)) {
3647 mlir::Value statAddr = fir::getBase(status);
3648 mlir::Value statIsPresentAtRuntime =
3649 builder.genIsNotNullAddr(loc, statAddr);
3650 builder.genIfThen(loc, statIsPresentAtRuntime)
3651 .genThen([&]() { builder.createStoreWithConvert(loc, stat, statAddr); })
3652 .end();
3653 }
3654 }
3655
3656 // GETPID
3657 mlir::Value IntrinsicLibrary::genGetPID(mlir::Type resultType,
3658 llvm::ArrayRef<mlir::Value> args) {
3659 assert(args.size() == 0 && "getpid takes no input");
3660 return builder.createConvert(loc, resultType,
3661 fir::runtime::genGetPID(builder, loc));
3662 }
3663
3664 // GET_COMMAND_ARGUMENT
3665 void IntrinsicLibrary::genGetCommandArgument(
3666 llvm::ArrayRef<fir::ExtendedValue> args) {
3667 assert(args.size() == 5);
3668 mlir::Value number = fir::getBase(args[0]);
3669 const fir::ExtendedValue &value = args[1];
3670 const fir::ExtendedValue &length = args[2];
3671 const fir::ExtendedValue &status = args[3];
3672 const fir::ExtendedValue &errmsg = args[4];
3673
3674 if (!number)
3675 fir::emitFatalError(loc, "expected NUMBER parameter");
3676
3677 // If none of the optional parameters are present, do nothing.
3678 if (!isStaticallyPresent(value) && !isStaticallyPresent(length) &&
3679 !isStaticallyPresent(status) && !isStaticallyPresent(errmsg))
3680 return;
3681
3682 mlir::Type boxNoneTy = fir::BoxType::get(builder.getNoneType());
3683 mlir::Value valBox =
3684 isStaticallyPresent(value)
3685 ? fir::getBase(value)
3686 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3687 mlir::Value lenBox =
3688 isStaticallyPresent(length)
3689 ? fir::getBase(length)
3690 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3691 mlir::Value errBox =
3692 isStaticallyPresent(errmsg)
3693 ? fir::getBase(errmsg)
3694 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3695 mlir::Value stat = fir::runtime::genGetCommandArgument(
3696 builder, loc, number, valBox, lenBox, errBox);
3697 if (isStaticallyPresent(status)) {
3698 mlir::Value statAddr = fir::getBase(status);
3699 mlir::Value statIsPresentAtRuntime =
3700 builder.genIsNotNullAddr(loc, statAddr);
3701 builder.genIfThen(loc, statIsPresentAtRuntime)
3702 .genThen([&]() { builder.createStoreWithConvert(loc, stat, statAddr); })
3703 .end();
3704 }
3705 }
3706
3707 // GET_ENVIRONMENT_VARIABLE
3708 void IntrinsicLibrary::genGetEnvironmentVariable(
3709 llvm::ArrayRef<fir::ExtendedValue> args) {
3710 assert(args.size() == 6);
3711 mlir::Value name = fir::getBase(args[0]);
3712 const fir::ExtendedValue &value = args[1];
3713 const fir::ExtendedValue &length = args[2];
3714 const fir::ExtendedValue &status = args[3];
3715 const fir::ExtendedValue &trimName = args[4];
3716 const fir::ExtendedValue &errmsg = args[5];
3717
3718 if (!name)
3719 fir::emitFatalError(loc, "expected NAME parameter");
3720
3721 // If none of the optional parameters are present, do nothing.
3722 if (!isStaticallyPresent(value) && !isStaticallyPresent(length) &&
3723 !isStaticallyPresent(status) && !isStaticallyPresent(errmsg))
3724 return;
3725
3726 // Handle optional TRIM_NAME argument
3727 mlir::Value trim;
3728 if (isStaticallyAbsent(trimName)) {
3729 trim = builder.createBool(loc, true);
3730 } else {
3731 mlir::Type i1Ty = builder.getI1Type();
3732 mlir::Value trimNameAddr = fir::getBase(trimName);
3733 mlir::Value trimNameIsPresentAtRuntime =
3734 builder.genIsNotNullAddr(loc, trimNameAddr);
3735 trim = builder
3736 .genIfOp(loc, {i1Ty}, trimNameIsPresentAtRuntime,
3737 /*withElseRegion=*/true)
3738 .genThen([&]() {
3739 auto trimLoad = builder.create<fir::LoadOp>(loc, trimNameAddr);
3740 mlir::Value cast = builder.createConvert(loc, i1Ty, trimLoad);
3741 builder.create<fir::ResultOp>(loc, cast);
3742 })
3743 .genElse([&]() {
3744 mlir::Value trueVal = builder.createBool(loc, true);
3745 builder.create<fir::ResultOp>(loc, trueVal);
3746 })
3747 .getResults()[0];
3748 }
3749
3750 mlir::Type boxNoneTy = fir::BoxType::get(builder.getNoneType());
3751 mlir::Value valBox =
3752 isStaticallyPresent(value)
3753 ? fir::getBase(value)
3754 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3755 mlir::Value lenBox =
3756 isStaticallyPresent(length)
3757 ? fir::getBase(length)
3758 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3759 mlir::Value errBox =
3760 isStaticallyPresent(errmsg)
3761 ? fir::getBase(errmsg)
3762 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
3763 mlir::Value stat = fir::runtime::genGetEnvVariable(builder, loc, name, valBox,
3764 lenBox, trim, errBox);
3765 if (isStaticallyPresent(status)) {
3766 mlir::Value statAddr = fir::getBase(status);
3767 mlir::Value statIsPresentAtRuntime =
3768 builder.genIsNotNullAddr(loc, statAddr);
3769 builder.genIfThen(loc, statIsPresentAtRuntime)
3770 .genThen([&]() { builder.createStoreWithConvert(loc, stat, statAddr); })
3771 .end();
3772 }
3773 }
3774
3775 /// Process calls to Maxval, Minval, Product, Sum intrinsic functions that
3776 /// take a DIM argument.
3777 template <typename FD>
3778 static fir::MutableBoxValue
3779 genFuncDim(FD funcDim, mlir::Type resultType, fir::FirOpBuilder &builder,
3780 mlir::Location loc, mlir::Value array, fir::ExtendedValue dimArg,
3781 mlir::Value mask, int rank) {
3782
3783 // Create mutable fir.box to be passed to the runtime for the result.
3784 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, rank - 1);
3785 fir::MutableBoxValue resultMutableBox =
3786 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
3787 mlir::Value resultIrBox =
3788 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
3789
3790 mlir::Value dim =
3791 isStaticallyAbsent(dimArg)
3792 ? builder.createIntegerConstant(loc, builder.getIndexType(), 0)
3793 : fir::getBase(dimArg);
3794 funcDim(builder, loc, resultIrBox, array, dim, mask);
3795
3796 return resultMutableBox;
3797 }
3798
3799 /// Process calls to Product, Sum, IAll, IAny, IParity intrinsic functions
3800 template <typename FN, typename FD>
3801 fir::ExtendedValue
3802 IntrinsicLibrary::genReduction(FN func, FD funcDim, llvm::StringRef errMsg,
3803 mlir::Type resultType,
3804 llvm::ArrayRef<fir::ExtendedValue> args) {
3805
3806 assert(args.size() == 3);
3807
3808 // Handle required array argument
3809 fir::BoxValue arryTmp = builder.createBox(loc, args[0]);
3810 mlir::Value array = fir::getBase(arryTmp);
3811 int rank = arryTmp.rank();
3812 assert(rank >= 1);
3813
3814 // Handle optional mask argument
3815 auto mask = isStaticallyAbsent(args[2])
3816 ? builder.create<fir::AbsentOp>(
3817 loc, fir::BoxType::get(builder.getI1Type()))
3818 : builder.createBox(loc, args[2]);
3819
3820 bool absentDim = isStaticallyAbsent(args[1]);
3821
3822 // We call the type specific versions because the result is scalar
3823 // in the case below.
3824 if (absentDim || rank == 1) {
3825 mlir::Type ty = array.getType();
3826 mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty);
3827 auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
3828 if (fir::isa_complex(eleTy)) {
3829 mlir::Value result = builder.createTemporary(loc, eleTy);
3830 func(builder, loc, array, mask, result);
3831 return builder.create<fir::LoadOp>(loc, result);
3832 }
3833 auto resultBox = builder.create<fir::AbsentOp>(
3834 loc, fir::BoxType::get(builder.getI1Type()));
3835 return func(builder, loc, array, mask, resultBox);
3836 }
3837 // Handle Product/Sum cases that have an array result.
3838 auto resultMutableBox =
3839 genFuncDim(funcDim, resultType, builder, loc, array, args[1], mask, rank);
3840 return readAndAddCleanUp(resultMutableBox, resultType, errMsg);
3841 }
3842
3843 // IALL
3844 fir::ExtendedValue
3845 IntrinsicLibrary::genIall(mlir::Type resultType,
3846 llvm::ArrayRef<fir::ExtendedValue> args) {
3847 return genReduction(fir::runtime::genIAll, fir::runtime::genIAllDim, "IALL",
3848 resultType, args);
3849 }
3850
3851 // IAND
3852 mlir::Value IntrinsicLibrary::genIand(mlir::Type resultType,
3853 llvm::ArrayRef<mlir::Value> args) {
3854 assert(args.size() == 2);
3855 auto arg0 = builder.createConvert(loc, resultType, args[0]);
3856 auto arg1 = builder.createConvert(loc, resultType, args[1]);
3857 return builder.create<mlir::arith::AndIOp>(loc, arg0, arg1);
3858 }
3859
3860 // IANY
3861 fir::ExtendedValue
3862 IntrinsicLibrary::genIany(mlir::Type resultType,
3863 llvm::ArrayRef<fir::ExtendedValue> args) {
3864 return genReduction(fir::runtime::genIAny, fir::runtime::genIAnyDim, "IANY",
3865 resultType, args);
3866 }
3867
3868 // IBCLR
3869 mlir::Value IntrinsicLibrary::genIbclr(mlir::Type resultType,
3870 llvm::ArrayRef<mlir::Value> args) {
3871 // A conformant IBCLR(I,POS) call satisfies:
3872 // POS >= 0
3873 // POS < BIT_SIZE(I)
3874 // Return: I & (!(1 << POS))
3875 assert(args.size() == 2);
3876 mlir::Value pos = builder.createConvert(loc, resultType, args[1]);
3877 mlir::Value one = builder.createIntegerConstant(loc, resultType, 1);
3878 mlir::Value ones = builder.createAllOnesInteger(loc, resultType);
3879 auto mask = builder.create<mlir::arith::ShLIOp>(loc, one, pos);
3880 auto res = builder.create<mlir::arith::XOrIOp>(loc, ones, mask);
3881 return builder.create<mlir::arith::AndIOp>(loc, args[0], res);
3882 }
3883
3884 // IBITS
3885 mlir::Value IntrinsicLibrary::genIbits(mlir::Type resultType,
3886 llvm::ArrayRef<mlir::Value> args) {
3887 // A conformant IBITS(I,POS,LEN) call satisfies:
3888 // POS >= 0
3889 // LEN >= 0
3890 // POS + LEN <= BIT_SIZE(I)
3891 // Return: LEN == 0 ? 0 : (I >> POS) & (-1 >> (BIT_SIZE(I) - LEN))
3892 // For a conformant call, implementing (I >> POS) with a signed or an
3893 // unsigned shift produces the same result. For a nonconformant call,
3894 // the two choices may produce different results.
3895 assert(args.size() == 3);
3896 mlir::Value pos = builder.createConvert(loc, resultType, args[1]);
3897 mlir::Value len = builder.createConvert(loc, resultType, args[2]);
3898 mlir::Value bitSize = builder.createIntegerConstant(
3899 loc, resultType, mlir::cast<mlir::IntegerType>(resultType).getWidth());
3900 auto shiftCount = builder.create<mlir::arith::SubIOp>(loc, bitSize, len);
3901 mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
3902 mlir::Value ones = builder.createAllOnesInteger(loc, resultType);
3903 auto mask = builder.create<mlir::arith::ShRUIOp>(loc, ones, shiftCount);
3904 auto res1 = builder.create<mlir::arith::ShRSIOp>(loc, args[0], pos);
3905 auto res2 = builder.create<mlir::arith::AndIOp>(loc, res1, mask);
3906 auto lenIsZero = builder.create<mlir::arith::CmpIOp>(
3907 loc, mlir::arith::CmpIPredicate::eq, len, zero);
3908 return builder.create<mlir::arith::SelectOp>(loc, lenIsZero, zero, res2);
3909 }
3910
3911 // IBSET
3912 mlir::Value IntrinsicLibrary::genIbset(mlir::Type resultType,
3913 llvm::ArrayRef<mlir::Value> args) {
3914 // A conformant IBSET(I,POS) call satisfies:
3915 // POS >= 0
3916 // POS < BIT_SIZE(I)
3917 // Return: I | (1 << POS)
3918 assert(args.size() == 2);
3919 mlir::Value pos = builder.createConvert(loc, resultType, args[1]);
3920 mlir::Value one = builder.createIntegerConstant(loc, resultType, 1);
3921 auto mask = builder.create<mlir::arith::ShLIOp>(loc, one, pos);
3922 return builder.create<mlir::arith::OrIOp>(loc, args[0], mask);
3923 }
3924
3925 // ICHAR
3926 fir::ExtendedValue
3927 IntrinsicLibrary::genIchar(mlir::Type resultType,
3928 llvm::ArrayRef<fir::ExtendedValue> args) {
3929 // There can be an optional kind in second argument.
3930 assert(args.size() == 2);
3931 const fir::CharBoxValue *charBox = args[0].getCharBox();
3932 if (!charBox)
3933 llvm::report_fatal_error("expected character scalar");
3934
3935 fir::factory::CharacterExprHelper helper{builder, loc};
3936 mlir::Value buffer = charBox->getBuffer();
3937 mlir::Type bufferTy = buffer.getType();
3938 mlir::Value charVal;
3939 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(bufferTy)) {
3940 assert(charTy.singleton());
3941 charVal = buffer;
3942 } else {
3943 // Character is in memory, cast to fir.ref<char> and load.
3944 mlir::Type ty = fir::dyn_cast_ptrEleTy(bufferTy);
3945 if (!ty)
3946 llvm::report_fatal_error("expected memory type");
3947 // The length of in the character type may be unknown. Casting
3948 // to a singleton ref is required before loading.
3949 fir::CharacterType eleType = helper.getCharacterType(ty);
3950 fir::CharacterType charType =
3951 fir::CharacterType::get(builder.getContext(), eleType.getFKind(), 1);
3952 mlir::Type toTy = builder.getRefType(charType);
3953 mlir::Value cast = builder.createConvert(loc, toTy, buffer);
3954 charVal = builder.create<fir::LoadOp>(loc, cast);
3955 }
3956 LLVM_DEBUG(llvm::dbgs() << "ichar(" << charVal << ")\n");
3957 auto code = helper.extractCodeFromSingleton(charVal);
3958 if (code.getType() == resultType)
3959 return code;
3960 return builder.create<mlir::arith::ExtUIOp>(loc, resultType, code);
3961 }
3962
3963 // llvm floating point class intrinsic test values
3964 // 0 Signaling NaN
3965 // 1 Quiet NaN
3966 // 2 Negative infinity
3967 // 3 Negative normal
3968 // 4 Negative subnormal
3969 // 5 Negative zero
3970 // 6 Positive zero
3971 // 7 Positive subnormal
3972 // 8 Positive normal
3973 // 9 Positive infinity
3974 static constexpr int finiteTest = 0b0111111000;
3975 static constexpr int nanTest = 0b0000000011;
3976 static constexpr int negativeTest = 0b0000111100;
3977 static constexpr int normalTest = 0b0101101000;
3978 static constexpr int positiveTest = 0b1111000000;
3979 static constexpr int snanTest = 0b0000000001;
3980
3981 mlir::Value IntrinsicLibrary::genIsFPClass(mlir::Type resultType,
3982 llvm::ArrayRef<mlir::Value> args,
3983 int fpclass) {
3984 assert(args.size() == 1);
3985 mlir::Type i1Ty = builder.getI1Type();
3986 mlir::Value isfpclass =
3987 builder.create<mlir::LLVM::IsFPClass>(loc, i1Ty, args[0], fpclass);
3988 return builder.createConvert(loc, resultType, isfpclass);
3989 }
3990
3991 /// Generate code to raise \p except if \p cond is absent, or present and true.
3992 void IntrinsicLibrary::genRaiseExcept(int except, mlir::Value cond) {
3993 fir::IfOp ifOp;
3994 if (cond) {
3995 ifOp = builder.create<fir::IfOp>(loc, cond, /*withElseRegion=*/false);
3996 builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
3997 }
3998 mlir::Type i32Ty = builder.getIntegerType(32);
3999 genRuntimeCall(
4000 "feraiseexcept", i32Ty,
4001 fir::runtime::genMapException(
4002 builder, loc, builder.createIntegerConstant(loc, i32Ty, except)));
4003 if (cond)
4004 builder.setInsertionPointAfter(ifOp);
4005 }
4006
4007 // Return a reference to the contents of a derived type with one field.
4008 // Also return the field type.
4009 static std::pair<mlir::Value, mlir::Type>
4010 getFieldRef(fir::FirOpBuilder &builder, mlir::Location loc, mlir::Value rec) {
4011 auto recType =
4012 mlir::dyn_cast<fir::RecordType>(fir::unwrapPassByRefType(rec.getType()));
4013 assert(recType.getTypeList().size() == 1 && "expected exactly one component");
4014 auto [fieldName, fieldTy] = recType.getTypeList().front();
4015 mlir::Value field = builder.create<fir::FieldIndexOp>(
4016 loc, fir::FieldType::get(recType.getContext()), fieldName, recType,
4017 fir::getTypeParams(rec));
4018 return {builder.create<fir::CoordinateOp>(loc, builder.getRefType(fieldTy),
4019 rec, field),
4020 fieldTy};
4021 }
4022
4023 // IEEE_CLASS_TYPE OPERATOR(==), OPERATOR(/=)
4024 // IEEE_ROUND_TYPE OPERATOR(==), OPERATOR(/=)
4025 template <mlir::arith::CmpIPredicate pred>
4026 mlir::Value
4027 IntrinsicLibrary::genIeeeTypeCompare(mlir::Type resultType,
4028 llvm::ArrayRef<mlir::Value> args) {
4029 assert(args.size() == 2);
4030 auto [leftRef, fieldTy] = getFieldRef(builder, loc, args[0]);
4031 auto [rightRef, ignore] = getFieldRef(builder, loc, args[1]);
4032 mlir::Value left = builder.create<fir::LoadOp>(loc, fieldTy, leftRef);
4033 mlir::Value right = builder.create<fir::LoadOp>(loc, fieldTy, rightRef);
4034 return builder.create<mlir::arith::CmpIOp>(loc, pred, left, right);
4035 }
4036
4037 // IEEE_CLASS
4038 mlir::Value IntrinsicLibrary::genIeeeClass(mlir::Type resultType,
4039 llvm::ArrayRef<mlir::Value> args) {
4040 // Classify REAL argument X as one of 11 IEEE_CLASS_TYPE values via
4041 // a table lookup on an index built from 5 values derived from X.
4042 // In indexing order, the values are:
4043 //
4044 // [s] sign bit
4045 // [e] exponent != 0
4046 // [m] exponent == 1..1 (max exponent)
4047 // [l] low-order significand != 0
4048 // [h] high-order significand (kind=10: 2 bits; other kinds: 1 bit)
4049 //
4050 // kind=10 values have an explicit high-order integer significand bit,
4051 // whereas this bit is implicit for other kinds. This requires using a 6-bit
4052 // index into a 64-slot table for kind=10 argument classification queries
4053 // vs. a 5-bit index into a 32-slot table for other argument kind queries.
4054 // The instruction sequence is the same for the two cases.
4055 //
4056 // Placing the [l] and [h] significand bits in "swapped" order rather than
4057 // "natural" order enables more efficient generated code.
4058
4059 assert(args.size() == 1);
4060 mlir::Value realVal = args[0];
4061 mlir::FloatType realType = mlir::dyn_cast<mlir::FloatType>(realVal.getType());
4062 const unsigned intWidth = realType.getWidth();
4063 mlir::Type intType = builder.getIntegerType(intWidth);
4064 mlir::Value intVal =
4065 builder.create<mlir::arith::BitcastOp>(loc, intType, realVal);
4066 llvm::StringRef tableName = RTNAME_STRING(IeeeClassTable);
4067 uint64_t highSignificandSize = (realType.getWidth() == 80) + 1;
4068
4069 // Get masks and shift counts.
4070 mlir::Value signShift, highSignificandShift, exponentMask, lowSignificandMask;
4071 auto createIntegerConstant = [&](uint64_t k) {
4072 return builder.createIntegerConstant(loc, intType, k);
4073 };
4074 auto createIntegerConstantAPI = [&](const llvm::APInt &apInt) {
4075 return builder.create<mlir::arith::ConstantOp>(
4076 loc, intType, builder.getIntegerAttr(intType, apInt));
4077 };
4078 auto getMasksAndShifts = [&](uint64_t totalSize, uint64_t exponentSize,
4079 uint64_t significandSize,
4080 bool hasExplicitBit = false) {
4081 assert(1 + exponentSize + significandSize == totalSize &&
4082 "invalid floating point fields");
4083 uint64_t lowSignificandSize = significandSize - hasExplicitBit - 1;
4084 signShift = createIntegerConstant(totalSize - 1 - hasExplicitBit - 4);
4085 highSignificandShift = createIntegerConstant(lowSignificandSize);
4086 llvm::APInt exponentMaskAPI =
4087 llvm::APInt::getBitsSet(intWidth, /*lo=*/significandSize,
4088 /*hi=*/significandSize + exponentSize);
4089 exponentMask = createIntegerConstantAPI(exponentMaskAPI);
4090 llvm::APInt lowSignificandMaskAPI =
4091 llvm::APInt::getLowBitsSet(intWidth, lowSignificandSize);
4092 lowSignificandMask = createIntegerConstantAPI(lowSignificandMaskAPI);
4093 };
4094 switch (realType.getWidth()) {
4095 case 16:
4096 if (realType.isF16()) {
4097 // kind=2: 1 sign bit, 5 exponent bits, 10 significand bits
4098 getMasksAndShifts(16, 5, 10);
4099 } else {
4100 // kind=3: 1 sign bit, 8 exponent bits, 7 significand bits
4101 getMasksAndShifts(16, 8, 7);
4102 }
4103 break;
4104 case 32: // kind=4: 1 sign bit, 8 exponent bits, 23 significand bits
4105 getMasksAndShifts(32, 8, 23);
4106 break;
4107 case 64: // kind=8: 1 sign bit, 11 exponent bits, 52 significand bits
4108 getMasksAndShifts(64, 11, 52);
4109 break;
4110 case 80: // kind=10: 1 sign bit, 15 exponent bits, 1+63 significand bits
4111 getMasksAndShifts(80, 15, 64, /*hasExplicitBit=*/true);
4112 tableName = RTNAME_STRING(IeeeClassTable_10);
4113 break;
4114 case 128: // kind=16: 1 sign bit, 15 exponent bits, 112 significand bits
4115 getMasksAndShifts(128, 15, 112);
4116 break;
4117 default:
4118 llvm_unreachable("unknown real type");
4119 }
4120
4121 // [s] sign bit
4122 int pos = 3 + highSignificandSize;
4123 mlir::Value index = builder.create<mlir::arith::AndIOp>(
4124 loc, builder.create<mlir::arith::ShRUIOp>(loc, intVal, signShift),
4125 createIntegerConstant(1ULL << pos));
4126
4127 // [e] exponent != 0
4128 mlir::Value exponent =
4129 builder.create<mlir::arith::AndIOp>(loc, intVal, exponentMask);
4130 mlir::Value zero = createIntegerConstant(0);
4131 index = builder.create<mlir::arith::OrIOp>(
4132 loc, index,
4133 builder.create<mlir::arith::SelectOp>(
4134 loc,
4135 builder.create<mlir::arith::CmpIOp>(
4136 loc, mlir::arith::CmpIPredicate::ne, exponent, zero),
4137 createIntegerConstant(1ULL << --pos), zero));
4138
4139 // [m] exponent == 1..1 (max exponent)
4140 index = builder.create<mlir::arith::OrIOp>(
4141 loc, index,
4142 builder.create<mlir::arith::SelectOp>(
4143 loc,
4144 builder.create<mlir::arith::CmpIOp>(
4145 loc, mlir::arith::CmpIPredicate::eq, exponent, exponentMask),
4146 createIntegerConstant(1ULL << --pos), zero));
4147
4148 // [l] low-order significand != 0
4149 index = builder.create<mlir::arith::OrIOp>(
4150 loc, index,
4151 builder.create<mlir::arith::SelectOp>(
4152 loc,
4153 builder.create<mlir::arith::CmpIOp>(
4154 loc, mlir::arith::CmpIPredicate::ne,
4155 builder.create<mlir::arith::AndIOp>(loc, intVal,
4156 lowSignificandMask),
4157 zero),
4158 createIntegerConstant(1ULL << --pos), zero));
4159
4160 // [h] high-order significand (1 or 2 bits)
4161 index = builder.create<mlir::arith::OrIOp>(
4162 loc, index,
4163 builder.create<mlir::arith::AndIOp>(
4164 loc,
4165 builder.create<mlir::arith::ShRUIOp>(loc, intVal,
4166 highSignificandShift),
4167 createIntegerConstant((1 << highSignificandSize) - 1)));
4168
4169 int tableSize = 1 << (4 + highSignificandSize);
4170 mlir::Type int8Ty = builder.getIntegerType(8);
4171 mlir::Type tableTy = fir::SequenceType::get(tableSize, int8Ty);
4172 if (!builder.getNamedGlobal(tableName)) {
4173 llvm::SmallVector<mlir::Attribute, 64> values;
4174 auto insert = [&](std::int8_t which) {
4175 values.push_back(builder.getIntegerAttr(int8Ty, which));
4176 };
4177 // If indexing value [e] is 0, value [m] can't be 1. (If the exponent is 0,
4178 // it can't be the max exponent). Use IEEE_OTHER_VALUE for impossible
4179 // combinations.
4180 constexpr std::int8_t impossible = _FORTRAN_RUNTIME_IEEE_OTHER_VALUE;
4181 if (tableSize == 32) {
4182 // s e m l h kinds 2,3,4,8,16
4183 // ===================================================================
4184 /* 0 0 0 0 0 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_ZERO);
4185 /* 0 0 0 0 1 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_SUBNORMAL);
4186 /* 0 0 0 1 0 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_SUBNORMAL);
4187 /* 0 0 0 1 1 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_SUBNORMAL);
4188 /* 0 0 1 0 0 */ insert(impossible);
4189 /* 0 0 1 0 1 */ insert(impossible);
4190 /* 0 0 1 1 0 */ insert(impossible);
4191 /* 0 0 1 1 1 */ insert(impossible);
4192 /* 0 1 0 0 0 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_NORMAL);
4193 /* 0 1 0 0 1 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_NORMAL);
4194 /* 0 1 0 1 0 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_NORMAL);
4195 /* 0 1 0 1 1 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_NORMAL);
4196 /* 0 1 1 0 0 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_INF);
4197 /* 0 1 1 0 1 */ insert(_FORTRAN_RUNTIME_IEEE_QUIET_NAN);
4198 /* 0 1 1 1 0 */ insert(_FORTRAN_RUNTIME_IEEE_SIGNALING_NAN);
4199 /* 0 1 1 1 1 */ insert(_FORTRAN_RUNTIME_IEEE_QUIET_NAN);
4200 /* 1 0 0 0 0 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_ZERO);
4201 /* 1 0 0 0 1 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_SUBNORMAL);
4202 /* 1 0 0 1 0 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_SUBNORMAL);
4203 /* 1 0 0 1 1 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_SUBNORMAL);
4204 /* 1 0 1 0 0 */ insert(impossible);
4205 /* 1 0 1 0 1 */ insert(impossible);
4206 /* 1 0 1 1 0 */ insert(impossible);
4207 /* 1 0 1 1 1 */ insert(impossible);
4208 /* 1 1 0 0 0 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_NORMAL);
4209 /* 1 1 0 0 1 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_NORMAL);
4210 /* 1 1 0 1 0 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_NORMAL);
4211 /* 1 1 0 1 1 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_NORMAL);
4212 /* 1 1 1 0 0 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_INF);
4213 /* 1 1 1 0 1 */ insert(_FORTRAN_RUNTIME_IEEE_QUIET_NAN);
4214 /* 1 1 1 1 0 */ insert(_FORTRAN_RUNTIME_IEEE_SIGNALING_NAN);
4215 /* 1 1 1 1 1 */ insert(_FORTRAN_RUNTIME_IEEE_QUIET_NAN);
4216 } else {
4217 // Unlike values of other kinds, kind=10 values can be "invalid", and
4218 // can appear in code. Use IEEE_OTHER_VALUE for invalid bit patterns.
4219 // Runtime IO may print an invalid value as a NaN.
4220 constexpr std::int8_t invalid = _FORTRAN_RUNTIME_IEEE_OTHER_VALUE;
4221 // s e m l h kind 10
4222 // ===================================================================
4223 /* 0 0 0 0 00 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_ZERO);
4224 /* 0 0 0 0 01 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_SUBNORMAL);
4225 /* 0 0 0 0 10 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_SUBNORMAL);
4226 /* 0 0 0 0 11 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_SUBNORMAL);
4227 /* 0 0 0 1 00 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_SUBNORMAL);
4228 /* 0 0 0 1 01 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_SUBNORMAL);
4229 /* 0 0 0 1 10 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_SUBNORMAL);
4230 /* 0 0 0 1 11 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_SUBNORMAL);
4231 /* 0 0 1 0 00 */ insert(impossible);
4232 /* 0 0 1 0 01 */ insert(impossible);
4233 /* 0 0 1 0 10 */ insert(impossible);
4234 /* 0 0 1 0 11 */ insert(impossible);
4235 /* 0 0 1 1 00 */ insert(impossible);
4236 /* 0 0 1 1 01 */ insert(impossible);
4237 /* 0 0 1 1 10 */ insert(impossible);
4238 /* 0 0 1 1 11 */ insert(impossible);
4239 /* 0 1 0 0 00 */ insert(invalid);
4240 /* 0 1 0 0 01 */ insert(invalid);
4241 /* 0 1 0 0 10 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_NORMAL);
4242 /* 0 1 0 0 11 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_NORMAL);
4243 /* 0 1 0 1 00 */ insert(invalid);
4244 /* 0 1 0 1 01 */ insert(invalid);
4245 /* 0 1 0 1 10 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_NORMAL);
4246 /* 0 1 0 1 11 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_NORMAL);
4247 /* 0 1 1 0 00 */ insert(invalid);
4248 /* 0 1 1 0 01 */ insert(invalid);
4249 /* 0 1 1 0 10 */ insert(_FORTRAN_RUNTIME_IEEE_POSITIVE_INF);
4250 /* 0 1 1 0 11 */ insert(_FORTRAN_RUNTIME_IEEE_QUIET_NAN);
4251 /* 0 1 1 1 00 */ insert(invalid);
4252 /* 0 1 1 1 01 */ insert(invalid);
4253 /* 0 1 1 1 10 */ insert(_FORTRAN_RUNTIME_IEEE_SIGNALING_NAN);
4254 /* 0 1 1 1 11 */ insert(_FORTRAN_RUNTIME_IEEE_QUIET_NAN);
4255 /* 1 0 0 0 00 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_ZERO);
4256 /* 1 0 0 0 01 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_SUBNORMAL);
4257 /* 1 0 0 0 10 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_SUBNORMAL);
4258 /* 1 0 0 0 11 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_SUBNORMAL);
4259 /* 1 0 0 1 00 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_SUBNORMAL);
4260 /* 1 0 0 1 01 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_SUBNORMAL);
4261 /* 1 0 0 1 10 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_SUBNORMAL);
4262 /* 1 0 0 1 11 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_SUBNORMAL);
4263 /* 1 0 1 0 00 */ insert(impossible);
4264 /* 1 0 1 0 01 */ insert(impossible);
4265 /* 1 0 1 0 10 */ insert(impossible);
4266 /* 1 0 1 0 11 */ insert(impossible);
4267 /* 1 0 1 1 00 */ insert(impossible);
4268 /* 1 0 1 1 01 */ insert(impossible);
4269 /* 1 0 1 1 10 */ insert(impossible);
4270 /* 1 0 1 1 11 */ insert(impossible);
4271 /* 1 1 0 0 00 */ insert(invalid);
4272 /* 1 1 0 0 01 */ insert(invalid);
4273 /* 1 1 0 0 10 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_NORMAL);
4274 /* 1 1 0 0 11 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_NORMAL);
4275 /* 1 1 0 1 00 */ insert(invalid);
4276 /* 1 1 0 1 01 */ insert(invalid);
4277 /* 1 1 0 1 10 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_NORMAL);
4278 /* 1 1 0 1 11 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_NORMAL);
4279 /* 1 1 1 0 00 */ insert(invalid);
4280 /* 1 1 1 0 01 */ insert(invalid);
4281 /* 1 1 1 0 10 */ insert(_FORTRAN_RUNTIME_IEEE_NEGATIVE_INF);
4282 /* 1 1 1 0 11 */ insert(_FORTRAN_RUNTIME_IEEE_QUIET_NAN);
4283 /* 1 1 1 1 00 */ insert(invalid);
4284 /* 1 1 1 1 01 */ insert(invalid);
4285 /* 1 1 1 1 10 */ insert(_FORTRAN_RUNTIME_IEEE_SIGNALING_NAN);
4286 /* 1 1 1 1 11 */ insert(_FORTRAN_RUNTIME_IEEE_QUIET_NAN);
4287 }
4288 builder.createGlobalConstant(
4289 loc, tableTy, tableName, builder.createLinkOnceLinkage(),
4290 mlir::DenseElementsAttr::get(
4291 mlir::RankedTensorType::get(tableSize, int8Ty), values));
4292 }
4293
4294 return builder.create<fir::CoordinateOp>(
4295 loc, builder.getRefType(resultType),
4296 builder.create<fir::AddrOfOp>(loc, builder.getRefType(tableTy),
4297 builder.getSymbolRefAttr(tableName)),
4298 index);
4299 }
4300
4301 // IEEE_COPY_SIGN
4302 mlir::Value
4303 IntrinsicLibrary::genIeeeCopySign(mlir::Type resultType,
4304 llvm::ArrayRef<mlir::Value> args) {
4305 // Copy the sign of REAL arg Y to REAL arg X.
4306 assert(args.size() == 2);
4307 mlir::Value xRealVal = args[0];
4308 mlir::Value yRealVal = args[1];
4309 mlir::FloatType xRealType =
4310 mlir::dyn_cast<mlir::FloatType>(xRealVal.getType());
4311 mlir::FloatType yRealType =
4312 mlir::dyn_cast<mlir::FloatType>(yRealVal.getType());
4313
4314 if (yRealType == mlir::FloatType::getBF16(builder.getContext())) {
4315 // Workaround: CopySignOp and BitcastOp don't work for kind 3 arg Y.
4316 // This conversion should always preserve the sign bit.
4317 yRealVal = builder.createConvert(
4318 loc, mlir::FloatType::getF32(builder.getContext()), yRealVal);
4319 yRealType = mlir::FloatType::getF32(builder.getContext());
4320 }
4321
4322 // Args have the same type.
4323 if (xRealType == yRealType)
4324 return builder.create<mlir::math::CopySignOp>(loc, xRealVal, yRealVal);
4325
4326 // Args have different types.
4327 mlir::Type xIntType = builder.getIntegerType(xRealType.getWidth());
4328 mlir::Type yIntType = builder.getIntegerType(yRealType.getWidth());
4329 mlir::Value xIntVal =
4330 builder.create<mlir::arith::BitcastOp>(loc, xIntType, xRealVal);
4331 mlir::Value yIntVal =
4332 builder.create<mlir::arith::BitcastOp>(loc, yIntType, yRealVal);
4333 mlir::Value xZero = builder.createIntegerConstant(loc, xIntType, 0);
4334 mlir::Value yZero = builder.createIntegerConstant(loc, yIntType, 0);
4335 mlir::Value xOne = builder.createIntegerConstant(loc, xIntType, 1);
4336 mlir::Value ySign = builder.create<mlir::arith::ShRUIOp>(
4337 loc, yIntVal,
4338 builder.createIntegerConstant(loc, yIntType, yRealType.getWidth() - 1));
4339 mlir::Value xAbs = builder.create<mlir::arith::ShRUIOp>(
4340 loc, builder.create<mlir::arith::ShLIOp>(loc, xIntVal, xOne), xOne);
4341 mlir::Value xSign = builder.create<mlir::arith::SelectOp>(
4342 loc,
4343 builder.create<mlir::arith::CmpIOp>(loc, mlir::arith::CmpIPredicate::eq,
4344 ySign, yZero),
4345 xZero,
4346 builder.create<mlir::arith::ShLIOp>(
4347 loc, xOne,
4348 builder.createIntegerConstant(loc, xIntType,
4349 xRealType.getWidth() - 1)));
4350 return builder.create<mlir::arith::BitcastOp>(
4351 loc, xRealType, builder.create<mlir::arith::OrIOp>(loc, xAbs, xSign));
4352 }
4353
4354 // IEEE_GET_FLAG
4355 void IntrinsicLibrary::genIeeeGetFlag(llvm::ArrayRef<fir::ExtendedValue> args) {
4356 assert(args.size() == 2);
4357 // Set FLAG_VALUE=.TRUE. if the exception specified by FLAG is signaling.
4358 mlir::Value flag = fir::getBase(args[0]);
4359 mlir::Value flagValue = fir::getBase(args[1]);
4360 mlir::Type resultTy =
4361 mlir::dyn_cast<fir::ReferenceType>(flagValue.getType()).getEleTy();
4362 mlir::Type i32Ty = builder.getIntegerType(32);
4363 mlir::Value zero = builder.createIntegerConstant(loc, i32Ty, 0);
4364 auto [fieldRef, ignore] = getFieldRef(builder, loc, flag);
4365 mlir::Value field = builder.create<fir::LoadOp>(loc, fieldRef);
4366 mlir::Value exceptSet = IntrinsicLibrary::genRuntimeCall(
4367 "fetestexcept", i32Ty,
4368 fir::runtime::genMapException(
4369 builder, loc, builder.create<fir::ConvertOp>(loc, i32Ty, field)));
4370 mlir::Value logicalResult = builder.create<fir::ConvertOp>(
4371 loc, resultTy,
4372 builder.create<mlir::arith::CmpIOp>(loc, mlir::arith::CmpIPredicate::ne,
4373 exceptSet, zero));
4374 builder.create<fir::StoreOp>(loc, logicalResult, flagValue);
4375 }
4376
4377 // IEEE_GET_HALTING_MODE
4378 void IntrinsicLibrary::genIeeeGetHaltingMode(
4379 llvm::ArrayRef<fir::ExtendedValue> args) {
4380 // Set HALTING=.TRUE. if the exception specified by FLAG will cause halting.
4381 assert(args.size() == 2);
4382 mlir::Value flag = fir::getBase(args[0]);
4383 mlir::Value halting = fir::getBase(args[1]);
4384 mlir::Type resultTy =
4385 mlir::dyn_cast<fir::ReferenceType>(halting.getType()).getEleTy();
4386 mlir::Type i32Ty = builder.getIntegerType(32);
4387 mlir::Value zero = builder.createIntegerConstant(loc, i32Ty, 0);
4388 auto [fieldRef, ignore] = getFieldRef(builder, loc, flag);
4389 mlir::Value field = builder.create<fir::LoadOp>(loc, fieldRef);
4390 mlir::Value haltSet =
4391 IntrinsicLibrary::genRuntimeCall("fegetexcept", i32Ty, {});
4392 mlir::Value intResult = builder.create<mlir::arith::AndIOp>(
4393 loc, haltSet,
4394 fir::runtime::genMapException(
4395 builder, loc, builder.create<fir::ConvertOp>(loc, i32Ty, field)));
4396 mlir::Value logicalResult = builder.create<fir::ConvertOp>(
4397 loc, resultTy,
4398 builder.create<mlir::arith::CmpIOp>(loc, mlir::arith::CmpIPredicate::ne,
4399 intResult, zero));
4400 builder.create<fir::StoreOp>(loc, logicalResult, halting);
4401 }
4402
4403 // IEEE_GET_MODES, IEEE_SET_MODES
4404 template <bool isGet>
4405 void IntrinsicLibrary::genIeeeGetOrSetModes(
4406 llvm::ArrayRef<fir::ExtendedValue> args) {
4407 assert(args.size() == 1);
4408 mlir::Type ptrTy = builder.getRefType(builder.getIntegerType(32));
4409 mlir::Type i32Ty = builder.getIntegerType(32);
4410 mlir::Value addr =
4411 builder.create<fir::ConvertOp>(loc, ptrTy, getBase(args[0]));
4412 genRuntimeCall(isGet ? "fegetmode" : "fesetmode", i32Ty, addr);
4413 }
4414
4415 // Check that an explicit ieee_[get|set]_rounding_mode call radix value is 2.
4416 static void checkRadix(fir::FirOpBuilder &builder, mlir::Location loc,
4417 mlir::Value radix, std::string procName) {
4418 mlir::Value notTwo = builder.create<mlir::arith::CmpIOp>(
4419 loc, mlir::arith::CmpIPredicate::ne, radix,
4420 builder.createIntegerConstant(loc, radix.getType(), 2));
4421 auto ifOp = builder.create<fir::IfOp>(loc, notTwo,
4422 /*withElseRegion=*/false);
4423 builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
4424 fir::runtime::genReportFatalUserError(builder, loc,
4425 procName + " radix argument must be 2");
4426 builder.setInsertionPointAfter(ifOp);
4427 }
4428
4429 // IEEE_GET_ROUNDING_MODE
4430 void IntrinsicLibrary::genIeeeGetRoundingMode(
4431 llvm::ArrayRef<fir::ExtendedValue> args) {
4432 // Set arg ROUNDING_VALUE to the current floating point rounding mode.
4433 // Values are chosen to match the llvm.get.rounding encoding.
4434 // Generate an error if the value of optional arg RADIX is not 2.
4435 assert(args.size() == 1 || args.size() == 2);
4436 if (args.size() == 2)
4437 checkRadix(builder, loc, fir::getBase(args[1]), "ieee_get_rounding_mode");
4438 auto [fieldRef, fieldTy] = getFieldRef(builder, loc, fir::getBase(args[0]));
4439 mlir::func::FuncOp getRound = fir::factory::getLlvmGetRounding(builder);
4440 mlir::Value mode = builder.create<fir::CallOp>(loc, getRound).getResult(0);
4441 mode = builder.createConvert(loc, fieldTy, mode);
4442 builder.create<fir::StoreOp>(loc, mode, fieldRef);
4443 }
4444
4445 // IEEE_GET_STATUS, IEEE_SET_STATUS
4446 template <bool isGet>
4447 void IntrinsicLibrary::genIeeeGetOrSetStatus(
4448 llvm::ArrayRef<fir::ExtendedValue> args) {
4449 assert(args.size() == 1);
4450 mlir::Type ptrTy = builder.getRefType(builder.getIntegerType(32));
4451 mlir::Type i32Ty = builder.getIntegerType(32);
4452 mlir::Value addr =
4453 builder.create<fir::ConvertOp>(loc, ptrTy, getBase(args[0]));
4454 genRuntimeCall(isGet ? "fegetenv" : "fesetenv", i32Ty, addr);
4455 }
4456
4457 // IEEE_IS_FINITE
4458 mlir::Value
4459 IntrinsicLibrary::genIeeeIsFinite(mlir::Type resultType,
4460 llvm::ArrayRef<mlir::Value> args) {
4461 // Check if arg X is a (negative or positive) (normal, denormal, or zero).
4462 assert(args.size() == 1);
4463 return genIsFPClass(resultType, args, finiteTest);
4464 }
4465
4466 // IEEE_IS_NAN
4467 mlir::Value IntrinsicLibrary::genIeeeIsNan(mlir::Type resultType,
4468 llvm::ArrayRef<mlir::Value> args) {
4469 // Check if arg X is a (signaling or quiet) NaN.
4470 assert(args.size() == 1);
4471 return genIsFPClass(resultType, args, nanTest);
4472 }
4473
4474 // IEEE_IS_NEGATIVE
4475 mlir::Value
4476 IntrinsicLibrary::genIeeeIsNegative(mlir::Type resultType,
4477 llvm::ArrayRef<mlir::Value> args) {
4478 // Check if arg X is a negative (infinity, normal, denormal or zero).
4479 assert(args.size() == 1);
4480 return genIsFPClass(resultType, args, negativeTest);
4481 }
4482
4483 // IEEE_IS_NORMAL
4484 mlir::Value
4485 IntrinsicLibrary::genIeeeIsNormal(mlir::Type resultType,
4486 llvm::ArrayRef<mlir::Value> args) {
4487 // Check if arg X is a (negative or positive) (normal or zero).
4488 assert(args.size() == 1);
4489 return genIsFPClass(resultType, args, normalTest);
4490 }
4491
4492 // IEEE_LOGB
4493 mlir::Value IntrinsicLibrary::genIeeeLogb(mlir::Type resultType,
4494 llvm::ArrayRef<mlir::Value> args) {
4495 // Exponent of X, with special case treatment for some input values.
4496 // Return: X == 0
4497 // ? -infinity (and raise FE_DIVBYZERO)
4498 // : ieee_is_finite(X)
4499 // ? exponent(X) - 1 // unbiased exponent of X
4500 // : ieee_copy_sign(X, 1.0) // +infinity or NaN
4501 assert(args.size() == 1);
4502 mlir::Value realVal = args[0];
4503 mlir::FloatType realType = mlir::dyn_cast<mlir::FloatType>(realVal.getType());
4504 int bitWidth = realType.getWidth();
4505 mlir::Type intType = builder.getIntegerType(realType.getWidth());
4506 mlir::Value intVal =
4507 builder.create<mlir::arith::BitcastOp>(loc, intType, realVal);
4508 mlir::Type i1Ty = builder.getI1Type();
4509
4510 int exponentBias, significandSize, nonSignificandSize;
4511 switch (bitWidth) {
4512 case 16:
4513 if (realType.isF16()) {
4514 // kind=2: 1 sign bit, 5 exponent bits, 10 significand bits
4515 exponentBias = (1 << (5 - 1)) - 1; // 15
4516 significandSize = 10;
4517 nonSignificandSize = 6;
4518 break;
4519 }
4520 assert(realType.isBF16() && "unknown 16-bit real type");
4521 // kind=3: 1 sign bit, 8 exponent bits, 7 significand bits
4522 exponentBias = (1 << (8 - 1)) - 1; // 127
4523 significandSize = 7;
4524 nonSignificandSize = 9;
4525 break;
4526 case 32:
4527 // kind=4: 1 sign bit, 8 exponent bits, 23 significand bits
4528 exponentBias = (1 << (8 - 1)) - 1; // 127
4529 significandSize = 23;
4530 nonSignificandSize = 9;
4531 break;
4532 case 64:
4533 // kind=8: 1 sign bit, 11 exponent bits, 52 significand bits
4534 exponentBias = (1 << (11 - 1)) - 1; // 1023
4535 significandSize = 52;
4536 nonSignificandSize = 12;
4537 break;
4538 case 80:
4539 // kind=10: 1 sign bit, 15 exponent bits, 1+63 significand bits
4540 exponentBias = (1 << (15 - 1)) - 1; // 16383
4541 significandSize = 64;
4542 nonSignificandSize = 16 + 1;
4543 break;
4544 case 128:
4545 // kind=16: 1 sign bit, 15 exponent bits, 112 significand bits
4546 exponentBias = (1 << (15 - 1)) - 1; // 16383
4547 significandSize = 112;
4548 nonSignificandSize = 16;
4549 break;
4550 default:
4551 llvm_unreachable("unknown real type");
4552 }
4553
4554 mlir::Value isZero = builder.create<mlir::arith::CmpFOp>(
4555 loc, mlir::arith::CmpFPredicate::OEQ, realVal,
4556 builder.createRealZeroConstant(loc, resultType));
4557 auto outerIfOp = builder.create<fir::IfOp>(loc, resultType, isZero,
4558 /*withElseRegion=*/true);
4559 // X is zero -- result is -infinity
4560 builder.setInsertionPointToStart(&outerIfOp.getThenRegion().front());
4561 genRaiseExcept(_FORTRAN_RUNTIME_IEEE_DIVIDE_BY_ZERO);
4562 mlir::Value ones = builder.createAllOnesInteger(loc, intType);
4563 mlir::Value result = builder.create<mlir::arith::ShLIOp>(
4564 loc, ones,
4565 builder.createIntegerConstant(loc, intType,
4566 // kind=10 high-order bit is explicit
4567 significandSize - (bitWidth == 80)));
4568 result = builder.create<mlir::arith::BitcastOp>(loc, resultType, result);
4569 builder.create<fir::ResultOp>(loc, result);
4570
4571 builder.setInsertionPointToStart(&outerIfOp.getElseRegion().front());
4572 mlir::Value one = builder.createIntegerConstant(loc, intType, 1);
4573 mlir::Value shiftLeftOne =
4574 builder.create<mlir::arith::ShLIOp>(loc, intVal, one);
4575 mlir::Value isFinite = genIsFPClass(i1Ty, args, finiteTest);
4576 auto innerIfOp = builder.create<fir::IfOp>(loc, resultType, isFinite,
4577 /*withElseRegion=*/true);
4578 // X is non-zero finite -- result is unbiased exponent of X
4579 builder.setInsertionPointToStart(&innerIfOp.getThenRegion().front());
4580 mlir::Value isNormal = genIsFPClass(i1Ty, args, normalTest);
4581 auto normalIfOp = builder.create<fir::IfOp>(loc, resultType, isNormal,
4582 /*withElseRegion=*/true);
4583 // X is normal
4584 builder.setInsertionPointToStart(&normalIfOp.getThenRegion().front());
4585 mlir::Value biasedExponent = builder.create<mlir::arith::ShRUIOp>(
4586 loc, shiftLeftOne,
4587 builder.createIntegerConstant(loc, intType, significandSize + 1));
4588 result = builder.create<mlir::arith::SubIOp>(
4589 loc, biasedExponent,
4590 builder.createIntegerConstant(loc, intType, exponentBias));
4591 result = builder.create<fir::ConvertOp>(loc, resultType, result);
4592 builder.create<fir::ResultOp>(loc, result);
4593
4594 // X is denormal -- result is (-exponentBias - ctlz(significand))
4595 builder.setInsertionPointToStart(&normalIfOp.getElseRegion().front());
4596 mlir::Value significand = builder.create<mlir::arith::ShLIOp>(
4597 loc, intVal,
4598 builder.createIntegerConstant(loc, intType, nonSignificandSize));
4599 mlir::Value ctlz =
4600 builder.create<mlir::math::CountLeadingZerosOp>(loc, significand);
4601 mlir::Type i32Ty = builder.getI32Type();
4602 result = builder.create<mlir::arith::SubIOp>(
4603 loc, builder.createIntegerConstant(loc, i32Ty, -exponentBias),
4604 builder.create<fir::ConvertOp>(loc, i32Ty, ctlz));
4605 result = builder.create<fir::ConvertOp>(loc, resultType, result);
4606 builder.create<fir::ResultOp>(loc, result);
4607
4608 builder.setInsertionPointToEnd(&innerIfOp.getThenRegion().front());
4609 builder.create<fir::ResultOp>(loc, normalIfOp.getResult(0));
4610
4611 // X is infinity or NaN -- result is +infinity or NaN
4612 builder.setInsertionPointToStart(&innerIfOp.getElseRegion().front());
4613 result = builder.create<mlir::arith::ShRUIOp>(loc, shiftLeftOne, one);
4614 result = builder.create<mlir::arith::BitcastOp>(loc, resultType, result);
4615 builder.create<fir::ResultOp>(loc, result);
4616
4617 // Unwind the if nest.
4618 builder.setInsertionPointToEnd(&outerIfOp.getElseRegion().front());
4619 builder.create<fir::ResultOp>(loc, innerIfOp.getResult(0));
4620 builder.setInsertionPointAfter(outerIfOp);
4621 return outerIfOp.getResult(0);
4622 }
4623
4624 // IEEE_MAX, IEEE_MAX_MAG, IEEE_MAX_NUM, IEEE_MAX_NUM_MAG
4625 // IEEE_MIN, IEEE_MIN_MAG, IEEE_MIN_NUM, IEEE_MIN_NUM_MAG
4626 template <bool isMax, bool isNum, bool isMag>
4627 mlir::Value IntrinsicLibrary::genIeeeMaxMin(mlir::Type resultType,
4628 llvm::ArrayRef<mlir::Value> args) {
4629 // Maximum/minimum of X and Y with special case treatment of NaN operands.
4630 // The f18 definitions of these procedures (where applicable) are incomplete.
4631 // And f18 results involving NaNs are different from and incompatible with
4632 // f23 results. This code implements the f23 procedures.
4633 // For IEEE_MAX_MAG and IEEE_MAX_NUM_MAG:
4634 // if (ABS(X) > ABS(Y))
4635 // return X
4636 // else if (ABS(Y) > ABS(X))
4637 // return Y
4638 // else if (ABS(X) == ABS(Y))
4639 // return IEEE_SIGNBIT(Y) ? X : Y
4640 // // X or Y or both are NaNs
4641 // if (X is an sNaN or Y is an sNaN) raise FE_INVALID
4642 // if (IEEE_MAX_NUM_MAG and X is not a NaN) return X
4643 // if (IEEE_MAX_NUM_MAG and Y is not a NaN) return Y
4644 // return a qNaN
4645 // For IEEE_MAX, IEEE_MAX_NUM: compare X vs. Y rather than ABS(X) vs. ABS(Y)
4646 // IEEE_MIN, IEEE_MIN_MAG, IEEE_MIN_NUM, IEEE_MIN_NUM_MAG: invert comparisons
4647 assert(args.size() == 2);
4648 mlir::Value x = args[0];
4649 mlir::Value y = args[1];
4650 mlir::Value x1, y1; // X or ABS(X), Y or ABS(Y)
4651 if constexpr (isMag) {
4652 mlir::Value zero = builder.createRealZeroConstant(loc, resultType);
4653 x1 = builder.create<mlir::math::CopySignOp>(loc, x, zero);
4654 y1 = builder.create<mlir::math::CopySignOp>(loc, y, zero);
4655 } else {
4656 x1 = x;
4657 y1 = y;
4658 }
4659 mlir::Type i1Ty = builder.getI1Type();
4660 mlir::Type i8Ty = builder.getIntegerType(8);
4661 mlir::arith::CmpFPredicate pred;
4662 mlir::Value cmp, result, resultIsX, resultIsY;
4663
4664 // X1 < Y1 -- MAX result is Y; MIN result is X.
4665 pred = mlir::arith::CmpFPredicate::OLT;
4666 cmp = builder.create<mlir::arith::CmpFOp>(loc, pred, x1, y1);
4667 auto ifOp1 = builder.create<fir::IfOp>(loc, resultType, cmp, true);
4668 builder.setInsertionPointToStart(&ifOp1.getThenRegion().front());
4669 result = isMax ? y : x;
4670 builder.create<fir::ResultOp>(loc, result);
4671
4672 // X1 > Y1 -- MAX result is X; MIN result is Y.
4673 builder.setInsertionPointToStart(&ifOp1.getElseRegion().front());
4674 pred = mlir::arith::CmpFPredicate::OGT;
4675 cmp = builder.create<mlir::arith::CmpFOp>(loc, pred, x1, y1);
4676 auto ifOp2 = builder.create<fir::IfOp>(loc, resultType, cmp, true);
4677 builder.setInsertionPointToStart(&ifOp2.getThenRegion().front());
4678 result = isMax ? x : y;
4679 builder.create<fir::ResultOp>(loc, result);
4680
4681 // X1 == Y1 -- MAX favors a positive result; MIN favors a negative result.
4682 builder.setInsertionPointToStart(&ifOp2.getElseRegion().front());
4683 pred = mlir::arith::CmpFPredicate::OEQ;
4684 cmp = builder.create<mlir::arith::CmpFOp>(loc, pred, x1, y1);
4685 auto ifOp3 = builder.create<fir::IfOp>(loc, resultType, cmp, true);
4686 builder.setInsertionPointToStart(&ifOp3.getThenRegion().front());
4687 resultIsX = isMax ? genIsFPClass(i1Ty, x, positiveTest)
4688 : genIsFPClass(i1Ty, x, negativeTest);
4689 result = builder.create<mlir::arith::SelectOp>(loc, resultIsX, x, y);
4690 builder.create<fir::ResultOp>(loc, result);
4691
4692 // X or Y or both are NaNs -- result may be X, Y, or a qNaN
4693 builder.setInsertionPointToStart(&ifOp3.getElseRegion().front());
4694 if constexpr (isNum) {
4695 pred = mlir::arith::CmpFPredicate::ORD; // check for a non-NaN
4696 resultIsX = builder.create<mlir::arith::CmpFOp>(loc, pred, x, x);
4697 resultIsY = builder.create<mlir::arith::CmpFOp>(loc, pred, y, y);
4698 } else {
4699 resultIsX = resultIsY = builder.createBool(loc, false);
4700 }
4701 mlir::Value qNaN =
4702 genIeeeValue(resultType, builder.createIntegerConstant(
4703 loc, i8Ty, _FORTRAN_RUNTIME_IEEE_QUIET_NAN));
4704 result = builder.create<mlir::arith::SelectOp>(
4705 loc, resultIsX, x,
4706 builder.create<mlir::arith::SelectOp>(loc, resultIsY, y, qNaN));
4707 mlir::Value hasSNaNOp = builder.create<mlir::arith::OrIOp>(
4708 loc, genIsFPClass(builder.getI1Type(), args[0], snanTest),
4709 genIsFPClass(builder.getI1Type(), args[1], snanTest));
4710 genRaiseExcept(_FORTRAN_RUNTIME_IEEE_INVALID, hasSNaNOp);
4711 builder.create<fir::ResultOp>(loc, result);
4712
4713 // Unwind the if nest.
4714 builder.setInsertionPointAfter(ifOp3);
4715 builder.create<fir::ResultOp>(loc, ifOp3.getResult(0));
4716 builder.setInsertionPointAfter(ifOp2);
4717 builder.create<fir::ResultOp>(loc, ifOp2.getResult(0));
4718 builder.setInsertionPointAfter(ifOp1);
4719 return ifOp1.getResult(0);
4720 }
4721
4722 // IEEE_QUIET_EQ, IEEE_QUIET_GE, IEEE_QUIET_GT,
4723 // IEEE_QUIET_LE, IEEE_QUIET_LT, IEEE_QUIET_NE
4724 template <mlir::arith::CmpFPredicate pred>
4725 mlir::Value
4726 IntrinsicLibrary::genIeeeQuietCompare(mlir::Type resultType,
4727 llvm::ArrayRef<mlir::Value> args) {
4728 // Compare X and Y with special case treatment of NaN operands.
4729 assert(args.size() == 2);
4730 mlir::Value hasSNaNOp = builder.create<mlir::arith::OrIOp>(
4731 loc, genIsFPClass(builder.getI1Type(), args[0], snanTest),
4732 genIsFPClass(builder.getI1Type(), args[1], snanTest));
4733 mlir::Value res =
4734 builder.create<mlir::arith::CmpFOp>(loc, pred, args[0], args[1]);
4735 genRaiseExcept(_FORTRAN_RUNTIME_IEEE_INVALID, hasSNaNOp);
4736 return builder.create<fir::ConvertOp>(loc, resultType, res);
4737 }
4738
4739 // IEEE_SET_FLAG, IEEE_SET_HALTING_MODE
4740 template <bool isFlag>
4741 void IntrinsicLibrary::genIeeeSetFlagOrHaltingMode(
4742 llvm::ArrayRef<fir::ExtendedValue> args) {
4743 // IEEE_SET_FLAG: Set an exception FLAG to a FLAG_VALUE.
4744 // IEEE_SET_HALTING: Set an exception halting mode FLAG to a HALTING value.
4745 assert(args.size() == 2);
4746 mlir::Type i1Ty = builder.getI1Type();
4747 mlir::Type i32Ty = builder.getIntegerType(32);
4748 auto [fieldRef, ignore] = getFieldRef(builder, loc, getBase(args[0]));
4749 mlir::Value field = builder.create<fir::LoadOp>(loc, fieldRef);
4750 mlir::Value except = fir::runtime::genMapException(
4751 builder, loc, builder.create<fir::ConvertOp>(loc, i32Ty, field));
4752 auto ifOp = builder.create<fir::IfOp>(
4753 loc, builder.create<fir::ConvertOp>(loc, i1Ty, getBase(args[1])),
4754 /*withElseRegion=*/true);
4755 builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
4756 genRuntimeCall(isFlag ? "feraiseexcept" : "feenableexcept", i32Ty, except);
4757 builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
4758 genRuntimeCall(isFlag ? "feclearexcept" : "fedisableexcept", i32Ty, except);
4759 builder.setInsertionPointAfter(ifOp);
4760 }
4761
4762 // IEEE_SET_ROUNDING_MODE
4763 void IntrinsicLibrary::genIeeeSetRoundingMode(
4764 llvm::ArrayRef<fir::ExtendedValue> args) {
4765 // Set the current floating point rounding mode to the value of arg
4766 // ROUNDING_VALUE. Values are llvm.get.rounding encoding values.
4767 // Generate an error if the value of optional arg RADIX is not 2.
4768 assert(args.size() == 1 || args.size() == 2);
4769 if (args.size() == 2)
4770 checkRadix(builder, loc, fir::getBase(args[1]), "ieee_set_rounding_mode");
4771 auto [fieldRef, ignore] = getFieldRef(builder, loc, fir::getBase(args[0]));
4772 mlir::func::FuncOp setRound = fir::factory::getLlvmSetRounding(builder);
4773 mlir::Value mode = builder.create<fir::LoadOp>(loc, fieldRef);
4774 mode = builder.create<fir::ConvertOp>(
4775 loc, setRound.getFunctionType().getInput(0), mode);
4776 builder.create<fir::CallOp>(loc, setRound, mode);
4777 }
4778
4779 // IEEE_SIGNALING_EQ, IEEE_SIGNALING_GE, IEEE_SIGNALING_GT,
4780 // IEEE_SIGNALING_LE, IEEE_SIGNALING_LT, IEEE_SIGNALING_NE
4781 template <mlir::arith::CmpFPredicate pred>
4782 mlir::Value
4783 IntrinsicLibrary::genIeeeSignalingCompare(mlir::Type resultType,
4784 llvm::ArrayRef<mlir::Value> args) {
4785 // Compare X and Y with special case treatment of NaN operands.
4786 assert(args.size() == 2);
4787 mlir::Value hasNaNOp = genIeeeUnordered(mlir::Type{}, args);
4788 mlir::Value res =
4789 builder.create<mlir::arith::CmpFOp>(loc, pred, args[0], args[1]);
4790 genRaiseExcept(_FORTRAN_RUNTIME_IEEE_INVALID, hasNaNOp);
4791 return builder.create<fir::ConvertOp>(loc, resultType, res);
4792 }
4793
4794 // IEEE_SIGNBIT
4795 mlir::Value IntrinsicLibrary::genIeeeSignbit(mlir::Type resultType,
4796 llvm::ArrayRef<mlir::Value> args) {
4797 // Check if the sign bit of arg X is set.
4798 assert(args.size() == 1);
4799 mlir::Value realVal = args[0];
4800 mlir::FloatType realType = mlir::dyn_cast<mlir::FloatType>(realVal.getType());
4801 int bitWidth = realType.getWidth();
4802 if (realType == mlir::FloatType::getBF16(builder.getContext())) {
4803 // Workaround: can't bitcast or convert real(3) to integer(2) or real(2).
4804 realVal = builder.createConvert(
4805 loc, mlir::FloatType::getF32(builder.getContext()), realVal);
4806 bitWidth = 32;
4807 }
4808 mlir::Type intType = builder.getIntegerType(bitWidth);
4809 mlir::Value intVal =
4810 builder.create<mlir::arith::BitcastOp>(loc, intType, realVal);
4811 mlir::Value shift = builder.createIntegerConstant(loc, intType, bitWidth - 1);
4812 mlir::Value sign = builder.create<mlir::arith::ShRUIOp>(loc, intVal, shift);
4813 return builder.createConvert(loc, resultType, sign);
4814 }
4815
4816 // IEEE_SUPPORT_FLAG, IEEE_SUPPORT_HALTING
4817 fir::ExtendedValue IntrinsicLibrary::genIeeeSupportFlagOrHalting(
4818 mlir::Type resultType, llvm::ArrayRef<fir::ExtendedValue> args) {
4819 // Check if a floating point exception or halting mode FLAG is supported.
4820 // An IEEE_SUPPORT_FLAG flag is supported either for all type kinds or none.
4821 // An optional kind argument X is therefore ignored.
4822 // Standard flags are all supported.
4823 // The nonstandard DENORM extension is not supported. (At least for now.)
4824 assert(args.size() == 1 || args.size() == 2);
4825 auto [fieldRef, fieldTy] = getFieldRef(builder, loc, fir::getBase(args[0]));
4826 mlir::Value flag = builder.create<fir::LoadOp>(loc, fieldRef);
4827 mlir::Value mask = builder.createIntegerConstant( // values are powers of 2
4828 loc, fieldTy,
4829 _FORTRAN_RUNTIME_IEEE_INVALID | _FORTRAN_RUNTIME_IEEE_DIVIDE_BY_ZERO |
4830 _FORTRAN_RUNTIME_IEEE_OVERFLOW | _FORTRAN_RUNTIME_IEEE_UNDERFLOW |
4831 _FORTRAN_RUNTIME_IEEE_INEXACT);
4832 return builder.createConvert(
4833 loc, resultType,
4834 builder.create<mlir::arith::CmpIOp>(
4835 loc, mlir::arith::CmpIPredicate::ne,
4836 builder.create<mlir::arith::AndIOp>(loc, flag, mask),
4837 builder.createIntegerConstant(loc, fieldTy, 0)));
4838 }
4839
4840 // IEEE_SUPPORT_ROUNDING
4841 mlir::Value
4842 IntrinsicLibrary::genIeeeSupportRounding(mlir::Type resultType,
4843 llvm::ArrayRef<mlir::Value> args) {
4844 // Check if floating point rounding mode ROUND_VALUE is supported.
4845 // Rounding is supported either for all type kinds or none.
4846 // An optional X kind argument is therefore ignored.
4847 // Values are chosen to match the llvm.get.rounding encoding:
4848 // 0 - toward zero [supported]
4849 // 1 - to nearest, ties to even [supported] - default
4850 // 2 - toward positive infinity [supported]
4851 // 3 - toward negative infinity [supported]
4852 // 4 - to nearest, ties away from zero [not supported]
4853 assert(args.size() == 1 || args.size() == 2);
4854 auto [fieldRef, fieldTy] = getFieldRef(builder, loc, args[0]);
4855 mlir::Value mode = builder.create<fir::LoadOp>(loc, fieldRef);
4856 mlir::Value lbOk = builder.create<mlir::arith::CmpIOp>(
4857 loc, mlir::arith::CmpIPredicate::sge, mode,
4858 builder.createIntegerConstant(loc, fieldTy,
4859 _FORTRAN_RUNTIME_IEEE_TO_ZERO));
4860 mlir::Value ubOk = builder.create<mlir::arith::CmpIOp>(
4861 loc, mlir::arith::CmpIPredicate::sle, mode,
4862 builder.createIntegerConstant(loc, fieldTy, _FORTRAN_RUNTIME_IEEE_DOWN));
4863 return builder.createConvert(
4864 loc, resultType, builder.create<mlir::arith::AndIOp>(loc, lbOk, ubOk));
4865 }
4866
4867 // IEEE_UNORDERED
4868 mlir::Value
4869 IntrinsicLibrary::genIeeeUnordered(mlir::Type resultType,
4870 llvm::ArrayRef<mlir::Value> args) {
4871 // Check if REAL args X or Y or both are (signaling or quiet) NaNs.
4872 // If there is no result type return an i1 result.
4873 assert(args.size() == 2);
4874 if (args[0].getType() == args[1].getType()) {
4875 mlir::Value res = builder.create<mlir::arith::CmpFOp>(
4876 loc, mlir::arith::CmpFPredicate::UNO, args[0], args[1]);
4877 return resultType ? builder.createConvert(loc, resultType, res) : res;
4878 }
4879 assert(resultType && "expecting a (mixed arg type) unordered result type");
4880 mlir::Type i1Ty = builder.getI1Type();
4881 mlir::Value xIsNan = genIsFPClass(i1Ty, args[0], nanTest);
4882 mlir::Value yIsNan = genIsFPClass(i1Ty, args[1], nanTest);
4883 mlir::Value res = builder.create<mlir::arith::OrIOp>(loc, xIsNan, yIsNan);
4884 return builder.createConvert(loc, resultType, res);
4885 }
4886
4887 // IEEE_VALUE
4888 mlir::Value IntrinsicLibrary::genIeeeValue(mlir::Type resultType,
4889 llvm::ArrayRef<mlir::Value> args) {
4890 // Return a KIND(X) REAL number of IEEE_CLASS_TYPE CLASS.
4891 // A user call has two arguments:
4892 // - arg[0] is X (ignored, since the resultType is provided)
4893 // - arg[1] is CLASS, an IEEE_CLASS_TYPE CLASS argument containing an index
4894 // A compiler generated call has one argument:
4895 // - arg[0] is an index constant
4896 assert(args.size() == 1 || args.size() == 2);
4897 mlir::FloatType realType = mlir::dyn_cast<mlir::FloatType>(resultType);
4898 int bitWidth = realType.getWidth();
4899 mlir::Type intType = builder.getIntegerType(bitWidth);
4900 mlir::Type valueTy = bitWidth <= 64 ? intType : builder.getIntegerType(64);
4901 constexpr int tableSize = _FORTRAN_RUNTIME_IEEE_OTHER_VALUE + 1;
4902 mlir::Type tableTy = fir::SequenceType::get(tableSize, valueTy);
4903 std::string tableName = RTNAME_STRING(IeeeValueTable_) +
4904 std::to_string(realType.isBF16() ? 3 : bitWidth >> 3);
4905 if (!builder.getNamedGlobal(tableName)) {
4906 llvm::SmallVector<mlir::Attribute, tableSize> values;
4907 auto insert = [&](std::int64_t v) {
4908 values.push_back(builder.getIntegerAttr(valueTy, v));
4909 };
4910 insert(0); // placeholder
4911 switch (bitWidth) {
4912 case 16:
4913 if (realType.isF16()) {
4914 // kind=2: 1 sign bit, 5 exponent bits, 10 significand bits
4915 /* IEEE_SIGNALING_NAN */ insert(0x7d00);
4916 /* IEEE_QUIET_NAN */ insert(0x7e00);
4917 /* IEEE_NEGATIVE_INF */ insert(0xfc00);
4918 /* IEEE_NEGATIVE_NORMAL */ insert(0xbc00);
4919 /* IEEE_NEGATIVE_SUBNORMAL */ insert(0x8200);
4920 /* IEEE_NEGATIVE_ZERO */ insert(0x8000);
4921 /* IEEE_POSITIVE_ZERO */ insert(0x0000);
4922 /* IEEE_POSITIVE_SUBNORMAL */ insert(0x0200);
4923 /* IEEE_POSITIVE_NORMAL */ insert(0x3c00); // 1.0
4924 /* IEEE_POSITIVE_INF */ insert(0x7c00);
4925 break;
4926 }
4927 assert(realType.isBF16() && "unknown 16-bit real type");
4928 // kind=3: 1 sign bit, 8 exponent bits, 7 significand bits
4929 /* IEEE_SIGNALING_NAN */ insert(0x7fa0);
4930 /* IEEE_QUIET_NAN */ insert(0x7fc0);
4931 /* IEEE_NEGATIVE_INF */ insert(0xff80);
4932 /* IEEE_NEGATIVE_NORMAL */ insert(0xbf80);
4933 /* IEEE_NEGATIVE_SUBNORMAL */ insert(0x8040);
4934 /* IEEE_NEGATIVE_ZERO */ insert(0x8000);
4935 /* IEEE_POSITIVE_ZERO */ insert(0x0000);
4936 /* IEEE_POSITIVE_SUBNORMAL */ insert(0x0040);
4937 /* IEEE_POSITIVE_NORMAL */ insert(0x3f80); // 1.0
4938 /* IEEE_POSITIVE_INF */ insert(0x7f80);
4939 break;
4940 case 32:
4941 // kind=4: 1 sign bit, 8 exponent bits, 23 significand bits
4942 /* IEEE_SIGNALING_NAN */ insert(0x7fa00000);
4943 /* IEEE_QUIET_NAN */ insert(0x7fc00000);
4944 /* IEEE_NEGATIVE_INF */ insert(0xff800000);
4945 /* IEEE_NEGATIVE_NORMAL */ insert(0xbf800000);
4946 /* IEEE_NEGATIVE_SUBNORMAL */ insert(0x80400000);
4947 /* IEEE_NEGATIVE_ZERO */ insert(0x80000000);
4948 /* IEEE_POSITIVE_ZERO */ insert(0x00000000);
4949 /* IEEE_POSITIVE_SUBNORMAL */ insert(0x00400000);
4950 /* IEEE_POSITIVE_NORMAL */ insert(0x3f800000); // 1.0
4951 /* IEEE_POSITIVE_INF */ insert(0x7f800000);
4952 break;
4953 case 64:
4954 // kind=8: 1 sign bit, 11 exponent bits, 52 significand bits
4955 /* IEEE_SIGNALING_NAN */ insert(0x7ff4000000000000);
4956 /* IEEE_QUIET_NAN */ insert(0x7ff8000000000000);
4957 /* IEEE_NEGATIVE_INF */ insert(0xfff0000000000000);
4958 /* IEEE_NEGATIVE_NORMAL */ insert(0xbff0000000000000);
4959 /* IEEE_NEGATIVE_SUBNORMAL */ insert(0x8008000000000000);
4960 /* IEEE_NEGATIVE_ZERO */ insert(0x8000000000000000);
4961 /* IEEE_POSITIVE_ZERO */ insert(0x0000000000000000);
4962 /* IEEE_POSITIVE_SUBNORMAL */ insert(0x0008000000000000);
4963 /* IEEE_POSITIVE_NORMAL */ insert(0x3ff0000000000000); // 1.0
4964 /* IEEE_POSITIVE_INF */ insert(0x7ff0000000000000);
4965 break;
4966 case 80:
4967 // kind=10: 1 sign bit, 15 exponent bits, 1+63 significand bits
4968 // 64 high order bits; 16 low order bits are 0.
4969 /* IEEE_SIGNALING_NAN */ insert(0x7fffa00000000000);
4970 /* IEEE_QUIET_NAN */ insert(0x7fffc00000000000);
4971 /* IEEE_NEGATIVE_INF */ insert(0xffff800000000000);
4972 /* IEEE_NEGATIVE_NORMAL */ insert(0xbfff800000000000);
4973 /* IEEE_NEGATIVE_SUBNORMAL */ insert(0x8000400000000000);
4974 /* IEEE_NEGATIVE_ZERO */ insert(0x8000000000000000);
4975 /* IEEE_POSITIVE_ZERO */ insert(0x0000000000000000);
4976 /* IEEE_POSITIVE_SUBNORMAL */ insert(0x0000400000000000);
4977 /* IEEE_POSITIVE_NORMAL */ insert(0x3fff800000000000); // 1.0
4978 /* IEEE_POSITIVE_INF */ insert(0x7fff800000000000);
4979 break;
4980 case 128:
4981 // kind=16: 1 sign bit, 15 exponent bits, 112 significand bits
4982 // 64 high order bits; 64 low order bits are 0.
4983 /* IEEE_SIGNALING_NAN */ insert(0x7fff400000000000);
4984 /* IEEE_QUIET_NAN */ insert(0x7fff800000000000);
4985 /* IEEE_NEGATIVE_INF */ insert(0xffff000000000000);
4986 /* IEEE_NEGATIVE_NORMAL */ insert(0xbfff000000000000);
4987 /* IEEE_NEGATIVE_SUBNORMAL */ insert(0x8000200000000000);
4988 /* IEEE_NEGATIVE_ZERO */ insert(0x8000000000000000);
4989 /* IEEE_POSITIVE_ZERO */ insert(0x0000000000000000);
4990 /* IEEE_POSITIVE_SUBNORMAL */ insert(0x0000200000000000);
4991 /* IEEE_POSITIVE_NORMAL */ insert(0x3fff000000000000); // 1.0
4992 /* IEEE_POSITIVE_INF */ insert(0x7fff000000000000);
4993 break;
4994 default:
4995 llvm_unreachable("unknown real type");
4996 }
4997 insert(0); // IEEE_OTHER_VALUE
4998 assert(values.size() == tableSize && "ieee value mismatch");
4999 builder.createGlobalConstant(
5000 loc, tableTy, tableName, builder.createLinkOnceLinkage(),
5001 mlir::DenseElementsAttr::get(
5002 mlir::RankedTensorType::get(tableSize, valueTy), values));
5003 }
5004
5005 mlir::Value which;
5006 if (args.size() == 2) { // user call
5007 auto [index, ignore] = getFieldRef(builder, loc, args[1]);
5008 which = builder.create<fir::LoadOp>(loc, index);
5009 } else { // compiler generated call
5010 which = args[0];
5011 }
5012 mlir::Value bits = builder.create<fir::LoadOp>(
5013 loc,
5014 builder.create<fir::CoordinateOp>(
5015 loc, builder.getRefType(valueTy),
5016 builder.create<fir::AddrOfOp>(loc, builder.getRefType(tableTy),
5017 builder.getSymbolRefAttr(tableName)),
5018 which));
5019 if (bitWidth > 64)
5020 bits = builder.create<mlir::arith::ShLIOp>(
5021 loc, builder.createConvert(loc, intType, bits),
5022 builder.createIntegerConstant(loc, intType, bitWidth - 64));
5023 return builder.create<mlir::arith::BitcastOp>(loc, realType, bits);
5024 }
5025
5026 // IEOR
5027 mlir::Value IntrinsicLibrary::genIeor(mlir::Type resultType,
5028 llvm::ArrayRef<mlir::Value> args) {
5029 assert(args.size() == 2);
5030 return builder.create<mlir::arith::XOrIOp>(loc, args[0], args[1]);
5031 }
5032
5033 // INDEX
5034 fir::ExtendedValue
5035 IntrinsicLibrary::genIndex(mlir::Type resultType,
5036 llvm::ArrayRef<fir::ExtendedValue> args) {
5037 assert(args.size() >= 2 && args.size() <= 4);
5038
5039 mlir::Value stringBase = fir::getBase(args[0]);
5040 fir::KindTy kind =
5041 fir::factory::CharacterExprHelper{builder, loc}.getCharacterKind(
5042 stringBase.getType());
5043 mlir::Value stringLen = fir::getLen(args[0]);
5044 mlir::Value substringBase = fir::getBase(args[1]);
5045 mlir::Value substringLen = fir::getLen(args[1]);
5046 mlir::Value back =
5047 isStaticallyAbsent(args, 2)
5048 ? builder.createIntegerConstant(loc, builder.getI1Type(), 0)
5049 : fir::getBase(args[2]);
5050 if (isStaticallyAbsent(args, 3))
5051 return builder.createConvert(
5052 loc, resultType,
5053 fir::runtime::genIndex(builder, loc, kind, stringBase, stringLen,
5054 substringBase, substringLen, back));
5055
5056 // Call the descriptor-based Index implementation
5057 mlir::Value string = builder.createBox(loc, args[0]);
5058 mlir::Value substring = builder.createBox(loc, args[1]);
5059 auto makeRefThenEmbox = [&](mlir::Value b) {
5060 fir::LogicalType logTy = fir::LogicalType::get(
5061 builder.getContext(), builder.getKindMap().defaultLogicalKind());
5062 mlir::Value temp = builder.createTemporary(loc, logTy);
5063 mlir::Value castb = builder.createConvert(loc, logTy, b);
5064 builder.create<fir::StoreOp>(loc, castb, temp);
5065 return builder.createBox(loc, temp);
5066 };
5067 mlir::Value backOpt = isStaticallyAbsent(args, 2)
5068 ? builder.create<fir::AbsentOp>(
5069 loc, fir::BoxType::get(builder.getI1Type()))
5070 : makeRefThenEmbox(fir::getBase(args[2]));
5071 mlir::Value kindVal = isStaticallyAbsent(args, 3)
5072 ? builder.createIntegerConstant(
5073 loc, builder.getIndexType(),
5074 builder.getKindMap().defaultIntegerKind())
5075 : fir::getBase(args[3]);
5076 // Create mutable fir.box to be passed to the runtime for the result.
5077 fir::MutableBoxValue mutBox =
5078 fir::factory::createTempMutableBox(builder, loc, resultType);
5079 mlir::Value resBox = fir::factory::getMutableIRBox(builder, loc, mutBox);
5080 // Call runtime. The runtime is allocating the result.
5081 fir::runtime::genIndexDescriptor(builder, loc, resBox, string, substring,
5082 backOpt, kindVal);
5083 // Read back the result from the mutable box.
5084 return readAndAddCleanUp(mutBox, resultType, "INDEX");
5085 }
5086
5087 // IOR
5088 mlir::Value IntrinsicLibrary::genIor(mlir::Type resultType,
5089 llvm::ArrayRef<mlir::Value> args) {
5090 assert(args.size() == 2);
5091 return builder.create<mlir::arith::OrIOp>(loc, args[0], args[1]);
5092 }
5093
5094 // IPARITY
5095 fir::ExtendedValue
5096 IntrinsicLibrary::genIparity(mlir::Type resultType,
5097 llvm::ArrayRef<fir::ExtendedValue> args) {
5098 return genReduction(fir::runtime::genIParity, fir::runtime::genIParityDim,
5099 "IPARITY", resultType, args);
5100 }
5101
5102 // IS_CONTIGUOUS
5103 fir::ExtendedValue
5104 IntrinsicLibrary::genIsContiguous(mlir::Type resultType,
5105 llvm::ArrayRef<fir::ExtendedValue> args) {
5106 assert(args.size() == 1);
5107 return builder.createConvert(
5108 loc, resultType,
5109 fir::runtime::genIsContiguous(builder, loc, fir::getBase(args[0])));
5110 }
5111
5112 // IS_IOSTAT_END, IS_IOSTAT_EOR
5113 template <Fortran::runtime::io::Iostat value>
5114 mlir::Value
5115 IntrinsicLibrary::genIsIostatValue(mlir::Type resultType,
5116 llvm::ArrayRef<mlir::Value> args) {
5117 assert(args.size() == 1);
5118 return builder.create<mlir::arith::CmpIOp>(
5119 loc, mlir::arith::CmpIPredicate::eq, args[0],
5120 builder.createIntegerConstant(loc, args[0].getType(), value));
5121 }
5122
5123 // ISHFT
5124 mlir::Value IntrinsicLibrary::genIshft(mlir::Type resultType,
5125 llvm::ArrayRef<mlir::Value> args) {
5126 // A conformant ISHFT(I,SHIFT) call satisfies:
5127 // abs(SHIFT) <= BIT_SIZE(I)
5128 // Return: abs(SHIFT) >= BIT_SIZE(I)
5129 // ? 0
5130 // : SHIFT < 0
5131 // ? I >> abs(SHIFT)
5132 // : I << abs(SHIFT)
5133 assert(args.size() == 2);
5134 mlir::Value bitSize = builder.createIntegerConstant(
5135 loc, resultType, mlir::cast<mlir::IntegerType>(resultType).getWidth());
5136 mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
5137 mlir::Value shift = builder.createConvert(loc, resultType, args[1]);
5138 mlir::Value absShift = genAbs(resultType, {shift});
5139 auto left = builder.create<mlir::arith::ShLIOp>(loc, args[0], absShift);
5140 auto right = builder.create<mlir::arith::ShRUIOp>(loc, args[0], absShift);
5141 auto shiftIsLarge = builder.create<mlir::arith::CmpIOp>(
5142 loc, mlir::arith::CmpIPredicate::sge, absShift, bitSize);
5143 auto shiftIsNegative = builder.create<mlir::arith::CmpIOp>(
5144 loc, mlir::arith::CmpIPredicate::slt, shift, zero);
5145 auto sel =
5146 builder.create<mlir::arith::SelectOp>(loc, shiftIsNegative, right, left);
5147 return builder.create<mlir::arith::SelectOp>(loc, shiftIsLarge, zero, sel);
5148 }
5149
5150 // ISHFTC
5151 mlir::Value IntrinsicLibrary::genIshftc(mlir::Type resultType,
5152 llvm::ArrayRef<mlir::Value> args) {
5153 // A conformant ISHFTC(I,SHIFT,SIZE) call satisfies:
5154 // SIZE > 0
5155 // SIZE <= BIT_SIZE(I)
5156 // abs(SHIFT) <= SIZE
5157 // if SHIFT > 0
5158 // leftSize = abs(SHIFT)
5159 // rightSize = SIZE - abs(SHIFT)
5160 // else [if SHIFT < 0]
5161 // leftSize = SIZE - abs(SHIFT)
5162 // rightSize = abs(SHIFT)
5163 // unchanged = SIZE == BIT_SIZE(I) ? 0 : (I >> SIZE) << SIZE
5164 // leftMaskShift = BIT_SIZE(I) - leftSize
5165 // rightMaskShift = BIT_SIZE(I) - rightSize
5166 // left = (I >> rightSize) & (-1 >> leftMaskShift)
5167 // right = (I & (-1 >> rightMaskShift)) << leftSize
5168 // Return: SHIFT == 0 || SIZE == abs(SHIFT) ? I : (unchanged | left | right)
5169 assert(args.size() == 3);
5170 mlir::Value bitSize = builder.createIntegerConstant(
5171 loc, resultType, mlir::cast<mlir::IntegerType>(resultType).getWidth());
5172 mlir::Value I = args[0];
5173 mlir::Value shift = builder.createConvert(loc, resultType, args[1]);
5174 mlir::Value size =
5175 args[2] ? builder.createConvert(loc, resultType, args[2]) : bitSize;
5176 mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
5177 mlir::Value ones = builder.createAllOnesInteger(loc, resultType);
5178 mlir::Value absShift = genAbs(resultType, {shift});
5179 auto elseSize = builder.create<mlir::arith::SubIOp>(loc, size, absShift);
5180 auto shiftIsZero = builder.create<mlir::arith::CmpIOp>(
5181 loc, mlir::arith::CmpIPredicate::eq, shift, zero);
5182 auto shiftEqualsSize = builder.create<mlir::arith::CmpIOp>(
5183 loc, mlir::arith::CmpIPredicate::eq, absShift, size);
5184 auto shiftIsNop =
5185 builder.create<mlir::arith::OrIOp>(loc, shiftIsZero, shiftEqualsSize);
5186 auto shiftIsPositive = builder.create<mlir::arith::CmpIOp>(
5187 loc, mlir::arith::CmpIPredicate::sgt, shift, zero);
5188 auto leftSize = builder.create<mlir::arith::SelectOp>(loc, shiftIsPositive,
5189 absShift, elseSize);
5190 auto rightSize = builder.create<mlir::arith::SelectOp>(loc, shiftIsPositive,
5191 elseSize, absShift);
5192 auto hasUnchanged = builder.create<mlir::arith::CmpIOp>(
5193 loc, mlir::arith::CmpIPredicate::ne, size, bitSize);
5194 auto unchangedTmp1 = builder.create<mlir::arith::ShRUIOp>(loc, I, size);
5195 auto unchangedTmp2 =
5196 builder.create<mlir::arith::ShLIOp>(loc, unchangedTmp1, size);
5197 auto unchanged = builder.create<mlir::arith::SelectOp>(loc, hasUnchanged,
5198 unchangedTmp2, zero);
5199 auto leftMaskShift =
5200 builder.create<mlir::arith::SubIOp>(loc, bitSize, leftSize);
5201 auto leftMask =
5202 builder.create<mlir::arith::ShRUIOp>(loc, ones, leftMaskShift);
5203 auto leftTmp = builder.create<mlir::arith::ShRUIOp>(loc, I, rightSize);
5204 auto left = builder.create<mlir::arith::AndIOp>(loc, leftTmp, leftMask);
5205 auto rightMaskShift =
5206 builder.create<mlir::arith::SubIOp>(loc, bitSize, rightSize);
5207 auto rightMask =
5208 builder.create<mlir::arith::ShRUIOp>(loc, ones, rightMaskShift);
5209 auto rightTmp = builder.create<mlir::arith::AndIOp>(loc, I, rightMask);
5210 auto right = builder.create<mlir::arith::ShLIOp>(loc, rightTmp, leftSize);
5211 auto resTmp = builder.create<mlir::arith::OrIOp>(loc, unchanged, left);
5212 auto res = builder.create<mlir::arith::OrIOp>(loc, resTmp, right);
5213 return builder.create<mlir::arith::SelectOp>(loc, shiftIsNop, I, res);
5214 }
5215
5216 // LEADZ
5217 mlir::Value IntrinsicLibrary::genLeadz(mlir::Type resultType,
5218 llvm::ArrayRef<mlir::Value> args) {
5219 assert(args.size() == 1);
5220
5221 mlir::Value result =
5222 builder.create<mlir::math::CountLeadingZerosOp>(loc, args);
5223
5224 return builder.createConvert(loc, resultType, result);
5225 }
5226
5227 // LEN
5228 // Note that this is only used for an unrestricted intrinsic LEN call.
5229 // Other uses of LEN are rewritten as descriptor inquiries by the front-end.
5230 fir::ExtendedValue
5231 IntrinsicLibrary::genLen(mlir::Type resultType,
5232 llvm::ArrayRef<fir::ExtendedValue> args) {
5233 // Optional KIND argument reflected in result type and otherwise ignored.
5234 assert(args.size() == 1 || args.size() == 2);
5235 mlir::Value len = fir::factory::readCharLen(builder, loc, args[0]);
5236 return builder.createConvert(loc, resultType, len);
5237 }
5238
5239 // LEN_TRIM
5240 fir::ExtendedValue
5241 IntrinsicLibrary::genLenTrim(mlir::Type resultType,
5242 llvm::ArrayRef<fir::ExtendedValue> args) {
5243 // Optional KIND argument reflected in result type and otherwise ignored.
5244 assert(args.size() == 1 || args.size() == 2);
5245 const fir::CharBoxValue *charBox = args[0].getCharBox();
5246 if (!charBox)
5247 TODO(loc, "intrinsic: len_trim for character array");
5248 auto len =
5249 fir::factory::CharacterExprHelper(builder, loc).createLenTrim(*charBox);
5250 return builder.createConvert(loc, resultType, len);
5251 }
5252
5253 // LGE, LGT, LLE, LLT
5254 template <mlir::arith::CmpIPredicate pred>
5255 fir::ExtendedValue
5256 IntrinsicLibrary::genCharacterCompare(mlir::Type resultType,
5257 llvm::ArrayRef<fir::ExtendedValue> args) {
5258 assert(args.size() == 2);
5259 return fir::runtime::genCharCompare(
5260 builder, loc, pred, fir::getBase(args[0]), fir::getLen(args[0]),
5261 fir::getBase(args[1]), fir::getLen(args[1]));
5262 }
5263
5264 static bool isOptional(mlir::Value value) {
5265 auto varIface = mlir::dyn_cast_or_null<fir::FortranVariableOpInterface>(
5266 value.getDefiningOp());
5267 return varIface && varIface.isOptional();
5268 }
5269
5270 // LOC
5271 fir::ExtendedValue
5272 IntrinsicLibrary::genLoc(mlir::Type resultType,
5273 llvm::ArrayRef<fir::ExtendedValue> args) {
5274 assert(args.size() == 1);
5275 mlir::Value box = fir::getBase(args[0]);
5276 assert(fir::isa_box_type(box.getType()) &&
5277 "argument must have been lowered to box type");
5278 bool isFunc = mlir::isa<fir::BoxProcType>(box.getType());
5279 if (!isOptional(box)) {
5280 mlir::Value argAddr = getAddrFromBox(builder, loc, args[0], isFunc);
5281 return builder.createConvert(loc, resultType, argAddr);
5282 }
5283 // Optional assumed shape case. Although this is not specified in this GNU
5284 // intrinsic extension, LOC accepts absent optional and returns zero in that
5285 // case.
5286 // Note that the other OPTIONAL cases do not fall here since `box` was
5287 // created when preparing the argument cases, but the box can be safely be
5288 // used for all those cases and the address will be null if absent.
5289 mlir::Value isPresent =
5290 builder.create<fir::IsPresentOp>(loc, builder.getI1Type(), box);
5291 return builder
5292 .genIfOp(loc, {resultType}, isPresent,
5293 /*withElseRegion=*/true)
5294 .genThen([&]() {
5295 mlir::Value argAddr = getAddrFromBox(builder, loc, args[0], isFunc);
5296 mlir::Value cast = builder.createConvert(loc, resultType, argAddr);
5297 builder.create<fir::ResultOp>(loc, cast);
5298 })
5299 .genElse([&]() {
5300 mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
5301 builder.create<fir::ResultOp>(loc, zero);
5302 })
5303 .getResults()[0];
5304 }
5305
5306 // MASKL, MASKR
5307 template <typename Shift>
5308 mlir::Value IntrinsicLibrary::genMask(mlir::Type resultType,
5309 llvm::ArrayRef<mlir::Value> args) {
5310 assert(args.size() == 2);
5311
5312 mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
5313 mlir::Value ones = builder.createAllOnesInteger(loc, resultType);
5314 mlir::Value bitSize = builder.createIntegerConstant(
5315 loc, resultType, resultType.getIntOrFloatBitWidth());
5316 mlir::Value bitsToSet = builder.createConvert(loc, resultType, args[0]);
5317
5318 // The standard does not specify what to return if the number of bits to be
5319 // set, I < 0 or I >= BIT_SIZE(KIND). The shift instruction used below will
5320 // produce a poison value which may return a possibly platform-specific and/or
5321 // non-deterministic result. Other compilers don't produce a consistent result
5322 // in this case either, so we choose the most efficient implementation.
5323 mlir::Value shift =
5324 builder.create<mlir::arith::SubIOp>(loc, bitSize, bitsToSet);
5325 mlir::Value shifted = builder.create<Shift>(loc, ones, shift);
5326 mlir::Value isZero = builder.create<mlir::arith::CmpIOp>(
5327 loc, mlir::arith::CmpIPredicate::eq, bitsToSet, zero);
5328
5329 return builder.create<mlir::arith::SelectOp>(loc, isZero, zero, shifted);
5330 }
5331
5332 // MATMUL
5333 fir::ExtendedValue
5334 IntrinsicLibrary::genMatmul(mlir::Type resultType,
5335 llvm::ArrayRef<fir::ExtendedValue> args) {
5336 assert(args.size() == 2);
5337
5338 // Handle required matmul arguments
5339 fir::BoxValue matrixTmpA = builder.createBox(loc, args[0]);
5340 mlir::Value matrixA = fir::getBase(matrixTmpA);
5341 fir::BoxValue matrixTmpB = builder.createBox(loc, args[1]);
5342 mlir::Value matrixB = fir::getBase(matrixTmpB);
5343 unsigned resultRank =
5344 (matrixTmpA.rank() == 1 || matrixTmpB.rank() == 1) ? 1 : 2;
5345
5346 // Create mutable fir.box to be passed to the runtime for the result.
5347 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, resultRank);
5348 fir::MutableBoxValue resultMutableBox =
5349 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
5350 mlir::Value resultIrBox =
5351 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
5352 // Call runtime. The runtime is allocating the result.
5353 fir::runtime::genMatmul(builder, loc, resultIrBox, matrixA, matrixB);
5354 // Read result from mutable fir.box and add it to the list of temps to be
5355 // finalized by the StatementContext.
5356 return readAndAddCleanUp(resultMutableBox, resultType, "MATMUL");
5357 }
5358
5359 // MATMUL_TRANSPOSE
5360 fir::ExtendedValue
5361 IntrinsicLibrary::genMatmulTranspose(mlir::Type resultType,
5362 llvm::ArrayRef<fir::ExtendedValue> args) {
5363 assert(args.size() == 2);
5364
5365 // Handle required matmul_transpose arguments
5366 fir::BoxValue matrixTmpA = builder.createBox(loc, args[0]);
5367 mlir::Value matrixA = fir::getBase(matrixTmpA);
5368 fir::BoxValue matrixTmpB = builder.createBox(loc, args[1]);
5369 mlir::Value matrixB = fir::getBase(matrixTmpB);
5370 unsigned resultRank =
5371 (matrixTmpA.rank() == 1 || matrixTmpB.rank() == 1) ? 1 : 2;
5372
5373 // Create mutable fir.box to be passed to the runtime for the result.
5374 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, resultRank);
5375 fir::MutableBoxValue resultMutableBox =
5376 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
5377 mlir::Value resultIrBox =
5378 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
5379 // Call runtime. The runtime is allocating the result.
5380 fir::runtime::genMatmulTranspose(builder, loc, resultIrBox, matrixA, matrixB);
5381 // Read result from mutable fir.box and add it to the list of temps to be
5382 // finalized by the StatementContext.
5383 return readAndAddCleanUp(resultMutableBox, resultType, "MATMUL_TRANSPOSE");
5384 }
5385
5386 // MERGE
5387 fir::ExtendedValue
5388 IntrinsicLibrary::genMerge(mlir::Type,
5389 llvm::ArrayRef<fir::ExtendedValue> args) {
5390 assert(args.size() == 3);
5391 mlir::Value tsource = fir::getBase(args[0]);
5392 mlir::Value fsource = fir::getBase(args[1]);
5393 mlir::Value rawMask = fir::getBase(args[2]);
5394 mlir::Type type0 = fir::unwrapRefType(tsource.getType());
5395 bool isCharRslt = fir::isa_char(type0); // result is same as first argument
5396 mlir::Value mask = builder.createConvert(loc, builder.getI1Type(), rawMask);
5397
5398 // The result is polymorphic if and only if both TSOURCE and FSOURCE are
5399 // polymorphic. TSOURCE and FSOURCE are required to have the same type
5400 // (for both declared and dynamic types) so a simple convert op can be
5401 // used.
5402 mlir::Value tsourceCast = tsource;
5403 mlir::Value fsourceCast = fsource;
5404 auto convertToStaticType = [&](mlir::Value polymorphic,
5405 mlir::Value other) -> mlir::Value {
5406 mlir::Type otherType = other.getType();
5407 if (mlir::isa<fir::BaseBoxType>(otherType))
5408 return builder.create<fir::ReboxOp>(loc, otherType, polymorphic,
5409 /*shape*/ mlir::Value{},
5410 /*slice=*/mlir::Value{});
5411 return builder.create<fir::BoxAddrOp>(loc, otherType, polymorphic);
5412 };
5413 if (fir::isPolymorphicType(tsource.getType()) &&
5414 !fir::isPolymorphicType(fsource.getType())) {
5415 tsourceCast = convertToStaticType(tsource, fsource);
5416 } else if (!fir::isPolymorphicType(tsource.getType()) &&
5417 fir::isPolymorphicType(fsource.getType())) {
5418 fsourceCast = convertToStaticType(fsource, tsource);
5419 } else {
5420 // FSOURCE and TSOURCE are not polymorphic.
5421 // FSOURCE has the same type as TSOURCE, but they may not have the same MLIR
5422 // types (one can have dynamic length while the other has constant lengths,
5423 // or one may be a fir.logical<> while the other is an i1). Insert a cast to
5424 // fulfill mlir::SelectOp constraint that the MLIR types must be the same.
5425 fsourceCast = builder.createConvert(loc, tsource.getType(), fsource);
5426 }
5427 auto rslt = builder.create<mlir::arith::SelectOp>(loc, mask, tsourceCast,
5428 fsourceCast);
5429 if (isCharRslt) {
5430 // Need a CharBoxValue for character results
5431 const fir::CharBoxValue *charBox = args[0].getCharBox();
5432 fir::CharBoxValue charRslt(rslt, charBox->getLen());
5433 return charRslt;
5434 }
5435 return rslt;
5436 }
5437
5438 // MERGE_BITS
5439 mlir::Value IntrinsicLibrary::genMergeBits(mlir::Type resultType,
5440 llvm::ArrayRef<mlir::Value> args) {
5441 assert(args.size() == 3);
5442
5443 mlir::Value i = builder.createConvert(loc, resultType, args[0]);
5444 mlir::Value j = builder.createConvert(loc, resultType, args[1]);
5445 mlir::Value mask = builder.createConvert(loc, resultType, args[2]);
5446 mlir::Value ones = builder.createAllOnesInteger(loc, resultType);
5447
5448 // MERGE_BITS(I, J, MASK) = IOR(IAND(I, MASK), IAND(J, NOT(MASK)))
5449 mlir::Value notMask = builder.create<mlir::arith::XOrIOp>(loc, mask, ones);
5450 mlir::Value lft = builder.create<mlir::arith::AndIOp>(loc, i, mask);
5451 mlir::Value rgt = builder.create<mlir::arith::AndIOp>(loc, j, notMask);
5452
5453 return builder.create<mlir::arith::OrIOp>(loc, lft, rgt);
5454 }
5455
5456 // MOD
5457 mlir::Value IntrinsicLibrary::genMod(mlir::Type resultType,
5458 llvm::ArrayRef<mlir::Value> args) {
5459 assert(args.size() == 2);
5460 if (mlir::isa<mlir::IntegerType>(resultType))
5461 return builder.create<mlir::arith::RemSIOp>(loc, args[0], args[1]);
5462
5463 // Use runtime.
5464 return builder.createConvert(
5465 loc, resultType, fir::runtime::genMod(builder, loc, args[0], args[1]));
5466 }
5467
5468 // MODULO
5469 mlir::Value IntrinsicLibrary::genModulo(mlir::Type resultType,
5470 llvm::ArrayRef<mlir::Value> args) {
5471 // TODO: we'd better generate a runtime call here, when runtime error
5472 // checking is needed (to detect 0 divisor) or when precise math is requested.
5473 assert(args.size() == 2);
5474 // No floored modulo op in LLVM/MLIR yet. TODO: add one to MLIR.
5475 // In the meantime, use a simple inlined implementation based on truncated
5476 // modulo (MOD(A, P) implemented by RemIOp, RemFOp). This avoids making manual
5477 // division and multiplication from MODULO formula.
5478 // - If A/P > 0 or MOD(A,P)=0, then INT(A/P) = FLOOR(A/P), and MODULO = MOD.
5479 // - Otherwise, when A/P < 0 and MOD(A,P) !=0, then MODULO(A, P) =
5480 // A-FLOOR(A/P)*P = A-(INT(A/P)-1)*P = A-INT(A/P)*P+P = MOD(A,P)+P
5481 // Note that A/P < 0 if and only if A and P signs are different.
5482 if (mlir::isa<mlir::IntegerType>(resultType)) {
5483 auto remainder =
5484 builder.create<mlir::arith::RemSIOp>(loc, args[0], args[1]);
5485 auto argXor = builder.create<mlir::arith::XOrIOp>(loc, args[0], args[1]);
5486 mlir::Value zero = builder.createIntegerConstant(loc, argXor.getType(), 0);
5487 auto argSignDifferent = builder.create<mlir::arith::CmpIOp>(
5488 loc, mlir::arith::CmpIPredicate::slt, argXor, zero);
5489 auto remainderIsNotZero = builder.create<mlir::arith::CmpIOp>(
5490 loc, mlir::arith::CmpIPredicate::ne, remainder, zero);
5491 auto mustAddP = builder.create<mlir::arith::AndIOp>(loc, remainderIsNotZero,
5492 argSignDifferent);
5493 auto remPlusP =
5494 builder.create<mlir::arith::AddIOp>(loc, remainder, args[1]);
5495 return builder.create<mlir::arith::SelectOp>(loc, mustAddP, remPlusP,
5496 remainder);
5497 }
5498
5499 auto fastMathFlags = builder.getFastMathFlags();
5500 // F128 arith::RemFOp may be lowered to a runtime call that may be unsupported
5501 // on the target, so generate a call to Fortran Runtime's ModuloReal16.
5502 if (resultType == mlir::FloatType::getF128(builder.getContext()) ||
5503 (fastMathFlags & mlir::arith::FastMathFlags::ninf) ==
5504 mlir::arith::FastMathFlags::none)
5505 return builder.createConvert(
5506 loc, resultType,
5507 fir::runtime::genModulo(builder, loc, args[0], args[1]));
5508
5509 auto remainder = builder.create<mlir::arith::RemFOp>(loc, args[0], args[1]);
5510 mlir::Value zero = builder.createRealZeroConstant(loc, remainder.getType());
5511 auto remainderIsNotZero = builder.create<mlir::arith::CmpFOp>(
5512 loc, mlir::arith::CmpFPredicate::UNE, remainder, zero);
5513 auto aLessThanZero = builder.create<mlir::arith::CmpFOp>(
5514 loc, mlir::arith::CmpFPredicate::OLT, args[0], zero);
5515 auto pLessThanZero = builder.create<mlir::arith::CmpFOp>(
5516 loc, mlir::arith::CmpFPredicate::OLT, args[1], zero);
5517 auto argSignDifferent =
5518 builder.create<mlir::arith::XOrIOp>(loc, aLessThanZero, pLessThanZero);
5519 auto mustAddP = builder.create<mlir::arith::AndIOp>(loc, remainderIsNotZero,
5520 argSignDifferent);
5521 auto remPlusP = builder.create<mlir::arith::AddFOp>(loc, remainder, args[1]);
5522 return builder.create<mlir::arith::SelectOp>(loc, mustAddP, remPlusP,
5523 remainder);
5524 }
5525
5526 void IntrinsicLibrary::genMoveAlloc(llvm::ArrayRef<fir::ExtendedValue> args) {
5527 assert(args.size() == 4);
5528
5529 const fir::ExtendedValue &from = args[0];
5530 const fir::ExtendedValue &to = args[1];
5531 const fir::ExtendedValue &status = args[2];
5532 const fir::ExtendedValue &errMsg = args[3];
5533
5534 mlir::Type boxNoneTy = fir::BoxType::get(builder.getNoneType());
5535 mlir::Value errBox =
5536 isStaticallyPresent(errMsg)
5537 ? fir::getBase(errMsg)
5538 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
5539
5540 const fir::MutableBoxValue *fromBox = from.getBoxOf<fir::MutableBoxValue>();
5541 const fir::MutableBoxValue *toBox = to.getBoxOf<fir::MutableBoxValue>();
5542
5543 assert(fromBox && toBox && "move_alloc parameters must be mutable arrays");
5544
5545 mlir::Value fromAddr = fir::factory::getMutableIRBox(builder, loc, *fromBox);
5546 mlir::Value toAddr = fir::factory::getMutableIRBox(builder, loc, *toBox);
5547
5548 mlir::Value hasStat = builder.createBool(loc, isStaticallyPresent(status));
5549
5550 mlir::Value stat = fir::runtime::genMoveAlloc(builder, loc, toAddr, fromAddr,
5551 hasStat, errBox);
5552
5553 fir::factory::syncMutableBoxFromIRBox(builder, loc, *fromBox);
5554 fir::factory::syncMutableBoxFromIRBox(builder, loc, *toBox);
5555
5556 if (isStaticallyPresent(status)) {
5557 mlir::Value statAddr = fir::getBase(status);
5558 mlir::Value statIsPresentAtRuntime =
5559 builder.genIsNotNullAddr(loc, statAddr);
5560 builder.genIfThen(loc, statIsPresentAtRuntime)
5561 .genThen([&]() { builder.createStoreWithConvert(loc, stat, statAddr); })
5562 .end();
5563 }
5564 }
5565
5566 // MVBITS
5567 void IntrinsicLibrary::genMvbits(llvm::ArrayRef<fir::ExtendedValue> args) {
5568 // A conformant MVBITS(FROM,FROMPOS,LEN,TO,TOPOS) call satisfies:
5569 // FROMPOS >= 0
5570 // LEN >= 0
5571 // TOPOS >= 0
5572 // FROMPOS + LEN <= BIT_SIZE(FROM)
5573 // TOPOS + LEN <= BIT_SIZE(TO)
5574 // MASK = -1 >> (BIT_SIZE(FROM) - LEN)
5575 // TO = LEN == 0 ? TO : ((!(MASK << TOPOS)) & TO) |
5576 // (((FROM >> FROMPOS) & MASK) << TOPOS)
5577 assert(args.size() == 5);
5578 auto unbox = [&](fir::ExtendedValue exv) {
5579 const mlir::Value *arg = exv.getUnboxed();
5580 assert(arg && "nonscalar mvbits argument");
5581 return *arg;
5582 };
5583 mlir::Value from = unbox(args[0]);
5584 mlir::Type resultType = from.getType();
5585 mlir::Value frompos = builder.createConvert(loc, resultType, unbox(args[1]));
5586 mlir::Value len = builder.createConvert(loc, resultType, unbox(args[2]));
5587 mlir::Value toAddr = unbox(args[3]);
5588 assert(fir::dyn_cast_ptrEleTy(toAddr.getType()) == resultType &&
5589 "mismatched mvbits types");
5590 auto to = builder.create<fir::LoadOp>(loc, resultType, toAddr);
5591 mlir::Value topos = builder.createConvert(loc, resultType, unbox(args[4]));
5592 mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
5593 mlir::Value ones = builder.createAllOnesInteger(loc, resultType);
5594 mlir::Value bitSize = builder.createIntegerConstant(
5595 loc, resultType, mlir::cast<mlir::IntegerType>(resultType).getWidth());
5596 auto shiftCount = builder.create<mlir::arith::SubIOp>(loc, bitSize, len);
5597 auto mask = builder.create<mlir::arith::ShRUIOp>(loc, ones, shiftCount);
5598 auto unchangedTmp1 = builder.create<mlir::arith::ShLIOp>(loc, mask, topos);
5599 auto unchangedTmp2 =
5600 builder.create<mlir::arith::XOrIOp>(loc, unchangedTmp1, ones);
5601 auto unchanged = builder.create<mlir::arith::AndIOp>(loc, unchangedTmp2, to);
5602 auto frombitsTmp1 = builder.create<mlir::arith::ShRUIOp>(loc, from, frompos);
5603 auto frombitsTmp2 =
5604 builder.create<mlir::arith::AndIOp>(loc, frombitsTmp1, mask);
5605 auto frombits = builder.create<mlir::arith::ShLIOp>(loc, frombitsTmp2, topos);
5606 auto resTmp = builder.create<mlir::arith::OrIOp>(loc, unchanged, frombits);
5607 auto lenIsZero = builder.create<mlir::arith::CmpIOp>(
5608 loc, mlir::arith::CmpIPredicate::eq, len, zero);
5609 auto res = builder.create<mlir::arith::SelectOp>(loc, lenIsZero, to, resTmp);
5610 builder.create<fir::StoreOp>(loc, res, toAddr);
5611 }
5612
5613 // NEAREST
5614 mlir::Value IntrinsicLibrary::genNearest(mlir::Type resultType,
5615 llvm::ArrayRef<mlir::Value> args) {
5616 assert(args.size() == 2);
5617
5618 mlir::Value realX = fir::getBase(args[0]);
5619 mlir::Value realS = fir::getBase(args[1]);
5620
5621 return builder.createConvert(
5622 loc, resultType, fir::runtime::genNearest(builder, loc, realX, realS));
5623 }
5624
5625 // NINT
5626 mlir::Value IntrinsicLibrary::genNint(mlir::Type resultType,
5627 llvm::ArrayRef<mlir::Value> args) {
5628 assert(args.size() >= 1);
5629 // Skip optional kind argument to search the runtime; it is already reflected
5630 // in result type.
5631 return genRuntimeCall("nint", resultType, {args[0]});
5632 }
5633
5634 // NORM2
5635 fir::ExtendedValue
5636 IntrinsicLibrary::genNorm2(mlir::Type resultType,
5637 llvm::ArrayRef<fir::ExtendedValue> args) {
5638 assert(args.size() == 2);
5639
5640 // Handle required array argument
5641 mlir::Value array = builder.createBox(loc, args[0]);
5642 unsigned rank = fir::BoxValue(array).rank();
5643 assert(rank >= 1);
5644
5645 // Check if the dim argument is present
5646 bool absentDim = isStaticallyAbsent(args[1]);
5647
5648 // If dim argument is absent or the array is rank 1, then the result is
5649 // a scalar (since the the result is rank-1 or 0). Otherwise, the result is
5650 // an array.
5651 if (absentDim || rank == 1) {
5652 return fir::runtime::genNorm2(builder, loc, array);
5653 } else {
5654 // Create mutable fir.box to be passed to the runtime for the result.
5655 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, rank - 1);
5656 fir::MutableBoxValue resultMutableBox =
5657 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
5658 mlir::Value resultIrBox =
5659 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
5660
5661 mlir::Value dim = fir::getBase(args[1]);
5662 fir::runtime::genNorm2Dim(builder, loc, resultIrBox, array, dim);
5663 // Handle cleanup of allocatable result descriptor and return
5664 return readAndAddCleanUp(resultMutableBox, resultType, "NORM2");
5665 }
5666 }
5667
5668 // NOT
5669 mlir::Value IntrinsicLibrary::genNot(mlir::Type resultType,
5670 llvm::ArrayRef<mlir::Value> args) {
5671 assert(args.size() == 1);
5672 mlir::Value allOnes = builder.createAllOnesInteger(loc, resultType);
5673 return builder.create<mlir::arith::XOrIOp>(loc, args[0], allOnes);
5674 }
5675
5676 // NULL
5677 fir::ExtendedValue
5678 IntrinsicLibrary::genNull(mlir::Type, llvm::ArrayRef<fir::ExtendedValue> args) {
5679 // NULL() without MOLD must be handled in the contexts where it can appear
5680 // (see table 16.5 of Fortran 2018 standard).
5681 assert(args.size() == 1 && isStaticallyPresent(args[0]) &&
5682 "MOLD argument required to lower NULL outside of any context");
5683 mlir::Type ptrTy = fir::getBase(args[0]).getType();
5684 if (ptrTy && fir::isBoxProcAddressType(ptrTy)) {
5685 auto boxProcType = mlir::cast<fir::BoxProcType>(fir::unwrapRefType(ptrTy));
5686 mlir::Value boxStorage = builder.createTemporary(loc, boxProcType);
5687 mlir::Value nullBoxProc =
5688 fir::factory::createNullBoxProc(builder, loc, boxProcType);
5689 builder.createStoreWithConvert(loc, nullBoxProc, boxStorage);
5690 return boxStorage;
5691 }
5692 const auto *mold = args[0].getBoxOf<fir::MutableBoxValue>();
5693 assert(mold && "MOLD must be a pointer or allocatable");
5694 fir::BaseBoxType boxType = mold->getBoxTy();
5695 mlir::Value boxStorage = builder.createTemporary(loc, boxType);
5696 mlir::Value box = fir::factory::createUnallocatedBox(
5697 builder, loc, boxType, mold->nonDeferredLenParams());
5698 builder.create<fir::StoreOp>(loc, box, boxStorage);
5699 return fir::MutableBoxValue(boxStorage, mold->nonDeferredLenParams(), {});
5700 }
5701
5702 // PACK
5703 fir::ExtendedValue
5704 IntrinsicLibrary::genPack(mlir::Type resultType,
5705 llvm::ArrayRef<fir::ExtendedValue> args) {
5706 [[maybe_unused]] auto numArgs = args.size();
5707 assert(numArgs == 2 || numArgs == 3);
5708
5709 // Handle required array argument
5710 mlir::Value array = builder.createBox(loc, args[0]);
5711
5712 // Handle required mask argument
5713 mlir::Value mask = builder.createBox(loc, args[1]);
5714
5715 // Handle optional vector argument
5716 mlir::Value vector = isStaticallyAbsent(args, 2)
5717 ? builder.create<fir::AbsentOp>(
5718 loc, fir::BoxType::get(builder.getI1Type()))
5719 : builder.createBox(loc, args[2]);
5720
5721 // Create mutable fir.box to be passed to the runtime for the result.
5722 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, 1);
5723 fir::MutableBoxValue resultMutableBox = fir::factory::createTempMutableBox(
5724 builder, loc, resultArrayType, {},
5725 fir::isPolymorphicType(array.getType()) ? array : mlir::Value{});
5726 mlir::Value resultIrBox =
5727 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
5728
5729 fir::runtime::genPack(builder, loc, resultIrBox, array, mask, vector);
5730
5731 return readAndAddCleanUp(resultMutableBox, resultType, "PACK");
5732 }
5733
5734 // PARITY
5735 fir::ExtendedValue
5736 IntrinsicLibrary::genParity(mlir::Type resultType,
5737 llvm::ArrayRef<fir::ExtendedValue> args) {
5738
5739 assert(args.size() == 2);
5740 // Handle required mask argument
5741 mlir::Value mask = builder.createBox(loc, args[0]);
5742
5743 fir::BoxValue maskArry = builder.createBox(loc, args[0]);
5744 int rank = maskArry.rank();
5745 assert(rank >= 1);
5746
5747 // Handle optional dim argument
5748 bool absentDim = isStaticallyAbsent(args[1]);
5749 mlir::Value dim =
5750 absentDim ? builder.createIntegerConstant(loc, builder.getIndexType(), 1)
5751 : fir::getBase(args[1]);
5752
5753 if (rank == 1 || absentDim)
5754 return builder.createConvert(
5755 loc, resultType, fir::runtime::genParity(builder, loc, mask, dim));
5756
5757 // else use the result descriptor ParityDim() intrinsic
5758
5759 // Create mutable fir.box to be passed to the runtime for the result.
5760
5761 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, rank - 1);
5762 fir::MutableBoxValue resultMutableBox =
5763 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
5764 mlir::Value resultIrBox =
5765 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
5766
5767 // Call runtime. The runtime is allocating the result.
5768 fir::runtime::genParityDescriptor(builder, loc, resultIrBox, mask, dim);
5769 return readAndAddCleanUp(resultMutableBox, resultType, "PARITY");
5770 }
5771
5772 // POPCNT
5773 mlir::Value IntrinsicLibrary::genPopcnt(mlir::Type resultType,
5774 llvm::ArrayRef<mlir::Value> args) {
5775 assert(args.size() == 1);
5776
5777 mlir::Value count = builder.create<mlir::math::CtPopOp>(loc, args);
5778
5779 return builder.createConvert(loc, resultType, count);
5780 }
5781
5782 // POPPAR
5783 mlir::Value IntrinsicLibrary::genPoppar(mlir::Type resultType,
5784 llvm::ArrayRef<mlir::Value> args) {
5785 assert(args.size() == 1);
5786
5787 mlir::Value count = genPopcnt(resultType, args);
5788 mlir::Value one = builder.createIntegerConstant(loc, resultType, 1);
5789
5790 return builder.create<mlir::arith::AndIOp>(loc, count, one);
5791 }
5792
5793 // PRESENT
5794 fir::ExtendedValue
5795 IntrinsicLibrary::genPresent(mlir::Type,
5796 llvm::ArrayRef<fir::ExtendedValue> args) {
5797 assert(args.size() == 1);
5798 return builder.create<fir::IsPresentOp>(loc, builder.getI1Type(),
5799 fir::getBase(args[0]));
5800 }
5801
5802 // PRODUCT
5803 fir::ExtendedValue
5804 IntrinsicLibrary::genProduct(mlir::Type resultType,
5805 llvm::ArrayRef<fir::ExtendedValue> args) {
5806 return genReduction(fir::runtime::genProduct, fir::runtime::genProductDim,
5807 "PRODUCT", resultType, args);
5808 }
5809
5810 // RANDOM_INIT
5811 void IntrinsicLibrary::genRandomInit(llvm::ArrayRef<fir::ExtendedValue> args) {
5812 assert(args.size() == 2);
5813 fir::runtime::genRandomInit(builder, loc, fir::getBase(args[0]),
5814 fir::getBase(args[1]));
5815 }
5816
5817 // RANDOM_NUMBER
5818 void IntrinsicLibrary::genRandomNumber(
5819 llvm::ArrayRef<fir::ExtendedValue> args) {
5820 assert(args.size() == 1);
5821 fir::runtime::genRandomNumber(builder, loc, fir::getBase(args[0]));
5822 }
5823
5824 // RANDOM_SEED
5825 void IntrinsicLibrary::genRandomSeed(llvm::ArrayRef<fir::ExtendedValue> args) {
5826 assert(args.size() == 3);
5827 mlir::Type boxNoneTy = fir::BoxType::get(builder.getNoneType());
5828 auto getDesc = [&](int i) {
5829 return isStaticallyPresent(args[i])
5830 ? fir::getBase(args[i])
5831 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
5832 };
5833 mlir::Value size = getDesc(0);
5834 mlir::Value put = getDesc(1);
5835 mlir::Value get = getDesc(2);
5836 fir::runtime::genRandomSeed(builder, loc, size, put, get);
5837 }
5838
5839 // REDUCE
5840 fir::ExtendedValue
5841 IntrinsicLibrary::genReduce(mlir::Type resultType,
5842 llvm::ArrayRef<fir::ExtendedValue> args) {
5843 assert(args.size() == 6);
5844
5845 fir::BoxValue arrayTmp = builder.createBox(loc, args[0]);
5846 mlir::Value array = fir::getBase(arrayTmp);
5847 mlir::Value operation = fir::getBase(args[1]);
5848 int rank = arrayTmp.rank();
5849 assert(rank >= 1);
5850
5851 // Arguements to the reduction operation are passed by reference or value?
5852 bool argByRef = true;
5853 if (!operation.getDefiningOp())
5854 TODO(loc, "Distinguigh dummy procedure arguments");
5855 if (auto embox =
5856 mlir::dyn_cast_or_null<fir::EmboxProcOp>(operation.getDefiningOp())) {
5857 auto fctTy = mlir::dyn_cast<mlir::FunctionType>(embox.getFunc().getType());
5858 argByRef = mlir::isa<fir::ReferenceType>(fctTy.getInput(0));
5859 } else if (auto load = mlir::dyn_cast_or_null<fir::LoadOp>(
5860 operation.getDefiningOp())) {
5861 auto boxProcTy = mlir::dyn_cast_or_null<fir::BoxProcType>(load.getType());
5862 assert(boxProcTy && "expect BoxProcType");
5863 auto fctTy = mlir::dyn_cast<mlir::FunctionType>(boxProcTy.getEleTy());
5864 argByRef = mlir::isa<fir::ReferenceType>(fctTy.getInput(0));
5865 }
5866
5867 mlir::Type ty = array.getType();
5868 mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(ty);
5869 mlir::Type eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
5870
5871 // Handle optional arguments
5872 bool absentDim = isStaticallyAbsent(args[2]);
5873
5874 auto mask = isStaticallyAbsent(args[3])
5875 ? builder.create<fir::AbsentOp>(
5876 loc, fir::BoxType::get(builder.getI1Type()))
5877 : builder.createBox(loc, args[3]);
5878
5879 mlir::Value identity =
5880 isStaticallyAbsent(args[4])
5881 ? builder.create<fir::AbsentOp>(loc, fir::ReferenceType::get(eleTy))
5882 : fir::getBase(args[4]);
5883
5884 mlir::Value ordered = isStaticallyAbsent(args[5])
5885 ? builder.createBool(loc, false)
5886 : fir::getBase(args[5]);
5887
5888 // We call the type specific versions because the result is scalar
5889 // in the case below.
5890 if (absentDim || rank == 1) {
5891 if (fir::isa_complex(eleTy) || fir::isa_derived(eleTy)) {
5892 mlir::Value result = builder.createTemporary(loc, eleTy);
5893 fir::runtime::genReduce(builder, loc, array, operation, mask, identity,
5894 ordered, result, argByRef);
5895 if (fir::isa_derived(eleTy))
5896 return result;
5897 return builder.create<fir::LoadOp>(loc, result);
5898 }
5899 if (fir::isa_char(eleTy)) {
5900 auto charTy = mlir::dyn_cast_or_null<fir::CharacterType>(resultType);
5901 assert(charTy && "expect CharacterType");
5902 fir::factory::CharacterExprHelper charHelper(builder, loc);
5903 mlir::Value len;
5904 if (charTy.hasDynamicLen())
5905 len = charHelper.readLengthFromBox(fir::getBase(arrayTmp), charTy);
5906 else
5907 len = builder.createIntegerConstant(loc, builder.getI32Type(),
5908 charTy.getLen());
5909 fir::CharBoxValue temp = charHelper.createCharacterTemp(eleTy, len);
5910 fir::runtime::genReduce(builder, loc, array, operation, mask, identity,
5911 ordered, temp.getBuffer(), argByRef);
5912 return temp;
5913 }
5914 return fir::runtime::genReduce(builder, loc, array, operation, mask,
5915 identity, ordered, argByRef);
5916 }
5917 // Handle cases that have an array result.
5918 // Create mutable fir.box to be passed to the runtime for the result.
5919 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, rank - 1);
5920 fir::MutableBoxValue resultMutableBox =
5921 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
5922 mlir::Value resultIrBox =
5923 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
5924 mlir::Value dim = fir::getBase(args[2]);
5925 fir::runtime::genReduceDim(builder, loc, array, operation, dim, mask,
5926 identity, ordered, resultIrBox, argByRef);
5927 return readAndAddCleanUp(resultMutableBox, resultType, "REDUCE");
5928 }
5929
5930 // RENAME
5931 fir::ExtendedValue
5932 IntrinsicLibrary::genRename(std::optional<mlir::Type> resultType,
5933 mlir::ArrayRef<fir::ExtendedValue> args) {
5934 assert((args.size() == 3 && !resultType.has_value()) ||
5935 (args.size() == 2 && resultType.has_value()));
5936
5937 mlir::Value path1 = fir::getBase(args[0]);
5938 mlir::Value path2 = fir::getBase(args[1]);
5939 if (!path1 || !path2)
5940 fir::emitFatalError(loc, "Expected at least two dummy arguments");
5941
5942 if (resultType.has_value()) {
5943 // code-gen for the function form of RENAME
5944 auto statusAddr = builder.createTemporary(loc, *resultType);
5945 auto statusBox = builder.createBox(loc, statusAddr);
5946 fir::runtime::genRename(builder, loc, path1, path2, statusBox);
5947 return builder.create<fir::LoadOp>(loc, statusAddr);
5948 } else {
5949 // code-gen for the procedure form of RENAME
5950 mlir::Type boxNoneTy = fir::BoxType::get(builder.getNoneType());
5951 auto status = args[2];
5952 mlir::Value statusBox =
5953 isStaticallyPresent(status)
5954 ? fir::getBase(status)
5955 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
5956 fir::runtime::genRename(builder, loc, path1, path2, statusBox);
5957 return {};
5958 }
5959 }
5960
5961 // REPEAT
5962 fir::ExtendedValue
5963 IntrinsicLibrary::genRepeat(mlir::Type resultType,
5964 llvm::ArrayRef<fir::ExtendedValue> args) {
5965 assert(args.size() == 2);
5966 mlir::Value string = builder.createBox(loc, args[0]);
5967 mlir::Value ncopies = fir::getBase(args[1]);
5968 // Create mutable fir.box to be passed to the runtime for the result.
5969 fir::MutableBoxValue resultMutableBox =
5970 fir::factory::createTempMutableBox(builder, loc, resultType);
5971 mlir::Value resultIrBox =
5972 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
5973 // Call runtime. The runtime is allocating the result.
5974 fir::runtime::genRepeat(builder, loc, resultIrBox, string, ncopies);
5975 // Read result from mutable fir.box and add it to the list of temps to be
5976 // finalized by the StatementContext.
5977 return readAndAddCleanUp(resultMutableBox, resultType, "REPEAT");
5978 }
5979
5980 // RESHAPE
5981 fir::ExtendedValue
5982 IntrinsicLibrary::genReshape(mlir::Type resultType,
5983 llvm::ArrayRef<fir::ExtendedValue> args) {
5984 assert(args.size() == 4);
5985
5986 // Handle source argument
5987 mlir::Value source = builder.createBox(loc, args[0]);
5988
5989 // Handle shape argument
5990 mlir::Value shape = builder.createBox(loc, args[1]);
5991 assert(fir::BoxValue(shape).rank() == 1);
5992 mlir::Type shapeTy = shape.getType();
5993 mlir::Type shapeArrTy = fir::dyn_cast_ptrOrBoxEleTy(shapeTy);
5994 auto resultRank = mlir::cast<fir::SequenceType>(shapeArrTy).getShape()[0];
5995
5996 if (resultRank == fir::SequenceType::getUnknownExtent())
5997 TODO(loc, "intrinsic: reshape requires computing rank of result");
5998
5999 // Handle optional pad argument
6000 mlir::Value pad = isStaticallyAbsent(args[2])
6001 ? builder.create<fir::AbsentOp>(
6002 loc, fir::BoxType::get(builder.getI1Type()))
6003 : builder.createBox(loc, args[2]);
6004
6005 // Handle optional order argument
6006 mlir::Value order = isStaticallyAbsent(args[3])
6007 ? builder.create<fir::AbsentOp>(
6008 loc, fir::BoxType::get(builder.getI1Type()))
6009 : builder.createBox(loc, args[3]);
6010
6011 // Create mutable fir.box to be passed to the runtime for the result.
6012 mlir::Type type = builder.getVarLenSeqTy(resultType, resultRank);
6013 fir::MutableBoxValue resultMutableBox = fir::factory::createTempMutableBox(
6014 builder, loc, type, {},
6015 fir::isPolymorphicType(source.getType()) ? source : mlir::Value{});
6016
6017 mlir::Value resultIrBox =
6018 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
6019
6020 fir::runtime::genReshape(builder, loc, resultIrBox, source, shape, pad,
6021 order);
6022
6023 return readAndAddCleanUp(resultMutableBox, resultType, "RESHAPE");
6024 }
6025
6026 // RRSPACING
6027 mlir::Value IntrinsicLibrary::genRRSpacing(mlir::Type resultType,
6028 llvm::ArrayRef<mlir::Value> args) {
6029 assert(args.size() == 1);
6030
6031 return builder.createConvert(
6032 loc, resultType,
6033 fir::runtime::genRRSpacing(builder, loc, fir::getBase(args[0])));
6034 }
6035
6036 // ERFC_SCALED
6037 mlir::Value IntrinsicLibrary::genErfcScaled(mlir::Type resultType,
6038 llvm::ArrayRef<mlir::Value> args) {
6039 assert(args.size() == 1);
6040
6041 return builder.createConvert(
6042 loc, resultType,
6043 fir::runtime::genErfcScaled(builder, loc, fir::getBase(args[0])));
6044 }
6045
6046 // SAME_TYPE_AS
6047 fir::ExtendedValue
6048 IntrinsicLibrary::genSameTypeAs(mlir::Type resultType,
6049 llvm::ArrayRef<fir::ExtendedValue> args) {
6050 assert(args.size() == 2);
6051
6052 return builder.createConvert(
6053 loc, resultType,
6054 fir::runtime::genSameTypeAs(builder, loc, fir::getBase(args[0]),
6055 fir::getBase(args[1])));
6056 }
6057
6058 // SCALE
6059 mlir::Value IntrinsicLibrary::genScale(mlir::Type resultType,
6060 llvm::ArrayRef<mlir::Value> args) {
6061 assert(args.size() == 2);
6062
6063 mlir::Value realX = fir::getBase(args[0]);
6064 mlir::Value intI = fir::getBase(args[1]);
6065
6066 return builder.createConvert(
6067 loc, resultType, fir::runtime::genScale(builder, loc, realX, intI));
6068 }
6069
6070 // SCAN
6071 fir::ExtendedValue
6072 IntrinsicLibrary::genScan(mlir::Type resultType,
6073 llvm::ArrayRef<fir::ExtendedValue> args) {
6074
6075 assert(args.size() == 4);
6076
6077 if (isStaticallyAbsent(args[3])) {
6078 // Kind not specified, so call scan/verify runtime routine that is
6079 // specialized on the kind of characters in string.
6080
6081 // Handle required string base arg
6082 mlir::Value stringBase = fir::getBase(args[0]);
6083
6084 // Handle required set string base arg
6085 mlir::Value setBase = fir::getBase(args[1]);
6086
6087 // Handle kind argument; it is the kind of character in this case
6088 fir::KindTy kind =
6089 fir::factory::CharacterExprHelper{builder, loc}.getCharacterKind(
6090 stringBase.getType());
6091
6092 // Get string length argument
6093 mlir::Value stringLen = fir::getLen(args[0]);
6094
6095 // Get set string length argument
6096 mlir::Value setLen = fir::getLen(args[1]);
6097
6098 // Handle optional back argument
6099 mlir::Value back =
6100 isStaticallyAbsent(args[2])
6101 ? builder.createIntegerConstant(loc, builder.getI1Type(), 0)
6102 : fir::getBase(args[2]);
6103
6104 return builder.createConvert(loc, resultType,
6105 fir::runtime::genScan(builder, loc, kind,
6106 stringBase, stringLen,
6107 setBase, setLen, back));
6108 }
6109 // else use the runtime descriptor version of scan/verify
6110
6111 // Handle optional argument, back
6112 auto makeRefThenEmbox = [&](mlir::Value b) {
6113 fir::LogicalType logTy = fir::LogicalType::get(
6114 builder.getContext(), builder.getKindMap().defaultLogicalKind());
6115 mlir::Value temp = builder.createTemporary(loc, logTy);
6116 mlir::Value castb = builder.createConvert(loc, logTy, b);
6117 builder.create<fir::StoreOp>(loc, castb, temp);
6118 return builder.createBox(loc, temp);
6119 };
6120 mlir::Value back = fir::isUnboxedValue(args[2])
6121 ? makeRefThenEmbox(*args[2].getUnboxed())
6122 : builder.create<fir::AbsentOp>(
6123 loc, fir::BoxType::get(builder.getI1Type()));
6124
6125 // Handle required string argument
6126 mlir::Value string = builder.createBox(loc, args[0]);
6127
6128 // Handle required set argument
6129 mlir::Value set = builder.createBox(loc, args[1]);
6130
6131 // Handle kind argument
6132 mlir::Value kind = fir::getBase(args[3]);
6133
6134 // Create result descriptor
6135 fir::MutableBoxValue resultMutableBox =
6136 fir::factory::createTempMutableBox(builder, loc, resultType);
6137 mlir::Value resultIrBox =
6138 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
6139
6140 fir::runtime::genScanDescriptor(builder, loc, resultIrBox, string, set, back,
6141 kind);
6142
6143 // Handle cleanup of allocatable result descriptor and return
6144 return readAndAddCleanUp(resultMutableBox, resultType, "SCAN");
6145 }
6146
6147 // SECOND
6148 fir::ExtendedValue
6149 IntrinsicLibrary::genSecond(std::optional<mlir::Type> resultType,
6150 mlir::ArrayRef<fir::ExtendedValue> args) {
6151 assert((args.size() == 1 && !resultType) || (args.empty() && resultType));
6152
6153 fir::ExtendedValue result;
6154
6155 if (resultType)
6156 result = builder.createTemporary(loc, *resultType);
6157 else
6158 result = args[0];
6159
6160 llvm::SmallVector<fir::ExtendedValue, 1> subroutineArgs(1, result);
6161 genCpuTime(subroutineArgs);
6162
6163 if (resultType)
6164 return builder.create<fir::LoadOp>(loc, fir::getBase(result));
6165 return {};
6166 }
6167
6168 // SELECTED_CHAR_KIND
6169 fir::ExtendedValue
6170 IntrinsicLibrary::genSelectedCharKind(mlir::Type resultType,
6171 llvm::ArrayRef<fir::ExtendedValue> args) {
6172 assert(args.size() == 1);
6173
6174 return builder.createConvert(
6175 loc, resultType,
6176 fir::runtime::genSelectedCharKind(builder, loc, fir::getBase(args[0]),
6177 fir::getLen(args[0])));
6178 }
6179
6180 // SELECTED_INT_KIND
6181 mlir::Value
6182 IntrinsicLibrary::genSelectedIntKind(mlir::Type resultType,
6183 llvm::ArrayRef<mlir::Value> args) {
6184 assert(args.size() == 1);
6185
6186 return builder.createConvert(
6187 loc, resultType,
6188 fir::runtime::genSelectedIntKind(builder, loc, fir::getBase(args[0])));
6189 }
6190
6191 // SELECTED_LOGICAL_KIND
6192 mlir::Value
6193 IntrinsicLibrary::genSelectedLogicalKind(mlir::Type resultType,
6194 llvm::ArrayRef<mlir::Value> args) {
6195 assert(args.size() == 1);
6196
6197 return builder.createConvert(loc, resultType,
6198 fir::runtime::genSelectedLogicalKind(
6199 builder, loc, fir::getBase(args[0])));
6200 }
6201
6202 // SELECTED_REAL_KIND
6203 mlir::Value
6204 IntrinsicLibrary::genSelectedRealKind(mlir::Type resultType,
6205 llvm::ArrayRef<mlir::Value> args) {
6206 assert(args.size() == 3);
6207
6208 // Handle optional precision(P) argument
6209 mlir::Value precision =
6210 isStaticallyAbsent(args[0])
6211 ? builder.create<fir::AbsentOp>(
6212 loc, fir::ReferenceType::get(builder.getI1Type()))
6213 : fir::getBase(args[0]);
6214
6215 // Handle optional range(R) argument
6216 mlir::Value range =
6217 isStaticallyAbsent(args[1])
6218 ? builder.create<fir::AbsentOp>(
6219 loc, fir::ReferenceType::get(builder.getI1Type()))
6220 : fir::getBase(args[1]);
6221
6222 // Handle optional radix(RADIX) argument
6223 mlir::Value radix =
6224 isStaticallyAbsent(args[2])
6225 ? builder.create<fir::AbsentOp>(
6226 loc, fir::ReferenceType::get(builder.getI1Type()))
6227 : fir::getBase(args[2]);
6228
6229 return builder.createConvert(
6230 loc, resultType,
6231 fir::runtime::genSelectedRealKind(builder, loc, precision, range, radix));
6232 }
6233
6234 // SET_EXPONENT
6235 mlir::Value IntrinsicLibrary::genSetExponent(mlir::Type resultType,
6236 llvm::ArrayRef<mlir::Value> args) {
6237 assert(args.size() == 2);
6238
6239 return builder.createConvert(
6240 loc, resultType,
6241 fir::runtime::genSetExponent(builder, loc, fir::getBase(args[0]),
6242 fir::getBase(args[1])));
6243 }
6244
6245 /// Create a fir.box to be passed to the LBOUND/UBOUND runtime.
6246 /// This ensure that local lower bounds of assumed shape are propagated and that
6247 /// a fir.box with equivalent LBOUNDs.
6248 static mlir::Value
6249 createBoxForRuntimeBoundInquiry(mlir::Location loc, fir::FirOpBuilder &builder,
6250 const fir::ExtendedValue &array) {
6251 // Assumed-rank descriptor must always carry accurate lower bound information
6252 // in lowering since they cannot be tracked on the side in a vector at compile
6253 // time.
6254 if (array.hasAssumedRank())
6255 return builder.createBox(loc, array);
6256
6257 return array.match(
6258 [&](const fir::BoxValue &boxValue) -> mlir::Value {
6259 // This entity is mapped to a fir.box that may not contain the local
6260 // lower bound information if it is a dummy. Rebox it with the local
6261 // shape information.
6262 mlir::Value localShape = builder.createShape(loc, array);
6263 mlir::Value oldBox = boxValue.getAddr();
6264 return builder.create<fir::ReboxOp>(loc, oldBox.getType(), oldBox,
6265 localShape,
6266 /*slice=*/mlir::Value{});
6267 },
6268 [&](const auto &) -> mlir::Value {
6269 // This is a pointer/allocatable, or an entity not yet tracked with a
6270 // fir.box. For pointer/allocatable, createBox will forward the
6271 // descriptor that contains the correct lower bound information. For
6272 // other entities, a new fir.box will be made with the local lower
6273 // bounds.
6274 return builder.createBox(loc, array);
6275 });
6276 }
6277
6278 /// Generate runtime call to inquire about all the bounds/extents of an
6279 /// array (or an assumed-rank).
6280 template <typename Func>
6281 static fir::ExtendedValue
6282 genBoundInquiry(fir::FirOpBuilder &builder, mlir::Location loc,
6283 mlir::Type resultType, llvm::ArrayRef<fir::ExtendedValue> args,
6284 int kindPos, Func genRtCall, bool needAccurateLowerBound) {
6285 const fir::ExtendedValue &array = args[0];
6286 const bool hasAssumedRank = array.hasAssumedRank();
6287 mlir::Type resultElementType = fir::unwrapSequenceType(resultType);
6288 // For assumed-rank arrays, allocate an array with the maximum rank, that is
6289 // big enough to hold the result but still "small" (15 elements). Static size
6290 // alloca make stack analysis/manipulation easier.
6291 int rank = hasAssumedRank ? Fortran::common::maxRank : array.rank();
6292 mlir::Type allocSeqType = fir::SequenceType::get(rank, resultElementType);
6293 mlir::Value resultStorage = builder.createTemporary(loc, allocSeqType);
6294 mlir::Value arrayBox =
6295 needAccurateLowerBound
6296 ? createBoxForRuntimeBoundInquiry(loc, builder, array)
6297 : builder.createBox(loc, array);
6298 mlir::Value kind = isStaticallyAbsent(args, kindPos)
6299 ? builder.createIntegerConstant(
6300 loc, builder.getI32Type(),
6301 builder.getKindMap().defaultIntegerKind())
6302 : fir::getBase(args[kindPos]);
6303 genRtCall(builder, loc, resultStorage, arrayBox, kind);
6304 if (hasAssumedRank) {
6305 // Cast to fir.ref<array<?xik>> since the result extent is not a compile
6306 // time constant.
6307 mlir::Type baseType =
6308 fir::ReferenceType::get(builder.getVarLenSeqTy(resultElementType));
6309 mlir::Value resultBase =
6310 builder.createConvert(loc, baseType, resultStorage);
6311 mlir::Value rankValue =
6312 builder.create<fir::BoxRankOp>(loc, builder.getIndexType(), arrayBox);
6313 return fir::ArrayBoxValue{resultBase, {rankValue}};
6314 }
6315 // Result extent is a compile time constant in the other cases.
6316 mlir::Value rankValue =
6317 builder.createIntegerConstant(loc, builder.getIndexType(), rank);
6318 return fir::ArrayBoxValue{resultStorage, {rankValue}};
6319 }
6320
6321 // SHAPE
6322 fir::ExtendedValue
6323 IntrinsicLibrary::genShape(mlir::Type resultType,
6324 llvm::ArrayRef<fir::ExtendedValue> args) {
6325 assert(args.size() >= 1);
6326 const fir::ExtendedValue &array = args[0];
6327 if (array.hasAssumedRank())
6328 return genBoundInquiry(builder, loc, resultType, args,
6329 /*kindPos=*/1, fir::runtime::genShape,
6330 /*needAccurateLowerBound=*/false);
6331 int rank = array.rank();
6332 mlir::Type indexType = builder.getIndexType();
6333 mlir::Type extentType = fir::unwrapSequenceType(resultType);
6334 mlir::Type seqType = fir::SequenceType::get(
6335 {static_cast<fir::SequenceType::Extent>(rank)}, extentType);
6336 mlir::Value shapeArray = builder.createTemporary(loc, seqType);
6337 mlir::Type shapeAddrType = builder.getRefType(extentType);
6338 for (int dim = 0; dim < rank; ++dim) {
6339 mlir::Value extent = fir::factory::readExtent(builder, loc, array, dim);
6340 extent = builder.createConvert(loc, extentType, extent);
6341 auto index = builder.createIntegerConstant(loc, indexType, dim);
6342 auto shapeAddr = builder.create<fir::CoordinateOp>(loc, shapeAddrType,
6343 shapeArray, index);
6344 builder.create<fir::StoreOp>(loc, extent, shapeAddr);
6345 }
6346 mlir::Value shapeArrayExtent =
6347 builder.createIntegerConstant(loc, indexType, rank);
6348 llvm::SmallVector<mlir::Value> extents{shapeArrayExtent};
6349 return fir::ArrayBoxValue{shapeArray, extents};
6350 }
6351
6352 // SHIFTL, SHIFTR
6353 template <typename Shift>
6354 mlir::Value IntrinsicLibrary::genShift(mlir::Type resultType,
6355 llvm::ArrayRef<mlir::Value> args) {
6356 assert(args.size() == 2);
6357
6358 // If SHIFT < 0 or SHIFT >= BIT_SIZE(I), return 0. This is not required by
6359 // the standard. However, several other compilers behave this way, so try and
6360 // maintain compatibility with them to an extent.
6361
6362 unsigned bits = resultType.getIntOrFloatBitWidth();
6363 mlir::Value bitSize = builder.createIntegerConstant(loc, resultType, bits);
6364 mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
6365 mlir::Value shift = builder.createConvert(loc, resultType, args[1]);
6366
6367 mlir::Value tooSmall = builder.create<mlir::arith::CmpIOp>(
6368 loc, mlir::arith::CmpIPredicate::slt, shift, zero);
6369 mlir::Value tooLarge = builder.create<mlir::arith::CmpIOp>(
6370 loc, mlir::arith::CmpIPredicate::sge, shift, bitSize);
6371 mlir::Value outOfBounds =
6372 builder.create<mlir::arith::OrIOp>(loc, tooSmall, tooLarge);
6373
6374 mlir::Value shifted = builder.create<Shift>(loc, args[0], shift);
6375 return builder.create<mlir::arith::SelectOp>(loc, outOfBounds, zero, shifted);
6376 }
6377
6378 // SHIFTA
6379 mlir::Value IntrinsicLibrary::genShiftA(mlir::Type resultType,
6380 llvm::ArrayRef<mlir::Value> args) {
6381 unsigned bits = resultType.getIntOrFloatBitWidth();
6382 mlir::Value bitSize = builder.createIntegerConstant(loc, resultType, bits);
6383 mlir::Value shift = builder.createConvert(loc, resultType, args[1]);
6384 mlir::Value shiftEqBitSize = builder.create<mlir::arith::CmpIOp>(
6385 loc, mlir::arith::CmpIPredicate::eq, shift, bitSize);
6386
6387 // Lowering of mlir::arith::ShRSIOp is using `ashr`. `ashr` is undefined when
6388 // the shift amount is equal to the element size.
6389 // So if SHIFT is equal to the bit width then it is handled as a special case.
6390 mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
6391 mlir::Value minusOne = builder.createMinusOneInteger(loc, resultType);
6392 mlir::Value valueIsNeg = builder.create<mlir::arith::CmpIOp>(
6393 loc, mlir::arith::CmpIPredicate::slt, args[0], zero);
6394 mlir::Value specialRes =
6395 builder.create<mlir::arith::SelectOp>(loc, valueIsNeg, minusOne, zero);
6396
6397 mlir::Value shifted =
6398 builder.create<mlir::arith::ShRSIOp>(loc, args[0], shift);
6399 return builder.create<mlir::arith::SelectOp>(loc, shiftEqBitSize, specialRes,
6400 shifted);
6401 }
6402
6403 // SIGNAL
6404 void IntrinsicLibrary::genSignalSubroutine(
6405 llvm::ArrayRef<fir::ExtendedValue> args) {
6406 assert(args.size() == 2 || args.size() == 3);
6407 mlir::Value number = fir::getBase(args[0]);
6408 mlir::Value handler = fir::getBase(args[1]);
6409 mlir::Value status;
6410 if (args.size() == 3)
6411 status = fir::getBase(args[2]);
6412 fir::runtime::genSignal(builder, loc, number, handler, status);
6413 }
6414
6415 // SIGN
6416 mlir::Value IntrinsicLibrary::genSign(mlir::Type resultType,
6417 llvm::ArrayRef<mlir::Value> args) {
6418 assert(args.size() == 2);
6419 if (mlir::isa<mlir::IntegerType>(resultType)) {
6420 mlir::Value abs = genAbs(resultType, {args[0]});
6421 mlir::Value zero = builder.createIntegerConstant(loc, resultType, 0);
6422 auto neg = builder.create<mlir::arith::SubIOp>(loc, zero, abs);
6423 auto cmp = builder.create<mlir::arith::CmpIOp>(
6424 loc, mlir::arith::CmpIPredicate::slt, args[1], zero);
6425 return builder.create<mlir::arith::SelectOp>(loc, cmp, neg, abs);
6426 }
6427 return genRuntimeCall("sign", resultType, args);
6428 }
6429
6430 // SIND
6431 mlir::Value IntrinsicLibrary::genSind(mlir::Type resultType,
6432 llvm::ArrayRef<mlir::Value> args) {
6433 assert(args.size() == 1);
6434 mlir::MLIRContext *context = builder.getContext();
6435 mlir::FunctionType ftype =
6436 mlir::FunctionType::get(context, {resultType}, {args[0].getType()});
6437 llvm::APFloat pi = llvm::APFloat(llvm::numbers::pi);
6438 mlir::Value dfactor = builder.createRealConstant(
6439 loc, mlir::FloatType::getF64(context), pi / llvm::APFloat(180.0));
6440 mlir::Value factor = builder.createConvert(loc, args[0].getType(), dfactor);
6441 mlir::Value arg = builder.create<mlir::arith::MulFOp>(loc, args[0], factor);
6442 return getRuntimeCallGenerator("sin", ftype)(builder, loc, {arg});
6443 }
6444
6445 // SIZE
6446 fir::ExtendedValue
6447 IntrinsicLibrary::genSize(mlir::Type resultType,
6448 llvm::ArrayRef<fir::ExtendedValue> args) {
6449 // Note that the value of the KIND argument is already reflected in the
6450 // resultType
6451 assert(args.size() == 3);
6452
6453 // Get the ARRAY argument
6454 mlir::Value array = builder.createBox(loc, args[0]);
6455
6456 // The front-end rewrites SIZE without the DIM argument to
6457 // an array of SIZE with DIM in most cases, but it may not be
6458 // possible in some cases like when in SIZE(function_call()).
6459 if (isStaticallyAbsent(args, 1))
6460 return builder.createConvert(loc, resultType,
6461 fir::runtime::genSize(builder, loc, array));
6462
6463 // Get the DIM argument.
6464 mlir::Value dim = fir::getBase(args[1]);
6465 if (!args[0].hasAssumedRank())
6466 if (std::optional<std::int64_t> cstDim = fir::getIntIfConstant(dim)) {
6467 // If both DIM and the rank are compile time constants, skip the runtime
6468 // call.
6469 return builder.createConvert(
6470 loc, resultType,
6471 fir::factory::readExtent(builder, loc, fir::BoxValue{array},
6472 cstDim.value() - 1));
6473 }
6474 if (!fir::isa_ref_type(dim.getType()))
6475 return builder.createConvert(
6476 loc, resultType, fir::runtime::genSizeDim(builder, loc, array, dim));
6477
6478 mlir::Value isDynamicallyAbsent = builder.genIsNullAddr(loc, dim);
6479 return builder
6480 .genIfOp(loc, {resultType}, isDynamicallyAbsent,
6481 /*withElseRegion=*/true)
6482 .genThen([&]() {
6483 mlir::Value size = builder.createConvert(
6484 loc, resultType, fir::runtime::genSize(builder, loc, array));
6485 builder.create<fir::ResultOp>(loc, size);
6486 })
6487 .genElse([&]() {
6488 mlir::Value dimValue = builder.create<fir::LoadOp>(loc, dim);
6489 mlir::Value size = builder.createConvert(
6490 loc, resultType,
6491 fir::runtime::genSizeDim(builder, loc, array, dimValue));
6492 builder.create<fir::ResultOp>(loc, size);
6493 })
6494 .getResults()[0];
6495 }
6496
6497 // SIZEOF
6498 fir::ExtendedValue
6499 IntrinsicLibrary::genSizeOf(mlir::Type resultType,
6500 llvm::ArrayRef<fir::ExtendedValue> args) {
6501 assert(args.size() == 1);
6502 mlir::Value box = fir::getBase(args[0]);
6503 mlir::Value eleSize = builder.create<fir::BoxEleSizeOp>(loc, resultType, box);
6504 if (!fir::isArray(args[0]))
6505 return eleSize;
6506 mlir::Value arraySize = builder.createConvert(
6507 loc, resultType, fir::runtime::genSize(builder, loc, box));
6508 return builder.create<mlir::arith::MulIOp>(loc, eleSize, arraySize);
6509 }
6510
6511 // TAND
6512 mlir::Value IntrinsicLibrary::genTand(mlir::Type resultType,
6513 llvm::ArrayRef<mlir::Value> args) {
6514 assert(args.size() == 1);
6515 mlir::MLIRContext *context = builder.getContext();
6516 mlir::FunctionType ftype =
6517 mlir::FunctionType::get(context, {resultType}, {args[0].getType()});
6518 llvm::APFloat pi = llvm::APFloat(llvm::numbers::pi);
6519 mlir::Value dfactor = builder.createRealConstant(
6520 loc, mlir::FloatType::getF64(context), pi / llvm::APFloat(180.0));
6521 mlir::Value factor = builder.createConvert(loc, args[0].getType(), dfactor);
6522 mlir::Value arg = builder.create<mlir::arith::MulFOp>(loc, args[0], factor);
6523 return getRuntimeCallGenerator("tan", ftype)(builder, loc, {arg});
6524 }
6525
6526 // TRAILZ
6527 mlir::Value IntrinsicLibrary::genTrailz(mlir::Type resultType,
6528 llvm::ArrayRef<mlir::Value> args) {
6529 assert(args.size() == 1);
6530
6531 mlir::Value result =
6532 builder.create<mlir::math::CountTrailingZerosOp>(loc, args);
6533
6534 return builder.createConvert(loc, resultType, result);
6535 }
6536
6537 static bool hasDefaultLowerBound(const fir::ExtendedValue &exv) {
6538 return exv.match(
6539 [](const fir::ArrayBoxValue &arr) { return arr.getLBounds().empty(); },
6540 [](const fir::CharArrayBoxValue &arr) {
6541 return arr.getLBounds().empty();
6542 },
6543 [](const fir::BoxValue &arr) { return arr.getLBounds().empty(); },
6544 [](const auto &) { return false; });
6545 }
6546
6547 /// Compute the lower bound in dimension \p dim (zero based) of \p array
6548 /// taking care of returning one when the related extent is zero.
6549 static mlir::Value computeLBOUND(fir::FirOpBuilder &builder, mlir::Location loc,
6550 const fir::ExtendedValue &array, unsigned dim,
6551 mlir::Value zero, mlir::Value one) {
6552 assert(dim < array.rank() && "invalid dimension");
6553 if (hasDefaultLowerBound(array))
6554 return one;
6555 mlir::Value lb = fir::factory::readLowerBound(builder, loc, array, dim, one);
6556 mlir::Value extent = fir::factory::readExtent(builder, loc, array, dim);
6557 zero = builder.createConvert(loc, extent.getType(), zero);
6558 // Note: for assumed size, the extent is -1, and the lower bound should
6559 // be returned. It is important to test extent == 0 and not extent > 0.
6560 auto dimIsEmpty = builder.create<mlir::arith::CmpIOp>(
6561 loc, mlir::arith::CmpIPredicate::eq, extent, zero);
6562 one = builder.createConvert(loc, lb.getType(), one);
6563 return builder.create<mlir::arith::SelectOp>(loc, dimIsEmpty, one, lb);
6564 }
6565
6566 // LBOUND
6567 fir::ExtendedValue
6568 IntrinsicLibrary::genLbound(mlir::Type resultType,
6569 llvm::ArrayRef<fir::ExtendedValue> args) {
6570 assert(args.size() == 2 || args.size() == 3);
6571 const fir::ExtendedValue &array = args[0];
6572 // Semantics builds signatures for LBOUND calls as either
6573 // LBOUND(array, dim, [kind]) or LBOUND(array, [kind]).
6574 const bool dimIsAbsent = args.size() == 2 || isStaticallyAbsent(args, 1);
6575 if (array.hasAssumedRank() && dimIsAbsent) {
6576 int kindPos = args.size() == 2 ? 1 : 2;
6577 return genBoundInquiry(builder, loc, resultType, args, kindPos,
6578 fir::runtime::genLbound,
6579 /*needAccurateLowerBound=*/true);
6580 }
6581
6582 mlir::Type indexType = builder.getIndexType();
6583
6584 if (dimIsAbsent) {
6585 // DIM is absent and the rank of array is a compile time constant.
6586 mlir::Type lbType = fir::unwrapSequenceType(resultType);
6587 unsigned rank = array.rank();
6588 mlir::Type lbArrayType = fir::SequenceType::get(
6589 {static_cast<fir::SequenceType::Extent>(array.rank())}, lbType);
6590 mlir::Value lbArray = builder.createTemporary(loc, lbArrayType);
6591 mlir::Type lbAddrType = builder.getRefType(lbType);
6592 mlir::Value one = builder.createIntegerConstant(loc, lbType, 1);
6593 mlir::Value zero = builder.createIntegerConstant(loc, indexType, 0);
6594 for (unsigned dim = 0; dim < rank; ++dim) {
6595 mlir::Value lb = computeLBOUND(builder, loc, array, dim, zero, one);
6596 lb = builder.createConvert(loc, lbType, lb);
6597 auto index = builder.createIntegerConstant(loc, indexType, dim);
6598 auto lbAddr =
6599 builder.create<fir::CoordinateOp>(loc, lbAddrType, lbArray, index);
6600 builder.create<fir::StoreOp>(loc, lb, lbAddr);
6601 }
6602 mlir::Value lbArrayExtent =
6603 builder.createIntegerConstant(loc, indexType, rank);
6604 llvm::SmallVector<mlir::Value> extents{lbArrayExtent};
6605 return fir::ArrayBoxValue{lbArray, extents};
6606 }
6607 // DIM is present.
6608 mlir::Value dim = fir::getBase(args[1]);
6609
6610 // If it is a compile time constant and the rank is known, skip the runtime
6611 // call.
6612 if (!array.hasAssumedRank())
6613 if (std::optional<std::int64_t> cstDim = fir::getIntIfConstant(dim)) {
6614 mlir::Value one = builder.createIntegerConstant(loc, resultType, 1);
6615 mlir::Value zero = builder.createIntegerConstant(loc, indexType, 0);
6616 mlir::Value lb =
6617 computeLBOUND(builder, loc, array, *cstDim - 1, zero, one);
6618 return builder.createConvert(loc, resultType, lb);
6619 }
6620
6621 fir::ExtendedValue box = createBoxForRuntimeBoundInquiry(loc, builder, array);
6622 return builder.createConvert(
6623 loc, resultType,
6624 fir::runtime::genLboundDim(builder, loc, fir::getBase(box), dim));
6625 }
6626
6627 // UBOUND
6628 fir::ExtendedValue
6629 IntrinsicLibrary::genUbound(mlir::Type resultType,
6630 llvm::ArrayRef<fir::ExtendedValue> args) {
6631 assert(args.size() == 3 || args.size() == 2);
6632 const bool dimIsAbsent = args.size() == 2 || isStaticallyAbsent(args, 1);
6633 if (!dimIsAbsent) {
6634 // Handle calls to UBOUND with the DIM argument, which return a scalar
6635 mlir::Value extent = fir::getBase(genSize(resultType, args));
6636 mlir::Value lbound = fir::getBase(genLbound(resultType, args));
6637
6638 mlir::Value one = builder.createIntegerConstant(loc, resultType, 1);
6639 mlir::Value ubound = builder.create<mlir::arith::SubIOp>(loc, lbound, one);
6640 return builder.create<mlir::arith::AddIOp>(loc, ubound, extent);
6641 }
6642 // Handle calls to UBOUND without the DIM argument, which return an array
6643 int kindPos = args.size() == 2 ? 1 : 2;
6644 return genBoundInquiry(builder, loc, resultType, args, kindPos,
6645 fir::runtime::genUbound,
6646 /*needAccurateLowerBound=*/true);
6647 }
6648
6649 // SPACING
6650 mlir::Value IntrinsicLibrary::genSpacing(mlir::Type resultType,
6651 llvm::ArrayRef<mlir::Value> args) {
6652 assert(args.size() == 1);
6653
6654 return builder.createConvert(
6655 loc, resultType,
6656 fir::runtime::genSpacing(builder, loc, fir::getBase(args[0])));
6657 }
6658
6659 // SPREAD
6660 fir::ExtendedValue
6661 IntrinsicLibrary::genSpread(mlir::Type resultType,
6662 llvm::ArrayRef<fir::ExtendedValue> args) {
6663
6664 assert(args.size() == 3);
6665
6666 // Handle source argument
6667 mlir::Value source = builder.createBox(loc, args[0]);
6668 fir::BoxValue sourceTmp = source;
6669 unsigned sourceRank = sourceTmp.rank();
6670
6671 // Handle Dim argument
6672 mlir::Value dim = fir::getBase(args[1]);
6673
6674 // Handle ncopies argument
6675 mlir::Value ncopies = fir::getBase(args[2]);
6676
6677 // Generate result descriptor
6678 mlir::Type resultArrayType =
6679 builder.getVarLenSeqTy(resultType, sourceRank + 1);
6680 fir::MutableBoxValue resultMutableBox = fir::factory::createTempMutableBox(
6681 builder, loc, resultArrayType, {},
6682 fir::isPolymorphicType(source.getType()) ? source : mlir::Value{});
6683 mlir::Value resultIrBox =
6684 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
6685
6686 fir::runtime::genSpread(builder, loc, resultIrBox, source, dim, ncopies);
6687
6688 return readAndAddCleanUp(resultMutableBox, resultType, "SPREAD");
6689 }
6690
6691 // STORAGE_SIZE
6692 fir::ExtendedValue
6693 IntrinsicLibrary::genStorageSize(mlir::Type resultType,
6694 llvm::ArrayRef<fir::ExtendedValue> args) {
6695 assert(args.size() == 2 || args.size() == 1);
6696 mlir::Value box = fir::getBase(args[0]);
6697 mlir::Type boxTy = box.getType();
6698 mlir::Type kindTy = builder.getDefaultIntegerType();
6699 bool needRuntimeCheck = false;
6700 std::string errorMsg;
6701
6702 if (fir::isUnlimitedPolymorphicType(boxTy) &&
6703 (fir::isAllocatableType(boxTy) || fir::isPointerType(boxTy))) {
6704 needRuntimeCheck = true;
6705 errorMsg =
6706 fir::isPointerType(boxTy)
6707 ? "unlimited polymorphic disassociated POINTER in STORAGE_SIZE"
6708 : "unlimited polymorphic unallocated ALLOCATABLE in STORAGE_SIZE";
6709 }
6710 const fir::MutableBoxValue *mutBox = args[0].getBoxOf<fir::MutableBoxValue>();
6711 if (needRuntimeCheck && mutBox) {
6712 mlir::Value isNotAllocOrAssoc =
6713 fir::factory::genIsNotAllocatedOrAssociatedTest(builder, loc, *mutBox);
6714 builder.genIfThen(loc, isNotAllocOrAssoc)
6715 .genThen([&]() {
6716 fir::runtime::genReportFatalUserError(builder, loc, errorMsg);
6717 })
6718 .end();
6719 }
6720
6721 // Handle optional kind argument
6722 bool absentKind = isStaticallyAbsent(args, 1);
6723 if (!absentKind) {
6724 mlir::Operation *defKind = fir::getBase(args[1]).getDefiningOp();
6725 assert(mlir::isa<mlir::arith::ConstantOp>(*defKind) &&
6726 "kind not a constant");
6727 auto constOp = mlir::dyn_cast<mlir::arith::ConstantOp>(*defKind);
6728 kindTy = builder.getIntegerType(
6729 builder.getKindMap().getIntegerBitsize(fir::toInt(constOp)));
6730 }
6731
6732 box = builder.createBox(loc, args[0],
6733 /*isPolymorphic=*/args[0].isPolymorphic());
6734 mlir::Value eleSize = builder.create<fir::BoxEleSizeOp>(loc, kindTy, box);
6735 mlir::Value c8 = builder.createIntegerConstant(loc, kindTy, 8);
6736 return builder.create<mlir::arith::MulIOp>(loc, eleSize, c8);
6737 }
6738
6739 // SUM
6740 fir::ExtendedValue
6741 IntrinsicLibrary::genSum(mlir::Type resultType,
6742 llvm::ArrayRef<fir::ExtendedValue> args) {
6743 return genReduction(fir::runtime::genSum, fir::runtime::genSumDim, "SUM",
6744 resultType, args);
6745 }
6746
6747 // SYSTEM
6748 void IntrinsicLibrary::genSystem(llvm::ArrayRef<fir::ExtendedValue> args) {
6749 assert(args.size() == 2);
6750 mlir::Value command = fir::getBase(args[0]);
6751 const fir::ExtendedValue &exitstat = args[1];
6752 assert(command && "expected COMMAND parameter");
6753
6754 mlir::Type boxNoneTy = fir::BoxType::get(builder.getNoneType());
6755
6756 mlir::Value waitBool = builder.createBool(loc, true);
6757 mlir::Value exitstatBox =
6758 isStaticallyPresent(exitstat)
6759 ? fir::getBase(exitstat)
6760 : builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
6761
6762 // Create a dummmy cmdstat to prevent EXECUTE_COMMAND_LINE terminate itself
6763 // when cmdstat is assigned with a non-zero value but not present
6764 mlir::Value tempValue =
6765 builder.createIntegerConstant(loc, builder.getI16Type(), 0);
6766 mlir::Value temp = builder.createTemporary(loc, builder.getI16Type());
6767 builder.create<fir::StoreOp>(loc, tempValue, temp);
6768 mlir::Value cmdstatBox = builder.createBox(loc, temp);
6769
6770 mlir::Value cmdmsgBox =
6771 builder.create<fir::AbsentOp>(loc, boxNoneTy).getResult();
6772
6773 fir::runtime::genExecuteCommandLine(builder, loc, command, waitBool,
6774 exitstatBox, cmdstatBox, cmdmsgBox);
6775 }
6776
6777 // SYSTEM_CLOCK
6778 void IntrinsicLibrary::genSystemClock(llvm::ArrayRef<fir::ExtendedValue> args) {
6779 assert(args.size() == 3);
6780 fir::runtime::genSystemClock(builder, loc, fir::getBase(args[0]),
6781 fir::getBase(args[1]), fir::getBase(args[2]));
6782 }
6783
6784 // SLEEP
6785 void IntrinsicLibrary::genSleep(llvm::ArrayRef<fir::ExtendedValue> args) {
6786 assert(args.size() == 1 && "SLEEP has one compulsory argument");
6787 fir::runtime::genSleep(builder, loc, fir::getBase(args[0]));
6788 }
6789
6790 // TRANSFER
6791 fir::ExtendedValue
6792 IntrinsicLibrary::genTransfer(mlir::Type resultType,
6793 llvm::ArrayRef<fir::ExtendedValue> args) {
6794
6795 assert(args.size() >= 2); // args.size() == 2 when size argument is omitted.
6796
6797 // Handle source argument
6798 mlir::Value source = builder.createBox(loc, args[0]);
6799
6800 // Handle mold argument
6801 mlir::Value mold = builder.createBox(loc, args[1]);
6802 fir::BoxValue moldTmp = mold;
6803 unsigned moldRank = moldTmp.rank();
6804
6805 bool absentSize = (args.size() == 2);
6806
6807 // Create mutable fir.box to be passed to the runtime for the result.
6808 mlir::Type type = (moldRank == 0 && absentSize)
6809 ? resultType
6810 : builder.getVarLenSeqTy(resultType, 1);
6811 fir::MutableBoxValue resultMutableBox = fir::factory::createTempMutableBox(
6812 builder, loc, type, {},
6813 fir::isPolymorphicType(mold.getType()) ? mold : mlir::Value{});
6814
6815 if (moldRank == 0 && absentSize) {
6816 // This result is a scalar in this case.
6817 mlir::Value resultIrBox =
6818 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
6819
6820 fir::runtime::genTransfer(builder, loc, resultIrBox, source, mold);
6821 } else {
6822 // The result is a rank one array in this case.
6823 mlir::Value resultIrBox =
6824 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
6825
6826 if (absentSize) {
6827 fir::runtime::genTransfer(builder, loc, resultIrBox, source, mold);
6828 } else {
6829 mlir::Value sizeArg = fir::getBase(args[2]);
6830 fir::runtime::genTransferSize(builder, loc, resultIrBox, source, mold,
6831 sizeArg);
6832 }
6833 }
6834 return readAndAddCleanUp(resultMutableBox, resultType, "TRANSFER");
6835 }
6836
6837 // TRANSPOSE
6838 fir::ExtendedValue
6839 IntrinsicLibrary::genTranspose(mlir::Type resultType,
6840 llvm::ArrayRef<fir::ExtendedValue> args) {
6841
6842 assert(args.size() == 1);
6843
6844 // Handle source argument
6845 mlir::Value source = builder.createBox(loc, args[0]);
6846
6847 // Create mutable fir.box to be passed to the runtime for the result.
6848 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, 2);
6849 fir::MutableBoxValue resultMutableBox = fir::factory::createTempMutableBox(
6850 builder, loc, resultArrayType, {},
6851 fir::isPolymorphicType(source.getType()) ? source : mlir::Value{});
6852 mlir::Value resultIrBox =
6853 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
6854 // Call runtime. The runtime is allocating the result.
6855 fir::runtime::genTranspose(builder, loc, resultIrBox, source);
6856 // Read result from mutable fir.box and add it to the list of temps to be
6857 // finalized by the StatementContext.
6858 return readAndAddCleanUp(resultMutableBox, resultType, "TRANSPOSE");
6859 }
6860
6861 // TRIM
6862 fir::ExtendedValue
6863 IntrinsicLibrary::genTrim(mlir::Type resultType,
6864 llvm::ArrayRef<fir::ExtendedValue> args) {
6865 assert(args.size() == 1);
6866 mlir::Value string = builder.createBox(loc, args[0]);
6867 // Create mutable fir.box to be passed to the runtime for the result.
6868 fir::MutableBoxValue resultMutableBox =
6869 fir::factory::createTempMutableBox(builder, loc, resultType);
6870 mlir::Value resultIrBox =
6871 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
6872 // Call runtime. The runtime is allocating the result.
6873 fir::runtime::genTrim(builder, loc, resultIrBox, string);
6874 // Read result from mutable fir.box and add it to the list of temps to be
6875 // finalized by the StatementContext.
6876 return readAndAddCleanUp(resultMutableBox, resultType, "TRIM");
6877 }
6878
6879 // Compare two FIR values and return boolean result as i1.
6880 template <Extremum extremum, ExtremumBehavior behavior>
6881 static mlir::Value createExtremumCompare(mlir::Location loc,
6882 fir::FirOpBuilder &builder,
6883 mlir::Value left, mlir::Value right) {
6884 static constexpr mlir::arith::CmpIPredicate integerPredicate =
6885 extremum == Extremum::Max ? mlir::arith::CmpIPredicate::sgt
6886 : mlir::arith::CmpIPredicate::slt;
6887 static constexpr mlir::arith::CmpFPredicate orderedCmp =
6888 extremum == Extremum::Max ? mlir::arith::CmpFPredicate::OGT
6889 : mlir::arith::CmpFPredicate::OLT;
6890 mlir::Type type = left.getType();
6891 mlir::Value result;
6892 if (fir::isa_real(type)) {
6893 // Note: the signaling/quit aspect of the result required by IEEE
6894 // cannot currently be obtained with LLVM without ad-hoc runtime.
6895 if constexpr (behavior == ExtremumBehavior::IeeeMinMaximumNumber) {
6896 // Return the number if one of the inputs is NaN and the other is
6897 // a number.
6898 auto leftIsResult =
6899 builder.create<mlir::arith::CmpFOp>(loc, orderedCmp, left, right);
6900 auto rightIsNan = builder.create<mlir::arith::CmpFOp>(
6901 loc, mlir::arith::CmpFPredicate::UNE, right, right);
6902 result =
6903 builder.create<mlir::arith::OrIOp>(loc, leftIsResult, rightIsNan);
6904 } else if constexpr (behavior == ExtremumBehavior::IeeeMinMaximum) {
6905 // Always return NaNs if one the input is NaNs
6906 auto leftIsResult =
6907 builder.create<mlir::arith::CmpFOp>(loc, orderedCmp, left, right);
6908 auto leftIsNan = builder.create<mlir::arith::CmpFOp>(
6909 loc, mlir::arith::CmpFPredicate::UNE, left, left);
6910 result = builder.create<mlir::arith::OrIOp>(loc, leftIsResult, leftIsNan);
6911 } else if constexpr (behavior == ExtremumBehavior::MinMaxss) {
6912 // If the left is a NaN, return the right whatever it is.
6913 result =
6914 builder.create<mlir::arith::CmpFOp>(loc, orderedCmp, left, right);
6915 } else if constexpr (behavior == ExtremumBehavior::PgfortranLlvm) {
6916 // If one of the operand is a NaN, return left whatever it is.
6917 static constexpr auto unorderedCmp =
6918 extremum == Extremum::Max ? mlir::arith::CmpFPredicate::UGT
6919 : mlir::arith::CmpFPredicate::ULT;
6920 result =
6921 builder.create<mlir::arith::CmpFOp>(loc, unorderedCmp, left, right);
6922 } else {
6923 // TODO: ieeeMinNum/ieeeMaxNum
6924 static_assert(behavior == ExtremumBehavior::IeeeMinMaxNum,
6925 "ieeeMinNum/ieeeMaxNum behavior not implemented");
6926 }
6927 } else if (fir::isa_integer(type)) {
6928 result =
6929 builder.create<mlir::arith::CmpIOp>(loc, integerPredicate, left, right);
6930 } else if (fir::isa_char(type) || fir::isa_char(fir::unwrapRefType(type))) {
6931 // TODO: ! character min and max is tricky because the result
6932 // length is the length of the longest argument!
6933 // So we may need a temp.
6934 TODO(loc, "intrinsic: min and max for CHARACTER");
6935 }
6936 assert(result && "result must be defined");
6937 return result;
6938 }
6939
6940 // UNPACK
6941 fir::ExtendedValue
6942 IntrinsicLibrary::genUnpack(mlir::Type resultType,
6943 llvm::ArrayRef<fir::ExtendedValue> args) {
6944 assert(args.size() == 3);
6945
6946 // Handle required vector argument
6947 mlir::Value vector = builder.createBox(loc, args[0]);
6948
6949 // Handle required mask argument
6950 fir::BoxValue maskBox = builder.createBox(loc, args[1]);
6951 mlir::Value mask = fir::getBase(maskBox);
6952 unsigned maskRank = maskBox.rank();
6953
6954 // Handle required field argument
6955 mlir::Value field = builder.createBox(loc, args[2]);
6956
6957 // Create mutable fir.box to be passed to the runtime for the result.
6958 mlir::Type resultArrayType = builder.getVarLenSeqTy(resultType, maskRank);
6959 fir::MutableBoxValue resultMutableBox = fir::factory::createTempMutableBox(
6960 builder, loc, resultArrayType, {},
6961 fir::isPolymorphicType(vector.getType()) ? vector : mlir::Value{});
6962 mlir::Value resultIrBox =
6963 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
6964
6965 fir::runtime::genUnpack(builder, loc, resultIrBox, vector, mask, field);
6966
6967 return readAndAddCleanUp(resultMutableBox, resultType, "UNPACK");
6968 }
6969
6970 // VERIFY
6971 fir::ExtendedValue
6972 IntrinsicLibrary::genVerify(mlir::Type resultType,
6973 llvm::ArrayRef<fir::ExtendedValue> args) {
6974
6975 assert(args.size() == 4);
6976
6977 if (isStaticallyAbsent(args[3])) {
6978 // Kind not specified, so call scan/verify runtime routine that is
6979 // specialized on the kind of characters in string.
6980
6981 // Handle required string base arg
6982 mlir::Value stringBase = fir::getBase(args[0]);
6983
6984 // Handle required set string base arg
6985 mlir::Value setBase = fir::getBase(args[1]);
6986
6987 // Handle kind argument; it is the kind of character in this case
6988 fir::KindTy kind =
6989 fir::factory::CharacterExprHelper{builder, loc}.getCharacterKind(
6990 stringBase.getType());
6991
6992 // Get string length argument
6993 mlir::Value stringLen = fir::getLen(args[0]);
6994
6995 // Get set string length argument
6996 mlir::Value setLen = fir::getLen(args[1]);
6997
6998 // Handle optional back argument
6999 mlir::Value back =
7000 isStaticallyAbsent(args[2])
7001 ? builder.createIntegerConstant(loc, builder.getI1Type(), 0)
7002 : fir::getBase(args[2]);
7003
7004 return builder.createConvert(
7005 loc, resultType,
7006 fir::runtime::genVerify(builder, loc, kind, stringBase, stringLen,
7007 setBase, setLen, back));
7008 }
7009 // else use the runtime descriptor version of scan/verify
7010
7011 // Handle optional argument, back
7012 auto makeRefThenEmbox = [&](mlir::Value b) {
7013 fir::LogicalType logTy = fir::LogicalType::get(
7014 builder.getContext(), builder.getKindMap().defaultLogicalKind());
7015 mlir::Value temp = builder.createTemporary(loc, logTy);
7016 mlir::Value castb = builder.createConvert(loc, logTy, b);
7017 builder.create<fir::StoreOp>(loc, castb, temp);
7018 return builder.createBox(loc, temp);
7019 };
7020 mlir::Value back = fir::isUnboxedValue(args[2])
7021 ? makeRefThenEmbox(*args[2].getUnboxed())
7022 : builder.create<fir::AbsentOp>(
7023 loc, fir::BoxType::get(builder.getI1Type()));
7024
7025 // Handle required string argument
7026 mlir::Value string = builder.createBox(loc, args[0]);
7027
7028 // Handle required set argument
7029 mlir::Value set = builder.createBox(loc, args[1]);
7030
7031 // Handle kind argument
7032 mlir::Value kind = fir::getBase(args[3]);
7033
7034 // Create result descriptor
7035 fir::MutableBoxValue resultMutableBox =
7036 fir::factory::createTempMutableBox(builder, loc, resultType);
7037 mlir::Value resultIrBox =
7038 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
7039
7040 fir::runtime::genVerifyDescriptor(builder, loc, resultIrBox, string, set,
7041 back, kind);
7042
7043 // Handle cleanup of allocatable result descriptor and return
7044 return readAndAddCleanUp(resultMutableBox, resultType, "VERIFY");
7045 }
7046
7047 /// Process calls to Minloc, Maxloc intrinsic functions
7048 template <typename FN, typename FD>
7049 fir::ExtendedValue
7050 IntrinsicLibrary::genExtremumloc(FN func, FD funcDim, llvm::StringRef errMsg,
7051 mlir::Type resultType,
7052 llvm::ArrayRef<fir::ExtendedValue> args) {
7053
7054 assert(args.size() == 5);
7055
7056 // Handle required array argument
7057 mlir::Value array = builder.createBox(loc, args[0]);
7058 unsigned rank = fir::BoxValue(array).rank();
7059 assert(rank >= 1);
7060
7061 // Handle optional mask argument
7062 auto mask = isStaticallyAbsent(args[2])
7063 ? builder.create<fir::AbsentOp>(
7064 loc, fir::BoxType::get(builder.getI1Type()))
7065 : builder.createBox(loc, args[2]);
7066
7067 // Handle optional kind argument
7068 auto kind = isStaticallyAbsent(args[3])
7069 ? builder.createIntegerConstant(
7070 loc, builder.getIndexType(),
7071 builder.getKindMap().defaultIntegerKind())
7072 : fir::getBase(args[3]);
7073
7074 // Handle optional back argument
7075 auto back = isStaticallyAbsent(args[4]) ? builder.createBool(loc, false)
7076 : fir::getBase(args[4]);
7077
7078 bool absentDim = isStaticallyAbsent(args[1]);
7079
7080 if (!absentDim && rank == 1) {
7081 // If dim argument is present and the array is rank 1, then the result is
7082 // a scalar (since the the result is rank-1 or 0).
7083 // Therefore, we use a scalar result descriptor with Min/MaxlocDim().
7084 mlir::Value dim = fir::getBase(args[1]);
7085 // Create mutable fir.box to be passed to the runtime for the result.
7086 fir::MutableBoxValue resultMutableBox =
7087 fir::factory::createTempMutableBox(builder, loc, resultType);
7088 mlir::Value resultIrBox =
7089 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
7090
7091 funcDim(builder, loc, resultIrBox, array, dim, mask, kind, back);
7092
7093 // Handle cleanup of allocatable result descriptor and return
7094 return readAndAddCleanUp(resultMutableBox, resultType, errMsg);
7095 }
7096
7097 // Note: The Min/Maxloc/val cases below have an array result.
7098
7099 // Create mutable fir.box to be passed to the runtime for the result.
7100 mlir::Type resultArrayType =
7101 builder.getVarLenSeqTy(resultType, absentDim ? 1 : rank - 1);
7102 fir::MutableBoxValue resultMutableBox =
7103 fir::factory::createTempMutableBox(builder, loc, resultArrayType);
7104 mlir::Value resultIrBox =
7105 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
7106
7107 if (absentDim) {
7108 // Handle min/maxloc/val case where there is no dim argument
7109 // (calls Min/Maxloc()/MinMaxval() runtime routine)
7110 func(builder, loc, resultIrBox, array, mask, kind, back);
7111 } else {
7112 // else handle min/maxloc case with dim argument (calls
7113 // Min/Max/loc/val/Dim() runtime routine).
7114 mlir::Value dim = fir::getBase(args[1]);
7115 funcDim(builder, loc, resultIrBox, array, dim, mask, kind, back);
7116 }
7117 return readAndAddCleanUp(resultMutableBox, resultType, errMsg);
7118 }
7119
7120 // MAXLOC
7121 fir::ExtendedValue
7122 IntrinsicLibrary::genMaxloc(mlir::Type resultType,
7123 llvm::ArrayRef<fir::ExtendedValue> args) {
7124 return genExtremumloc(fir::runtime::genMaxloc, fir::runtime::genMaxlocDim,
7125 "MAXLOC", resultType, args);
7126 }
7127
7128 /// Process calls to Maxval and Minval
7129 template <typename FN, typename FD, typename FC>
7130 fir::ExtendedValue
7131 IntrinsicLibrary::genExtremumVal(FN func, FD funcDim, FC funcChar,
7132 llvm::StringRef errMsg, mlir::Type resultType,
7133 llvm::ArrayRef<fir::ExtendedValue> args) {
7134
7135 assert(args.size() == 3);
7136
7137 // Handle required array argument
7138 fir::BoxValue arryTmp = builder.createBox(loc, args[0]);
7139 mlir::Value array = fir::getBase(arryTmp);
7140 int rank = arryTmp.rank();
7141 assert(rank >= 1);
7142 bool hasCharacterResult = arryTmp.isCharacter();
7143
7144 // Handle optional mask argument
7145 auto mask = isStaticallyAbsent(args[2])
7146 ? builder.create<fir::AbsentOp>(
7147 loc, fir::BoxType::get(builder.getI1Type()))
7148 : builder.createBox(loc, args[2]);
7149
7150 bool absentDim = isStaticallyAbsent(args[1]);
7151
7152 // For Maxval/MinVal, we call the type specific versions of
7153 // Maxval/Minval because the result is scalar in the case below.
7154 if (!hasCharacterResult && (absentDim || rank == 1))
7155 return func(builder, loc, array, mask);
7156
7157 if (hasCharacterResult && (absentDim || rank == 1)) {
7158 // Create mutable fir.box to be passed to the runtime for the result.
7159 fir::MutableBoxValue resultMutableBox =
7160 fir::factory::createTempMutableBox(builder, loc, resultType);
7161 mlir::Value resultIrBox =
7162 fir::factory::getMutableIRBox(builder, loc, resultMutableBox);
7163
7164 funcChar(builder, loc, resultIrBox, array, mask);
7165
7166 // Handle cleanup of allocatable result descriptor and return
7167 return readAndAddCleanUp(resultMutableBox, resultType, errMsg);
7168 }
7169
7170 // Handle Min/Maxval cases that have an array result.
7171 auto resultMutableBox =
7172 genFuncDim(funcDim, resultType, builder, loc, array, args[1], mask, rank);
7173 return readAndAddCleanUp(resultMutableBox, resultType, errMsg);
7174 }
7175
7176 // MAXVAL
7177 fir::ExtendedValue
7178 IntrinsicLibrary::genMaxval(mlir::Type resultType,
7179 llvm::ArrayRef<fir::ExtendedValue> args) {
7180 return genExtremumVal(fir::runtime::genMaxval, fir::runtime::genMaxvalDim,
7181 fir::runtime::genMaxvalChar, "MAXVAL", resultType,
7182 args);
7183 }
7184
7185 // MINLOC
7186 fir::ExtendedValue
7187 IntrinsicLibrary::genMinloc(mlir::Type resultType,
7188 llvm::ArrayRef<fir::ExtendedValue> args) {
7189 return genExtremumloc(fir::runtime::genMinloc, fir::runtime::genMinlocDim,
7190 "MINLOC", resultType, args);
7191 }
7192
7193 // MINVAL
7194 fir::ExtendedValue
7195 IntrinsicLibrary::genMinval(mlir::Type resultType,
7196 llvm::ArrayRef<fir::ExtendedValue> args) {
7197 return genExtremumVal(fir::runtime::genMinval, fir::runtime::genMinvalDim,
7198 fir::runtime::genMinvalChar, "MINVAL", resultType,
7199 args);
7200 }
7201
7202 // MIN and MAX
7203 template <Extremum extremum, ExtremumBehavior behavior>
7204 mlir::Value IntrinsicLibrary::genExtremum(mlir::Type,
7205 llvm::ArrayRef<mlir::Value> args) {
7206 assert(args.size() >= 1);
7207 mlir::Value result = args[0];
7208 for (auto arg : args.drop_front()) {
7209 mlir::Value mask =
7210 createExtremumCompare<extremum, behavior>(loc, builder, result, arg);
7211 result = builder.create<mlir::arith::SelectOp>(loc, mask, result, arg);
7212 }
7213 return result;
7214 }
7215
7216 //===----------------------------------------------------------------------===//
7217 // Argument lowering rules interface for intrinsic or intrinsic module
7218 // procedure.
7219 //===----------------------------------------------------------------------===//
7220
7221 const IntrinsicArgumentLoweringRules *
7222 getIntrinsicArgumentLowering(llvm::StringRef specificName) {
7223 llvm::StringRef name = genericName(specificName);
7224 if (const IntrinsicHandler *handler = findIntrinsicHandler(name))
7225 if (!handler->argLoweringRules.hasDefaultRules())
7226 return &handler->argLoweringRules;
7227 if (const IntrinsicHandler *ppcHandler = findPPCIntrinsicHandler(name))
7228 if (!ppcHandler->argLoweringRules.hasDefaultRules())
7229 return &ppcHandler->argLoweringRules;
7230 return nullptr;
7231 }
7232
7233 const IntrinsicArgumentLoweringRules *
7234 IntrinsicHandlerEntry::getArgumentLoweringRules() const {
7235 if (const IntrinsicHandler *const *handler =
7236 std::get_if<const IntrinsicHandler *>(&entry)) {
7237 assert(*handler);
7238 if (!(*handler)->argLoweringRules.hasDefaultRules())
7239 return &(*handler)->argLoweringRules;
7240 }
7241 return nullptr;
7242 }
7243
7244 /// Return how argument \p argName should be lowered given the rules for the
7245 /// intrinsic function.
7246 fir::ArgLoweringRule
7247 lowerIntrinsicArgumentAs(const IntrinsicArgumentLoweringRules &rules,
7248 unsigned position) {
7249 assert(position < sizeof(rules.args) / (sizeof(decltype(*rules.args))) &&
7250 "invalid argument");
7251 return {rules.args[position].lowerAs,
7252 rules.args[position].handleDynamicOptional};
7253 }
7254
7255 //===----------------------------------------------------------------------===//
7256 // Public intrinsic call helpers
7257 //===----------------------------------------------------------------------===//
7258
7259 std::pair<fir::ExtendedValue, bool>
7260 genIntrinsicCall(fir::FirOpBuilder &builder, mlir::Location loc,
7261 llvm::StringRef name, std::optional<mlir::Type> resultType,
7262 llvm::ArrayRef<fir::ExtendedValue> args,
7263 Fortran::lower::AbstractConverter *converter) {
7264 return IntrinsicLibrary{builder, loc, converter}.genIntrinsicCall(
7265 name, resultType, args);
7266 }
7267
7268 mlir::Value genMax(fir::FirOpBuilder &builder, mlir::Location loc,
7269 llvm::ArrayRef<mlir::Value> args) {
7270 assert(args.size() > 0 && "max requires at least one argument");
7271 return IntrinsicLibrary{builder, loc}
7272 .genExtremum<Extremum::Max, ExtremumBehavior::MinMaxss>(args[0].getType(),
7273 args);
7274 }
7275
7276 mlir::Value genMin(fir::FirOpBuilder &builder, mlir::Location loc,
7277 llvm::ArrayRef<mlir::Value> args) {
7278 assert(args.size() > 0 && "min requires at least one argument");
7279 return IntrinsicLibrary{builder, loc}
7280 .genExtremum<Extremum::Min, ExtremumBehavior::MinMaxss>(args[0].getType(),
7281 args);
7282 }
7283
7284 mlir::Value genDivC(fir::FirOpBuilder &builder, mlir::Location loc,
7285 mlir::Type type, mlir::Value x, mlir::Value y) {
7286 return IntrinsicLibrary{builder, loc}.genRuntimeCall("divc", type, {x, y});
7287 }
7288
7289 mlir::Value genPow(fir::FirOpBuilder &builder, mlir::Location loc,
7290 mlir::Type type, mlir::Value x, mlir::Value y) {
7291 // TODO: since there is no libm version of pow with integer exponent,
7292 // we have to provide an alternative implementation for
7293 // "precise/strict" FP mode.
7294 // One option is to generate internal function with inlined
7295 // implementation and mark it 'strictfp'.
7296 // Another option is to implement it in Fortran runtime library
7297 // (just like matmul).
7298 return IntrinsicLibrary{builder, loc}.genRuntimeCall("pow", type, {x, y});
7299 }
7300
7301 mlir::SymbolRefAttr
7302 getUnrestrictedIntrinsicSymbolRefAttr(fir::FirOpBuilder &builder,
7303 mlir::Location loc, llvm::StringRef name,
7304 mlir::FunctionType signature) {
7305 return IntrinsicLibrary{builder, loc}.getUnrestrictedIntrinsicSymbolRefAttr(
7306 name, signature);
7307 }
7308 } // namespace fir